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