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