Compilo fix
[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 static wxString delimiters = wxT(" ,.:;!?-\"'~£$%^&*()_+-={}[]@#<>/\\|");
1614 return !text.IsEmpty() && delimiters.Find(text) != wxNOT_FOUND;
1615 }
1616
1617 /// Select the word at the given character position
1618 bool wxRichTextCtrl::SelectWord(long position)
1619 {
1620 if (position < 0 || position > GetBuffer().GetRange().GetEnd())
1621 return false;
1622
1623 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(position);
1624 if (!para)
1625 return false;
1626
1627 long positionStart = position;
1628 long positionEnd = position;
1629
1630 for (positionStart = position; positionStart >= para->GetRange().GetStart(); positionStart --)
1631 {
1632 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionStart, positionStart));
1633 if (wxIsWordDelimiter(text))
1634 {
1635 positionStart ++;
1636 break;
1637 }
1638 }
1639 if (positionStart < para->GetRange().GetStart())
1640 positionStart = para->GetRange().GetStart();
1641
1642 for (positionEnd = position; positionEnd < para->GetRange().GetEnd(); positionEnd ++)
1643 {
1644 wxString text = GetBuffer().GetTextForRange(wxRichTextRange(positionEnd, positionEnd));
1645 if (wxIsWordDelimiter(text))
1646 {
1647 positionEnd --;
1648 break;
1649 }
1650 }
1651 if (positionEnd >= para->GetRange().GetEnd())
1652 positionEnd = para->GetRange().GetEnd();
1653
1654 SetSelection(positionStart, positionEnd+1);
1655
1656 if (positionStart >= 0)
1657 {
1658 MoveCaret(positionStart-1, true);
1659 SetDefaultStyleToCursorStyle();
1660 }
1661
1662 return true;
1663 }
1664
1665 wxString wxRichTextCtrl::GetStringSelection() const
1666 {
1667 long from, to;
1668 GetSelection(&from, &to);
1669
1670 return GetRange(from, to);
1671 }
1672
1673 // do the window-specific processing after processing the update event
1674 #if !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
1675 void wxRichTextCtrl::DoUpdateWindowUI(wxUpdateUIEvent& event)
1676 {
1677 // call inherited
1678 wxWindowBase::DoUpdateWindowUI(event);
1679
1680 // update text
1681 if ( event.GetSetText() )
1682 {
1683 if ( event.GetText() != GetValue() )
1684 SetValue(event.GetText());
1685 }
1686 }
1687 #endif // !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
1688
1689 // ----------------------------------------------------------------------------
1690 // hit testing
1691 // ----------------------------------------------------------------------------
1692
1693 wxTextCtrlHitTestResult
1694 wxRichTextCtrl::HitTest(const wxPoint& pt, wxTextCoord *x, wxTextCoord *y) const
1695 {
1696 // implement in terms of the other overload as the native ports typically
1697 // can get the position and not (x, y) pair directly (although wxUniv
1698 // directly gets x and y -- and so overrides this method as well)
1699 long pos;
1700 wxTextCtrlHitTestResult rc = HitTest(pt, &pos);
1701
1702 if ( rc != wxTE_HT_UNKNOWN )
1703 {
1704 PositionToXY(pos, x, y);
1705 }
1706
1707 return rc;
1708 }
1709
1710 wxTextCtrlHitTestResult
1711 wxRichTextCtrl::HitTest(const wxPoint& pt,
1712 long * pos) const
1713 {
1714 wxClientDC dc((wxRichTextCtrl*) this);
1715 ((wxRichTextCtrl*)this)->PrepareDC(dc);
1716
1717 // Buffer uses logical position (relative to start of buffer)
1718 // so convert
1719 wxPoint pt2 = GetLogicalPoint(pt);
1720
1721 int hit = ((wxRichTextCtrl*)this)->GetBuffer().HitTest(dc, pt2, *pos);
1722
1723 switch ( hit )
1724 {
1725 case wxRICHTEXT_HITTEST_BEFORE:
1726 return wxTE_HT_BEFORE;
1727
1728 case wxRICHTEXT_HITTEST_AFTER:
1729 return wxTE_HT_BEYOND;
1730
1731 case wxRICHTEXT_HITTEST_ON:
1732 return wxTE_HT_ON_TEXT;
1733 }
1734
1735 return wxTE_HT_UNKNOWN;
1736 }
1737
1738 // ----------------------------------------------------------------------------
1739 // set/get the controls text
1740 // ----------------------------------------------------------------------------
1741
1742 wxString wxRichTextCtrl::GetValue() const
1743 {
1744 return GetBuffer().GetText();
1745 }
1746
1747 wxString wxRichTextCtrl::GetRange(long from, long to) const
1748 {
1749 // Public API for range is different from internals
1750 return GetBuffer().GetTextForRange(wxRichTextRange(from, to-1));
1751 }
1752
1753 void wxRichTextCtrl::SetValue(const wxString& value)
1754 {
1755 Clear();
1756
1757 // if the text is long enough, it's faster to just set it instead of first
1758 // comparing it with the old one (chances are that it will be different
1759 // anyhow, this comparison is there to avoid flicker for small single-line
1760 // edit controls mostly)
1761 if ( (value.length() > 0x400) || (value != GetValue()) )
1762 {
1763 DoWriteText(value, false /* not selection only */);
1764
1765 // for compatibility, don't move the cursor when doing SetValue()
1766 SetInsertionPoint(0);
1767 }
1768 else // same text
1769 {
1770 // still send an event for consistency
1771 SendUpdateEvent();
1772 }
1773
1774 // we should reset the modified flag even if the value didn't really change
1775
1776 // mark the control as being not dirty - we changed its text, not the
1777 // user
1778 DiscardEdits();
1779 }
1780
1781 void wxRichTextCtrl::WriteText(const wxString& value)
1782 {
1783 DoWriteText(value);
1784 }
1785
1786 void wxRichTextCtrl::DoWriteText(const wxString& value, bool WXUNUSED(selectionOnly))
1787 {
1788 wxString valueUnix = wxTextFile::Translate(value, wxTextFileType_Unix);
1789
1790 GetBuffer().InsertTextWithUndo(m_caretPosition+1, valueUnix, this);
1791 }
1792
1793 void wxRichTextCtrl::AppendText(const wxString& text)
1794 {
1795 SetInsertionPointEnd();
1796
1797 WriteText(text);
1798 }
1799
1800 /// Write an image at the current insertion point
1801 bool wxRichTextCtrl::WriteImage(const wxImage& image, int bitmapType)
1802 {
1803 wxRichTextImageBlock imageBlock;
1804
1805 wxImage image2 = image;
1806 if (imageBlock.MakeImageBlock(image2, bitmapType))
1807 return WriteImage(imageBlock);
1808
1809 return false;
1810 }
1811
1812 bool wxRichTextCtrl::WriteImage(const wxString& filename, int bitmapType)
1813 {
1814 wxRichTextImageBlock imageBlock;
1815
1816 wxImage image;
1817 if (imageBlock.MakeImageBlock(filename, bitmapType, image, false))
1818 return WriteImage(imageBlock);
1819
1820 return false;
1821 }
1822
1823 bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock& imageBlock)
1824 {
1825 return GetBuffer().InsertImageWithUndo(m_caretPosition+1, imageBlock, this);
1826 }
1827
1828 bool wxRichTextCtrl::WriteImage(const wxBitmap& bitmap, int bitmapType)
1829 {
1830 if (bitmap.Ok())
1831 {
1832 wxRichTextImageBlock imageBlock;
1833
1834 wxImage image = bitmap.ConvertToImage();
1835 if (image.Ok() && imageBlock.MakeImageBlock(image, bitmapType))
1836 return WriteImage(imageBlock);
1837 }
1838
1839 return false;
1840 }
1841
1842 /// Insert a newline (actually paragraph) at the current insertion point.
1843 bool wxRichTextCtrl::Newline()
1844 {
1845 return GetBuffer().InsertNewlineWithUndo(m_caretPosition+1, this);
1846 }
1847
1848
1849 // ----------------------------------------------------------------------------
1850 // Clipboard operations
1851 // ----------------------------------------------------------------------------
1852
1853 void wxRichTextCtrl::Copy()
1854 {
1855 if (CanCopy())
1856 {
1857 wxRichTextRange range = GetInternalSelectionRange();
1858 GetBuffer().CopyToClipboard(range);
1859 }
1860 }
1861
1862 void wxRichTextCtrl::Cut()
1863 {
1864 if (CanCut())
1865 {
1866 wxRichTextRange range = GetInternalSelectionRange();
1867 GetBuffer().CopyToClipboard(range);
1868
1869 DeleteSelectedContent();
1870 LayoutContent();
1871 Refresh(false);
1872 }
1873 }
1874
1875 void wxRichTextCtrl::Paste()
1876 {
1877 if (CanPaste())
1878 {
1879 BeginBatchUndo(_("Paste"));
1880
1881 long newPos = m_caretPosition;
1882 DeleteSelectedContent(& newPos);
1883
1884 GetBuffer().PasteFromClipboard(newPos);
1885
1886 EndBatchUndo();
1887 }
1888 }
1889
1890 void wxRichTextCtrl::DeleteSelection()
1891 {
1892 if (CanDeleteSelection())
1893 {
1894 DeleteSelectedContent();
1895 }
1896 }
1897
1898 bool wxRichTextCtrl::HasSelection() const
1899 {
1900 return m_selectionRange.GetStart() != -2 && m_selectionRange.GetEnd() != -2;
1901 }
1902
1903 bool wxRichTextCtrl::CanCopy() const
1904 {
1905 // Can copy if there's a selection
1906 return HasSelection();
1907 }
1908
1909 bool wxRichTextCtrl::CanCut() const
1910 {
1911 return HasSelection() && IsEditable();
1912 }
1913
1914 bool wxRichTextCtrl::CanPaste() const
1915 {
1916 if ( !IsEditable() )
1917 return false;
1918
1919 return GetBuffer().CanPasteFromClipboard();
1920 }
1921
1922 bool wxRichTextCtrl::CanDeleteSelection() const
1923 {
1924 return HasSelection() && IsEditable();
1925 }
1926
1927
1928 // ----------------------------------------------------------------------------
1929 // Accessors
1930 // ----------------------------------------------------------------------------
1931
1932 void wxRichTextCtrl::SetEditable(bool editable)
1933 {
1934 m_editable = editable;
1935 }
1936
1937 void wxRichTextCtrl::SetInsertionPoint(long pos)
1938 {
1939 SelectNone();
1940
1941 m_caretPosition = pos - 1;
1942 }
1943
1944 void wxRichTextCtrl::SetInsertionPointEnd()
1945 {
1946 long pos = GetLastPosition();
1947 SetInsertionPoint(pos);
1948 }
1949
1950 long wxRichTextCtrl::GetInsertionPoint() const
1951 {
1952 return m_caretPosition+1;
1953 }
1954
1955 wxTextPos wxRichTextCtrl::GetLastPosition() const
1956 {
1957 return GetBuffer().GetRange().GetEnd();
1958 }
1959
1960 // If the return values from and to are the same, there is no
1961 // selection.
1962 void wxRichTextCtrl::GetSelection(long* from, long* to) const
1963 {
1964 *from = m_selectionRange.GetStart();
1965 *to = m_selectionRange.GetEnd();
1966 if ((*to) != -1 && (*to) != -2)
1967 (*to) ++;
1968 }
1969
1970 bool wxRichTextCtrl::IsEditable() const
1971 {
1972 return m_editable;
1973 }
1974
1975 // ----------------------------------------------------------------------------
1976 // selection
1977 // ----------------------------------------------------------------------------
1978
1979 void wxRichTextCtrl::SetSelection(long from, long to)
1980 {
1981 // if from and to are both -1, it means (in wxWidgets) that all text should
1982 // be selected.
1983 if ( (from == -1) && (to == -1) )
1984 {
1985 from = 0;
1986 to = GetLastPosition()+1;
1987 }
1988
1989 DoSetSelection(from, to);
1990 }
1991
1992 void wxRichTextCtrl::DoSetSelection(long from, long to, bool WXUNUSED(scrollCaret))
1993 {
1994 m_selectionAnchor = from;
1995 m_selectionRange.SetRange(from, to-1);
1996
1997 Refresh(false);
1998 PositionCaret();
1999 }
2000
2001 // ----------------------------------------------------------------------------
2002 // Editing
2003 // ----------------------------------------------------------------------------
2004
2005 void wxRichTextCtrl::Replace(long WXUNUSED(from), long WXUNUSED(to), const wxString& value)
2006 {
2007 BeginBatchUndo(_("Replace"));
2008
2009 DeleteSelectedContent();
2010
2011 DoWriteText(value, true /* selection only */);
2012
2013 EndBatchUndo();
2014 }
2015
2016 void wxRichTextCtrl::Remove(long from, long to)
2017 {
2018 SelectNone();
2019
2020 GetBuffer().DeleteRangeWithUndo(wxRichTextRange(from, to),
2021 m_caretPosition, // Current caret position
2022 from, // New caret position
2023 this);
2024
2025 LayoutContent();
2026 if (!IsFrozen())
2027 Refresh(false);
2028 }
2029
2030 bool wxRichTextCtrl::IsModified() const
2031 {
2032 return m_buffer.IsModified();
2033 }
2034
2035 void wxRichTextCtrl::MarkDirty()
2036 {
2037 m_buffer.Modify(true);
2038 }
2039
2040 void wxRichTextCtrl::DiscardEdits()
2041 {
2042 m_caretPositionForDefaultStyle = -2;
2043 m_buffer.Modify(false);
2044 m_buffer.GetCommandProcessor()->ClearCommands();
2045 }
2046
2047 int wxRichTextCtrl::GetNumberOfLines() const
2048 {
2049 return GetBuffer().GetParagraphCount();
2050 }
2051
2052 // ----------------------------------------------------------------------------
2053 // Positions <-> coords
2054 // ----------------------------------------------------------------------------
2055
2056 long wxRichTextCtrl::XYToPosition(long x, long y) const
2057 {
2058 return GetBuffer().XYToPosition(x, y);
2059 }
2060
2061 bool wxRichTextCtrl::PositionToXY(long pos, long *x, long *y) const
2062 {
2063 return GetBuffer().PositionToXY(pos, x, y);
2064 }
2065
2066 // ----------------------------------------------------------------------------
2067 //
2068 // ----------------------------------------------------------------------------
2069
2070 void wxRichTextCtrl::ShowPosition(long pos)
2071 {
2072 if (!IsPositionVisible(pos))
2073 ScrollIntoView(pos-1, WXK_DOWN);
2074 }
2075
2076 int wxRichTextCtrl::GetLineLength(long lineNo) const
2077 {
2078 return GetBuffer().GetParagraphLength(lineNo);
2079 }
2080
2081 wxString wxRichTextCtrl::GetLineText(long lineNo) const
2082 {
2083 return GetBuffer().GetParagraphText(lineNo);
2084 }
2085
2086 // ----------------------------------------------------------------------------
2087 // Undo/redo
2088 // ----------------------------------------------------------------------------
2089
2090 void wxRichTextCtrl::Undo()
2091 {
2092 if (CanUndo())
2093 {
2094 GetCommandProcessor()->Undo();
2095 }
2096 }
2097
2098 void wxRichTextCtrl::Redo()
2099 {
2100 if (CanRedo())
2101 {
2102 GetCommandProcessor()->Redo();
2103 }
2104 }
2105
2106 bool wxRichTextCtrl::CanUndo() const
2107 {
2108 return GetCommandProcessor()->CanUndo();
2109 }
2110
2111 bool wxRichTextCtrl::CanRedo() const
2112 {
2113 return GetCommandProcessor()->CanRedo();
2114 }
2115
2116 // ----------------------------------------------------------------------------
2117 // implementation details
2118 // ----------------------------------------------------------------------------
2119
2120 void wxRichTextCtrl::Command(wxCommandEvent& event)
2121 {
2122 SetValue(event.GetString());
2123 GetEventHandler()->ProcessEvent(event);
2124 }
2125
2126 void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent& event)
2127 {
2128 // By default, load the first file into the text window.
2129 if (event.GetNumberOfFiles() > 0)
2130 {
2131 LoadFile(event.GetFiles()[0]);
2132 }
2133 }
2134
2135 // ----------------------------------------------------------------------------
2136 // text control event processing
2137 // ----------------------------------------------------------------------------
2138
2139 bool wxRichTextCtrl::SendUpdateEvent()
2140 {
2141 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
2142 InitCommandEvent(event);
2143
2144 return GetEventHandler()->ProcessEvent(event);
2145 }
2146
2147 void wxRichTextCtrl::InitCommandEvent(wxCommandEvent& event) const
2148 {
2149 event.SetEventObject((wxControlBase *)this); // const_cast
2150
2151 switch ( m_clientDataType )
2152 {
2153 case wxClientData_Void:
2154 event.SetClientData(GetClientData());
2155 break;
2156
2157 case wxClientData_Object:
2158 event.SetClientObject(GetClientObject());
2159 break;
2160
2161 case wxClientData_None:
2162 // nothing to do
2163 ;
2164 }
2165 }
2166
2167
2168 wxSize wxRichTextCtrl::DoGetBestSize() const
2169 {
2170 return wxSize(10, 10);
2171 }
2172
2173 // ----------------------------------------------------------------------------
2174 // standard handlers for standard edit menu events
2175 // ----------------------------------------------------------------------------
2176
2177 void wxRichTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
2178 {
2179 Cut();
2180 }
2181
2182 void wxRichTextCtrl::OnClear(wxCommandEvent& WXUNUSED(event))
2183 {
2184 DeleteSelection();
2185 }
2186
2187 void wxRichTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
2188 {
2189 Copy();
2190 }
2191
2192 void wxRichTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
2193 {
2194 Paste();
2195 }
2196
2197 void wxRichTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
2198 {
2199 Undo();
2200 }
2201
2202 void wxRichTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
2203 {
2204 Redo();
2205 }
2206
2207 void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
2208 {
2209 event.Enable( CanCut() );
2210 }
2211
2212 void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
2213 {
2214 event.Enable( CanCopy() );
2215 }
2216
2217 void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent& event)
2218 {
2219 event.Enable( CanDeleteSelection() );
2220 }
2221
2222 void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
2223 {
2224 event.Enable( CanPaste() );
2225 }
2226
2227 void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
2228 {
2229 event.Enable( CanUndo() );
2230 event.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
2231 }
2232
2233 void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
2234 {
2235 event.Enable( CanRedo() );
2236 event.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
2237 }
2238
2239 void wxRichTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
2240 {
2241 SelectAll();
2242 }
2243
2244 void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
2245 {
2246 event.Enable(GetLastPosition() > 0);
2247 }
2248
2249 void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent& WXUNUSED(event))
2250 {
2251 if (!m_contextMenu)
2252 {
2253 m_contextMenu = new wxMenu;
2254 m_contextMenu->Append(wxID_UNDO, _("&Undo"));
2255 m_contextMenu->Append(wxID_REDO, _("&Redo"));
2256 m_contextMenu->AppendSeparator();
2257 m_contextMenu->Append(wxID_CUT, _("Cu&t"));
2258 m_contextMenu->Append(wxID_COPY, _("&Copy"));
2259 m_contextMenu->Append(wxID_PASTE, _("&Paste"));
2260 m_contextMenu->Append(wxID_CLEAR, _("&Delete"));
2261 m_contextMenu->AppendSeparator();
2262 m_contextMenu->Append(wxID_SELECTALL, _("Select &All"));
2263 }
2264 PopupMenu(m_contextMenu);
2265 return;
2266 }
2267
2268 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttrEx& style)
2269 {
2270 return GetBuffer().SetStyle(wxRichTextRange(start, end-1), style);
2271 }
2272
2273 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
2274 {
2275 return GetBuffer().SetStyle(wxRichTextRange(start, end-1), wxTextAttrEx(style));
2276 }
2277
2278 bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style)
2279 {
2280 return GetBuffer().SetStyle(range.ToInternal(), style);
2281 }
2282
2283 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttrEx& style)
2284 {
2285 return GetBuffer().SetDefaultStyle(style);
2286 }
2287
2288 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr& style)
2289 {
2290 return GetBuffer().SetDefaultStyle(wxTextAttrEx(style));
2291 }
2292
2293 const wxTextAttrEx& wxRichTextCtrl::GetDefaultStyleEx() const
2294 {
2295 return GetBuffer().GetDefaultStyle();
2296 }
2297
2298 const wxTextAttr& wxRichTextCtrl::GetDefaultStyle() const
2299 {
2300 return GetBuffer().GetDefaultStyle();
2301 }
2302
2303 bool wxRichTextCtrl::GetStyle(long position, wxTextAttr& style)
2304 {
2305 wxTextAttrEx attr(style);
2306 if (GetBuffer().GetStyle(position, attr))
2307 {
2308 style = attr;
2309 return true;
2310 }
2311 else
2312 return false;
2313 }
2314
2315 bool wxRichTextCtrl::GetStyle(long position, wxTextAttrEx& style)
2316 {
2317 return GetBuffer().GetStyle(position, style);
2318 }
2319
2320 bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style)
2321 {
2322 return GetBuffer().GetStyle(position, style);
2323 }
2324
2325 /// Get the content (uncombined) attributes for this position.
2326
2327 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxTextAttr& style)
2328 {
2329 wxTextAttrEx attr(style);
2330 if (GetBuffer().GetUncombinedStyle(position, attr))
2331 {
2332 style = attr;
2333 return true;
2334 }
2335 else
2336 return false;
2337 }
2338
2339 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxTextAttrEx& style)
2340 {
2341 return GetBuffer().GetUncombinedStyle(position, style);
2342 }
2343
2344 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style)
2345 {
2346 return GetBuffer().GetUncombinedStyle(position, style);
2347 }
2348
2349 /// Set font, and also the buffer attributes
2350 bool wxRichTextCtrl::SetFont(const wxFont& font)
2351 {
2352 #if wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
2353 wxControl::SetFont(font);
2354 #else
2355 wxScrolledWindow::SetFont(font);
2356 #endif
2357
2358 wxTextAttrEx attr = GetBuffer().GetAttributes();
2359 attr.SetFont(font);
2360 GetBuffer().SetBasicStyle(attr);
2361
2362 #if !wxRICHTEXT_DERIVES_FROM_TEXTCTRLBASE
2363 // Don't set the default style, since it will be inherited from
2364 // the basic style.
2365 GetBuffer().SetDefaultStyle(attr);
2366 #endif
2367
2368 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2369 Refresh(false);
2370
2371 return true;
2372 }
2373
2374 /// Transform logical to physical
2375 wxPoint wxRichTextCtrl::GetPhysicalPoint(const wxPoint& ptLogical) const
2376 {
2377 wxPoint pt;
2378 CalcScrolledPosition(ptLogical.x, ptLogical.y, & pt.x, & pt.y);
2379
2380 return pt;
2381 }
2382
2383 /// Transform physical to logical
2384 wxPoint wxRichTextCtrl::GetLogicalPoint(const wxPoint& ptPhysical) const
2385 {
2386 wxPoint pt;
2387 CalcUnscrolledPosition(ptPhysical.x, ptPhysical.y, & pt.x, & pt.y);
2388
2389 return pt;
2390 }
2391
2392 /// Position the caret
2393 void wxRichTextCtrl::PositionCaret()
2394 {
2395 if (!GetCaret())
2396 return;
2397
2398 //wxLogDebug(wxT("PositionCaret"));
2399
2400 wxRect caretRect;
2401 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect))
2402 {
2403 wxPoint originalPt = caretRect.GetPosition();
2404 wxPoint pt = GetPhysicalPoint(originalPt);
2405 if (GetCaret()->GetPosition() != pt)
2406 {
2407 GetCaret()->Move(pt);
2408 GetCaret()->SetSize(caretRect.GetSize());
2409 }
2410 }
2411 }
2412
2413 /// Get the caret height and position for the given character position
2414 bool wxRichTextCtrl::GetCaretPositionForIndex(long position, wxRect& rect)
2415 {
2416 wxClientDC dc(this);
2417 dc.SetFont(GetFont());
2418
2419 PrepareDC(dc);
2420
2421 wxPoint pt;
2422 int height = 0;
2423
2424 if (GetBuffer().FindPosition(dc, position, pt, & height, m_caretAtLineStart))
2425 {
2426 rect = wxRect(pt, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH, height));
2427 return true;
2428 }
2429
2430 return false;
2431 }
2432
2433 /// Gets the line for the visible caret position. If the caret is
2434 /// shown at the very end of the line, it means the next character is actually
2435 /// on the following line. So let's get the line we're expecting to find
2436 /// if this is the case.
2437 wxRichTextLine* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition) const
2438 {
2439 wxRichTextLine* line = GetBuffer().GetLineAtPosition(caretPosition, true);
2440 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPosition, true);
2441 if (line)
2442 {
2443 wxRichTextRange lineRange = line->GetAbsoluteRange();
2444 if (caretPosition == lineRange.GetStart()-1 &&
2445 (para->GetRange().GetStart() != lineRange.GetStart()))
2446 {
2447 if (!m_caretAtLineStart)
2448 line = GetBuffer().GetLineAtPosition(caretPosition-1, true);
2449 }
2450 }
2451 return line;
2452 }
2453
2454
2455 /// Move the caret to the given character position
2456 bool wxRichTextCtrl::MoveCaret(long pos, bool showAtLineStart)
2457 {
2458 if (GetBuffer().GetDirty())
2459 LayoutContent();
2460
2461 if (pos <= GetBuffer().GetRange().GetEnd())
2462 {
2463 SetCaretPosition(pos, showAtLineStart);
2464
2465 PositionCaret();
2466
2467 return true;
2468 }
2469 else
2470 return false;
2471 }
2472
2473 /// Layout the buffer: which we must do before certain operations, such as
2474 /// setting the caret position.
2475 bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect)
2476 {
2477 if (GetBuffer().GetDirty() || onlyVisibleRect)
2478 {
2479 wxRect availableSpace(GetClientSize());
2480 if (availableSpace.width == 0)
2481 availableSpace.width = 10;
2482 if (availableSpace.height == 0)
2483 availableSpace.height = 10;
2484
2485 int flags = wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT;
2486 if (onlyVisibleRect)
2487 {
2488 flags |= wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
2489 availableSpace.SetPosition(GetLogicalPoint(wxPoint(0, 0)));
2490 }
2491
2492 wxClientDC dc(this);
2493 dc.SetFont(GetFont());
2494
2495 PrepareDC(dc);
2496
2497 GetBuffer().Defragment();
2498 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
2499 GetBuffer().Layout(dc, availableSpace, flags);
2500 GetBuffer().SetDirty(false);
2501
2502 if (!IsFrozen())
2503 SetupScrollbars();
2504 }
2505
2506 return true;
2507 }
2508
2509 /// Is all of the selection bold?
2510 bool wxRichTextCtrl::IsSelectionBold()
2511 {
2512 if (HasSelection())
2513 {
2514 wxRichTextAttr attr;
2515 wxRichTextRange range = GetInternalSelectionRange();
2516 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2517 attr.SetFontWeight(wxBOLD);
2518
2519 return HasCharacterAttributes(range, attr);
2520 }
2521 else
2522 {
2523 // If no selection, then we need to combine current style with default style
2524 // to see what the effect would be if we started typing.
2525 wxRichTextAttr attr;
2526 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2527
2528 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2529 if (GetStyle(pos, attr))
2530 {
2531 if (IsDefaultStyleShowing())
2532 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2533 return attr.GetFontWeight() == wxBOLD;
2534 }
2535 }
2536 return false;
2537 }
2538
2539 /// Is all of the selection italics?
2540 bool wxRichTextCtrl::IsSelectionItalics()
2541 {
2542 if (HasSelection())
2543 {
2544 wxRichTextRange range = GetInternalSelectionRange();
2545 wxRichTextAttr attr;
2546 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2547 attr.SetFontStyle(wxITALIC);
2548
2549 return HasCharacterAttributes(range, attr);
2550 }
2551 else
2552 {
2553 // If no selection, then we need to combine current style with default style
2554 // to see what the effect would be if we started typing.
2555 wxRichTextAttr attr;
2556 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2557
2558 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2559 if (GetStyle(pos, attr))
2560 {
2561 if (IsDefaultStyleShowing())
2562 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2563 return attr.GetFontStyle() == wxITALIC;
2564 }
2565 }
2566 return false;
2567 }
2568
2569 /// Is all of the selection underlined?
2570 bool wxRichTextCtrl::IsSelectionUnderlined()
2571 {
2572 if (HasSelection())
2573 {
2574 wxRichTextRange range = GetInternalSelectionRange();
2575 wxRichTextAttr attr;
2576 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2577 attr.SetFontUnderlined(true);
2578
2579 return HasCharacterAttributes(range, attr);
2580 }
2581 else
2582 {
2583 // If no selection, then we need to combine current style with default style
2584 // to see what the effect would be if we started typing.
2585 wxRichTextAttr attr;
2586 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2587 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2588
2589 if (GetStyle(pos, attr))
2590 {
2591 if (IsDefaultStyleShowing())
2592 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
2593 return attr.GetFontUnderlined();
2594 }
2595 }
2596 return false;
2597 }
2598
2599 /// Apply bold to the selection
2600 bool wxRichTextCtrl::ApplyBoldToSelection()
2601 {
2602 wxRichTextAttr attr;
2603 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
2604 attr.SetFontWeight(IsSelectionBold() ? wxNORMAL : wxBOLD);
2605
2606 if (HasSelection())
2607 return SetStyle(GetSelectionRange(), attr);
2608 else
2609 SetAndShowDefaultStyle(attr);
2610 return true;
2611 }
2612
2613 /// Apply italic to the selection
2614 bool wxRichTextCtrl::ApplyItalicToSelection()
2615 {
2616 wxRichTextAttr attr;
2617 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
2618 attr.SetFontStyle(IsSelectionItalics() ? wxNORMAL : wxITALIC);
2619
2620 if (HasSelection())
2621 return SetStyle(GetSelectionRange(), attr);
2622 else
2623 SetAndShowDefaultStyle(attr);
2624 return true;
2625 }
2626
2627 /// Apply underline to the selection
2628 bool wxRichTextCtrl::ApplyUnderlineToSelection()
2629 {
2630 wxRichTextAttr attr;
2631 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
2632 attr.SetFontUnderlined(!IsSelectionUnderlined());
2633
2634 if (HasSelection())
2635 return SetStyle(GetSelectionRange(), attr);
2636 else
2637 SetAndShowDefaultStyle(attr);
2638 return true;
2639 }
2640
2641 /// Is all of the selection aligned according to the specified flag?
2642 bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment)
2643 {
2644 wxRichTextRange range;
2645 if (HasSelection())
2646 range = GetInternalSelectionRange();
2647 else
2648 range = wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+1);
2649
2650 wxRichTextAttr attr;
2651 attr.SetAlignment(alignment);
2652
2653 return HasParagraphAttributes(range, attr);
2654 }
2655
2656 /// Apply alignment to the selection
2657 bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment)
2658 {
2659 wxRichTextAttr attr;
2660 attr.SetAlignment(alignment);
2661 if (HasSelection())
2662 return SetStyle(GetSelectionRange(), attr);
2663 else
2664 {
2665 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(GetCaretPosition()+1);
2666 if (para)
2667 return SetStyle(para->GetRange().FromInternal(), attr);
2668 }
2669 return true;
2670 }
2671
2672 /// Apply a named style to the selection
2673 void wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition* def)
2674 {
2675 // Flags are defined within each definition, so only certain
2676 // attributes are applied.
2677 wxRichTextAttr attr(def->GetStyle());
2678
2679 // Make sure the attr has the style name
2680 if (def->IsKindOf(CLASSINFO(wxRichTextParagraphStyleDefinition)))
2681 attr.SetParagraphStyleName(def->GetName());
2682 else
2683 attr.SetCharacterStyleName(def->GetName());
2684
2685 if (HasSelection())
2686 SetStyle(GetSelectionRange(), attr);
2687 else
2688 SetAndShowDefaultStyle(attr);
2689 }
2690
2691 /// Apply the style sheet to the buffer, for example if the styles have changed.
2692 bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
2693 {
2694 if (!styleSheet)
2695 styleSheet = GetBuffer().GetStyleSheet();
2696 if (!styleSheet)
2697 return false;
2698
2699 if (GetBuffer().ApplyStyleSheet(styleSheet))
2700 {
2701 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2702 Refresh(false);
2703 return true;
2704 }
2705 else
2706 return false;
2707 }
2708
2709 /// Sets the default style to the style under the cursor
2710 bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
2711 {
2712 wxTextAttrEx attr;
2713 attr.SetFlags(wxTEXT_ATTR_CHARACTER);
2714
2715 // If at the start of a paragraph, use the next position.
2716 long pos = GetAdjustedCaretPosition(GetCaretPosition());
2717
2718 #if wxRICHTEXT_USE_DYNAMIC_STYLES
2719 if (GetUncombinedStyle(pos, attr))
2720 #else
2721 if (GetStyle(pos, attr))
2722 #endif
2723 {
2724 SetDefaultStyle(attr);
2725 return true;
2726 }
2727
2728 return false;
2729 }
2730
2731 /// Returns the first visible position in the current view
2732 long wxRichTextCtrl::GetFirstVisiblePosition() const
2733 {
2734 wxRichTextLine* line = GetBuffer().GetLineAtYPosition(GetLogicalPoint(wxPoint(0, 0)).y);
2735 if (line)
2736 return line->GetAbsoluteRange().GetStart();
2737 else
2738 return 0;
2739 }
2740
2741 /// The adjusted caret position is the character position adjusted to take
2742 /// into account whether we're at the start of a paragraph, in which case
2743 /// style information should be taken from the next position, not current one.
2744 long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos) const
2745 {
2746 wxRichTextParagraph* para = GetBuffer().GetParagraphAtPosition(caretPos+1);
2747
2748 if (para && (caretPos+1 == para->GetRange().GetStart()))
2749 caretPos ++;
2750 return caretPos;
2751 }
2752
2753 /// Get/set the selection range in character positions. -1, -1 means no selection.
2754 /// The range is in API convention, i.e. a single character selection is denoted
2755 /// by (n, n+1)
2756 wxRichTextRange wxRichTextCtrl::GetSelectionRange() const
2757 {
2758 wxRichTextRange range = GetInternalSelectionRange();
2759 if (range != wxRichTextRange(-2,-2) && range != wxRichTextRange(-1,-1))
2760 range.SetEnd(range.GetEnd() + 1);
2761 return range;
2762 }
2763
2764 void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange& range)
2765 {
2766 wxRichTextRange range1(range);
2767 if (range1 != wxRichTextRange(-2,-2) && range1 != wxRichTextRange(-1,-1) )
2768 range1.SetEnd(range1.GetEnd() - 1);
2769
2770 wxASSERT( range1.GetStart() > range1.GetEnd() );
2771
2772 SetInternalSelectionRange(range1);
2773 }
2774
2775 #endif
2776 // wxUSE_RICHTEXT