Fixed [ 1905777 ] Defining default accelerators for wxRichTextCtrl
[wxWidgets.git] / src / richtext / richtextctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richeditctrl.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/textfile.h"
30 #include "wx/ffile.h"
31 #include "wx/filename.h"
32 #include "wx/dcbuffer.h"
33 #include "wx/arrimpl.cpp"
34 #include "wx/fontenum.h"
35 #include "wx/accel.h"
36
37 // DLL options compatibility check:
38 #include "wx/app.h"
39 WX_CHECK_BUILD_OPTIONS("wxRichTextCtrl")
40
41 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_LEFT_CLICK)
42 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK)
43 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK)
44 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK)
45 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_RETURN)
46 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_CHARACTER)
47 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_DELETE)
48
49 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING)
50 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED)
51 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING)
52 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED)
53
54 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED)
55 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED)
56 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED)
57 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED)
58 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_BUFFER_RESET)
59
60 #if wxRICHTEXT_USE_OWN_CARET
61
62 /*!
63 * wxRichTextCaret
64 *
65 * This implements a non-flashing cursor in case there
66 * are platform-specific problems with the generic caret.
67 * wxRICHTEXT_USE_OWN_CARET is set in richtextbuffer.h.
68 */
69
70 class wxRichTextCaret: public wxCaret
71 {
72 public:
73 // ctors
74 // -----
75 // default - use Create()
76 wxRichTextCaret() { Init(); }
77 // creates a block caret associated with the given window
78 wxRichTextCaret(wxRichTextCtrl *window, int width, int height)
79 : wxCaret(window, width, height) { Init(); m_richTextCtrl = window; }
80 wxRichTextCaret(wxRichTextCtrl *window, const wxSize& size)
81 : wxCaret(window, size) { Init(); m_richTextCtrl = window; }
82
83 virtual ~wxRichTextCaret();
84
85 // implementation
86 // --------------
87
88 // called by wxWindow (not using the event tables)
89 virtual void OnSetFocus();
90 virtual void OnKillFocus();
91
92 // draw the caret on the given DC
93 void DoDraw(wxDC *dc);
94
95 // get the visible count
96 int GetVisibleCount() const { return m_countVisible; }
97
98 // delay repositioning
99 bool GetNeedsUpdate() const { return m_needsUpdate; }
100 void SetNeedsUpdate(bool needsUpdate = true ) { m_needsUpdate = needsUpdate; }
101
102 protected:
103 virtual void DoShow();
104 virtual void DoHide();
105 virtual void DoMove();
106 virtual void DoSize();
107
108 // refresh the caret
109 void Refresh();
110
111 private:
112 void Init();
113
114 int m_xOld,
115 m_yOld;
116 bool m_hasFocus; // true => our window has focus
117 bool m_needsUpdate; // must be repositioned
118
119 wxRichTextCtrl* m_richTextCtrl;
120 };
121 #endif
122
123 IMPLEMENT_CLASS( wxRichTextCtrl, wxControl )
124
125 IMPLEMENT_CLASS( wxRichTextEvent, wxNotifyEvent )
126
127 BEGIN_EVENT_TABLE( wxRichTextCtrl, wxControl )
128 EVT_PAINT(wxRichTextCtrl::OnPaint)
129 EVT_ERASE_BACKGROUND(wxRichTextCtrl::OnEraseBackground)
130 EVT_IDLE(wxRichTextCtrl::OnIdle)
131 EVT_SCROLLWIN(wxRichTextCtrl::OnScroll)
132 EVT_LEFT_DOWN(wxRichTextCtrl::OnLeftClick)
133 EVT_MOTION(wxRichTextCtrl::OnMoveMouse)
134 EVT_LEFT_UP(wxRichTextCtrl::OnLeftUp)
135 EVT_RIGHT_DOWN(wxRichTextCtrl::OnRightClick)
136 EVT_MIDDLE_DOWN(wxRichTextCtrl::OnMiddleClick)
137 EVT_LEFT_DCLICK(wxRichTextCtrl::OnLeftDClick)
138 EVT_CHAR(wxRichTextCtrl::OnChar)
139 EVT_SIZE(wxRichTextCtrl::OnSize)
140 EVT_SET_FOCUS(wxRichTextCtrl::OnSetFocus)
141 EVT_KILL_FOCUS(wxRichTextCtrl::OnKillFocus)
142 EVT_MOUSE_CAPTURE_LOST(wxRichTextCtrl::OnCaptureLost)
143 EVT_CONTEXT_MENU(wxRichTextCtrl::OnContextMenu)
144 EVT_SYS_COLOUR_CHANGED(wxRichTextCtrl::OnSysColourChanged)
145
146 EVT_MENU(wxID_UNDO, wxRichTextCtrl::OnUndo)
147 EVT_UPDATE_UI(wxID_UNDO, wxRichTextCtrl::OnUpdateUndo)
148
149 EVT_MENU(wxID_REDO, wxRichTextCtrl::OnRedo)
150 EVT_UPDATE_UI(wxID_REDO, wxRichTextCtrl::OnUpdateRedo)
151
152 EVT_MENU(wxID_COPY, wxRichTextCtrl::OnCopy)
153 EVT_UPDATE_UI(wxID_COPY, wxRichTextCtrl::OnUpdateCopy)
154
155 EVT_MENU(wxID_PASTE, wxRichTextCtrl::OnPaste)
156 EVT_UPDATE_UI(wxID_PASTE, wxRichTextCtrl::OnUpdatePaste)
157
158 EVT_MENU(wxID_CUT, wxRichTextCtrl::OnCut)
159 EVT_UPDATE_UI(wxID_CUT, wxRichTextCtrl::OnUpdateCut)
160
161 EVT_MENU(wxID_CLEAR, wxRichTextCtrl::OnClear)
162 EVT_UPDATE_UI(wxID_CLEAR, wxRichTextCtrl::OnUpdateClear)
163
164 EVT_MENU(wxID_SELECTALL, wxRichTextCtrl::OnSelectAll)
165 EVT_UPDATE_UI(wxID_SELECTALL, wxRichTextCtrl::OnUpdateSelectAll)
166 END_EVENT_TABLE()
167
168 /*!
169 * wxRichTextCtrl
170 */
171
172 wxArrayString wxRichTextCtrl::sm_availableFontNames;
173
174 wxRichTextCtrl::wxRichTextCtrl()
175 : wxScrollHelper(this)
176 {
177 Init();
178 }
179
180 wxRichTextCtrl::wxRichTextCtrl(wxWindow* parent,
181 wxWindowID id,
182 const wxString& value,
183 const wxPoint& pos,
184 const wxSize& size,
185 long style,
186 const wxValidator& validator,
187 const wxString& name)
188 : wxScrollHelper(this)
189 {
190 Init();
191 Create(parent, id, value, pos, size, style, validator, name);
192 }
193
194 /// Creation
195 bool wxRichTextCtrl::Create( wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style,
196 const wxValidator& validator, const wxString& name)
197 {
198 if (!wxControl::Create(parent, id, pos, size,
199 style|wxFULL_REPAINT_ON_RESIZE,
200 validator, name))
201 return false;
202
203 if (!GetFont().Ok())
204 {
205 SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
206 }
207
208 if (style & wxTE_READONLY)
209 SetEditable(false);
210
211 // The base attributes must all have default values
212 wxTextAttr attributes;
213 attributes.SetFont(GetFont());
214 attributes.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
215 attributes.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
216 attributes.SetLineSpacing(10);
217 attributes.SetParagraphSpacingAfter(10);
218 attributes.SetParagraphSpacingBefore(0);
219 attributes.SetTextEffects(0);
220 attributes.SetTextEffectFlags(wxTEXT_ATTR_EFFECT_STRIKETHROUGH|wxTEXT_ATTR_EFFECT_CAPITALS);
221
222 SetBasicStyle(attributes);
223
224 // The default attributes will be merged with base attributes, so
225 // can be empty to begin with
226 wxTextAttr defaultAttributes;
227 SetDefaultStyle(defaultAttributes);
228
229 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
230 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
231
232 GetBuffer().Reset();
233 GetBuffer().SetRichTextCtrl(this);
234
235 #if wxRICHTEXT_USE_OWN_CARET
236 SetCaret(new wxRichTextCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
237 #else
238 SetCaret(new wxCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
239 #endif
240
241 // Tell the sizers to use the given or best size
242 SetInitialSize(size);
243
244 #if wxRICHTEXT_BUFFERED_PAINTING
245 // Create a buffer
246 RecreateBuffer(size);
247 #endif
248
249 m_textCursor = wxCursor(wxCURSOR_IBEAM);
250 m_urlCursor = wxCursor(wxCURSOR_HAND);
251
252 SetCursor(m_textCursor);
253
254 if (!value.IsEmpty())
255 SetValue(value);
256
257 GetBuffer().AddEventHandler(this);
258
259 // Accelerators
260 wxAcceleratorEntry entries[4];
261
262 entries[0].Set(wxACCEL_CMD, (int) 'C', wxID_COPY);
263 entries[1].Set(wxACCEL_CMD, (int) 'X', wxID_CUT);
264 entries[2].Set(wxACCEL_CMD, (int) 'V', wxID_PASTE);
265 entries[3].Set(wxACCEL_CMD, (int) 'A', wxID_SELECTALL);
266
267 wxAcceleratorTable accel(4, entries);
268 SetAcceleratorTable(accel);
269
270 return true;
271 }
272
273 wxRichTextCtrl::~wxRichTextCtrl()
274 {
275 GetBuffer().RemoveEventHandler(this);
276
277 delete m_contextMenu;
278 }
279
280 /// Member initialisation
281 void wxRichTextCtrl::Init()
282 {
283 m_contextMenu = NULL;
284 m_caret = NULL;
285 m_caretPosition = -1;
286 m_selectionRange.SetRange(-2, -2);
287 m_selectionAnchor = -2;
288 m_editable = true;
289 m_caretAtLineStart = false;
290 m_dragging = false;
291 m_fullLayoutRequired = false;
292 m_fullLayoutTime = 0;
293 m_fullLayoutSavedPosition = 0;
294 m_delayedLayoutThreshold = wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD;
295 m_caretPositionForDefaultStyle = -2;
296 }
297
298 void wxRichTextCtrl::DoThaw()
299 {
300 if (GetBuffer().GetDirty())
301 LayoutContent();
302 else
303 SetupScrollbars();
304 Refresh(false);
305 }
306
307 /// Clear all text
308 void wxRichTextCtrl::Clear()
309 {
310 m_buffer.ResetAndClearCommands();
311 m_buffer.SetDirty(true);
312 m_caretPosition = -1;
313 m_caretPositionForDefaultStyle = -2;
314 m_caretAtLineStart = false;
315 m_selectionRange.SetRange(-2, -2);
316
317 Scroll(0,0);
318
319 if (!IsFrozen())
320 {
321 LayoutContent();
322 Refresh(false);
323 }
324
325 wxTextCtrl::SendTextUpdatedEvent(this);
326 }
327
328 /// Painting
329 void wxRichTextCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
330 {
331 #if !wxRICHTEXT_USE_OWN_CARET
332 if (GetCaret() && !IsFrozen())
333 GetCaret()->Hide();
334 #endif
335
336 {
337 #if wxRICHTEXT_BUFFERED_PAINTING
338 wxBufferedPaintDC dc(this, m_bufferBitmap);
339 #else
340 wxPaintDC dc(this);
341 #endif
342
343 if (IsFrozen())
344 return;
345
346 PrepareDC(dc);
347
348 dc.SetFont(GetFont());
349
350 // Paint the background
351 PaintBackground(dc);
352
353 // wxRect drawingArea(GetLogicalPoint(wxPoint(0, 0)), GetClientSize());
354
355 wxRect drawingArea(GetUpdateRegion().GetBox());
356 drawingArea.SetPosition(GetLogicalPoint(drawingArea.GetPosition()));
357
358 wxRect availableSpace(GetClientSize());
359 if (GetBuffer().GetDirty())
360 {
361 GetBuffer().Layout(dc, availableSpace, wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT);
362 GetBuffer().SetDirty(false);
363 SetupScrollbars();
364 }
365
366 GetBuffer().Draw(dc, GetBuffer().GetRange(), GetInternalSelectionRange(), drawingArea, 0 /* descent */, 0 /* flags */);
367 #if wxRICHTEXT_USE_OWN_CARET
368 if (GetCaret()->IsVisible())
369 {
370 ((wxRichTextCaret*) GetCaret())->DoDraw(& dc);
371 }
372 #endif
373 }
374
375 #if !wxRICHTEXT_USE_OWN_CARET
376 if (GetCaret())
377 GetCaret()->Show();
378 PositionCaret();
379 #endif
380 }
381
382 // Empty implementation, to prevent flicker
383 void wxRichTextCtrl::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
384 {
385 }
386
387 void wxRichTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
388 {
389 if (GetCaret())
390 {
391 #if !wxRICHTEXT_USE_OWN_CARET
392 PositionCaret();
393 #endif
394 GetCaret()->Show();
395 }
396
397 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
398 // Work around dropouts when control is focused
399 if (!IsFrozen())
400 {
401 Refresh(false);
402 }
403 #endif
404 }
405
406 void wxRichTextCtrl::OnKillFocus(wxFocusEvent& WXUNUSED(event))
407 {
408 if (GetCaret())
409 GetCaret()->Hide();
410
411 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
412 // Work around dropouts when control is focused
413 if (!IsFrozen())
414 {
415 Refresh(false);
416 }
417 #endif
418 }
419
420 void wxRichTextCtrl::OnCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
421 {
422 m_dragging = false;
423 }
424
425 /// Left-click
426 void wxRichTextCtrl::OnLeftClick(wxMouseEvent& event)
427 {
428 SetFocus();
429
430 wxClientDC dc(this);
431 PrepareDC(dc);
432 dc.SetFont(GetFont());
433
434 long position = 0;
435 int hit = GetBuffer().HitTest(dc, event.GetLogicalPosition(dc), position);
436
437 if (hit != wxRICHTEXT_HITTEST_NONE)
438 {
439 m_dragStart = event.GetLogicalPosition(dc);
440 m_dragging = true;
441 CaptureMouse();
442
443 bool caretAtLineStart = false;
444
445 if (hit & wxRICHTEXT_HITTEST_BEFORE)
446 {
447 // If we're at the start of a line (but not first in para)
448 // then we should keep the caret showing at the start of the line
449 // by showing the m_caretAtLineStart flag.
450 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
451 wxRichTextLine* line = GetBuffer().GetLineAtPosition(position);
452
453 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
454 caretAtLineStart = true;
455 position --;
456 }
457
458 long oldCaretPos = m_caretPosition;
459
460 MoveCaret(position, caretAtLineStart);
461
462 if (event.ShiftDown())
463 {
464 if (m_selectionRange.GetStart() == -2)
465 ExtendSelection(oldCaretPos, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
466 else
467 ExtendSelection(m_caretPosition, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
468 }
469 else
470 SelectNone();
471 }
472
473 event.Skip();
474 }
475
476 /// Left-up
477 void wxRichTextCtrl::OnLeftUp(wxMouseEvent& event)
478 {
479 if (m_dragging)
480 {
481 m_dragging = false;
482 if (GetCapture() == this)
483 ReleaseMouse();
484
485 // See if we clicked on a URL
486 wxClientDC dc(this);
487 PrepareDC(dc);
488 dc.SetFont(GetFont());
489
490 long position = 0;
491 wxPoint logicalPt = event.GetLogicalPosition(dc);
492 int hit = GetBuffer().HitTest(dc, logicalPt, position);
493
494 if ((hit != wxRICHTEXT_HITTEST_NONE) && !(hit & wxRICHTEXT_HITTEST_OUTSIDE))
495 {
496 wxRichTextEvent cmdEvent(
497 wxEVT_COMMAND_RICHTEXT_LEFT_CLICK,
498 GetId());
499 cmdEvent.SetEventObject(this);
500 cmdEvent.SetPosition(m_caretPosition+1);
501
502 if (!GetEventHandler()->ProcessEvent(cmdEvent))
503 {
504 wxTextAttr attr;
505 if (GetStyle(position, attr))
506 {
507 if (attr.HasFlag(wxTEXT_ATTR_URL))
508 {
509 wxString urlTarget = attr.GetURL();
510 if (!urlTarget.IsEmpty())
511 {
512 wxMouseEvent mouseEvent(event);
513
514 long startPos = 0, endPos = 0;
515 wxRichTextObject* obj = GetBuffer().GetLeafObjectAtPosition(position);
516 if (obj)
517 {
518 startPos = obj->GetRange().GetStart();
519 endPos = obj->GetRange().GetEnd();
520 }
521
522 wxTextUrlEvent urlEvent(GetId(), mouseEvent, startPos, endPos);
523 InitCommandEvent(urlEvent);
524
525 urlEvent.SetString(urlTarget);
526
527 GetEventHandler()->ProcessEvent(urlEvent);
528 }
529 }
530 }
531 }
532 }
533 }
534 }
535
536 /// Left-click
537 void wxRichTextCtrl::OnMoveMouse(wxMouseEvent& event)
538 {
539 wxClientDC dc(this);
540 PrepareDC(dc);
541 dc.SetFont(GetFont());
542
543 long position = 0;
544 wxPoint logicalPt = event.GetLogicalPosition(dc);
545 int hit = GetBuffer().HitTest(dc, logicalPt, position);
546
547 // See if we need to change the cursor
548
549 {
550 if (hit != wxRICHTEXT_HITTEST_NONE && !(hit & wxRICHTEXT_HITTEST_OUTSIDE))
551 {
552 wxTextAttr attr;
553 if (GetStyle(position, attr))
554 {
555 if (attr.HasFlag(wxTEXT_ATTR_URL))
556 {
557 SetCursor(m_urlCursor);
558 }
559 else if (!attr.HasFlag(wxTEXT_ATTR_URL))
560 {
561 SetCursor(m_textCursor);
562 }
563 }
564 }
565 else
566 SetCursor(m_textCursor);
567 }
568
569 if (!event.Dragging())
570 {
571 event.Skip();
572 return;
573 }
574
575 if (m_dragging && hit != wxRICHTEXT_HITTEST_NONE)
576 {
577 // TODO: test closeness
578
579 bool caretAtLineStart = false;
580
581 if (hit & wxRICHTEXT_HITTEST_BEFORE)
582 {
583 // If we're at the start of a line (but not first in para)
584 // then we should keep the caret showing at the start of the line
585 // by showing the m_caretAtLineStart flag.
586 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
587 wxRichTextLine* line = GetBuffer().GetLineAtPosition(position);
588
589 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
590 caretAtLineStart = true;
591 position --;
592 }
593
594 if (m_caretPosition != position)
595 {
596 ExtendSelection(m_caretPosition, position, wxRICHTEXT_SHIFT_DOWN);
597
598 MoveCaret(position, caretAtLineStart);
599 }
600 }
601 }
602
603 /// Right-click
604 void wxRichTextCtrl::OnRightClick(wxMouseEvent& event)
605 {
606 SetFocus();
607
608 wxRichTextEvent cmdEvent(
609 wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK,
610 GetId());
611 cmdEvent.SetEventObject(this);
612 cmdEvent.SetPosition(m_caretPosition+1);
613
614 if (!GetEventHandler()->ProcessEvent(cmdEvent))
615 event.Skip();
616 }
617
618 /// Left-double-click
619 void wxRichTextCtrl::OnLeftDClick(wxMouseEvent& WXUNUSED(event))
620 {
621 wxRichTextEvent cmdEvent(
622 wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK,
623 GetId());
624 cmdEvent.SetEventObject(this);
625 cmdEvent.SetPosition(m_caretPosition+1);
626
627 if (!GetEventHandler()->ProcessEvent(cmdEvent))
628 {
629 SelectWord(GetCaretPosition()+1);
630 }
631 }
632
633 /// Middle-click
634 void wxRichTextCtrl::OnMiddleClick(wxMouseEvent& event)
635 {
636 wxRichTextEvent cmdEvent(
637 wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK,
638 GetId());
639 cmdEvent.SetEventObject(this);
640 cmdEvent.SetPosition(m_caretPosition+1);
641
642 if (!GetEventHandler()->ProcessEvent(cmdEvent))
643 event.Skip();
644 }
645
646 /// Key press
647 void wxRichTextCtrl::OnChar(wxKeyEvent& event)
648 {
649 int flags = 0;
650 if (event.CmdDown())
651 flags |= wxRICHTEXT_CTRL_DOWN;
652 if (event.ShiftDown())
653 flags |= wxRICHTEXT_SHIFT_DOWN;
654 if (event.AltDown())
655 flags |= wxRICHTEXT_ALT_DOWN;
656
657 if (event.GetKeyCode() == WXK_LEFT ||
658 event.GetKeyCode() == WXK_RIGHT ||
659 event.GetKeyCode() == WXK_UP ||
660 event.GetKeyCode() == WXK_DOWN ||
661 event.GetKeyCode() == WXK_HOME ||
662 event.GetKeyCode() == WXK_PAGEUP ||
663 event.GetKeyCode() == WXK_PAGEDOWN ||
664 event.GetKeyCode() == WXK_END ||
665
666 event.GetKeyCode() == WXK_NUMPAD_LEFT ||
667 event.GetKeyCode() == WXK_NUMPAD_RIGHT ||
668 event.GetKeyCode() == WXK_NUMPAD_UP ||
669 event.GetKeyCode() == WXK_NUMPAD_DOWN ||
670 event.GetKeyCode() == WXK_NUMPAD_HOME ||
671 event.GetKeyCode() == WXK_NUMPAD_PAGEUP ||
672 event.GetKeyCode() == WXK_NUMPAD_PAGEDOWN ||
673 event.GetKeyCode() == WXK_NUMPAD_END)
674 {
675 KeyboardNavigate(event.GetKeyCode(), flags);
676 return;
677 }
678
679 // all the other keys modify the controls contents which shouldn't be
680 // possible if we're read-only
681 if ( !IsEditable() )
682 {
683 event.Skip();
684 return;
685 }
686
687 if (event.GetKeyCode() == WXK_RETURN)
688 {
689 SetDefaultStyleToCursorStyle();
690 BeginBatchUndo(_("Insert Text"));
691
692 long newPos = m_caretPosition;
693
694 DeleteSelectedContent(& newPos);
695
696 if (event.ShiftDown())
697 {
698 wxString text;
699 text = wxRichTextLineBreakChar;
700 GetBuffer().InsertTextWithUndo(newPos+1, text, this);
701 }
702 else
703 GetBuffer().InsertNewlineWithUndo(newPos+1, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE|wxRICHTEXT_INSERT_INTERACTIVE);
704
705 EndBatchUndo();
706
707 ScrollIntoView(m_caretPosition, WXK_RIGHT);
708
709 wxRichTextEvent cmdEvent(
710 wxEVT_COMMAND_RICHTEXT_RETURN,
711 GetId());
712 cmdEvent.SetEventObject(this);
713 cmdEvent.SetFlags(flags);
714 cmdEvent.SetPosition(newPos+1);
715
716 if (!GetEventHandler()->ProcessEvent(cmdEvent))
717 {
718 // Generate conventional event
719 wxCommandEvent textEvent(wxEVT_COMMAND_TEXT_ENTER, GetId());
720 InitCommandEvent(textEvent);
721
722 GetEventHandler()->ProcessEvent(textEvent);
723 }
724 Update();
725 }
726 else if (event.GetKeyCode() == WXK_BACK)
727 {
728 BeginBatchUndo(_("Delete Text"));
729
730 // Submit range in character positions, which are greater than caret positions,
731 // so subtract 1 for deleted character and add 1 for conversion to character position.
732 if (m_caretPosition > -1 && !HasSelection())
733 {
734 bool processed = false;
735 if (event.CmdDown())
736 {
737 long pos = wxRichTextCtrl::FindNextWordPosition(-1);
738 if (pos != -1 && (pos < m_caretPosition))
739 {
740 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(pos+1, m_caretPosition), this);
741 processed = true;
742 }
743 }
744
745 if (!processed)
746 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(m_caretPosition, m_caretPosition), this);
747 }
748 else
749 DeleteSelectedContent();
750
751 EndBatchUndo();
752
753 if (GetLastPosition() == -1)
754 {
755 GetBuffer().Reset();
756
757 m_caretPosition = -1;
758 PositionCaret();
759 }
760
761 ScrollIntoView(m_caretPosition, WXK_LEFT);
762
763 wxRichTextEvent cmdEvent(
764 wxEVT_COMMAND_RICHTEXT_DELETE,
765 GetId());
766 cmdEvent.SetEventObject(this);
767 cmdEvent.SetFlags(flags);
768 cmdEvent.SetPosition(m_caretPosition+1);
769 GetEventHandler()->ProcessEvent(cmdEvent);
770
771 Update();
772 }
773 else if (event.GetKeyCode() == WXK_DELETE)
774 {
775 BeginBatchUndo(_("Delete Text"));
776
777 // Submit range in character positions, which are greater than caret positions,
778 if (m_caretPosition < GetBuffer().GetRange().GetEnd()+1 && !HasSelection())
779 {
780 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(m_caretPosition+1, m_caretPosition+1), this);
781 }
782 else
783 DeleteSelectedContent();
784
785 EndBatchUndo();
786
787 if (GetLastPosition() == -1)
788 {
789 GetBuffer().Reset();
790
791 m_caretPosition = -1;
792 PositionCaret();
793 }
794
795 wxRichTextEvent cmdEvent(
796 wxEVT_COMMAND_RICHTEXT_DELETE,
797 GetId());
798 cmdEvent.SetEventObject(this);
799 cmdEvent.SetFlags(flags);
800 cmdEvent.SetPosition(m_caretPosition+1);
801 GetEventHandler()->ProcessEvent(cmdEvent);
802
803 Update();
804 }
805 else
806 {
807 long keycode = event.GetKeyCode();
808 switch ( keycode )
809 {
810 case WXK_ESCAPE:
811 case WXK_DELETE:
812 case WXK_START:
813 case WXK_LBUTTON:
814 case WXK_RBUTTON:
815 case WXK_CANCEL:
816 case WXK_MBUTTON:
817 case WXK_CLEAR:
818 case WXK_SHIFT:
819 case WXK_ALT:
820 case WXK_CONTROL:
821 case WXK_MENU:
822 case WXK_PAUSE:
823 case WXK_CAPITAL:
824 case WXK_END:
825 case WXK_HOME:
826 case WXK_LEFT:
827 case WXK_UP:
828 case WXK_RIGHT:
829 case WXK_DOWN:
830 case WXK_SELECT:
831 case WXK_PRINT:
832 case WXK_EXECUTE:
833 case WXK_SNAPSHOT:
834 case WXK_INSERT:
835 case WXK_HELP:
836 case WXK_NUMPAD0:
837 case WXK_NUMPAD1:
838 case WXK_NUMPAD2:
839 case WXK_NUMPAD3:
840 case WXK_NUMPAD4:
841 case WXK_NUMPAD5:
842 case WXK_NUMPAD6:
843 case WXK_NUMPAD7:
844 case WXK_NUMPAD8:
845 case WXK_NUMPAD9:
846 case WXK_MULTIPLY:
847 case WXK_ADD:
848 case WXK_SEPARATOR:
849 case WXK_SUBTRACT:
850 case WXK_DECIMAL:
851 case WXK_DIVIDE:
852 case WXK_F1:
853 case WXK_F2:
854 case WXK_F3:
855 case WXK_F4:
856 case WXK_F5:
857 case WXK_F6:
858 case WXK_F7:
859 case WXK_F8:
860 case WXK_F9:
861 case WXK_F10:
862 case WXK_F11:
863 case WXK_F12:
864 case WXK_F13:
865 case WXK_F14:
866 case WXK_F15:
867 case WXK_F16:
868 case WXK_F17:
869 case WXK_F18:
870 case WXK_F19:
871 case WXK_F20:
872 case WXK_F21:
873 case WXK_F22:
874 case WXK_F23:
875 case WXK_F24:
876 case WXK_NUMLOCK:
877 case WXK_SCROLL:
878 case WXK_PAGEUP:
879 case WXK_PAGEDOWN:
880 case WXK_NUMPAD_SPACE:
881 case WXK_NUMPAD_TAB:
882 case WXK_NUMPAD_ENTER:
883 case WXK_NUMPAD_F1:
884 case WXK_NUMPAD_F2:
885 case WXK_NUMPAD_F3:
886 case WXK_NUMPAD_F4:
887 case WXK_NUMPAD_HOME:
888 case WXK_NUMPAD_LEFT:
889 case WXK_NUMPAD_UP:
890 case WXK_NUMPAD_RIGHT:
891 case WXK_NUMPAD_DOWN:
892 case WXK_NUMPAD_PAGEUP:
893 case WXK_NUMPAD_PAGEDOWN:
894 case WXK_NUMPAD_END:
895 case WXK_NUMPAD_BEGIN:
896 case WXK_NUMPAD_INSERT:
897 case WXK_NUMPAD_DELETE:
898 case WXK_NUMPAD_EQUAL:
899 case WXK_NUMPAD_MULTIPLY:
900 case WXK_NUMPAD_ADD:
901 case WXK_NUMPAD_SEPARATOR:
902 case WXK_NUMPAD_SUBTRACT:
903 case WXK_NUMPAD_DECIMAL:
904 case WXK_WINDOWS_LEFT:
905 {
906 event.Skip();
907 return;
908 }
909
910 default:
911 {
912 if (event.CmdDown() || event.AltDown())
913 {
914 event.Skip();
915 return;
916 }
917
918 wxRichTextEvent cmdEvent(
919 wxEVT_COMMAND_RICHTEXT_CHARACTER,
920 GetId());
921 cmdEvent.SetEventObject(this);
922 cmdEvent.SetFlags(flags);
923 #if wxUSE_UNICODE
924 cmdEvent.SetCharacter(event.GetUnicodeKey());
925 #else
926 cmdEvent.SetCharacter((wxChar) keycode);
927 #endif
928 cmdEvent.SetPosition(m_caretPosition+1);
929
930 if (keycode == wxT('\t'))
931 {
932 // See if we need to promote or demote the selection or paragraph at the cursor
933 // position, instead of inserting a tab.
934 long pos = GetAdjustedCaretPosition(GetCaretPosition());
935 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(pos);
936 if (para && para->GetRange().GetStart() == pos && para->GetAttributes().HasListStyleName())
937 {
938 wxRichTextRange range;
939 if (HasSelection())
940 range = GetSelectionRange();
941 else
942 range = para->GetRange().FromInternal();
943
944 int promoteBy = event.ShiftDown() ? 1 : -1;
945
946 PromoteList(promoteBy, range, NULL);
947
948 GetEventHandler()->ProcessEvent(cmdEvent);
949
950 return;
951 }
952 }
953
954 SetDefaultStyleToCursorStyle();
955 BeginBatchUndo(_("Insert Text"));
956
957 long newPos = m_caretPosition;
958 DeleteSelectedContent(& newPos);
959
960 #if wxUSE_UNICODE
961 wxString str = event.GetUnicodeKey();
962 #else
963 wxString str = (wxChar) event.GetKeyCode();
964 #endif
965 GetBuffer().InsertTextWithUndo(newPos+1, str, this, 0);
966
967 EndBatchUndo();
968
969 ScrollIntoView(m_caretPosition, WXK_RIGHT);
970
971 GetEventHandler()->ProcessEvent(cmdEvent);
972
973 Update();
974 }
975 }
976 }
977 }
978
979 /// Delete content if there is a selection, e.g. when pressing a key.
980 bool wxRichTextCtrl::DeleteSelectedContent(long* newPos)
981 {
982 if (HasSelection())
983 {
984 long pos = m_selectionRange.GetStart();
985 GetBuffer().DeleteRangeWithUndo(m_selectionRange, this);
986 m_selectionRange.SetRange(-2, -2);
987
988 if (newPos)
989 *newPos = pos-1;
990 return true;
991 }
992 else
993 return false;
994 }
995
996 /// Keyboard navigation
997
998 /*
999
1000 Left: left one character
1001 Right: right one character
1002 Up: up one line
1003 Down: down one line
1004 Ctrl-Left: left one word
1005 Ctrl-Right: right one word
1006 Ctrl-Up: previous paragraph start
1007 Ctrl-Down: next start of paragraph
1008 Home: start of line
1009 End: end of line
1010 Ctrl-Home: start of document
1011 Ctrl-End: end of document
1012 Page-Up: Up a screen
1013 Page-Down: Down a screen
1014
1015 Maybe:
1016
1017 Ctrl-Alt-PgUp: Start of window
1018 Ctrl-Alt-PgDn: End of window
1019 F8: Start selection mode
1020 Esc: End selection mode
1021
1022 Adding Shift does the above but starts/extends selection.
1023
1024
1025 */
1026
1027 bool wxRichTextCtrl::KeyboardNavigate(int keyCode, int flags)
1028 {
1029 bool success = false;
1030
1031 if (keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT)
1032 {
1033 if (flags & wxRICHTEXT_CTRL_DOWN)
1034 success = WordRight(1, flags);
1035 else
1036 success = MoveRight(1, flags);
1037 }
1038 else if (keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT)
1039 {
1040 if (flags & wxRICHTEXT_CTRL_DOWN)
1041 success = WordLeft(1, flags);
1042 else
1043 success = MoveLeft(1, flags);
1044 }
1045 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP)
1046 {
1047 if (flags & wxRICHTEXT_CTRL_DOWN)
1048 success = MoveToParagraphStart(flags);
1049 else
1050 success = MoveUp(1, flags);
1051 }
1052 else if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN)
1053 {
1054 if (flags & wxRICHTEXT_CTRL_DOWN)
1055 success = MoveToParagraphEnd(flags);
1056 else
1057 success = MoveDown(1, flags);
1058 }
1059 else if (keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP)
1060 {
1061 success = PageUp(1, flags);
1062 }
1063 else if (keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
1064 {
1065 success = PageDown(1, flags);
1066 }
1067 else if (keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME)
1068 {
1069 if (flags & wxRICHTEXT_CTRL_DOWN)
1070 success = MoveHome(flags);
1071 else
1072 success = MoveToLineStart(flags);
1073 }
1074 else if (keyCode == WXK_END || keyCode == WXK_NUMPAD_END)
1075 {
1076 if (flags & wxRICHTEXT_CTRL_DOWN)
1077 success = MoveEnd(flags);
1078 else
1079 success = MoveToLineEnd(flags);
1080 }
1081
1082 if (success)
1083 {
1084 ScrollIntoView(m_caretPosition, keyCode);
1085 }
1086
1087 return success;
1088 }
1089
1090 /// Extend the selection. Selections are in caret positions.
1091 bool wxRichTextCtrl::ExtendSelection(long oldPos, long newPos, int flags)
1092 {
1093 if (flags & wxRICHTEXT_SHIFT_DOWN)
1094 {
1095 wxRichTextRange oldSelection = m_selectionRange;
1096
1097 // If not currently selecting, start selecting
1098 if (m_selectionRange.GetStart() == -2)
1099 {
1100 m_selectionAnchor = oldPos;
1101
1102 if (oldPos > newPos)
1103 m_selectionRange.SetRange(newPos+1, oldPos);
1104 else
1105 m_selectionRange.SetRange(oldPos+1, newPos);
1106 }
1107 else
1108 {
1109 // Always ensure that the selection range start is greater than
1110 // the end.
1111 if (newPos > m_selectionAnchor)
1112 m_selectionRange.SetRange(m_selectionAnchor+1, newPos);
1113 else
1114 m_selectionRange.SetRange(newPos+1, m_selectionAnchor);
1115 }
1116
1117 RefreshForSelectionChange(oldSelection, m_selectionRange);
1118
1119 if (m_selectionRange.GetStart() > m_selectionRange.GetEnd())
1120 {
1121 wxLogDebug(wxT("Strange selection range"));
1122 }
1123
1124 return true;
1125 }
1126 else
1127 return false;
1128 }
1129
1130 /// Scroll into view, returning true if we scrolled.
1131 /// This takes a _caret_ position.
1132 bool wxRichTextCtrl::ScrollIntoView(long position, int keyCode)
1133 {
1134 wxRichTextLine* line = GetVisibleLineForCaretPosition(position);
1135
1136 if (!line)
1137 return false;
1138
1139 int ppuX, ppuY;
1140 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1141
1142 int startXUnits, startYUnits;
1143 GetViewStart(& startXUnits, & startYUnits);
1144 int startY = startYUnits * ppuY;
1145
1146 int sx = 0, sy = 0;
1147 GetVirtualSize(& sx, & sy);
1148 int sxUnits = 0;
1149 int syUnits = 0;
1150 if (ppuY != 0)
1151 syUnits = sy/ppuY;
1152
1153 wxRect rect = line->GetRect();
1154
1155 bool scrolled = false;
1156
1157 wxSize clientSize = GetClientSize();
1158
1159 // Going down
1160 if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN ||
1161 keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT ||
1162 keyCode == WXK_END || keyCode == WXK_NUMPAD_END ||
1163 keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
1164 {
1165 if ((rect.y + rect.height) > (clientSize.y + startY))
1166 {
1167 // Make it scroll so this item is at the bottom
1168 // of the window
1169 int y = rect.y - (clientSize.y - rect.height);
1170 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1171
1172 // If we're still off the screen, scroll another line down
1173 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1174 yUnits ++;
1175
1176 if (startYUnits != yUnits)
1177 {
1178 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1179 scrolled = true;
1180 }
1181 }
1182 else if (rect.y < startY)
1183 {
1184 // Make it scroll so this item is at the top
1185 // of the window
1186 int y = rect.y ;
1187 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1188
1189 if (startYUnits != yUnits)
1190 {
1191 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1192 scrolled = true;
1193 }
1194 }
1195 }
1196 // Going up
1197 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP ||
1198 keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT ||
1199 keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME ||
1200 keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP )
1201 {
1202 if (rect.y < startY)
1203 {
1204 // Make it scroll so this item is at the top
1205 // of the window
1206 int y = rect.y ;
1207 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1208
1209 if (startYUnits != yUnits)
1210 {
1211 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1212 scrolled = true;
1213 }
1214 }
1215 else if ((rect.y + rect.height) > (clientSize.y + startY))
1216 {
1217 // Make it scroll so this item is at the bottom
1218 // of the window
1219 int y = rect.y - (clientSize.y - rect.height);
1220 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1221
1222 // If we're still off the screen, scroll another line down
1223 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1224 yUnits ++;
1225
1226 if (startYUnits != yUnits)
1227 {
1228 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1229 scrolled = true;
1230 }
1231 }
1232 }
1233
1234 #if !wxRICHTEXT_USE_OWN_CARET
1235 if (scrolled)
1236 #endif
1237 PositionCaret();
1238
1239 return scrolled;
1240 }
1241
1242 /// Is the given position visible on the screen?
1243 bool wxRichTextCtrl::IsPositionVisible(long pos) const
1244 {
1245 wxRichTextLine* line = GetVisibleLineForCaretPosition(pos-1);
1246
1247 if (!line)
1248 return false;
1249
1250 int ppuX, ppuY;
1251 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1252
1253 int startX, startY;
1254 GetViewStart(& startX, & startY);
1255 startX = 0;
1256 startY = startY * ppuY;
1257
1258 wxRect rect = line->GetRect();
1259 wxSize clientSize = GetClientSize();
1260
1261 return (rect.GetBottom() > startY) && (rect.GetTop() < (startY + clientSize.y));
1262 }
1263
1264 void wxRichTextCtrl::SetCaretPosition(long position, bool showAtLineStart)
1265 {
1266 m_caretPosition = position;
1267 m_caretAtLineStart = showAtLineStart;
1268 }
1269
1270 /// Move caret one visual step forward: this may mean setting a flag
1271 /// and keeping the same position if we're going from the end of one line
1272 /// to the start of the next, which may be the exact same caret position.
1273 void wxRichTextCtrl::MoveCaretForward(long oldPosition)
1274 {
1275 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(oldPosition);
1276
1277 // Only do the check if we're not at the end of the paragraph (where things work OK
1278 // anyway)
1279 if (para && (oldPosition != para->GetRange().GetEnd() - 1))
1280 {
1281 wxRichTextLine* line = GetBuffer().GetLineAtPosition(oldPosition);
1282
1283 if (line)
1284 {
1285 wxRichTextRange lineRange = line->GetAbsoluteRange();
1286
1287 // We're at the end of a line. See whether we need to
1288 // stay at the same actual caret position but change visual
1289 // position, or not.
1290 if (oldPosition == lineRange.GetEnd())
1291 {
1292 if (m_caretAtLineStart)
1293 {
1294 // We're already at the start of the line, so actually move on now.
1295 m_caretPosition = oldPosition + 1;
1296 m_caretAtLineStart = false;
1297 }
1298 else
1299 {
1300 // We're showing at the end of the line, so keep to
1301 // the same position but indicate that we're to show
1302 // at the start of the next line.
1303 m_caretPosition = oldPosition;
1304 m_caretAtLineStart = true;
1305 }
1306 return;
1307 }
1308 }
1309 }
1310 m_caretPosition ++;
1311 }
1312
1313 /// Move caret one visual step backward: this may mean setting a flag
1314 /// and keeping the same position if we're going from the end of one line
1315 /// to the start of the next, which may be the exact same caret position.
1316 void wxRichTextCtrl::MoveCaretBack(long oldPosition)
1317 {
1318 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(oldPosition);
1319
1320 // Only do the check if we're not at the start of the paragraph (where things work OK
1321 // anyway)
1322 if (para && (oldPosition != para->GetRange().GetStart()))
1323 {
1324 wxRichTextLine* line = GetBuffer().GetLineAtPosition(oldPosition);
1325
1326 if (line)
1327 {
1328 wxRichTextRange lineRange = line->GetAbsoluteRange();
1329
1330 // We're at the start of a line. See whether we need to
1331 // stay at the same actual caret position but change visual
1332 // position, or not.
1333 if (oldPosition == lineRange.GetStart())
1334 {
1335 m_caretPosition = oldPosition-1;
1336 m_caretAtLineStart = true;
1337 return;
1338 }
1339 else if (oldPosition == lineRange.GetEnd())
1340 {
1341 if (m_caretAtLineStart)
1342 {
1343 // We're at the start of the line, so keep the same caret position
1344 // but clear the start-of-line flag.
1345 m_caretPosition = oldPosition;
1346 m_caretAtLineStart = false;
1347 }
1348 else
1349 {
1350 // We're showing at the end of the line, so go back
1351 // to the previous character position.
1352 m_caretPosition = oldPosition - 1;
1353 }
1354 return;
1355 }
1356 }
1357 }
1358 m_caretPosition --;
1359 }
1360
1361 /// Move right
1362 bool wxRichTextCtrl::MoveRight(int noPositions, int flags)
1363 {
1364 long endPos = GetBuffer().GetRange().GetEnd();
1365
1366 if (m_caretPosition + noPositions < endPos)
1367 {
1368 long oldPos = m_caretPosition;
1369 long newPos = m_caretPosition + noPositions;
1370
1371 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1372 if (!extendSel)
1373 SelectNone();
1374
1375 // Determine by looking at oldPos and m_caretPosition whether
1376 // we moved from the end of a line to the start of the next line, in which case
1377 // we want to adjust the caret position such that it is positioned at the
1378 // start of the next line, rather than jumping past the first character of the
1379 // line.
1380 if (noPositions == 1 && !extendSel)
1381 MoveCaretForward(oldPos);
1382 else
1383 SetCaretPosition(newPos);
1384
1385 PositionCaret();
1386
1387 return true;
1388 }
1389 else
1390 return false;
1391 }
1392
1393 /// Move left
1394 bool wxRichTextCtrl::MoveLeft(int noPositions, int flags)
1395 {
1396 long startPos = -1;
1397
1398 if (m_caretPosition > startPos - noPositions + 1)
1399 {
1400 long oldPos = m_caretPosition;
1401 long newPos = m_caretPosition - noPositions;
1402 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1403 if (!extendSel)
1404 SelectNone();
1405
1406 if (noPositions == 1 && !extendSel)
1407 MoveCaretBack(oldPos);
1408 else
1409 SetCaretPosition(newPos);
1410
1411 PositionCaret();
1412
1413 return true;
1414 }
1415 else
1416 return false;
1417 }
1418
1419 /// Move up
1420 bool wxRichTextCtrl::MoveUp(int noLines, int flags)
1421 {
1422 return MoveDown(- noLines, flags);
1423 }
1424
1425 /// Move up
1426 bool wxRichTextCtrl::MoveDown(int noLines, int flags)
1427 {
1428 if (!GetCaret())
1429 return false;
1430
1431 long lineNumber = GetBuffer().GetVisibleLineNumber(m_caretPosition, true, m_caretAtLineStart);
1432 wxPoint pt = GetCaret()->GetPosition();
1433 long newLine = lineNumber + noLines;
1434
1435 if (lineNumber != -1)
1436 {
1437 if (noLines > 0)
1438 {
1439 long lastLine = GetBuffer().GetVisibleLineNumber(GetBuffer().GetRange().GetEnd());
1440
1441 if (newLine > lastLine)
1442 return false;
1443 }
1444 else
1445 {
1446 if (newLine < 0)
1447 return false;
1448 }
1449 }
1450
1451 wxRichTextLine* lineObj = GetBuffer().GetLineForVisibleLineNumber(newLine);
1452 if (lineObj)
1453 {
1454 pt.y = lineObj->GetAbsolutePosition().y + 2;
1455 }
1456 else
1457 return false;
1458
1459 long newPos = 0;
1460 wxClientDC dc(this);
1461 PrepareDC(dc);
1462 dc.SetFont(GetFont());
1463
1464 int hitTest = GetBuffer().HitTest(dc, pt, newPos);
1465
1466 if (hitTest != wxRICHTEXT_HITTEST_NONE)
1467 {
1468 // If end of previous line, and hitTest is wxRICHTEXT_HITTEST_BEFORE,
1469 // we want to be at the end of the last line but with m_caretAtLineStart set to true,
1470 // so we view the caret at the start of the line.
1471 bool caretLineStart = false;
1472 if (hitTest & wxRICHTEXT_HITTEST_BEFORE)
1473 {
1474 wxRichTextLine* thisLine = GetBuffer().GetLineAtPosition(newPos-1);
1475 wxRichTextRange lineRange;
1476 if (thisLine)
1477 lineRange = thisLine->GetAbsoluteRange();
1478
1479 if (thisLine && (newPos-1) == lineRange.GetEnd())
1480 {
1481 newPos --;
1482 caretLineStart = true;
1483 }
1484 else
1485 {
1486 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(newPos);
1487 if (para && para->GetRange().GetStart() == newPos)
1488 newPos --;
1489 }
1490 }
1491
1492 long newSelEnd = newPos;
1493
1494 bool extendSel = ExtendSelection(m_caretPosition, newSelEnd, flags);
1495 if (!extendSel)
1496 SelectNone();
1497
1498 SetCaretPosition(newPos, caretLineStart);
1499 PositionCaret();
1500
1501 return true;
1502 }
1503
1504 return false;
1505 }
1506
1507 /// Move to the end of the paragraph
1508 bool wxRichTextCtrl::MoveToParagraphEnd(int flags)
1509 {
1510 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(m_caretPosition, true);
1511 if (para)
1512 {
1513 long newPos = para->GetRange().GetEnd() - 1;
1514 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1515 if (!extendSel)
1516 SelectNone();
1517
1518 SetCaretPosition(newPos);
1519 PositionCaret();
1520
1521 return true;
1522 }
1523
1524 return false;
1525 }
1526
1527 /// Move to the start of the paragraph
1528 bool wxRichTextCtrl::MoveToParagraphStart(int flags)
1529 {
1530 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(m_caretPosition, true);
1531 if (para)
1532 {
1533 long newPos = para->GetRange().GetStart() - 1;
1534 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1535 if (!extendSel)
1536 SelectNone();
1537
1538 SetCaretPosition(newPos);
1539 PositionCaret();
1540
1541 return true;
1542 }
1543
1544 return false;
1545 }
1546
1547 /// Move to the end of the line
1548 bool wxRichTextCtrl::MoveToLineEnd(int flags)
1549 {
1550 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1551
1552 if (line)
1553 {
1554 wxRichTextRange lineRange = line->GetAbsoluteRange();
1555 long newPos = lineRange.GetEnd();
1556 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1557 if (!extendSel)
1558 SelectNone();
1559
1560 SetCaretPosition(newPos);
1561 PositionCaret();
1562
1563 return true;
1564 }
1565
1566 return false;
1567 }
1568
1569 /// Move to the start of the line
1570 bool wxRichTextCtrl::MoveToLineStart(int flags)
1571 {
1572 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1573 if (line)
1574 {
1575 wxRichTextRange lineRange = line->GetAbsoluteRange();
1576 long newPos = lineRange.GetStart()-1;
1577
1578 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1579 if (!extendSel)
1580 SelectNone();
1581
1582 wxRichTextParagraph* para = GetBuffer().GetParagraphForLine(line);
1583
1584 SetCaretPosition(newPos, para->GetRange().GetStart() != lineRange.GetStart());
1585 PositionCaret();
1586
1587 return true;
1588 }
1589
1590 return false;
1591 }
1592
1593 /// Move to the start of the buffer
1594 bool wxRichTextCtrl::MoveHome(int flags)
1595 {
1596 if (m_caretPosition != -1)
1597 {
1598 bool extendSel = ExtendSelection(m_caretPosition, -1, flags);
1599 if (!extendSel)
1600 SelectNone();
1601
1602 SetCaretPosition(-1);
1603 PositionCaret();
1604
1605 return true;
1606 }
1607 else
1608 return false;
1609 }
1610
1611 /// Move to the end of the buffer
1612 bool wxRichTextCtrl::MoveEnd(int flags)
1613 {
1614 long endPos = GetBuffer().GetRange().GetEnd()-1;
1615
1616 if (m_caretPosition != endPos)
1617 {
1618 bool extendSel = ExtendSelection(m_caretPosition, endPos, flags);
1619 if (!extendSel)
1620 SelectNone();
1621
1622 SetCaretPosition(endPos);
1623 PositionCaret();
1624
1625 return true;
1626 }
1627 else
1628 return false;
1629 }
1630
1631 /// Move noPages pages up
1632 bool wxRichTextCtrl::PageUp(int noPages, int flags)
1633 {
1634 return PageDown(- noPages, flags);
1635 }
1636
1637 /// Move noPages pages down
1638 bool wxRichTextCtrl::PageDown(int noPages, int flags)
1639 {
1640 // Calculate which line occurs noPages * screen height further down.
1641 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1642 if (line)
1643 {
1644 wxSize clientSize = GetClientSize();
1645 int newY = line->GetAbsolutePosition().y + noPages*clientSize.y;
1646
1647 wxRichTextLine* newLine = GetBuffer().GetLineAtYPosition(newY);
1648 if (newLine)
1649 {
1650 wxRichTextRange lineRange = newLine->GetAbsoluteRange();
1651 long pos = lineRange.GetStart()-1;
1652 if (pos != m_caretPosition)
1653 {
1654 wxRichTextParagraph* para = GetBuffer().GetParagraphForLine(newLine);
1655
1656 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1657 if (!extendSel)
1658 SelectNone();
1659
1660 SetCaretPosition(pos, para->GetRange().GetStart() != lineRange.GetStart());
1661 PositionCaret();
1662
1663 return true;
1664 }
1665 }
1666 }
1667
1668 return false;
1669 }
1670
1671 static bool wxRichTextCtrlIsWhitespace(const wxString& str)
1672 {
1673 return str == wxT(" ") || str == wxT("\t");
1674 }
1675
1676 // Finds the caret position for the next word
1677 long wxRichTextCtrl::FindNextWordPosition(int direction) const
1678 {
1679 long endPos = GetBuffer().GetRange().GetEnd();
1680
1681 if (direction > 0)
1682 {
1683 long i = m_caretPosition+1+direction; // +1 for conversion to character pos
1684
1685 // First skip current text to space
1686 while (i < endPos && i > -1)
1687 {
1688 // i is in character, not caret positions
1689 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1690 wxRichTextLine* line = GetBuffer().GetLineAtPosition(i, false);
1691 if (line && (i == line->GetAbsoluteRange().GetEnd()))
1692 {
1693 break;
1694 }
1695 else if (!wxRichTextCtrlIsWhitespace(text) && !text.empty())
1696 i += direction;
1697 else
1698 {
1699 break;
1700 }
1701 }
1702 while (i < endPos && i > -1)
1703 {
1704 // i is in character, not caret positions
1705 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1706 wxRichTextLine* line = GetBuffer().GetLineAtPosition(i, false);
1707 if (line && (i == line->GetAbsoluteRange().GetEnd()))
1708 return wxMax(-1, i);
1709
1710 if (text.empty()) // End of paragraph, or maybe an image
1711 return wxMax(-1, i - 1);
1712 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
1713 i += direction;
1714 else
1715 {
1716 // Convert to caret position
1717 return wxMax(-1, i - 1);
1718 }
1719 }
1720 if (i >= endPos)
1721 return endPos-1;
1722 return i-1;
1723 }
1724 else
1725 {
1726 long i = m_caretPosition;
1727
1728 // First skip white space
1729 while (i < endPos && i > -1)
1730 {
1731 // i is in character, not caret positions
1732 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1733 wxRichTextLine* line = GetBuffer().GetLineAtPosition(i, false);
1734
1735 if (text.empty() || (line && (i == line->GetAbsoluteRange().GetStart()))) // End of paragraph, or maybe an image
1736 break;
1737 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
1738 i += direction;
1739 else
1740 break;
1741 }
1742 // Next skip current text to space
1743 while (i < endPos && i > -1)
1744 {
1745 // i is in character, not caret positions
1746 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1747 wxRichTextLine* line = GetBuffer().GetLineAtPosition(i, false);
1748 if (line && line->GetAbsoluteRange().GetStart() == i)
1749 return i-1;
1750
1751 if (!wxRichTextCtrlIsWhitespace(text) /* && !text.empty() */)
1752 i += direction;
1753 else
1754 {
1755 return i;
1756 }
1757 }
1758 if (i < -1)
1759 return -1;
1760 return i;
1761 }
1762 }
1763
1764 /// Move n words left
1765 bool wxRichTextCtrl::WordLeft(int WXUNUSED(n), int flags)
1766 {
1767 long pos = FindNextWordPosition(-1);
1768 if (pos != m_caretPosition)
1769 {
1770 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(pos, true);
1771
1772 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1773 if (!extendSel)
1774 SelectNone();
1775
1776 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
1777 PositionCaret();
1778
1779 return true;
1780 }
1781
1782 return false;
1783 }
1784
1785 /// Move n words right
1786 bool wxRichTextCtrl::WordRight(int WXUNUSED(n), int flags)
1787 {
1788 long pos = FindNextWordPosition(1);
1789 if (pos != m_caretPosition)
1790 {
1791 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(pos, true);
1792
1793 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1794 if (!extendSel)
1795 SelectNone();
1796
1797 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
1798 PositionCaret();
1799
1800 return true;
1801 }
1802
1803 return false;
1804 }
1805
1806 /// Sizing
1807 void wxRichTextCtrl::OnSize(wxSizeEvent& event)
1808 {
1809 // Only do sizing optimization for large buffers
1810 if (GetBuffer().GetRange().GetEnd() > m_delayedLayoutThreshold)
1811 {
1812 m_fullLayoutRequired = true;
1813 m_fullLayoutTime = wxGetLocalTimeMillis();
1814 m_fullLayoutSavedPosition = GetFirstVisiblePosition();
1815 LayoutContent(true /* onlyVisibleRect */);
1816 }
1817 else
1818 GetBuffer().Invalidate(wxRICHTEXT_ALL);
1819
1820 #if wxRICHTEXT_BUFFERED_PAINTING
1821 RecreateBuffer();
1822 #endif
1823
1824 event.Skip();
1825 }
1826
1827
1828 /// Idle-time processing
1829 void wxRichTextCtrl::OnIdle(wxIdleEvent& event)
1830 {
1831 #if wxRICHTEXT_USE_OWN_CARET
1832 if (((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
1833 {
1834 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate(false);
1835 PositionCaret();
1836 GetCaret()->Show();
1837 }
1838 #endif
1839
1840 const int layoutInterval = wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL;
1841
1842 if (m_fullLayoutRequired && (wxGetLocalTimeMillis() > (m_fullLayoutTime + layoutInterval)))
1843 {
1844 m_fullLayoutRequired = false;
1845 m_fullLayoutTime = 0;
1846 GetBuffer().Invalidate(wxRICHTEXT_ALL);
1847 ShowPosition(m_fullLayoutSavedPosition);
1848 Refresh(false);
1849 }
1850
1851 if (m_caretPositionForDefaultStyle != -2)
1852 {
1853 // If the caret position has changed, no longer reflect the default style
1854 // in the UI.
1855 if (GetCaretPosition() != m_caretPositionForDefaultStyle)
1856 m_caretPositionForDefaultStyle = -2;
1857 }
1858
1859 event.Skip();
1860 }
1861
1862 /// Scrolling
1863 void wxRichTextCtrl::OnScroll(wxScrollWinEvent& event)
1864 {
1865 #if wxRICHTEXT_USE_OWN_CARET
1866 if (!((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
1867 {
1868 GetCaret()->Hide();
1869 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate();
1870 }
1871 #endif
1872
1873 event.Skip();
1874 }
1875
1876 /// Set up scrollbars, e.g. after a resize
1877 void wxRichTextCtrl::SetupScrollbars(bool atTop)
1878 {
1879 if (IsFrozen())
1880 return;
1881
1882 if (GetBuffer().IsEmpty())
1883 {
1884 SetScrollbars(0, 0, 0, 0, 0, 0);
1885 return;
1886 }
1887
1888 // TODO: reimplement scrolling so we scroll by line, not by fixed number
1889 // of pixels. See e.g. wxVScrolledWindow for ideas.
1890 int pixelsPerUnit = 5;
1891 wxSize clientSize = GetClientSize();
1892
1893 int maxHeight = GetBuffer().GetCachedSize().y;
1894
1895 // Round up so we have at least maxHeight pixels
1896 int unitsY = (int) (((float)maxHeight/(float)pixelsPerUnit) + 0.5);
1897
1898 int startX = 0, startY = 0;
1899 if (!atTop)
1900 GetViewStart(& startX, & startY);
1901
1902 int maxPositionX = 0;
1903 int maxPositionY = (int) ((((float)(wxMax((unitsY*pixelsPerUnit) - clientSize.y, 0)))/((float)pixelsPerUnit)) + 0.5);
1904
1905 int newStartX = wxMin(maxPositionX, startX);
1906 int newStartY = wxMin(maxPositionY, startY);
1907
1908 int oldPPUX, oldPPUY;
1909 int oldStartX, oldStartY;
1910 int oldVirtualSizeX = 0, oldVirtualSizeY = 0;
1911 GetScrollPixelsPerUnit(& oldPPUX, & oldPPUY);
1912 GetViewStart(& oldStartX, & oldStartY);
1913 GetVirtualSize(& oldVirtualSizeX, & oldVirtualSizeY);
1914 if (oldPPUY > 0)
1915 oldVirtualSizeY /= oldPPUY;
1916
1917 if (oldPPUX == 0 && oldPPUY == pixelsPerUnit && oldVirtualSizeY == unitsY && oldStartX == newStartX && oldStartY == newStartY)
1918 return;
1919
1920 // Don't set scrollbars if there were none before, and there will be none now.
1921 if (oldPPUY != 0 && (oldVirtualSizeY < clientSize.y) && (unitsY*pixelsPerUnit < clientSize.y))
1922 return;
1923
1924 // Move to previous scroll position if
1925 // possible
1926 SetScrollbars(0, pixelsPerUnit, 0, unitsY, newStartX, newStartY);
1927 }
1928
1929 /// Paint the background
1930 void wxRichTextCtrl::PaintBackground(wxDC& dc)
1931 {
1932 wxColour backgroundColour = GetBackgroundColour();
1933 if (!backgroundColour.Ok())
1934 backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
1935
1936 // Clear the background
1937 dc.SetBrush(wxBrush(backgroundColour));
1938 dc.SetPen(*wxTRANSPARENT_PEN);
1939 wxRect windowRect(GetClientSize());
1940 windowRect.x -= 2; windowRect.y -= 2;
1941 windowRect.width += 4; windowRect.height += 4;
1942
1943 // We need to shift the rectangle to take into account
1944 // scrolling. Converting device to logical coordinates.
1945 CalcUnscrolledPosition(windowRect.x, windowRect.y, & windowRect.x, & windowRect.y);
1946 dc.DrawRectangle(windowRect);
1947 }
1948
1949 #if wxRICHTEXT_BUFFERED_PAINTING
1950 /// Recreate buffer bitmap if necessary
1951 bool wxRichTextCtrl::RecreateBuffer(const wxSize& size)
1952 {
1953 wxSize sz = size;
1954 if (sz == wxDefaultSize)
1955 sz = GetClientSize();
1956
1957 if (sz.x < 1 || sz.y < 1)
1958 return false;
1959
1960 if (!m_bufferBitmap.Ok() || m_bufferBitmap.GetWidth() < sz.x || m_bufferBitmap.GetHeight() < sz.y)
1961 m_bufferBitmap = wxBitmap(sz.x, sz.y);
1962 return m_bufferBitmap.Ok();
1963 }
1964 #endif
1965
1966 // ----------------------------------------------------------------------------
1967 // file IO functions
1968 // ----------------------------------------------------------------------------
1969
1970 bool wxRichTextCtrl::DoLoadFile(const wxString& filename, int fileType)
1971 {
1972 bool success = GetBuffer().LoadFile(filename, fileType);
1973 if (success)
1974 m_filename = filename;
1975
1976 DiscardEdits();
1977 SetInsertionPoint(0);
1978 LayoutContent();
1979 PositionCaret();
1980 SetupScrollbars(true);
1981 Refresh(false);
1982 wxTextCtrl::SendTextUpdatedEvent(this);
1983
1984 if (success)
1985 return true;
1986 else
1987 {
1988 wxLogError(_("File couldn't be loaded."));
1989
1990 return false;
1991 }
1992 }
1993
1994 bool wxRichTextCtrl::DoSaveFile(const wxString& filename, int fileType)
1995 {
1996 if (GetBuffer().SaveFile(filename, fileType))
1997 {
1998 m_filename = filename;
1999
2000 DiscardEdits();
2001
2002 return true;
2003 }
2004
2005 wxLogError(_("The text couldn't be saved."));
2006
2007 return false;
2008 }
2009
2010 // ----------------------------------------------------------------------------
2011 // wxRichTextCtrl specific functionality
2012 // ----------------------------------------------------------------------------
2013
2014 /// Add a new paragraph of text to the end of the buffer
2015 wxRichTextRange wxRichTextCtrl::AddParagraph(const wxString& text)
2016 {
2017 wxRichTextRange range = GetBuffer().AddParagraph(text);
2018 LayoutContent();
2019 return range;
2020 }
2021
2022 /// Add an image
2023 wxRichTextRange wxRichTextCtrl::AddImage(const wxImage& image)
2024 {
2025 wxRichTextRange range = GetBuffer().AddImage(image);
2026 LayoutContent();
2027 return range;
2028 }
2029
2030 // ----------------------------------------------------------------------------
2031 // selection and ranges
2032 // ----------------------------------------------------------------------------
2033
2034 void wxRichTextCtrl::SelectAll()
2035 {
2036 SetSelection(0, GetLastPosition()+1);
2037 m_selectionAnchor = -1;
2038 }
2039
2040 /// Select none
2041 void wxRichTextCtrl::SelectNone()
2042 {
2043 if (!(GetSelectionRange() == wxRichTextRange(-2, -2)))
2044 {
2045 wxRichTextRange oldSelection = m_selectionRange;
2046
2047 m_selectionRange = wxRichTextRange(-2, -2);
2048
2049 RefreshForSelectionChange(oldSelection, m_selectionRange);
2050 }
2051 m_selectionAnchor = -2;
2052 }
2053
2054 static bool wxIsWordDelimiter(const wxString& text)
2055 {
2056 return !text.IsEmpty() && !wxIsalnum(text[0]);
2057 }
2058
2059 /// Select the word at the given character position
2060 bool wxRichTextCtrl::SelectWord(long position)
2061 {
2062 if (position < 0 || position > GetBuffer().GetRange().GetEnd())
2063 return false;
2064
2065 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
2066 if (!para)
2067 return false;
2068
2069 if (position == para->GetRange().GetEnd())
2070 position --;
2071
2072 long positionStart = position;
2073 long positionEnd = position;
2074
2075 for (positionStart = position; positionStart >= para->GetRange().GetStart(); positionStart --)
2076 {
2077 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionStart, positionStart));
2078 if (wxIsWordDelimiter(text))
2079 {
2080 positionStart ++;
2081 break;
2082 }
2083 }
2084 if (positionStart < para->GetRange().GetStart())
2085 positionStart = para->GetRange().GetStart();
2086
2087 for (positionEnd = position; positionEnd < para->GetRange().GetEnd(); positionEnd ++)
2088 {
2089 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionEnd, positionEnd));
2090 if (wxIsWordDelimiter(text))
2091 {
2092 positionEnd --;
2093 break;
2094 }
2095 }
2096 if (positionEnd >= para->GetRange().GetEnd())
2097 positionEnd = para->GetRange().GetEnd();
2098
2099 if (positionEnd < positionStart)
2100 return false;
2101
2102 SetSelection(positionStart, positionEnd+1);
2103
2104 if (positionStart >= 0)
2105 {
2106 MoveCaret(positionStart-1, true);
2107 }
2108
2109 return true;
2110 }
2111
2112 wxString wxRichTextCtrl::GetStringSelection() const
2113 {
2114 long from, to;
2115 GetSelection(&from, &to);
2116
2117 return GetRange(from, to);
2118 }
2119
2120 // ----------------------------------------------------------------------------
2121 // hit testing
2122 // ----------------------------------------------------------------------------
2123
2124 wxTextCtrlHitTestResult
2125 wxRichTextCtrl::HitTest(const wxPoint& pt, wxTextCoord *x, wxTextCoord *y) const
2126 {
2127 // implement in terms of the other overload as the native ports typically
2128 // can get the position and not (x, y) pair directly (although wxUniv
2129 // directly gets x and y -- and so overrides this method as well)
2130 long pos;
2131 wxTextCtrlHitTestResult rc = HitTest(pt, &pos);
2132
2133 if ( rc != wxTE_HT_UNKNOWN )
2134 {
2135 PositionToXY(pos, x, y);
2136 }
2137
2138 return rc;
2139 }
2140
2141 wxTextCtrlHitTestResult
2142 wxRichTextCtrl::HitTest(const wxPoint& pt,
2143 long * pos) const
2144 {
2145 wxClientDC dc((wxRichTextCtrl*) this);
2146 ((wxRichTextCtrl*)this)->PrepareDC(dc);
2147
2148 // Buffer uses logical position (relative to start of buffer)
2149 // so convert
2150 wxPoint pt2 = GetLogicalPoint(pt);
2151
2152 int hit = ((wxRichTextCtrl*)this)->GetBuffer().HitTest(dc, pt2, *pos);
2153
2154 if ((hit & wxRICHTEXT_HITTEST_BEFORE) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2155 return wxTE_HT_BEFORE;
2156 else if ((hit & wxRICHTEXT_HITTEST_AFTER) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2157 return wxTE_HT_BEYOND;
2158 else if (hit & (wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_AFTER))
2159 return wxTE_HT_ON_TEXT;
2160
2161 return wxTE_HT_UNKNOWN;
2162 }
2163
2164 // ----------------------------------------------------------------------------
2165 // set/get the controls text
2166 // ----------------------------------------------------------------------------
2167
2168 wxString wxRichTextCtrl::GetValue() const
2169 {
2170 return GetBuffer().GetText();
2171 }
2172
2173 wxString wxRichTextCtrl::GetRange(long from, long to) const
2174 {
2175 // Public API for range is different from internals
2176 return GetBuffer().GetTextForRange(wxRichTextRange(from, to-1));
2177 }
2178
2179 void wxRichTextCtrl::DoSetValue(const wxString& value, int flags)
2180 {
2181 // Don't call Clear here, since it always sends a text updated event
2182 m_buffer.ResetAndClearCommands();
2183 m_buffer.SetDirty(true);
2184 m_caretPosition = -1;
2185 m_caretPositionForDefaultStyle = -2;
2186 m_caretAtLineStart = false;
2187 m_selectionRange.SetRange(-2, -2);
2188
2189 Scroll(0,0);
2190
2191 if (!IsFrozen())
2192 {
2193 LayoutContent();
2194 Refresh(false);
2195 }
2196
2197 if (!value.IsEmpty())
2198 {
2199 // Remove empty paragraph
2200 GetBuffer().Clear();
2201 DoWriteText(value, flags);
2202
2203 // for compatibility, don't move the cursor when doing SetValue()
2204 SetInsertionPoint(0);
2205 }
2206 else
2207 {
2208 // still send an event for consistency
2209 if (flags & SetValue_SendEvent)
2210 wxTextCtrl::SendTextUpdatedEvent(this);
2211 }
2212 DiscardEdits();
2213 }
2214
2215 void wxRichTextCtrl::WriteText(const wxString& value)
2216 {
2217 DoWriteText(value);
2218 }
2219
2220 void wxRichTextCtrl::DoWriteText(const wxString& value, int flags)
2221 {
2222 wxString valueUnix = wxTextFile::Translate(value, wxTextFileType_Unix);
2223
2224 SetDefaultStyleToCursorStyle();
2225 GetBuffer().InsertTextWithUndo(m_caretPosition+1, valueUnix, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
2226
2227 if ( flags & SetValue_SendEvent )
2228 wxTextCtrl::SendTextUpdatedEvent(this);
2229 }
2230
2231 void wxRichTextCtrl::AppendText(const wxString& text)
2232 {
2233 SetInsertionPointEnd();
2234
2235 WriteText(text);
2236 }
2237
2238 /// Write an image at the current insertion point
2239 bool wxRichTextCtrl::WriteImage(const wxImage& image, int bitmapType)
2240 {
2241 wxRichTextImageBlock imageBlock;
2242
2243 wxImage image2 = image;
2244 if (imageBlock.MakeImageBlock(image2, bitmapType))
2245 return WriteImage(imageBlock);
2246
2247 return false;
2248 }
2249
2250 bool wxRichTextCtrl::WriteImage(const wxString& filename, int bitmapType)
2251 {
2252 wxRichTextImageBlock imageBlock;
2253
2254 wxImage image;
2255 if (imageBlock.MakeImageBlock(filename, bitmapType, image, false))
2256 return WriteImage(imageBlock);
2257
2258 return false;
2259 }
2260
2261 bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock& imageBlock)
2262 {
2263 return GetBuffer().InsertImageWithUndo(m_caretPosition+1, imageBlock, this);
2264 }
2265
2266 bool wxRichTextCtrl::WriteImage(const wxBitmap& bitmap, int bitmapType)
2267 {
2268 if (bitmap.Ok())
2269 {
2270 wxRichTextImageBlock imageBlock;
2271
2272 wxImage image = bitmap.ConvertToImage();
2273 if (image.Ok() && imageBlock.MakeImageBlock(image, bitmapType))
2274 return WriteImage(imageBlock);
2275 }
2276
2277 return false;
2278 }
2279
2280 /// Insert a newline (actually paragraph) at the current insertion point.
2281 bool wxRichTextCtrl::Newline()
2282 {
2283 return GetBuffer().InsertNewlineWithUndo(m_caretPosition+1, this);
2284 }
2285
2286 /// Insert a line break at the current insertion point.
2287 bool wxRichTextCtrl::LineBreak()
2288 {
2289 wxString text;
2290 text = wxRichTextLineBreakChar;
2291 return GetBuffer().InsertTextWithUndo(m_caretPosition+1, text, this);
2292 }
2293
2294 // ----------------------------------------------------------------------------
2295 // Clipboard operations
2296 // ----------------------------------------------------------------------------
2297
2298 void wxRichTextCtrl::Copy()
2299 {
2300 if (CanCopy())
2301 {
2302 wxRichTextRange range = GetInternalSelectionRange();
2303 GetBuffer().CopyToClipboard(range);
2304 }
2305 }
2306
2307 void wxRichTextCtrl::Cut()
2308 {
2309 if (CanCut())
2310 {
2311 wxRichTextRange range = GetInternalSelectionRange();
2312 GetBuffer().CopyToClipboard(range);
2313
2314 DeleteSelectedContent();
2315 LayoutContent();
2316 Refresh(false);
2317 }
2318 }
2319
2320 void wxRichTextCtrl::Paste()
2321 {
2322 if (CanPaste())
2323 {
2324 SetDefaultStyleToCursorStyle();
2325 BeginBatchUndo(_("Paste"));
2326
2327 long newPos = m_caretPosition;
2328 DeleteSelectedContent(& newPos);
2329
2330 GetBuffer().PasteFromClipboard(newPos);
2331
2332 EndBatchUndo();
2333 }
2334 }
2335
2336 void wxRichTextCtrl::DeleteSelection()
2337 {
2338 if (CanDeleteSelection())
2339 {
2340 DeleteSelectedContent();
2341 }
2342 }
2343
2344 bool wxRichTextCtrl::HasSelection() const
2345 {
2346 return m_selectionRange.GetStart() != -2 && m_selectionRange.GetEnd() != -2;
2347 }
2348
2349 bool wxRichTextCtrl::CanCopy() const
2350 {
2351 // Can copy if there's a selection
2352 return HasSelection();
2353 }
2354
2355 bool wxRichTextCtrl::CanCut() const
2356 {
2357 return HasSelection() && IsEditable();
2358 }
2359
2360 bool wxRichTextCtrl::CanPaste() const
2361 {
2362 if ( !IsEditable() )
2363 return false;
2364
2365 return GetBuffer().CanPasteFromClipboard();
2366 }
2367
2368 bool wxRichTextCtrl::CanDeleteSelection() const
2369 {
2370 return HasSelection() && IsEditable();
2371 }
2372
2373
2374 // ----------------------------------------------------------------------------
2375 // Accessors
2376 // ----------------------------------------------------------------------------
2377
2378 void wxRichTextCtrl::SetEditable(bool editable)
2379 {
2380 m_editable = editable;
2381 }
2382
2383 void wxRichTextCtrl::SetInsertionPoint(long pos)
2384 {
2385 SelectNone();
2386
2387 m_caretPosition = pos - 1;
2388
2389 PositionCaret();
2390 }
2391
2392 void wxRichTextCtrl::SetInsertionPointEnd()
2393 {
2394 long pos = GetLastPosition();
2395 SetInsertionPoint(pos);
2396 }
2397
2398 long wxRichTextCtrl::GetInsertionPoint() const
2399 {
2400 return m_caretPosition+1;
2401 }
2402
2403 wxTextPos wxRichTextCtrl::GetLastPosition() const
2404 {
2405 return GetBuffer().GetRange().GetEnd();
2406 }
2407
2408 // If the return values from and to are the same, there is no
2409 // selection.
2410 void wxRichTextCtrl::GetSelection(long* from, long* to) const
2411 {
2412 *from = m_selectionRange.GetStart();
2413 *to = m_selectionRange.GetEnd();
2414 if ((*to) != -1 && (*to) != -2)
2415 (*to) ++;
2416 }
2417
2418 bool wxRichTextCtrl::IsEditable() const
2419 {
2420 return m_editable;
2421 }
2422
2423 // ----------------------------------------------------------------------------
2424 // selection
2425 // ----------------------------------------------------------------------------
2426
2427 void wxRichTextCtrl::SetSelection(long from, long to)
2428 {
2429 // if from and to are both -1, it means (in wxWidgets) that all text should
2430 // be selected.
2431 if ( (from == -1) && (to == -1) )
2432 {
2433 from = 0;
2434 to = GetLastPosition()+1;
2435 }
2436
2437 DoSetSelection(from, to);
2438 }
2439
2440 void wxRichTextCtrl::DoSetSelection(long from, long to, bool WXUNUSED(scrollCaret))
2441 {
2442 if (from == to)
2443 {
2444 SelectNone();
2445 }
2446 else
2447 {
2448 wxRichTextRange oldSelection = m_selectionRange;
2449 m_selectionAnchor = from;
2450 m_selectionRange.SetRange(from, to-1);
2451 if (from > -2)
2452 m_caretPosition = from-1;
2453
2454 RefreshForSelectionChange(oldSelection, m_selectionRange);
2455 PositionCaret();
2456 }
2457 }
2458
2459 // ----------------------------------------------------------------------------
2460 // Editing
2461 // ----------------------------------------------------------------------------
2462
2463 void wxRichTextCtrl::Replace(long WXUNUSED(from), long WXUNUSED(to),
2464 const wxString& value)
2465 {
2466 BeginBatchUndo(_("Replace"));
2467
2468 DeleteSelectedContent();
2469
2470 DoWriteText(value, SetValue_SelectionOnly);
2471
2472 EndBatchUndo();
2473 }
2474
2475 void wxRichTextCtrl::Remove(long from, long to)
2476 {
2477 SelectNone();
2478
2479 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(from, to-1), this);
2480
2481 LayoutContent();
2482 if (!IsFrozen())
2483 Refresh(false);
2484 }
2485
2486 bool wxRichTextCtrl::IsModified() const
2487 {
2488 return m_buffer.IsModified();
2489 }
2490
2491 void wxRichTextCtrl::MarkDirty()
2492 {
2493 m_buffer.Modify(true);
2494 }
2495
2496 void wxRichTextCtrl::DiscardEdits()
2497 {
2498 m_caretPositionForDefaultStyle = -2;
2499 m_buffer.Modify(false);
2500 m_buffer.GetCommandProcessor()->ClearCommands();
2501 }
2502
2503 int wxRichTextCtrl::GetNumberOfLines() const
2504 {
2505 return GetBuffer().GetParagraphCount();
2506 }
2507
2508 // ----------------------------------------------------------------------------
2509 // Positions <-> coords
2510 // ----------------------------------------------------------------------------
2511
2512 long wxRichTextCtrl::XYToPosition(long x, long y) const
2513 {
2514 return GetBuffer().XYToPosition(x, y);
2515 }
2516
2517 bool wxRichTextCtrl::PositionToXY(long pos, long *x, long *y) const
2518 {
2519 return GetBuffer().PositionToXY(pos, x, y);
2520 }
2521
2522 // ----------------------------------------------------------------------------
2523 //
2524 // ----------------------------------------------------------------------------
2525
2526 void wxRichTextCtrl::ShowPosition(long pos)
2527 {
2528 if (!IsPositionVisible(pos))
2529 ScrollIntoView(pos-1, WXK_DOWN);
2530 }
2531
2532 int wxRichTextCtrl::GetLineLength(long lineNo) const
2533 {
2534 return GetBuffer().GetParagraphLength(lineNo);
2535 }
2536
2537 wxString wxRichTextCtrl::GetLineText(long lineNo) const
2538 {
2539 return GetBuffer().GetParagraphText(lineNo);
2540 }
2541
2542 // ----------------------------------------------------------------------------
2543 // Undo/redo
2544 // ----------------------------------------------------------------------------
2545
2546 void wxRichTextCtrl::Undo()
2547 {
2548 if (CanUndo())
2549 {
2550 GetCommandProcessor()->Undo();
2551 }
2552 }
2553
2554 void wxRichTextCtrl::Redo()
2555 {
2556 if (CanRedo())
2557 {
2558 GetCommandProcessor()->Redo();
2559 }
2560 }
2561
2562 bool wxRichTextCtrl::CanUndo() const
2563 {
2564 return GetCommandProcessor()->CanUndo();
2565 }
2566
2567 bool wxRichTextCtrl::CanRedo() const
2568 {
2569 return GetCommandProcessor()->CanRedo();
2570 }
2571
2572 // ----------------------------------------------------------------------------
2573 // implementation details
2574 // ----------------------------------------------------------------------------
2575
2576 void wxRichTextCtrl::Command(wxCommandEvent& event)
2577 {
2578 SetValue(event.GetString());
2579 GetEventHandler()->ProcessEvent(event);
2580 }
2581
2582 void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent& event)
2583 {
2584 // By default, load the first file into the text window.
2585 if (event.GetNumberOfFiles() > 0)
2586 {
2587 LoadFile(event.GetFiles()[0]);
2588 }
2589 }
2590
2591 wxSize wxRichTextCtrl::DoGetBestSize() const
2592 {
2593 return wxSize(10, 10);
2594 }
2595
2596 // ----------------------------------------------------------------------------
2597 // standard handlers for standard edit menu events
2598 // ----------------------------------------------------------------------------
2599
2600 void wxRichTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
2601 {
2602 Cut();
2603 }
2604
2605 void wxRichTextCtrl::OnClear(wxCommandEvent& WXUNUSED(event))
2606 {
2607 DeleteSelection();
2608 }
2609
2610 void wxRichTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
2611 {
2612 Copy();
2613 }
2614
2615 void wxRichTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
2616 {
2617 Paste();
2618 }
2619
2620 void wxRichTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
2621 {
2622 Undo();
2623 }
2624
2625 void wxRichTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
2626 {
2627 Redo();
2628 }
2629
2630 void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
2631 {
2632 event.Enable( CanCut() );
2633 }
2634
2635 void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
2636 {
2637 event.Enable( CanCopy() );
2638 }
2639
2640 void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent& event)
2641 {
2642 event.Enable( CanDeleteSelection() );
2643 }
2644
2645 void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
2646 {
2647 event.Enable( CanPaste() );
2648 }
2649
2650 void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
2651 {
2652 event.Enable( CanUndo() );
2653 event.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
2654 }
2655
2656 void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
2657 {
2658 event.Enable( CanRedo() );
2659 event.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
2660 }
2661
2662 void wxRichTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
2663 {
2664 SelectAll();
2665 }
2666
2667 void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
2668 {
2669 event.Enable(GetLastPosition() > 0);
2670 }
2671
2672 void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent& event)
2673 {
2674 if (event.GetEventObject() != this)
2675 {
2676 event.Skip();
2677 return;
2678 }
2679
2680 if (!m_contextMenu)
2681 {
2682 m_contextMenu = new wxMenu;
2683 m_contextMenu->Append(wxID_UNDO, _("&Undo"));
2684 m_contextMenu->Append(wxID_REDO, _("&Redo"));
2685 m_contextMenu->AppendSeparator();
2686 m_contextMenu->Append(wxID_CUT, _("Cu&t"));
2687 m_contextMenu->Append(wxID_COPY, _("&Copy"));
2688 m_contextMenu->Append(wxID_PASTE, _("&Paste"));
2689 m_contextMenu->Append(wxID_CLEAR, _("&Delete"));
2690 m_contextMenu->AppendSeparator();
2691 m_contextMenu->Append(wxID_SELECTALL, _("Select &All"));
2692 }
2693 PopupMenu(m_contextMenu);
2694 return;
2695 }
2696
2697 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
2698 {
2699 return GetBuffer().SetStyle(wxRichTextRange(start, end-1), wxTextAttr(style));
2700 }
2701
2702 bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxTextAttr& style)
2703 {
2704 return GetBuffer().SetStyle(range.ToInternal(), style);
2705 }
2706
2707 // extended style setting operation with flags including:
2708 // wxRICHTEXT_SETSTYLE_WITH_UNDO, wxRICHTEXT_SETSTYLE_OPTIMIZE, wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY.
2709 // see richtextbuffer.h for more details.
2710
2711 bool wxRichTextCtrl::SetStyleEx(const wxRichTextRange& range, const wxTextAttr& style, int flags)
2712 {
2713 return GetBuffer().SetStyle(range.ToInternal(), style, flags);
2714 }
2715
2716 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr& style)
2717 {
2718 return GetBuffer().SetDefaultStyle(wxTextAttr(style));
2719 }
2720
2721 const wxTextAttr& wxRichTextCtrl::GetDefaultStyle() const
2722 {
2723 return GetBuffer().GetDefaultStyle();
2724 }
2725
2726 bool wxRichTextCtrl::GetStyle(long position, wxTextAttr& style)
2727 {
2728 return GetBuffer().GetStyle(position, style);
2729 }
2730
2731 // get the common set of styles for the range
2732 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxTextAttr& style)
2733 {
2734 return GetBuffer().GetStyleForRange(range.ToInternal(), style);
2735 }
2736
2737 /// Get the content (uncombined) attributes for this position.
2738 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxTextAttr& style)
2739 {
2740 return GetBuffer().GetUncombinedStyle(position, style);
2741 }
2742
2743 /// Set font, and also the buffer attributes
2744 bool wxRichTextCtrl::SetFont(const wxFont& font)
2745 {
2746 wxControl::SetFont(font);
2747
2748 wxTextAttr attr = GetBuffer().GetAttributes();
2749 attr.SetFont(font);
2750 GetBuffer().SetBasicStyle(attr);
2751
2752 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2753 Refresh(false);
2754
2755 return true;
2756 }
2757
2758 /// Transform logical to physical
2759 wxPoint wxRichTextCtrl::GetPhysicalPoint(const wxPoint& ptLogical) const
2760 {
2761 wxPoint pt;
2762 CalcScrolledPosition(ptLogical.x, ptLogical.y, & pt.x, & pt.y);
2763
2764 return pt;
2765 }
2766
2767 /// Transform physical to logical
2768 wxPoint wxRichTextCtrl::GetLogicalPoint(const wxPoint& ptPhysical) const
2769 {
2770 wxPoint pt;
2771 CalcUnscrolledPosition(ptPhysical.x, ptPhysical.y, & pt.x, & pt.y);
2772
2773 return pt;
2774 }
2775
2776 /// Position the caret
2777 void wxRichTextCtrl::PositionCaret()
2778 {
2779 if (!GetCaret())
2780 return;
2781
2782 //wxLogDebug(wxT("PositionCaret"));
2783
2784 wxRect caretRect;
2785 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect))
2786 {
2787 wxPoint newPt = caretRect.GetPosition();
2788 wxSize newSz = caretRect.GetSize();
2789 wxPoint pt = GetPhysicalPoint(newPt);
2790 if (GetCaret()->GetPosition() != pt || GetCaret()->GetSize() != newSz)
2791 {
2792 GetCaret()->Hide();
2793 if (GetCaret()->GetSize() != newSz)
2794 GetCaret()->SetSize(newSz);
2795 GetCaret()->Move(pt);
2796 GetCaret()->Show();
2797 }
2798 }
2799 }
2800
2801 /// Get the caret height and position for the given character position
2802 bool wxRichTextCtrl::GetCaretPositionForIndex(long position, wxRect& rect)
2803 {
2804 wxClientDC dc(this);
2805 dc.SetFont(GetFont());
2806
2807 PrepareDC(dc);
2808
2809 wxPoint pt;
2810 int height = 0;
2811
2812 if (GetBuffer().FindPosition(dc, position, pt, & height, m_caretAtLineStart))
2813 {
2814 // Caret height can't be zero
2815 if (height == 0)
2816 height = dc.GetCharHeight();
2817
2818 rect = wxRect(pt, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH, height));
2819 return true;
2820 }
2821
2822 return false;
2823 }
2824
2825 /// Gets the line for the visible caret position. If the caret is
2826 /// shown at the very end of the line, it means the next character is actually
2827 /// on the following line. So let's get the line we're expecting to find
2828 /// if this is the case.
2829 wxRichTextLine* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition) const
2830 {
2831 wxRichTextLine* line = GetBuffer().GetLineAtPosition(caretPosition, true);
2832 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPosition, true);
2833 if (line)
2834 {
2835 wxRichTextRange lineRange = line->GetAbsoluteRange();
2836 if (caretPosition == lineRange.GetStart()-1 &&
2837 (para->GetRange().GetStart() != lineRange.GetStart()))
2838 {
2839 if (!m_caretAtLineStart)
2840 line = GetBuffer().GetLineAtPosition(caretPosition-1, true);
2841 }
2842 }
2843 return line;
2844 }
2845
2846
2847 /// Move the caret to the given character position
2848 bool wxRichTextCtrl::MoveCaret(long pos, bool showAtLineStart)
2849 {
2850 if (GetBuffer().GetDirty())
2851 LayoutContent();
2852
2853 if (pos <= GetBuffer().GetRange().GetEnd())
2854 {
2855 SetCaretPosition(pos, showAtLineStart);
2856
2857 PositionCaret();
2858
2859 return true;
2860 }
2861 else
2862 return false;
2863 }
2864
2865 /// Layout the buffer: which we must do before certain operations, such as
2866 /// setting the caret position.
2867 bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect)
2868 {
2869 if (GetBuffer().GetDirty() || onlyVisibleRect)
2870 {
2871 wxRect availableSpace(GetClientSize());
2872 if (availableSpace.width == 0)
2873 availableSpace.width = 10;
2874 if (availableSpace.height == 0)
2875 availableSpace.height = 10;
2876
2877 int flags = wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT;
2878 if (onlyVisibleRect)
2879 {
2880 flags |= wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
2881 availableSpace.SetPosition(GetLogicalPoint(wxPoint(0, 0)));
2882 }
2883
2884 wxClientDC dc(this);
2885 dc.SetFont(GetFont());
2886
2887 PrepareDC(dc);
2888
2889 GetBuffer().Defragment();
2890 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
2891 GetBuffer().Layout(dc, availableSpace, flags);
2892 GetBuffer().SetDirty(false);
2893
2894 if (!IsFrozen())
2895 SetupScrollbars();
2896 }
2897
2898 return true;
2899 }
2900
2901 /// Is all of the selection bold?
2902 bool wxRichTextCtrl::IsSelectionBold()
2903 {
2904 if (HasSelection())
2905 {
2906 wxTextAttr attr;
2907 wxRichTextRange range = GetSelectionRange();
2908 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2909 attr.SetFontWeight(wxBOLD);
2910
2911 return HasCharacterAttributes(range, attr);
2912 }
2913 else
2914 {
2915 // If no selection, then we need to combine current style with default style
2916 // to see what the effect would be if we started typing.
2917 wxTextAttr attr;
2918 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2919
2920 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2921 if (GetStyle(pos, attr))
2922 {
2923 if (IsDefaultStyleShowing())
2924 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2925 return attr.GetFontWeight() == wxBOLD;
2926 }
2927 }
2928 return false;
2929 }
2930
2931 /// Is all of the selection italics?
2932 bool wxRichTextCtrl::IsSelectionItalics()
2933 {
2934 if (HasSelection())
2935 {
2936 wxRichTextRange range = GetSelectionRange();
2937 wxTextAttr attr;
2938 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2939 attr.SetFontStyle(wxITALIC);
2940
2941 return HasCharacterAttributes(range, attr);
2942 }
2943 else
2944 {
2945 // If no selection, then we need to combine current style with default style
2946 // to see what the effect would be if we started typing.
2947 wxTextAttr attr;
2948 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2949
2950 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2951 if (GetStyle(pos, attr))
2952 {
2953 if (IsDefaultStyleShowing())
2954 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2955 return attr.GetFontStyle() == wxITALIC;
2956 }
2957 }
2958 return false;
2959 }
2960
2961 /// Is all of the selection underlined?
2962 bool wxRichTextCtrl::IsSelectionUnderlined()
2963 {
2964 if (HasSelection())
2965 {
2966 wxRichTextRange range = GetSelectionRange();
2967 wxTextAttr attr;
2968 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2969 attr.SetFontUnderlined(true);
2970
2971 return HasCharacterAttributes(range, attr);
2972 }
2973 else
2974 {
2975 // If no selection, then we need to combine current style with default style
2976 // to see what the effect would be if we started typing.
2977 wxTextAttr attr;
2978 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2979 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2980
2981 if (GetStyle(pos, attr))
2982 {
2983 if (IsDefaultStyleShowing())
2984 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2985 return attr.GetFontUnderlined();
2986 }
2987 }
2988 return false;
2989 }
2990
2991 /// Apply bold to the selection
2992 bool wxRichTextCtrl::ApplyBoldToSelection()
2993 {
2994 wxTextAttr attr;
2995 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2996 attr.SetFontWeight(IsSelectionBold() ? wxNORMAL : wxBOLD);
2997
2998 if (HasSelection())
2999 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3000 else
3001 {
3002 wxRichTextAttr current = GetDefaultStyleEx();
3003 current.Apply(attr);
3004 SetAndShowDefaultStyle(current);
3005 }
3006 return true;
3007 }
3008
3009 /// Apply italic to the selection
3010 bool wxRichTextCtrl::ApplyItalicToSelection()
3011 {
3012 wxTextAttr attr;
3013 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
3014 attr.SetFontStyle(IsSelectionItalics() ? wxNORMAL : wxITALIC);
3015
3016 if (HasSelection())
3017 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3018 else
3019 {
3020 wxRichTextAttr current = GetDefaultStyleEx();
3021 current.Apply(attr);
3022 SetAndShowDefaultStyle(current);
3023 }
3024 return true;
3025 }
3026
3027 /// Apply underline to the selection
3028 bool wxRichTextCtrl::ApplyUnderlineToSelection()
3029 {
3030 wxTextAttr attr;
3031 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
3032 attr.SetFontUnderlined(!IsSelectionUnderlined());
3033
3034 if (HasSelection())
3035 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3036 else
3037 {
3038 wxRichTextAttr current = GetDefaultStyleEx();
3039 current.Apply(attr);
3040 SetAndShowDefaultStyle(current);
3041 }
3042 return true;
3043 }
3044
3045 /// Is all of the selection aligned according to the specified flag?
3046 bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment)
3047 {
3048 wxRichTextRange range;
3049 if (HasSelection())
3050 range = GetSelectionRange();
3051 else
3052 range = wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+2);
3053
3054 wxTextAttr attr;
3055 attr.SetAlignment(alignment);
3056
3057 return HasParagraphAttributes(range, attr);
3058 }
3059
3060 /// Apply alignment to the selection
3061 bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment)
3062 {
3063 wxTextAttr attr;
3064 attr.SetAlignment(alignment);
3065 if (HasSelection())
3066 return SetStyle(GetSelectionRange(), attr);
3067 else
3068 {
3069 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(GetCaretPosition()+1);
3070 if (para)
3071 return SetStyleEx(para->GetRange().FromInternal(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY);
3072 }
3073 return true;
3074 }
3075
3076 /// Apply a named style to the selection
3077 bool wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition* def)
3078 {
3079 // Flags are defined within each definition, so only certain
3080 // attributes are applied.
3081 wxTextAttr attr(GetStyleSheet() ? def->GetStyleMergedWithBase(GetStyleSheet()) : def->GetStyle());
3082
3083 int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_RESET;
3084
3085 if (def->IsKindOf(CLASSINFO(wxRichTextListStyleDefinition)))
3086 {
3087 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
3088
3089 wxRichTextRange range;
3090
3091 if (HasSelection())
3092 range = GetSelectionRange();
3093 else
3094 {
3095 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3096 range = wxRichTextRange(pos, pos+1);
3097 }
3098
3099 return SetListStyle(range, (wxRichTextListStyleDefinition*) def, flags);
3100 }
3101
3102 // Make sure the attr has the style name
3103 if (def->IsKindOf(CLASSINFO(wxRichTextParagraphStyleDefinition)))
3104 {
3105 attr.SetParagraphStyleName(def->GetName());
3106
3107 // If applying a paragraph style, we only want the paragraph nodes to adopt these
3108 // attributes, and not the leaf nodes. This will allow the content (e.g. text)
3109 // to change its style independently.
3110 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
3111 }
3112 else
3113 attr.SetCharacterStyleName(def->GetName());
3114
3115 if (HasSelection())
3116 return SetStyleEx(GetSelectionRange(), attr, flags);
3117 else
3118 {
3119 wxRichTextAttr current = GetDefaultStyleEx();
3120 current.Apply(attr);
3121 SetAndShowDefaultStyle(current);
3122 return true;
3123 }
3124 }
3125
3126 /// Apply the style sheet to the buffer, for example if the styles have changed.
3127 bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
3128 {
3129 if (!styleSheet)
3130 styleSheet = GetBuffer().GetStyleSheet();
3131 if (!styleSheet)
3132 return false;
3133
3134 if (GetBuffer().ApplyStyleSheet(styleSheet))
3135 {
3136 GetBuffer().Invalidate(wxRICHTEXT_ALL);
3137 Refresh(false);
3138 return true;
3139 }
3140 else
3141 return false;
3142 }
3143
3144 /// Sets the default style to the style under the cursor
3145 bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
3146 {
3147 wxTextAttr attr;
3148 attr.SetFlags(wxTEXT_ATTR_CHARACTER);
3149
3150 // If at the start of a paragraph, use the next position.
3151 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3152
3153 if (GetUncombinedStyle(pos, attr))
3154 {
3155 SetDefaultStyle(attr);
3156 return true;
3157 }
3158
3159 return false;
3160 }
3161
3162 /// Returns the first visible position in the current view
3163 long wxRichTextCtrl::GetFirstVisiblePosition() const
3164 {
3165 wxRichTextLine* line = GetBuffer().GetLineAtYPosition(GetLogicalPoint(wxPoint(0, 0)).y);
3166 if (line)
3167 return line->GetAbsoluteRange().GetStart();
3168 else
3169 return 0;
3170 }
3171
3172 /// Get the first visible point in the window
3173 wxPoint wxRichTextCtrl::GetFirstVisiblePoint() const
3174 {
3175 int ppuX, ppuY;
3176 int startXUnits, startYUnits;
3177
3178 GetScrollPixelsPerUnit(& ppuX, & ppuY);
3179 GetViewStart(& startXUnits, & startYUnits);
3180
3181 return wxPoint(startXUnits * ppuX, startYUnits * ppuY);
3182 }
3183
3184 /// The adjusted caret position is the character position adjusted to take
3185 /// into account whether we're at the start of a paragraph, in which case
3186 /// style information should be taken from the next position, not current one.
3187 long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos) const
3188 {
3189 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPos+1);
3190
3191 if (para && (caretPos+1 == para->GetRange().GetStart()))
3192 caretPos ++;
3193 return caretPos;
3194 }
3195
3196 /// Get/set the selection range in character positions. -1, -1 means no selection.
3197 /// The range is in API convention, i.e. a single character selection is denoted
3198 /// by (n, n+1)
3199 wxRichTextRange wxRichTextCtrl::GetSelectionRange() const
3200 {
3201 wxRichTextRange range = GetInternalSelectionRange();
3202 if (range != wxRichTextRange(-2,-2) && range != wxRichTextRange(-1,-1))
3203 range.SetEnd(range.GetEnd() + 1);
3204 return range;
3205 }
3206
3207 void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange& range)
3208 {
3209 wxRichTextRange range1(range);
3210 if (range1 != wxRichTextRange(-2,-2) && range1 != wxRichTextRange(-1,-1) )
3211 range1.SetEnd(range1.GetEnd() - 1);
3212
3213 wxASSERT( range1.GetStart() > range1.GetEnd() );
3214
3215 SetInternalSelectionRange(range1);
3216 }
3217
3218 /// Set list style
3219 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
3220 {
3221 return GetBuffer().SetListStyle(range.ToInternal(), def, flags, startFrom, specifiedLevel);
3222 }
3223
3224 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
3225 {
3226 return GetBuffer().SetListStyle(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
3227 }
3228
3229 /// Clear list for given range
3230 bool wxRichTextCtrl::ClearListStyle(const wxRichTextRange& range, int flags)
3231 {
3232 return GetBuffer().ClearListStyle(range.ToInternal(), flags);
3233 }
3234
3235 /// Number/renumber any list elements in the given range
3236 bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
3237 {
3238 return GetBuffer().NumberList(range.ToInternal(), def, flags, startFrom, specifiedLevel);
3239 }
3240
3241 bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
3242 {
3243 return GetBuffer().NumberList(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
3244 }
3245
3246 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
3247 bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int specifiedLevel)
3248 {
3249 return GetBuffer().PromoteList(promoteBy, range.ToInternal(), def, flags, specifiedLevel);
3250 }
3251
3252 bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags, int specifiedLevel)
3253 {
3254 return GetBuffer().PromoteList(promoteBy, range.ToInternal(), defName, flags, specifiedLevel);
3255 }
3256
3257 /// Deletes the content in the given range
3258 bool wxRichTextCtrl::Delete(const wxRichTextRange& range)
3259 {
3260 return GetBuffer().DeleteRangeWithUndo(range.ToInternal(), this);
3261 }
3262
3263 const wxArrayString& wxRichTextCtrl::GetAvailableFontNames()
3264 {
3265 if (sm_availableFontNames.GetCount() == 0)
3266 {
3267 sm_availableFontNames = wxFontEnumerator::GetFacenames();
3268 sm_availableFontNames.Sort();
3269 }
3270 return sm_availableFontNames;
3271 }
3272
3273 void wxRichTextCtrl::ClearAvailableFontNames()
3274 {
3275 sm_availableFontNames.Clear();
3276 }
3277
3278 void wxRichTextCtrl::OnSysColourChanged(wxSysColourChangedEvent& WXUNUSED(event))
3279 {
3280 //wxLogDebug(wxT("wxRichTextCtrl::OnSysColourChanged"));
3281
3282 wxTextAttrEx basicStyle = GetBasicStyle();
3283 basicStyle.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
3284 SetBasicStyle(basicStyle);
3285 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
3286
3287 Refresh();
3288 }
3289
3290 // Refresh the area affected by a selection change
3291 bool wxRichTextCtrl::RefreshForSelectionChange(const wxRichTextRange& oldSelection, const wxRichTextRange& newSelection)
3292 {
3293 // Calculate the refresh rectangle - just the affected lines
3294 long firstPos, lastPos;
3295 if (oldSelection.GetStart() == -2 && newSelection.GetStart() != -2)
3296 {
3297 firstPos = newSelection.GetStart();
3298 lastPos = newSelection.GetEnd();
3299 }
3300 else if (oldSelection.GetStart() != -2 && newSelection.GetStart() == -2)
3301 {
3302 firstPos = oldSelection.GetStart();
3303 lastPos = oldSelection.GetEnd();
3304 }
3305 else if (oldSelection.GetStart() == -2 && newSelection.GetStart() == -2)
3306 {
3307 return false;
3308 }
3309 else
3310 {
3311 firstPos = wxMin(oldSelection.GetStart(), newSelection.GetStart());
3312 lastPos = wxMax(oldSelection.GetEnd(), newSelection.GetEnd());
3313 }
3314
3315 wxRichTextLine* firstLine = GetBuffer().GetLineAtPosition(firstPos);
3316 wxRichTextLine* lastLine = GetBuffer().GetLineAtPosition(lastPos);
3317
3318 if (firstLine && lastLine)
3319 {
3320 wxSize clientSize = GetClientSize();
3321 wxPoint pt1 = GetPhysicalPoint(firstLine->GetAbsolutePosition());
3322 wxPoint pt2 = GetPhysicalPoint(lastLine->GetAbsolutePosition()) + wxPoint(0, lastLine->GetSize().y);
3323
3324 pt1.x = 0;
3325 pt1.y = wxMax(0, pt1.y);
3326 pt2.x = 0;
3327 pt2.y = wxMin(clientSize.y, pt2.y);
3328
3329 wxRect rect(pt1, wxSize(clientSize.x, pt2.y - pt1.y));
3330 RefreshRect(rect, false);
3331 }
3332 else
3333 Refresh(false);
3334
3335 return true;
3336 }
3337
3338 #if wxRICHTEXT_USE_OWN_CARET
3339
3340 // ----------------------------------------------------------------------------
3341 // initialization and destruction
3342 // ----------------------------------------------------------------------------
3343
3344 void wxRichTextCaret::Init()
3345 {
3346 m_hasFocus = true;
3347
3348 m_xOld =
3349 m_yOld = -1;
3350 m_richTextCtrl = NULL;
3351 m_needsUpdate = false;
3352 }
3353
3354 wxRichTextCaret::~wxRichTextCaret()
3355 {
3356 }
3357
3358 // ----------------------------------------------------------------------------
3359 // showing/hiding/moving the caret (base class interface)
3360 // ----------------------------------------------------------------------------
3361
3362 void wxRichTextCaret::DoShow()
3363 {
3364 Refresh();
3365 }
3366
3367 void wxRichTextCaret::DoHide()
3368 {
3369 Refresh();
3370 }
3371
3372 void wxRichTextCaret::DoMove()
3373 {
3374 if (IsVisible())
3375 {
3376 Refresh();
3377
3378 if (m_xOld != -1 && m_yOld != -1)
3379 {
3380 if (m_richTextCtrl)
3381 {
3382 wxRect rect(GetPosition(), GetSize());
3383 m_richTextCtrl->RefreshRect(rect, false);
3384 }
3385 }
3386 }
3387
3388 m_xOld = m_x;
3389 m_yOld = m_y;
3390 }
3391
3392 void wxRichTextCaret::DoSize()
3393 {
3394 int countVisible = m_countVisible;
3395 if (countVisible > 0)
3396 {
3397 m_countVisible = 0;
3398 DoHide();
3399 }
3400
3401 if (countVisible > 0)
3402 {
3403 m_countVisible = countVisible;
3404 DoShow();
3405 }
3406 }
3407
3408 // ----------------------------------------------------------------------------
3409 // handling the focus
3410 // ----------------------------------------------------------------------------
3411
3412 void wxRichTextCaret::OnSetFocus()
3413 {
3414 m_hasFocus = true;
3415
3416 if ( IsVisible() )
3417 Refresh();
3418 }
3419
3420 void wxRichTextCaret::OnKillFocus()
3421 {
3422 m_hasFocus = false;
3423 }
3424
3425 // ----------------------------------------------------------------------------
3426 // drawing the caret
3427 // ----------------------------------------------------------------------------
3428
3429 void wxRichTextCaret::Refresh()
3430 {
3431 if (m_richTextCtrl)
3432 {
3433 wxRect rect(GetPosition(), GetSize());
3434 m_richTextCtrl->RefreshRect(rect, false);
3435 }
3436 }
3437
3438 void wxRichTextCaret::DoDraw(wxDC *dc)
3439 {
3440 dc->SetPen( *wxBLACK_PEN );
3441
3442 dc->SetBrush(*(m_hasFocus ? wxBLACK_BRUSH : wxTRANSPARENT_BRUSH));
3443 dc->SetPen(*wxBLACK_PEN);
3444
3445 // VZ: unfortunately, the rectangle comes out a pixel smaller when this is
3446 // done under wxGTK - no idea why
3447 //dc->SetLogicalFunction(wxINVERT);
3448
3449 wxPoint pt(m_x, m_y);
3450
3451 if (m_richTextCtrl)
3452 {
3453 pt = m_richTextCtrl->GetLogicalPoint(pt);
3454 }
3455 dc->DrawRectangle(pt.x, pt.y, m_width, m_height);
3456 }
3457 #endif
3458 // wxRICHTEXT_USE_OWN_CARET
3459
3460 #endif
3461 // wxUSE_RICHTEXT