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