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