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