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