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