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