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