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