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