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