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