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