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