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