]> git.saurik.com Git - wxWidgets.git/blame - src/richtext/richtextctrl.cpp
Fill in mouse button and key state when generating mouse event for auto scrolling
[wxWidgets.git] / src / richtext / richtextctrl.cpp
CommitLineData
5d7836c4 1/////////////////////////////////////////////////////////////////////////////
80fdcdb9 2// Name: src/richtext/richtextctrl.cpp
5d7836c4
JS
3// Purpose: A rich edit control
4// Author: Julian Smart
7fe8059f 5// Modified by:
5d7836c4 6// Created: 2005-09-30
7fe8059f 7// RCS-ID: $Id$
5d7836c4
JS
8// Copyright: (c) Julian Smart
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// For compilers that support precompilation, includes "wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
9eddec69 16 #pragma hdrstop
5d7836c4
JS
17#endif
18
b01ca8b6
JS
19#if wxUSE_RICHTEXT
20
21#include "wx/richtext/richtextctrl.h"
ab14c7aa 22#include "wx/richtext/richtextstyles.h"
b01ca8b6 23
5d7836c4 24#ifndef WX_PRECOMP
fe5aa22c 25 #include "wx/wx.h"
9eddec69 26 #include "wx/settings.h"
5d7836c4
JS
27#endif
28
a188ac29 29#include "wx/timer.h"
5d7836c4
JS
30#include "wx/textfile.h"
31#include "wx/ffile.h"
5d7836c4
JS
32#include "wx/filename.h"
33#include "wx/dcbuffer.h"
5d7836c4 34#include "wx/arrimpl.cpp"
dadd4f55 35#include "wx/fontenum.h"
addcf76c 36#include "wx/accel.h"
5d7836c4 37
5dec941a
JS
38#if defined (__WXGTK__) || defined(__WXX11__) || defined(__WXMOTIF__)
39#define wxHAVE_PRIMARY_SELECTION 1
40#else
41#define wxHAVE_PRIMARY_SELECTION 0
42#endif
43
44#if wxUSE_CLIPBOARD && wxHAVE_PRIMARY_SELECTION
45#include "wx/clipbrd.h"
46#endif
47
27e20452
JS
48// DLL options compatibility check:
49#include "wx/app.h"
50WX_CHECK_BUILD_OPTIONS("wxRichTextCtrl")
51
9b11752c
VZ
52wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, wxRichTextEvent );
53wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, wxRichTextEvent );
54wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, wxRichTextEvent );
55wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, wxRichTextEvent );
56wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RETURN, wxRichTextEvent );
57wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CHARACTER, wxRichTextEvent );
58wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_DELETE, wxRichTextEvent );
5912d19e 59
9b11752c
VZ
60wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, wxRichTextEvent );
61wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, wxRichTextEvent );
62wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, wxRichTextEvent );
63wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, wxRichTextEvent );
5d7836c4 64
9b11752c
VZ
65wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, wxRichTextEvent );
66wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, wxRichTextEvent );
67wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, wxRichTextEvent );
590a0f8b 68wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_PROPERTIES_CHANGED, wxRichTextEvent );
9b11752c
VZ
69wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, wxRichTextEvent );
70wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_BUFFER_RESET, wxRichTextEvent );
603f702b 71wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED, wxRichTextEvent );
5912d19e 72
1c13f06e
JS
73#if wxRICHTEXT_USE_OWN_CARET
74
75/*!
76 * wxRichTextCaret
77 *
78 * This implements a non-flashing cursor in case there
79 * are platform-specific problems with the generic caret.
80 * wxRICHTEXT_USE_OWN_CARET is set in richtextbuffer.h.
81 */
82
a188ac29
JS
83class wxRichTextCaret;
84class wxRichTextCaretTimer: public wxTimer
85{
86 public:
87 wxRichTextCaretTimer(wxRichTextCaret* caret)
88 {
89 m_caret = caret;
90 }
91 virtual void Notify();
92 wxRichTextCaret* m_caret;
93};
94
1c13f06e
JS
95class wxRichTextCaret: public wxCaret
96{
97public:
98 // ctors
99 // -----
100 // default - use Create()
a188ac29 101 wxRichTextCaret(): m_timer(this) { Init(); }
1c13f06e
JS
102 // creates a block caret associated with the given window
103 wxRichTextCaret(wxRichTextCtrl *window, int width, int height)
a188ac29 104 : wxCaret(window, width, height), m_timer(this) { Init(); m_richTextCtrl = window; }
1c13f06e 105 wxRichTextCaret(wxRichTextCtrl *window, const wxSize& size)
a188ac29 106 : wxCaret(window, size), m_timer(this) { Init(); m_richTextCtrl = window; }
1c13f06e
JS
107
108 virtual ~wxRichTextCaret();
109
110 // implementation
111 // --------------
112
113 // called by wxWindow (not using the event tables)
114 virtual void OnSetFocus();
115 virtual void OnKillFocus();
116
117 // draw the caret on the given DC
118 void DoDraw(wxDC *dc);
119
120 // get the visible count
121 int GetVisibleCount() const { return m_countVisible; }
122
123 // delay repositioning
124 bool GetNeedsUpdate() const { return m_needsUpdate; }
125 void SetNeedsUpdate(bool needsUpdate = true ) { m_needsUpdate = needsUpdate; }
126
a188ac29
JS
127 void Notify();
128
cd45ed36
JS
129 bool GetRefreshEnabled() const { return m_refreshEnabled; }
130 void EnableRefresh(bool b) { m_refreshEnabled = b; }
131
1c13f06e
JS
132protected:
133 virtual void DoShow();
134 virtual void DoHide();
135 virtual void DoMove();
136 virtual void DoSize();
137
138 // refresh the caret
139 void Refresh();
140
141private:
142 void Init();
143
144 int m_xOld,
145 m_yOld;
146 bool m_hasFocus; // true => our window has focus
147 bool m_needsUpdate; // must be repositioned
a188ac29
JS
148 bool m_flashOn;
149 wxRichTextCaretTimer m_timer;
1c13f06e 150 wxRichTextCtrl* m_richTextCtrl;
cd45ed36 151 bool m_refreshEnabled;
1c13f06e
JS
152};
153#endif
154
24777478 155IMPLEMENT_DYNAMIC_CLASS( wxRichTextCtrl, wxControl )
5d7836c4 156
d0960f6d 157IMPLEMENT_DYNAMIC_CLASS( wxRichTextEvent, wxNotifyEvent )
5d7836c4 158
24777478 159BEGIN_EVENT_TABLE( wxRichTextCtrl, wxControl )
5d7836c4
JS
160 EVT_PAINT(wxRichTextCtrl::OnPaint)
161 EVT_ERASE_BACKGROUND(wxRichTextCtrl::OnEraseBackground)
4d551ad5 162 EVT_IDLE(wxRichTextCtrl::OnIdle)
c59f6793 163 EVT_SCROLLWIN(wxRichTextCtrl::OnScroll)
5d7836c4
JS
164 EVT_LEFT_DOWN(wxRichTextCtrl::OnLeftClick)
165 EVT_MOTION(wxRichTextCtrl::OnMoveMouse)
166 EVT_LEFT_UP(wxRichTextCtrl::OnLeftUp)
167 EVT_RIGHT_DOWN(wxRichTextCtrl::OnRightClick)
168 EVT_MIDDLE_DOWN(wxRichTextCtrl::OnMiddleClick)
169 EVT_LEFT_DCLICK(wxRichTextCtrl::OnLeftDClick)
170 EVT_CHAR(wxRichTextCtrl::OnChar)
c80e8cbe 171 EVT_KEY_DOWN(wxRichTextCtrl::OnChar)
5d7836c4
JS
172 EVT_SIZE(wxRichTextCtrl::OnSize)
173 EVT_SET_FOCUS(wxRichTextCtrl::OnSetFocus)
174 EVT_KILL_FOCUS(wxRichTextCtrl::OnKillFocus)
61f84e24 175 EVT_MOUSE_CAPTURE_LOST(wxRichTextCtrl::OnCaptureLost)
5d7836c4 176 EVT_CONTEXT_MENU(wxRichTextCtrl::OnContextMenu)
52170c5b 177 EVT_SYS_COLOUR_CHANGED(wxRichTextCtrl::OnSysColourChanged)
5d7836c4
JS
178
179 EVT_MENU(wxID_UNDO, wxRichTextCtrl::OnUndo)
180 EVT_UPDATE_UI(wxID_UNDO, wxRichTextCtrl::OnUpdateUndo)
181
182 EVT_MENU(wxID_REDO, wxRichTextCtrl::OnRedo)
183 EVT_UPDATE_UI(wxID_REDO, wxRichTextCtrl::OnUpdateRedo)
184
185 EVT_MENU(wxID_COPY, wxRichTextCtrl::OnCopy)
186 EVT_UPDATE_UI(wxID_COPY, wxRichTextCtrl::OnUpdateCopy)
187
188 EVT_MENU(wxID_PASTE, wxRichTextCtrl::OnPaste)
189 EVT_UPDATE_UI(wxID_PASTE, wxRichTextCtrl::OnUpdatePaste)
190
191 EVT_MENU(wxID_CUT, wxRichTextCtrl::OnCut)
192 EVT_UPDATE_UI(wxID_CUT, wxRichTextCtrl::OnUpdateCut)
193
194 EVT_MENU(wxID_CLEAR, wxRichTextCtrl::OnClear)
195 EVT_UPDATE_UI(wxID_CLEAR, wxRichTextCtrl::OnUpdateClear)
196
197 EVT_MENU(wxID_SELECTALL, wxRichTextCtrl::OnSelectAll)
198 EVT_UPDATE_UI(wxID_SELECTALL, wxRichTextCtrl::OnUpdateSelectAll)
603f702b
JS
199
200 EVT_MENU(wxID_RICHTEXT_PROPERTIES1, wxRichTextCtrl::OnProperties)
201 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES1, wxRichTextCtrl::OnUpdateProperties)
202
203 EVT_MENU(wxID_RICHTEXT_PROPERTIES2, wxRichTextCtrl::OnProperties)
204 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES2, wxRichTextCtrl::OnUpdateProperties)
205
206 EVT_MENU(wxID_RICHTEXT_PROPERTIES3, wxRichTextCtrl::OnProperties)
207 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES3, wxRichTextCtrl::OnUpdateProperties)
208
5d7836c4
JS
209END_EVENT_TABLE()
210
211/*!
212 * wxRichTextCtrl
213 */
214
dadd4f55
JS
215wxArrayString wxRichTextCtrl::sm_availableFontNames;
216
5d7836c4 217wxRichTextCtrl::wxRichTextCtrl()
343ae70d 218 : wxScrollHelper(this)
5d7836c4
JS
219{
220 Init();
221}
222
343ae70d
VZ
223wxRichTextCtrl::wxRichTextCtrl(wxWindow* parent,
224 wxWindowID id,
225 const wxString& value,
226 const wxPoint& pos,
227 const wxSize& size,
4e8d9558
JS
228 long style,
229 const wxValidator& validator,
230 const wxString& name)
343ae70d 231 : wxScrollHelper(this)
5d7836c4
JS
232{
233 Init();
4e8d9558 234 Create(parent, id, value, pos, size, style, validator, name);
5d7836c4
JS
235}
236
237/// Creation
4e8d9558
JS
238bool wxRichTextCtrl::Create( wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style,
239 const wxValidator& validator, const wxString& name)
5d7836c4 240{
6d595f3d
JS
241 style |= wxVSCROLL;
242
24777478 243 if (!wxControl::Create(parent, id, pos, size,
0ec1179b
VZ
244 style|wxFULL_REPAINT_ON_RESIZE,
245 validator, name))
5d7836c4 246 return false;
5d7836c4 247
a1b806b9 248 if (!GetFont().IsOk())
5d7836c4
JS
249 {
250 SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
251 }
7fe8059f 252
e9f10004
JS
253 // No physical scrolling, so we can preserve margins
254 EnableScrolling(false, false);
255
dadd4f55
JS
256 if (style & wxTE_READONLY)
257 SetEditable(false);
258
42688aea 259 // The base attributes must all have default values
24777478 260 wxRichTextAttr attributes;
5d7836c4 261 attributes.SetFont(GetFont());
79f955ec 262 attributes.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
5d7836c4 263 attributes.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
3e3a754f
JS
264 attributes.SetLineSpacing(10);
265 attributes.SetParagraphSpacingAfter(10);
266 attributes.SetParagraphSpacingBefore(0);
5d7836c4
JS
267 SetBasicStyle(attributes);
268
603f702b
JS
269 int margin = 5;
270 SetMargins(margin, margin);
271
fe5aa22c
JS
272 // The default attributes will be merged with base attributes, so
273 // can be empty to begin with
24777478 274 wxRichTextAttr defaultAttributes;
fe5aa22c
JS
275 SetDefaultStyle(defaultAttributes);
276
79f955ec 277 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
5d7836c4
JS
278 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
279
cd8ba0d9
JS
280 GetBuffer().Reset();
281 GetBuffer().SetRichTextCtrl(this);
282
1c13f06e
JS
283#if wxRICHTEXT_USE_OWN_CARET
284 SetCaret(new wxRichTextCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
285#else
cd8ba0d9 286 SetCaret(new wxCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
1c13f06e 287#endif
cd8ba0d9 288
7fe8059f 289 // Tell the sizers to use the given or best size
170acdc9 290 SetInitialSize(size);
7fe8059f 291
3e3a754f 292#if wxRICHTEXT_BUFFERED_PAINTING
5d7836c4
JS
293 // Create a buffer
294 RecreateBuffer(size);
3e3a754f 295#endif
5d7836c4 296
d2d0adc7
JS
297 m_textCursor = wxCursor(wxCURSOR_IBEAM);
298 m_urlCursor = wxCursor(wxCURSOR_HAND);
299
300 SetCursor(m_textCursor);
61399247 301
27e20452
JS
302 if (!value.IsEmpty())
303 SetValue(value);
7fe8059f 304
d2d0adc7
JS
305 GetBuffer().AddEventHandler(this);
306
addcf76c 307 // Accelerators
0951fe0a 308 wxAcceleratorEntry entries[6];
addcf76c 309
675ec665
SC
310 entries[0].Set(wxACCEL_CTRL, (int) 'C', wxID_COPY);
311 entries[1].Set(wxACCEL_CTRL, (int) 'X', wxID_CUT);
312 entries[2].Set(wxACCEL_CTRL, (int) 'V', wxID_PASTE);
313 entries[3].Set(wxACCEL_CTRL, (int) 'A', wxID_SELECTALL);
314 entries[4].Set(wxACCEL_CTRL, (int) 'Z', wxID_UNDO);
315 entries[5].Set(wxACCEL_CTRL, (int) 'Y', wxID_REDO);
addcf76c 316
0951fe0a 317 wxAcceleratorTable accel(6, entries);
addcf76c
JS
318 SetAcceleratorTable(accel);
319
8e43fc77
JS
320 m_contextMenu = new wxMenu;
321 m_contextMenu->Append(wxID_UNDO, _("&Undo"));
322 m_contextMenu->Append(wxID_REDO, _("&Redo"));
323 m_contextMenu->AppendSeparator();
324 m_contextMenu->Append(wxID_CUT, _("Cu&t"));
325 m_contextMenu->Append(wxID_COPY, _("&Copy"));
326 m_contextMenu->Append(wxID_PASTE, _("&Paste"));
327 m_contextMenu->Append(wxID_CLEAR, _("&Delete"));
328 m_contextMenu->AppendSeparator();
329 m_contextMenu->Append(wxID_SELECTALL, _("Select &All"));
cdaed652 330 m_contextMenu->AppendSeparator();
603f702b 331 m_contextMenu->Append(wxID_RICHTEXT_PROPERTIES1, _("&Properties"));
cdaed652 332
590a0f8b
JS
333#if wxUSE_DRAG_AND_DROP
334 SetDropTarget(new wxRichTextDropTarget(this));
335#endif
336
5d7836c4
JS
337 return true;
338}
339
340wxRichTextCtrl::~wxRichTextCtrl()
341{
603f702b 342 SetFocusObject(& GetBuffer(), false);
d2d0adc7 343 GetBuffer().RemoveEventHandler(this);
88bee7e6 344
5d7836c4
JS
345 delete m_contextMenu;
346}
347
348/// Member initialisation
349void wxRichTextCtrl::Init()
350{
5d7836c4
JS
351 m_contextMenu = NULL;
352 m_caret = NULL;
353 m_caretPosition = -1;
5d7836c4 354 m_selectionAnchor = -2;
603f702b
JS
355 m_selectionAnchorObject = NULL;
356 m_selectionState = wxRichTextCtrlSelectionState_Normal;
5d7836c4 357 m_editable = true;
12f5219f 358 m_verticalScrollbarEnabled = true;
5d7836c4
JS
359 m_caretAtLineStart = false;
360 m_dragging = false;
9fa7b436 361#if wxUSE_DRAG_AND_DROP
0c0e063e 362 m_preDrag = false;
9fa7b436 363#endif
4d551ad5
JS
364 m_fullLayoutRequired = false;
365 m_fullLayoutTime = 0;
366 m_fullLayoutSavedPosition = 0;
367 m_delayedLayoutThreshold = wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD;
ab14c7aa 368 m_caretPositionForDefaultStyle = -2;
603f702b 369 m_focusObject = & m_buffer;
4ba36292 370 m_scale = 1.0;
5d7836c4
JS
371}
372
17808a75 373void wxRichTextCtrl::DoThaw()
5d7836c4 374{
603f702b 375 if (GetBuffer().IsDirty())
17808a75
VZ
376 LayoutContent();
377 else
378 SetupScrollbars();
8251c171 379
6a8e61e0 380 wxWindow::DoThaw();
5d7836c4
JS
381}
382
383/// Clear all text
384void wxRichTextCtrl::Clear()
385{
603f702b
JS
386 if (GetFocusObject() == & GetBuffer())
387 {
388 m_buffer.ResetAndClearCommands();
389 m_buffer.Invalidate(wxRICHTEXT_ALL);
390 }
391 else
392 {
393 GetFocusObject()->Reset();
394 }
395
5d7836c4 396 m_caretPosition = -1;
ab14c7aa 397 m_caretPositionForDefaultStyle = -2;
5d7836c4 398 m_caretAtLineStart = false;
603f702b
JS
399 m_selection.Reset();
400 m_selectionState = wxRichTextCtrlSelectionState_Normal;
5d7836c4 401
495a248e
JS
402 Scroll(0,0);
403
17808a75 404 if (!IsFrozen())
5d7836c4 405 {
cecf8eee 406 LayoutContent();
76bcd815 407 Refresh(false);
5d7836c4 408 }
0ec1179b
VZ
409
410 wxTextCtrl::SendTextUpdatedEvent(this);
5d7836c4
JS
411}
412
413/// Painting
414void wxRichTextCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
415{
1c13f06e
JS
416#if !wxRICHTEXT_USE_OWN_CARET
417 if (GetCaret() && !IsFrozen())
d2142335 418 GetCaret()->Hide();
cd45ed36
JS
419#else
420 // Stop the caret refreshing the control from within the
421 // paint handler
422 if (GetCaret())
423 ((wxRichTextCaret*) GetCaret())->EnableRefresh(false);
1c13f06e 424#endif
d2142335 425
5d7836c4 426 {
3e3a754f 427#if wxRICHTEXT_BUFFERED_PAINTING
c59f6793 428 wxBufferedPaintDC dc(this, m_bufferBitmap);
3e3a754f
JS
429#else
430 wxPaintDC dc(this);
431#endif
41e155b4 432
17808a75 433 if (IsFrozen())
c59f6793 434 return;
41e155b4 435
17808a75
VZ
436 PrepareDC(dc);
437
c59f6793 438 dc.SetFont(GetFont());
41e155b4 439
c59f6793
JS
440 // Paint the background
441 PaintBackground(dc);
41e155b4 442
ea160b2e 443 wxRect drawingArea(GetUpdateRegion().GetBox());
4ba36292
JS
444 drawingArea.SetPosition(GetUnscaledPoint(GetLogicalPoint(drawingArea.GetPosition())));
445 drawingArea.SetSize(GetUnscaledSize(drawingArea.GetSize()));
ea160b2e 446
4ba36292 447 wxRect availableSpace(GetUnscaledSize(GetClientSize()));
8db2e3ef 448 wxRichTextDrawingContext context(& GetBuffer());
603f702b 449 if (GetBuffer().IsDirty())
c59f6793 450 {
4ba36292
JS
451 dc.SetUserScale(GetScale(), GetScale());
452
8db2e3ef 453 GetBuffer().Layout(dc, context, availableSpace, availableSpace, wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT);
603f702b 454 GetBuffer().Invalidate(wxRICHTEXT_NONE);
4ba36292
JS
455
456 dc.SetUserScale(1.0, 1.0);
457
c59f6793
JS
458 SetupScrollbars();
459 }
41e155b4 460
e9f10004
JS
461 wxRect clipRect(availableSpace);
462 clipRect.x += GetBuffer().GetLeftMargin();
463 clipRect.y += GetBuffer().GetTopMargin();
464 clipRect.width -= (GetBuffer().GetLeftMargin() + GetBuffer().GetRightMargin());
465 clipRect.height -= (GetBuffer().GetTopMargin() + GetBuffer().GetBottomMargin());
4ba36292
JS
466
467 clipRect = GetScaledRect(clipRect);
e9f10004 468 clipRect.SetPosition(GetLogicalPoint(clipRect.GetPosition()));
4ba36292 469
e9f10004
JS
470 dc.SetClippingRegion(clipRect);
471
603f702b
JS
472 int flags = 0;
473 if ((GetExtraStyle() & wxRICHTEXT_EX_NO_GUIDELINES) == 0)
474 flags |= wxRICHTEXT_DRAW_GUIDELINES;
4fe83b93 475
4ba36292
JS
476 dc.SetUserScale(GetScale(), GetScale());
477
8db2e3ef 478 GetBuffer().Draw(dc, context, GetBuffer().GetOwnRange(), GetSelection(), drawingArea, 0 /* descent */, flags);
e9f10004
JS
479
480 dc.DestroyClippingRegion();
481
35bdbae5
JS
482 // Other user defined painting after everything else (i.e. all text) is painted
483 PaintAboveContent(dc);
484
1c13f06e
JS
485#if wxRICHTEXT_USE_OWN_CARET
486 if (GetCaret()->IsVisible())
487 {
cd45ed36 488 PositionCaret();
1c13f06e
JS
489 ((wxRichTextCaret*) GetCaret())->DoDraw(& dc);
490 }
491#endif
4ba36292
JS
492
493 dc.SetUserScale(1.0, 1.0);
5d7836c4 494 }
d2142335 495
1c13f06e
JS
496#if !wxRICHTEXT_USE_OWN_CARET
497 if (GetCaret())
d2142335 498 GetCaret()->Show();
7383cf9d 499 PositionCaret();
5219cf05 500#else
cd45ed36
JS
501 if (GetCaret())
502 ((wxRichTextCaret*) GetCaret())->EnableRefresh(true);
1c13f06e 503#endif
5d7836c4
JS
504}
505
506// Empty implementation, to prevent flicker
507void wxRichTextCtrl::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
508{
509}
510
511void wxRichTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
512{
ea160b2e
JS
513 if (GetCaret())
514 {
1c13f06e 515#if !wxRICHTEXT_USE_OWN_CARET
ea160b2e 516 PositionCaret();
1c13f06e
JS
517#endif
518 GetCaret()->Show();
ea160b2e 519 }
c59f6793 520
1c13f06e
JS
521#if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
522 // Work around dropouts when control is focused
523 if (!IsFrozen())
524 {
525 Refresh(false);
526 }
527#endif
5d7836c4
JS
528}
529
530void wxRichTextCtrl::OnKillFocus(wxFocusEvent& WXUNUSED(event))
531{
1c13f06e 532 if (GetCaret())
ea160b2e 533 GetCaret()->Hide();
c59f6793 534
1c13f06e
JS
535#if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
536 // Work around dropouts when control is focused
537 if (!IsFrozen())
538 {
539 Refresh(false);
540 }
541#endif
5d7836c4
JS
542}
543
61f84e24
JS
544void wxRichTextCtrl::OnCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
545{
88bee7e6 546 m_dragging = false;
61f84e24
JS
547}
548
603f702b
JS
549// Set up the caret for the given position and container, after a mouse click
550bool wxRichTextCtrl::SetCaretPositionAfterClick(wxRichTextParagraphLayoutBox* container, long position, int hitTestFlags, bool extendSelection)
551{
552 bool caretAtLineStart = false;
553
554 if (hitTestFlags & wxRICHTEXT_HITTEST_BEFORE)
555 {
556 // If we're at the start of a line (but not first in para)
557 // then we should keep the caret showing at the start of the line
558 // by showing the m_caretAtLineStart flag.
559 wxRichTextParagraph* para = container->GetParagraphAtPosition(position);
560 wxRichTextLine* line = container->GetLineAtPosition(position);
561
562 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
563 caretAtLineStart = true;
564 position --;
565 }
566
567 if (extendSelection && (m_caretPosition != position))
568 ExtendSelection(m_caretPosition, position, wxRICHTEXT_SHIFT_DOWN);
569
570 MoveCaret(position, caretAtLineStart);
571 SetDefaultStyleToCursorStyle();
4fe83b93 572
603f702b
JS
573 return true;
574}
575
5d7836c4
JS
576/// Left-click
577void wxRichTextCtrl::OnLeftClick(wxMouseEvent& event)
578{
579 SetFocus();
580
581 wxClientDC dc(this);
582 PrepareDC(dc);
583 dc.SetFont(GetFont());
7fe8059f 584
603f702b 585 // TODO: detect change of focus object
5d7836c4 586 long position = 0;
603f702b
JS
587 wxRichTextObject* hitObj = NULL;
588 wxRichTextObject* contextObj = NULL;
8db2e3ef 589 wxRichTextDrawingContext context(& GetBuffer());
4ba36292 590 int hit = GetBuffer().HitTest(dc, context, GetUnscaledPoint(event.GetLogicalPosition(dc)), position, & hitObj, & contextObj, wxRICHTEXT_HITTEST_HONOUR_ATOMIC);
5d7836c4 591
0c0e063e
JS
592#if wxUSE_DRAG_AND_DROP
593 // If there's no selection, or we're not inside it, this isn't an attempt to initiate Drag'n'Drop
b33e0c2c 594 if (IsEditable() && HasSelection() && GetSelectionRange().ToInternal().Contains(position))
0c0e063e
JS
595 {
596 // This might be an attempt at initiating Drag'n'Drop. So set the time & flags
597 m_preDrag = true;
598 m_dragStartPoint = event.GetPosition(); // No need to worry about logical positions etc, we only care about the distance from the original pt
599
600#if wxUSE_DATETIME
601 m_dragStartTime = wxDateTime::UNow();
602#endif // wxUSE_DATETIME
603
604 // Preserve behaviour of clicking on an object within the selection
605 if (hit != wxRICHTEXT_HITTEST_NONE && hitObj)
606 m_dragging = true;
607
608 return; // Don't skip the event, else the selection will be lost
609 }
610#endif // wxUSE_DRAG_AND_DROP
611
603f702b 612 if (hit != wxRICHTEXT_HITTEST_NONE && hitObj)
5d7836c4 613 {
603f702b
JS
614 wxRichTextParagraphLayoutBox* oldFocusObject = GetFocusObject();
615 wxRichTextParagraphLayoutBox* container = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
616 if (container && container != GetFocusObject() && container->AcceptsFocus())
617 {
618 SetFocusObject(container, false /* don't set caret position yet */);
619 }
4fe83b93 620
5d7836c4
JS
621 m_dragging = true;
622 CaptureMouse();
623
f7222f4c
JS
624 long oldCaretPos = m_caretPosition;
625
603f702b 626 SetCaretPositionAfterClick(container, position, hit);
f7222f4c 627
603f702b
JS
628 // For now, don't handle shift-click when we're selecting multiple objects.
629 if (event.ShiftDown() && GetFocusObject() == oldFocusObject && m_selectionState == wxRichTextCtrlSelectionState_Normal)
77ea6c48 630 ExtendSelection(oldCaretPos, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
f7222f4c
JS
631 else
632 SelectNone();
5d7836c4
JS
633 }
634
635 event.Skip();
636}
637
638/// Left-up
d2d0adc7 639void wxRichTextCtrl::OnLeftUp(wxMouseEvent& event)
5d7836c4
JS
640{
641 if (m_dragging)
642 {
643 m_dragging = false;
644 if (GetCapture() == this)
645 ReleaseMouse();
d2d0adc7
JS
646
647 // See if we clicked on a URL
648 wxClientDC dc(this);
649 PrepareDC(dc);
650 dc.SetFont(GetFont());
651
652 long position = 0;
653 wxPoint logicalPt = event.GetLogicalPosition(dc);
603f702b
JS
654 wxRichTextObject* hitObj = NULL;
655 wxRichTextObject* contextObj = NULL;
8db2e3ef 656 wxRichTextDrawingContext context(& GetBuffer());
603f702b 657 // Only get objects at this level, not nested, because otherwise we couldn't swipe text at a single level.
4ba36292 658 int hit = GetFocusObject()->HitTest(dc, context, GetUnscaledPoint(logicalPt), position, & hitObj, & contextObj, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS|wxRICHTEXT_HITTEST_HONOUR_ATOMIC);
88bee7e6 659
0c0e063e
JS
660#if wxUSE_DRAG_AND_DROP
661 if (m_preDrag)
662 {
663 // Preserve the behaviour that would have happened without drag-and-drop detection, in OnLeftClick
664 m_preDrag = false; // Tell DnD not to happen now: we are processing Left Up ourselves.
665
666 // Do the actions that would have been done in OnLeftClick if we hadn't tried to drag
667 long position = 0;
668 wxRichTextObject* hitObj = NULL;
669 wxRichTextObject* contextObj = NULL;
4ba36292 670 int hit = GetBuffer().HitTest(dc, context, GetUnscaledPoint(event.GetLogicalPosition(dc)), position, & hitObj, & contextObj, wxRICHTEXT_HITTEST_HONOUR_ATOMIC);
0c0e063e
JS
671 wxRichTextParagraphLayoutBox* oldFocusObject = GetFocusObject();
672 wxRichTextParagraphLayoutBox* container = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
673 if (container && container != GetFocusObject() && container->AcceptsFocus())
674 {
675 SetFocusObject(container, false /* don't set caret position yet */);
676 }
677
678 long oldCaretPos = m_caretPosition;
679
680 SetCaretPositionAfterClick(container, position, hit);
681
682 // For now, don't handle shift-click when we're selecting multiple objects.
683 if (event.ShiftDown() && GetFocusObject() == oldFocusObject && m_selectionState == wxRichTextCtrlSelectionState_Normal)
684 ExtendSelection(oldCaretPos, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
685 else
686 SelectNone();
687 }
688#endif
689
62381daa 690 if ((hit != wxRICHTEXT_HITTEST_NONE) && !(hit & wxRICHTEXT_HITTEST_OUTSIDE))
d2d0adc7 691 {
db6634e0
JS
692 wxRichTextEvent cmdEvent(
693 wxEVT_COMMAND_RICHTEXT_LEFT_CLICK,
694 GetId());
695 cmdEvent.SetEventObject(this);
603f702b
JS
696 cmdEvent.SetPosition(position);
697 if (hitObj)
698 cmdEvent.SetContainer(hitObj->GetContainer());
db6634e0
JS
699
700 if (!GetEventHandler()->ProcessEvent(cmdEvent))
d2d0adc7 701 {
24777478 702 wxRichTextAttr attr;
db6634e0 703 if (GetStyle(position, attr))
d2d0adc7 704 {
db6634e0 705 if (attr.HasFlag(wxTEXT_ATTR_URL))
d2d0adc7 706 {
db6634e0
JS
707 wxString urlTarget = attr.GetURL();
708 if (!urlTarget.IsEmpty())
d2d0adc7 709 {
db6634e0 710 wxMouseEvent mouseEvent(event);
1a75935d 711
db6634e0 712 long startPos = 0, endPos = 0;
603f702b 713 wxRichTextObject* obj = GetFocusObject()->GetLeafObjectAtPosition(position);
db6634e0
JS
714 if (obj)
715 {
716 startPos = obj->GetRange().GetStart();
717 endPos = obj->GetRange().GetEnd();
718 }
1a75935d 719
db6634e0
JS
720 wxTextUrlEvent urlEvent(GetId(), mouseEvent, startPos, endPos);
721 InitCommandEvent(urlEvent);
1a75935d 722
db6634e0 723 urlEvent.SetString(urlTarget);
1a75935d 724
db6634e0 725 GetEventHandler()->ProcessEvent(urlEvent);
88bee7e6 726 }
d2d0adc7
JS
727 }
728 }
729 }
730 }
5d7836c4 731 }
5dec941a 732
0c0e063e
JS
733#if wxUSE_DRAG_AND_DROP
734 m_preDrag = false;
735#endif // wxUSE_DRAG_AND_DROP
736
5dec941a
JS
737#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ && wxHAVE_PRIMARY_SELECTION
738 if (HasSelection() && GetFocusObject() && GetFocusObject()->GetBuffer())
739 {
740 // Put the selection in PRIMARY, if it exists
741 wxTheClipboard->UsePrimarySelection(true);
742
743 wxRichTextRange range = GetInternalSelectionRange();
744 GetFocusObject()->GetBuffer()->CopyToClipboard(range);
745
746 wxTheClipboard->UsePrimarySelection(false);
747 }
748#endif
5d7836c4
JS
749}
750
0c0e063e 751/// Mouse-movements
5d7836c4
JS
752void wxRichTextCtrl::OnMoveMouse(wxMouseEvent& event)
753{
0c0e063e 754#if wxUSE_DRAG_AND_DROP
f819ed5d
JS
755 size_t distance = 0;
756 if (m_preDrag || m_dragging)
0c0e063e
JS
757 {
758 int x = m_dragStartPoint.x - event.GetPosition().x;
759 int y = m_dragStartPoint.y - event.GetPosition().y;
f819ed5d
JS
760 distance = abs(x) + abs(y);
761 }
762
763 // See if we're starting Drag'n'Drop
764 if (m_preDrag)
765 {
0c0e063e
JS
766#if wxUSE_DATETIME
767 wxTimeSpan diff = wxDateTime::UNow() - m_dragStartTime;
768#endif
769 if ((distance > 10)
770#if wxUSE_DATETIME
771 && (diff.GetMilliseconds() > 100)
772#endif
773 )
774 {
775 m_dragging = false;
776
777 // Start drag'n'drop
778 wxRichTextRange range = GetInternalSelectionRange();
779 if (range == wxRICHTEXT_NONE)
780 {
781 // Don't try to drag an empty range
782 m_preDrag = false;
783 return;
784 }
785
786 // Cache the current situation, to be restored if Drag'n'Drop is cancelled
787 long oldPos = GetCaretPosition();
788 wxRichTextParagraphLayoutBox* oldFocus = GetFocusObject();
789
790 wxDataObjectComposite* compositeObject = new wxDataObjectComposite();
791 wxString text = GetFocusObject()->GetTextForRange(range);
792#ifdef __WXMSW__
793 text = wxTextFile::Translate(text, wxTextFileType_Dos);
794#endif
795 compositeObject->Add(new wxTextDataObject(text), false /* not preferred */);
796
797 wxRichTextBuffer* richTextBuf = new wxRichTextBuffer;
798 GetFocusObject()->CopyFragment(range, *richTextBuf);
799 compositeObject->Add(new wxRichTextBufferDataObject(richTextBuf), true /* preferred */);
800
801 wxRichTextDropSource source(*compositeObject, this);
802 // Use wxDrag_DefaultMove, not because it's the likelier choice but because pressing Ctrl for Copy obeys the principle of least surprise
803 // The alternative, wxDrag_DefaultCopy, requires the user to know that Move needs the Shift key pressed
804 BeginBatchUndo(_("Drag"));
805 switch (source.DoDragDrop(wxDrag_AllowMove | wxDrag_DefaultMove))
806 {
807 case wxDragMove:
808 case wxDragCopy: break;
809
810 case wxDragError:
811 wxLogError(wxT("An error occurred during drag and drop operation"));
812 case wxDragNone:
813 case wxDragCancel:
814 Refresh(); // This is needed in wxMSW, otherwise resetting the position doesn't 'take'
815 SetCaretPosition(oldPos);
816 SetFocusObject(oldFocus, false);
817 default: break;
818 }
819 EndBatchUndo();
820
821 m_preDrag = false;
822 return;
823 }
824 }
825#endif // wxUSE_DRAG_AND_DROP
826
5d7836c4
JS
827 wxClientDC dc(this);
828 PrepareDC(dc);
829 dc.SetFont(GetFont());
7fe8059f 830
5d7836c4
JS
831 long position = 0;
832 wxPoint logicalPt = event.GetLogicalPosition(dc);
603f702b
JS
833 wxRichTextObject* hitObj = NULL;
834 wxRichTextObject* contextObj = NULL;
4fe83b93 835
603f702b 836 int flags = 0;
4fe83b93 837
603f702b
JS
838 // If we're dragging, let's only consider positions at this level; otherwise
839 // selecting a range is not going to work.
840 wxRichTextParagraphLayoutBox* container = & GetBuffer();
841 if (m_dragging)
842 {
843 flags = wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS;
844 container = GetFocusObject();
845 }
8db2e3ef 846 wxRichTextDrawingContext context(& GetBuffer());
4ba36292 847 int hit = container->HitTest(dc, context, GetUnscaledPoint(logicalPt), position, & hitObj, & contextObj, flags);
4fe83b93 848
d2d0adc7 849 // See if we need to change the cursor
88bee7e6 850
d2d0adc7 851 {
603f702b 852 if (hit != wxRICHTEXT_HITTEST_NONE && !(hit & wxRICHTEXT_HITTEST_OUTSIDE) && hitObj)
d2d0adc7 853 {
603f702b 854 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
590a0f8b
JS
855 if (actualContainer)
856 ProcessMouseMovement(actualContainer, hitObj, position, logicalPt);
d2d0adc7 857 }
f262b25c
JS
858 else
859 SetCursor(m_textCursor);
d2d0adc7
JS
860 }
861
862 if (!event.Dragging())
863 {
864 event.Skip();
865 return;
866 }
4fe83b93 867
0c0e063e
JS
868 if (m_dragging
869#if wxUSE_DRAG_AND_DROP
870 && !m_preDrag
f819ed5d 871 && (distance > 4)
55e01008 872#endif
0c0e063e 873 )
5d7836c4 874 {
603f702b
JS
875 wxRichTextParagraphLayoutBox* commonAncestor = NULL;
876 wxRichTextParagraphLayoutBox* otherContainer = NULL;
877 wxRichTextParagraphLayoutBox* firstContainer = NULL;
878
879 // Check for dragging across multiple containers
880 long position2 = 0;
881 wxRichTextObject* hitObj2 = NULL, *contextObj2 = NULL;
4ba36292 882 int hit2 = GetBuffer().HitTest(dc, context, GetUnscaledPoint(logicalPt), position2, & hitObj2, & contextObj2, 0);
603f702b
JS
883 if (hit2 != wxRICHTEXT_HITTEST_NONE && !(hit2 & wxRICHTEXT_HITTEST_OUTSIDE) && hitObj2 && hitObj != hitObj2)
884 {
885 // See if we can find a common ancestor
886 if (m_selectionState == wxRichTextCtrlSelectionState_Normal)
887 {
888 firstContainer = GetFocusObject();
889 commonAncestor = wxDynamicCast(firstContainer->GetParent(), wxRichTextParagraphLayoutBox);
890 }
891 else
892 {
893 firstContainer = wxDynamicCast(m_selectionAnchorObject, wxRichTextParagraphLayoutBox);
894 //commonAncestor = GetFocusObject(); // when the selection state is not normal, the focus object (e.g. table)
895 // is the common ancestor.
896 commonAncestor = wxDynamicCast(firstContainer->GetParent(), wxRichTextParagraphLayoutBox);
897 }
4fe83b93 898
603f702b
JS
899 if (commonAncestor && commonAncestor->HandlesChildSelections())
900 {
901 wxRichTextObject* p = hitObj2;
902 while (p)
903 {
904 if (p->GetParent() == commonAncestor)
905 {
906 otherContainer = wxDynamicCast(p, wxRichTextParagraphLayoutBox);
907 break;
908 }
909 p = p->GetParent();
910 }
911 }
5d7836c4 912
603f702b
JS
913 if (commonAncestor && firstContainer && otherContainer)
914 {
915 // We have now got a second container that shares a parent with the current or anchor object.
916 if (m_selectionState == wxRichTextCtrlSelectionState_Normal)
917 {
918 // Don't go into common-ancestor selection mode if we still have the same
919 // container.
920 if (otherContainer != firstContainer)
921 {
922 m_selectionState = wxRichTextCtrlSelectionState_CommonAncestor;
923 m_selectionAnchorObject = firstContainer;
924 m_selectionAnchor = firstContainer->GetRange().GetStart();
5d7836c4 925
603f702b
JS
926 // The common ancestor, such as a table, returns the cell selection
927 // between the anchor and current position.
928 m_selection = commonAncestor->GetSelection(m_selectionAnchor, otherContainer->GetRange().GetStart());
929 }
930 }
931 else
932 {
933 m_selection = commonAncestor->GetSelection(m_selectionAnchor, otherContainer->GetRange().GetStart());
934 }
5d7836c4 935
603f702b 936 Refresh();
7fe8059f 937
603f702b
JS
938 if (otherContainer->AcceptsFocus())
939 SetFocusObject(otherContainer, false /* don't set caret and clear selection */);
4fe83b93 940 MoveCaret(-1, false);
603f702b
JS
941 SetDefaultStyleToCursorStyle();
942 }
5d7836c4
JS
943 }
944 }
603f702b 945
0c0e063e
JS
946 if (hitObj && m_dragging && hit != wxRICHTEXT_HITTEST_NONE && m_selectionState == wxRichTextCtrlSelectionState_Normal
947#if wxUSE_DRAG_AND_DROP
948 && !m_preDrag
f819ed5d 949 && (distance > 4)
55e01008 950#endif
0c0e063e 951 )
603f702b 952 {
603f702b
JS
953 SetCaretPositionAfterClick(container, position, hit, true /* extend selection */);
954 }
5d7836c4
JS
955}
956
957/// Right-click
52170c5b 958void wxRichTextCtrl::OnRightClick(wxMouseEvent& event)
5d7836c4
JS
959{
960 SetFocus();
4fe83b93 961
603f702b
JS
962 wxClientDC dc(this);
963 PrepareDC(dc);
964 dc.SetFont(GetFont());
965
966 long position = 0;
967 wxPoint logicalPt = event.GetLogicalPosition(dc);
968 wxRichTextObject* hitObj = NULL;
969 wxRichTextObject* contextObj = NULL;
8db2e3ef 970 wxRichTextDrawingContext context(& GetBuffer());
4ba36292 971 int hit = GetFocusObject()->HitTest(dc, context, GetUnscaledPoint(logicalPt), position, & hitObj, & contextObj, wxRICHTEXT_HITTEST_HONOUR_ATOMIC);
603f702b
JS
972
973 if (hitObj && hitObj->GetContainer() != GetFocusObject())
974 {
975 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
976 if (actualContainer && actualContainer->AcceptsFocus())
977 {
978 SetFocusObject(actualContainer, false /* don't set caret position yet */);
979 SetCaretPositionAfterClick(actualContainer, position, hit);
980 }
981 }
db6634e0
JS
982
983 wxRichTextEvent cmdEvent(
984 wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK,
985 GetId());
986 cmdEvent.SetEventObject(this);
603f702b
JS
987 cmdEvent.SetPosition(position);
988 if (hitObj)
989 cmdEvent.SetContainer(hitObj->GetContainer());
1a75935d 990
52170c5b
JS
991 if (!GetEventHandler()->ProcessEvent(cmdEvent))
992 event.Skip();
5d7836c4
JS
993}
994
995/// Left-double-click
db6634e0 996void wxRichTextCtrl::OnLeftDClick(wxMouseEvent& WXUNUSED(event))
5d7836c4 997{
db6634e0
JS
998 wxRichTextEvent cmdEvent(
999 wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK,
1000 GetId());
1001 cmdEvent.SetEventObject(this);
1002 cmdEvent.SetPosition(m_caretPosition+1);
603f702b 1003 cmdEvent.SetContainer(GetFocusObject());
1a75935d 1004
db6634e0
JS
1005 if (!GetEventHandler()->ProcessEvent(cmdEvent))
1006 {
1007 SelectWord(GetCaretPosition()+1);
1008 }
5d7836c4
JS
1009}
1010
1011/// Middle-click
1012void wxRichTextCtrl::OnMiddleClick(wxMouseEvent& event)
1013{
db6634e0
JS
1014 wxRichTextEvent cmdEvent(
1015 wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK,
1016 GetId());
1017 cmdEvent.SetEventObject(this);
1018 cmdEvent.SetPosition(m_caretPosition+1);
603f702b 1019 cmdEvent.SetContainer(GetFocusObject());
1a75935d 1020
db6634e0
JS
1021 if (!GetEventHandler()->ProcessEvent(cmdEvent))
1022 event.Skip();
5dec941a
JS
1023
1024#if wxUSE_CLIPBOARD && wxUSE_DATAOBJ && wxHAVE_PRIMARY_SELECTION
1025 // Paste any PRIMARY selection, if it exists
1026 wxTheClipboard->UsePrimarySelection(true);
1027 Paste();
1028 wxTheClipboard->UsePrimarySelection(false);
1029#endif
5d7836c4
JS
1030}
1031
1032/// Key press
1033void wxRichTextCtrl::OnChar(wxKeyEvent& event)
1034{
1035 int flags = 0;
3e3a754f 1036 if (event.CmdDown())
5d7836c4
JS
1037 flags |= wxRICHTEXT_CTRL_DOWN;
1038 if (event.ShiftDown())
1039 flags |= wxRICHTEXT_SHIFT_DOWN;
1040 if (event.AltDown())
1041 flags |= wxRICHTEXT_ALT_DOWN;
1042
c80e8cbe
JS
1043 if (event.GetEventType() == wxEVT_KEY_DOWN)
1044 {
7a34307e 1045 if (event.IsKeyInCategory(WXK_CATEGORY_NAVIGATION))
8c9e72f9
JS
1046 {
1047 KeyboardNavigate(event.GetKeyCode(), flags);
1048 return;
1049 }
1050
1051 long keycode = event.GetKeyCode();
1052 switch ( keycode )
1053 {
1054 case WXK_ESCAPE:
1055 case WXK_START:
1056 case WXK_LBUTTON:
1057 case WXK_RBUTTON:
1058 case WXK_CANCEL:
1059 case WXK_MBUTTON:
1060 case WXK_CLEAR:
1061 case WXK_SHIFT:
1062 case WXK_ALT:
1063 case WXK_CONTROL:
1064 case WXK_MENU:
1065 case WXK_PAUSE:
1066 case WXK_CAPITAL:
1067 case WXK_END:
1068 case WXK_HOME:
1069 case WXK_LEFT:
1070 case WXK_UP:
1071 case WXK_RIGHT:
1072 case WXK_DOWN:
1073 case WXK_SELECT:
1074 case WXK_PRINT:
1075 case WXK_EXECUTE:
1076 case WXK_SNAPSHOT:
1077 case WXK_INSERT:
1078 case WXK_HELP:
1079 case WXK_F1:
1080 case WXK_F2:
1081 case WXK_F3:
1082 case WXK_F4:
1083 case WXK_F5:
1084 case WXK_F6:
1085 case WXK_F7:
1086 case WXK_F8:
1087 case WXK_F9:
1088 case WXK_F10:
1089 case WXK_F11:
1090 case WXK_F12:
1091 case WXK_F13:
1092 case WXK_F14:
1093 case WXK_F15:
1094 case WXK_F16:
1095 case WXK_F17:
1096 case WXK_F18:
1097 case WXK_F19:
1098 case WXK_F20:
1099 case WXK_F21:
1100 case WXK_F22:
1101 case WXK_F23:
1102 case WXK_F24:
1103 case WXK_NUMLOCK:
1104 case WXK_SCROLL:
1105 case WXK_PAGEUP:
1106 case WXK_PAGEDOWN:
1107 case WXK_NUMPAD_F1:
1108 case WXK_NUMPAD_F2:
1109 case WXK_NUMPAD_F3:
1110 case WXK_NUMPAD_F4:
1111 case WXK_NUMPAD_HOME:
1112 case WXK_NUMPAD_LEFT:
1113 case WXK_NUMPAD_UP:
1114 case WXK_NUMPAD_RIGHT:
1115 case WXK_NUMPAD_DOWN:
1116 case WXK_NUMPAD_PAGEUP:
1117 case WXK_NUMPAD_PAGEDOWN:
1118 case WXK_NUMPAD_END:
1119 case WXK_NUMPAD_BEGIN:
1120 case WXK_NUMPAD_INSERT:
8c9e72f9
JS
1121 case WXK_WINDOWS_LEFT:
1122 {
1123 return;
1124 }
1125 default:
1126 {
1127 }
1128 }
1129
c80e8cbe
JS
1130 // Must process this before translation, otherwise it's translated into a WXK_DELETE event.
1131 if (event.CmdDown() && event.GetKeyCode() == WXK_BACK)
1132 {
4ce3ebd3 1133 if (!ProcessBackKey(event, flags))
cc2aecde 1134 return;
c80e8cbe
JS
1135 }
1136 else
1137 event.Skip();
1138
1139 return;
1140 }
1141
99257cbe
VZ
1142 // all the other keys modify the controls contents which shouldn't be
1143 // possible if we're read-only
1144 if ( !IsEditable() )
1145 {
1146 event.Skip();
1147 return;
1148 }
1149
1150 if (event.GetKeyCode() == WXK_RETURN)
5d7836c4 1151 {
cc2aecde
JS
1152 if (!CanInsertContent(* GetFocusObject(), m_caretPosition+1))
1153 return;
5d7836c4
JS
1154
1155 long newPos = m_caretPosition;
1156
cc2aecde
JS
1157 if (HasSelection() && !CanDeleteRange(* GetFocusObject(), GetSelectionRange()))
1158 {
1159 return;
1160 }
1161
1162 BeginBatchUndo(_("Insert Text"));
1163
5d7836c4
JS
1164 DeleteSelectedContent(& newPos);
1165
ff76711f
JS
1166 if (event.ShiftDown())
1167 {
1168 wxString text;
1169 text = wxRichTextLineBreakChar;
4e63bfb9 1170 GetFocusObject()->InsertTextWithUndo(& GetBuffer(), newPos+1, text, this);
4bf9e5bc 1171 m_caretAtLineStart = true;
043c0d58 1172 PositionCaret();
ff76711f
JS
1173 }
1174 else
4e63bfb9 1175 GetFocusObject()->InsertNewlineWithUndo(& GetBuffer(), newPos+1, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE|wxRICHTEXT_INSERT_INTERACTIVE);
ff76711f 1176
4ce3ebd3
JS
1177 // Automatically renumber list
1178 bool isNumberedList = false;
1179 wxRichTextRange numberedListRange = FindRangeForList(newPos+1, isNumberedList);
1180 if (isNumberedList && numberedListRange != wxRichTextRange(-1, -1))
1181 {
1182 NumberList(numberedListRange, NULL, wxRICHTEXT_SETSTYLE_RENUMBER|wxRICHTEXT_SETSTYLE_WITH_UNDO);
1183 }
1184
d2d0adc7 1185 EndBatchUndo();
0a21bea0 1186 SetDefaultStyleToCursorStyle();
d2d0adc7
JS
1187
1188 ScrollIntoView(m_caretPosition, WXK_RIGHT);
5d7836c4
JS
1189
1190 wxRichTextEvent cmdEvent(
1191 wxEVT_COMMAND_RICHTEXT_RETURN,
1192 GetId());
1193 cmdEvent.SetEventObject(this);
1194 cmdEvent.SetFlags(flags);
5912d19e 1195 cmdEvent.SetPosition(newPos+1);
603f702b 1196 cmdEvent.SetContainer(GetFocusObject());
5912d19e 1197
d2d0adc7
JS
1198 if (!GetEventHandler()->ProcessEvent(cmdEvent))
1199 {
1200 // Generate conventional event
1201 wxCommandEvent textEvent(wxEVT_COMMAND_TEXT_ENTER, GetId());
1202 InitCommandEvent(textEvent);
88bee7e6 1203
d2d0adc7
JS
1204 GetEventHandler()->ProcessEvent(textEvent);
1205 }
621ae374 1206 Update();
5d7836c4
JS
1207 }
1208 else if (event.GetKeyCode() == WXK_BACK)
1209 {
4ce3ebd3 1210 ProcessBackKey(event, flags);
5d7836c4
JS
1211 }
1212 else if (event.GetKeyCode() == WXK_DELETE)
1213 {
c80e8cbe
JS
1214 long newPos = m_caretPosition;
1215
cc2aecde
JS
1216 if (HasSelection() && !CanDeleteRange(* GetFocusObject(), GetSelectionRange()))
1217 {
1218 return;
1219 }
1220
1221 BeginBatchUndo(_("Delete Text"));
1222
dc5de0dd 1223 bool processed = DeleteSelectedContent(& newPos);
c80e8cbe 1224
cc2aecde
JS
1225 int deletions = 0;
1226 if (processed)
1227 deletions ++;
1228
5d7836c4 1229 // Submit range in character positions, which are greater than caret positions,
603f702b 1230 if (newPos < GetFocusObject()->GetOwnRange().GetEnd()+1)
5d7836c4 1231 {
c80e8cbe
JS
1232 if (event.CmdDown())
1233 {
1234 long pos = wxRichTextCtrl::FindNextWordPosition(1);
1235 if (pos != -1 && (pos > newPos))
1236 {
cc2aecde
JS
1237 wxRichTextRange range(newPos+1, pos);
1238 if (CanDeleteRange(* GetFocusObject(), range.FromInternal()))
1239 {
1240 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1241 deletions ++;
1242 }
c80e8cbe
JS
1243 processed = true;
1244 }
1245 }
1246
fc6d9d0d 1247 if (!processed && newPos < (GetLastPosition()-1))
cc2aecde
JS
1248 {
1249 wxRichTextRange range(newPos+1, newPos+1);
1250 if (CanDeleteRange(* GetFocusObject(), range.FromInternal()))
1251 {
1252 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1253 deletions ++;
1254 }
1255 }
5d7836c4 1256 }
5d7836c4
JS
1257
1258 EndBatchUndo();
1259
5d7836c4
JS
1260 if (GetLastPosition() == -1)
1261 {
603f702b 1262 GetFocusObject()->Reset();
5d7836c4
JS
1263
1264 m_caretPosition = -1;
1265 PositionCaret();
0a21bea0 1266 SetDefaultStyleToCursorStyle();
5d7836c4 1267 }
5912d19e 1268
575be976
JS
1269 ScrollIntoView(m_caretPosition, WXK_LEFT);
1270
6cabfc59 1271 // Always send this event; wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED will be sent only if there is an actual deletion.
cc2aecde
JS
1272 {
1273 wxRichTextEvent cmdEvent(
1274 wxEVT_COMMAND_RICHTEXT_DELETE,
1275 GetId());
1276 cmdEvent.SetEventObject(this);
1277 cmdEvent.SetFlags(flags);
1278 cmdEvent.SetPosition(m_caretPosition+1);
1279 cmdEvent.SetContainer(GetFocusObject());
1280 GetEventHandler()->ProcessEvent(cmdEvent);
1281 }
5912d19e 1282
621ae374 1283 Update();
5d7836c4
JS
1284 }
1285 else
1286 {
3e3a754f
JS
1287 long keycode = event.GetKeyCode();
1288 switch ( keycode )
1289 {
1290 case WXK_ESCAPE:
3e3a754f
JS
1291 {
1292 event.Skip();
1293 return;
1294 }
1807a1f3 1295
3e3a754f
JS
1296 default:
1297 {
cfceb4a8 1298#ifdef __WXMAC__
91babb9d 1299 if (event.CmdDown())
cfceb4a8 1300#else
d2bb72ff
JS
1301 // Fixes AltGr+key with European input languages on Windows
1302 if ((event.CmdDown() && !event.AltDown()) || (event.AltDown() && !event.CmdDown()))
cfceb4a8 1303#endif
3e3a754f
JS
1304 {
1305 event.Skip();
1306 return;
1307 }
41a85215 1308
5912d19e
JS
1309 wxRichTextEvent cmdEvent(
1310 wxEVT_COMMAND_RICHTEXT_CHARACTER,
1311 GetId());
1312 cmdEvent.SetEventObject(this);
1313 cmdEvent.SetFlags(flags);
0b14a7bd
JS
1314#if wxUSE_UNICODE
1315 cmdEvent.SetCharacter(event.GetUnicodeKey());
1316#else
5912d19e 1317 cmdEvent.SetCharacter((wxChar) keycode);
0b14a7bd 1318#endif
5912d19e 1319 cmdEvent.SetPosition(m_caretPosition+1);
603f702b 1320 cmdEvent.SetContainer(GetFocusObject());
88bee7e6 1321
dadd4f55
JS
1322 if (keycode == wxT('\t'))
1323 {
1324 // See if we need to promote or demote the selection or paragraph at the cursor
1325 // position, instead of inserting a tab.
1326 long pos = GetAdjustedCaretPosition(GetCaretPosition());
603f702b 1327 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos);
dadd4f55
JS
1328 if (para && para->GetRange().GetStart() == pos && para->GetAttributes().HasListStyleName())
1329 {
1330 wxRichTextRange range;
1331 if (HasSelection())
1332 range = GetSelectionRange();
1333 else
1334 range = para->GetRange().FromInternal();
41a85215 1335
dadd4f55
JS
1336 int promoteBy = event.ShiftDown() ? 1 : -1;
1337
1338 PromoteList(promoteBy, range, NULL);
d2d0adc7 1339
5912d19e
JS
1340 GetEventHandler()->ProcessEvent(cmdEvent);
1341
dadd4f55
JS
1342 return;
1343 }
1344 }
5d7836c4 1345
cc2aecde
JS
1346 if (!CanInsertContent(* GetFocusObject(), m_caretPosition+1))
1347 return;
1348
1349 if (HasSelection() && !CanDeleteRange(* GetFocusObject(), GetSelectionRange()))
1350 return;
1351
3e3a754f 1352 BeginBatchUndo(_("Insert Text"));
5d7836c4 1353
3e3a754f
JS
1354 long newPos = m_caretPosition;
1355 DeleteSelectedContent(& newPos);
5d7836c4 1356
0b14a7bd
JS
1357#if wxUSE_UNICODE
1358 wxString str = event.GetUnicodeKey();
1359#else
3e3a754f 1360 wxString str = (wxChar) event.GetKeyCode();
0b14a7bd 1361#endif
4e63bfb9 1362 GetFocusObject()->InsertTextWithUndo(& GetBuffer(), newPos+1, str, this, 0);
5d7836c4 1363
3e3a754f
JS
1364 EndBatchUndo();
1365
0a21bea0 1366 SetDefaultStyleToCursorStyle();
3e3a754f 1367 ScrollIntoView(m_caretPosition, WXK_RIGHT);
88bee7e6 1368
c1dd924d 1369 cmdEvent.SetPosition(m_caretPosition);
5912d19e
JS
1370 GetEventHandler()->ProcessEvent(cmdEvent);
1371
621ae374 1372 Update();
3e3a754f
JS
1373 }
1374 }
5d7836c4 1375 }
5d7836c4
JS
1376}
1377
8db2e3ef 1378bool wxRichTextCtrl::ProcessMouseMovement(wxRichTextParagraphLayoutBox* container, wxRichTextObject* WXUNUSED(obj), long position, const wxPoint& WXUNUSED(pos))
590a0f8b
JS
1379{
1380 wxRichTextAttr attr;
1381 if (container && GetStyle(position, attr, container))
1382 {
1383 if (attr.HasFlag(wxTEXT_ATTR_URL))
1384 {
1385 SetCursor(m_urlCursor);
1386 }
1387 else if (!attr.HasFlag(wxTEXT_ATTR_URL))
1388 {
1389 SetCursor(m_textCursor);
1390 }
1391 return true;
1392 }
1393 else
1394 return false;
1395}
1396
4ce3ebd3
JS
1397// Processes the back key
1398bool wxRichTextCtrl::ProcessBackKey(wxKeyEvent& event, int flags)
1399{
1400 if (!IsEditable())
1401 {
1402 return false;
1403 }
1404
1405 if (HasSelection() && !CanDeleteRange(* GetFocusObject(), GetSelectionRange()))
1406 {
1407 return false;
1408 }
1409
1410 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(m_caretPosition, true);
1411
1412 // If we're at the start of a list item with a bullet, let's 'delete' the bullet, i.e.
1413 // make it a continuation paragraph.
1414 if (!HasSelection() && para && ((m_caretPosition+1) == para->GetRange().GetStart()) &&
1415 para->GetAttributes().HasBulletStyle() && (para->GetAttributes().GetBulletStyle() & wxTEXT_ATTR_BULLET_STYLE_CONTINUATION) == 0)
1416 {
1417 wxRichTextParagraph* newPara = wxDynamicCast(para->Clone(), wxRichTextParagraph);
1418 newPara->GetAttributes().SetBulletStyle(newPara->GetAttributes().GetBulletStyle() | wxTEXT_ATTR_BULLET_STYLE_CONTINUATION);
1419
1420 wxRichTextAction* action = new wxRichTextAction(NULL, _("Remove Bullet"), wxRICHTEXT_CHANGE_STYLE, & GetBuffer(), GetFocusObject(), this);
1421 action->SetRange(newPara->GetRange());
1422 action->SetPosition(GetCaretPosition());
1423 action->GetNewParagraphs().AppendChild(newPara);
1424 // Also store the old ones for Undo
1425 action->GetOldParagraphs().AppendChild(new wxRichTextParagraph(*para));
1426
1427 GetBuffer().Invalidate(para->GetRange());
1428 GetBuffer().SubmitAction(action);
1429
1430 // Automatically renumber list
1431 bool isNumberedList = false;
1432 wxRichTextRange numberedListRange = FindRangeForList(m_caretPosition, isNumberedList);
1433 if (isNumberedList && numberedListRange != wxRichTextRange(-1, -1))
1434 {
1435 NumberList(numberedListRange, NULL, wxRICHTEXT_SETSTYLE_RENUMBER|wxRICHTEXT_SETSTYLE_WITH_UNDO);
1436 }
1437
1438 Update();
1439 }
1440 else
1441 {
1442 BeginBatchUndo(_("Delete Text"));
1443
1444 long newPos = m_caretPosition;
1445
1446 bool processed = DeleteSelectedContent(& newPos);
1447
1448 int deletions = 0;
1449 if (processed)
1450 deletions ++;
1451
1452 // Submit range in character positions, which are greater than caret positions,
1453 // so subtract 1 for deleted character and add 1 for conversion to character position.
1454 if (newPos > -1)
1455 {
1456 if (event.CmdDown())
1457 {
1458 long pos = wxRichTextCtrl::FindNextWordPosition(-1);
1459 if (pos < newPos)
1460 {
1461 wxRichTextRange range(pos+1, newPos);
1462 if (CanDeleteRange(* GetFocusObject(), range.FromInternal()))
1463 {
1464 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1465 deletions ++;
1466 }
1467 processed = true;
1468 }
1469 }
1470
1471 if (!processed)
1472 {
1473 wxRichTextRange range(newPos, newPos);
1474 if (CanDeleteRange(* GetFocusObject(), range.FromInternal()))
1475 {
1476 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1477 deletions ++;
1478 }
1479 }
1480 }
1481
1482 EndBatchUndo();
1483
1484 if (GetLastPosition() == -1)
1485 {
1486 GetFocusObject()->Reset();
1487
1488 m_caretPosition = -1;
1489 PositionCaret();
1490 SetDefaultStyleToCursorStyle();
1491 }
1492
1493 ScrollIntoView(m_caretPosition, WXK_LEFT);
1494
1495 // Always send this event; wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED will be sent only if there is an actual deletion.
1496 {
1497 wxRichTextEvent cmdEvent(
1498 wxEVT_COMMAND_RICHTEXT_DELETE,
1499 GetId());
1500 cmdEvent.SetEventObject(this);
1501 cmdEvent.SetFlags(flags);
1502 cmdEvent.SetPosition(m_caretPosition+1);
1503 cmdEvent.SetContainer(GetFocusObject());
1504 GetEventHandler()->ProcessEvent(cmdEvent);
1505 }
1506
1507 Update();
1508 }
1509
1510 return true;
1511}
1512
5d7836c4
JS
1513/// Delete content if there is a selection, e.g. when pressing a key.
1514bool wxRichTextCtrl::DeleteSelectedContent(long* newPos)
1515{
1516 if (HasSelection())
1517 {
603f702b
JS
1518 long pos = m_selection.GetRange().GetStart();
1519 wxRichTextRange range = m_selection.GetRange();
205a1ad9
JS
1520
1521 // SelectAll causes more to be selected than doing it interactively,
1522 // and causes a new paragraph to be inserted. So for multiline buffers,
1523 // don't delete the final position.
1524 if (range.GetEnd() == GetLastPosition() && GetNumberOfLines() > 0)
1525 range.SetEnd(range.GetEnd()-1);
1526
603f702b
JS
1527 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1528 m_selection.Reset();
1529 m_selectionState = wxRichTextCtrlSelectionState_Normal;
5d7836c4
JS
1530
1531 if (newPos)
1532 *newPos = pos-1;
1533 return true;
1534 }
1535 else
1536 return false;
1537}
1538
1539/// Keyboard navigation
1540
1541/*
1542
1543Left: left one character
1544Right: right one character
1545Up: up one line
1546Down: down one line
1547Ctrl-Left: left one word
1548Ctrl-Right: right one word
1549Ctrl-Up: previous paragraph start
1550Ctrl-Down: next start of paragraph
1551Home: start of line
1552End: end of line
1553Ctrl-Home: start of document
1554Ctrl-End: end of document
1555Page-Up: Up a screen
1556Page-Down: Down a screen
1557
1558Maybe:
1559
1560Ctrl-Alt-PgUp: Start of window
1561Ctrl-Alt-PgDn: End of window
1562F8: Start selection mode
1563Esc: End selection mode
1564
1565Adding Shift does the above but starts/extends selection.
1566
1567
1568 */
1569
0bab774b 1570bool wxRichTextCtrl::KeyboardNavigate(int keyCode, int flags)
5d7836c4
JS
1571{
1572 bool success = false;
5d7836c4 1573
3e3a754f 1574 if (keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT)
5d7836c4
JS
1575 {
1576 if (flags & wxRICHTEXT_CTRL_DOWN)
1577 success = WordRight(1, flags);
1578 else
1579 success = MoveRight(1, flags);
1580 }
3e3a754f 1581 else if (keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT)
5d7836c4
JS
1582 {
1583 if (flags & wxRICHTEXT_CTRL_DOWN)
1584 success = WordLeft(1, flags);
1585 else
1586 success = MoveLeft(1, flags);
1587 }
3e3a754f 1588 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP)
5d7836c4
JS
1589 {
1590 if (flags & wxRICHTEXT_CTRL_DOWN)
1591 success = MoveToParagraphStart(flags);
1592 else
1593 success = MoveUp(1, flags);
1594 }
3e3a754f 1595 else if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN)
5d7836c4
JS
1596 {
1597 if (flags & wxRICHTEXT_CTRL_DOWN)
1598 success = MoveToParagraphEnd(flags);
1599 else
1600 success = MoveDown(1, flags);
1601 }
3e3a754f 1602 else if (keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP)
5d7836c4
JS
1603 {
1604 success = PageUp(1, flags);
1605 }
3e3a754f 1606 else if (keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
5d7836c4
JS
1607 {
1608 success = PageDown(1, flags);
1609 }
3e3a754f 1610 else if (keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME)
5d7836c4
JS
1611 {
1612 if (flags & wxRICHTEXT_CTRL_DOWN)
1613 success = MoveHome(flags);
1614 else
1615 success = MoveToLineStart(flags);
1616 }
3e3a754f 1617 else if (keyCode == WXK_END || keyCode == WXK_NUMPAD_END)
5d7836c4
JS
1618 {
1619 if (flags & wxRICHTEXT_CTRL_DOWN)
1620 success = MoveEnd(flags);
1621 else
1622 success = MoveToLineEnd(flags);
1623 }
1624
1625 if (success)
1626 {
1627 ScrollIntoView(m_caretPosition, keyCode);
0a21bea0 1628 SetDefaultStyleToCursorStyle();
5d7836c4
JS
1629 }
1630
5d7836c4
JS
1631 return success;
1632}
1633
1634/// Extend the selection. Selections are in caret positions.
1635bool wxRichTextCtrl::ExtendSelection(long oldPos, long newPos, int flags)
1636{
1637 if (flags & wxRICHTEXT_SHIFT_DOWN)
1638 {
e2d0875a
JS
1639 if (oldPos == newPos)
1640 return false;
1641
603f702b 1642 wxRichTextSelection oldSelection = m_selection;
4fe83b93 1643
603f702b 1644 m_selection.SetContainer(GetFocusObject());
4fe83b93 1645
603f702b
JS
1646 wxRichTextRange oldRange;
1647 if (m_selection.IsValid())
1648 oldRange = m_selection.GetRange();
1649 else
1650 oldRange = wxRICHTEXT_NO_SELECTION;
1651 wxRichTextRange newRange;
7051fa41 1652
5d7836c4 1653 // If not currently selecting, start selecting
603f702b 1654 if (oldRange.GetStart() == -2)
5d7836c4
JS
1655 {
1656 m_selectionAnchor = oldPos;
1657
1658 if (oldPos > newPos)
603f702b 1659 newRange.SetRange(newPos+1, oldPos);
5d7836c4 1660 else
603f702b 1661 newRange.SetRange(oldPos+1, newPos);
5d7836c4
JS
1662 }
1663 else
1664 {
1665 // Always ensure that the selection range start is greater than
1666 // the end.
1667 if (newPos > m_selectionAnchor)
603f702b 1668 newRange.SetRange(m_selectionAnchor+1, newPos);
e2d0875a 1669 else if (newPos == m_selectionAnchor)
603f702b 1670 newRange = wxRichTextRange(-2, -2);
5d7836c4 1671 else
603f702b 1672 newRange.SetRange(newPos+1, m_selectionAnchor);
5d7836c4 1673 }
4fe83b93 1674
603f702b 1675 m_selection.SetRange(newRange);
5d7836c4 1676
603f702b 1677 RefreshForSelectionChange(oldSelection, m_selection);
7051fa41 1678
603f702b 1679 if (newRange.GetStart() > newRange.GetEnd())
5d7836c4
JS
1680 {
1681 wxLogDebug(wxT("Strange selection range"));
1682 }
7fe8059f 1683
5d7836c4
JS
1684 return true;
1685 }
1686 else
1687 return false;
1688}
1689
1690/// Scroll into view, returning true if we scrolled.
1691/// This takes a _caret_ position.
1692bool wxRichTextCtrl::ScrollIntoView(long position, int keyCode)
1693{
1694 wxRichTextLine* line = GetVisibleLineForCaretPosition(position);
1695
1696 if (!line)
1697 return false;
1698
1699 int ppuX, ppuY;
1700 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1701
3956d02a
JS
1702 int startXUnits, startYUnits;
1703 GetViewStart(& startXUnits, & startYUnits);
1704 int startY = startYUnits * ppuY;
5d7836c4 1705
8d7eaf91 1706 int sx = 0, sy = 0;
5d7836c4 1707 GetVirtualSize(& sx, & sy);
3956d02a
JS
1708 int sxUnits = 0;
1709 int syUnits = 0;
5d7836c4 1710 if (ppuY != 0)
3956d02a 1711 syUnits = sy/ppuY;
5d7836c4 1712
4ba36292 1713 wxRect rect = GetScaledRect(line->GetRect());
5d7836c4
JS
1714
1715 bool scrolled = false;
1716
1717 wxSize clientSize = GetClientSize();
4fe83b93 1718
603f702b
JS
1719 int leftMargin, rightMargin, topMargin, bottomMargin;
1720
1721 {
1722 wxClientDC dc(this);
1723 wxRichTextObject::GetTotalMargin(dc, & GetBuffer(), GetBuffer().GetAttributes(), leftMargin, rightMargin,
1724 topMargin, bottomMargin);
1725 }
4ba36292 1726 clientSize.y -= (int) (0.5 + bottomMargin * GetScale());
e9f10004
JS
1727
1728 if (GetWindowStyle() & wxRE_CENTRE_CARET)
1729 {
1730 int y = rect.y - GetClientSize().y/2;
1731 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
4ba36292 1732 if (y >= 0 && (y + clientSize.y) < (int) (0.5 + GetBuffer().GetCachedSize().y * GetScale()))
e9f10004
JS
1733 {
1734 if (startYUnits != yUnits)
1735 {
1736 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1737 scrolled = true;
1738 }
1739#if !wxRICHTEXT_USE_OWN_CARET
1740 if (scrolled)
1741#endif
1742 PositionCaret();
1743
1744 return scrolled;
1745 }
1746 }
5d7836c4
JS
1747
1748 // Going down
3e3a754f 1749 if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN ||
ec36b155 1750 keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT ||
3e3a754f
JS
1751 keyCode == WXK_END || keyCode == WXK_NUMPAD_END ||
1752 keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
5d7836c4
JS
1753 {
1754 if ((rect.y + rect.height) > (clientSize.y + startY))
1755 {
1756 // Make it scroll so this item is at the bottom
1757 // of the window
1758 int y = rect.y - (clientSize.y - rect.height);
3956d02a 1759 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
c59f6793 1760
3956d02a
JS
1761 // If we're still off the screen, scroll another line down
1762 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1763 yUnits ++;
1764
1765 if (startYUnits != yUnits)
c59f6793 1766 {
3956d02a 1767 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
c59f6793
JS
1768 scrolled = true;
1769 }
5d7836c4 1770 }
4ba36292 1771 else if (rect.y < (startY + (int) (0.5 + GetBuffer().GetTopMargin() * GetScale())))
5d7836c4
JS
1772 {
1773 // Make it scroll so this item is at the top
1774 // of the window
4ba36292 1775 int y = rect.y - (int) (0.5 + GetBuffer().GetTopMargin() * GetScale());
3956d02a 1776 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
c59f6793 1777
3956d02a 1778 if (startYUnits != yUnits)
c59f6793 1779 {
3956d02a 1780 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
c59f6793
JS
1781 scrolled = true;
1782 }
5d7836c4 1783 }
5d7836c4
JS
1784 }
1785 // Going up
3e3a754f
JS
1786 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP ||
1787 keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT ||
1788 keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME ||
1789 keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP )
5d7836c4 1790 {
4ba36292 1791 if (rect.y < (startY + (int) (0.5 + GetBuffer().GetBottomMargin() * GetScale())))
5d7836c4
JS
1792 {
1793 // Make it scroll so this item is at the top
1794 // of the window
4ba36292 1795 int y = rect.y - (int) (0.5 + GetBuffer().GetTopMargin() * GetScale());
3956d02a 1796 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
c59f6793 1797
3956d02a 1798 if (startYUnits != yUnits)
c59f6793 1799 {
3956d02a 1800 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
c59f6793
JS
1801 scrolled = true;
1802 }
5d7836c4
JS
1803 }
1804 else if ((rect.y + rect.height) > (clientSize.y + startY))
1805 {
1806 // Make it scroll so this item is at the bottom
1807 // of the window
1808 int y = rect.y - (clientSize.y - rect.height);
3956d02a
JS
1809 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1810
1811 // If we're still off the screen, scroll another line down
1812 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1813 yUnits ++;
c59f6793 1814
3956d02a 1815 if (startYUnits != yUnits)
c59f6793 1816 {
3956d02a 1817 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
c59f6793
JS
1818 scrolled = true;
1819 }
5d7836c4 1820 }
5d7836c4 1821 }
109bfc88 1822
1c13f06e 1823#if !wxRICHTEXT_USE_OWN_CARET
109bfc88 1824 if (scrolled)
1c13f06e 1825#endif
109bfc88 1826 PositionCaret();
5d7836c4
JS
1827
1828 return scrolled;
1829}
1830
1831/// Is the given position visible on the screen?
1832bool wxRichTextCtrl::IsPositionVisible(long pos) const
1833{
1834 wxRichTextLine* line = GetVisibleLineForCaretPosition(pos-1);
1835
1836 if (!line)
1837 return false;
1838
1839 int ppuX, ppuY;
1840 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1841
1842 int startX, startY;
1843 GetViewStart(& startX, & startY);
1844 startX = 0;
1845 startY = startY * ppuY;
1846
4ba36292 1847 wxRect rect = GetScaledRect(line->GetRect());
5d7836c4 1848 wxSize clientSize = GetClientSize();
4ba36292 1849 clientSize.y -= (int) (0.5 + GetBuffer().GetBottomMargin() * GetScale());
5d7836c4 1850
4ba36292
JS
1851 return (rect.GetTop() >= (startY + (int) (0.5 + GetBuffer().GetTopMargin() * GetScale()))) &&
1852 (rect.GetBottom() <= (startY + clientSize.y));
5d7836c4
JS
1853}
1854
1855void wxRichTextCtrl::SetCaretPosition(long position, bool showAtLineStart)
1856{
1857 m_caretPosition = position;
1858 m_caretAtLineStart = showAtLineStart;
1859}
1860
1861/// Move caret one visual step forward: this may mean setting a flag
1862/// and keeping the same position if we're going from the end of one line
1863/// to the start of the next, which may be the exact same caret position.
1864void wxRichTextCtrl::MoveCaretForward(long oldPosition)
1865{
603f702b 1866 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(oldPosition);
5d7836c4
JS
1867
1868 // Only do the check if we're not at the end of the paragraph (where things work OK
1869 // anyway)
1870 if (para && (oldPosition != para->GetRange().GetEnd() - 1))
1871 {
603f702b 1872 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(oldPosition);
5d7836c4
JS
1873
1874 if (line)
1875 {
1e967276
JS
1876 wxRichTextRange lineRange = line->GetAbsoluteRange();
1877
5d7836c4
JS
1878 // We're at the end of a line. See whether we need to
1879 // stay at the same actual caret position but change visual
1880 // position, or not.
1e967276 1881 if (oldPosition == lineRange.GetEnd())
5d7836c4
JS
1882 {
1883 if (m_caretAtLineStart)
1884 {
1885 // We're already at the start of the line, so actually move on now.
1886 m_caretPosition = oldPosition + 1;
1887 m_caretAtLineStart = false;
1888 }
1889 else
1890 {
1891 // We're showing at the end of the line, so keep to
1892 // the same position but indicate that we're to show
1893 // at the start of the next line.
1894 m_caretPosition = oldPosition;
7fe8059f 1895 m_caretAtLineStart = true;
5d7836c4 1896 }
0a21bea0 1897 SetDefaultStyleToCursorStyle();
5d7836c4
JS
1898 return;
1899 }
1900 }
1901 }
1902 m_caretPosition ++;
0a21bea0 1903 SetDefaultStyleToCursorStyle();
5d7836c4
JS
1904}
1905
1906/// Move caret one visual step backward: this may mean setting a flag
1907/// and keeping the same position if we're going from the end of one line
1908/// to the start of the next, which may be the exact same caret position.
1909void wxRichTextCtrl::MoveCaretBack(long oldPosition)
1910{
603f702b 1911 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(oldPosition);
5d7836c4
JS
1912
1913 // Only do the check if we're not at the start of the paragraph (where things work OK
1914 // anyway)
1915 if (para && (oldPosition != para->GetRange().GetStart()))
1916 {
603f702b 1917 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(oldPosition);
5d7836c4
JS
1918
1919 if (line)
1920 {
1e967276
JS
1921 wxRichTextRange lineRange = line->GetAbsoluteRange();
1922
5d7836c4
JS
1923 // We're at the start of a line. See whether we need to
1924 // stay at the same actual caret position but change visual
1925 // position, or not.
1e967276 1926 if (oldPosition == lineRange.GetStart())
5d7836c4
JS
1927 {
1928 m_caretPosition = oldPosition-1;
1929 m_caretAtLineStart = true;
1930 return;
1931 }
1e967276 1932 else if (oldPosition == lineRange.GetEnd())
5d7836c4
JS
1933 {
1934 if (m_caretAtLineStart)
1935 {
1936 // We're at the start of the line, so keep the same caret position
1937 // but clear the start-of-line flag.
1938 m_caretPosition = oldPosition;
1939 m_caretAtLineStart = false;
1940 }
1941 else
1942 {
1943 // We're showing at the end of the line, so go back
1944 // to the previous character position.
1945 m_caretPosition = oldPosition - 1;
1946 }
0a21bea0 1947 SetDefaultStyleToCursorStyle();
5d7836c4
JS
1948 return;
1949 }
1950 }
1951 }
1952 m_caretPosition --;
0a21bea0 1953 SetDefaultStyleToCursorStyle();
5d7836c4
JS
1954}
1955
1956/// Move right
1957bool wxRichTextCtrl::MoveRight(int noPositions, int flags)
1958{
603f702b 1959 long endPos = GetFocusObject()->GetOwnRange().GetEnd();
5d7836c4
JS
1960
1961 if (m_caretPosition + noPositions < endPos)
1962 {
1963 long oldPos = m_caretPosition;
1964 long newPos = m_caretPosition + noPositions;
1965
1966 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1967 if (!extendSel)
1968 SelectNone();
1969
1970 // Determine by looking at oldPos and m_caretPosition whether
1971 // we moved from the end of a line to the start of the next line, in which case
1972 // we want to adjust the caret position such that it is positioned at the
1973 // start of the next line, rather than jumping past the first character of the
1974 // line.
75e50f45 1975 if (noPositions == 1)
5d7836c4
JS
1976 MoveCaretForward(oldPos);
1977 else
1978 SetCaretPosition(newPos);
1979
1980 PositionCaret();
0a21bea0 1981 SetDefaultStyleToCursorStyle();
5d7836c4 1982
5d7836c4
JS
1983 return true;
1984 }
1985 else
7fe8059f 1986 return false;
5d7836c4
JS
1987}
1988
1989/// Move left
1990bool wxRichTextCtrl::MoveLeft(int noPositions, int flags)
1991{
1992 long startPos = -1;
1993
1994 if (m_caretPosition > startPos - noPositions + 1)
1995 {
1996 long oldPos = m_caretPosition;
1997 long newPos = m_caretPosition - noPositions;
1998 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1999 if (!extendSel)
2000 SelectNone();
2001
75e50f45 2002 if (noPositions == 1)
5d7836c4
JS
2003 MoveCaretBack(oldPos);
2004 else
2005 SetCaretPosition(newPos);
2006
2007 PositionCaret();
0a21bea0 2008 SetDefaultStyleToCursorStyle();
5d7836c4 2009
5d7836c4
JS
2010 return true;
2011 }
2012 else
7fe8059f 2013 return false;
5d7836c4
JS
2014}
2015
603f702b
JS
2016// Find the caret position for the combination of hit-test flags and character position.
2017// Returns the caret position and also an indication of where to place the caret (caretLineStart)
2018// since this is ambiguous (same position used for end of line and start of next).
2019long wxRichTextCtrl::FindCaretPositionForCharacterPosition(long position, int hitTestFlags, wxRichTextParagraphLayoutBox* container,
2020 bool& caretLineStart)
2021{
2022 // If end of previous line, and hitTest is wxRICHTEXT_HITTEST_BEFORE,
2023 // we want to be at the end of the last line but with m_caretAtLineStart set to true,
2024 // so we view the caret at the start of the line.
2025 caretLineStart = false;
2026 long caretPosition = position;
2027
2028 if (hitTestFlags & wxRICHTEXT_HITTEST_BEFORE)
2029 {
2030 wxRichTextLine* thisLine = container->GetLineAtPosition(position-1);
2031 wxRichTextRange lineRange;
2032 if (thisLine)
2033 lineRange = thisLine->GetAbsoluteRange();
2034
2035 if (thisLine && (position-1) == lineRange.GetEnd())
2036 {
2037 caretPosition --;
2038 caretLineStart = true;
2039 }
2040 else
2041 {
2042 wxRichTextParagraph* para = container->GetParagraphAtPosition(position);
2043 if (para && para->GetRange().GetStart() == position)
2044 caretPosition --;
2045 }
2046 }
2047 return caretPosition;
2048}
2049
5d7836c4
JS
2050/// Move up
2051bool wxRichTextCtrl::MoveUp(int noLines, int flags)
2052{
2053 return MoveDown(- noLines, flags);
2054}
2055
2056/// Move up
2057bool wxRichTextCtrl::MoveDown(int noLines, int flags)
2058{
c59f6793
JS
2059 if (!GetCaret())
2060 return false;
2061
603f702b 2062 long lineNumber = GetFocusObject()->GetVisibleLineNumber(m_caretPosition, true, m_caretAtLineStart);
5d7836c4 2063 wxPoint pt = GetCaret()->GetPosition();
4fe83b93 2064 long newLine = lineNumber + noLines;
603f702b 2065 bool notInThisObject = false;
5d7836c4
JS
2066
2067 if (lineNumber != -1)
2068 {
2069 if (noLines > 0)
2070 {
603f702b 2071 long lastLine = GetFocusObject()->GetVisibleLineNumber(GetFocusObject()->GetOwnRange().GetEnd());
5d7836c4 2072 if (newLine > lastLine)
603f702b 2073 notInThisObject = true;
5d7836c4
JS
2074 }
2075 else
2076 {
2077 if (newLine < 0)
603f702b 2078 notInThisObject = true;
5d7836c4
JS
2079 }
2080 }
4fe83b93 2081
603f702b 2082 wxRichTextParagraphLayoutBox* container = GetFocusObject();
7c9fdebe 2083 int hitTestFlags = wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS|wxRICHTEXT_HITTEST_NO_FLOATING_OBJECTS|wxRICHTEXT_HITTEST_HONOUR_ATOMIC;
5d7836c4 2084
76e36b94 2085 bool lineIsEmpty = false;
603f702b 2086 if (notInThisObject)
7fe8059f 2087 {
603f702b
JS
2088 // If we know we're navigating out of the current object,
2089 // try to find an object anywhere in the buffer at the new position (up or down a bit)
2090 container = & GetBuffer();
343ef639 2091 hitTestFlags &= ~wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS;
4fe83b93 2092
603f702b
JS
2093 if (noLines > 0) // going down
2094 {
2095 pt.y = GetFocusObject()->GetPosition().y + GetFocusObject()->GetCachedSize().y + 2;
2096 }
2097 else // going up
2098 {
2099 pt.y = GetFocusObject()->GetPosition().y - 2;
2100 }
5d7836c4
JS
2101 }
2102 else
603f702b
JS
2103 {
2104 wxRichTextLine* lineObj = GetFocusObject()->GetLineForVisibleLineNumber(newLine);
2105 if (lineObj)
76e36b94 2106 {
603f702b 2107 pt.y = lineObj->GetAbsolutePosition().y + 2;
76e36b94
JS
2108 if (lineObj->GetRange().GetStart() == lineObj->GetRange().GetEnd())
2109 lineIsEmpty = true;
2110 }
603f702b
JS
2111 else
2112 return false;
2113 }
5d7836c4
JS
2114
2115 long newPos = 0;
2116 wxClientDC dc(this);
2117 PrepareDC(dc);
2118 dc.SetFont(GetFont());
7fe8059f 2119
603f702b
JS
2120 wxRichTextObject* hitObj = NULL;
2121 wxRichTextObject* contextObj = NULL;
8db2e3ef
JS
2122 wxRichTextDrawingContext context(& GetBuffer());
2123 int hitTest = container->HitTest(dc, context, pt, newPos, & hitObj, & contextObj, hitTestFlags);
7fe8059f 2124
343ef639
JS
2125 if (hitObj &&
2126 ((hitTest & wxRICHTEXT_HITTEST_NONE) == 0) &&
2127 (! (hitObj == (& m_buffer) && ((hitTest & wxRICHTEXT_HITTEST_OUTSIDE) != 0))) // outside the buffer counts as 'do nothing'
2128 )
5d7836c4 2129 {
603f702b 2130 if (notInThisObject)
5d7836c4 2131 {
603f702b
JS
2132 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
2133 if (actualContainer && actualContainer != GetFocusObject() && actualContainer->AcceptsFocus())
5d7836c4 2134 {
603f702b 2135 SetFocusObject(actualContainer, false /* don't set caret position yet */);
4fe83b93 2136
603f702b 2137 container = actualContainer;
5d7836c4
JS
2138 }
2139 }
4fe83b93 2140
603f702b 2141 bool caretLineStart = true;
76e36b94
JS
2142
2143 // If the line is empty, there is only one possible position for the caret,
2144 // so force the 'before' state so FindCaretPositionForCharacterPosition doesn't
2145 // just return the same position.
2146 if (lineIsEmpty)
2147 {
2148 hitTest &= ~wxRICHTEXT_HITTEST_AFTER;
2149 hitTest |= wxRICHTEXT_HITTEST_BEFORE;
2150 }
603f702b
JS
2151 long caretPosition = FindCaretPositionForCharacterPosition(newPos, hitTest, container, caretLineStart);
2152 long newSelEnd = caretPosition;
2153 bool extendSel;
2154
2155 if (notInThisObject)
2156 extendSel = false;
2157 else
2158 extendSel = ExtendSelection(m_caretPosition, newSelEnd, flags);
5d7836c4 2159
c59f6793 2160 if (!extendSel)
5d7836c4
JS
2161 SelectNone();
2162
603f702b 2163 SetCaretPosition(caretPosition, caretLineStart);
5d7836c4 2164 PositionCaret();
0a21bea0 2165 SetDefaultStyleToCursorStyle();
5d7836c4 2166
5d7836c4
JS
2167 return true;
2168 }
41e155b4
WS
2169
2170 return false;
5d7836c4
JS
2171}
2172
2173/// Move to the end of the paragraph
2174bool wxRichTextCtrl::MoveToParagraphEnd(int flags)
2175{
603f702b 2176 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(m_caretPosition, true);
5d7836c4
JS
2177 if (para)
2178 {
2179 long newPos = para->GetRange().GetEnd() - 1;
c59f6793
JS
2180 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
2181 if (!extendSel)
5d7836c4
JS
2182 SelectNone();
2183
2184 SetCaretPosition(newPos);
2185 PositionCaret();
0a21bea0 2186 SetDefaultStyleToCursorStyle();
5d7836c4 2187
5d7836c4
JS
2188 return true;
2189 }
2190
2191 return false;
2192}
2193
2194/// Move to the start of the paragraph
2195bool wxRichTextCtrl::MoveToParagraphStart(int flags)
2196{
603f702b 2197 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(m_caretPosition, true);
5d7836c4
JS
2198 if (para)
2199 {
2200 long newPos = para->GetRange().GetStart() - 1;
c59f6793
JS
2201 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
2202 if (!extendSel)
5d7836c4
JS
2203 SelectNone();
2204
04b2b47a 2205 SetCaretPosition(newPos, true);
5d7836c4 2206 PositionCaret();
0a21bea0 2207 SetDefaultStyleToCursorStyle();
5d7836c4 2208
5d7836c4
JS
2209 return true;
2210 }
2211
2212 return false;
2213}
2214
2215/// Move to the end of the line
2216bool wxRichTextCtrl::MoveToLineEnd(int flags)
2217{
2218 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
2219
2220 if (line)
2221 {
1e967276
JS
2222 wxRichTextRange lineRange = line->GetAbsoluteRange();
2223 long newPos = lineRange.GetEnd();
c59f6793
JS
2224 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
2225 if (!extendSel)
5d7836c4
JS
2226 SelectNone();
2227
2228 SetCaretPosition(newPos);
2229 PositionCaret();
0a21bea0 2230 SetDefaultStyleToCursorStyle();
5d7836c4 2231
5d7836c4
JS
2232 return true;
2233 }
2234
2235 return false;
2236}
2237
2238/// Move to the start of the line
2239bool wxRichTextCtrl::MoveToLineStart(int flags)
2240{
2241 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
2242 if (line)
2243 {
1e967276
JS
2244 wxRichTextRange lineRange = line->GetAbsoluteRange();
2245 long newPos = lineRange.GetStart()-1;
5d7836c4 2246
c59f6793
JS
2247 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
2248 if (!extendSel)
5d7836c4
JS
2249 SelectNone();
2250
603f702b 2251 wxRichTextParagraph* para = GetFocusObject()->GetParagraphForLine(line);
5d7836c4 2252
1e967276 2253 SetCaretPosition(newPos, para->GetRange().GetStart() != lineRange.GetStart());
5d7836c4 2254 PositionCaret();
0a21bea0 2255 SetDefaultStyleToCursorStyle();
5d7836c4 2256
5d7836c4
JS
2257 return true;
2258 }
2259
2260 return false;
2261}
2262
2263/// Move to the start of the buffer
2264bool wxRichTextCtrl::MoveHome(int flags)
2265{
2266 if (m_caretPosition != -1)
2267 {
c59f6793
JS
2268 bool extendSel = ExtendSelection(m_caretPosition, -1, flags);
2269 if (!extendSel)
5d7836c4
JS
2270 SelectNone();
2271
2272 SetCaretPosition(-1);
2273 PositionCaret();
0a21bea0 2274 SetDefaultStyleToCursorStyle();
5d7836c4 2275
5d7836c4
JS
2276 return true;
2277 }
2278 else
7fe8059f 2279 return false;
5d7836c4
JS
2280}
2281
2282/// Move to the end of the buffer
2283bool wxRichTextCtrl::MoveEnd(int flags)
2284{
603f702b 2285 long endPos = GetFocusObject()->GetOwnRange().GetEnd()-1;
5d7836c4
JS
2286
2287 if (m_caretPosition != endPos)
2288 {
c59f6793
JS
2289 bool extendSel = ExtendSelection(m_caretPosition, endPos, flags);
2290 if (!extendSel)
5d7836c4
JS
2291 SelectNone();
2292
2293 SetCaretPosition(endPos);
2294 PositionCaret();
0a21bea0 2295 SetDefaultStyleToCursorStyle();
5d7836c4 2296
5d7836c4
JS
2297 return true;
2298 }
2299 else
7fe8059f 2300 return false;
5d7836c4
JS
2301}
2302
2303/// Move noPages pages up
2304bool wxRichTextCtrl::PageUp(int noPages, int flags)
2305{
2306 return PageDown(- noPages, flags);
2307}
2308
2309/// Move noPages pages down
2310bool wxRichTextCtrl::PageDown(int noPages, int flags)
2311{
2312 // Calculate which line occurs noPages * screen height further down.
2313 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
2314 if (line)
2315 {
2316 wxSize clientSize = GetClientSize();
2317 int newY = line->GetAbsolutePosition().y + noPages*clientSize.y;
2318
603f702b 2319 wxRichTextLine* newLine = GetFocusObject()->GetLineAtYPosition(newY);
5d7836c4
JS
2320 if (newLine)
2321 {
1e967276
JS
2322 wxRichTextRange lineRange = newLine->GetAbsoluteRange();
2323 long pos = lineRange.GetStart()-1;
5d7836c4
JS
2324 if (pos != m_caretPosition)
2325 {
603f702b 2326 wxRichTextParagraph* para = GetFocusObject()->GetParagraphForLine(newLine);
5d7836c4 2327
c59f6793
JS
2328 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2329 if (!extendSel)
5d7836c4
JS
2330 SelectNone();
2331
1e967276 2332 SetCaretPosition(pos, para->GetRange().GetStart() != lineRange.GetStart());
5d7836c4 2333 PositionCaret();
0a21bea0 2334 SetDefaultStyleToCursorStyle();
5d7836c4 2335
5d7836c4
JS
2336 return true;
2337 }
2338 }
2339 }
2340
2341 return false;
2342}
2343
0871b343
JS
2344static bool wxRichTextCtrlIsWhitespace(const wxString& str)
2345{
bea12bf0 2346 return str == wxT(" ") || str == wxT("\t") || (!str.empty() && (str[0] == (wxChar) 160));
0871b343
JS
2347}
2348
5d7836c4
JS
2349// Finds the caret position for the next word
2350long wxRichTextCtrl::FindNextWordPosition(int direction) const
7fe8059f 2351{
603f702b 2352 long endPos = GetFocusObject()->GetOwnRange().GetEnd();
5d7836c4
JS
2353
2354 if (direction > 0)
2355 {
2356 long i = m_caretPosition+1+direction; // +1 for conversion to character pos
7fe8059f 2357
5d7836c4
JS
2358 // First skip current text to space
2359 while (i < endPos && i > -1)
2360 {
2361 // i is in character, not caret positions
603f702b
JS
2362 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2363 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
0871b343
JS
2364 if (line && (i == line->GetAbsoluteRange().GetEnd()))
2365 {
2366 break;
2367 }
2368 else if (!wxRichTextCtrlIsWhitespace(text) && !text.empty())
5d7836c4
JS
2369 i += direction;
2370 else
2371 {
2372 break;
2373 }
2374 }
2375 while (i < endPos && i > -1)
2376 {
2377 // i is in character, not caret positions
603f702b
JS
2378 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2379 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
0871b343
JS
2380 if (line && (i == line->GetAbsoluteRange().GetEnd()))
2381 return wxMax(-1, i);
2382
7fe8059f 2383 if (text.empty()) // End of paragraph, or maybe an image
5d7836c4 2384 return wxMax(-1, i - 1);
0871b343 2385 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
5d7836c4
JS
2386 i += direction;
2387 else
2388 {
2389 // Convert to caret position
2390 return wxMax(-1, i - 1);
2391 }
2392 }
2393 if (i >= endPos)
2394 return endPos-1;
2395 return i-1;
2396 }
2397 else
2398 {
2399 long i = m_caretPosition;
2400
2401 // First skip white space
2402 while (i < endPos && i > -1)
2403 {
2404 // i is in character, not caret positions
603f702b
JS
2405 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2406 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
0871b343
JS
2407
2408 if (text.empty() || (line && (i == line->GetAbsoluteRange().GetStart()))) // End of paragraph, or maybe an image
5d7836c4 2409 break;
0871b343 2410 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
5d7836c4
JS
2411 i += direction;
2412 else
2413 break;
2414 }
2415 // Next skip current text to space
2416 while (i < endPos && i > -1)
2417 {
2418 // i is in character, not caret positions
603f702b
JS
2419 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2420 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
0871b343
JS
2421 if (line && line->GetAbsoluteRange().GetStart() == i)
2422 return i-1;
2423
2424 if (!wxRichTextCtrlIsWhitespace(text) /* && !text.empty() */)
5d7836c4
JS
2425 i += direction;
2426 else
2427 {
2428 return i;
5d7836c4
JS
2429 }
2430 }
2431 if (i < -1)
2432 return -1;
2433 return i;
2434 }
2435}
2436
2437/// Move n words left
2438bool wxRichTextCtrl::WordLeft(int WXUNUSED(n), int flags)
2439{
2440 long pos = FindNextWordPosition(-1);
2441 if (pos != m_caretPosition)
2442 {
603f702b 2443 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos, true);
7fe8059f 2444
c59f6793
JS
2445 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2446 if (!extendSel)
5d7836c4 2447 SelectNone();
7fe8059f 2448
5d7836c4
JS
2449 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
2450 PositionCaret();
0a21bea0 2451 SetDefaultStyleToCursorStyle();
5d7836c4 2452
5d7836c4
JS
2453 return true;
2454 }
7fe8059f 2455
5d7836c4
JS
2456 return false;
2457}
2458
2459/// Move n words right
2460bool wxRichTextCtrl::WordRight(int WXUNUSED(n), int flags)
2461{
2462 long pos = FindNextWordPosition(1);
2463 if (pos != m_caretPosition)
2464 {
603f702b 2465 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos, true);
7fe8059f 2466
c59f6793
JS
2467 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2468 if (!extendSel)
5d7836c4 2469 SelectNone();
7fe8059f 2470
5d7836c4
JS
2471 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
2472 PositionCaret();
0a21bea0 2473 SetDefaultStyleToCursorStyle();
5d7836c4 2474
5d7836c4
JS
2475 return true;
2476 }
7fe8059f 2477
5d7836c4
JS
2478 return false;
2479}
2480
2481/// Sizing
2482void wxRichTextCtrl::OnSize(wxSizeEvent& event)
2483{
4d551ad5 2484 // Only do sizing optimization for large buffers
603f702b 2485 if (GetBuffer().GetOwnRange().GetEnd() > m_delayedLayoutThreshold)
4d551ad5
JS
2486 {
2487 m_fullLayoutRequired = true;
2488 m_fullLayoutTime = wxGetLocalTimeMillis();
2489 m_fullLayoutSavedPosition = GetFirstVisiblePosition();
2f36e8dc 2490 LayoutContent(true /* onlyVisibleRect */);
4d551ad5
JS
2491 }
2492 else
2493 GetBuffer().Invalidate(wxRICHTEXT_ALL);
7fe8059f 2494
3e3a754f 2495#if wxRICHTEXT_BUFFERED_PAINTING
5d7836c4 2496 RecreateBuffer();
3e3a754f 2497#endif
5d7836c4
JS
2498
2499 event.Skip();
2500}
2501
98769552
JS
2502// Force any pending layout due to large buffer
2503void wxRichTextCtrl::ForceDelayedLayout()
2504{
2505 if (m_fullLayoutRequired)
2506 {
2507 m_fullLayoutRequired = false;
2508 m_fullLayoutTime = 0;
2509 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2510 ShowPosition(m_fullLayoutSavedPosition);
2511 Refresh(false);
2512 Update();
2513 }
2514}
4d551ad5
JS
2515
2516/// Idle-time processing
2517void wxRichTextCtrl::OnIdle(wxIdleEvent& event)
2518{
1c13f06e
JS
2519#if wxRICHTEXT_USE_OWN_CARET
2520 if (((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
2521 {
2522 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate(false);
2523 PositionCaret();
2524 GetCaret()->Show();
2525 }
2526#endif
2527
4d551ad5
JS
2528 const int layoutInterval = wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL;
2529
2530 if (m_fullLayoutRequired && (wxGetLocalTimeMillis() > (m_fullLayoutTime + layoutInterval)))
2531 {
2532 m_fullLayoutRequired = false;
2533 m_fullLayoutTime = 0;
2534 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2535 ShowPosition(m_fullLayoutSavedPosition);
76bcd815 2536 Refresh(false);
4d551ad5 2537 }
ab14c7aa
JS
2538
2539 if (m_caretPositionForDefaultStyle != -2)
2540 {
2541 // If the caret position has changed, no longer reflect the default style
2542 // in the UI.
2543 if (GetCaretPosition() != m_caretPositionForDefaultStyle)
2544 m_caretPositionForDefaultStyle = -2;
2545 }
2546
4d551ad5
JS
2547 event.Skip();
2548}
2549
c59f6793
JS
2550/// Scrolling
2551void wxRichTextCtrl::OnScroll(wxScrollWinEvent& event)
2552{
1c13f06e
JS
2553#if wxRICHTEXT_USE_OWN_CARET
2554 if (!((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
2555 {
2556 GetCaret()->Hide();
2557 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate();
2558 }
2559#endif
2560
c59f6793
JS
2561 event.Skip();
2562}
2563
5d7836c4 2564/// Set up scrollbars, e.g. after a resize
169adfa9 2565void wxRichTextCtrl::SetupScrollbars(bool atTop)
5d7836c4 2566{
17808a75 2567 if (IsFrozen())
5d7836c4
JS
2568 return;
2569
12f5219f 2570 if (GetBuffer().IsEmpty() || !m_verticalScrollbarEnabled)
5d7836c4
JS
2571 {
2572 SetScrollbars(0, 0, 0, 0, 0, 0);
2573 return;
2574 }
2575
2576 // TODO: reimplement scrolling so we scroll by line, not by fixed number
2577 // of pixels. See e.g. wxVScrolledWindow for ideas.
3956d02a 2578 int pixelsPerUnit = 5;
5d7836c4
JS
2579 wxSize clientSize = GetClientSize();
2580
4ba36292 2581 int maxHeight = (int) (0.5 + GetScale() * (GetBuffer().GetCachedSize().y + GetBuffer().GetTopMargin()));
5d7836c4 2582
3956d02a
JS
2583 // Round up so we have at least maxHeight pixels
2584 int unitsY = (int) (((float)maxHeight/(float)pixelsPerUnit) + 0.5);
5d7836c4 2585
169adfa9
JS
2586 int startX = 0, startY = 0;
2587 if (!atTop)
2588 GetViewStart(& startX, & startY);
7fe8059f 2589
7051fa41 2590 int maxPositionX = 0;
3956d02a 2591 int maxPositionY = (int) ((((float)(wxMax((unitsY*pixelsPerUnit) - clientSize.y, 0)))/((float)pixelsPerUnit)) + 0.5);
7fe8059f 2592
7051fa41
JS
2593 int newStartX = wxMin(maxPositionX, startX);
2594 int newStartY = wxMin(maxPositionY, startY);
2595
2596 int oldPPUX, oldPPUY;
2597 int oldStartX, oldStartY;
2598 int oldVirtualSizeX = 0, oldVirtualSizeY = 0;
2599 GetScrollPixelsPerUnit(& oldPPUX, & oldPPUY);
2600 GetViewStart(& oldStartX, & oldStartY);
2601 GetVirtualSize(& oldVirtualSizeX, & oldVirtualSizeY);
2602 if (oldPPUY > 0)
2603 oldVirtualSizeY /= oldPPUY;
2604
2605 if (oldPPUX == 0 && oldPPUY == pixelsPerUnit && oldVirtualSizeY == unitsY && oldStartX == newStartX && oldStartY == newStartY)
2606 return;
2607
2608 // Don't set scrollbars if there were none before, and there will be none now.
205a1ad9 2609 if (oldPPUY != 0 && (oldVirtualSizeY*oldPPUY < clientSize.y) && (unitsY*pixelsPerUnit < clientSize.y))
7051fa41
JS
2610 return;
2611
5d7836c4
JS
2612 // Move to previous scroll position if
2613 // possible
7051fa41 2614 SetScrollbars(0, pixelsPerUnit, 0, unitsY, newStartX, newStartY);
5d7836c4
JS
2615}
2616
2617/// Paint the background
2618void wxRichTextCtrl::PaintBackground(wxDC& dc)
2619{
2620 wxColour backgroundColour = GetBackgroundColour();
a1b806b9 2621 if (!backgroundColour.IsOk())
5d7836c4
JS
2622 backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
2623
2624 // Clear the background
2625 dc.SetBrush(wxBrush(backgroundColour));
2626 dc.SetPen(*wxTRANSPARENT_PEN);
7fe8059f 2627 wxRect windowRect(GetClientSize());
5d7836c4
JS
2628 windowRect.x -= 2; windowRect.y -= 2;
2629 windowRect.width += 4; windowRect.height += 4;
7fe8059f 2630
5d7836c4
JS
2631 // We need to shift the rectangle to take into account
2632 // scrolling. Converting device to logical coordinates.
2633 CalcUnscrolledPosition(windowRect.x, windowRect.y, & windowRect.x, & windowRect.y);
2634 dc.DrawRectangle(windowRect);
2635}
2636
3e3a754f 2637#if wxRICHTEXT_BUFFERED_PAINTING
5d7836c4
JS
2638/// Recreate buffer bitmap if necessary
2639bool wxRichTextCtrl::RecreateBuffer(const wxSize& size)
2640{
2641 wxSize sz = size;
2642 if (sz == wxDefaultSize)
2643 sz = GetClientSize();
7fe8059f 2644
5d7836c4
JS
2645 if (sz.x < 1 || sz.y < 1)
2646 return false;
7fe8059f 2647
a1b806b9 2648 if (!m_bufferBitmap.IsOk() || m_bufferBitmap.GetWidth() < sz.x || m_bufferBitmap.GetHeight() < sz.y)
5d7836c4 2649 m_bufferBitmap = wxBitmap(sz.x, sz.y);
a1b806b9 2650 return m_bufferBitmap.IsOk();
5d7836c4 2651}
3e3a754f 2652#endif
5d7836c4
JS
2653
2654// ----------------------------------------------------------------------------
2655// file IO functions
2656// ----------------------------------------------------------------------------
2657
3306aec1
JS
2658bool wxRichTextCtrl::DoLoadFile(const wxString& filename, int fileType)
2659{
5a376169
JS
2660 SetFocusObject(& GetBuffer(), true);
2661
d75a69e8 2662 bool success = GetBuffer().LoadFile(filename, (wxRichTextFileType)fileType);
5d7836c4
JS
2663 if (success)
2664 m_filename = filename;
2665
2666 DiscardEdits();
2667 SetInsertionPoint(0);
2f36e8dc 2668 LayoutContent();
5d7836c4 2669 PositionCaret();
169adfa9 2670 SetupScrollbars(true);
76bcd815 2671 Refresh(false);
0ec1179b 2672 wxTextCtrl::SendTextUpdatedEvent(this);
5d7836c4
JS
2673
2674 if (success)
2675 return true;
2676 else
2677 {
2678 wxLogError(_("File couldn't be loaded."));
7fe8059f 2679
5d7836c4
JS
2680 return false;
2681 }
2682}
2683
3306aec1 2684bool wxRichTextCtrl::DoSaveFile(const wxString& filename, int fileType)
5d7836c4 2685{
d75a69e8 2686 if (GetBuffer().SaveFile(filename, (wxRichTextFileType)fileType))
5d7836c4 2687 {
3306aec1 2688 m_filename = filename;
5d7836c4
JS
2689
2690 DiscardEdits();
2691
2692 return true;
5d7836c4
JS
2693 }
2694
2695 wxLogError(_("The text couldn't be saved."));
2696
2697 return false;
2698}
2699
2700// ----------------------------------------------------------------------------
2701// wxRichTextCtrl specific functionality
2702// ----------------------------------------------------------------------------
2703
2704/// Add a new paragraph of text to the end of the buffer
2705wxRichTextRange wxRichTextCtrl::AddParagraph(const wxString& text)
2706{
603f702b 2707 wxRichTextRange range = GetFocusObject()->AddParagraph(text);
4fe83b93 2708 GetBuffer().Invalidate();
62381daa
JS
2709 LayoutContent();
2710 return range;
5d7836c4
JS
2711}
2712
2713/// Add an image
2714wxRichTextRange wxRichTextCtrl::AddImage(const wxImage& image)
2715{
603f702b 2716 wxRichTextRange range = GetFocusObject()->AddImage(image);
4fe83b93 2717 GetBuffer().Invalidate();
62381daa
JS
2718 LayoutContent();
2719 return range;
5d7836c4
JS
2720}
2721
2722// ----------------------------------------------------------------------------
2723// selection and ranges
2724// ----------------------------------------------------------------------------
2725
5d7836c4
JS
2726/// Select none
2727void wxRichTextCtrl::SelectNone()
2728{
603f702b 2729 if (m_selection.IsValid())
c1aec196 2730 {
603f702b 2731 wxRichTextSelection oldSelection = m_selection;
7051fa41 2732
603f702b 2733 m_selection.Reset();
7051fa41 2734
603f702b 2735 RefreshForSelectionChange(oldSelection, m_selection);
c1aec196 2736 }
5d7836c4 2737 m_selectionAnchor = -2;
603f702b
JS
2738 m_selectionAnchorObject = NULL;
2739 m_selectionState = wxRichTextCtrlSelectionState_Normal;
5d7836c4
JS
2740}
2741
0ca07313
JS
2742static bool wxIsWordDelimiter(const wxString& text)
2743{
1c07e924 2744 return !text.IsEmpty() && !wxIsalnum(text[0]);
0ca07313
JS
2745}
2746
2747/// Select the word at the given character position
2748bool wxRichTextCtrl::SelectWord(long position)
2749{
603f702b 2750 if (position < 0 || position > GetFocusObject()->GetOwnRange().GetEnd())
0ca07313 2751 return false;
1807a1f3 2752
603f702b 2753 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(position);
0ca07313
JS
2754 if (!para)
2755 return false;
2756
62381daa
JS
2757 if (position == para->GetRange().GetEnd())
2758 position --;
2759
0ca07313
JS
2760 long positionStart = position;
2761 long positionEnd = position;
1807a1f3 2762
0ca07313
JS
2763 for (positionStart = position; positionStart >= para->GetRange().GetStart(); positionStart --)
2764 {
603f702b 2765 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(positionStart, positionStart));
0ca07313
JS
2766 if (wxIsWordDelimiter(text))
2767 {
2768 positionStart ++;
2769 break;
2770 }
2771 }
2772 if (positionStart < para->GetRange().GetStart())
2773 positionStart = para->GetRange().GetStart();
1807a1f3 2774
0ca07313
JS
2775 for (positionEnd = position; positionEnd < para->GetRange().GetEnd(); positionEnd ++)
2776 {
603f702b 2777 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(positionEnd, positionEnd));
0ca07313
JS
2778 if (wxIsWordDelimiter(text))
2779 {
2780 positionEnd --;
2781 break;
2782 }
2783 }
2784 if (positionEnd >= para->GetRange().GetEnd())
2785 positionEnd = para->GetRange().GetEnd();
1807a1f3 2786
62381daa
JS
2787 if (positionEnd < positionStart)
2788 return false;
2789
0ca07313
JS
2790 SetSelection(positionStart, positionEnd+1);
2791
2792 if (positionStart >= 0)
2793 {
2794 MoveCaret(positionStart-1, true);
0a21bea0 2795 SetDefaultStyleToCursorStyle();
0ca07313
JS
2796 }
2797
2798 return true;
2799}
2800
5d7836c4
JS
2801wxString wxRichTextCtrl::GetStringSelection() const
2802{
2803 long from, to;
2804 GetSelection(&from, &to);
2805
2806 return GetRange(from, to);
2807}
2808
5d7836c4
JS
2809// ----------------------------------------------------------------------------
2810// hit testing
2811// ----------------------------------------------------------------------------
2812
2813wxTextCtrlHitTestResult
2814wxRichTextCtrl::HitTest(const wxPoint& pt, wxTextCoord *x, wxTextCoord *y) const
2815{
2816 // implement in terms of the other overload as the native ports typically
2817 // can get the position and not (x, y) pair directly (although wxUniv
2818 // directly gets x and y -- and so overrides this method as well)
2819 long pos;
2820 wxTextCtrlHitTestResult rc = HitTest(pt, &pos);
2821
2822 if ( rc != wxTE_HT_UNKNOWN )
2823 {
2824 PositionToXY(pos, x, y);
2825 }
2826
2827 return rc;
2828}
2829
2830wxTextCtrlHitTestResult
2831wxRichTextCtrl::HitTest(const wxPoint& pt,
2832 long * pos) const
2833{
2834 wxClientDC dc((wxRichTextCtrl*) this);
2835 ((wxRichTextCtrl*)this)->PrepareDC(dc);
61399247 2836
563d25ba
JS
2837 // Buffer uses logical position (relative to start of buffer)
2838 // so convert
2839 wxPoint pt2 = GetLogicalPoint(pt);
5d7836c4 2840
603f702b
JS
2841 wxRichTextObject* hitObj = NULL;
2842 wxRichTextObject* contextObj = NULL;
8db2e3ef
JS
2843 wxRichTextDrawingContext context((wxRichTextBuffer*) & GetBuffer());
2844 int hit = ((wxRichTextCtrl*)this)->GetFocusObject()->HitTest(dc, context, pt2, *pos, & hitObj, & contextObj, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS);
41e155b4 2845
f262b25c
JS
2846 if ((hit & wxRICHTEXT_HITTEST_BEFORE) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2847 return wxTE_HT_BEFORE;
2848 else if ((hit & wxRICHTEXT_HITTEST_AFTER) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2849 return wxTE_HT_BEYOND;
25d6eb3a 2850 else if (hit & (wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_AFTER))
f262b25c 2851 return wxTE_HT_ON_TEXT;
41e155b4
WS
2852
2853 return wxTE_HT_UNKNOWN;
5d7836c4
JS
2854}
2855
0c0e063e
JS
2856wxRichTextParagraphLayoutBox*
2857wxRichTextCtrl::FindContainerAtPoint(const wxPoint pt, long& position, int& hit, wxRichTextObject* hitObj, int flags/* = 0*/)
2858{
2859 wxClientDC dc(this);
2860 PrepareDC(dc);
2861 dc.SetFont(GetFont());
2862
2863 wxPoint logicalPt = GetLogicalPoint(pt);
2864
2865 wxRichTextObject* contextObj = NULL;
8db2e3ef 2866 wxRichTextDrawingContext context(& GetBuffer());
4ba36292 2867 hit = GetBuffer().HitTest(dc, context, GetUnscaledPoint(logicalPt), position, &hitObj, &contextObj, flags);
0c0e063e
JS
2868 wxRichTextParagraphLayoutBox* container = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
2869
2870 return container;
2871}
2872
2873
5d7836c4
JS
2874// ----------------------------------------------------------------------------
2875// set/get the controls text
2876// ----------------------------------------------------------------------------
2877
805c8d92 2878wxString wxRichTextCtrl::DoGetValue() const
5d7836c4
JS
2879{
2880 return GetBuffer().GetText();
2881}
2882
2883wxString wxRichTextCtrl::GetRange(long from, long to) const
2884{
96c9f0f6 2885 // Public API for range is different from internals
603f702b 2886 return GetFocusObject()->GetTextForRange(wxRichTextRange(from, to-1));
5d7836c4
JS
2887}
2888
343ae70d 2889void wxRichTextCtrl::DoSetValue(const wxString& value, int flags)
5d7836c4 2890{
d081739d
JS
2891 // Don't call Clear here, since it always sends a text updated event
2892 m_buffer.ResetAndClearCommands();
603f702b 2893 m_buffer.Invalidate(wxRICHTEXT_ALL);
d081739d
JS
2894 m_caretPosition = -1;
2895 m_caretPositionForDefaultStyle = -2;
2896 m_caretAtLineStart = false;
603f702b
JS
2897 m_selection.Reset();
2898 m_selectionState = wxRichTextCtrlSelectionState_Normal;
d081739d
JS
2899
2900 Scroll(0,0);
2901
2902 if (!IsFrozen())
2903 {
2904 LayoutContent();
2905 Refresh(false);
2906 }
5d7836c4 2907
1a75935d 2908 if (!value.IsEmpty())
5d7836c4 2909 {
1a75935d
JS
2910 // Remove empty paragraph
2911 GetBuffer().Clear();
d081739d 2912 DoWriteText(value, flags);
5d7836c4
JS
2913
2914 // for compatibility, don't move the cursor when doing SetValue()
2915 SetInsertionPoint(0);
2916 }
1a75935d 2917 else
5d7836c4 2918 {
1a75935d
JS
2919 // still send an event for consistency
2920 if (flags & SetValue_SendEvent)
0ec1179b 2921 wxTextCtrl::SendTextUpdatedEvent(this);
5d7836c4 2922 }
5d7836c4
JS
2923 DiscardEdits();
2924}
2925
2926void wxRichTextCtrl::WriteText(const wxString& value)
2927{
2928 DoWriteText(value);
2929}
2930
343ae70d 2931void wxRichTextCtrl::DoWriteText(const wxString& value, int flags)
5d7836c4 2932{
0ca07313 2933 wxString valueUnix = wxTextFile::Translate(value, wxTextFileType_Unix);
fe5aa22c 2934
4e63bfb9 2935 GetFocusObject()->InsertTextWithUndo(& GetBuffer(), m_caretPosition+1, valueUnix, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
32423dd8 2936 GetBuffer().Defragment();
343ae70d
VZ
2937
2938 if ( flags & SetValue_SendEvent )
0ec1179b 2939 wxTextCtrl::SendTextUpdatedEvent(this);
5d7836c4
JS
2940}
2941
2942void wxRichTextCtrl::AppendText(const wxString& text)
2943{
2944 SetInsertionPointEnd();
2945
2946 WriteText(text);
2947}
2948
2949/// Write an image at the current insertion point
24777478 2950bool wxRichTextCtrl::WriteImage(const wxImage& image, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
5d7836c4
JS
2951{
2952 wxRichTextImageBlock imageBlock;
2953
2954 wxImage image2 = image;
2955 if (imageBlock.MakeImageBlock(image2, bitmapType))
24777478 2956 return WriteImage(imageBlock, textAttr);
41e155b4
WS
2957
2958 return false;
5d7836c4
JS
2959}
2960
24777478 2961bool wxRichTextCtrl::WriteImage(const wxString& filename, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
5d7836c4
JS
2962{
2963 wxRichTextImageBlock imageBlock;
2964
2965 wxImage image;
2966 if (imageBlock.MakeImageBlock(filename, bitmapType, image, false))
24777478 2967 return WriteImage(imageBlock, textAttr);
41e155b4
WS
2968
2969 return false;
5d7836c4
JS
2970}
2971
24777478 2972bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock& imageBlock, const wxRichTextAttr& textAttr)
5d7836c4 2973{
4e63bfb9 2974 return GetFocusObject()->InsertImageWithUndo(& GetBuffer(), m_caretPosition+1, imageBlock, this, 0, textAttr);
5d7836c4
JS
2975}
2976
24777478 2977bool wxRichTextCtrl::WriteImage(const wxBitmap& bitmap, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
5d7836c4 2978{
a1b806b9 2979 if (bitmap.IsOk())
5d7836c4
JS
2980 {
2981 wxRichTextImageBlock imageBlock;
7fe8059f 2982
5d7836c4 2983 wxImage image = bitmap.ConvertToImage();
a1b806b9 2984 if (image.IsOk() && imageBlock.MakeImageBlock(image, bitmapType))
24777478 2985 return WriteImage(imageBlock, textAttr);
5d7836c4 2986 }
41e155b4 2987
5d7836c4
JS
2988 return false;
2989}
2990
603f702b
JS
2991// Write a text box at the current insertion point.
2992wxRichTextBox* wxRichTextCtrl::WriteTextBox(const wxRichTextAttr& textAttr)
2993{
2994 wxRichTextBox* textBox = new wxRichTextBox;
2995 textBox->SetAttributes(textAttr);
2996 textBox->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
2997 textBox->AddParagraph(wxEmptyString);
2998 textBox->SetParent(NULL);
2999
3000 // The object returned is the one actually inserted into the buffer,
3001 // while the original one is deleted.
4e63bfb9 3002 wxRichTextObject* obj = GetFocusObject()->InsertObjectWithUndo(& GetBuffer(), m_caretPosition+1, textBox, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
603f702b
JS
3003 wxRichTextBox* box = wxDynamicCast(obj, wxRichTextBox);
3004 return box;
3005}
3006
7c9fdebe
JS
3007wxRichTextField* wxRichTextCtrl::WriteField(const wxString& fieldType, const wxRichTextProperties& properties,
3008 const wxRichTextAttr& textAttr)
3009{
3010 return GetFocusObject()->InsertFieldWithUndo(& GetBuffer(), m_caretPosition+1, fieldType, properties,
3011 this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE, textAttr);
3012}
3013
603f702b
JS
3014// Write a table at the current insertion point, returning the table.
3015wxRichTextTable* wxRichTextCtrl::WriteTable(int rows, int cols, const wxRichTextAttr& tableAttr, const wxRichTextAttr& cellAttr)
3016{
3017 wxASSERT(rows > 0 && cols > 0);
3018
3019 if (rows <= 0 || cols <= 0)
3020 return NULL;
3021
3022 wxRichTextTable* table = new wxRichTextTable;
3023 table->SetAttributes(tableAttr);
3024 table->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
4fe83b93 3025
603f702b
JS
3026 table->CreateTable(rows, cols);
3027
3028 table->SetParent(NULL);
3029
3030 int i, j;
3031 for (j = 0; j < rows; j++)
3032 {
3033 for (i = 0; i < cols; i++)
3034 {
3035 table->GetCell(j, i)->GetAttributes() = cellAttr;
3036 }
3037 }
3038
3039 // The object returned is the one actually inserted into the buffer,
3040 // while the original one is deleted.
4e63bfb9 3041 wxRichTextObject* obj = GetFocusObject()->InsertObjectWithUndo(& GetBuffer(), m_caretPosition+1, table, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
603f702b
JS
3042 wxRichTextTable* tableResult = wxDynamicCast(obj, wxRichTextTable);
3043 return tableResult;
3044}
3045
3046
5d7836c4
JS
3047/// Insert a newline (actually paragraph) at the current insertion point.
3048bool wxRichTextCtrl::Newline()
3049{
4e63bfb9 3050 return GetFocusObject()->InsertNewlineWithUndo(& GetBuffer(), m_caretPosition+1, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
5d7836c4
JS
3051}
3052
ff76711f
JS
3053/// Insert a line break at the current insertion point.
3054bool wxRichTextCtrl::LineBreak()
3055{
3056 wxString text;
3057 text = wxRichTextLineBreakChar;
4e63bfb9 3058 return GetFocusObject()->InsertTextWithUndo(& GetBuffer(), m_caretPosition+1, text, this);
ff76711f 3059}
5d7836c4
JS
3060
3061// ----------------------------------------------------------------------------
3062// Clipboard operations
3063// ----------------------------------------------------------------------------
3064
3065void wxRichTextCtrl::Copy()
3066{
3067 if (CanCopy())
3068 {
fe5aa22c 3069 wxRichTextRange range = GetInternalSelectionRange();
5d7836c4
JS
3070 GetBuffer().CopyToClipboard(range);
3071 }
3072}
3073
3074void wxRichTextCtrl::Cut()
3075{
3076 if (CanCut())
3077 {
fe5aa22c 3078 wxRichTextRange range = GetInternalSelectionRange();
5d7836c4
JS
3079 GetBuffer().CopyToClipboard(range);
3080
3081 DeleteSelectedContent();
2f36e8dc 3082 LayoutContent();
76bcd815 3083 Refresh(false);
5d7836c4
JS
3084 }
3085}
3086
3087void wxRichTextCtrl::Paste()
3088{
3089 if (CanPaste())
3090 {
3091 BeginBatchUndo(_("Paste"));
7fe8059f 3092
5d7836c4
JS
3093 long newPos = m_caretPosition;
3094 DeleteSelectedContent(& newPos);
7fe8059f 3095
5d7836c4
JS
3096 GetBuffer().PasteFromClipboard(newPos);
3097
3098 EndBatchUndo();
3099 }
3100}
3101
3102void wxRichTextCtrl::DeleteSelection()
3103{
3104 if (CanDeleteSelection())
3105 {
3106 DeleteSelectedContent();
3107 }
3108}
3109
3110bool wxRichTextCtrl::HasSelection() const
3111{
603f702b
JS
3112 return (m_selection.IsValid() && m_selection.GetContainer() == GetFocusObject());
3113}
3114
3115bool wxRichTextCtrl::HasUnfocusedSelection() const
3116{
3117 return m_selection.IsValid();
5d7836c4
JS
3118}
3119
3120bool wxRichTextCtrl::CanCopy() const
3121{
3122 // Can copy if there's a selection
3123 return HasSelection();
3124}
3125
3126bool wxRichTextCtrl::CanCut() const
3127{
cc2aecde 3128 return CanDeleteSelection();
5d7836c4
JS
3129}
3130
3131bool wxRichTextCtrl::CanPaste() const
3132{
cc2aecde 3133 if ( !IsEditable() || !GetFocusObject() || !CanInsertContent(* GetFocusObject(), m_caretPosition+1))
5d7836c4
JS
3134 return false;
3135
3136 return GetBuffer().CanPasteFromClipboard();
3137}
3138
3139bool wxRichTextCtrl::CanDeleteSelection() const
3140{
cc2aecde 3141 return HasSelection() && IsEditable() && CanDeleteRange(* GetFocusObject(), GetSelectionRange());
5d7836c4
JS
3142}
3143
3144
3145// ----------------------------------------------------------------------------
3146// Accessors
3147// ----------------------------------------------------------------------------
3148
8e43fc77
JS
3149void wxRichTextCtrl::SetContextMenu(wxMenu* menu)
3150{
3151 if (m_contextMenu && m_contextMenu != menu)
3152 delete m_contextMenu;
3153 m_contextMenu = menu;
3154}
3155
5d7836c4
JS
3156void wxRichTextCtrl::SetEditable(bool editable)
3157{
3158 m_editable = editable;
3159}
3160
3161void wxRichTextCtrl::SetInsertionPoint(long pos)
3162{
3163 SelectNone();
3164
3165 m_caretPosition = pos - 1;
04b2b47a 3166 m_caretAtLineStart = true;
6f5d63bc
JS
3167
3168 PositionCaret();
4427f297
JS
3169
3170 SetDefaultStyleToCursorStyle();
5d7836c4
JS
3171}
3172
3173void wxRichTextCtrl::SetInsertionPointEnd()
3174{
3175 long pos = GetLastPosition();
3176 SetInsertionPoint(pos);
3177}
3178
3179long wxRichTextCtrl::GetInsertionPoint() const
3180{
3181 return m_caretPosition+1;
3182}
3183
3184wxTextPos wxRichTextCtrl::GetLastPosition() const
3185{
603f702b 3186 return GetFocusObject()->GetOwnRange().GetEnd();
5d7836c4
JS
3187}
3188
3189// If the return values from and to are the same, there is no
3190// selection.
3191void wxRichTextCtrl::GetSelection(long* from, long* to) const
3192{
603f702b
JS
3193 if (m_selection.IsValid())
3194 {
3195 *from = m_selection.GetRange().GetStart();
3196 *to = m_selection.GetRange().GetEnd();
96c9f0f6 3197 (*to) ++;
603f702b
JS
3198 }
3199 else
3200 {
3201 *from = -2;
3202 *to = -2;
3203 }
5d7836c4
JS
3204}
3205
3206bool wxRichTextCtrl::IsEditable() const
3207{
3208 return m_editable;
3209}
3210
3211// ----------------------------------------------------------------------------
3212// selection
3213// ----------------------------------------------------------------------------
3214
3215void wxRichTextCtrl::SetSelection(long from, long to)
3216{
3217 // if from and to are both -1, it means (in wxWidgets) that all text should
3218 // be selected.
3219 if ( (from == -1) && (to == -1) )
3220 {
3221 from = 0;
96c9f0f6 3222 to = GetLastPosition()+1;
5d7836c4
JS
3223 }
3224
c1aec196
JS
3225 if (from == to)
3226 {
3227 SelectNone();
3228 }
3229 else
3230 {
603f702b
JS
3231 wxRichTextSelection oldSelection = m_selection;
3232
205a1ad9 3233 m_selectionAnchor = from-1;
603f702b
JS
3234 m_selectionAnchorObject = NULL;
3235 m_selection.Set(wxRichTextRange(from, to-1), GetFocusObject());
76d7fc29 3236
a216dfa2 3237 m_caretPosition = wxMax(-1, to-1);
0ca07313 3238
603f702b 3239 RefreshForSelectionChange(oldSelection, m_selection);
c1aec196
JS
3240 PositionCaret();
3241 }
5d7836c4
JS
3242}
3243
3244// ----------------------------------------------------------------------------
3245// Editing
3246// ----------------------------------------------------------------------------
3247
e3bb4c54 3248void wxRichTextCtrl::Replace(long from, long to,
343ae70d 3249 const wxString& value)
5d7836c4
JS
3250{
3251 BeginBatchUndo(_("Replace"));
3252
e3bb4c54
JS
3253 SetSelection(from, to);
3254
3255 wxRichTextAttr attr = GetDefaultStyle();
3256
5d7836c4
JS
3257 DeleteSelectedContent();
3258
e3bb4c54
JS
3259 SetDefaultStyle(attr);
3260
4aa079bf
JS
3261 if (!value.IsEmpty())
3262 DoWriteText(value, SetValue_SelectionOnly);
5d7836c4
JS
3263
3264 EndBatchUndo();
3265}
3266
3267void wxRichTextCtrl::Remove(long from, long to)
3268{
3269 SelectNone();
3270
603f702b 3271 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(from, to-1), this, & GetBuffer());
5d7836c4 3272
2f36e8dc 3273 LayoutContent();
5d7836c4 3274 if (!IsFrozen())
76bcd815 3275 Refresh(false);
5d7836c4
JS
3276}
3277
3278bool wxRichTextCtrl::IsModified() const
3279{
3280 return m_buffer.IsModified();
3281}
3282
3283void wxRichTextCtrl::MarkDirty()
3284{
3285 m_buffer.Modify(true);
3286}
3287
3288void wxRichTextCtrl::DiscardEdits()
3289{
ab14c7aa 3290 m_caretPositionForDefaultStyle = -2;
5d7836c4
JS
3291 m_buffer.Modify(false);
3292 m_buffer.GetCommandProcessor()->ClearCommands();
3293}
3294
3295int wxRichTextCtrl::GetNumberOfLines() const
3296{
603f702b 3297 return GetFocusObject()->GetParagraphCount();
5d7836c4
JS
3298}
3299
3300// ----------------------------------------------------------------------------
3301// Positions <-> coords
3302// ----------------------------------------------------------------------------
3303
3304long wxRichTextCtrl::XYToPosition(long x, long y) const
3305{
603f702b 3306 return GetFocusObject()->XYToPosition(x, y);
5d7836c4
JS
3307}
3308
3309bool wxRichTextCtrl::PositionToXY(long pos, long *x, long *y) const
3310{
603f702b 3311 return GetFocusObject()->PositionToXY(pos, x, y);
5d7836c4
JS
3312}
3313
3314// ----------------------------------------------------------------------------
3315//
3316// ----------------------------------------------------------------------------
3317
3318void wxRichTextCtrl::ShowPosition(long pos)
3319{
3320 if (!IsPositionVisible(pos))
3321 ScrollIntoView(pos-1, WXK_DOWN);
3322}
3323
3324int wxRichTextCtrl::GetLineLength(long lineNo) const
3325{
603f702b 3326 return GetFocusObject()->GetParagraphLength(lineNo);
5d7836c4
JS
3327}
3328
3329wxString wxRichTextCtrl::GetLineText(long lineNo) const
3330{
603f702b 3331 return GetFocusObject()->GetParagraphText(lineNo);
5d7836c4
JS
3332}
3333
3334// ----------------------------------------------------------------------------
3335// Undo/redo
3336// ----------------------------------------------------------------------------
3337
3338void wxRichTextCtrl::Undo()
3339{
3340 if (CanUndo())
3341 {
3342 GetCommandProcessor()->Undo();
3343 }
3344}
3345
3346void wxRichTextCtrl::Redo()
3347{
3348 if (CanRedo())
3349 {
3350 GetCommandProcessor()->Redo();
3351 }
3352}
3353
3354bool wxRichTextCtrl::CanUndo() const
3355{
3a4a38c1 3356 return GetCommandProcessor()->CanUndo() && IsEditable();
5d7836c4
JS
3357}
3358
3359bool wxRichTextCtrl::CanRedo() const
3360{
3a4a38c1 3361 return GetCommandProcessor()->CanRedo() && IsEditable();
5d7836c4
JS
3362}
3363
3364// ----------------------------------------------------------------------------
563d25ba 3365// implementation details
5d7836c4
JS
3366// ----------------------------------------------------------------------------
3367
563d25ba 3368void wxRichTextCtrl::Command(wxCommandEvent& event)
5d7836c4
JS
3369{
3370 SetValue(event.GetString());
3371 GetEventHandler()->ProcessEvent(event);
3372}
3373
3374void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent& event)
3375{
3376 // By default, load the first file into the text window.
3377 if (event.GetNumberOfFiles() > 0)
3378 {
3379 LoadFile(event.GetFiles()[0]);
3380 }
3381}
3382
5d7836c4
JS
3383wxSize wxRichTextCtrl::DoGetBestSize() const
3384{
3385 return wxSize(10, 10);
3386}
3387
3388// ----------------------------------------------------------------------------
3389// standard handlers for standard edit menu events
3390// ----------------------------------------------------------------------------
3391
3392void wxRichTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
3393{
3394 Cut();
3395}
3396
3397void wxRichTextCtrl::OnClear(wxCommandEvent& WXUNUSED(event))
3398{
3399 DeleteSelection();
3400}
3401
3402void wxRichTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
3403{
3404 Copy();
3405}
3406
3407void wxRichTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
3408{
3409 Paste();
3410}
3411
3412void wxRichTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
3413{
3414 Undo();
3415}
3416
3417void wxRichTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
3418{
3419 Redo();
3420}
3421
3422void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
3423{
3424 event.Enable( CanCut() );
3425}
3426
3427void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
3428{
3429 event.Enable( CanCopy() );
3430}
3431
3432void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent& event)
3433{
3434 event.Enable( CanDeleteSelection() );
3435}
3436
3437void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
3438{
3439 event.Enable( CanPaste() );
3440}
3441
3442void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
3443{
3444 event.Enable( CanUndo() );
3445 event.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
3446}
3447
3448void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
3449{
3450 event.Enable( CanRedo() );
3451 event.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
3452}
3453
3454void wxRichTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
3455{
b30661fd
JS
3456 if (GetLastPosition() > 0)
3457 SelectAll();
5d7836c4
JS
3458}
3459
3460void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
3461{
b30661fd 3462 event.Enable(GetLastPosition() > 0);
5d7836c4
JS
3463}
3464
603f702b 3465void wxRichTextCtrl::OnProperties(wxCommandEvent& event)
cdaed652 3466{
603f702b
JS
3467 int idx = event.GetId() - wxID_RICHTEXT_PROPERTIES1;
3468 if (idx >= 0 && idx < m_contextMenuPropertiesInfo.GetCount())
3469 {
3470 wxRichTextObject* obj = m_contextMenuPropertiesInfo.GetObject(idx);
303f0be7
JS
3471 if (obj && CanEditProperties(obj))
3472 EditProperties(obj, this);
603f702b
JS
3473
3474 m_contextMenuPropertiesInfo.Clear();
3475 }
cdaed652
VZ
3476}
3477
603f702b 3478void wxRichTextCtrl::OnUpdateProperties(wxUpdateUIEvent& event)
cdaed652 3479{
603f702b
JS
3480 int idx = event.GetId() - wxID_RICHTEXT_PROPERTIES1;
3481 event.Enable(idx >= 0 && idx < m_contextMenuPropertiesInfo.GetCount());
cdaed652
VZ
3482}
3483
b4ae0def 3484void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent& event)
5d7836c4 3485{
b4ae0def
JS
3486 if (event.GetEventObject() != this)
3487 {
3488 event.Skip();
3489 return;
3490 }
3491
9b794421
JS
3492 ShowContextMenu(m_contextMenu, event.GetPosition());
3493}
3494
3495// Prepares the context menu, adding appropriate property-editing commands.
3496// Returns the number of property commands added.
3497int wxRichTextCtrl::PrepareContextMenu(wxMenu* menu, const wxPoint& pt, bool addPropertyCommands)
3498{
cdaed652
VZ
3499 wxClientDC dc(this);
3500 PrepareDC(dc);
3501 dc.SetFont(GetFont());
3502
9b794421
JS
3503 m_contextMenuPropertiesInfo.Clear();
3504
cdaed652 3505 long position = 0;
603f702b
JS
3506 wxRichTextObject* hitObj = NULL;
3507 wxRichTextObject* contextObj = NULL;
9b794421
JS
3508 if (pt != wxDefaultPosition)
3509 {
3510 wxPoint logicalPt = GetLogicalPoint(ScreenToClient(pt));
8db2e3ef 3511 wxRichTextDrawingContext context(& GetBuffer());
4ba36292 3512 int hit = GetBuffer().HitTest(dc, context, GetUnscaledPoint(logicalPt), position, & hitObj, & contextObj);
4fe83b93 3513
9b794421
JS
3514 if (hit == wxRICHTEXT_HITTEST_ON || hit == wxRICHTEXT_HITTEST_BEFORE || hit == wxRICHTEXT_HITTEST_AFTER)
3515 {
3516 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
3517 if (hitObj && actualContainer)
3518 {
3519 if (actualContainer->AcceptsFocus())
3520 {
3521 SetFocusObject(actualContainer, false /* don't set caret position yet */);
3522 SetCaretPositionAfterClick(actualContainer, position, hit);
3523 }
4fe83b93 3524
9b794421 3525 if (addPropertyCommands)
303f0be7 3526 m_contextMenuPropertiesInfo.AddItems(this, actualContainer, hitObj);
9b794421
JS
3527 }
3528 else
3529 {
3530 if (addPropertyCommands)
303f0be7 3531 m_contextMenuPropertiesInfo.AddItems(this, GetFocusObject(), NULL);
9b794421
JS
3532 }
3533 }
3534 else
3535 {
3536 if (addPropertyCommands)
303f0be7 3537 m_contextMenuPropertiesInfo.AddItems(this, GetFocusObject(), NULL);
9b794421
JS
3538 }
3539 }
3540 else
cdaed652 3541 {
9b794421
JS
3542 // Invoked from the keyboard, so don't set the caret position and don't use the event
3543 // position
3544 hitObj = GetFocusObject()->GetLeafObjectAtPosition(m_caretPosition+1);
3545 if (hitObj)
3546 contextObj = hitObj->GetParentContainer();
3547 else
3548 contextObj = GetFocusObject();
3549
603f702b
JS
3550 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
3551 if (hitObj && actualContainer)
3552 {
9b794421 3553 if (addPropertyCommands)
303f0be7 3554 m_contextMenuPropertiesInfo.AddItems(this, actualContainer, hitObj);
603f702b
JS
3555 }
3556 else
9b794421
JS
3557 {
3558 if (addPropertyCommands)
303f0be7 3559 m_contextMenuPropertiesInfo.AddItems(this, GetFocusObject(), NULL);
9b794421 3560 }
cdaed652 3561 }
9b794421
JS
3562
3563 if (menu)
cdaed652 3564 {
9b794421
JS
3565 if (addPropertyCommands)
3566 m_contextMenuPropertiesInfo.AddMenuItems(menu);
3567 return m_contextMenuPropertiesInfo.GetCount();
cdaed652 3568 }
9b794421
JS
3569 else
3570 return 0;
3571}
cdaed652 3572
9b794421
JS
3573// Shows the context menu, adding appropriate property-editing commands
3574bool wxRichTextCtrl::ShowContextMenu(wxMenu* menu, const wxPoint& pt, bool addPropertyCommands)
3575{
3576 if (menu)
603f702b 3577 {
9b794421
JS
3578 PrepareContextMenu(menu, pt, addPropertyCommands);
3579 PopupMenu(menu);
3580 return true;
603f702b 3581 }
9b794421
JS
3582 else
3583 return false;
5d7836c4
JS
3584}
3585
27e20452
JS
3586bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
3587{
603f702b 3588 return GetFocusObject()->SetStyle(wxRichTextRange(start, end-1), wxRichTextAttr(style));
24777478
JS
3589}
3590
3591bool wxRichTextCtrl::SetStyle(long start, long end, const wxRichTextAttr& style)
3592{
603f702b 3593 return GetFocusObject()->SetStyle(wxRichTextRange(start, end-1), style);
27e20452
JS
3594}
3595
44cc96a8 3596bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxTextAttr& style)
24777478 3597{
603f702b 3598 return GetFocusObject()->SetStyle(range.ToInternal(), wxRichTextAttr(style));
24777478
JS
3599}
3600
3601bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style)
5d7836c4 3602{
603f702b 3603 return GetFocusObject()->SetStyle(range.ToInternal(), style);
5d7836c4
JS
3604}
3605
e059e1bb 3606void wxRichTextCtrl::SetStyle(wxRichTextObject *obj, const wxRichTextAttr& textAttr, int flags)
cdaed652 3607{
e059e1bb 3608 GetFocusObject()->SetStyle(obj, textAttr, flags);
cdaed652
VZ
3609}
3610
3e3a754f
JS
3611// extended style setting operation with flags including:
3612// wxRICHTEXT_SETSTYLE_WITH_UNDO, wxRICHTEXT_SETSTYLE_OPTIMIZE, wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY.
3613// see richtextbuffer.h for more details.
3e3a754f 3614
24777478 3615bool wxRichTextCtrl::SetStyleEx(const wxRichTextRange& range, const wxRichTextAttr& style, int flags)
3e3a754f 3616{
603f702b 3617 return GetFocusObject()->SetStyle(range.ToInternal(), style, flags);
3e3a754f
JS
3618}
3619
27e20452
JS
3620bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr& style)
3621{
24777478 3622 return GetBuffer().SetDefaultStyle(style);
5d7836c4
JS
3623}
3624
24777478
JS
3625bool wxRichTextCtrl::SetDefaultStyle(const wxRichTextAttr& style)
3626{
603f702b
JS
3627 wxRichTextAttr attr1(style);
3628 attr1.GetTextBoxAttr().Reset();
3629 return GetBuffer().SetDefaultStyle(attr1);
24777478
JS
3630}
3631
3632const wxRichTextAttr& wxRichTextCtrl::GetDefaultStyleEx() const
27e20452 3633{
61399247 3634 return GetBuffer().GetDefaultStyle();
27e20452
JS
3635}
3636
3966a9f4 3637bool wxRichTextCtrl::GetStyle(long position, wxTextAttr& style)
24777478
JS
3638{
3639 wxRichTextAttr attr;
603f702b 3640 if (GetFocusObject()->GetStyle(position, attr))
24777478
JS
3641 {
3642 style = attr;
3643 return true;
3644 }
3645 else
3646 return false;
3647}
3648
3649bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style)
5d7836c4 3650{
603f702b
JS
3651 return GetFocusObject()->GetStyle(position, style);
3652}
3653
3654bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3655{
3656 wxRichTextAttr attr;
3657 if (container->GetStyle(position, attr))
3658 {
3659 style = attr;
3660 return true;
3661 }
3662 else
3663 return false;
5d7836c4
JS
3664}
3665
a7ed48a5 3666// get the common set of styles for the range
44cc96a8 3667bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxTextAttr& style)
24777478
JS
3668{
3669 wxRichTextAttr attr;
603f702b 3670 if (GetFocusObject()->GetStyleForRange(range.ToInternal(), attr))
24777478
JS
3671 {
3672 style = attr;
3673 return true;
3674 }
3675 else
3676 return false;
3677}
3678
3679bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style)
a7ed48a5 3680{
603f702b
JS
3681 return GetFocusObject()->GetStyleForRange(range.ToInternal(), style);
3682}
3683
3684bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3685{
3686 return container->GetStyleForRange(range.ToInternal(), style);
a7ed48a5
JS
3687}
3688
fe5aa22c 3689/// Get the content (uncombined) attributes for this position.
24777478 3690bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style)
fe5aa22c 3691{
603f702b
JS
3692 return GetFocusObject()->GetUncombinedStyle(position, style);
3693}
3694
3695/// Get the content (uncombined) attributes for this position.
3696bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3697{
3698 return container->GetUncombinedStyle(position, style);
fe5aa22c
JS
3699}
3700
590a0f8b
JS
3701bool wxRichTextCtrl::SetProperties(const wxRichTextRange& range, const wxRichTextProperties& properties, int flags)
3702{
3703 return GetFocusObject()->SetProperties(range.ToInternal(), properties, flags);
3704}
3705
5d7836c4
JS
3706/// Set font, and also the buffer attributes
3707bool wxRichTextCtrl::SetFont(const wxFont& font)
3708{
24777478 3709 wxControl::SetFont(font);
5d7836c4 3710
24777478 3711 wxRichTextAttr attr = GetBuffer().GetAttributes();
5d7836c4
JS
3712 attr.SetFont(font);
3713 GetBuffer().SetBasicStyle(attr);
fe5aa22c 3714
fe5aa22c
JS
3715 GetBuffer().Invalidate(wxRICHTEXT_ALL);
3716 Refresh(false);
5d7836c4
JS
3717
3718 return true;
3719}
3720
4d551ad5
JS
3721/// Transform logical to physical
3722wxPoint wxRichTextCtrl::GetPhysicalPoint(const wxPoint& ptLogical) const
5d7836c4
JS
3723{
3724 wxPoint pt;
3725 CalcScrolledPosition(ptLogical.x, ptLogical.y, & pt.x, & pt.y);
3726
3727 return pt;
3728}
3729
3730/// Transform physical to logical
4d551ad5 3731wxPoint wxRichTextCtrl::GetLogicalPoint(const wxPoint& ptPhysical) const
5d7836c4
JS
3732{
3733 wxPoint pt;
3734 CalcUnscrolledPosition(ptPhysical.x, ptPhysical.y, & pt.x, & pt.y);
3735
3736 return pt;
3737}
3738
3739/// Position the caret
603f702b 3740void wxRichTextCtrl::PositionCaret(wxRichTextParagraphLayoutBox* container)
5d7836c4 3741{
c59f6793
JS
3742 if (!GetCaret())
3743 return;
3744
3745 //wxLogDebug(wxT("PositionCaret"));
3746
5d7836c4 3747 wxRect caretRect;
603f702b 3748 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect, container))
5d7836c4 3749 {
4ba36292
JS
3750 caretRect = GetScaledRect(caretRect);
3751 int topMargin = (int) (0.5 + GetScale()*GetBuffer().GetTopMargin());
3752 int bottomMargin = (int) (0.5 + GetScale()*GetBuffer().GetBottomMargin());
7e4fe193
JS
3753 wxPoint newPt = caretRect.GetPosition();
3754 wxSize newSz = caretRect.GetSize();
3755 wxPoint pt = GetPhysicalPoint(newPt);
3756 if (GetCaret()->GetPosition() != pt || GetCaret()->GetSize() != newSz)
c59f6793 3757 {
1c13f06e
JS
3758 GetCaret()->Hide();
3759 if (GetCaret()->GetSize() != newSz)
3760 GetCaret()->SetSize(newSz);
e9f10004 3761
423b9ba5 3762 // Adjust size so the caret size and position doesn't appear in the margins
4ba36292 3763 if (((pt.y + newSz.y) <= topMargin) || (pt.y >= (GetClientSize().y - bottomMargin)))
603f702b
JS
3764 {
3765 pt.x = -200;
e9f10004 3766 pt.y = -200;
603f702b 3767 }
4ba36292 3768 else if (pt.y < topMargin && (pt.y + newSz.y) > topMargin)
423b9ba5 3769 {
4ba36292 3770 newSz.y -= (topMargin - pt.y);
423b9ba5
JS
3771 if (newSz.y > 0)
3772 {
4ba36292 3773 pt.y = topMargin;
423b9ba5
JS
3774 GetCaret()->SetSize(newSz);
3775 }
3776 }
4ba36292 3777 else if (pt.y < (GetClientSize().y - bottomMargin) && (pt.y + newSz.y) > (GetClientSize().y - bottomMargin))
423b9ba5 3778 {
4ba36292 3779 newSz.y = GetClientSize().y - bottomMargin - pt.y;
423b9ba5
JS
3780 GetCaret()->SetSize(newSz);
3781 }
e9f10004 3782
c59f6793 3783 GetCaret()->Move(pt);
1c13f06e 3784 GetCaret()->Show();
c59f6793 3785 }
5d7836c4
JS
3786 }
3787}
3788
3789/// Get the caret height and position for the given character position
603f702b 3790bool wxRichTextCtrl::GetCaretPositionForIndex(long position, wxRect& rect, wxRichTextParagraphLayoutBox* container)
5d7836c4
JS
3791{
3792 wxClientDC dc(this);
5d7836c4 3793 PrepareDC(dc);
4ba36292
JS
3794 dc.SetUserScale(GetScale(), GetScale());
3795 dc.SetFont(GetFont());
5d7836c4
JS
3796
3797 wxPoint pt;
3798 int height = 0;
4fe83b93 3799
603f702b
JS
3800 if (!container)
3801 container = GetFocusObject();
5d7836c4 3802
8db2e3ef
JS
3803 wxRichTextDrawingContext context(& GetBuffer());
3804 if (container->FindPosition(dc, context, position, pt, & height, m_caretAtLineStart))
5d7836c4 3805 {
88bee7e6
JS
3806 // Caret height can't be zero
3807 if (height == 0)
3808 height = dc.GetCharHeight();
3809
5d7836c4
JS
3810 rect = wxRect(pt, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH, height));
3811 return true;
3812 }
41e155b4
WS
3813
3814 return false;
5d7836c4
JS
3815}
3816
3817/// Gets the line for the visible caret position. If the caret is
3818/// shown at the very end of the line, it means the next character is actually
3819/// on the following line. So let's get the line we're expecting to find
3820/// if this is the case.
3821wxRichTextLine* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition) const
3822{
603f702b
JS
3823 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(caretPosition, true);
3824 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(caretPosition, true);
5d7836c4
JS
3825 if (line)
3826 {
1e967276
JS
3827 wxRichTextRange lineRange = line->GetAbsoluteRange();
3828 if (caretPosition == lineRange.GetStart()-1 &&
3829 (para->GetRange().GetStart() != lineRange.GetStart()))
5d7836c4
JS
3830 {
3831 if (!m_caretAtLineStart)
603f702b 3832 line = GetFocusObject()->GetLineAtPosition(caretPosition-1, true);
5d7836c4
JS
3833 }
3834 }
3835 return line;
3836}
3837
3838
3839/// Move the caret to the given character position
603f702b 3840bool wxRichTextCtrl::MoveCaret(long pos, bool showAtLineStart, wxRichTextParagraphLayoutBox* container)
5d7836c4 3841{
603f702b 3842 if (GetBuffer().IsDirty())
2f36e8dc 3843 LayoutContent();
5d7836c4 3844
603f702b
JS
3845 if (!container)
3846 container = GetFocusObject();
3847
3848 if (pos <= container->GetOwnRange().GetEnd())
5d7836c4
JS
3849 {
3850 SetCaretPosition(pos, showAtLineStart);
3851
603f702b 3852 PositionCaret(container);
5d7836c4
JS
3853
3854 return true;
3855 }
3856 else
3857 return false;
3858}
3859
3860/// Layout the buffer: which we must do before certain operations, such as
3861/// setting the caret position.
2f36e8dc 3862bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect)
5d7836c4 3863{
603f702b 3864 if (GetBuffer().IsDirty() || onlyVisibleRect)
1e967276 3865 {
4ba36292 3866 wxRect availableSpace(GetUnscaledSize(GetClientSize()));
1e967276
JS
3867 if (availableSpace.width == 0)
3868 availableSpace.width = 10;
3869 if (availableSpace.height == 0)
3870 availableSpace.height = 10;
4d551ad5
JS
3871
3872 int flags = wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT;
3873 if (onlyVisibleRect)
3874 {
3875 flags |= wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
4ba36292 3876 availableSpace.SetPosition(GetUnscaledPoint(GetLogicalPoint(wxPoint(0, 0))));
4d551ad5 3877 }
41e155b4 3878
1e967276 3879 wxClientDC dc(this);
41e155b4 3880
1e967276 3881 PrepareDC(dc);
4ba36292 3882 dc.SetFont(GetFont());
41e155b4 3883
8db2e3ef 3884 wxRichTextDrawingContext context(& GetBuffer());
1e967276
JS
3885 GetBuffer().Defragment();
3886 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
8db2e3ef 3887 GetBuffer().Layout(dc, context, availableSpace, availableSpace, flags);
603f702b 3888 GetBuffer().Invalidate(wxRICHTEXT_NONE);
41e155b4 3889
5a0259e6 3890 if (!IsFrozen() && !onlyVisibleRect)
1e967276
JS
3891 SetupScrollbars();
3892 }
5d7836c4
JS
3893
3894 return true;
3895}
3896
75936ec6 3897/// Is all of the selection, or the current caret position, bold?
3966a9f4 3898bool wxRichTextCtrl::IsSelectionBold()
5d7836c4
JS
3899{
3900 if (HasSelection())
3901 {
24777478 3902 wxRichTextAttr attr;
a7ed48a5 3903 wxRichTextRange range = GetSelectionRange();
5d7836c4 3904 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
7d76fbd5 3905 attr.SetFontWeight(wxFONTWEIGHT_BOLD);
7fe8059f 3906
5d7836c4
JS
3907 return HasCharacterAttributes(range, attr);
3908 }
3909 else
3910 {
3911 // If no selection, then we need to combine current style with default style
3912 // to see what the effect would be if we started typing.
24777478 3913 wxRichTextAttr attr;
5d7836c4 3914 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
ab14c7aa
JS
3915
3916 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3917 if (GetStyle(pos, attr))
5d7836c4 3918 {
ab14c7aa
JS
3919 if (IsDefaultStyleShowing())
3920 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
7d76fbd5 3921 return attr.GetFontWeight() == wxFONTWEIGHT_BOLD;
5d7836c4
JS
3922 }
3923 }
3924 return false;
3925}
3926
75936ec6 3927/// Is all of the selection, or the current caret position, italics?
3966a9f4 3928bool wxRichTextCtrl::IsSelectionItalics()
5d7836c4
JS
3929{
3930 if (HasSelection())
3931 {
a7ed48a5 3932 wxRichTextRange range = GetSelectionRange();
24777478 3933 wxRichTextAttr attr;
5d7836c4 3934 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
7d76fbd5 3935 attr.SetFontStyle(wxFONTSTYLE_ITALIC);
7fe8059f 3936
5d7836c4
JS
3937 return HasCharacterAttributes(range, attr);
3938 }
3939 else
3940 {
3941 // If no selection, then we need to combine current style with default style
3942 // to see what the effect would be if we started typing.
24777478 3943 wxRichTextAttr attr;
5d7836c4 3944 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
ab14c7aa
JS
3945
3946 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3947 if (GetStyle(pos, attr))
5d7836c4 3948 {
ab14c7aa
JS
3949 if (IsDefaultStyleShowing())
3950 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
7d76fbd5 3951 return attr.GetFontStyle() == wxFONTSTYLE_ITALIC;
5d7836c4
JS
3952 }
3953 }
3954 return false;
3955}
3956
75936ec6 3957/// Is all of the selection, or the current caret position, underlined?
3966a9f4 3958bool wxRichTextCtrl::IsSelectionUnderlined()
5d7836c4
JS
3959{
3960 if (HasSelection())
3961 {
a7ed48a5 3962 wxRichTextRange range = GetSelectionRange();
24777478 3963 wxRichTextAttr attr;
5d7836c4
JS
3964 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
3965 attr.SetFontUnderlined(true);
7fe8059f 3966
5d7836c4
JS
3967 return HasCharacterAttributes(range, attr);
3968 }
3969 else
3970 {
3971 // If no selection, then we need to combine current style with default style
3972 // to see what the effect would be if we started typing.
24777478 3973 wxRichTextAttr attr;
5d7836c4 3974 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
ab14c7aa 3975 long pos = GetAdjustedCaretPosition(GetCaretPosition());
fe5aa22c 3976
ab14c7aa 3977 if (GetStyle(pos, attr))
5d7836c4 3978 {
ab14c7aa
JS
3979 if (IsDefaultStyleShowing())
3980 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
5d7836c4
JS
3981 return attr.GetFontUnderlined();
3982 }
3983 }
3984 return false;
3985}
3986
75936ec6
JS
3987/// Does all of the selection, or the current caret position, have this wxTextAttrEffects flag(s)?
3988bool wxRichTextCtrl::DoesSelectionHaveTextEffectFlag(int flag)
3989{
3990 wxRichTextAttr attr;
3991 attr.SetFlags(wxTEXT_ATTR_EFFECTS);
3992 attr.SetTextEffectFlags(flag);
3993 attr.SetTextEffects(flag);
3994
3995 if (HasSelection())
3996 {
3997 return HasCharacterAttributes(GetSelectionRange(), attr);
3998 }
3999 else
4000 {
4001 // If no selection, then we need to combine current style with default style
4002 // to see what the effect would be if we started typing.
4003 long pos = GetAdjustedCaretPosition(GetCaretPosition());
4004 if (GetStyle(pos, attr))
4005 {
4006 if (IsDefaultStyleShowing())
4007 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
dabf7342 4008 return (attr.GetTextEffectFlags() & flag) != 0;
75936ec6
JS
4009 }
4010 }
4011 return false;
4012}
4013
5d7836c4
JS
4014/// Apply bold to the selection
4015bool wxRichTextCtrl::ApplyBoldToSelection()
4016{
24777478 4017 wxRichTextAttr attr;
5d7836c4 4018 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
7d76fbd5 4019 attr.SetFontWeight(IsSelectionBold() ? wxFONTWEIGHT_NORMAL : wxFONTWEIGHT_BOLD);
5d7836c4
JS
4020
4021 if (HasSelection())
3e3a754f 4022 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
5d7836c4 4023 else
063dbace
JS
4024 {
4025 wxRichTextAttr current = GetDefaultStyleEx();
4026 current.Apply(attr);
4027 SetAndShowDefaultStyle(current);
4028 }
5d7836c4
JS
4029 return true;
4030}
4031
4032/// Apply italic to the selection
4033bool wxRichTextCtrl::ApplyItalicToSelection()
4034{
24777478 4035 wxRichTextAttr attr;
5d7836c4 4036 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
7d76fbd5 4037 attr.SetFontStyle(IsSelectionItalics() ? wxFONTSTYLE_NORMAL : wxFONTSTYLE_ITALIC);
5d7836c4
JS
4038
4039 if (HasSelection())
3e3a754f 4040 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
5d7836c4 4041 else
063dbace
JS
4042 {
4043 wxRichTextAttr current = GetDefaultStyleEx();
4044 current.Apply(attr);
4045 SetAndShowDefaultStyle(current);
4046 }
5d7836c4
JS
4047 return true;
4048}
4049
4050/// Apply underline to the selection
4051bool wxRichTextCtrl::ApplyUnderlineToSelection()
4052{
24777478 4053 wxRichTextAttr attr;
5d7836c4 4054 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
4d551ad5 4055 attr.SetFontUnderlined(!IsSelectionUnderlined());
5d7836c4 4056
75936ec6
JS
4057 if (HasSelection())
4058 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
4059 else
4060 {
4061 wxRichTextAttr current = GetDefaultStyleEx();
4062 current.Apply(attr);
4063 SetAndShowDefaultStyle(current);
4064 }
4065 return true;
4066}
4067
4068/// Apply the wxTextAttrEffects flag(s) to the selection, or the current caret position if there's no selection
4069bool wxRichTextCtrl::ApplyTextEffectToSelection(int flags)
4070{
4071 wxRichTextAttr attr;
4072 attr.SetFlags(wxTEXT_ATTR_EFFECTS);
4073 attr.SetTextEffectFlags(flags);
4074 if (!DoesSelectionHaveTextEffectFlag(flags))
4075 attr.SetTextEffects(flags);
4076 else
4077 attr.SetTextEffects(attr.GetTextEffectFlags() & ~flags);
4078
5d7836c4 4079 if (HasSelection())
3e3a754f 4080 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
5d7836c4 4081 else
063dbace
JS
4082 {
4083 wxRichTextAttr current = GetDefaultStyleEx();
4084 current.Apply(attr);
4085 SetAndShowDefaultStyle(current);
4086 }
5d7836c4
JS
4087 return true;
4088}
4089
4090/// Is all of the selection aligned according to the specified flag?
3966a9f4 4091bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment)
5d7836c4 4092{
0ca07313 4093 wxRichTextRange range;
5d7836c4 4094 if (HasSelection())
a7ed48a5 4095 range = GetSelectionRange();
5d7836c4 4096 else
a7ed48a5 4097 range = wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+2);
0ca07313 4098
24777478 4099 wxRichTextAttr attr;
0ca07313
JS
4100 attr.SetAlignment(alignment);
4101
4102 return HasParagraphAttributes(range, attr);
5d7836c4
JS
4103}
4104
4105/// Apply alignment to the selection
4106bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment)
4107{
24777478 4108 wxRichTextAttr attr;
5d7836c4
JS
4109 attr.SetAlignment(alignment);
4110 if (HasSelection())
4111 return SetStyle(GetSelectionRange(), attr);
4112 else
4113 {
603f702b 4114 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(GetCaretPosition()+1);
5d7836c4 4115 if (para)
3e3a754f 4116 return SetStyleEx(para->GetRange().FromInternal(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY);
5d7836c4
JS
4117 }
4118 return true;
4119}
4120
ab14c7aa 4121/// Apply a named style to the selection
1807a1f3 4122bool wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition* def)
ab14c7aa
JS
4123{
4124 // Flags are defined within each definition, so only certain
4125 // attributes are applied.
24777478 4126 wxRichTextAttr attr(GetStyleSheet() ? def->GetStyleMergedWithBase(GetStyleSheet()) : def->GetStyle());
1807a1f3 4127
f2ab7bf3 4128 int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_RESET;
ab14c7aa 4129
345c78ca 4130 if (wxDynamicCast(def, wxRichTextListStyleDefinition))
38f833b1
JS
4131 {
4132 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
41a85215 4133
38f833b1 4134 wxRichTextRange range;
41a85215 4135
38f833b1
JS
4136 if (HasSelection())
4137 range = GetSelectionRange();
4138 else
4139 {
41a85215 4140 long pos = GetAdjustedCaretPosition(GetCaretPosition());
38f833b1
JS
4141 range = wxRichTextRange(pos, pos+1);
4142 }
41a85215
WS
4143
4144 return SetListStyle(range, (wxRichTextListStyleDefinition*) def, flags);
4145 }
4146
edae63b0
JS
4147 bool isPara = false;
4148
ab14c7aa 4149 // Make sure the attr has the style name
345c78ca 4150 if (wxDynamicCast(def, wxRichTextParagraphStyleDefinition))
3e3a754f 4151 {
edae63b0 4152 isPara = true;
ab14c7aa 4153 attr.SetParagraphStyleName(def->GetName());
1807a1f3 4154
3e3a754f 4155 // If applying a paragraph style, we only want the paragraph nodes to adopt these
38f833b1 4156 // attributes, and not the leaf nodes. This will allow the content (e.g. text)
3e3a754f
JS
4157 // to change its style independently.
4158 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
4159 }
345c78ca 4160 else if (wxDynamicCast(def, wxRichTextCharacterStyleDefinition))
ab14c7aa 4161 attr.SetCharacterStyleName(def->GetName());
345c78ca 4162 else if (wxDynamicCast(def, wxRichTextBoxStyleDefinition))
b9433288 4163 attr.GetTextBoxAttr().SetBoxStyleName(def->GetName());
ab14c7aa 4164
345c78ca 4165 if (wxDynamicCast(def, wxRichTextBoxStyleDefinition))
b9433288
JS
4166 {
4167 if (GetFocusObject() && (GetFocusObject() != & GetBuffer()))
4168 {
4169 SetStyle(GetFocusObject(), attr);
4170 return true;
4171 }
4172 else
4173 return false;
4174 }
4175 else if (HasSelection())
1807a1f3 4176 return SetStyleEx(GetSelectionRange(), attr, flags);
ab14c7aa 4177 else
1807a1f3 4178 {
24777478
JS
4179 wxRichTextAttr current = GetDefaultStyleEx();
4180 wxRichTextAttr defaultStyle(attr);
edae63b0
JS
4181 if (isPara)
4182 {
4183 // Don't apply extra character styles since they are already implied
4184 // in the paragraph style
4185 defaultStyle.SetFlags(defaultStyle.GetFlags() & ~wxTEXT_ATTR_CHARACTER);
4186 }
4187 current.Apply(defaultStyle);
063dbace 4188 SetAndShowDefaultStyle(current);
edae63b0
JS
4189
4190 // If it's a paragraph style, we want to apply the style to the
4191 // current paragraph even if we didn't select any text.
4192 if (isPara)
4193 {
4194 long pos = GetAdjustedCaretPosition(GetCaretPosition());
603f702b 4195 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos);
edae63b0
JS
4196 if (para)
4197 {
4198 return SetStyleEx(para->GetRange().FromInternal(), attr, flags);
4199 }
4200 }
1807a1f3
JS
4201 return true;
4202 }
ab14c7aa
JS
4203}
4204
fe5aa22c
JS
4205/// Apply the style sheet to the buffer, for example if the styles have changed.
4206bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
4207{
4208 if (!styleSheet)
4209 styleSheet = GetBuffer().GetStyleSheet();
4210 if (!styleSheet)
4211 return false;
4212
4213 if (GetBuffer().ApplyStyleSheet(styleSheet))
4214 {
4215 GetBuffer().Invalidate(wxRICHTEXT_ALL);
4216 Refresh(false);
4217 return true;
4218 }
4219 else
4220 return false;
4221}
4222
5d7836c4
JS
4223/// Sets the default style to the style under the cursor
4224bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
4225{
24777478 4226 wxRichTextAttr attr;
5d7836c4
JS
4227 attr.SetFlags(wxTEXT_ATTR_CHARACTER);
4228
ab14c7aa
JS
4229 // If at the start of a paragraph, use the next position.
4230 long pos = GetAdjustedCaretPosition(GetCaretPosition());
4231
1199fbd4
JS
4232 wxRichTextObject* obj = GetFocusObject()->GetLeafObjectAtPosition(pos);
4233 if (obj && obj->IsTopLevel())
4234 {
4235 // Don't use the attributes of a top-level object, since they might apply
4236 // to content of the object, e.g. background colour.
4237 SetDefaultStyle(wxRichTextAttr());
4238 return true;
4239 }
4240 else if (GetUncombinedStyle(pos, attr))
5d7836c4
JS
4241 {
4242 SetDefaultStyle(attr);
4243 return true;
4244 }
41e155b4
WS
4245
4246 return false;
5d7836c4
JS
4247}
4248
4d551ad5
JS
4249/// Returns the first visible position in the current view
4250long wxRichTextCtrl::GetFirstVisiblePosition() const
4251{
4ba36292 4252 wxRichTextLine* line = GetFocusObject()->GetLineAtYPosition(GetUnscaledPoint(GetLogicalPoint(wxPoint(0, 0))).y);
4d551ad5
JS
4253 if (line)
4254 return line->GetAbsoluteRange().GetStart();
4255 else
4256 return 0;
4257}
4258
ea160b2e
JS
4259/// Get the first visible point in the window
4260wxPoint wxRichTextCtrl::GetFirstVisiblePoint() const
4261{
4262 int ppuX, ppuY;
4263 int startXUnits, startYUnits;
4264
4265 GetScrollPixelsPerUnit(& ppuX, & ppuY);
4266 GetViewStart(& startXUnits, & startYUnits);
4267
4268 return wxPoint(startXUnits * ppuX, startYUnits * ppuY);
4269}
4270
ab14c7aa
JS
4271/// The adjusted caret position is the character position adjusted to take
4272/// into account whether we're at the start of a paragraph, in which case
4273/// style information should be taken from the next position, not current one.
4274long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos) const
4275{
603f702b 4276 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(caretPos+1);
ab14c7aa
JS
4277
4278 if (para && (caretPos+1 == para->GetRange().GetStart()))
4279 caretPos ++;
4280 return caretPos;
4281}
4282
96c9f0f6
JS
4283/// Get/set the selection range in character positions. -1, -1 means no selection.
4284/// The range is in API convention, i.e. a single character selection is denoted
4285/// by (n, n+1)
4286wxRichTextRange wxRichTextCtrl::GetSelectionRange() const
4287{
4288 wxRichTextRange range = GetInternalSelectionRange();
4289 if (range != wxRichTextRange(-2,-2) && range != wxRichTextRange(-1,-1))
4290 range.SetEnd(range.GetEnd() + 1);
4291 return range;
4292}
4293
4294void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange& range)
4295{
76d7fc29 4296 SetSelection(range.GetStart(), range.GetEnd());
96c9f0f6
JS
4297}
4298
38f833b1
JS
4299/// Set list style
4300bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
4301{
603f702b 4302 return GetFocusObject()->SetListStyle(range.ToInternal(), def, flags, startFrom, specifiedLevel);
38f833b1
JS
4303}
4304
4305bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
4306{
603f702b 4307 return GetFocusObject()->SetListStyle(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
38f833b1
JS
4308}
4309
4310/// Clear list for given range
4311bool wxRichTextCtrl::ClearListStyle(const wxRichTextRange& range, int flags)
4312{
603f702b 4313 return GetFocusObject()->ClearListStyle(range.ToInternal(), flags);
38f833b1
JS
4314}
4315
4316/// Number/renumber any list elements in the given range
4317bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
4318{
603f702b 4319 return GetFocusObject()->NumberList(range.ToInternal(), def, flags, startFrom, specifiedLevel);
38f833b1
JS
4320}
4321
4322bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
4323{
603f702b 4324 return GetFocusObject()->NumberList(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
38f833b1
JS
4325}
4326
4327/// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
4328bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int specifiedLevel)
4329{
603f702b 4330 return GetFocusObject()->PromoteList(promoteBy, range.ToInternal(), def, flags, specifiedLevel);
38f833b1
JS
4331}
4332
4333bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags, int specifiedLevel)
4334{
603f702b 4335 return GetFocusObject()->PromoteList(promoteBy, range.ToInternal(), defName, flags, specifiedLevel);
38f833b1
JS
4336}
4337
4ce3ebd3
JS
4338// Given a character position at which there is a list style, find the range
4339// encompassing the same list style by looking backwards and forwards.
4340wxRichTextRange wxRichTextCtrl::FindRangeForList(long pos, bool& isNumberedList)
4341{
4342 wxRichTextParagraphLayoutBox* focusObject = GetFocusObject();
4343 wxRichTextRange range = wxRichTextRange(-1, -1);
4344 wxRichTextParagraph* para = focusObject->GetParagraphAtPosition(pos);
4345 if (!para || !para->GetAttributes().HasListStyleName())
4346 return range;
4347 else
4348 {
4349 wxString listStyle = para->GetAttributes().GetListStyleName();
4350 range = para->GetRange();
4351
4352 isNumberedList = para->GetAttributes().HasBulletNumber();
4353
4354 // Search back
4355 wxRichTextObjectList::compatibility_iterator initialNode = focusObject->GetChildren().Find(para);
4356 if (initialNode)
4357 {
4358 wxRichTextObjectList::compatibility_iterator startNode = initialNode->GetPrevious();
4359 while (startNode)
4360 {
4361 wxRichTextParagraph* p = wxDynamicCast(startNode->GetData(), wxRichTextParagraph);
4362 if (p)
4363 {
4364 if (!p->GetAttributes().HasListStyleName() || p->GetAttributes().GetListStyleName() != listStyle)
4365 break;
4366 else
4367 range.SetStart(p->GetRange().GetStart());
4368 }
4369
4370 startNode = startNode->GetPrevious();
4371 }
4372
4373 // Search forward
4374 wxRichTextObjectList::compatibility_iterator endNode = initialNode->GetNext();
4375 while (endNode)
4376 {
4377 wxRichTextParagraph* p = wxDynamicCast(endNode->GetData(), wxRichTextParagraph);
4378 if (p)
4379 {
4380 if (!p->GetAttributes().HasListStyleName() || p->GetAttributes().GetListStyleName() != listStyle)
4381 break;
4382 else
4383 range.SetEnd(p->GetRange().GetEnd());
4384 }
4385
4386 endNode = endNode->GetNext();
4387 }
4388 }
4389 }
4390 return range;
4391}
4392
12cc29c5
JS
4393/// Deletes the content in the given range
4394bool wxRichTextCtrl::Delete(const wxRichTextRange& range)
4395{
603f702b 4396 return GetFocusObject()->DeleteRangeWithUndo(range.ToInternal(), this, & GetBuffer());
12cc29c5
JS
4397}
4398
dadd4f55
JS
4399const wxArrayString& wxRichTextCtrl::GetAvailableFontNames()
4400{
4401 if (sm_availableFontNames.GetCount() == 0)
4402 {
4403 sm_availableFontNames = wxFontEnumerator::GetFacenames();
4404 sm_availableFontNames.Sort();
4405 }
4406 return sm_availableFontNames;
4407}
4408
4409void wxRichTextCtrl::ClearAvailableFontNames()
4410{
4411 sm_availableFontNames.Clear();
4412}
4413
c0a5145a 4414void wxRichTextCtrl::OnSysColourChanged(wxSysColourChangedEvent& WXUNUSED(event))
52170c5b
JS
4415{
4416 //wxLogDebug(wxT("wxRichTextCtrl::OnSysColourChanged"));
4417
4418 wxTextAttrEx basicStyle = GetBasicStyle();
4419 basicStyle.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
4420 SetBasicStyle(basicStyle);
4421 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
4422
4423 Refresh();
4424}
4425
7051fa41 4426// Refresh the area affected by a selection change
603f702b
JS
4427bool wxRichTextCtrl::RefreshForSelectionChange(const wxRichTextSelection& oldSelection, const wxRichTextSelection& newSelection)
4428{
4429 // If the selection is not part of the focus object, or we have multiple ranges, then the chances are that
4430 // the selection contains whole containers rather than just text, so refresh everything
4431 // for now as it would be hard to compute the rectangle bounding all selections.
4432 // TODO: improve on this.
4433 if ((oldSelection.IsValid() && (oldSelection.GetContainer() != GetFocusObject() || oldSelection.GetCount() > 1)) ||
4434 (newSelection.IsValid() && (newSelection.GetContainer() != GetFocusObject() || newSelection.GetCount() > 1)))
4435 {
4436 Refresh(false);
4437 return true;
4438 }
4fe83b93 4439
603f702b
JS
4440 wxRichTextRange oldRange, newRange;
4441 if (oldSelection.IsValid())
4442 oldRange = oldSelection.GetRange();
4443 else
4444 oldRange = wxRICHTEXT_NO_SELECTION;
4445 if (newSelection.IsValid())
4446 newRange = newSelection.GetRange();
4447 else
4448 newRange = wxRICHTEXT_NO_SELECTION;
4fe83b93 4449
7051fa41
JS
4450 // Calculate the refresh rectangle - just the affected lines
4451 long firstPos, lastPos;
603f702b 4452 if (oldRange.GetStart() == -2 && newRange.GetStart() != -2)
7051fa41 4453 {
603f702b
JS
4454 firstPos = newRange.GetStart();
4455 lastPos = newRange.GetEnd();
7051fa41 4456 }
603f702b 4457 else if (oldRange.GetStart() != -2 && newRange.GetStart() == -2)
7051fa41 4458 {
603f702b
JS
4459 firstPos = oldRange.GetStart();
4460 lastPos = oldRange.GetEnd();
7051fa41 4461 }
603f702b 4462 else if (oldRange.GetStart() == -2 && newRange.GetStart() == -2)
7051fa41
JS
4463 {
4464 return false;
4465 }
4466 else
4467 {
603f702b
JS
4468 firstPos = wxMin(oldRange.GetStart(), newRange.GetStart());
4469 lastPos = wxMax(oldRange.GetEnd(), newRange.GetEnd());
7051fa41
JS
4470 }
4471
603f702b
JS
4472 wxRichTextLine* firstLine = GetFocusObject()->GetLineAtPosition(firstPos);
4473 wxRichTextLine* lastLine = GetFocusObject()->GetLineAtPosition(lastPos);
7051fa41
JS
4474
4475 if (firstLine && lastLine)
4476 {
4477 wxSize clientSize = GetClientSize();
4ba36292
JS
4478 wxPoint pt1 = GetPhysicalPoint(GetScaledPoint(firstLine->GetAbsolutePosition()));
4479 wxPoint pt2 = GetPhysicalPoint(GetScaledPoint(lastLine->GetAbsolutePosition())) + wxPoint(0, (int) (0.5 + lastLine->GetSize().y * GetScale()));
7051fa41
JS
4480
4481 pt1.x = 0;
4482 pt1.y = wxMax(0, pt1.y);
4483 pt2.x = 0;
4484 pt2.y = wxMin(clientSize.y, pt2.y);
4485
4486 wxRect rect(pt1, wxSize(clientSize.x, pt2.y - pt1.y));
4487 RefreshRect(rect, false);
4488 }
4489 else
4490 Refresh(false);
4491
4492 return true;
4493}
4494
603f702b
JS
4495// margins functions
4496bool wxRichTextCtrl::DoSetMargins(const wxPoint& pt)
4497{
4498 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().SetValue(pt.x, wxTEXT_ATTR_UNITS_PIXELS);
4499 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetRight().SetValue(pt.x, wxTEXT_ATTR_UNITS_PIXELS);
4500 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().SetValue(pt.y, wxTEXT_ATTR_UNITS_PIXELS);
4501 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetBottom().SetValue(pt.y, wxTEXT_ATTR_UNITS_PIXELS);
4fe83b93 4502
603f702b
JS
4503 return true;
4504}
4505
4506wxPoint wxRichTextCtrl::DoGetMargins() const
4507{
4508 return wxPoint(GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().GetValue(),
4509 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().GetValue());
4510}
4511
4512bool wxRichTextCtrl::SetFocusObject(wxRichTextParagraphLayoutBox* obj, bool setCaretPosition)
4513{
4514 if (obj && !obj->AcceptsFocus())
4515 return false;
4516
4517 wxRichTextParagraphLayoutBox* oldContainer = GetFocusObject();
4518 bool changingContainer = (m_focusObject != obj);
4519
eadb039e
JS
4520 if (changingContainer && HasSelection())
4521 SelectNone();
4522
603f702b 4523 m_focusObject = obj;
4fe83b93 4524
603f702b
JS
4525 if (!obj)
4526 m_focusObject = & m_buffer;
4527
4528 if (setCaretPosition && changingContainer)
4529 {
4530 m_selection.Reset();
4531 m_selectionAnchor = -2;
4532 m_selectionAnchorObject = NULL;
4533 m_selectionState = wxRichTextCtrlSelectionState_Normal;
4534
4535 long pos = -1;
4fe83b93 4536
603f702b
JS
4537 m_caretAtLineStart = false;
4538 MoveCaret(pos, m_caretAtLineStart);
4539 SetDefaultStyleToCursorStyle();
4540
4541 wxRichTextEvent cmdEvent(
4542 wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED,
4543 GetId());
4544 cmdEvent.SetEventObject(this);
4545 cmdEvent.SetPosition(m_caretPosition+1);
4546 cmdEvent.SetOldContainer(oldContainer);
4547 cmdEvent.SetContainer(m_focusObject);
4548
4549 GetEventHandler()->ProcessEvent(cmdEvent);
4550 }
4551 return true;
4552}
4553
0c0e063e
JS
4554#if wxUSE_DRAG_AND_DROP
4555void wxRichTextCtrl::OnDrop(wxCoord WXUNUSED(x), wxCoord WXUNUSED(y), wxDragResult def, wxDataObject* DataObj)
4556{
4557 m_preDrag = false;
4558
4559 if ((def != wxDragCopy) && (def != wxDragMove))
4560 {
4561 return;
4562 }
4563
4564 if (!GetSelection().IsValid())
4565 {
4566 return;
4567 }
4568
4569 wxRichTextParagraphLayoutBox* originContainer = GetSelection().GetContainer();
4570 wxRichTextParagraphLayoutBox* destContainer = GetFocusObject(); // This will be the drop container, not necessarily the same as the origin one
4571
0c0e063e
JS
4572 wxRichTextBuffer* richTextBuffer = ((wxRichTextBufferDataObject*)DataObj)->GetRichTextBuffer();
4573 if (richTextBuffer)
4574 {
4575 long position = GetCaretPosition();
4576 wxRichTextRange selectionrange = GetInternalSelectionRange();
4577 if (selectionrange.Contains(position) && (def == wxDragMove))
4578 {
4579 // It doesn't make sense to move onto itself
4580 return;
4581 }
4582
4583 // If we're moving, and the data is being moved forward, we need to drop first, then delete the selection
4584 // If moving backwards, we need to delete then drop. If we're copying (or doing nothing) we don't delete anyway
4585 bool DeleteAfter = (def == wxDragMove) && (position > selectionrange.GetEnd());
4586 if ((def == wxDragMove) && !DeleteAfter)
4587 {
4588 // We can't use e.g. DeleteSelectedContent() as it uses the focus container
4589 originContainer->DeleteRangeWithUndo(selectionrange, this, &GetBuffer());
4590 }
4591
4e63bfb9 4592 destContainer->InsertParagraphsWithUndo(&GetBuffer(), position+1, *richTextBuffer, this, 0);
0c0e063e
JS
4593 ShowPosition(position + richTextBuffer->GetOwnRange().GetEnd());
4594
4595 delete richTextBuffer;
4596
4597 if (DeleteAfter)
4598 {
4599 // We can't use e.g. DeleteSelectedContent() as it uses the focus container
4600 originContainer->DeleteRangeWithUndo(selectionrange, this, &GetBuffer());
4601 }
4602
0c0e063e
JS
4603 SelectNone();
4604 Refresh();
4605 }
4606}
4607#endif // wxUSE_DRAG_AND_DROP
4608
4609
4610#if wxUSE_DRAG_AND_DROP
4611bool wxRichTextDropSource::GiveFeedback(wxDragResult WXUNUSED(effect))
4612{
4613 wxCHECK_MSG(m_rtc, false, wxT("NULL m_rtc"));
4614
4615 long position = 0;
4616 int hit = 0;
4617 wxRichTextObject* hitObj = NULL;
4ba36292 4618 wxRichTextParagraphLayoutBox* container = m_rtc->FindContainerAtPoint(m_rtc->GetUnscaledPoint(m_rtc->ScreenToClient(wxGetMousePosition())), position, hit, hitObj);
0c0e063e
JS
4619
4620 if (!(hit & wxRICHTEXT_HITTEST_NONE) && container && container->AcceptsFocus())
4621 {
4622 m_rtc->StoreFocusObject(container);
4623 m_rtc->SetCaretPositionAfterClick(container, position, hit);
4624 }
4625
4626 return false; // so that the base-class sets a cursor
4627}
4628#endif // wxUSE_DRAG_AND_DROP
4629
cc2aecde
JS
4630bool wxRichTextCtrl::CanDeleteRange(wxRichTextParagraphLayoutBox& WXUNUSED(container), const wxRichTextRange& WXUNUSED(range)) const
4631{
4632 return true;
4633}
4634
4635bool wxRichTextCtrl::CanInsertContent(wxRichTextParagraphLayoutBox& WXUNUSED(container), long WXUNUSED(pos)) const
4636{
4637 return true;
4638}
4639
12f5219f
JS
4640void wxRichTextCtrl::EnableVerticalScrollbar(bool enable)
4641{
4642 m_verticalScrollbarEnabled = enable;
4643 SetupScrollbars();
4644}
4645
32423dd8
JS
4646void wxRichTextCtrl::SetFontScale(double fontScale, bool refresh)
4647{
4648 GetBuffer().SetFontScale(fontScale);
4649 if (refresh)
4650 {
4651 GetBuffer().Invalidate(wxRICHTEXT_ALL);
4652 Refresh();
4653 }
4654}
4655
4656void wxRichTextCtrl::SetDimensionScale(double dimScale, bool refresh)
4657{
4658 GetBuffer().SetDimensionScale(dimScale);
4659 if (refresh)
4660 {
4661 GetBuffer().Invalidate(wxRICHTEXT_ALL);
4662 Refresh();
4663 }
4664}
4665
4ba36292
JS
4666// Sets an overall scale factor for displaying and editing the content.
4667void wxRichTextCtrl::SetScale(double scale, bool refresh)
4668{
4669 m_scale = scale;
4670 if (refresh)
4671 {
4672 GetBuffer().Invalidate(wxRICHTEXT_ALL);
4673 Refresh();
4674 }
4675}
4676
4677// Get an unscaled point
4678wxPoint wxRichTextCtrl::GetUnscaledPoint(const wxPoint& pt) const
4679{
4680 if (GetScale() == 1.0)
4681 return pt;
4682 else
4683 return wxPoint((int) (0.5 + double(pt.x) / GetScale()), (int) (0.5 + double(pt.y) / GetScale()));
4684}
4685
4686// Get a scaled point
4687wxPoint wxRichTextCtrl::GetScaledPoint(const wxPoint& pt) const
4688{
4689 if (GetScale() == 1.0)
4690 return pt;
4691 else
4692 return wxPoint((int) (0.5 + double(pt.x) * GetScale()), (int) (0.5 + double(pt.y) * GetScale()));
4693}
4694
4695// Get an unscaled size
4696wxSize wxRichTextCtrl::GetUnscaledSize(const wxSize& sz) const
4697{
4698 if (GetScale() == 1.0)
4699 return sz;
4700 else
4701 return wxSize((int) (0.5 + double(sz.x) / GetScale()), (int) (0.5 + double(sz.y) / GetScale()));
4702}
4703
4704// Get a scaled size
4705wxSize wxRichTextCtrl::GetScaledSize(const wxSize& sz) const
4706{
4707 if (GetScale() == 1.0)
4708 return sz;
4709 else
4710 return wxSize((int) (0.5 + double(sz.x) * GetScale()), (int) (0.5 + double(sz.y) * GetScale()));
4711}
4712
4713// Get an unscaled rect
4714wxRect wxRichTextCtrl::GetUnscaledRect(const wxRect& rect) const
4715{
4716 if (GetScale() == 1.0)
4717 return rect;
4718 else
4719 return wxRect((int) (0.5 + double(rect.x) / GetScale()), (int) (0.5 + double(rect.y) / GetScale()),
4720 (int) (0.5 + double(rect.width) / GetScale()), (int) (0.5 + double(rect.height) / GetScale()));
4721}
4722
4723// Get a scaled rect
4724wxRect wxRichTextCtrl::GetScaledRect(const wxRect& rect) const
4725{
4726 if (GetScale() == 1.0)
4727 return rect;
4728 else
4729 return wxRect((int) (0.5 + double(rect.x) * GetScale()), (int) (0.5 + double(rect.y) * GetScale()),
4730 (int) (0.5 + double(rect.width) * GetScale()), (int) (0.5 + double(rect.height) * GetScale()));
4731}
4732
1c13f06e
JS
4733#if wxRICHTEXT_USE_OWN_CARET
4734
4735// ----------------------------------------------------------------------------
4736// initialization and destruction
4737// ----------------------------------------------------------------------------
4738
4739void wxRichTextCaret::Init()
4740{
4741 m_hasFocus = true;
cd45ed36 4742 m_refreshEnabled = true;
1c13f06e
JS
4743
4744 m_xOld =
4745 m_yOld = -1;
4746 m_richTextCtrl = NULL;
4747 m_needsUpdate = false;
a188ac29 4748 m_flashOn = true;
1c13f06e
JS
4749}
4750
4751wxRichTextCaret::~wxRichTextCaret()
4752{
a188ac29
JS
4753 if (m_timer.IsRunning())
4754 m_timer.Stop();
1c13f06e
JS
4755}
4756
4757// ----------------------------------------------------------------------------
4758// showing/hiding/moving the caret (base class interface)
4759// ----------------------------------------------------------------------------
4760
4761void wxRichTextCaret::DoShow()
4762{
a188ac29 4763 m_flashOn = true;
ab52bac8 4764
a188ac29
JS
4765 if (!m_timer.IsRunning())
4766 m_timer.Start(GetBlinkTime());
4767
1c13f06e
JS
4768 Refresh();
4769}
4770
4771void wxRichTextCaret::DoHide()
4772{
a188ac29
JS
4773 if (m_timer.IsRunning())
4774 m_timer.Stop();
4775
1c13f06e
JS
4776 Refresh();
4777}
4778
4779void wxRichTextCaret::DoMove()
4780{
4781 if (IsVisible())
4782 {
4783 Refresh();
4784
4785 if (m_xOld != -1 && m_yOld != -1)
4786 {
cd45ed36 4787 if (m_richTextCtrl && m_refreshEnabled)
1c13f06e
JS
4788 {
4789 wxRect rect(GetPosition(), GetSize());
4790 m_richTextCtrl->RefreshRect(rect, false);
4791 }
4792 }
4793 }
4794
4795 m_xOld = m_x;
4796 m_yOld = m_y;
4797}
4798
4799void wxRichTextCaret::DoSize()
4800{
4801 int countVisible = m_countVisible;
4802 if (countVisible > 0)
4803 {
4804 m_countVisible = 0;
4805 DoHide();
4806 }
4807
4808 if (countVisible > 0)
4809 {
4810 m_countVisible = countVisible;
4811 DoShow();
4812 }
4813}
4814
4815// ----------------------------------------------------------------------------
4816// handling the focus
4817// ----------------------------------------------------------------------------
4818
4819void wxRichTextCaret::OnSetFocus()
4820{
4821 m_hasFocus = true;
4822
4823 if ( IsVisible() )
4824 Refresh();
4825}
4826
4827void wxRichTextCaret::OnKillFocus()
4828{
4829 m_hasFocus = false;
4830}
4831
4832// ----------------------------------------------------------------------------
4833// drawing the caret
4834// ----------------------------------------------------------------------------
4835
4836void wxRichTextCaret::Refresh()
4837{
cd45ed36 4838 if (m_richTextCtrl && m_refreshEnabled)
1c13f06e
JS
4839 {
4840 wxRect rect(GetPosition(), GetSize());
4841 m_richTextCtrl->RefreshRect(rect, false);
4842 }
4843}
4844
4845void wxRichTextCaret::DoDraw(wxDC *dc)
4846{
4847 dc->SetPen( *wxBLACK_PEN );
4848
4849 dc->SetBrush(*(m_hasFocus ? wxBLACK_BRUSH : wxTRANSPARENT_BRUSH));
4850 dc->SetPen(*wxBLACK_PEN);
4851
1c13f06e
JS
4852 wxPoint pt(m_x, m_y);
4853
4854 if (m_richTextCtrl)
4855 {
4856 pt = m_richTextCtrl->GetLogicalPoint(pt);
4857 }
a188ac29
JS
4858 if (IsVisible() && m_flashOn)
4859 dc->DrawRectangle(pt.x, pt.y, m_width, m_height);
4860}
4861
4862void wxRichTextCaret::Notify()
4863{
4864 m_flashOn = !m_flashOn;
4865 Refresh();
4866}
4867
4868void wxRichTextCaretTimer::Notify()
4869{
4870 m_caret->Notify();
1c13f06e
JS
4871}
4872#endif
4873 // wxRICHTEXT_USE_OWN_CARET
4874
603f702b
JS
4875// Add an item
4876bool wxRichTextContextMenuPropertiesInfo::AddItem(const wxString& label, wxRichTextObject* obj)
4877{
4878 if (GetCount() < 3)
4879 {
4880 m_labels.Add(label);
4881 m_objects.Add(obj);
4882 return true;
4883 }
4884 else
4885 return false;
4886}
4887
4888// Returns number of menu items were added.
4889int wxRichTextContextMenuPropertiesInfo::AddMenuItems(wxMenu* menu, int startCmd) const
4890{
4891 wxMenuItem* item = menu->FindItem(startCmd);
9b794421
JS
4892 // If none of the standard properties identifiers are in the menu, add them if necessary.
4893 // If no items to add, just set the text to something generic
4894 if (GetCount() == 0)
603f702b 4895 {
9b794421 4896 if (item)
603f702b
JS
4897 {
4898 menu->SetLabel(startCmd, _("&Properties"));
4fe83b93 4899
603f702b
JS
4900 // Delete the others if necessary
4901 int i;
4902 for (i = startCmd+1; i < startCmd+3; i++)
4903 {
4904 if (menu->FindItem(i))
4905 {
4906 menu->Delete(i);
4907 }
4908 }
4909 }
9b794421
JS
4910 }
4911 else
4912 {
4913 int i;
4914 int pos = -1;
4915 // Find the position of the first properties item
4916 for (i = 0; i < (int) menu->GetMenuItemCount(); i++)
603f702b 4917 {
9b794421
JS
4918 wxMenuItem* item = menu->FindItemByPosition(i);
4919 if (item && item->GetId() == startCmd)
603f702b 4920 {
9b794421
JS
4921 pos = i;
4922 break;
603f702b 4923 }
9b794421 4924 }
4fe83b93 4925
9b794421
JS
4926 if (pos != -1)
4927 {
4928 int insertBefore = pos+1;
4929 for (i = startCmd; i < startCmd+GetCount(); i++)
603f702b 4930 {
9b794421 4931 if (menu->FindItem(i))
603f702b 4932 {
9b794421
JS
4933 menu->SetLabel(i, m_labels[i - startCmd]);
4934 }
4935 else
4936 {
4937 if (insertBefore >= (int) menu->GetMenuItemCount())
4938 menu->Append(i, m_labels[i - startCmd]);
603f702b 4939 else
9b794421 4940 menu->Insert(insertBefore, i, m_labels[i - startCmd]);
603f702b 4941 }
9b794421
JS
4942 insertBefore ++;
4943 }
4fe83b93 4944
9b794421
JS
4945 // Delete any old items still left on the menu
4946 for (i = startCmd + GetCount(); i < startCmd+3; i++)
4947 {
4948 if (menu->FindItem(i))
603f702b 4949 {
9b794421 4950 menu->Delete(i);
603f702b
JS
4951 }
4952 }
4953 }
9b794421
JS
4954 else
4955 {
4956 // No existing property identifiers were found, so append to the end of the menu.
4957 menu->AppendSeparator();
4958 for (i = startCmd; i < startCmd+GetCount(); i++)
4959 {
4960 menu->Append(i, m_labels[i - startCmd]);
4961 }
4962 }
603f702b
JS
4963 }
4964
4965 return GetCount();
4966}
4967
4968// Add appropriate menu items for the current container and clicked on object
4969// (and container's parent, if appropriate).
303f0be7 4970int wxRichTextContextMenuPropertiesInfo::AddItems(wxRichTextCtrl* ctrl, wxRichTextObject* container, wxRichTextObject* obj)
603f702b
JS
4971{
4972 Clear();
303f0be7 4973 if (obj && ctrl->CanEditProperties(obj))
590a0f8b 4974 AddItem(ctrl->GetPropertiesMenuLabel(obj), obj);
603f702b 4975
590a0f8b
JS
4976 if (container && container != obj && ctrl->CanEditProperties(container) && m_labels.Index(ctrl->GetPropertiesMenuLabel(container)) == wxNOT_FOUND)
4977 AddItem(ctrl->GetPropertiesMenuLabel(container), container);
603f702b 4978
590a0f8b
JS
4979 if (container && container->GetParent() && ctrl->CanEditProperties(container->GetParent()) && m_labels.Index(ctrl->GetPropertiesMenuLabel(container->GetParent())) == wxNOT_FOUND)
4980 AddItem(ctrl->GetPropertiesMenuLabel(container->GetParent()), container->GetParent());
603f702b
JS
4981
4982 return GetCount();
4983}
4984
5d7836c4
JS
4985#endif
4986 // wxUSE_RICHTEXT