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