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