Use wxIsalnum to test for word delimiters
[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
35 // DLL options compatibility check:
36 #include "wx/app.h"
37 WX_CHECK_BUILD_OPTIONS("wxRichTextCtrl")
38
39 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_ITEM_SELECTED)
40 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_ITEM_DESELECTED)
41 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_LEFT_CLICK)
42 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK)
43 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK)
44 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK)
45 DEFINE_EVENT_TYPE(wxEVT_COMMAND_RICHTEXT_RETURN)
46
47 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
48 IMPLEMENT_CLASS( wxRichTextCtrl, wxControl )
49 #else
50 IMPLEMENT_CLASS( wxRichTextCtrl, wxScrolledWindow )
51 #endif
52
53 IMPLEMENT_CLASS( wxRichTextEvent, wxNotifyEvent )
54
55 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
56 BEGIN_EVENT_TABLE( wxRichTextCtrl, wxControl )
57 #else
58 BEGIN_EVENT_TABLE( wxRichTextCtrl, wxScrolledWindow )
59 #endif
60 EVT_PAINT(wxRichTextCtrl::OnPaint)
61 EVT_ERASE_BACKGROUND(wxRichTextCtrl::OnEraseBackground)
62 EVT_IDLE(wxRichTextCtrl::OnIdle)
63 EVT_SCROLLWIN(wxRichTextCtrl::OnScroll)
64 EVT_LEFT_DOWN(wxRichTextCtrl::OnLeftClick)
65 EVT_MOTION(wxRichTextCtrl::OnMoveMouse)
66 EVT_LEFT_UP(wxRichTextCtrl::OnLeftUp)
67 EVT_RIGHT_DOWN(wxRichTextCtrl::OnRightClick)
68 EVT_MIDDLE_DOWN(wxRichTextCtrl::OnMiddleClick)
69 EVT_LEFT_DCLICK(wxRichTextCtrl::OnLeftDClick)
70 EVT_CHAR(wxRichTextCtrl::OnChar)
71 EVT_SIZE(wxRichTextCtrl::OnSize)
72 EVT_SET_FOCUS(wxRichTextCtrl::OnSetFocus)
73 EVT_KILL_FOCUS(wxRichTextCtrl::OnKillFocus)
74 EVT_CONTEXT_MENU(wxRichTextCtrl::OnContextMenu)
75
76 EVT_MENU(wxID_UNDO, wxRichTextCtrl::OnUndo)
77 EVT_UPDATE_UI(wxID_UNDO, wxRichTextCtrl::OnUpdateUndo)
78
79 EVT_MENU(wxID_REDO, wxRichTextCtrl::OnRedo)
80 EVT_UPDATE_UI(wxID_REDO, wxRichTextCtrl::OnUpdateRedo)
81
82 EVT_MENU(wxID_COPY, wxRichTextCtrl::OnCopy)
83 EVT_UPDATE_UI(wxID_COPY, wxRichTextCtrl::OnUpdateCopy)
84
85 EVT_MENU(wxID_PASTE, wxRichTextCtrl::OnPaste)
86 EVT_UPDATE_UI(wxID_PASTE, wxRichTextCtrl::OnUpdatePaste)
87
88 EVT_MENU(wxID_CUT, wxRichTextCtrl::OnCut)
89 EVT_UPDATE_UI(wxID_CUT, wxRichTextCtrl::OnUpdateCut)
90
91 EVT_MENU(wxID_CLEAR, wxRichTextCtrl::OnClear)
92 EVT_UPDATE_UI(wxID_CLEAR, wxRichTextCtrl::OnUpdateClear)
93
94 EVT_MENU(wxID_SELECTALL, wxRichTextCtrl::OnSelectAll)
95 EVT_UPDATE_UI(wxID_SELECTALL, wxRichTextCtrl::OnUpdateSelectAll)
96 END_EVENT_TABLE()
97
98 /*!
99 * wxRichTextCtrl
100 */
101
102 wxRichTextCtrl::wxRichTextCtrl()
103 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
104 : wxScrollHelper(this)
105 #endif
106 {
107 Init();
108 }
109
110 wxRichTextCtrl::wxRichTextCtrl( wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style)
111 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
112 : wxScrollHelper(this)
113 #endif
114 {
115 Init();
116 Create(parent, id, value, pos, size, style);
117 }
118
119 /// Creation
120 bool wxRichTextCtrl::Create( wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style)
121 {
122 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
123 if (!wxTextCtrlBase::Create(parent, id, pos, size, style|wxFULL_REPAINT_ON_RESIZE
124 ))
125 return false;
126 #else
127 if (!wxScrolledWindow::Create(parent, id, pos, size, style|wxFULL_REPAINT_ON_RESIZE
128 ))
129 return false;
130 #endif
131
132 if (!GetFont().Ok())
133 {
134 SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
135 }
136
137 GetBuffer().SetRichTextCtrl(this);
138
139 wxTextAttrEx attributes;
140 attributes.SetFont(GetFont());
141 attributes.SetTextColour(*wxBLACK);
142 attributes.SetBackgroundColour(*wxWHITE);
143 attributes.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
144 attributes.SetFlags(wxTEXT_ATTR_ALL);
145 SetBasicStyle(attributes);
146
147 // The default attributes will be merged with base attributes, so
148 // can be empty to begin with
149 wxTextAttrEx defaultAttributes;
150 SetDefaultStyle(defaultAttributes);
151
152 SetBackgroundColour(*wxWHITE);
153 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
154
155 // Tell the sizers to use the given or best size
156 SetBestFittingSize(size);
157
158 // Create a buffer
159 RecreateBuffer(size);
160
161 SetCursor(wxCursor(wxCURSOR_IBEAM));
162
163 if (!value.IsEmpty())
164 SetValue(value);
165
166 return true;
167 }
168
169 wxRichTextCtrl::~wxRichTextCtrl()
170 {
171 delete m_contextMenu;
172 }
173
174 /// Member initialisation
175 void wxRichTextCtrl::Init()
176 {
177 m_freezeCount = 0;
178 m_contextMenu = NULL;
179 m_caret = NULL;
180 m_caretPosition = -1;
181 m_selectionRange.SetRange(-2, -2);
182 m_selectionAnchor = -2;
183 m_editable = true;
184 m_caretAtLineStart = false;
185 m_dragging = false;
186 m_fullLayoutRequired = false;
187 m_fullLayoutTime = 0;
188 m_fullLayoutSavedPosition = 0;
189 m_delayedLayoutThreshold = wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD;
190 m_caretPositionForDefaultStyle = -2;
191 }
192
193 /// Call Freeze to prevent refresh
194 void wxRichTextCtrl::Freeze()
195 {
196 m_freezeCount ++;
197 }
198
199 /// Call Thaw to refresh
200 void wxRichTextCtrl::Thaw()
201 {
202 m_freezeCount --;
203
204 if (m_freezeCount == 0)
205 {
206 SetupScrollbars();
207 Refresh(false);
208 }
209 }
210
211 /// Clear all text
212 void wxRichTextCtrl::Clear()
213 {
214 m_buffer.Reset();
215 m_buffer.SetDirty(true);
216 m_caretPosition = -1;
217 m_caretPositionForDefaultStyle = -2;
218 m_caretAtLineStart = false;
219 m_selectionRange.SetRange(-2, -2);
220
221 SetScrollbars(0, 0, 0, 0, 0, 0);
222
223 if (m_freezeCount == 0)
224 {
225 SetupScrollbars();
226 Refresh(false);
227 }
228 SendUpdateEvent();
229 }
230
231 /// Painting
232 void wxRichTextCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
233 {
234 if (GetCaret())
235 GetCaret()->Hide();
236
237 {
238 wxBufferedPaintDC dc(this, m_bufferBitmap);
239 //wxLogDebug(wxT("OnPaint"));
240
241 PrepareDC(dc);
242
243 if (m_freezeCount > 0)
244 return;
245
246 dc.SetFont(GetFont());
247
248 // Paint the background
249 PaintBackground(dc);
250
251 wxRegion dirtyRegion = GetUpdateRegion();
252
253 wxRect drawingArea(GetLogicalPoint(wxPoint(0, 0)), GetClientSize());
254 wxRect availableSpace(GetClientSize());
255 if (GetBuffer().GetDirty())
256 {
257 GetBuffer().Layout(dc, availableSpace, wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT);
258 GetBuffer().SetDirty(false);
259 SetupScrollbars();
260 }
261
262 GetBuffer().Draw(dc, GetBuffer().GetRange(), GetInternalSelectionRange(), drawingArea, 0 /* descent */, 0 /* flags */);
263 }
264
265 if (GetCaret())
266 GetCaret()->Show();
267
268 PositionCaret();
269 }
270
271 // Empty implementation, to prevent flicker
272 void wxRichTextCtrl::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
273 {
274 }
275
276 void wxRichTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
277 {
278 wxCaret* caret = new wxCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16);
279 SetCaret(caret);
280 caret->Show();
281 PositionCaret();
282
283 if (!IsFrozen())
284 Refresh(false);
285 }
286
287 void wxRichTextCtrl::OnKillFocus(wxFocusEvent& WXUNUSED(event))
288 {
289 SetCaret(NULL);
290
291 if (!IsFrozen())
292 Refresh(false);
293 }
294
295 /// Left-click
296 void wxRichTextCtrl::OnLeftClick(wxMouseEvent& event)
297 {
298 SetFocus();
299
300 wxClientDC dc(this);
301 PrepareDC(dc);
302 dc.SetFont(GetFont());
303
304 long position = 0;
305 int hit = GetBuffer().HitTest(dc, event.GetLogicalPosition(dc), position);
306
307 if (hit != wxRICHTEXT_HITTEST_NONE)
308 {
309 m_dragStart = event.GetLogicalPosition(dc);
310 m_dragging = true;
311 CaptureMouse();
312
313 SelectNone();
314
315 bool caretAtLineStart = false;
316
317 if (hit & wxRICHTEXT_HITTEST_BEFORE)
318 {
319 // If we're at the start of a line (but not first in para)
320 // then we should keep the caret showing at the start of the line
321 // by showing the m_caretAtLineStart flag.
322 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
323 wxRichTextLine* line = GetBuffer().GetLineAtPosition(position);
324
325 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
326 caretAtLineStart = true;
327 position --;
328 }
329
330 MoveCaret(position, caretAtLineStart);
331 SetDefaultStyleToCursorStyle();
332 }
333
334 event.Skip();
335 }
336
337 /// Left-up
338 void wxRichTextCtrl::OnLeftUp(wxMouseEvent& WXUNUSED(event))
339 {
340 if (m_dragging)
341 {
342 m_dragging = false;
343 if (GetCapture() == this)
344 ReleaseMouse();
345 }
346 }
347
348 /// Left-click
349 void wxRichTextCtrl::OnMoveMouse(wxMouseEvent& event)
350 {
351 if (!event.Dragging())
352 {
353 event.Skip();
354 return;
355 }
356
357 wxClientDC dc(this);
358 PrepareDC(dc);
359 dc.SetFont(GetFont());
360
361 long position = 0;
362 wxPoint logicalPt = event.GetLogicalPosition(dc);
363 int hit = GetBuffer().HitTest(dc, logicalPt, position);
364
365 if (m_dragging && hit != wxRICHTEXT_HITTEST_NONE)
366 {
367 // TODO: test closeness
368
369 bool caretAtLineStart = false;
370
371 if (hit & wxRICHTEXT_HITTEST_BEFORE)
372 {
373 // If we're at the start of a line (but not first in para)
374 // then we should keep the caret showing at the start of the line
375 // by showing the m_caretAtLineStart flag.
376 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
377 wxRichTextLine* line = GetBuffer().GetLineAtPosition(position);
378
379 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
380 caretAtLineStart = true;
381 position --;
382 }
383
384 if (m_caretPosition != position)
385 {
386 bool extendSel = ExtendSelection(m_caretPosition, position, wxRICHTEXT_SHIFT_DOWN);
387
388 MoveCaret(position, caretAtLineStart);
389 SetDefaultStyleToCursorStyle();
390
391 if (extendSel)
392 Refresh(false);
393 }
394 }
395 }
396
397 /// Right-click
398 void wxRichTextCtrl::OnRightClick(wxMouseEvent& event)
399 {
400 SetFocus();
401 event.Skip();
402 }
403
404 /// Left-double-click
405 void wxRichTextCtrl::OnLeftDClick(wxMouseEvent& event)
406 {
407 SelectWord(GetCaretPosition()+1);
408 event.Skip();
409 }
410
411 /// Middle-click
412 void wxRichTextCtrl::OnMiddleClick(wxMouseEvent& event)
413 {
414 event.Skip();
415 }
416
417 /// Key press
418 void wxRichTextCtrl::OnChar(wxKeyEvent& event)
419 {
420 int flags = 0;
421 if (event.ControlDown())
422 flags |= wxRICHTEXT_CTRL_DOWN;
423 if (event.ShiftDown())
424 flags |= wxRICHTEXT_SHIFT_DOWN;
425 if (event.AltDown())
426 flags |= wxRICHTEXT_ALT_DOWN;
427
428 if (event.GetKeyCode() == WXK_LEFT ||
429 event.GetKeyCode() == WXK_RIGHT ||
430 event.GetKeyCode() == WXK_UP ||
431 event.GetKeyCode() == WXK_DOWN ||
432 event.GetKeyCode() == WXK_HOME ||
433 event.GetKeyCode() == WXK_PAGEUP ||
434 event.GetKeyCode() == WXK_PAGEDOWN ||
435 event.GetKeyCode() == WXK_END)
436 {
437 KeyboardNavigate(event.GetKeyCode(), flags);
438 return;
439 }
440
441 // all the other keys modify the controls contents which shouldn't be
442 // possible if we're read-only
443 if ( !IsEditable() )
444 {
445 event.Skip();
446 return;
447 }
448
449 if (event.GetKeyCode() == WXK_RETURN)
450 {
451 BeginBatchUndo(_("Insert Text"));
452
453 long newPos = m_caretPosition;
454
455 DeleteSelectedContent(& newPos);
456
457 GetBuffer().InsertNewlineWithUndo(newPos+1, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
458
459 wxRichTextEvent cmdEvent(
460 wxEVT_COMMAND_RICHTEXT_RETURN,
461 GetId());
462 cmdEvent.SetEventObject(this);
463 cmdEvent.SetFlags(flags);
464 GetEventHandler()->ProcessEvent(cmdEvent);
465
466 EndBatchUndo();
467 SetDefaultStyleToCursorStyle();
468
469 ScrollIntoView(m_caretPosition, WXK_RIGHT);
470 }
471 else if (event.GetKeyCode() == WXK_BACK)
472 {
473 BeginBatchUndo(_("Delete Text"));
474
475 // Submit range in character positions, which are greater than caret positions,
476 // so subtract 1 for deleted character and add 1 for conversion to character position.
477 if (m_caretPosition > -1 && !HasSelection())
478 {
479 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(m_caretPosition, m_caretPosition),
480 m_caretPosition, // Current caret position
481 m_caretPosition-1, // New caret position
482 this);
483 }
484 else
485 DeleteSelectedContent();
486
487 EndBatchUndo();
488
489 // Shouldn't this be in Do()?
490 if (GetLastPosition() == -1)
491 {
492 GetBuffer().Reset();
493
494 m_caretPosition = -1;
495 PositionCaret();
496 SetDefaultStyleToCursorStyle();
497 }
498
499 ScrollIntoView(m_caretPosition, WXK_LEFT);
500 }
501 else if (event.GetKeyCode() == WXK_DELETE)
502 {
503 BeginBatchUndo(_("Delete Text"));
504
505 // Submit range in character positions, which are greater than caret positions,
506 if (m_caretPosition < GetBuffer().GetRange().GetEnd()+1 && !HasSelection())
507 {
508 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(m_caretPosition+1, m_caretPosition+1),
509 m_caretPosition, // Current caret position
510 m_caretPosition+1, // New caret position
511 this);
512 }
513 else
514 DeleteSelectedContent();
515
516 EndBatchUndo();
517
518 // Shouldn't this be in Do()?
519 if (GetLastPosition() == -1)
520 {
521 GetBuffer().Reset();
522
523 m_caretPosition = -1;
524 PositionCaret();
525 SetDefaultStyleToCursorStyle();
526 }
527 }
528 else
529 {
530 BeginBatchUndo(_("Insert Text"));
531
532 long newPos = m_caretPosition;
533 DeleteSelectedContent(& newPos);
534
535 wxString str = (wxChar) event.GetKeyCode();
536 GetBuffer().InsertTextWithUndo(newPos+1, str, this, wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
537
538 EndBatchUndo();
539
540 SetDefaultStyleToCursorStyle();
541 ScrollIntoView(m_caretPosition, WXK_RIGHT);
542 }
543 }
544
545 /// Delete content if there is a selection, e.g. when pressing a key.
546 bool wxRichTextCtrl::DeleteSelectedContent(long* newPos)
547 {
548 if (HasSelection())
549 {
550 long pos = m_selectionRange.GetStart();
551 GetBuffer().DeleteRangeWithUndo(m_selectionRange,
552 m_caretPosition, // Current caret position
553 pos, // New caret position
554 this);
555 m_selectionRange.SetRange(-2, -2);
556
557 if (newPos)
558 *newPos = pos-1;
559 return true;
560 }
561 else
562 return false;
563 }
564
565 /// Keyboard navigation
566
567 /*
568
569 Left: left one character
570 Right: right one character
571 Up: up one line
572 Down: down one line
573 Ctrl-Left: left one word
574 Ctrl-Right: right one word
575 Ctrl-Up: previous paragraph start
576 Ctrl-Down: next start of paragraph
577 Home: start of line
578 End: end of line
579 Ctrl-Home: start of document
580 Ctrl-End: end of document
581 Page-Up: Up a screen
582 Page-Down: Down a screen
583
584 Maybe:
585
586 Ctrl-Alt-PgUp: Start of window
587 Ctrl-Alt-PgDn: End of window
588 F8: Start selection mode
589 Esc: End selection mode
590
591 Adding Shift does the above but starts/extends selection.
592
593
594 */
595
596 bool wxRichTextCtrl::KeyboardNavigate(int keyCode, int flags)
597 {
598 bool success = false;
599
600 if (keyCode == WXK_RIGHT)
601 {
602 if (flags & wxRICHTEXT_CTRL_DOWN)
603 success = WordRight(1, flags);
604 else
605 success = MoveRight(1, flags);
606 }
607 else if (keyCode == WXK_LEFT)
608 {
609 if (flags & wxRICHTEXT_CTRL_DOWN)
610 success = WordLeft(1, flags);
611 else
612 success = MoveLeft(1, flags);
613 }
614 else if (keyCode == WXK_UP)
615 {
616 if (flags & wxRICHTEXT_CTRL_DOWN)
617 success = MoveToParagraphStart(flags);
618 else
619 success = MoveUp(1, flags);
620 }
621 else if (keyCode == WXK_DOWN)
622 {
623 if (flags & wxRICHTEXT_CTRL_DOWN)
624 success = MoveToParagraphEnd(flags);
625 else
626 success = MoveDown(1, flags);
627 }
628 else if (keyCode == WXK_PAGEUP)
629 {
630 success = PageUp(1, flags);
631 }
632 else if (keyCode == WXK_PAGEDOWN)
633 {
634 success = PageDown(1, flags);
635 }
636 else if (keyCode == WXK_HOME)
637 {
638 if (flags & wxRICHTEXT_CTRL_DOWN)
639 success = MoveHome(flags);
640 else
641 success = MoveToLineStart(flags);
642 }
643 else if (keyCode == WXK_END)
644 {
645 if (flags & wxRICHTEXT_CTRL_DOWN)
646 success = MoveEnd(flags);
647 else
648 success = MoveToLineEnd(flags);
649 }
650
651 if (success)
652 {
653 ScrollIntoView(m_caretPosition, keyCode);
654 SetDefaultStyleToCursorStyle();
655 }
656
657 return success;
658 }
659
660 /// Extend the selection. Selections are in caret positions.
661 bool wxRichTextCtrl::ExtendSelection(long oldPos, long newPos, int flags)
662 {
663 if (flags & wxRICHTEXT_SHIFT_DOWN)
664 {
665 // If not currently selecting, start selecting
666 if (m_selectionRange.GetStart() == -2)
667 {
668 m_selectionAnchor = oldPos;
669
670 if (oldPos > newPos)
671 m_selectionRange.SetRange(newPos+1, oldPos);
672 else
673 m_selectionRange.SetRange(oldPos+1, newPos);
674 }
675 else
676 {
677 // Always ensure that the selection range start is greater than
678 // the end.
679 if (newPos > m_selectionAnchor)
680 m_selectionRange.SetRange(m_selectionAnchor+1, newPos);
681 else
682 m_selectionRange.SetRange(newPos+1, m_selectionAnchor);
683 }
684
685 if (m_selectionRange.GetStart() > m_selectionRange.GetEnd())
686 {
687 wxLogDebug(wxT("Strange selection range"));
688 }
689
690 return true;
691 }
692 else
693 return false;
694 }
695
696 /// Scroll into view, returning true if we scrolled.
697 /// This takes a _caret_ position.
698 bool wxRichTextCtrl::ScrollIntoView(long position, int keyCode)
699 {
700 wxRichTextLine* line = GetVisibleLineForCaretPosition(position);
701
702 if (!line)
703 return false;
704
705 int ppuX, ppuY;
706 GetScrollPixelsPerUnit(& ppuX, & ppuY);
707
708 int startXUnits, startYUnits;
709 GetViewStart(& startXUnits, & startYUnits);
710 int startY = startYUnits * ppuY;
711
712 int sx = 0, sy = 0;
713 GetVirtualSize(& sx, & sy);
714 int sxUnits = 0;
715 int syUnits = 0;
716 if (ppuY != 0)
717 syUnits = sy/ppuY;
718
719 wxRect rect = line->GetRect();
720
721 bool scrolled = false;
722
723 wxSize clientSize = GetClientSize();
724
725 // Going down
726 if (keyCode == WXK_DOWN || keyCode == WXK_RIGHT || keyCode == WXK_END || keyCode == WXK_PAGEDOWN)
727 {
728 if ((rect.y + rect.height) > (clientSize.y + startY))
729 {
730 // Make it scroll so this item is at the bottom
731 // of the window
732 int y = rect.y - (clientSize.y - rect.height);
733 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
734
735 // If we're still off the screen, scroll another line down
736 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
737 yUnits ++;
738
739 if (startYUnits != yUnits)
740 {
741 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
742 scrolled = true;
743 }
744 }
745 else if (rect.y < startY)
746 {
747 // Make it scroll so this item is at the top
748 // of the window
749 int y = rect.y ;
750 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
751
752 if (startYUnits != yUnits)
753 {
754 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
755 scrolled = true;
756 }
757 }
758 }
759 // Going up
760 else if (keyCode == WXK_UP || keyCode == WXK_LEFT || keyCode == WXK_HOME || keyCode == WXK_PAGEUP )
761 {
762 if (rect.y < startY)
763 {
764 // Make it scroll so this item is at the top
765 // of the window
766 int y = rect.y ;
767 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
768
769 if (startYUnits != yUnits)
770 {
771 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
772 scrolled = true;
773 }
774 }
775 else if ((rect.y + rect.height) > (clientSize.y + startY))
776 {
777 // Make it scroll so this item is at the bottom
778 // of the window
779 int y = rect.y - (clientSize.y - rect.height);
780 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
781
782 // If we're still off the screen, scroll another line down
783 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
784 yUnits ++;
785
786 if (startYUnits != yUnits)
787 {
788 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
789 scrolled = true;
790 }
791 }
792 }
793 PositionCaret();
794
795 return scrolled;
796 }
797
798 /// Is the given position visible on the screen?
799 bool wxRichTextCtrl::IsPositionVisible(long pos) const
800 {
801 wxRichTextLine* line = GetVisibleLineForCaretPosition(pos-1);
802
803 if (!line)
804 return false;
805
806 int ppuX, ppuY;
807 GetScrollPixelsPerUnit(& ppuX, & ppuY);
808
809 int startX, startY;
810 GetViewStart(& startX, & startY);
811 startX = 0;
812 startY = startY * ppuY;
813
814 int sx = 0, sy = 0;
815 GetVirtualSize(& sx, & sy);
816 sx = 0;
817 if (ppuY != 0)
818 sy = sy/ppuY;
819
820 wxRect rect = line->GetRect();
821
822 wxSize clientSize = GetClientSize();
823
824 return !(((rect.y + rect.height) > (clientSize.y + startY)) || rect.y < startY);
825 }
826
827 void wxRichTextCtrl::SetCaretPosition(long position, bool showAtLineStart)
828 {
829 m_caretPosition = position;
830 m_caretAtLineStart = showAtLineStart;
831 }
832
833 /// Move caret one visual step forward: this may mean setting a flag
834 /// and keeping the same position if we're going from the end of one line
835 /// to the start of the next, which may be the exact same caret position.
836 void wxRichTextCtrl::MoveCaretForward(long oldPosition)
837 {
838 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(oldPosition);
839
840 // Only do the check if we're not at the end of the paragraph (where things work OK
841 // anyway)
842 if (para && (oldPosition != para->GetRange().GetEnd() - 1))
843 {
844 wxRichTextLine* line = GetBuffer().GetLineAtPosition(oldPosition);
845
846 if (line)
847 {
848 wxRichTextRange lineRange = line->GetAbsoluteRange();
849
850 // We're at the end of a line. See whether we need to
851 // stay at the same actual caret position but change visual
852 // position, or not.
853 if (oldPosition == lineRange.GetEnd())
854 {
855 if (m_caretAtLineStart)
856 {
857 // We're already at the start of the line, so actually move on now.
858 m_caretPosition = oldPosition + 1;
859 m_caretAtLineStart = false;
860 }
861 else
862 {
863 // We're showing at the end of the line, so keep to
864 // the same position but indicate that we're to show
865 // at the start of the next line.
866 m_caretPosition = oldPosition;
867 m_caretAtLineStart = true;
868 }
869 SetDefaultStyleToCursorStyle();
870 return;
871 }
872 }
873 }
874 m_caretPosition ++;
875 SetDefaultStyleToCursorStyle();
876 }
877
878 /// Move caret one visual step backward: this may mean setting a flag
879 /// and keeping the same position if we're going from the end of one line
880 /// to the start of the next, which may be the exact same caret position.
881 void wxRichTextCtrl::MoveCaretBack(long oldPosition)
882 {
883 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(oldPosition);
884
885 // Only do the check if we're not at the start of the paragraph (where things work OK
886 // anyway)
887 if (para && (oldPosition != para->GetRange().GetStart()))
888 {
889 wxRichTextLine* line = GetBuffer().GetLineAtPosition(oldPosition);
890
891 if (line)
892 {
893 wxRichTextRange lineRange = line->GetAbsoluteRange();
894
895 // We're at the start of a line. See whether we need to
896 // stay at the same actual caret position but change visual
897 // position, or not.
898 if (oldPosition == lineRange.GetStart())
899 {
900 m_caretPosition = oldPosition-1;
901 m_caretAtLineStart = true;
902 return;
903 }
904 else if (oldPosition == lineRange.GetEnd())
905 {
906 if (m_caretAtLineStart)
907 {
908 // We're at the start of the line, so keep the same caret position
909 // but clear the start-of-line flag.
910 m_caretPosition = oldPosition;
911 m_caretAtLineStart = false;
912 }
913 else
914 {
915 // We're showing at the end of the line, so go back
916 // to the previous character position.
917 m_caretPosition = oldPosition - 1;
918 }
919 SetDefaultStyleToCursorStyle();
920 return;
921 }
922 }
923 }
924 m_caretPosition --;
925 SetDefaultStyleToCursorStyle();
926 }
927
928 /// Move right
929 bool wxRichTextCtrl::MoveRight(int noPositions, int flags)
930 {
931 long endPos = GetBuffer().GetRange().GetEnd();
932
933 if (m_caretPosition + noPositions < endPos)
934 {
935 long oldPos = m_caretPosition;
936 long newPos = m_caretPosition + noPositions;
937
938 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
939 if (!extendSel)
940 SelectNone();
941
942 // Determine by looking at oldPos and m_caretPosition whether
943 // we moved from the end of a line to the start of the next line, in which case
944 // we want to adjust the caret position such that it is positioned at the
945 // start of the next line, rather than jumping past the first character of the
946 // line.
947 if (noPositions == 1 && !extendSel)
948 MoveCaretForward(oldPos);
949 else
950 SetCaretPosition(newPos);
951
952 PositionCaret();
953 SetDefaultStyleToCursorStyle();
954
955 if (extendSel)
956 Refresh(false);
957 return true;
958 }
959 else
960 return false;
961 }
962
963 /// Move left
964 bool wxRichTextCtrl::MoveLeft(int noPositions, int flags)
965 {
966 long startPos = -1;
967
968 if (m_caretPosition > startPos - noPositions + 1)
969 {
970 long oldPos = m_caretPosition;
971 long newPos = m_caretPosition - noPositions;
972 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
973 if (!extendSel)
974 SelectNone();
975
976 if (noPositions == 1 && !extendSel)
977 MoveCaretBack(oldPos);
978 else
979 SetCaretPosition(newPos);
980
981 PositionCaret();
982 SetDefaultStyleToCursorStyle();
983
984 if (extendSel)
985 Refresh(false);
986 return true;
987 }
988 else
989 return false;
990 }
991
992 /// Move up
993 bool wxRichTextCtrl::MoveUp(int noLines, int flags)
994 {
995 return MoveDown(- noLines, flags);
996 }
997
998 /// Move up
999 bool wxRichTextCtrl::MoveDown(int noLines, int flags)
1000 {
1001 if (!GetCaret())
1002 return false;
1003
1004 long lineNumber = GetBuffer().GetVisibleLineNumber(m_caretPosition, true, m_caretAtLineStart);
1005 wxPoint pt = GetCaret()->GetPosition();
1006 long newLine = lineNumber + noLines;
1007
1008 if (lineNumber != -1)
1009 {
1010 if (noLines > 0)
1011 {
1012 long lastLine = GetBuffer().GetVisibleLineNumber(GetBuffer().GetRange().GetEnd());
1013
1014 if (newLine > lastLine)
1015 return false;
1016 }
1017 else
1018 {
1019 if (newLine < 0)
1020 return false;
1021 }
1022 }
1023
1024 wxRichTextLine* lineObj = GetBuffer().GetLineForVisibleLineNumber(newLine);
1025 if (lineObj)
1026 {
1027 pt.y = lineObj->GetAbsolutePosition().y + 2;
1028 }
1029 else
1030 return false;
1031
1032 long newPos = 0;
1033 wxClientDC dc(this);
1034 PrepareDC(dc);
1035 dc.SetFont(GetFont());
1036
1037 int hitTest = GetBuffer().HitTest(dc, pt, newPos);
1038
1039 if (hitTest != wxRICHTEXT_HITTEST_NONE)
1040 {
1041 // If end of previous line, and hitTest is wxRICHTEXT_HITTEST_BEFORE,
1042 // we want to be at the end of the last line but with m_caretAtLineStart set to true,
1043 // so we view the caret at the start of the line.
1044 bool caretLineStart = false;
1045 if (hitTest == wxRICHTEXT_HITTEST_BEFORE)
1046 {
1047 wxRichTextLine* thisLine = GetBuffer().GetLineAtPosition(newPos-1);
1048 wxRichTextRange lineRange;
1049 if (thisLine)
1050 lineRange = thisLine->GetAbsoluteRange();
1051
1052 if (thisLine && (newPos-1) == lineRange.GetEnd())
1053 {
1054 newPos --;
1055 caretLineStart = true;
1056 }
1057 else
1058 {
1059 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(newPos);
1060 if (para && para->GetRange().GetStart() == newPos)
1061 newPos --;
1062 }
1063 }
1064
1065 long newSelEnd = newPos;
1066
1067 bool extendSel = ExtendSelection(m_caretPosition, newSelEnd, flags);
1068 if (!extendSel)
1069 SelectNone();
1070
1071 SetCaretPosition(newPos, caretLineStart);
1072 PositionCaret();
1073 SetDefaultStyleToCursorStyle();
1074
1075 if (extendSel)
1076 Refresh(false);
1077 return true;
1078 }
1079
1080 return false;
1081 }
1082
1083 /// Move to the end of the paragraph
1084 bool wxRichTextCtrl::MoveToParagraphEnd(int flags)
1085 {
1086 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(m_caretPosition, true);
1087 if (para)
1088 {
1089 long newPos = para->GetRange().GetEnd() - 1;
1090 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1091 if (!extendSel)
1092 SelectNone();
1093
1094 SetCaretPosition(newPos);
1095 PositionCaret();
1096 SetDefaultStyleToCursorStyle();
1097
1098 if (extendSel)
1099 Refresh(false);
1100 return true;
1101 }
1102
1103 return false;
1104 }
1105
1106 /// Move to the start of the paragraph
1107 bool wxRichTextCtrl::MoveToParagraphStart(int flags)
1108 {
1109 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(m_caretPosition, true);
1110 if (para)
1111 {
1112 long newPos = para->GetRange().GetStart() - 1;
1113 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1114 if (!extendSel)
1115 SelectNone();
1116
1117 SetCaretPosition(newPos);
1118 PositionCaret();
1119 SetDefaultStyleToCursorStyle();
1120
1121 if (extendSel)
1122 Refresh(false);
1123 return true;
1124 }
1125
1126 return false;
1127 }
1128
1129 /// Move to the end of the line
1130 bool wxRichTextCtrl::MoveToLineEnd(int flags)
1131 {
1132 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1133
1134 if (line)
1135 {
1136 wxRichTextRange lineRange = line->GetAbsoluteRange();
1137 long newPos = lineRange.GetEnd();
1138 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1139 if (!extendSel)
1140 SelectNone();
1141
1142 SetCaretPosition(newPos);
1143 PositionCaret();
1144 SetDefaultStyleToCursorStyle();
1145
1146 if (extendSel)
1147 Refresh(false);
1148 return true;
1149 }
1150
1151 return false;
1152 }
1153
1154 /// Move to the start of the line
1155 bool wxRichTextCtrl::MoveToLineStart(int flags)
1156 {
1157 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1158 if (line)
1159 {
1160 wxRichTextRange lineRange = line->GetAbsoluteRange();
1161 long newPos = lineRange.GetStart()-1;
1162
1163 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1164 if (!extendSel)
1165 SelectNone();
1166
1167 wxRichTextParagraph* para = GetBuffer().GetParagraphForLine(line);
1168
1169 SetCaretPosition(newPos, para->GetRange().GetStart() != lineRange.GetStart());
1170 PositionCaret();
1171 SetDefaultStyleToCursorStyle();
1172
1173 if (extendSel)
1174 Refresh(false);
1175 return true;
1176 }
1177
1178 return false;
1179 }
1180
1181 /// Move to the start of the buffer
1182 bool wxRichTextCtrl::MoveHome(int flags)
1183 {
1184 if (m_caretPosition != -1)
1185 {
1186 bool extendSel = ExtendSelection(m_caretPosition, -1, flags);
1187 if (!extendSel)
1188 SelectNone();
1189
1190 SetCaretPosition(-1);
1191 PositionCaret();
1192 SetDefaultStyleToCursorStyle();
1193
1194 if (extendSel)
1195 Refresh(false);
1196 return true;
1197 }
1198 else
1199 return false;
1200 }
1201
1202 /// Move to the end of the buffer
1203 bool wxRichTextCtrl::MoveEnd(int flags)
1204 {
1205 long endPos = GetBuffer().GetRange().GetEnd()-1;
1206
1207 if (m_caretPosition != endPos)
1208 {
1209 bool extendSel = ExtendSelection(m_caretPosition, endPos, flags);
1210 if (!extendSel)
1211 SelectNone();
1212
1213 SetCaretPosition(endPos);
1214 PositionCaret();
1215 SetDefaultStyleToCursorStyle();
1216
1217 if (extendSel)
1218 Refresh(false);
1219 return true;
1220 }
1221 else
1222 return false;
1223 }
1224
1225 /// Move noPages pages up
1226 bool wxRichTextCtrl::PageUp(int noPages, int flags)
1227 {
1228 return PageDown(- noPages, flags);
1229 }
1230
1231 /// Move noPages pages down
1232 bool wxRichTextCtrl::PageDown(int noPages, int flags)
1233 {
1234 // Calculate which line occurs noPages * screen height further down.
1235 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1236 if (line)
1237 {
1238 wxSize clientSize = GetClientSize();
1239 int newY = line->GetAbsolutePosition().y + noPages*clientSize.y;
1240
1241 wxRichTextLine* newLine = GetBuffer().GetLineAtYPosition(newY);
1242 if (newLine)
1243 {
1244 wxRichTextRange lineRange = newLine->GetAbsoluteRange();
1245 long pos = lineRange.GetStart()-1;
1246 if (pos != m_caretPosition)
1247 {
1248 wxRichTextParagraph* para = GetBuffer().GetParagraphForLine(newLine);
1249
1250 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1251 if (!extendSel)
1252 SelectNone();
1253
1254 SetCaretPosition(pos, para->GetRange().GetStart() != lineRange.GetStart());
1255 PositionCaret();
1256 SetDefaultStyleToCursorStyle();
1257
1258 if (extendSel)
1259 Refresh(false);
1260 return true;
1261 }
1262 }
1263 }
1264
1265 return false;
1266 }
1267
1268 // Finds the caret position for the next word
1269 long wxRichTextCtrl::FindNextWordPosition(int direction) const
1270 {
1271 long endPos = GetBuffer().GetRange().GetEnd();
1272
1273 if (direction > 0)
1274 {
1275 long i = m_caretPosition+1+direction; // +1 for conversion to character pos
1276
1277 // First skip current text to space
1278 while (i < endPos && i > -1)
1279 {
1280 // i is in character, not caret positions
1281 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1282 if (text != wxT(" ") && !text.empty())
1283 i += direction;
1284 else
1285 {
1286 break;
1287 }
1288 }
1289 while (i < endPos && i > -1)
1290 {
1291 // i is in character, not caret positions
1292 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1293 if (text.empty()) // End of paragraph, or maybe an image
1294 return wxMax(-1, i - 1);
1295 else if (text == wxT(" ") || text.empty())
1296 i += direction;
1297 else
1298 {
1299 // Convert to caret position
1300 return wxMax(-1, i - 1);
1301 }
1302 }
1303 if (i >= endPos)
1304 return endPos-1;
1305 return i-1;
1306 }
1307 else
1308 {
1309 long i = m_caretPosition;
1310
1311 // First skip white space
1312 while (i < endPos && i > -1)
1313 {
1314 // i is in character, not caret positions
1315 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1316 if (text.empty()) // End of paragraph, or maybe an image
1317 break;
1318 else if (text == wxT(" ") || text.empty())
1319 i += direction;
1320 else
1321 break;
1322 }
1323 // Next skip current text to space
1324 while (i < endPos && i > -1)
1325 {
1326 // i is in character, not caret positions
1327 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(i, i));
1328 if (text != wxT(" ") /* && !text.empty() */)
1329 i += direction;
1330 else
1331 {
1332 return i;
1333 }
1334 }
1335 if (i < -1)
1336 return -1;
1337 return i;
1338 }
1339 }
1340
1341 /// Move n words left
1342 bool wxRichTextCtrl::WordLeft(int WXUNUSED(n), int flags)
1343 {
1344 long pos = FindNextWordPosition(-1);
1345 if (pos != m_caretPosition)
1346 {
1347 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(pos, true);
1348
1349 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1350 if (!extendSel)
1351 SelectNone();
1352
1353 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
1354 PositionCaret();
1355 SetDefaultStyleToCursorStyle();
1356
1357 if (extendSel)
1358 Refresh(false);
1359 return true;
1360 }
1361
1362 return false;
1363 }
1364
1365 /// Move n words right
1366 bool wxRichTextCtrl::WordRight(int WXUNUSED(n), int flags)
1367 {
1368 long pos = FindNextWordPosition(1);
1369 if (pos != m_caretPosition)
1370 {
1371 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(pos, true);
1372
1373 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
1374 if (!extendSel)
1375 SelectNone();
1376
1377 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
1378 PositionCaret();
1379 SetDefaultStyleToCursorStyle();
1380
1381 if (extendSel)
1382 Refresh(false);
1383 return true;
1384 }
1385
1386 return false;
1387 }
1388
1389 /// Sizing
1390 void wxRichTextCtrl::OnSize(wxSizeEvent& event)
1391 {
1392 // Only do sizing optimization for large buffers
1393 if (GetBuffer().GetRange().GetEnd() > m_delayedLayoutThreshold)
1394 {
1395 m_fullLayoutRequired = true;
1396 m_fullLayoutTime = wxGetLocalTimeMillis();
1397 m_fullLayoutSavedPosition = GetFirstVisiblePosition();
1398 LayoutContent(true /* onlyVisibleRect */);
1399 }
1400 else
1401 GetBuffer().Invalidate(wxRICHTEXT_ALL);
1402
1403 RecreateBuffer();
1404
1405 event.Skip();
1406 }
1407
1408
1409 /// Idle-time processing
1410 void wxRichTextCtrl::OnIdle(wxIdleEvent& event)
1411 {
1412 const int layoutInterval = wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL;
1413
1414 if (m_fullLayoutRequired && (wxGetLocalTimeMillis() > (m_fullLayoutTime + layoutInterval)))
1415 {
1416 m_fullLayoutRequired = false;
1417 m_fullLayoutTime = 0;
1418 GetBuffer().Invalidate(wxRICHTEXT_ALL);
1419 ShowPosition(m_fullLayoutSavedPosition);
1420 Refresh(false);
1421 }
1422
1423 if (m_caretPositionForDefaultStyle != -2)
1424 {
1425 // If the caret position has changed, no longer reflect the default style
1426 // in the UI.
1427 if (GetCaretPosition() != m_caretPositionForDefaultStyle)
1428 m_caretPositionForDefaultStyle = -2;
1429 }
1430
1431 event.Skip();
1432 }
1433
1434 /// Scrolling
1435 void wxRichTextCtrl::OnScroll(wxScrollWinEvent& event)
1436 {
1437 // Not used
1438 event.Skip();
1439 }
1440
1441 /// Set up scrollbars, e.g. after a resize
1442 void wxRichTextCtrl::SetupScrollbars(bool atTop)
1443 {
1444 if (m_freezeCount)
1445 return;
1446
1447 if (GetBuffer().IsEmpty())
1448 {
1449 SetScrollbars(0, 0, 0, 0, 0, 0);
1450 return;
1451 }
1452
1453 // TODO: reimplement scrolling so we scroll by line, not by fixed number
1454 // of pixels. See e.g. wxVScrolledWindow for ideas.
1455 int pixelsPerUnit = 5;
1456 wxSize clientSize = GetClientSize();
1457
1458 int maxHeight = GetBuffer().GetCachedSize().y;
1459
1460 // Round up so we have at least maxHeight pixels
1461 int unitsY = (int) (((float)maxHeight/(float)pixelsPerUnit) + 0.5);
1462
1463 int startX = 0, startY = 0;
1464 if (!atTop)
1465 GetViewStart(& startX, & startY);
1466
1467 int maxPositionX = 0; // wxMax(sz.x - clientSize.x, 0);
1468 int maxPositionY = (int) ((((float)(wxMax((unitsY*pixelsPerUnit) - clientSize.y, 0)))/((float)pixelsPerUnit)) + 0.5);
1469
1470 // Move to previous scroll position if
1471 // possible
1472 SetScrollbars(0, pixelsPerUnit,
1473 0, unitsY,
1474 wxMin(maxPositionX, startX), wxMin(maxPositionY, startY));
1475 }
1476
1477 /// Paint the background
1478 void wxRichTextCtrl::PaintBackground(wxDC& dc)
1479 {
1480 wxColour backgroundColour = GetBackgroundColour();
1481 if (!backgroundColour.Ok())
1482 backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
1483
1484 // Clear the background
1485 dc.SetBrush(wxBrush(backgroundColour));
1486 dc.SetPen(*wxTRANSPARENT_PEN);
1487 wxRect windowRect(GetClientSize());
1488 windowRect.x -= 2; windowRect.y -= 2;
1489 windowRect.width += 4; windowRect.height += 4;
1490
1491 // We need to shift the rectangle to take into account
1492 // scrolling. Converting device to logical coordinates.
1493 CalcUnscrolledPosition(windowRect.x, windowRect.y, & windowRect.x, & windowRect.y);
1494 dc.DrawRectangle(windowRect);
1495 }
1496
1497 /// Recreate buffer bitmap if necessary
1498 bool wxRichTextCtrl::RecreateBuffer(const wxSize& size)
1499 {
1500 wxSize sz = size;
1501 if (sz == wxDefaultSize)
1502 sz = GetClientSize();
1503
1504 if (sz.x < 1 || sz.y < 1)
1505 return false;
1506
1507 if (!m_bufferBitmap.Ok() || m_bufferBitmap.GetWidth() < sz.x || m_bufferBitmap.GetHeight() < sz.y)
1508 m_bufferBitmap = wxBitmap(sz.x, sz.y);
1509 return m_bufferBitmap.Ok();
1510 }
1511
1512 // ----------------------------------------------------------------------------
1513 // file IO functions
1514 // ----------------------------------------------------------------------------
1515
1516 #if !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
1517 bool wxRichTextCtrl::LoadFile(const wxString& filename, int fileType)
1518 {
1519 return DoLoadFile(filename, fileType);
1520 }
1521
1522 bool wxRichTextCtrl::SaveFile(const wxString& filename, int fileType)
1523 {
1524 wxString filenameToUse = filename.empty() ? m_filename : filename;
1525 if ( filenameToUse.empty() )
1526 {
1527 // what kind of message to give? is it an error or a program bug?
1528 wxLogDebug(wxT("Can't save textctrl to file without filename."));
1529
1530 return false;
1531 }
1532
1533 return DoSaveFile(filenameToUse, fileType);
1534 }
1535 #endif
1536
1537 bool wxRichTextCtrl::DoLoadFile(const wxString& filename, int fileType)
1538 {
1539 bool success = GetBuffer().LoadFile(filename, fileType);
1540 if (success)
1541 m_filename = filename;
1542
1543 DiscardEdits();
1544 SetInsertionPoint(0);
1545 LayoutContent();
1546 PositionCaret();
1547 SetupScrollbars(true);
1548 Refresh(false);
1549 SendUpdateEvent();
1550
1551 if (success)
1552 return true;
1553 else
1554 {
1555 wxLogError(_("File couldn't be loaded."));
1556
1557 return false;
1558 }
1559 }
1560
1561 bool wxRichTextCtrl::DoSaveFile(const wxString& filename, int fileType)
1562 {
1563 if (GetBuffer().SaveFile(filename, fileType))
1564 {
1565 m_filename = filename;
1566
1567 DiscardEdits();
1568
1569 return true;
1570 }
1571
1572 wxLogError(_("The text couldn't be saved."));
1573
1574 return false;
1575 }
1576
1577 // ----------------------------------------------------------------------------
1578 // wxRichTextCtrl specific functionality
1579 // ----------------------------------------------------------------------------
1580
1581 /// Add a new paragraph of text to the end of the buffer
1582 wxRichTextRange wxRichTextCtrl::AddParagraph(const wxString& text)
1583 {
1584 return GetBuffer().AddParagraph(text);
1585 }
1586
1587 /// Add an image
1588 wxRichTextRange wxRichTextCtrl::AddImage(const wxImage& image)
1589 {
1590 return GetBuffer().AddImage(image);
1591 }
1592
1593 // ----------------------------------------------------------------------------
1594 // selection and ranges
1595 // ----------------------------------------------------------------------------
1596
1597 void wxRichTextCtrl::SelectAll()
1598 {
1599 SetSelection(0, GetLastPosition()+1);
1600 m_selectionAnchor = -1;
1601 }
1602
1603 /// Select none
1604 void wxRichTextCtrl::SelectNone()
1605 {
1606 if (!(GetSelectionRange() == wxRichTextRange(-2, -2)))
1607 SetSelection(-2, -2);
1608 m_selectionAnchor = -2;
1609 }
1610
1611 static bool wxIsWordDelimiter(const wxString& text)
1612 {
1613 return !text.IsEmpty() && !wxIsalnum(text[0]);
1614 }
1615
1616 /// Select the word at the given character position
1617 bool wxRichTextCtrl::SelectWord(long position)
1618 {
1619 if (position < 0 || position > GetBuffer().GetRange().GetEnd())
1620 return false;
1621
1622 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
1623 if (!para)
1624 return false;
1625
1626 long positionStart = position;
1627 long positionEnd = position;
1628
1629 for (positionStart = position; positionStart >= para->GetRange().GetStart(); positionStart --)
1630 {
1631 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionStart, positionStart));
1632 if (wxIsWordDelimiter(text))
1633 {
1634 positionStart ++;
1635 break;
1636 }
1637 }
1638 if (positionStart < para->GetRange().GetStart())
1639 positionStart = para->GetRange().GetStart();
1640
1641 for (positionEnd = position; positionEnd < para->GetRange().GetEnd(); positionEnd ++)
1642 {
1643 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionEnd, positionEnd));
1644 if (wxIsWordDelimiter(text))
1645 {
1646 positionEnd --;
1647 break;
1648 }
1649 }
1650 if (positionEnd >= para->GetRange().GetEnd())
1651 positionEnd = para->GetRange().GetEnd();
1652
1653 SetSelection(positionStart, positionEnd+1);
1654
1655 if (positionStart >= 0)
1656 {
1657 MoveCaret(positionStart-1, true);
1658 SetDefaultStyleToCursorStyle();
1659 }
1660
1661 return true;
1662 }
1663
1664 wxString wxRichTextCtrl::GetStringSelection() const
1665 {
1666 long from, to;
1667 GetSelection(&from, &to);
1668
1669 return GetRange(from, to);
1670 }
1671
1672 // do the window-specific processing after processing the update event
1673 #if !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
1674 void wxRichTextCtrl::DoUpdateWindowUI(wxUpdateUIEvent& event)
1675 {
1676 // call inherited
1677 wxWindowBase::DoUpdateWindowUI(event);
1678
1679 // update text
1680 if ( event.GetSetText() )
1681 {
1682 if ( event.GetText() != GetValue() )
1683 SetValue(event.GetText());
1684 }
1685 }
1686 #endif // !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
1687
1688 // ----------------------------------------------------------------------------
1689 // hit testing
1690 // ----------------------------------------------------------------------------
1691
1692 wxTextCtrlHitTestResult
1693 wxRichTextCtrl::HitTest(const wxPoint& pt, wxTextCoord *x, wxTextCoord *y) const
1694 {
1695 // implement in terms of the other overload as the native ports typically
1696 // can get the position and not (x, y) pair directly (although wxUniv
1697 // directly gets x and y -- and so overrides this method as well)
1698 long pos;
1699 wxTextCtrlHitTestResult rc = HitTest(pt, &pos);
1700
1701 if ( rc != wxTE_HT_UNKNOWN )
1702 {
1703 PositionToXY(pos, x, y);
1704 }
1705
1706 return rc;
1707 }
1708
1709 wxTextCtrlHitTestResult
1710 wxRichTextCtrl::HitTest(const wxPoint& pt,
1711 long * pos) const
1712 {
1713 wxClientDC dc((wxRichTextCtrl*) this);
1714 ((wxRichTextCtrl*)this)->PrepareDC(dc);
1715
1716 // Buffer uses logical position (relative to start of buffer)
1717 // so convert
1718 wxPoint pt2 = GetLogicalPoint(pt);
1719
1720 int hit = ((wxRichTextCtrl*)this)->GetBuffer().HitTest(dc, pt2, *pos);
1721
1722 switch ( hit )
1723 {
1724 case wxRICHTEXT_HITTEST_BEFORE:
1725 return wxTE_HT_BEFORE;
1726
1727 case wxRICHTEXT_HITTEST_AFTER:
1728 return wxTE_HT_BEYOND;
1729
1730 case wxRICHTEXT_HITTEST_ON:
1731 return wxTE_HT_ON_TEXT;
1732 }
1733
1734 return wxTE_HT_UNKNOWN;
1735 }
1736
1737 // ----------------------------------------------------------------------------
1738 // set/get the controls text
1739 // ----------------------------------------------------------------------------
1740
1741 wxString wxRichTextCtrl::GetValue() const
1742 {
1743 return GetBuffer().GetText();
1744 }
1745
1746 wxString wxRichTextCtrl::GetRange(long from, long to) const
1747 {
1748 // Public API for range is different from internals
1749 return GetBuffer().GetTextForRange(wxRichTextRange(from, to-1));
1750 }
1751
1752 void wxRichTextCtrl::SetValue(const wxString& value)
1753 {
1754 Clear();
1755
1756 // if the text is long enough, it's faster to just set it instead of first
1757 // comparing it with the old one (chances are that it will be different
1758 // anyhow, this comparison is there to avoid flicker for small single-line
1759 // edit controls mostly)
1760 if ( (value.length() > 0x400) || (value != GetValue()) )
1761 {
1762 DoWriteText(value, false /* not selection only */);
1763
1764 // for compatibility, don't move the cursor when doing SetValue()
1765 SetInsertionPoint(0);
1766 }
1767 else // same text
1768 {
1769 // still send an event for consistency
1770 SendUpdateEvent();
1771 }
1772
1773 // we should reset the modified flag even if the value didn't really change
1774
1775 // mark the control as being not dirty - we changed its text, not the
1776 // user
1777 DiscardEdits();
1778 }
1779
1780 void wxRichTextCtrl::WriteText(const wxString& value)
1781 {
1782 DoWriteText(value);
1783 }
1784
1785 void wxRichTextCtrl::DoWriteText(const wxString& value, bool WXUNUSED(selectionOnly))
1786 {
1787 wxString valueUnix = wxTextFile::Translate(value, wxTextFileType_Unix);
1788
1789 GetBuffer().InsertTextWithUndo(m_caretPosition+1, valueUnix, this);
1790 }
1791
1792 void wxRichTextCtrl::AppendText(const wxString& text)
1793 {
1794 SetInsertionPointEnd();
1795
1796 WriteText(text);
1797 }
1798
1799 /// Write an image at the current insertion point
1800 bool wxRichTextCtrl::WriteImage(const wxImage& image, int bitmapType)
1801 {
1802 wxRichTextImageBlock imageBlock;
1803
1804 wxImage image2 = image;
1805 if (imageBlock.MakeImageBlock(image2, bitmapType))
1806 return WriteImage(imageBlock);
1807
1808 return false;
1809 }
1810
1811 bool wxRichTextCtrl::WriteImage(const wxString& filename, int bitmapType)
1812 {
1813 wxRichTextImageBlock imageBlock;
1814
1815 wxImage image;
1816 if (imageBlock.MakeImageBlock(filename, bitmapType, image, false))
1817 return WriteImage(imageBlock);
1818
1819 return false;
1820 }
1821
1822 bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock& imageBlock)
1823 {
1824 return GetBuffer().InsertImageWithUndo(m_caretPosition+1, imageBlock, this);
1825 }
1826
1827 bool wxRichTextCtrl::WriteImage(const wxBitmap& bitmap, int bitmapType)
1828 {
1829 if (bitmap.Ok())
1830 {
1831 wxRichTextImageBlock imageBlock;
1832
1833 wxImage image = bitmap.ConvertToImage();
1834 if (image.Ok() && imageBlock.MakeImageBlock(image, bitmapType))
1835 return WriteImage(imageBlock);
1836 }
1837
1838 return false;
1839 }
1840
1841 /// Insert a newline (actually paragraph) at the current insertion point.
1842 bool wxRichTextCtrl::Newline()
1843 {
1844 return GetBuffer().InsertNewlineWithUndo(m_caretPosition+1, this);
1845 }
1846
1847
1848 // ----------------------------------------------------------------------------
1849 // Clipboard operations
1850 // ----------------------------------------------------------------------------
1851
1852 void wxRichTextCtrl::Copy()
1853 {
1854 if (CanCopy())
1855 {
1856 wxRichTextRange range = GetInternalSelectionRange();
1857 GetBuffer().CopyToClipboard(range);
1858 }
1859 }
1860
1861 void wxRichTextCtrl::Cut()
1862 {
1863 if (CanCut())
1864 {
1865 wxRichTextRange range = GetInternalSelectionRange();
1866 GetBuffer().CopyToClipboard(range);
1867
1868 DeleteSelectedContent();
1869 LayoutContent();
1870 Refresh(false);
1871 }
1872 }
1873
1874 void wxRichTextCtrl::Paste()
1875 {
1876 if (CanPaste())
1877 {
1878 BeginBatchUndo(_("Paste"));
1879
1880 long newPos = m_caretPosition;
1881 DeleteSelectedContent(& newPos);
1882
1883 GetBuffer().PasteFromClipboard(newPos);
1884
1885 EndBatchUndo();
1886 }
1887 }
1888
1889 void wxRichTextCtrl::DeleteSelection()
1890 {
1891 if (CanDeleteSelection())
1892 {
1893 DeleteSelectedContent();
1894 }
1895 }
1896
1897 bool wxRichTextCtrl::HasSelection() const
1898 {
1899 return m_selectionRange.GetStart() != -2 && m_selectionRange.GetEnd() != -2;
1900 }
1901
1902 bool wxRichTextCtrl::CanCopy() const
1903 {
1904 // Can copy if there's a selection
1905 return HasSelection();
1906 }
1907
1908 bool wxRichTextCtrl::CanCut() const
1909 {
1910 return HasSelection() && IsEditable();
1911 }
1912
1913 bool wxRichTextCtrl::CanPaste() const
1914 {
1915 if ( !IsEditable() )
1916 return false;
1917
1918 return GetBuffer().CanPasteFromClipboard();
1919 }
1920
1921 bool wxRichTextCtrl::CanDeleteSelection() const
1922 {
1923 return HasSelection() && IsEditable();
1924 }
1925
1926
1927 // ----------------------------------------------------------------------------
1928 // Accessors
1929 // ----------------------------------------------------------------------------
1930
1931 void wxRichTextCtrl::SetEditable(bool editable)
1932 {
1933 m_editable = editable;
1934 }
1935
1936 void wxRichTextCtrl::SetInsertionPoint(long pos)
1937 {
1938 SelectNone();
1939
1940 m_caretPosition = pos - 1;
1941 }
1942
1943 void wxRichTextCtrl::SetInsertionPointEnd()
1944 {
1945 long pos = GetLastPosition();
1946 SetInsertionPoint(pos);
1947 }
1948
1949 long wxRichTextCtrl::GetInsertionPoint() const
1950 {
1951 return m_caretPosition+1;
1952 }
1953
1954 wxTextPos wxRichTextCtrl::GetLastPosition() const
1955 {
1956 return GetBuffer().GetRange().GetEnd();
1957 }
1958
1959 // If the return values from and to are the same, there is no
1960 // selection.
1961 void wxRichTextCtrl::GetSelection(long* from, long* to) const
1962 {
1963 *from = m_selectionRange.GetStart();
1964 *to = m_selectionRange.GetEnd();
1965 if ((*to) != -1 && (*to) != -2)
1966 (*to) ++;
1967 }
1968
1969 bool wxRichTextCtrl::IsEditable() const
1970 {
1971 return m_editable;
1972 }
1973
1974 // ----------------------------------------------------------------------------
1975 // selection
1976 // ----------------------------------------------------------------------------
1977
1978 void wxRichTextCtrl::SetSelection(long from, long to)
1979 {
1980 // if from and to are both -1, it means (in wxWidgets) that all text should
1981 // be selected.
1982 if ( (from == -1) && (to == -1) )
1983 {
1984 from = 0;
1985 to = GetLastPosition()+1;
1986 }
1987
1988 DoSetSelection(from, to);
1989 }
1990
1991 void wxRichTextCtrl::DoSetSelection(long from, long to, bool WXUNUSED(scrollCaret))
1992 {
1993 m_selectionAnchor = from;
1994 m_selectionRange.SetRange(from, to-1);
1995
1996 Refresh(false);
1997 PositionCaret();
1998 }
1999
2000 // ----------------------------------------------------------------------------
2001 // Editing
2002 // ----------------------------------------------------------------------------
2003
2004 void wxRichTextCtrl::Replace(long WXUNUSED(from), long WXUNUSED(to), const wxString& value)
2005 {
2006 BeginBatchUndo(_("Replace"));
2007
2008 DeleteSelectedContent();
2009
2010 DoWriteText(value, true /* selection only */);
2011
2012 EndBatchUndo();
2013 }
2014
2015 void wxRichTextCtrl::Remove(long from, long to)
2016 {
2017 SelectNone();
2018
2019 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(from, to),
2020 m_caretPosition, // Current caret position
2021 from, // New caret position
2022 this);
2023
2024 LayoutContent();
2025 if (!IsFrozen())
2026 Refresh(false);
2027 }
2028
2029 bool wxRichTextCtrl::IsModified() const
2030 {
2031 return m_buffer.IsModified();
2032 }
2033
2034 void wxRichTextCtrl::MarkDirty()
2035 {
2036 m_buffer.Modify(true);
2037 }
2038
2039 void wxRichTextCtrl::DiscardEdits()
2040 {
2041 m_caretPositionForDefaultStyle = -2;
2042 m_buffer.Modify(false);
2043 m_buffer.GetCommandProcessor()->ClearCommands();
2044 }
2045
2046 int wxRichTextCtrl::GetNumberOfLines() const
2047 {
2048 return GetBuffer().GetParagraphCount();
2049 }
2050
2051 // ----------------------------------------------------------------------------
2052 // Positions <-> coords
2053 // ----------------------------------------------------------------------------
2054
2055 long wxRichTextCtrl::XYToPosition(long x, long y) const
2056 {
2057 return GetBuffer().XYToPosition(x, y);
2058 }
2059
2060 bool wxRichTextCtrl::PositionToXY(long pos, long *x, long *y) const
2061 {
2062 return GetBuffer().PositionToXY(pos, x, y);
2063 }
2064
2065 // ----------------------------------------------------------------------------
2066 //
2067 // ----------------------------------------------------------------------------
2068
2069 void wxRichTextCtrl::ShowPosition(long pos)
2070 {
2071 if (!IsPositionVisible(pos))
2072 ScrollIntoView(pos-1, WXK_DOWN);
2073 }
2074
2075 int wxRichTextCtrl::GetLineLength(long lineNo) const
2076 {
2077 return GetBuffer().GetParagraphLength(lineNo);
2078 }
2079
2080 wxString wxRichTextCtrl::GetLineText(long lineNo) const
2081 {
2082 return GetBuffer().GetParagraphText(lineNo);
2083 }
2084
2085 // ----------------------------------------------------------------------------
2086 // Undo/redo
2087 // ----------------------------------------------------------------------------
2088
2089 void wxRichTextCtrl::Undo()
2090 {
2091 if (CanUndo())
2092 {
2093 GetCommandProcessor()->Undo();
2094 }
2095 }
2096
2097 void wxRichTextCtrl::Redo()
2098 {
2099 if (CanRedo())
2100 {
2101 GetCommandProcessor()->Redo();
2102 }
2103 }
2104
2105 bool wxRichTextCtrl::CanUndo() const
2106 {
2107 return GetCommandProcessor()->CanUndo();
2108 }
2109
2110 bool wxRichTextCtrl::CanRedo() const
2111 {
2112 return GetCommandProcessor()->CanRedo();
2113 }
2114
2115 // ----------------------------------------------------------------------------
2116 // implementation details
2117 // ----------------------------------------------------------------------------
2118
2119 void wxRichTextCtrl::Command(wxCommandEvent& event)
2120 {
2121 SetValue(event.GetString());
2122 GetEventHandler()->ProcessEvent(event);
2123 }
2124
2125 void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent& event)
2126 {
2127 // By default, load the first file into the text window.
2128 if (event.GetNumberOfFiles() > 0)
2129 {
2130 LoadFile(event.GetFiles()[0]);
2131 }
2132 }
2133
2134 // ----------------------------------------------------------------------------
2135 // text control event processing
2136 // ----------------------------------------------------------------------------
2137
2138 bool wxRichTextCtrl::SendUpdateEvent()
2139 {
2140 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
2141 InitCommandEvent(event);
2142
2143 return GetEventHandler()->ProcessEvent(event);
2144 }
2145
2146 void wxRichTextCtrl::InitCommandEvent(wxCommandEvent& event) const
2147 {
2148 event.SetEventObject((wxControlBase *)this); // const_cast
2149
2150 switch ( m_clientDataType )
2151 {
2152 case wxClientData_Void:
2153 event.SetClientData(GetClientData());
2154 break;
2155
2156 case wxClientData_Object:
2157 event.SetClientObject(GetClientObject());
2158 break;
2159
2160 case wxClientData_None:
2161 // nothing to do
2162 ;
2163 }
2164 }
2165
2166
2167 wxSize wxRichTextCtrl::DoGetBestSize() const
2168 {
2169 return wxSize(10, 10);
2170 }
2171
2172 // ----------------------------------------------------------------------------
2173 // standard handlers for standard edit menu events
2174 // ----------------------------------------------------------------------------
2175
2176 void wxRichTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
2177 {
2178 Cut();
2179 }
2180
2181 void wxRichTextCtrl::OnClear(wxCommandEvent& WXUNUSED(event))
2182 {
2183 DeleteSelection();
2184 }
2185
2186 void wxRichTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
2187 {
2188 Copy();
2189 }
2190
2191 void wxRichTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
2192 {
2193 Paste();
2194 }
2195
2196 void wxRichTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
2197 {
2198 Undo();
2199 }
2200
2201 void wxRichTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
2202 {
2203 Redo();
2204 }
2205
2206 void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
2207 {
2208 event.Enable( CanCut() );
2209 }
2210
2211 void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
2212 {
2213 event.Enable( CanCopy() );
2214 }
2215
2216 void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent& event)
2217 {
2218 event.Enable( CanDeleteSelection() );
2219 }
2220
2221 void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
2222 {
2223 event.Enable( CanPaste() );
2224 }
2225
2226 void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
2227 {
2228 event.Enable( CanUndo() );
2229 event.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
2230 }
2231
2232 void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
2233 {
2234 event.Enable( CanRedo() );
2235 event.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
2236 }
2237
2238 void wxRichTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
2239 {
2240 SelectAll();
2241 }
2242
2243 void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
2244 {
2245 event.Enable(GetLastPosition() > 0);
2246 }
2247
2248 void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent& WXUNUSED(event))
2249 {
2250 if (!m_contextMenu)
2251 {
2252 m_contextMenu = new wxMenu;
2253 m_contextMenu->Append(wxID_UNDO, _("&Undo"));
2254 m_contextMenu->Append(wxID_REDO, _("&Redo"));
2255 m_contextMenu->AppendSeparator();
2256 m_contextMenu->Append(wxID_CUT, _("Cu&t"));
2257 m_contextMenu->Append(wxID_COPY, _("&Copy"));
2258 m_contextMenu->Append(wxID_PASTE, _("&Paste"));
2259 m_contextMenu->Append(wxID_CLEAR, _("&Delete"));
2260 m_contextMenu->AppendSeparator();
2261 m_contextMenu->Append(wxID_SELECTALL, _("Select &All"));
2262 }
2263 PopupMenu(m_contextMenu);
2264 return;
2265 }
2266
2267 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttrEx& style)
2268 {
2269 return GetBuffer().SetStyle(wxRichTextRange(start, end-1), style);
2270 }
2271
2272 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
2273 {
2274 return GetBuffer().SetStyle(wxRichTextRange(start, end-1), wxTextAttrEx(style));
2275 }
2276
2277 bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style)
2278 {
2279 return GetBuffer().SetStyle(range.ToInternal(), style);
2280 }
2281
2282 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttrEx& style)
2283 {
2284 return GetBuffer().SetDefaultStyle(style);
2285 }
2286
2287 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr& style)
2288 {
2289 return GetBuffer().SetDefaultStyle(wxTextAttrEx(style));
2290 }
2291
2292 const wxTextAttrEx& wxRichTextCtrl::GetDefaultStyleEx() const
2293 {
2294 return GetBuffer().GetDefaultStyle();
2295 }
2296
2297 const wxTextAttr& wxRichTextCtrl::GetDefaultStyle() const
2298 {
2299 return GetBuffer().GetDefaultStyle();
2300 }
2301
2302 bool wxRichTextCtrl::GetStyle(long position, wxTextAttr& style)
2303 {
2304 wxTextAttrEx attr(style);
2305 if (GetBuffer().GetStyle(position, attr))
2306 {
2307 style = attr;
2308 return true;
2309 }
2310 else
2311 return false;
2312 }
2313
2314 bool wxRichTextCtrl::GetStyle(long position, wxTextAttrEx& style)
2315 {
2316 return GetBuffer().GetStyle(position, style);
2317 }
2318
2319 bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style)
2320 {
2321 return GetBuffer().GetStyle(position, style);
2322 }
2323
2324 /// Get the content (uncombined) attributes for this position.
2325
2326 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxTextAttr& style)
2327 {
2328 wxTextAttrEx attr(style);
2329 if (GetBuffer().GetUncombinedStyle(position, attr))
2330 {
2331 style = attr;
2332 return true;
2333 }
2334 else
2335 return false;
2336 }
2337
2338 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxTextAttrEx& style)
2339 {
2340 return GetBuffer().GetUncombinedStyle(position, style);
2341 }
2342
2343 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style)
2344 {
2345 return GetBuffer().GetUncombinedStyle(position, style);
2346 }
2347
2348 /// Set font, and also the buffer attributes
2349 bool wxRichTextCtrl::SetFont(const wxFont& font)
2350 {
2351 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
2352 wxControl::SetFont(font);
2353 #else
2354 wxScrolledWindow::SetFont(font);
2355 #endif
2356
2357 wxTextAttrEx attr = GetBuffer().GetAttributes();
2358 attr.SetFont(font);
2359 GetBuffer().SetBasicStyle(attr);
2360
2361 #if !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
2362 // Don't set the default style, since it will be inherited from
2363 // the basic style.
2364 GetBuffer().SetDefaultStyle(attr);
2365 #endif
2366
2367 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2368 Refresh(false);
2369
2370 return true;
2371 }
2372
2373 /// Transform logical to physical
2374 wxPoint wxRichTextCtrl::GetPhysicalPoint(const wxPoint& ptLogical) const
2375 {
2376 wxPoint pt;
2377 CalcScrolledPosition(ptLogical.x, ptLogical.y, & pt.x, & pt.y);
2378
2379 return pt;
2380 }
2381
2382 /// Transform physical to logical
2383 wxPoint wxRichTextCtrl::GetLogicalPoint(const wxPoint& ptPhysical) const
2384 {
2385 wxPoint pt;
2386 CalcUnscrolledPosition(ptPhysical.x, ptPhysical.y, & pt.x, & pt.y);
2387
2388 return pt;
2389 }
2390
2391 /// Position the caret
2392 void wxRichTextCtrl::PositionCaret()
2393 {
2394 if (!GetCaret())
2395 return;
2396
2397 //wxLogDebug(wxT("PositionCaret"));
2398
2399 wxRect caretRect;
2400 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect))
2401 {
2402 wxPoint originalPt = caretRect.GetPosition();
2403 wxPoint pt = GetPhysicalPoint(originalPt);
2404 if (GetCaret()->GetPosition() != pt)
2405 {
2406 GetCaret()->Move(pt);
2407 GetCaret()->SetSize(caretRect.GetSize());
2408 }
2409 }
2410 }
2411
2412 /// Get the caret height and position for the given character position
2413 bool wxRichTextCtrl::GetCaretPositionForIndex(long position, wxRect& rect)
2414 {
2415 wxClientDC dc(this);
2416 dc.SetFont(GetFont());
2417
2418 PrepareDC(dc);
2419
2420 wxPoint pt;
2421 int height = 0;
2422
2423 if (GetBuffer().FindPosition(dc, position, pt, & height, m_caretAtLineStart))
2424 {
2425 rect = wxRect(pt, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH, height));
2426 return true;
2427 }
2428
2429 return false;
2430 }
2431
2432 /// Gets the line for the visible caret position. If the caret is
2433 /// shown at the very end of the line, it means the next character is actually
2434 /// on the following line. So let's get the line we're expecting to find
2435 /// if this is the case.
2436 wxRichTextLine* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition) const
2437 {
2438 wxRichTextLine* line = GetBuffer().GetLineAtPosition(caretPosition, true);
2439 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPosition, true);
2440 if (line)
2441 {
2442 wxRichTextRange lineRange = line->GetAbsoluteRange();
2443 if (caretPosition == lineRange.GetStart()-1 &&
2444 (para->GetRange().GetStart() != lineRange.GetStart()))
2445 {
2446 if (!m_caretAtLineStart)
2447 line = GetBuffer().GetLineAtPosition(caretPosition-1, true);
2448 }
2449 }
2450 return line;
2451 }
2452
2453
2454 /// Move the caret to the given character position
2455 bool wxRichTextCtrl::MoveCaret(long pos, bool showAtLineStart)
2456 {
2457 if (GetBuffer().GetDirty())
2458 LayoutContent();
2459
2460 if (pos <= GetBuffer().GetRange().GetEnd())
2461 {
2462 SetCaretPosition(pos, showAtLineStart);
2463
2464 PositionCaret();
2465
2466 return true;
2467 }
2468 else
2469 return false;
2470 }
2471
2472 /// Layout the buffer: which we must do before certain operations, such as
2473 /// setting the caret position.
2474 bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect)
2475 {
2476 if (GetBuffer().GetDirty() || onlyVisibleRect)
2477 {
2478 wxRect availableSpace(GetClientSize());
2479 if (availableSpace.width == 0)
2480 availableSpace.width = 10;
2481 if (availableSpace.height == 0)
2482 availableSpace.height = 10;
2483
2484 int flags = wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT;
2485 if (onlyVisibleRect)
2486 {
2487 flags |= wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
2488 availableSpace.SetPosition(GetLogicalPoint(wxPoint(0, 0)));
2489 }
2490
2491 wxClientDC dc(this);
2492 dc.SetFont(GetFont());
2493
2494 PrepareDC(dc);
2495
2496 GetBuffer().Defragment();
2497 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
2498 GetBuffer().Layout(dc, availableSpace, flags);
2499 GetBuffer().SetDirty(false);
2500
2501 if (!IsFrozen())
2502 SetupScrollbars();
2503 }
2504
2505 return true;
2506 }
2507
2508 /// Is all of the selection bold?
2509 bool wxRichTextCtrl::IsSelectionBold()
2510 {
2511 if (HasSelection())
2512 {
2513 wxRichTextAttr attr;
2514 wxRichTextRange range = GetInternalSelectionRange();
2515 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2516 attr.SetFontWeight(wxBOLD);
2517
2518 return HasCharacterAttributes(range, attr);
2519 }
2520 else
2521 {
2522 // If no selection, then we need to combine current style with default style
2523 // to see what the effect would be if we started typing.
2524 wxRichTextAttr attr;
2525 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2526
2527 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2528 if (GetStyle(pos, attr))
2529 {
2530 if (IsDefaultStyleShowing())
2531 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2532 return attr.GetFontWeight() == wxBOLD;
2533 }
2534 }
2535 return false;
2536 }
2537
2538 /// Is all of the selection italics?
2539 bool wxRichTextCtrl::IsSelectionItalics()
2540 {
2541 if (HasSelection())
2542 {
2543 wxRichTextRange range = GetInternalSelectionRange();
2544 wxRichTextAttr attr;
2545 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2546 attr.SetFontStyle(wxITALIC);
2547
2548 return HasCharacterAttributes(range, attr);
2549 }
2550 else
2551 {
2552 // If no selection, then we need to combine current style with default style
2553 // to see what the effect would be if we started typing.
2554 wxRichTextAttr attr;
2555 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2556
2557 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2558 if (GetStyle(pos, attr))
2559 {
2560 if (IsDefaultStyleShowing())
2561 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2562 return attr.GetFontStyle() == wxITALIC;
2563 }
2564 }
2565 return false;
2566 }
2567
2568 /// Is all of the selection underlined?
2569 bool wxRichTextCtrl::IsSelectionUnderlined()
2570 {
2571 if (HasSelection())
2572 {
2573 wxRichTextRange range = GetInternalSelectionRange();
2574 wxRichTextAttr attr;
2575 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2576 attr.SetFontUnderlined(true);
2577
2578 return HasCharacterAttributes(range, attr);
2579 }
2580 else
2581 {
2582 // If no selection, then we need to combine current style with default style
2583 // to see what the effect would be if we started typing.
2584 wxRichTextAttr attr;
2585 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2586 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2587
2588 if (GetStyle(pos, attr))
2589 {
2590 if (IsDefaultStyleShowing())
2591 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2592 return attr.GetFontUnderlined();
2593 }
2594 }
2595 return false;
2596 }
2597
2598 /// Apply bold to the selection
2599 bool wxRichTextCtrl::ApplyBoldToSelection()
2600 {
2601 wxRichTextAttr attr;
2602 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2603 attr.SetFontWeight(IsSelectionBold() ? wxNORMAL : wxBOLD);
2604
2605 if (HasSelection())
2606 return SetStyle(GetSelectionRange(), attr);
2607 else
2608 SetAndShowDefaultStyle(attr);
2609 return true;
2610 }
2611
2612 /// Apply italic to the selection
2613 bool wxRichTextCtrl::ApplyItalicToSelection()
2614 {
2615 wxRichTextAttr attr;
2616 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2617 attr.SetFontStyle(IsSelectionItalics() ? wxNORMAL : wxITALIC);
2618
2619 if (HasSelection())
2620 return SetStyle(GetSelectionRange(), attr);
2621 else
2622 SetAndShowDefaultStyle(attr);
2623 return true;
2624 }
2625
2626 /// Apply underline to the selection
2627 bool wxRichTextCtrl::ApplyUnderlineToSelection()
2628 {
2629 wxRichTextAttr attr;
2630 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2631 attr.SetFontUnderlined(!IsSelectionUnderlined());
2632
2633 if (HasSelection())
2634 return SetStyle(GetSelectionRange(), attr);
2635 else
2636 SetAndShowDefaultStyle(attr);
2637 return true;
2638 }
2639
2640 /// Is all of the selection aligned according to the specified flag?
2641 bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment)
2642 {
2643 wxRichTextRange range;
2644 if (HasSelection())
2645 range = GetInternalSelectionRange();
2646 else
2647 range = wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+1);
2648
2649 wxRichTextAttr attr;
2650 attr.SetAlignment(alignment);
2651
2652 return HasParagraphAttributes(range, attr);
2653 }
2654
2655 /// Apply alignment to the selection
2656 bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment)
2657 {
2658 wxRichTextAttr attr;
2659 attr.SetAlignment(alignment);
2660 if (HasSelection())
2661 return SetStyle(GetSelectionRange(), attr);
2662 else
2663 {
2664 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(GetCaretPosition()+1);
2665 if (para)
2666 return SetStyle(para->GetRange().FromInternal(), attr);
2667 }
2668 return true;
2669 }
2670
2671 /// Apply a named style to the selection
2672 void wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition* def)
2673 {
2674 // Flags are defined within each definition, so only certain
2675 // attributes are applied.
2676 wxRichTextAttr attr(def->GetStyle());
2677
2678 // Make sure the attr has the style name
2679 if (def->IsKindOf(CLASSINFO(wxRichTextParagraphStyleDefinition)))
2680 attr.SetParagraphStyleName(def->GetName());
2681 else
2682 attr.SetCharacterStyleName(def->GetName());
2683
2684 if (HasSelection())
2685 SetStyle(GetSelectionRange(), attr);
2686 else
2687 SetAndShowDefaultStyle(attr);
2688 }
2689
2690 /// Apply the style sheet to the buffer, for example if the styles have changed.
2691 bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
2692 {
2693 if (!styleSheet)
2694 styleSheet = GetBuffer().GetStyleSheet();
2695 if (!styleSheet)
2696 return false;
2697
2698 if (GetBuffer().ApplyStyleSheet(styleSheet))
2699 {
2700 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2701 Refresh(false);
2702 return true;
2703 }
2704 else
2705 return false;
2706 }
2707
2708 /// Sets the default style to the style under the cursor
2709 bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
2710 {
2711 wxTextAttrEx attr;
2712 attr.SetFlags(wxTEXT_ATTR_CHARACTER);
2713
2714 // If at the start of a paragraph, use the next position.
2715 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2716
2717 #if wxRICHTEXT_USE_DYNAMIC_STYLES
2718 if (GetUncombinedStyle(pos, attr))
2719 #else
2720 if (GetStyle(pos, attr))
2721 #endif
2722 {
2723 SetDefaultStyle(attr);
2724 return true;
2725 }
2726
2727 return false;
2728 }
2729
2730 /// Returns the first visible position in the current view
2731 long wxRichTextCtrl::GetFirstVisiblePosition() const
2732 {
2733 wxRichTextLine* line = GetBuffer().GetLineAtYPosition(GetLogicalPoint(wxPoint(0, 0)).y);
2734 if (line)
2735 return line->GetAbsoluteRange().GetStart();
2736 else
2737 return 0;
2738 }
2739
2740 /// The adjusted caret position is the character position adjusted to take
2741 /// into account whether we're at the start of a paragraph, in which case
2742 /// style information should be taken from the next position, not current one.
2743 long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos) const
2744 {
2745 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPos+1);
2746
2747 if (para && (caretPos+1 == para->GetRange().GetStart()))
2748 caretPos ++;
2749 return caretPos;
2750 }
2751
2752 /// Get/set the selection range in character positions. -1, -1 means no selection.
2753 /// The range is in API convention, i.e. a single character selection is denoted
2754 /// by (n, n+1)
2755 wxRichTextRange wxRichTextCtrl::GetSelectionRange() const
2756 {
2757 wxRichTextRange range = GetInternalSelectionRange();
2758 if (range != wxRichTextRange(-2,-2) && range != wxRichTextRange(-1,-1))
2759 range.SetEnd(range.GetEnd() + 1);
2760 return range;
2761 }
2762
2763 void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange& range)
2764 {
2765 wxRichTextRange range1(range);
2766 if (range1 != wxRichTextRange(-2,-2) && range1 != wxRichTextRange(-1,-1) )
2767 range1.SetEnd(range1.GetEnd() - 1);
2768
2769 wxASSERT( range1.GetStart() > range1.GetEnd() );
2770
2771 SetInternalSelectionRange(range1);
2772 }
2773
2774 #endif
2775 // wxUSE_RICHTEXT