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