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