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