]> git.saurik.com Git - wxWidgets.git/blob - src/richtext/richtextctrl.cpp
set default deployment and compiler flags
[wxWidgets.git] / src / richtext / richtextctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/richtext/richtextctrl.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/timer.h"
30 #include "wx/textfile.h"
31 #include "wx/ffile.h"
32 #include "wx/filename.h"
33 #include "wx/dcbuffer.h"
34 #include "wx/arrimpl.cpp"
35 #include "wx/fontenum.h"
36 #include "wx/accel.h"
37
38 // DLL options compatibility check:
39 #include "wx/app.h"
40 WX_CHECK_BUILD_OPTIONS("wxRichTextCtrl")
41
42 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_CLICK, wxRichTextEvent );
43 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK, wxRichTextEvent );
44 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK, wxRichTextEvent );
45 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK, wxRichTextEvent );
46 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_RETURN, wxRichTextEvent );
47 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CHARACTER, wxRichTextEvent );
48 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_DELETE, wxRichTextEvent );
49
50 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACING, wxRichTextEvent );
51 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_REPLACED, wxRichTextEvent );
52 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGING, wxRichTextEvent );
53 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLESHEET_CHANGED, wxRichTextEvent );
54
55 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_INSERTED, wxRichTextEvent );
56 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_CONTENT_DELETED, wxRichTextEvent );
57 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_STYLE_CHANGED, wxRichTextEvent );
58 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_SELECTION_CHANGED, wxRichTextEvent );
59 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_BUFFER_RESET, wxRichTextEvent );
60 wxDEFINE_EVENT( wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED, wxRichTextEvent );
61
62 #if wxRICHTEXT_USE_OWN_CARET
63
64 /*!
65 * wxRichTextCaret
66 *
67 * This implements a non-flashing cursor in case there
68 * are platform-specific problems with the generic caret.
69 * wxRICHTEXT_USE_OWN_CARET is set in richtextbuffer.h.
70 */
71
72 class wxRichTextCaret;
73 class wxRichTextCaretTimer: public wxTimer
74 {
75 public:
76 wxRichTextCaretTimer(wxRichTextCaret* caret)
77 {
78 m_caret = caret;
79 }
80 virtual void Notify();
81 wxRichTextCaret* m_caret;
82 };
83
84 class wxRichTextCaret: public wxCaret
85 {
86 public:
87 // ctors
88 // -----
89 // default - use Create()
90 wxRichTextCaret(): m_timer(this) { Init(); }
91 // creates a block caret associated with the given window
92 wxRichTextCaret(wxRichTextCtrl *window, int width, int height)
93 : wxCaret(window, width, height), m_timer(this) { Init(); m_richTextCtrl = window; }
94 wxRichTextCaret(wxRichTextCtrl *window, const wxSize& size)
95 : wxCaret(window, size), m_timer(this) { Init(); m_richTextCtrl = window; }
96
97 virtual ~wxRichTextCaret();
98
99 // implementation
100 // --------------
101
102 // called by wxWindow (not using the event tables)
103 virtual void OnSetFocus();
104 virtual void OnKillFocus();
105
106 // draw the caret on the given DC
107 void DoDraw(wxDC *dc);
108
109 // get the visible count
110 int GetVisibleCount() const { return m_countVisible; }
111
112 // delay repositioning
113 bool GetNeedsUpdate() const { return m_needsUpdate; }
114 void SetNeedsUpdate(bool needsUpdate = true ) { m_needsUpdate = needsUpdate; }
115
116 void Notify();
117
118 protected:
119 virtual void DoShow();
120 virtual void DoHide();
121 virtual void DoMove();
122 virtual void DoSize();
123
124 // refresh the caret
125 void Refresh();
126
127 private:
128 void Init();
129
130 int m_xOld,
131 m_yOld;
132 bool m_hasFocus; // true => our window has focus
133 bool m_needsUpdate; // must be repositioned
134 bool m_flashOn;
135 wxRichTextCaretTimer m_timer;
136 wxRichTextCtrl* m_richTextCtrl;
137 };
138 #endif
139
140 IMPLEMENT_DYNAMIC_CLASS( wxRichTextCtrl, wxControl )
141
142 IMPLEMENT_DYNAMIC_CLASS( wxRichTextEvent, wxNotifyEvent )
143
144 BEGIN_EVENT_TABLE( wxRichTextCtrl, wxControl )
145 EVT_PAINT(wxRichTextCtrl::OnPaint)
146 EVT_ERASE_BACKGROUND(wxRichTextCtrl::OnEraseBackground)
147 EVT_IDLE(wxRichTextCtrl::OnIdle)
148 EVT_SCROLLWIN(wxRichTextCtrl::OnScroll)
149 EVT_LEFT_DOWN(wxRichTextCtrl::OnLeftClick)
150 EVT_MOTION(wxRichTextCtrl::OnMoveMouse)
151 EVT_LEFT_UP(wxRichTextCtrl::OnLeftUp)
152 EVT_RIGHT_DOWN(wxRichTextCtrl::OnRightClick)
153 EVT_MIDDLE_DOWN(wxRichTextCtrl::OnMiddleClick)
154 EVT_LEFT_DCLICK(wxRichTextCtrl::OnLeftDClick)
155 EVT_CHAR(wxRichTextCtrl::OnChar)
156 EVT_KEY_DOWN(wxRichTextCtrl::OnChar)
157 EVT_SIZE(wxRichTextCtrl::OnSize)
158 EVT_SET_FOCUS(wxRichTextCtrl::OnSetFocus)
159 EVT_KILL_FOCUS(wxRichTextCtrl::OnKillFocus)
160 EVT_MOUSE_CAPTURE_LOST(wxRichTextCtrl::OnCaptureLost)
161 EVT_CONTEXT_MENU(wxRichTextCtrl::OnContextMenu)
162 EVT_SYS_COLOUR_CHANGED(wxRichTextCtrl::OnSysColourChanged)
163
164 EVT_MENU(wxID_UNDO, wxRichTextCtrl::OnUndo)
165 EVT_UPDATE_UI(wxID_UNDO, wxRichTextCtrl::OnUpdateUndo)
166
167 EVT_MENU(wxID_REDO, wxRichTextCtrl::OnRedo)
168 EVT_UPDATE_UI(wxID_REDO, wxRichTextCtrl::OnUpdateRedo)
169
170 EVT_MENU(wxID_COPY, wxRichTextCtrl::OnCopy)
171 EVT_UPDATE_UI(wxID_COPY, wxRichTextCtrl::OnUpdateCopy)
172
173 EVT_MENU(wxID_PASTE, wxRichTextCtrl::OnPaste)
174 EVT_UPDATE_UI(wxID_PASTE, wxRichTextCtrl::OnUpdatePaste)
175
176 EVT_MENU(wxID_CUT, wxRichTextCtrl::OnCut)
177 EVT_UPDATE_UI(wxID_CUT, wxRichTextCtrl::OnUpdateCut)
178
179 EVT_MENU(wxID_CLEAR, wxRichTextCtrl::OnClear)
180 EVT_UPDATE_UI(wxID_CLEAR, wxRichTextCtrl::OnUpdateClear)
181
182 EVT_MENU(wxID_SELECTALL, wxRichTextCtrl::OnSelectAll)
183 EVT_UPDATE_UI(wxID_SELECTALL, wxRichTextCtrl::OnUpdateSelectAll)
184
185 EVT_MENU(wxID_RICHTEXT_PROPERTIES1, wxRichTextCtrl::OnProperties)
186 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES1, wxRichTextCtrl::OnUpdateProperties)
187
188 EVT_MENU(wxID_RICHTEXT_PROPERTIES2, wxRichTextCtrl::OnProperties)
189 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES2, wxRichTextCtrl::OnUpdateProperties)
190
191 EVT_MENU(wxID_RICHTEXT_PROPERTIES3, wxRichTextCtrl::OnProperties)
192 EVT_UPDATE_UI(wxID_RICHTEXT_PROPERTIES3, wxRichTextCtrl::OnUpdateProperties)
193
194 END_EVENT_TABLE()
195
196 /*!
197 * wxRichTextCtrl
198 */
199
200 wxArrayString wxRichTextCtrl::sm_availableFontNames;
201
202 wxRichTextCtrl::wxRichTextCtrl()
203 : wxScrollHelper(this)
204 {
205 Init();
206 }
207
208 wxRichTextCtrl::wxRichTextCtrl(wxWindow* parent,
209 wxWindowID id,
210 const wxString& value,
211 const wxPoint& pos,
212 const wxSize& size,
213 long style,
214 const wxValidator& validator,
215 const wxString& name)
216 : wxScrollHelper(this)
217 {
218 Init();
219 Create(parent, id, value, pos, size, style, validator, name);
220 }
221
222 /// Creation
223 bool wxRichTextCtrl::Create( wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style,
224 const wxValidator& validator, const wxString& name)
225 {
226 style |= wxVSCROLL;
227
228 if (!wxControl::Create(parent, id, pos, size,
229 style|wxFULL_REPAINT_ON_RESIZE,
230 validator, name))
231 return false;
232
233 if (!GetFont().IsOk())
234 {
235 SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
236 }
237
238 // No physical scrolling, so we can preserve margins
239 EnableScrolling(false, false);
240
241 if (style & wxTE_READONLY)
242 SetEditable(false);
243
244 // The base attributes must all have default values
245 wxRichTextAttr attributes;
246 attributes.SetFont(GetFont());
247 attributes.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
248 attributes.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
249 attributes.SetLineSpacing(10);
250 attributes.SetParagraphSpacingAfter(10);
251 attributes.SetParagraphSpacingBefore(0);
252
253 SetBasicStyle(attributes);
254
255 int margin = 5;
256 SetMargins(margin, margin);
257
258 // The default attributes will be merged with base attributes, so
259 // can be empty to begin with
260 wxRichTextAttr defaultAttributes;
261 SetDefaultStyle(defaultAttributes);
262
263 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
264 SetBackgroundStyle(wxBG_STYLE_CUSTOM);
265
266 GetBuffer().Reset();
267 GetBuffer().SetRichTextCtrl(this);
268
269 #if wxRICHTEXT_USE_OWN_CARET
270 SetCaret(new wxRichTextCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
271 #else
272 SetCaret(new wxCaret(this, wxRICHTEXT_DEFAULT_CARET_WIDTH, 16));
273 #endif
274
275 // Tell the sizers to use the given or best size
276 SetInitialSize(size);
277
278 #if wxRICHTEXT_BUFFERED_PAINTING
279 // Create a buffer
280 RecreateBuffer(size);
281 #endif
282
283 m_textCursor = wxCursor(wxCURSOR_IBEAM);
284 m_urlCursor = wxCursor(wxCURSOR_HAND);
285
286 SetCursor(m_textCursor);
287
288 if (!value.IsEmpty())
289 SetValue(value);
290
291 GetBuffer().AddEventHandler(this);
292
293 // Accelerators
294 wxAcceleratorEntry entries[6];
295
296 entries[0].Set(wxACCEL_CMD, (int) 'C', wxID_COPY);
297 entries[1].Set(wxACCEL_CMD, (int) 'X', wxID_CUT);
298 entries[2].Set(wxACCEL_CMD, (int) 'V', wxID_PASTE);
299 entries[3].Set(wxACCEL_CMD, (int) 'A', wxID_SELECTALL);
300 entries[4].Set(wxACCEL_CMD, (int) 'Z', wxID_UNDO);
301 entries[5].Set(wxACCEL_CMD, (int) 'Y', wxID_REDO);
302
303 wxAcceleratorTable accel(6, entries);
304 SetAcceleratorTable(accel);
305
306 m_contextMenu = new wxMenu;
307 m_contextMenu->Append(wxID_UNDO, _("&Undo"));
308 m_contextMenu->Append(wxID_REDO, _("&Redo"));
309 m_contextMenu->AppendSeparator();
310 m_contextMenu->Append(wxID_CUT, _("Cu&t"));
311 m_contextMenu->Append(wxID_COPY, _("&Copy"));
312 m_contextMenu->Append(wxID_PASTE, _("&Paste"));
313 m_contextMenu->Append(wxID_CLEAR, _("&Delete"));
314 m_contextMenu->AppendSeparator();
315 m_contextMenu->Append(wxID_SELECTALL, _("Select &All"));
316 m_contextMenu->AppendSeparator();
317 m_contextMenu->Append(wxID_RICHTEXT_PROPERTIES1, _("&Properties"));
318
319 return true;
320 }
321
322 wxRichTextCtrl::~wxRichTextCtrl()
323 {
324 SetFocusObject(& GetBuffer(), false);
325 GetBuffer().RemoveEventHandler(this);
326
327 delete m_contextMenu;
328 }
329
330 /// Member initialisation
331 void wxRichTextCtrl::Init()
332 {
333 m_contextMenu = NULL;
334 m_caret = NULL;
335 m_caretPosition = -1;
336 m_selectionAnchor = -2;
337 m_selectionAnchorObject = NULL;
338 m_selectionState = wxRichTextCtrlSelectionState_Normal;
339 m_editable = true;
340 m_caretAtLineStart = false;
341 m_dragging = false;
342 m_fullLayoutRequired = false;
343 m_fullLayoutTime = 0;
344 m_fullLayoutSavedPosition = 0;
345 m_delayedLayoutThreshold = wxRICHTEXT_DEFAULT_DELAYED_LAYOUT_THRESHOLD;
346 m_caretPositionForDefaultStyle = -2;
347 m_focusObject = & m_buffer;
348 }
349
350 void wxRichTextCtrl::DoThaw()
351 {
352 if (GetBuffer().IsDirty())
353 LayoutContent();
354 else
355 SetupScrollbars();
356
357 wxWindow::DoThaw();
358 }
359
360 /// Clear all text
361 void wxRichTextCtrl::Clear()
362 {
363 if (GetFocusObject() == & GetBuffer())
364 {
365 m_buffer.ResetAndClearCommands();
366 m_buffer.Invalidate(wxRICHTEXT_ALL);
367 }
368 else
369 {
370 GetFocusObject()->Reset();
371 }
372
373 m_caretPosition = -1;
374 m_caretPositionForDefaultStyle = -2;
375 m_caretAtLineStart = false;
376 m_selection.Reset();
377 m_selectionState = wxRichTextCtrlSelectionState_Normal;
378
379 Scroll(0,0);
380
381 if (!IsFrozen())
382 {
383 LayoutContent();
384 Refresh(false);
385 }
386
387 wxTextCtrl::SendTextUpdatedEvent(this);
388 }
389
390 /// Painting
391 void wxRichTextCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
392 {
393 #if !wxRICHTEXT_USE_OWN_CARET
394 if (GetCaret() && !IsFrozen())
395 GetCaret()->Hide();
396 #endif
397
398 {
399 #if wxRICHTEXT_BUFFERED_PAINTING
400 wxBufferedPaintDC dc(this, m_bufferBitmap);
401 #else
402 wxPaintDC dc(this);
403 #endif
404
405 if (IsFrozen())
406 return;
407
408 PrepareDC(dc);
409
410 dc.SetFont(GetFont());
411
412 // Paint the background
413 PaintBackground(dc);
414
415 // wxRect drawingArea(GetLogicalPoint(wxPoint(0, 0)), GetClientSize());
416
417 wxRect drawingArea(GetUpdateRegion().GetBox());
418 drawingArea.SetPosition(GetLogicalPoint(drawingArea.GetPosition()));
419
420 wxRect availableSpace(GetClientSize());
421 if (GetBuffer().IsDirty())
422 {
423 GetBuffer().Layout(dc, availableSpace, wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT);
424 GetBuffer().Invalidate(wxRICHTEXT_NONE);
425 SetupScrollbars();
426 }
427
428 wxRect clipRect(availableSpace);
429 clipRect.x += GetBuffer().GetLeftMargin();
430 clipRect.y += GetBuffer().GetTopMargin();
431 clipRect.width -= (GetBuffer().GetLeftMargin() + GetBuffer().GetRightMargin());
432 clipRect.height -= (GetBuffer().GetTopMargin() + GetBuffer().GetBottomMargin());
433 clipRect.SetPosition(GetLogicalPoint(clipRect.GetPosition()));
434 dc.SetClippingRegion(clipRect);
435
436 int flags = 0;
437 if ((GetExtraStyle() & wxRICHTEXT_EX_NO_GUIDELINES) == 0)
438 flags |= wxRICHTEXT_DRAW_GUIDELINES;
439
440 GetBuffer().Draw(dc, GetBuffer().GetOwnRange(), GetSelection(), drawingArea, 0 /* descent */, flags);
441
442 dc.DestroyClippingRegion();
443
444 // Other user defined painting after everything else (i.e. all text) is painted
445 PaintAboveContent(dc);
446
447 #if wxRICHTEXT_USE_OWN_CARET
448 if (GetCaret()->IsVisible())
449 {
450 ((wxRichTextCaret*) GetCaret())->DoDraw(& dc);
451 }
452 #endif
453 }
454
455 #if !wxRICHTEXT_USE_OWN_CARET
456 if (GetCaret())
457 GetCaret()->Show();
458 PositionCaret();
459 #else
460 #if !defined(__WXMAC__)
461 // Causes caret dropouts on Mac
462 PositionCaret();
463 #endif
464 #endif
465 }
466
467 // Empty implementation, to prevent flicker
468 void wxRichTextCtrl::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
469 {
470 }
471
472 void wxRichTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
473 {
474 if (GetCaret())
475 {
476 #if !wxRICHTEXT_USE_OWN_CARET
477 PositionCaret();
478 #endif
479 GetCaret()->Show();
480 }
481
482 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
483 // Work around dropouts when control is focused
484 if (!IsFrozen())
485 {
486 Refresh(false);
487 }
488 #endif
489 }
490
491 void wxRichTextCtrl::OnKillFocus(wxFocusEvent& WXUNUSED(event))
492 {
493 if (GetCaret())
494 GetCaret()->Hide();
495
496 #if defined(__WXGTK__) && !wxRICHTEXT_USE_OWN_CARET
497 // Work around dropouts when control is focused
498 if (!IsFrozen())
499 {
500 Refresh(false);
501 }
502 #endif
503 }
504
505 void wxRichTextCtrl::OnCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
506 {
507 m_dragging = false;
508 }
509
510 // Set up the caret for the given position and container, after a mouse click
511 bool wxRichTextCtrl::SetCaretPositionAfterClick(wxRichTextParagraphLayoutBox* container, long position, int hitTestFlags, bool extendSelection)
512 {
513 bool caretAtLineStart = false;
514
515 if (hitTestFlags & wxRICHTEXT_HITTEST_BEFORE)
516 {
517 // If we're at the start of a line (but not first in para)
518 // then we should keep the caret showing at the start of the line
519 // by showing the m_caretAtLineStart flag.
520 wxRichTextParagraph* para = container->GetParagraphAtPosition(position);
521 wxRichTextLine* line = container->GetLineAtPosition(position);
522
523 if (line && para && line->GetAbsoluteRange().GetStart() == position && para->GetRange().GetStart() != position)
524 caretAtLineStart = true;
525 position --;
526 }
527
528 if (extendSelection && (m_caretPosition != position))
529 ExtendSelection(m_caretPosition, position, wxRICHTEXT_SHIFT_DOWN);
530
531 MoveCaret(position, caretAtLineStart);
532 SetDefaultStyleToCursorStyle();
533
534 return true;
535 }
536
537 /// Left-click
538 void wxRichTextCtrl::OnLeftClick(wxMouseEvent& event)
539 {
540 SetFocus();
541
542 wxClientDC dc(this);
543 PrepareDC(dc);
544 dc.SetFont(GetFont());
545
546 // TODO: detect change of focus object
547 long position = 0;
548 wxRichTextObject* hitObj = NULL;
549 wxRichTextObject* contextObj = NULL;
550 int hit = GetBuffer().HitTest(dc, event.GetLogicalPosition(dc), position, & hitObj, & contextObj);
551
552 if (hit != wxRICHTEXT_HITTEST_NONE && hitObj)
553 {
554 wxRichTextParagraphLayoutBox* oldFocusObject = GetFocusObject();
555 wxRichTextParagraphLayoutBox* container = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
556 if (container && container != GetFocusObject() && container->AcceptsFocus())
557 {
558 SetFocusObject(container, false /* don't set caret position yet */);
559 }
560
561 m_dragStart = event.GetLogicalPosition(dc);
562 m_dragging = true;
563 CaptureMouse();
564
565 long oldCaretPos = m_caretPosition;
566
567 SetCaretPositionAfterClick(container, position, hit);
568
569 // For now, don't handle shift-click when we're selecting multiple objects.
570 if (event.ShiftDown() && GetFocusObject() == oldFocusObject && m_selectionState == wxRichTextCtrlSelectionState_Normal)
571 {
572 if (!m_selection.IsValid())
573 ExtendSelection(oldCaretPos, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
574 else
575 ExtendSelection(m_caretPosition, m_caretPosition, wxRICHTEXT_SHIFT_DOWN);
576 }
577 else
578 SelectNone();
579 }
580
581 event.Skip();
582 }
583
584 /// Left-up
585 void wxRichTextCtrl::OnLeftUp(wxMouseEvent& event)
586 {
587 if (m_dragging)
588 {
589 m_dragging = false;
590 if (GetCapture() == this)
591 ReleaseMouse();
592
593 // See if we clicked on a URL
594 wxClientDC dc(this);
595 PrepareDC(dc);
596 dc.SetFont(GetFont());
597
598 long position = 0;
599 wxPoint logicalPt = event.GetLogicalPosition(dc);
600 wxRichTextObject* hitObj = NULL;
601 wxRichTextObject* contextObj = NULL;
602 // Only get objects at this level, not nested, because otherwise we couldn't swipe text at a single level.
603 int hit = GetFocusObject()->HitTest(dc, logicalPt, position, & hitObj, & contextObj, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS);
604
605 if ((hit != wxRICHTEXT_HITTEST_NONE) && !(hit & wxRICHTEXT_HITTEST_OUTSIDE))
606 {
607 wxRichTextEvent cmdEvent(
608 wxEVT_COMMAND_RICHTEXT_LEFT_CLICK,
609 GetId());
610 cmdEvent.SetEventObject(this);
611 cmdEvent.SetPosition(position);
612 if (hitObj)
613 cmdEvent.SetContainer(hitObj->GetContainer());
614
615 if (!GetEventHandler()->ProcessEvent(cmdEvent))
616 {
617 wxRichTextAttr attr;
618 if (GetStyle(position, attr))
619 {
620 if (attr.HasFlag(wxTEXT_ATTR_URL))
621 {
622 wxString urlTarget = attr.GetURL();
623 if (!urlTarget.IsEmpty())
624 {
625 wxMouseEvent mouseEvent(event);
626
627 long startPos = 0, endPos = 0;
628 wxRichTextObject* obj = GetFocusObject()->GetLeafObjectAtPosition(position);
629 if (obj)
630 {
631 startPos = obj->GetRange().GetStart();
632 endPos = obj->GetRange().GetEnd();
633 }
634
635 wxTextUrlEvent urlEvent(GetId(), mouseEvent, startPos, endPos);
636 InitCommandEvent(urlEvent);
637
638 urlEvent.SetString(urlTarget);
639
640 GetEventHandler()->ProcessEvent(urlEvent);
641 }
642 }
643 }
644 }
645 }
646 }
647 }
648
649 /// Left-click
650 void wxRichTextCtrl::OnMoveMouse(wxMouseEvent& event)
651 {
652 wxClientDC dc(this);
653 PrepareDC(dc);
654 dc.SetFont(GetFont());
655
656 long position = 0;
657 wxPoint logicalPt = event.GetLogicalPosition(dc);
658 wxRichTextObject* hitObj = NULL;
659 wxRichTextObject* contextObj = NULL;
660
661 int flags = 0;
662
663 // If we're dragging, let's only consider positions at this level; otherwise
664 // selecting a range is not going to work.
665 wxRichTextParagraphLayoutBox* container = & GetBuffer();
666 if (m_dragging)
667 {
668 flags = wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS;
669 container = GetFocusObject();
670 }
671 int hit = container->HitTest(dc, logicalPt, position, & hitObj, & contextObj, flags);
672
673 // See if we need to change the cursor
674
675 {
676 if (hit != wxRICHTEXT_HITTEST_NONE && !(hit & wxRICHTEXT_HITTEST_OUTSIDE) && hitObj)
677 {
678 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
679 wxRichTextAttr attr;
680 if (actualContainer && GetStyle(position, attr, actualContainer))
681 {
682 if (attr.HasFlag(wxTEXT_ATTR_URL))
683 {
684 SetCursor(m_urlCursor);
685 }
686 else if (!attr.HasFlag(wxTEXT_ATTR_URL))
687 {
688 SetCursor(m_textCursor);
689 }
690 }
691 }
692 else
693 SetCursor(m_textCursor);
694 }
695
696 if (!event.Dragging())
697 {
698 event.Skip();
699 return;
700 }
701
702 if (m_dragging)
703 {
704 wxRichTextParagraphLayoutBox* commonAncestor = NULL;
705 wxRichTextParagraphLayoutBox* otherContainer = NULL;
706 wxRichTextParagraphLayoutBox* firstContainer = NULL;
707
708 // Check for dragging across multiple containers
709 long position2 = 0;
710 wxRichTextObject* hitObj2 = NULL, *contextObj2 = NULL;
711 int hit2 = GetBuffer().HitTest(dc, logicalPt, position2, & hitObj2, & contextObj2, 0);
712 if (hit2 != wxRICHTEXT_HITTEST_NONE && !(hit2 & wxRICHTEXT_HITTEST_OUTSIDE) && hitObj2 && hitObj != hitObj2)
713 {
714 // See if we can find a common ancestor
715 if (m_selectionState == wxRichTextCtrlSelectionState_Normal)
716 {
717 firstContainer = GetFocusObject();
718 commonAncestor = wxDynamicCast(firstContainer->GetParent(), wxRichTextParagraphLayoutBox);
719 }
720 else
721 {
722 firstContainer = wxDynamicCast(m_selectionAnchorObject, wxRichTextParagraphLayoutBox);
723 //commonAncestor = GetFocusObject(); // when the selection state is not normal, the focus object (e.g. table)
724 // is the common ancestor.
725 commonAncestor = wxDynamicCast(firstContainer->GetParent(), wxRichTextParagraphLayoutBox);
726 }
727
728 if (commonAncestor && commonAncestor->HandlesChildSelections())
729 {
730 wxRichTextObject* p = hitObj2;
731 while (p)
732 {
733 if (p->GetParent() == commonAncestor)
734 {
735 otherContainer = wxDynamicCast(p, wxRichTextParagraphLayoutBox);
736 break;
737 }
738 p = p->GetParent();
739 }
740 }
741
742 if (commonAncestor && firstContainer && otherContainer)
743 {
744 // We have now got a second container that shares a parent with the current or anchor object.
745 if (m_selectionState == wxRichTextCtrlSelectionState_Normal)
746 {
747 // Don't go into common-ancestor selection mode if we still have the same
748 // container.
749 if (otherContainer != firstContainer)
750 {
751 m_selectionState = wxRichTextCtrlSelectionState_CommonAncestor;
752 m_selectionAnchorObject = firstContainer;
753 m_selectionAnchor = firstContainer->GetRange().GetStart();
754
755 // The common ancestor, such as a table, returns the cell selection
756 // between the anchor and current position.
757 m_selection = commonAncestor->GetSelection(m_selectionAnchor, otherContainer->GetRange().GetStart());
758 }
759 }
760 else
761 {
762 m_selection = commonAncestor->GetSelection(m_selectionAnchor, otherContainer->GetRange().GetStart());
763 }
764
765 Refresh();
766
767 if (otherContainer->AcceptsFocus())
768 SetFocusObject(otherContainer, false /* don't set caret and clear selection */);
769 MoveCaret(-1, false);
770 SetDefaultStyleToCursorStyle();
771 }
772 }
773 }
774
775 if (hitObj && m_dragging && hit != wxRICHTEXT_HITTEST_NONE && m_selectionState == wxRichTextCtrlSelectionState_Normal)
776 {
777 // TODO: test closeness
778 SetCaretPositionAfterClick(container, position, hit, true /* extend selection */);
779 }
780 }
781
782 /// Right-click
783 void wxRichTextCtrl::OnRightClick(wxMouseEvent& event)
784 {
785 SetFocus();
786
787 wxClientDC dc(this);
788 PrepareDC(dc);
789 dc.SetFont(GetFont());
790
791 long position = 0;
792 wxPoint logicalPt = event.GetLogicalPosition(dc);
793 wxRichTextObject* hitObj = NULL;
794 wxRichTextObject* contextObj = NULL;
795 int hit = GetFocusObject()->HitTest(dc, logicalPt, position, & hitObj, & contextObj);
796
797 if (hitObj && hitObj->GetContainer() != GetFocusObject())
798 {
799 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
800 if (actualContainer && actualContainer->AcceptsFocus())
801 {
802 SetFocusObject(actualContainer, false /* don't set caret position yet */);
803 SetCaretPositionAfterClick(actualContainer, position, hit);
804 }
805 }
806
807 wxRichTextEvent cmdEvent(
808 wxEVT_COMMAND_RICHTEXT_RIGHT_CLICK,
809 GetId());
810 cmdEvent.SetEventObject(this);
811 cmdEvent.SetPosition(position);
812 if (hitObj)
813 cmdEvent.SetContainer(hitObj->GetContainer());
814
815 if (!GetEventHandler()->ProcessEvent(cmdEvent))
816 event.Skip();
817 }
818
819 /// Left-double-click
820 void wxRichTextCtrl::OnLeftDClick(wxMouseEvent& WXUNUSED(event))
821 {
822 wxRichTextEvent cmdEvent(
823 wxEVT_COMMAND_RICHTEXT_LEFT_DCLICK,
824 GetId());
825 cmdEvent.SetEventObject(this);
826 cmdEvent.SetPosition(m_caretPosition+1);
827 cmdEvent.SetContainer(GetFocusObject());
828
829 if (!GetEventHandler()->ProcessEvent(cmdEvent))
830 {
831 SelectWord(GetCaretPosition()+1);
832 }
833 }
834
835 /// Middle-click
836 void wxRichTextCtrl::OnMiddleClick(wxMouseEvent& event)
837 {
838 wxRichTextEvent cmdEvent(
839 wxEVT_COMMAND_RICHTEXT_MIDDLE_CLICK,
840 GetId());
841 cmdEvent.SetEventObject(this);
842 cmdEvent.SetPosition(m_caretPosition+1);
843 cmdEvent.SetContainer(GetFocusObject());
844
845 if (!GetEventHandler()->ProcessEvent(cmdEvent))
846 event.Skip();
847 }
848
849 /// Key press
850 void wxRichTextCtrl::OnChar(wxKeyEvent& event)
851 {
852 int flags = 0;
853 if (event.CmdDown())
854 flags |= wxRICHTEXT_CTRL_DOWN;
855 if (event.ShiftDown())
856 flags |= wxRICHTEXT_SHIFT_DOWN;
857 if (event.AltDown())
858 flags |= wxRICHTEXT_ALT_DOWN;
859
860 if (event.GetEventType() == wxEVT_KEY_DOWN)
861 {
862 if (event.IsKeyInCategory(WXK_CATEGORY_NAVIGATION))
863 {
864 KeyboardNavigate(event.GetKeyCode(), flags);
865 return;
866 }
867
868 long keycode = event.GetKeyCode();
869 switch ( keycode )
870 {
871 case WXK_ESCAPE:
872 case WXK_START:
873 case WXK_LBUTTON:
874 case WXK_RBUTTON:
875 case WXK_CANCEL:
876 case WXK_MBUTTON:
877 case WXK_CLEAR:
878 case WXK_SHIFT:
879 case WXK_ALT:
880 case WXK_CONTROL:
881 case WXK_MENU:
882 case WXK_PAUSE:
883 case WXK_CAPITAL:
884 case WXK_END:
885 case WXK_HOME:
886 case WXK_LEFT:
887 case WXK_UP:
888 case WXK_RIGHT:
889 case WXK_DOWN:
890 case WXK_SELECT:
891 case WXK_PRINT:
892 case WXK_EXECUTE:
893 case WXK_SNAPSHOT:
894 case WXK_INSERT:
895 case WXK_HELP:
896 case WXK_F1:
897 case WXK_F2:
898 case WXK_F3:
899 case WXK_F4:
900 case WXK_F5:
901 case WXK_F6:
902 case WXK_F7:
903 case WXK_F8:
904 case WXK_F9:
905 case WXK_F10:
906 case WXK_F11:
907 case WXK_F12:
908 case WXK_F13:
909 case WXK_F14:
910 case WXK_F15:
911 case WXK_F16:
912 case WXK_F17:
913 case WXK_F18:
914 case WXK_F19:
915 case WXK_F20:
916 case WXK_F21:
917 case WXK_F22:
918 case WXK_F23:
919 case WXK_F24:
920 case WXK_NUMLOCK:
921 case WXK_SCROLL:
922 case WXK_PAGEUP:
923 case WXK_PAGEDOWN:
924 case WXK_NUMPAD_F1:
925 case WXK_NUMPAD_F2:
926 case WXK_NUMPAD_F3:
927 case WXK_NUMPAD_F4:
928 case WXK_NUMPAD_HOME:
929 case WXK_NUMPAD_LEFT:
930 case WXK_NUMPAD_UP:
931 case WXK_NUMPAD_RIGHT:
932 case WXK_NUMPAD_DOWN:
933 case WXK_NUMPAD_PAGEUP:
934 case WXK_NUMPAD_PAGEDOWN:
935 case WXK_NUMPAD_END:
936 case WXK_NUMPAD_BEGIN:
937 case WXK_NUMPAD_INSERT:
938 case WXK_WINDOWS_LEFT:
939 {
940 return;
941 }
942 default:
943 {
944 }
945 }
946
947 // Must process this before translation, otherwise it's translated into a WXK_DELETE event.
948 if (event.CmdDown() && event.GetKeyCode() == WXK_BACK)
949 {
950 BeginBatchUndo(_("Delete Text"));
951
952 long newPos = m_caretPosition;
953
954 bool processed = DeleteSelectedContent(& newPos);
955
956 // Submit range in character positions, which are greater than caret positions,
957 // so subtract 1 for deleted character and add 1 for conversion to character position.
958 if (newPos > -1)
959 {
960 if (event.CmdDown())
961 {
962 long pos = wxRichTextCtrl::FindNextWordPosition(-1);
963 if (pos < newPos)
964 {
965 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(pos+1, newPos), this, & GetBuffer());
966 processed = true;
967 }
968 }
969
970 if (!processed)
971 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos, newPos), this, & GetBuffer());
972 }
973
974 EndBatchUndo();
975
976 if (GetLastPosition() == -1)
977 {
978 GetFocusObject()->Reset();
979
980 m_caretPosition = -1;
981 PositionCaret();
982 SetDefaultStyleToCursorStyle();
983 }
984
985 ScrollIntoView(m_caretPosition, WXK_LEFT);
986
987 wxRichTextEvent cmdEvent(
988 wxEVT_COMMAND_RICHTEXT_DELETE,
989 GetId());
990 cmdEvent.SetEventObject(this);
991 cmdEvent.SetFlags(flags);
992 cmdEvent.SetPosition(m_caretPosition+1);
993 cmdEvent.SetContainer(GetFocusObject());
994 GetEventHandler()->ProcessEvent(cmdEvent);
995
996 Update();
997 }
998 else
999 event.Skip();
1000
1001 return;
1002 }
1003
1004 // all the other keys modify the controls contents which shouldn't be
1005 // possible if we're read-only
1006 if ( !IsEditable() )
1007 {
1008 event.Skip();
1009 return;
1010 }
1011
1012 if (event.GetKeyCode() == WXK_RETURN)
1013 {
1014 BeginBatchUndo(_("Insert Text"));
1015
1016 long newPos = m_caretPosition;
1017
1018 DeleteSelectedContent(& newPos);
1019
1020 if (event.ShiftDown())
1021 {
1022 wxString text;
1023 text = wxRichTextLineBreakChar;
1024 GetFocusObject()->InsertTextWithUndo(newPos+1, text, this, & GetBuffer());
1025 m_caretAtLineStart = true;
1026 PositionCaret();
1027 }
1028 else
1029 GetFocusObject()->InsertNewlineWithUndo(newPos+1, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE|wxRICHTEXT_INSERT_INTERACTIVE);
1030
1031 EndBatchUndo();
1032 SetDefaultStyleToCursorStyle();
1033
1034 ScrollIntoView(m_caretPosition, WXK_RIGHT);
1035
1036 wxRichTextEvent cmdEvent(
1037 wxEVT_COMMAND_RICHTEXT_RETURN,
1038 GetId());
1039 cmdEvent.SetEventObject(this);
1040 cmdEvent.SetFlags(flags);
1041 cmdEvent.SetPosition(newPos+1);
1042 cmdEvent.SetContainer(GetFocusObject());
1043
1044 if (!GetEventHandler()->ProcessEvent(cmdEvent))
1045 {
1046 // Generate conventional event
1047 wxCommandEvent textEvent(wxEVT_COMMAND_TEXT_ENTER, GetId());
1048 InitCommandEvent(textEvent);
1049
1050 GetEventHandler()->ProcessEvent(textEvent);
1051 }
1052 Update();
1053 }
1054 else if (event.GetKeyCode() == WXK_BACK)
1055 {
1056 BeginBatchUndo(_("Delete Text"));
1057
1058 long newPos = m_caretPosition;
1059
1060 bool processed = DeleteSelectedContent(& newPos);
1061
1062 // Submit range in character positions, which are greater than caret positions,
1063 // so subtract 1 for deleted character and add 1 for conversion to character position.
1064 if (newPos > -1)
1065 {
1066 if (event.CmdDown())
1067 {
1068 long pos = wxRichTextCtrl::FindNextWordPosition(-1);
1069 if (pos < newPos)
1070 {
1071 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(pos+1, newPos), this, & GetBuffer());
1072 processed = true;
1073 }
1074 }
1075
1076 if (!processed)
1077 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos, newPos), this, & GetBuffer());
1078 }
1079
1080 EndBatchUndo();
1081
1082 if (GetLastPosition() == -1)
1083 {
1084 GetFocusObject()->Reset();
1085
1086 m_caretPosition = -1;
1087 PositionCaret();
1088 SetDefaultStyleToCursorStyle();
1089 }
1090
1091 ScrollIntoView(m_caretPosition, WXK_LEFT);
1092
1093 wxRichTextEvent cmdEvent(
1094 wxEVT_COMMAND_RICHTEXT_DELETE,
1095 GetId());
1096 cmdEvent.SetEventObject(this);
1097 cmdEvent.SetFlags(flags);
1098 cmdEvent.SetPosition(m_caretPosition+1);
1099 cmdEvent.SetContainer(GetFocusObject());
1100 GetEventHandler()->ProcessEvent(cmdEvent);
1101
1102 Update();
1103 }
1104 else if (event.GetKeyCode() == WXK_DELETE)
1105 {
1106 BeginBatchUndo(_("Delete Text"));
1107
1108 long newPos = m_caretPosition;
1109
1110 bool processed = DeleteSelectedContent(& newPos);
1111
1112 // Submit range in character positions, which are greater than caret positions,
1113 if (newPos < GetFocusObject()->GetOwnRange().GetEnd()+1)
1114 {
1115 if (event.CmdDown())
1116 {
1117 long pos = wxRichTextCtrl::FindNextWordPosition(1);
1118 if (pos != -1 && (pos > newPos))
1119 {
1120 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos+1, pos), this, & GetBuffer());
1121 processed = true;
1122 }
1123 }
1124
1125 if (!processed && newPos < (GetLastPosition()-1))
1126 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(newPos+1, newPos+1), this, & GetBuffer());
1127 }
1128
1129 EndBatchUndo();
1130
1131 if (GetLastPosition() == -1)
1132 {
1133 GetFocusObject()->Reset();
1134
1135 m_caretPosition = -1;
1136 PositionCaret();
1137 SetDefaultStyleToCursorStyle();
1138 }
1139
1140 wxRichTextEvent cmdEvent(
1141 wxEVT_COMMAND_RICHTEXT_DELETE,
1142 GetId());
1143 cmdEvent.SetEventObject(this);
1144 cmdEvent.SetFlags(flags);
1145 cmdEvent.SetPosition(m_caretPosition+1);
1146 cmdEvent.SetContainer(GetFocusObject());
1147 GetEventHandler()->ProcessEvent(cmdEvent);
1148
1149 Update();
1150 }
1151 else
1152 {
1153 long keycode = event.GetKeyCode();
1154 switch ( keycode )
1155 {
1156 case WXK_ESCAPE:
1157 {
1158 event.Skip();
1159 return;
1160 }
1161
1162 default:
1163 {
1164 #ifdef __WXMAC__
1165 if (event.CmdDown())
1166 #else
1167 // Fixes AltGr+key with European input languages on Windows
1168 if ((event.CmdDown() && !event.AltDown()) || (event.AltDown() && !event.CmdDown()))
1169 #endif
1170 {
1171 event.Skip();
1172 return;
1173 }
1174
1175 wxRichTextEvent cmdEvent(
1176 wxEVT_COMMAND_RICHTEXT_CHARACTER,
1177 GetId());
1178 cmdEvent.SetEventObject(this);
1179 cmdEvent.SetFlags(flags);
1180 #if wxUSE_UNICODE
1181 cmdEvent.SetCharacter(event.GetUnicodeKey());
1182 #else
1183 cmdEvent.SetCharacter((wxChar) keycode);
1184 #endif
1185 cmdEvent.SetPosition(m_caretPosition+1);
1186 cmdEvent.SetContainer(GetFocusObject());
1187
1188 if (keycode == wxT('\t'))
1189 {
1190 // See if we need to promote or demote the selection or paragraph at the cursor
1191 // position, instead of inserting a tab.
1192 long pos = GetAdjustedCaretPosition(GetCaretPosition());
1193 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos);
1194 if (para && para->GetRange().GetStart() == pos && para->GetAttributes().HasListStyleName())
1195 {
1196 wxRichTextRange range;
1197 if (HasSelection())
1198 range = GetSelectionRange();
1199 else
1200 range = para->GetRange().FromInternal();
1201
1202 int promoteBy = event.ShiftDown() ? 1 : -1;
1203
1204 PromoteList(promoteBy, range, NULL);
1205
1206 GetEventHandler()->ProcessEvent(cmdEvent);
1207
1208 return;
1209 }
1210 }
1211
1212 BeginBatchUndo(_("Insert Text"));
1213
1214 long newPos = m_caretPosition;
1215 DeleteSelectedContent(& newPos);
1216
1217 #if wxUSE_UNICODE
1218 wxString str = event.GetUnicodeKey();
1219 #else
1220 wxString str = (wxChar) event.GetKeyCode();
1221 #endif
1222 GetFocusObject()->InsertTextWithUndo(newPos+1, str, this, & GetBuffer(), 0);
1223
1224 EndBatchUndo();
1225
1226 SetDefaultStyleToCursorStyle();
1227 ScrollIntoView(m_caretPosition, WXK_RIGHT);
1228
1229 cmdEvent.SetPosition(m_caretPosition);
1230 GetEventHandler()->ProcessEvent(cmdEvent);
1231
1232 Update();
1233 }
1234 }
1235 }
1236 }
1237
1238 /// Delete content if there is a selection, e.g. when pressing a key.
1239 bool wxRichTextCtrl::DeleteSelectedContent(long* newPos)
1240 {
1241 if (HasSelection())
1242 {
1243 long pos = m_selection.GetRange().GetStart();
1244 wxRichTextRange range = m_selection.GetRange();
1245
1246 // SelectAll causes more to be selected than doing it interactively,
1247 // and causes a new paragraph to be inserted. So for multiline buffers,
1248 // don't delete the final position.
1249 if (range.GetEnd() == GetLastPosition() && GetNumberOfLines() > 0)
1250 range.SetEnd(range.GetEnd()-1);
1251
1252 GetFocusObject()->DeleteRangeWithUndo(range, this, & GetBuffer());
1253 m_selection.Reset();
1254 m_selectionState = wxRichTextCtrlSelectionState_Normal;
1255
1256 if (newPos)
1257 *newPos = pos-1;
1258 return true;
1259 }
1260 else
1261 return false;
1262 }
1263
1264 /// Keyboard navigation
1265
1266 /*
1267
1268 Left: left one character
1269 Right: right one character
1270 Up: up one line
1271 Down: down one line
1272 Ctrl-Left: left one word
1273 Ctrl-Right: right one word
1274 Ctrl-Up: previous paragraph start
1275 Ctrl-Down: next start of paragraph
1276 Home: start of line
1277 End: end of line
1278 Ctrl-Home: start of document
1279 Ctrl-End: end of document
1280 Page-Up: Up a screen
1281 Page-Down: Down a screen
1282
1283 Maybe:
1284
1285 Ctrl-Alt-PgUp: Start of window
1286 Ctrl-Alt-PgDn: End of window
1287 F8: Start selection mode
1288 Esc: End selection mode
1289
1290 Adding Shift does the above but starts/extends selection.
1291
1292
1293 */
1294
1295 bool wxRichTextCtrl::KeyboardNavigate(int keyCode, int flags)
1296 {
1297 bool success = false;
1298
1299 if (keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT)
1300 {
1301 if (flags & wxRICHTEXT_CTRL_DOWN)
1302 success = WordRight(1, flags);
1303 else
1304 success = MoveRight(1, flags);
1305 }
1306 else if (keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT)
1307 {
1308 if (flags & wxRICHTEXT_CTRL_DOWN)
1309 success = WordLeft(1, flags);
1310 else
1311 success = MoveLeft(1, flags);
1312 }
1313 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP)
1314 {
1315 if (flags & wxRICHTEXT_CTRL_DOWN)
1316 success = MoveToParagraphStart(flags);
1317 else
1318 success = MoveUp(1, flags);
1319 }
1320 else if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN)
1321 {
1322 if (flags & wxRICHTEXT_CTRL_DOWN)
1323 success = MoveToParagraphEnd(flags);
1324 else
1325 success = MoveDown(1, flags);
1326 }
1327 else if (keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP)
1328 {
1329 success = PageUp(1, flags);
1330 }
1331 else if (keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
1332 {
1333 success = PageDown(1, flags);
1334 }
1335 else if (keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME)
1336 {
1337 if (flags & wxRICHTEXT_CTRL_DOWN)
1338 success = MoveHome(flags);
1339 else
1340 success = MoveToLineStart(flags);
1341 }
1342 else if (keyCode == WXK_END || keyCode == WXK_NUMPAD_END)
1343 {
1344 if (flags & wxRICHTEXT_CTRL_DOWN)
1345 success = MoveEnd(flags);
1346 else
1347 success = MoveToLineEnd(flags);
1348 }
1349
1350 if (success)
1351 {
1352 ScrollIntoView(m_caretPosition, keyCode);
1353 SetDefaultStyleToCursorStyle();
1354 }
1355
1356 return success;
1357 }
1358
1359 /// Extend the selection. Selections are in caret positions.
1360 bool wxRichTextCtrl::ExtendSelection(long oldPos, long newPos, int flags)
1361 {
1362 if (flags & wxRICHTEXT_SHIFT_DOWN)
1363 {
1364 if (oldPos == newPos)
1365 return false;
1366
1367 wxRichTextSelection oldSelection = m_selection;
1368
1369 m_selection.SetContainer(GetFocusObject());
1370
1371 wxRichTextRange oldRange;
1372 if (m_selection.IsValid())
1373 oldRange = m_selection.GetRange();
1374 else
1375 oldRange = wxRICHTEXT_NO_SELECTION;
1376 wxRichTextRange newRange;
1377
1378 // If not currently selecting, start selecting
1379 if (oldRange.GetStart() == -2)
1380 {
1381 m_selectionAnchor = oldPos;
1382
1383 if (oldPos > newPos)
1384 newRange.SetRange(newPos+1, oldPos);
1385 else
1386 newRange.SetRange(oldPos+1, newPos);
1387 }
1388 else
1389 {
1390 // Always ensure that the selection range start is greater than
1391 // the end.
1392 if (newPos > m_selectionAnchor)
1393 newRange.SetRange(m_selectionAnchor+1, newPos);
1394 else if (newPos == m_selectionAnchor)
1395 newRange = wxRichTextRange(-2, -2);
1396 else
1397 newRange.SetRange(newPos+1, m_selectionAnchor);
1398 }
1399
1400 m_selection.SetRange(newRange);
1401
1402 RefreshForSelectionChange(oldSelection, m_selection);
1403
1404 if (newRange.GetStart() > newRange.GetEnd())
1405 {
1406 wxLogDebug(wxT("Strange selection range"));
1407 }
1408
1409 return true;
1410 }
1411 else
1412 return false;
1413 }
1414
1415 /// Scroll into view, returning true if we scrolled.
1416 /// This takes a _caret_ position.
1417 bool wxRichTextCtrl::ScrollIntoView(long position, int keyCode)
1418 {
1419 wxRichTextLine* line = GetVisibleLineForCaretPosition(position);
1420
1421 if (!line)
1422 return false;
1423
1424 int ppuX, ppuY;
1425 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1426
1427 int startXUnits, startYUnits;
1428 GetViewStart(& startXUnits, & startYUnits);
1429 int startY = startYUnits * ppuY;
1430
1431 int sx = 0, sy = 0;
1432 GetVirtualSize(& sx, & sy);
1433 int sxUnits = 0;
1434 int syUnits = 0;
1435 if (ppuY != 0)
1436 syUnits = sy/ppuY;
1437
1438 wxRect rect = line->GetRect();
1439
1440 bool scrolled = false;
1441
1442 wxSize clientSize = GetClientSize();
1443
1444 int leftMargin, rightMargin, topMargin, bottomMargin;
1445
1446 {
1447 wxClientDC dc(this);
1448 wxRichTextObject::GetTotalMargin(dc, & GetBuffer(), GetBuffer().GetAttributes(), leftMargin, rightMargin,
1449 topMargin, bottomMargin);
1450 }
1451 // clientSize.y -= GetBuffer().GetBottomMargin();
1452 clientSize.y -= bottomMargin;
1453
1454 if (GetWindowStyle() & wxRE_CENTRE_CARET)
1455 {
1456 int y = rect.y - GetClientSize().y/2;
1457 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1458 if (y >= 0 && (y + clientSize.y) < GetBuffer().GetCachedSize().y)
1459 {
1460 if (startYUnits != yUnits)
1461 {
1462 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1463 scrolled = true;
1464 }
1465 #if !wxRICHTEXT_USE_OWN_CARET
1466 if (scrolled)
1467 #endif
1468 PositionCaret();
1469
1470 return scrolled;
1471 }
1472 }
1473
1474 // Going down
1475 if (keyCode == WXK_DOWN || keyCode == WXK_NUMPAD_DOWN ||
1476 keyCode == WXK_RIGHT || keyCode == WXK_NUMPAD_RIGHT ||
1477 keyCode == WXK_END || keyCode == WXK_NUMPAD_END ||
1478 keyCode == WXK_PAGEDOWN || keyCode == WXK_NUMPAD_PAGEDOWN)
1479 {
1480 if ((rect.y + rect.height) > (clientSize.y + startY))
1481 {
1482 // Make it scroll so this item is at the bottom
1483 // of the window
1484 int y = rect.y - (clientSize.y - rect.height);
1485 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1486
1487 // If we're still off the screen, scroll another line down
1488 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1489 yUnits ++;
1490
1491 if (startYUnits != yUnits)
1492 {
1493 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1494 scrolled = true;
1495 }
1496 }
1497 else if (rect.y < (startY + GetBuffer().GetTopMargin()))
1498 {
1499 // Make it scroll so this item is at the top
1500 // of the window
1501 int y = rect.y - GetBuffer().GetTopMargin();
1502 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1503
1504 if (startYUnits != yUnits)
1505 {
1506 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1507 scrolled = true;
1508 }
1509 }
1510 }
1511 // Going up
1512 else if (keyCode == WXK_UP || keyCode == WXK_NUMPAD_UP ||
1513 keyCode == WXK_LEFT || keyCode == WXK_NUMPAD_LEFT ||
1514 keyCode == WXK_HOME || keyCode == WXK_NUMPAD_HOME ||
1515 keyCode == WXK_PAGEUP || keyCode == WXK_NUMPAD_PAGEUP )
1516 {
1517 if (rect.y < (startY + GetBuffer().GetBottomMargin()))
1518 {
1519 // Make it scroll so this item is at the top
1520 // of the window
1521 int y = rect.y - GetBuffer().GetTopMargin();
1522 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1523
1524 if (startYUnits != yUnits)
1525 {
1526 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1527 scrolled = true;
1528 }
1529 }
1530 else if ((rect.y + rect.height) > (clientSize.y + startY))
1531 {
1532 // Make it scroll so this item is at the bottom
1533 // of the window
1534 int y = rect.y - (clientSize.y - rect.height);
1535 int yUnits = (int) (0.5 + ((float) y)/(float) ppuY);
1536
1537 // If we're still off the screen, scroll another line down
1538 if ((rect.y + rect.height) > (clientSize.y + (yUnits*ppuY)))
1539 yUnits ++;
1540
1541 if (startYUnits != yUnits)
1542 {
1543 SetScrollbars(ppuX, ppuY, sxUnits, syUnits, 0, yUnits);
1544 scrolled = true;
1545 }
1546 }
1547 }
1548
1549 #if !wxRICHTEXT_USE_OWN_CARET
1550 if (scrolled)
1551 #endif
1552 PositionCaret();
1553
1554 return scrolled;
1555 }
1556
1557 /// Is the given position visible on the screen?
1558 bool wxRichTextCtrl::IsPositionVisible(long pos) const
1559 {
1560 wxRichTextLine* line = GetVisibleLineForCaretPosition(pos-1);
1561
1562 if (!line)
1563 return false;
1564
1565 int ppuX, ppuY;
1566 GetScrollPixelsPerUnit(& ppuX, & ppuY);
1567
1568 int startX, startY;
1569 GetViewStart(& startX, & startY);
1570 startX = 0;
1571 startY = startY * ppuY;
1572
1573 wxRect rect = line->GetRect();
1574 wxSize clientSize = GetClientSize();
1575 clientSize.y -= GetBuffer().GetBottomMargin();
1576
1577 return (rect.GetTop() >= (startY + GetBuffer().GetTopMargin())) && (rect.GetBottom() <= (startY + clientSize.y));
1578 }
1579
1580 void wxRichTextCtrl::SetCaretPosition(long position, bool showAtLineStart)
1581 {
1582 m_caretPosition = position;
1583 m_caretAtLineStart = showAtLineStart;
1584 }
1585
1586 /// Move caret one visual step forward: this may mean setting a flag
1587 /// and keeping the same position if we're going from the end of one line
1588 /// to the start of the next, which may be the exact same caret position.
1589 void wxRichTextCtrl::MoveCaretForward(long oldPosition)
1590 {
1591 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(oldPosition);
1592
1593 // Only do the check if we're not at the end of the paragraph (where things work OK
1594 // anyway)
1595 if (para && (oldPosition != para->GetRange().GetEnd() - 1))
1596 {
1597 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(oldPosition);
1598
1599 if (line)
1600 {
1601 wxRichTextRange lineRange = line->GetAbsoluteRange();
1602
1603 // We're at the end of a line. See whether we need to
1604 // stay at the same actual caret position but change visual
1605 // position, or not.
1606 if (oldPosition == lineRange.GetEnd())
1607 {
1608 if (m_caretAtLineStart)
1609 {
1610 // We're already at the start of the line, so actually move on now.
1611 m_caretPosition = oldPosition + 1;
1612 m_caretAtLineStart = false;
1613 }
1614 else
1615 {
1616 // We're showing at the end of the line, so keep to
1617 // the same position but indicate that we're to show
1618 // at the start of the next line.
1619 m_caretPosition = oldPosition;
1620 m_caretAtLineStart = true;
1621 }
1622 SetDefaultStyleToCursorStyle();
1623 return;
1624 }
1625 }
1626 }
1627 m_caretPosition ++;
1628 SetDefaultStyleToCursorStyle();
1629 }
1630
1631 /// Move caret one visual step backward: this may mean setting a flag
1632 /// and keeping the same position if we're going from the end of one line
1633 /// to the start of the next, which may be the exact same caret position.
1634 void wxRichTextCtrl::MoveCaretBack(long oldPosition)
1635 {
1636 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(oldPosition);
1637
1638 // Only do the check if we're not at the start of the paragraph (where things work OK
1639 // anyway)
1640 if (para && (oldPosition != para->GetRange().GetStart()))
1641 {
1642 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(oldPosition);
1643
1644 if (line)
1645 {
1646 wxRichTextRange lineRange = line->GetAbsoluteRange();
1647
1648 // We're at the start of a line. See whether we need to
1649 // stay at the same actual caret position but change visual
1650 // position, or not.
1651 if (oldPosition == lineRange.GetStart())
1652 {
1653 m_caretPosition = oldPosition-1;
1654 m_caretAtLineStart = true;
1655 return;
1656 }
1657 else if (oldPosition == lineRange.GetEnd())
1658 {
1659 if (m_caretAtLineStart)
1660 {
1661 // We're at the start of the line, so keep the same caret position
1662 // but clear the start-of-line flag.
1663 m_caretPosition = oldPosition;
1664 m_caretAtLineStart = false;
1665 }
1666 else
1667 {
1668 // We're showing at the end of the line, so go back
1669 // to the previous character position.
1670 m_caretPosition = oldPosition - 1;
1671 }
1672 SetDefaultStyleToCursorStyle();
1673 return;
1674 }
1675 }
1676 }
1677 m_caretPosition --;
1678 SetDefaultStyleToCursorStyle();
1679 }
1680
1681 /// Move right
1682 bool wxRichTextCtrl::MoveRight(int noPositions, int flags)
1683 {
1684 long endPos = GetFocusObject()->GetOwnRange().GetEnd();
1685
1686 if (m_caretPosition + noPositions < endPos)
1687 {
1688 long oldPos = m_caretPosition;
1689 long newPos = m_caretPosition + noPositions;
1690
1691 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1692 if (!extendSel)
1693 SelectNone();
1694
1695 // Determine by looking at oldPos and m_caretPosition whether
1696 // we moved from the end of a line to the start of the next line, in which case
1697 // we want to adjust the caret position such that it is positioned at the
1698 // start of the next line, rather than jumping past the first character of the
1699 // line.
1700 if (noPositions == 1 && !extendSel)
1701 MoveCaretForward(oldPos);
1702 else
1703 SetCaretPosition(newPos);
1704
1705 PositionCaret();
1706 SetDefaultStyleToCursorStyle();
1707
1708 return true;
1709 }
1710 else
1711 return false;
1712 }
1713
1714 /// Move left
1715 bool wxRichTextCtrl::MoveLeft(int noPositions, int flags)
1716 {
1717 long startPos = -1;
1718
1719 if (m_caretPosition > startPos - noPositions + 1)
1720 {
1721 long oldPos = m_caretPosition;
1722 long newPos = m_caretPosition - noPositions;
1723 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1724 if (!extendSel)
1725 SelectNone();
1726
1727 if (noPositions == 1 && !extendSel)
1728 MoveCaretBack(oldPos);
1729 else
1730 SetCaretPosition(newPos);
1731
1732 PositionCaret();
1733 SetDefaultStyleToCursorStyle();
1734
1735 return true;
1736 }
1737 else
1738 return false;
1739 }
1740
1741 // Find the caret position for the combination of hit-test flags and character position.
1742 // Returns the caret position and also an indication of where to place the caret (caretLineStart)
1743 // since this is ambiguous (same position used for end of line and start of next).
1744 long wxRichTextCtrl::FindCaretPositionForCharacterPosition(long position, int hitTestFlags, wxRichTextParagraphLayoutBox* container,
1745 bool& caretLineStart)
1746 {
1747 // If end of previous line, and hitTest is wxRICHTEXT_HITTEST_BEFORE,
1748 // we want to be at the end of the last line but with m_caretAtLineStart set to true,
1749 // so we view the caret at the start of the line.
1750 caretLineStart = false;
1751 long caretPosition = position;
1752
1753 if (hitTestFlags & wxRICHTEXT_HITTEST_BEFORE)
1754 {
1755 wxRichTextLine* thisLine = container->GetLineAtPosition(position-1);
1756 wxRichTextRange lineRange;
1757 if (thisLine)
1758 lineRange = thisLine->GetAbsoluteRange();
1759
1760 if (thisLine && (position-1) == lineRange.GetEnd())
1761 {
1762 caretPosition --;
1763 caretLineStart = true;
1764 }
1765 else
1766 {
1767 wxRichTextParagraph* para = container->GetParagraphAtPosition(position);
1768 if (para && para->GetRange().GetStart() == position)
1769 caretPosition --;
1770 }
1771 }
1772 return caretPosition;
1773 }
1774
1775 /// Move up
1776 bool wxRichTextCtrl::MoveUp(int noLines, int flags)
1777 {
1778 return MoveDown(- noLines, flags);
1779 }
1780
1781 /// Move up
1782 bool wxRichTextCtrl::MoveDown(int noLines, int flags)
1783 {
1784 if (!GetCaret())
1785 return false;
1786
1787 long lineNumber = GetFocusObject()->GetVisibleLineNumber(m_caretPosition, true, m_caretAtLineStart);
1788 wxPoint pt = GetCaret()->GetPosition();
1789 long newLine = lineNumber + noLines;
1790 bool notInThisObject = false;
1791
1792 if (lineNumber != -1)
1793 {
1794 if (noLines > 0)
1795 {
1796 long lastLine = GetFocusObject()->GetVisibleLineNumber(GetFocusObject()->GetOwnRange().GetEnd());
1797 if (newLine > lastLine)
1798 notInThisObject = true;
1799 }
1800 else
1801 {
1802 if (newLine < 0)
1803 notInThisObject = true;
1804 }
1805 }
1806
1807 wxRichTextParagraphLayoutBox* container = GetFocusObject();
1808 int hitTestFlags = wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS|wxRICHTEXT_HITTEST_NO_FLOATING_OBJECTS;
1809
1810 if (notInThisObject)
1811 {
1812 // If we know we're navigating out of the current object,
1813 // try to find an object anywhere in the buffer at the new position (up or down a bit)
1814 container = & GetBuffer();
1815 hitTestFlags &= ~wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS;
1816
1817 if (noLines > 0) // going down
1818 {
1819 pt.y = GetFocusObject()->GetPosition().y + GetFocusObject()->GetCachedSize().y + 2;
1820 }
1821 else // going up
1822 {
1823 pt.y = GetFocusObject()->GetPosition().y - 2;
1824 }
1825 }
1826 else
1827 {
1828 wxRichTextLine* lineObj = GetFocusObject()->GetLineForVisibleLineNumber(newLine);
1829 if (lineObj)
1830 pt.y = lineObj->GetAbsolutePosition().y + 2;
1831 else
1832 return false;
1833 }
1834
1835 long newPos = 0;
1836 wxClientDC dc(this);
1837 PrepareDC(dc);
1838 dc.SetFont(GetFont());
1839
1840 wxRichTextObject* hitObj = NULL;
1841 wxRichTextObject* contextObj = NULL;
1842 int hitTest = container->HitTest(dc, pt, newPos, & hitObj, & contextObj, hitTestFlags);
1843
1844 if (hitObj &&
1845 ((hitTest & wxRICHTEXT_HITTEST_NONE) == 0) &&
1846 (! (hitObj == (& m_buffer) && ((hitTest & wxRICHTEXT_HITTEST_OUTSIDE) != 0))) // outside the buffer counts as 'do nothing'
1847 )
1848 {
1849 if (notInThisObject)
1850 {
1851 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
1852 if (actualContainer && actualContainer != GetFocusObject() && actualContainer->AcceptsFocus())
1853 {
1854 SetFocusObject(actualContainer, false /* don't set caret position yet */);
1855
1856 container = actualContainer;
1857 }
1858 }
1859
1860 bool caretLineStart = true;
1861 long caretPosition = FindCaretPositionForCharacterPosition(newPos, hitTest, container, caretLineStart);
1862 long newSelEnd = caretPosition;
1863 bool extendSel;
1864
1865 if (notInThisObject)
1866 extendSel = false;
1867 else
1868 extendSel = ExtendSelection(m_caretPosition, newSelEnd, flags);
1869
1870 if (!extendSel)
1871 SelectNone();
1872
1873 SetCaretPosition(caretPosition, caretLineStart);
1874 PositionCaret();
1875 SetDefaultStyleToCursorStyle();
1876
1877 return true;
1878 }
1879
1880 return false;
1881 }
1882
1883 /// Move to the end of the paragraph
1884 bool wxRichTextCtrl::MoveToParagraphEnd(int flags)
1885 {
1886 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(m_caretPosition, true);
1887 if (para)
1888 {
1889 long newPos = para->GetRange().GetEnd() - 1;
1890 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1891 if (!extendSel)
1892 SelectNone();
1893
1894 SetCaretPosition(newPos);
1895 PositionCaret();
1896 SetDefaultStyleToCursorStyle();
1897
1898 return true;
1899 }
1900
1901 return false;
1902 }
1903
1904 /// Move to the start of the paragraph
1905 bool wxRichTextCtrl::MoveToParagraphStart(int flags)
1906 {
1907 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(m_caretPosition, true);
1908 if (para)
1909 {
1910 long newPos = para->GetRange().GetStart() - 1;
1911 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1912 if (!extendSel)
1913 SelectNone();
1914
1915 SetCaretPosition(newPos);
1916 PositionCaret();
1917 SetDefaultStyleToCursorStyle();
1918
1919 return true;
1920 }
1921
1922 return false;
1923 }
1924
1925 /// Move to the end of the line
1926 bool wxRichTextCtrl::MoveToLineEnd(int flags)
1927 {
1928 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1929
1930 if (line)
1931 {
1932 wxRichTextRange lineRange = line->GetAbsoluteRange();
1933 long newPos = lineRange.GetEnd();
1934 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1935 if (!extendSel)
1936 SelectNone();
1937
1938 SetCaretPosition(newPos);
1939 PositionCaret();
1940 SetDefaultStyleToCursorStyle();
1941
1942 return true;
1943 }
1944
1945 return false;
1946 }
1947
1948 /// Move to the start of the line
1949 bool wxRichTextCtrl::MoveToLineStart(int flags)
1950 {
1951 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
1952 if (line)
1953 {
1954 wxRichTextRange lineRange = line->GetAbsoluteRange();
1955 long newPos = lineRange.GetStart()-1;
1956
1957 bool extendSel = ExtendSelection(m_caretPosition, newPos, flags);
1958 if (!extendSel)
1959 SelectNone();
1960
1961 wxRichTextParagraph* para = GetFocusObject()->GetParagraphForLine(line);
1962
1963 SetCaretPosition(newPos, para->GetRange().GetStart() != lineRange.GetStart());
1964 PositionCaret();
1965 SetDefaultStyleToCursorStyle();
1966
1967 return true;
1968 }
1969
1970 return false;
1971 }
1972
1973 /// Move to the start of the buffer
1974 bool wxRichTextCtrl::MoveHome(int flags)
1975 {
1976 if (m_caretPosition != -1)
1977 {
1978 bool extendSel = ExtendSelection(m_caretPosition, -1, flags);
1979 if (!extendSel)
1980 SelectNone();
1981
1982 SetCaretPosition(-1);
1983 PositionCaret();
1984 SetDefaultStyleToCursorStyle();
1985
1986 return true;
1987 }
1988 else
1989 return false;
1990 }
1991
1992 /// Move to the end of the buffer
1993 bool wxRichTextCtrl::MoveEnd(int flags)
1994 {
1995 long endPos = GetFocusObject()->GetOwnRange().GetEnd()-1;
1996
1997 if (m_caretPosition != endPos)
1998 {
1999 bool extendSel = ExtendSelection(m_caretPosition, endPos, flags);
2000 if (!extendSel)
2001 SelectNone();
2002
2003 SetCaretPosition(endPos);
2004 PositionCaret();
2005 SetDefaultStyleToCursorStyle();
2006
2007 return true;
2008 }
2009 else
2010 return false;
2011 }
2012
2013 /// Move noPages pages up
2014 bool wxRichTextCtrl::PageUp(int noPages, int flags)
2015 {
2016 return PageDown(- noPages, flags);
2017 }
2018
2019 /// Move noPages pages down
2020 bool wxRichTextCtrl::PageDown(int noPages, int flags)
2021 {
2022 // Calculate which line occurs noPages * screen height further down.
2023 wxRichTextLine* line = GetVisibleLineForCaretPosition(m_caretPosition);
2024 if (line)
2025 {
2026 wxSize clientSize = GetClientSize();
2027 int newY = line->GetAbsolutePosition().y + noPages*clientSize.y;
2028
2029 wxRichTextLine* newLine = GetFocusObject()->GetLineAtYPosition(newY);
2030 if (newLine)
2031 {
2032 wxRichTextRange lineRange = newLine->GetAbsoluteRange();
2033 long pos = lineRange.GetStart()-1;
2034 if (pos != m_caretPosition)
2035 {
2036 wxRichTextParagraph* para = GetFocusObject()->GetParagraphForLine(newLine);
2037
2038 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2039 if (!extendSel)
2040 SelectNone();
2041
2042 SetCaretPosition(pos, para->GetRange().GetStart() != lineRange.GetStart());
2043 PositionCaret();
2044 SetDefaultStyleToCursorStyle();
2045
2046 return true;
2047 }
2048 }
2049 }
2050
2051 return false;
2052 }
2053
2054 static bool wxRichTextCtrlIsWhitespace(const wxString& str)
2055 {
2056 return str == wxT(" ") || str == wxT("\t");
2057 }
2058
2059 // Finds the caret position for the next word
2060 long wxRichTextCtrl::FindNextWordPosition(int direction) const
2061 {
2062 long endPos = GetFocusObject()->GetOwnRange().GetEnd();
2063
2064 if (direction > 0)
2065 {
2066 long i = m_caretPosition+1+direction; // +1 for conversion to character pos
2067
2068 // First skip current text to space
2069 while (i < endPos && i > -1)
2070 {
2071 // i is in character, not caret positions
2072 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2073 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
2074 if (line && (i == line->GetAbsoluteRange().GetEnd()))
2075 {
2076 break;
2077 }
2078 else if (!wxRichTextCtrlIsWhitespace(text) && !text.empty())
2079 i += direction;
2080 else
2081 {
2082 break;
2083 }
2084 }
2085 while (i < endPos && i > -1)
2086 {
2087 // i is in character, not caret positions
2088 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2089 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
2090 if (line && (i == line->GetAbsoluteRange().GetEnd()))
2091 return wxMax(-1, i);
2092
2093 if (text.empty()) // End of paragraph, or maybe an image
2094 return wxMax(-1, i - 1);
2095 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
2096 i += direction;
2097 else
2098 {
2099 // Convert to caret position
2100 return wxMax(-1, i - 1);
2101 }
2102 }
2103 if (i >= endPos)
2104 return endPos-1;
2105 return i-1;
2106 }
2107 else
2108 {
2109 long i = m_caretPosition;
2110
2111 // First skip white space
2112 while (i < endPos && i > -1)
2113 {
2114 // i is in character, not caret positions
2115 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2116 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
2117
2118 if (text.empty() || (line && (i == line->GetAbsoluteRange().GetStart()))) // End of paragraph, or maybe an image
2119 break;
2120 else if (wxRichTextCtrlIsWhitespace(text) || text.empty())
2121 i += direction;
2122 else
2123 break;
2124 }
2125 // Next skip current text to space
2126 while (i < endPos && i > -1)
2127 {
2128 // i is in character, not caret positions
2129 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(i, i));
2130 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(i, false);
2131 if (line && line->GetAbsoluteRange().GetStart() == i)
2132 return i-1;
2133
2134 if (!wxRichTextCtrlIsWhitespace(text) /* && !text.empty() */)
2135 i += direction;
2136 else
2137 {
2138 return i;
2139 }
2140 }
2141 if (i < -1)
2142 return -1;
2143 return i;
2144 }
2145 }
2146
2147 /// Move n words left
2148 bool wxRichTextCtrl::WordLeft(int WXUNUSED(n), int flags)
2149 {
2150 long pos = FindNextWordPosition(-1);
2151 if (pos != m_caretPosition)
2152 {
2153 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos, true);
2154
2155 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2156 if (!extendSel)
2157 SelectNone();
2158
2159 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
2160 PositionCaret();
2161 SetDefaultStyleToCursorStyle();
2162
2163 return true;
2164 }
2165
2166 return false;
2167 }
2168
2169 /// Move n words right
2170 bool wxRichTextCtrl::WordRight(int WXUNUSED(n), int flags)
2171 {
2172 long pos = FindNextWordPosition(1);
2173 if (pos != m_caretPosition)
2174 {
2175 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos, true);
2176
2177 bool extendSel = ExtendSelection(m_caretPosition, pos, flags);
2178 if (!extendSel)
2179 SelectNone();
2180
2181 SetCaretPosition(pos, para->GetRange().GetStart() != pos);
2182 PositionCaret();
2183 SetDefaultStyleToCursorStyle();
2184
2185 return true;
2186 }
2187
2188 return false;
2189 }
2190
2191 /// Sizing
2192 void wxRichTextCtrl::OnSize(wxSizeEvent& event)
2193 {
2194 // Only do sizing optimization for large buffers
2195 if (GetBuffer().GetOwnRange().GetEnd() > m_delayedLayoutThreshold)
2196 {
2197 m_fullLayoutRequired = true;
2198 m_fullLayoutTime = wxGetLocalTimeMillis();
2199 m_fullLayoutSavedPosition = GetFirstVisiblePosition();
2200 LayoutContent(true /* onlyVisibleRect */);
2201 }
2202 else
2203 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2204
2205 #if wxRICHTEXT_BUFFERED_PAINTING
2206 RecreateBuffer();
2207 #endif
2208
2209 event.Skip();
2210 }
2211
2212 // Force any pending layout due to large buffer
2213 void wxRichTextCtrl::ForceDelayedLayout()
2214 {
2215 if (m_fullLayoutRequired)
2216 {
2217 m_fullLayoutRequired = false;
2218 m_fullLayoutTime = 0;
2219 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2220 ShowPosition(m_fullLayoutSavedPosition);
2221 Refresh(false);
2222 Update();
2223 }
2224 }
2225
2226 /// Idle-time processing
2227 void wxRichTextCtrl::OnIdle(wxIdleEvent& event)
2228 {
2229 #if wxRICHTEXT_USE_OWN_CARET
2230 if (((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
2231 {
2232 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate(false);
2233 PositionCaret();
2234 GetCaret()->Show();
2235 }
2236 #endif
2237
2238 const int layoutInterval = wxRICHTEXT_DEFAULT_LAYOUT_INTERVAL;
2239
2240 if (m_fullLayoutRequired && (wxGetLocalTimeMillis() > (m_fullLayoutTime + layoutInterval)))
2241 {
2242 m_fullLayoutRequired = false;
2243 m_fullLayoutTime = 0;
2244 GetBuffer().Invalidate(wxRICHTEXT_ALL);
2245 ShowPosition(m_fullLayoutSavedPosition);
2246 Refresh(false);
2247 }
2248
2249 if (m_caretPositionForDefaultStyle != -2)
2250 {
2251 // If the caret position has changed, no longer reflect the default style
2252 // in the UI.
2253 if (GetCaretPosition() != m_caretPositionForDefaultStyle)
2254 m_caretPositionForDefaultStyle = -2;
2255 }
2256
2257 event.Skip();
2258 }
2259
2260 /// Scrolling
2261 void wxRichTextCtrl::OnScroll(wxScrollWinEvent& event)
2262 {
2263 #if wxRICHTEXT_USE_OWN_CARET
2264 if (!((wxRichTextCaret*) GetCaret())->GetNeedsUpdate())
2265 {
2266 GetCaret()->Hide();
2267 ((wxRichTextCaret*) GetCaret())->SetNeedsUpdate();
2268 }
2269 #endif
2270
2271 event.Skip();
2272 }
2273
2274 /// Set up scrollbars, e.g. after a resize
2275 void wxRichTextCtrl::SetupScrollbars(bool atTop)
2276 {
2277 if (IsFrozen())
2278 return;
2279
2280 if (GetBuffer().IsEmpty())
2281 {
2282 SetScrollbars(0, 0, 0, 0, 0, 0);
2283 return;
2284 }
2285
2286 // TODO: reimplement scrolling so we scroll by line, not by fixed number
2287 // of pixels. See e.g. wxVScrolledWindow for ideas.
2288 int pixelsPerUnit = 5;
2289 wxSize clientSize = GetClientSize();
2290
2291 int maxHeight = GetBuffer().GetCachedSize().y + GetBuffer().GetTopMargin();
2292
2293 // Round up so we have at least maxHeight pixels
2294 int unitsY = (int) (((float)maxHeight/(float)pixelsPerUnit) + 0.5);
2295
2296 int startX = 0, startY = 0;
2297 if (!atTop)
2298 GetViewStart(& startX, & startY);
2299
2300 int maxPositionX = 0;
2301 int maxPositionY = (int) ((((float)(wxMax((unitsY*pixelsPerUnit) - clientSize.y, 0)))/((float)pixelsPerUnit)) + 0.5);
2302
2303 int newStartX = wxMin(maxPositionX, startX);
2304 int newStartY = wxMin(maxPositionY, startY);
2305
2306 int oldPPUX, oldPPUY;
2307 int oldStartX, oldStartY;
2308 int oldVirtualSizeX = 0, oldVirtualSizeY = 0;
2309 GetScrollPixelsPerUnit(& oldPPUX, & oldPPUY);
2310 GetViewStart(& oldStartX, & oldStartY);
2311 GetVirtualSize(& oldVirtualSizeX, & oldVirtualSizeY);
2312 if (oldPPUY > 0)
2313 oldVirtualSizeY /= oldPPUY;
2314
2315 if (oldPPUX == 0 && oldPPUY == pixelsPerUnit && oldVirtualSizeY == unitsY && oldStartX == newStartX && oldStartY == newStartY)
2316 return;
2317
2318 // Don't set scrollbars if there were none before, and there will be none now.
2319 if (oldPPUY != 0 && (oldVirtualSizeY*oldPPUY < clientSize.y) && (unitsY*pixelsPerUnit < clientSize.y))
2320 return;
2321
2322 // Move to previous scroll position if
2323 // possible
2324 SetScrollbars(0, pixelsPerUnit, 0, unitsY, newStartX, newStartY);
2325 }
2326
2327 /// Paint the background
2328 void wxRichTextCtrl::PaintBackground(wxDC& dc)
2329 {
2330 wxColour backgroundColour = GetBackgroundColour();
2331 if (!backgroundColour.IsOk())
2332 backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
2333
2334 // Clear the background
2335 dc.SetBrush(wxBrush(backgroundColour));
2336 dc.SetPen(*wxTRANSPARENT_PEN);
2337 wxRect windowRect(GetClientSize());
2338 windowRect.x -= 2; windowRect.y -= 2;
2339 windowRect.width += 4; windowRect.height += 4;
2340
2341 // We need to shift the rectangle to take into account
2342 // scrolling. Converting device to logical coordinates.
2343 CalcUnscrolledPosition(windowRect.x, windowRect.y, & windowRect.x, & windowRect.y);
2344 dc.DrawRectangle(windowRect);
2345 }
2346
2347 #if wxRICHTEXT_BUFFERED_PAINTING
2348 /// Recreate buffer bitmap if necessary
2349 bool wxRichTextCtrl::RecreateBuffer(const wxSize& size)
2350 {
2351 wxSize sz = size;
2352 if (sz == wxDefaultSize)
2353 sz = GetClientSize();
2354
2355 if (sz.x < 1 || sz.y < 1)
2356 return false;
2357
2358 if (!m_bufferBitmap.IsOk() || m_bufferBitmap.GetWidth() < sz.x || m_bufferBitmap.GetHeight() < sz.y)
2359 m_bufferBitmap = wxBitmap(sz.x, sz.y);
2360 return m_bufferBitmap.IsOk();
2361 }
2362 #endif
2363
2364 // ----------------------------------------------------------------------------
2365 // file IO functions
2366 // ----------------------------------------------------------------------------
2367
2368 bool wxRichTextCtrl::DoLoadFile(const wxString& filename, int fileType)
2369 {
2370 bool success = GetBuffer().LoadFile(filename, (wxRichTextFileType)fileType);
2371 if (success)
2372 m_filename = filename;
2373
2374 DiscardEdits();
2375 SetInsertionPoint(0);
2376 LayoutContent();
2377 PositionCaret();
2378 SetupScrollbars(true);
2379 Refresh(false);
2380 wxTextCtrl::SendTextUpdatedEvent(this);
2381
2382 if (success)
2383 return true;
2384 else
2385 {
2386 wxLogError(_("File couldn't be loaded."));
2387
2388 return false;
2389 }
2390 }
2391
2392 bool wxRichTextCtrl::DoSaveFile(const wxString& filename, int fileType)
2393 {
2394 if (GetBuffer().SaveFile(filename, (wxRichTextFileType)fileType))
2395 {
2396 m_filename = filename;
2397
2398 DiscardEdits();
2399
2400 return true;
2401 }
2402
2403 wxLogError(_("The text couldn't be saved."));
2404
2405 return false;
2406 }
2407
2408 // ----------------------------------------------------------------------------
2409 // wxRichTextCtrl specific functionality
2410 // ----------------------------------------------------------------------------
2411
2412 /// Add a new paragraph of text to the end of the buffer
2413 wxRichTextRange wxRichTextCtrl::AddParagraph(const wxString& text)
2414 {
2415 wxRichTextRange range = GetFocusObject()->AddParagraph(text);
2416 GetBuffer().Invalidate();
2417 LayoutContent();
2418 return range;
2419 }
2420
2421 /// Add an image
2422 wxRichTextRange wxRichTextCtrl::AddImage(const wxImage& image)
2423 {
2424 wxRichTextRange range = GetFocusObject()->AddImage(image);
2425 GetBuffer().Invalidate();
2426 LayoutContent();
2427 return range;
2428 }
2429
2430 // ----------------------------------------------------------------------------
2431 // selection and ranges
2432 // ----------------------------------------------------------------------------
2433
2434 void wxRichTextCtrl::SelectAll()
2435 {
2436 SetSelection(-1, -1);
2437 }
2438
2439 /// Select none
2440 void wxRichTextCtrl::SelectNone()
2441 {
2442 if (m_selection.IsValid())
2443 {
2444 wxRichTextSelection oldSelection = m_selection;
2445
2446 m_selection.Reset();
2447
2448 RefreshForSelectionChange(oldSelection, m_selection);
2449 }
2450 m_selectionAnchor = -2;
2451 m_selectionAnchorObject = NULL;
2452 m_selectionState = wxRichTextCtrlSelectionState_Normal;
2453 }
2454
2455 static bool wxIsWordDelimiter(const wxString& text)
2456 {
2457 return !text.IsEmpty() && !wxIsalnum(text[0]);
2458 }
2459
2460 /// Select the word at the given character position
2461 bool wxRichTextCtrl::SelectWord(long position)
2462 {
2463 if (position < 0 || position > GetFocusObject()->GetOwnRange().GetEnd())
2464 return false;
2465
2466 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(position);
2467 if (!para)
2468 return false;
2469
2470 if (position == para->GetRange().GetEnd())
2471 position --;
2472
2473 long positionStart = position;
2474 long positionEnd = position;
2475
2476 for (positionStart = position; positionStart >= para->GetRange().GetStart(); positionStart --)
2477 {
2478 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(positionStart, positionStart));
2479 if (wxIsWordDelimiter(text))
2480 {
2481 positionStart ++;
2482 break;
2483 }
2484 }
2485 if (positionStart < para->GetRange().GetStart())
2486 positionStart = para->GetRange().GetStart();
2487
2488 for (positionEnd = position; positionEnd < para->GetRange().GetEnd(); positionEnd ++)
2489 {
2490 wxString text = GetFocusObject()->GetTextForRange(wxRichTextRange(positionEnd, positionEnd));
2491 if (wxIsWordDelimiter(text))
2492 {
2493 positionEnd --;
2494 break;
2495 }
2496 }
2497 if (positionEnd >= para->GetRange().GetEnd())
2498 positionEnd = para->GetRange().GetEnd();
2499
2500 if (positionEnd < positionStart)
2501 return false;
2502
2503 SetSelection(positionStart, positionEnd+1);
2504
2505 if (positionStart >= 0)
2506 {
2507 MoveCaret(positionStart-1, true);
2508 SetDefaultStyleToCursorStyle();
2509 }
2510
2511 return true;
2512 }
2513
2514 wxString wxRichTextCtrl::GetStringSelection() const
2515 {
2516 long from, to;
2517 GetSelection(&from, &to);
2518
2519 return GetRange(from, to);
2520 }
2521
2522 // ----------------------------------------------------------------------------
2523 // hit testing
2524 // ----------------------------------------------------------------------------
2525
2526 wxTextCtrlHitTestResult
2527 wxRichTextCtrl::HitTest(const wxPoint& pt, wxTextCoord *x, wxTextCoord *y) const
2528 {
2529 // implement in terms of the other overload as the native ports typically
2530 // can get the position and not (x, y) pair directly (although wxUniv
2531 // directly gets x and y -- and so overrides this method as well)
2532 long pos;
2533 wxTextCtrlHitTestResult rc = HitTest(pt, &pos);
2534
2535 if ( rc != wxTE_HT_UNKNOWN )
2536 {
2537 PositionToXY(pos, x, y);
2538 }
2539
2540 return rc;
2541 }
2542
2543 wxTextCtrlHitTestResult
2544 wxRichTextCtrl::HitTest(const wxPoint& pt,
2545 long * pos) const
2546 {
2547 wxClientDC dc((wxRichTextCtrl*) this);
2548 ((wxRichTextCtrl*)this)->PrepareDC(dc);
2549
2550 // Buffer uses logical position (relative to start of buffer)
2551 // so convert
2552 wxPoint pt2 = GetLogicalPoint(pt);
2553
2554 wxRichTextObject* hitObj = NULL;
2555 wxRichTextObject* contextObj = NULL;
2556 int hit = ((wxRichTextCtrl*)this)->GetFocusObject()->HitTest(dc, pt2, *pos, & hitObj, & contextObj, wxRICHTEXT_HITTEST_NO_NESTED_OBJECTS);
2557
2558 if ((hit & wxRICHTEXT_HITTEST_BEFORE) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2559 return wxTE_HT_BEFORE;
2560 else if ((hit & wxRICHTEXT_HITTEST_AFTER) && (hit & wxRICHTEXT_HITTEST_OUTSIDE))
2561 return wxTE_HT_BEYOND;
2562 else if (hit & (wxRICHTEXT_HITTEST_BEFORE|wxRICHTEXT_HITTEST_AFTER))
2563 return wxTE_HT_ON_TEXT;
2564
2565 return wxTE_HT_UNKNOWN;
2566 }
2567
2568 // ----------------------------------------------------------------------------
2569 // set/get the controls text
2570 // ----------------------------------------------------------------------------
2571
2572 wxString wxRichTextCtrl::DoGetValue() const
2573 {
2574 return GetBuffer().GetText();
2575 }
2576
2577 wxString wxRichTextCtrl::GetRange(long from, long to) const
2578 {
2579 // Public API for range is different from internals
2580 return GetFocusObject()->GetTextForRange(wxRichTextRange(from, to-1));
2581 }
2582
2583 void wxRichTextCtrl::DoSetValue(const wxString& value, int flags)
2584 {
2585 // Don't call Clear here, since it always sends a text updated event
2586 m_buffer.ResetAndClearCommands();
2587 m_buffer.Invalidate(wxRICHTEXT_ALL);
2588 m_caretPosition = -1;
2589 m_caretPositionForDefaultStyle = -2;
2590 m_caretAtLineStart = false;
2591 m_selection.Reset();
2592 m_selectionState = wxRichTextCtrlSelectionState_Normal;
2593
2594 Scroll(0,0);
2595
2596 if (!IsFrozen())
2597 {
2598 LayoutContent();
2599 Refresh(false);
2600 }
2601
2602 if (!value.IsEmpty())
2603 {
2604 // Remove empty paragraph
2605 GetBuffer().Clear();
2606 DoWriteText(value, flags);
2607
2608 // for compatibility, don't move the cursor when doing SetValue()
2609 SetInsertionPoint(0);
2610 }
2611 else
2612 {
2613 // still send an event for consistency
2614 if (flags & SetValue_SendEvent)
2615 wxTextCtrl::SendTextUpdatedEvent(this);
2616 }
2617 DiscardEdits();
2618 }
2619
2620 void wxRichTextCtrl::WriteText(const wxString& value)
2621 {
2622 DoWriteText(value);
2623 }
2624
2625 void wxRichTextCtrl::DoWriteText(const wxString& value, int flags)
2626 {
2627 wxString valueUnix = wxTextFile::Translate(value, wxTextFileType_Unix);
2628
2629 GetFocusObject()->InsertTextWithUndo(m_caretPosition+1, valueUnix, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
2630
2631 if ( flags & SetValue_SendEvent )
2632 wxTextCtrl::SendTextUpdatedEvent(this);
2633 }
2634
2635 void wxRichTextCtrl::AppendText(const wxString& text)
2636 {
2637 SetInsertionPointEnd();
2638
2639 WriteText(text);
2640 }
2641
2642 /// Write an image at the current insertion point
2643 bool wxRichTextCtrl::WriteImage(const wxImage& image, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
2644 {
2645 wxRichTextImageBlock imageBlock;
2646
2647 wxImage image2 = image;
2648 if (imageBlock.MakeImageBlock(image2, bitmapType))
2649 return WriteImage(imageBlock, textAttr);
2650
2651 return false;
2652 }
2653
2654 bool wxRichTextCtrl::WriteImage(const wxString& filename, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
2655 {
2656 wxRichTextImageBlock imageBlock;
2657
2658 wxImage image;
2659 if (imageBlock.MakeImageBlock(filename, bitmapType, image, false))
2660 return WriteImage(imageBlock, textAttr);
2661
2662 return false;
2663 }
2664
2665 bool wxRichTextCtrl::WriteImage(const wxRichTextImageBlock& imageBlock, const wxRichTextAttr& textAttr)
2666 {
2667 return GetFocusObject()->InsertImageWithUndo(m_caretPosition+1, imageBlock, this, & GetBuffer(), 0, textAttr);
2668 }
2669
2670 bool wxRichTextCtrl::WriteImage(const wxBitmap& bitmap, wxBitmapType bitmapType, const wxRichTextAttr& textAttr)
2671 {
2672 if (bitmap.IsOk())
2673 {
2674 wxRichTextImageBlock imageBlock;
2675
2676 wxImage image = bitmap.ConvertToImage();
2677 if (image.IsOk() && imageBlock.MakeImageBlock(image, bitmapType))
2678 return WriteImage(imageBlock, textAttr);
2679 }
2680
2681 return false;
2682 }
2683
2684 // Write a text box at the current insertion point.
2685 wxRichTextBox* wxRichTextCtrl::WriteTextBox(const wxRichTextAttr& textAttr)
2686 {
2687 wxRichTextBox* textBox = new wxRichTextBox;
2688 textBox->SetAttributes(textAttr);
2689 textBox->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
2690 textBox->AddParagraph(wxEmptyString);
2691 textBox->SetParent(NULL);
2692
2693 // The object returned is the one actually inserted into the buffer,
2694 // while the original one is deleted.
2695 wxRichTextObject* obj = GetFocusObject()->InsertObjectWithUndo(m_caretPosition+1, textBox, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
2696 wxRichTextBox* box = wxDynamicCast(obj, wxRichTextBox);
2697 return box;
2698 }
2699
2700 // Write a table at the current insertion point, returning the table.
2701 wxRichTextTable* wxRichTextCtrl::WriteTable(int rows, int cols, const wxRichTextAttr& tableAttr, const wxRichTextAttr& cellAttr)
2702 {
2703 wxASSERT(rows > 0 && cols > 0);
2704
2705 if (rows <= 0 || cols <= 0)
2706 return NULL;
2707
2708 wxRichTextTable* table = new wxRichTextTable;
2709 table->SetAttributes(tableAttr);
2710 table->SetParent(& GetBuffer()); // set parent temporarily for AddParagraph to use correct style
2711
2712 table->CreateTable(rows, cols);
2713
2714 table->SetParent(NULL);
2715
2716 int i, j;
2717 for (j = 0; j < rows; j++)
2718 {
2719 for (i = 0; i < cols; i++)
2720 {
2721 table->GetCell(j, i)->GetAttributes() = cellAttr;
2722 }
2723 }
2724
2725 // The object returned is the one actually inserted into the buffer,
2726 // while the original one is deleted.
2727 wxRichTextObject* obj = GetFocusObject()->InsertObjectWithUndo(m_caretPosition+1, table, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
2728 wxRichTextTable* tableResult = wxDynamicCast(obj, wxRichTextTable);
2729 return tableResult;
2730 }
2731
2732
2733 /// Insert a newline (actually paragraph) at the current insertion point.
2734 bool wxRichTextCtrl::Newline()
2735 {
2736 return GetFocusObject()->InsertNewlineWithUndo(m_caretPosition+1, this, & GetBuffer(), wxRICHTEXT_INSERT_WITH_PREVIOUS_PARAGRAPH_STYLE);
2737 }
2738
2739 /// Insert a line break at the current insertion point.
2740 bool wxRichTextCtrl::LineBreak()
2741 {
2742 wxString text;
2743 text = wxRichTextLineBreakChar;
2744 return GetFocusObject()->InsertTextWithUndo(m_caretPosition+1, text, this, & GetBuffer());
2745 }
2746
2747 // ----------------------------------------------------------------------------
2748 // Clipboard operations
2749 // ----------------------------------------------------------------------------
2750
2751 void wxRichTextCtrl::Copy()
2752 {
2753 if (CanCopy())
2754 {
2755 wxRichTextRange range = GetInternalSelectionRange();
2756 GetBuffer().CopyToClipboard(range);
2757 }
2758 }
2759
2760 void wxRichTextCtrl::Cut()
2761 {
2762 if (CanCut())
2763 {
2764 wxRichTextRange range = GetInternalSelectionRange();
2765 GetBuffer().CopyToClipboard(range);
2766
2767 DeleteSelectedContent();
2768 LayoutContent();
2769 Refresh(false);
2770 }
2771 }
2772
2773 void wxRichTextCtrl::Paste()
2774 {
2775 if (CanPaste())
2776 {
2777 BeginBatchUndo(_("Paste"));
2778
2779 long newPos = m_caretPosition;
2780 DeleteSelectedContent(& newPos);
2781
2782 GetBuffer().PasteFromClipboard(newPos);
2783
2784 EndBatchUndo();
2785 }
2786 }
2787
2788 void wxRichTextCtrl::DeleteSelection()
2789 {
2790 if (CanDeleteSelection())
2791 {
2792 DeleteSelectedContent();
2793 }
2794 }
2795
2796 bool wxRichTextCtrl::HasSelection() const
2797 {
2798 return (m_selection.IsValid() && m_selection.GetContainer() == GetFocusObject());
2799 }
2800
2801 bool wxRichTextCtrl::HasUnfocusedSelection() const
2802 {
2803 return m_selection.IsValid();
2804 }
2805
2806 bool wxRichTextCtrl::CanCopy() const
2807 {
2808 // Can copy if there's a selection
2809 return HasSelection();
2810 }
2811
2812 bool wxRichTextCtrl::CanCut() const
2813 {
2814 return HasSelection() && IsEditable();
2815 }
2816
2817 bool wxRichTextCtrl::CanPaste() const
2818 {
2819 if ( !IsEditable() )
2820 return false;
2821
2822 return GetBuffer().CanPasteFromClipboard();
2823 }
2824
2825 bool wxRichTextCtrl::CanDeleteSelection() const
2826 {
2827 return HasSelection() && IsEditable();
2828 }
2829
2830
2831 // ----------------------------------------------------------------------------
2832 // Accessors
2833 // ----------------------------------------------------------------------------
2834
2835 void wxRichTextCtrl::SetContextMenu(wxMenu* menu)
2836 {
2837 if (m_contextMenu && m_contextMenu != menu)
2838 delete m_contextMenu;
2839 m_contextMenu = menu;
2840 }
2841
2842 void wxRichTextCtrl::SetEditable(bool editable)
2843 {
2844 m_editable = editable;
2845 }
2846
2847 void wxRichTextCtrl::SetInsertionPoint(long pos)
2848 {
2849 SelectNone();
2850
2851 m_caretPosition = pos - 1;
2852
2853 PositionCaret();
2854
2855 SetDefaultStyleToCursorStyle();
2856 }
2857
2858 void wxRichTextCtrl::SetInsertionPointEnd()
2859 {
2860 long pos = GetLastPosition();
2861 SetInsertionPoint(pos);
2862 }
2863
2864 long wxRichTextCtrl::GetInsertionPoint() const
2865 {
2866 return m_caretPosition+1;
2867 }
2868
2869 wxTextPos wxRichTextCtrl::GetLastPosition() const
2870 {
2871 return GetFocusObject()->GetOwnRange().GetEnd();
2872 }
2873
2874 // If the return values from and to are the same, there is no
2875 // selection.
2876 void wxRichTextCtrl::GetSelection(long* from, long* to) const
2877 {
2878 if (m_selection.IsValid())
2879 {
2880 *from = m_selection.GetRange().GetStart();
2881 *to = m_selection.GetRange().GetEnd();
2882 (*to) ++;
2883 }
2884 else
2885 {
2886 *from = -2;
2887 *to = -2;
2888 }
2889 }
2890
2891 bool wxRichTextCtrl::IsEditable() const
2892 {
2893 return m_editable;
2894 }
2895
2896 // ----------------------------------------------------------------------------
2897 // selection
2898 // ----------------------------------------------------------------------------
2899
2900 void wxRichTextCtrl::SetSelection(long from, long to)
2901 {
2902 // if from and to are both -1, it means (in wxWidgets) that all text should
2903 // be selected.
2904 if ( (from == -1) && (to == -1) )
2905 {
2906 from = 0;
2907 to = GetLastPosition()+1;
2908 }
2909
2910 if (from == to)
2911 {
2912 SelectNone();
2913 }
2914 else
2915 {
2916 wxRichTextSelection oldSelection = m_selection;
2917
2918 m_selectionAnchor = from-1;
2919 m_selectionAnchorObject = NULL;
2920 m_selection.Set(wxRichTextRange(from, to-1), GetFocusObject());
2921
2922 m_caretPosition = wxMax(-1, to-1);
2923
2924 RefreshForSelectionChange(oldSelection, m_selection);
2925 PositionCaret();
2926 }
2927 }
2928
2929 // ----------------------------------------------------------------------------
2930 // Editing
2931 // ----------------------------------------------------------------------------
2932
2933 void wxRichTextCtrl::Replace(long WXUNUSED(from), long WXUNUSED(to),
2934 const wxString& value)
2935 {
2936 BeginBatchUndo(_("Replace"));
2937
2938 DeleteSelectedContent();
2939
2940 DoWriteText(value, SetValue_SelectionOnly);
2941
2942 EndBatchUndo();
2943 }
2944
2945 void wxRichTextCtrl::Remove(long from, long to)
2946 {
2947 SelectNone();
2948
2949 GetFocusObject()->DeleteRangeWithUndo(wxRichTextRange(from, to-1), this, & GetBuffer());
2950
2951 LayoutContent();
2952 if (!IsFrozen())
2953 Refresh(false);
2954 }
2955
2956 bool wxRichTextCtrl::IsModified() const
2957 {
2958 return m_buffer.IsModified();
2959 }
2960
2961 void wxRichTextCtrl::MarkDirty()
2962 {
2963 m_buffer.Modify(true);
2964 }
2965
2966 void wxRichTextCtrl::DiscardEdits()
2967 {
2968 m_caretPositionForDefaultStyle = -2;
2969 m_buffer.Modify(false);
2970 m_buffer.GetCommandProcessor()->ClearCommands();
2971 }
2972
2973 int wxRichTextCtrl::GetNumberOfLines() const
2974 {
2975 return GetFocusObject()->GetParagraphCount();
2976 }
2977
2978 // ----------------------------------------------------------------------------
2979 // Positions <-> coords
2980 // ----------------------------------------------------------------------------
2981
2982 long wxRichTextCtrl::XYToPosition(long x, long y) const
2983 {
2984 return GetFocusObject()->XYToPosition(x, y);
2985 }
2986
2987 bool wxRichTextCtrl::PositionToXY(long pos, long *x, long *y) const
2988 {
2989 return GetFocusObject()->PositionToXY(pos, x, y);
2990 }
2991
2992 // ----------------------------------------------------------------------------
2993 //
2994 // ----------------------------------------------------------------------------
2995
2996 void wxRichTextCtrl::ShowPosition(long pos)
2997 {
2998 if (!IsPositionVisible(pos))
2999 ScrollIntoView(pos-1, WXK_DOWN);
3000 }
3001
3002 int wxRichTextCtrl::GetLineLength(long lineNo) const
3003 {
3004 return GetFocusObject()->GetParagraphLength(lineNo);
3005 }
3006
3007 wxString wxRichTextCtrl::GetLineText(long lineNo) const
3008 {
3009 return GetFocusObject()->GetParagraphText(lineNo);
3010 }
3011
3012 // ----------------------------------------------------------------------------
3013 // Undo/redo
3014 // ----------------------------------------------------------------------------
3015
3016 void wxRichTextCtrl::Undo()
3017 {
3018 if (CanUndo())
3019 {
3020 GetCommandProcessor()->Undo();
3021 }
3022 }
3023
3024 void wxRichTextCtrl::Redo()
3025 {
3026 if (CanRedo())
3027 {
3028 GetCommandProcessor()->Redo();
3029 }
3030 }
3031
3032 bool wxRichTextCtrl::CanUndo() const
3033 {
3034 return GetCommandProcessor()->CanUndo() && IsEditable();
3035 }
3036
3037 bool wxRichTextCtrl::CanRedo() const
3038 {
3039 return GetCommandProcessor()->CanRedo() && IsEditable();
3040 }
3041
3042 // ----------------------------------------------------------------------------
3043 // implementation details
3044 // ----------------------------------------------------------------------------
3045
3046 void wxRichTextCtrl::Command(wxCommandEvent& event)
3047 {
3048 SetValue(event.GetString());
3049 GetEventHandler()->ProcessEvent(event);
3050 }
3051
3052 void wxRichTextCtrl::OnDropFiles(wxDropFilesEvent& event)
3053 {
3054 // By default, load the first file into the text window.
3055 if (event.GetNumberOfFiles() > 0)
3056 {
3057 LoadFile(event.GetFiles()[0]);
3058 }
3059 }
3060
3061 wxSize wxRichTextCtrl::DoGetBestSize() const
3062 {
3063 return wxSize(10, 10);
3064 }
3065
3066 // ----------------------------------------------------------------------------
3067 // standard handlers for standard edit menu events
3068 // ----------------------------------------------------------------------------
3069
3070 void wxRichTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
3071 {
3072 Cut();
3073 }
3074
3075 void wxRichTextCtrl::OnClear(wxCommandEvent& WXUNUSED(event))
3076 {
3077 DeleteSelection();
3078 }
3079
3080 void wxRichTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
3081 {
3082 Copy();
3083 }
3084
3085 void wxRichTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
3086 {
3087 Paste();
3088 }
3089
3090 void wxRichTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
3091 {
3092 Undo();
3093 }
3094
3095 void wxRichTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
3096 {
3097 Redo();
3098 }
3099
3100 void wxRichTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
3101 {
3102 event.Enable( CanCut() );
3103 }
3104
3105 void wxRichTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
3106 {
3107 event.Enable( CanCopy() );
3108 }
3109
3110 void wxRichTextCtrl::OnUpdateClear(wxUpdateUIEvent& event)
3111 {
3112 event.Enable( CanDeleteSelection() );
3113 }
3114
3115 void wxRichTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
3116 {
3117 event.Enable( CanPaste() );
3118 }
3119
3120 void wxRichTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
3121 {
3122 event.Enable( CanUndo() );
3123 event.SetText( GetCommandProcessor()->GetUndoMenuLabel() );
3124 }
3125
3126 void wxRichTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
3127 {
3128 event.Enable( CanRedo() );
3129 event.SetText( GetCommandProcessor()->GetRedoMenuLabel() );
3130 }
3131
3132 void wxRichTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
3133 {
3134 if (GetLastPosition() > 0)
3135 SelectAll();
3136 }
3137
3138 void wxRichTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
3139 {
3140 event.Enable(GetLastPosition() > 0);
3141 }
3142
3143 void wxRichTextCtrl::OnProperties(wxCommandEvent& event)
3144 {
3145 int idx = event.GetId() - wxID_RICHTEXT_PROPERTIES1;
3146 if (idx >= 0 && idx < m_contextMenuPropertiesInfo.GetCount())
3147 {
3148 wxRichTextObject* obj = m_contextMenuPropertiesInfo.GetObject(idx);
3149 if (obj && obj->CanEditProperties())
3150 obj->EditProperties(this, & GetBuffer());
3151
3152 m_contextMenuPropertiesInfo.Clear();
3153 }
3154 }
3155
3156 void wxRichTextCtrl::OnUpdateProperties(wxUpdateUIEvent& event)
3157 {
3158 int idx = event.GetId() - wxID_RICHTEXT_PROPERTIES1;
3159 event.Enable(idx >= 0 && idx < m_contextMenuPropertiesInfo.GetCount());
3160 }
3161
3162 void wxRichTextCtrl::OnContextMenu(wxContextMenuEvent& event)
3163 {
3164 if (event.GetEventObject() != this)
3165 {
3166 event.Skip();
3167 return;
3168 }
3169
3170 wxClientDC dc(this);
3171 PrepareDC(dc);
3172 dc.SetFont(GetFont());
3173
3174 long position = 0;
3175 wxPoint pt = event.GetPosition();
3176 wxPoint logicalPt = GetLogicalPoint(ScreenToClient(pt));
3177 wxRichTextObject* hitObj = NULL;
3178 wxRichTextObject* contextObj = NULL;
3179 int hit = GetFocusObject()->HitTest(dc, logicalPt, position, & hitObj, & contextObj);
3180
3181 m_contextMenuPropertiesInfo.Clear();
3182
3183 if (hit == wxRICHTEXT_HITTEST_ON || hit == wxRICHTEXT_HITTEST_BEFORE || hit == wxRICHTEXT_HITTEST_AFTER)
3184 {
3185 wxRichTextParagraphLayoutBox* actualContainer = wxDynamicCast(contextObj, wxRichTextParagraphLayoutBox);
3186 if (hitObj && actualContainer)
3187 {
3188 if (actualContainer->AcceptsFocus())
3189 {
3190 SetFocusObject(actualContainer, false /* don't set caret position yet */);
3191 SetCaretPositionAfterClick(actualContainer, position, hit);
3192 }
3193
3194 m_contextMenuPropertiesInfo.AddItems(actualContainer, hitObj);
3195 }
3196 else
3197 m_contextMenuPropertiesInfo.AddItems(GetFocusObject(), NULL);
3198 }
3199 else
3200 {
3201 m_contextMenuPropertiesInfo.AddItems(GetFocusObject(), NULL);
3202 }
3203
3204 if (m_contextMenu)
3205 {
3206 m_contextMenuPropertiesInfo.AddMenuItems(m_contextMenu);
3207 PopupMenu(m_contextMenu);
3208 }
3209 }
3210
3211 bool wxRichTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
3212 {
3213 return GetFocusObject()->SetStyle(wxRichTextRange(start, end-1), wxRichTextAttr(style));
3214 }
3215
3216 bool wxRichTextCtrl::SetStyle(long start, long end, const wxRichTextAttr& style)
3217 {
3218 return GetFocusObject()->SetStyle(wxRichTextRange(start, end-1), style);
3219 }
3220
3221 bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxTextAttr& style)
3222 {
3223 return GetFocusObject()->SetStyle(range.ToInternal(), wxRichTextAttr(style));
3224 }
3225
3226 bool wxRichTextCtrl::SetStyle(const wxRichTextRange& range, const wxRichTextAttr& style)
3227 {
3228 return GetFocusObject()->SetStyle(range.ToInternal(), style);
3229 }
3230
3231 void wxRichTextCtrl::SetStyle(wxRichTextObject *obj, const wxRichTextAttr& textAttr)
3232 {
3233 GetFocusObject()->SetStyle(obj, textAttr);
3234 }
3235
3236 // extended style setting operation with flags including:
3237 // wxRICHTEXT_SETSTYLE_WITH_UNDO, wxRICHTEXT_SETSTYLE_OPTIMIZE, wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY.
3238 // see richtextbuffer.h for more details.
3239
3240 bool wxRichTextCtrl::SetStyleEx(const wxRichTextRange& range, const wxRichTextAttr& style, int flags)
3241 {
3242 return GetFocusObject()->SetStyle(range.ToInternal(), style, flags);
3243 }
3244
3245 bool wxRichTextCtrl::SetDefaultStyle(const wxTextAttr& style)
3246 {
3247 return GetBuffer().SetDefaultStyle(style);
3248 }
3249
3250 bool wxRichTextCtrl::SetDefaultStyle(const wxRichTextAttr& style)
3251 {
3252 wxRichTextAttr attr1(style);
3253 attr1.GetTextBoxAttr().Reset();
3254 return GetBuffer().SetDefaultStyle(attr1);
3255 }
3256
3257 const wxRichTextAttr& wxRichTextCtrl::GetDefaultStyleEx() const
3258 {
3259 return GetBuffer().GetDefaultStyle();
3260 }
3261
3262 bool wxRichTextCtrl::GetStyle(long position, wxTextAttr& style)
3263 {
3264 wxRichTextAttr attr;
3265 if (GetFocusObject()->GetStyle(position, attr))
3266 {
3267 style = attr;
3268 return true;
3269 }
3270 else
3271 return false;
3272 }
3273
3274 bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style)
3275 {
3276 return GetFocusObject()->GetStyle(position, style);
3277 }
3278
3279 bool wxRichTextCtrl::GetStyle(long position, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3280 {
3281 wxRichTextAttr attr;
3282 if (container->GetStyle(position, attr))
3283 {
3284 style = attr;
3285 return true;
3286 }
3287 else
3288 return false;
3289 }
3290
3291 // get the common set of styles for the range
3292 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxTextAttr& style)
3293 {
3294 wxRichTextAttr attr;
3295 if (GetFocusObject()->GetStyleForRange(range.ToInternal(), attr))
3296 {
3297 style = attr;
3298 return true;
3299 }
3300 else
3301 return false;
3302 }
3303
3304 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style)
3305 {
3306 return GetFocusObject()->GetStyleForRange(range.ToInternal(), style);
3307 }
3308
3309 bool wxRichTextCtrl::GetStyleForRange(const wxRichTextRange& range, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3310 {
3311 return container->GetStyleForRange(range.ToInternal(), style);
3312 }
3313
3314 /// Get the content (uncombined) attributes for this position.
3315 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style)
3316 {
3317 return GetFocusObject()->GetUncombinedStyle(position, style);
3318 }
3319
3320 /// Get the content (uncombined) attributes for this position.
3321 bool wxRichTextCtrl::GetUncombinedStyle(long position, wxRichTextAttr& style, wxRichTextParagraphLayoutBox* container)
3322 {
3323 return container->GetUncombinedStyle(position, style);
3324 }
3325
3326 /// Set font, and also the buffer attributes
3327 bool wxRichTextCtrl::SetFont(const wxFont& font)
3328 {
3329 wxControl::SetFont(font);
3330
3331 wxRichTextAttr attr = GetBuffer().GetAttributes();
3332 attr.SetFont(font);
3333 GetBuffer().SetBasicStyle(attr);
3334
3335 GetBuffer().Invalidate(wxRICHTEXT_ALL);
3336 Refresh(false);
3337
3338 return true;
3339 }
3340
3341 /// Transform logical to physical
3342 wxPoint wxRichTextCtrl::GetPhysicalPoint(const wxPoint& ptLogical) const
3343 {
3344 wxPoint pt;
3345 CalcScrolledPosition(ptLogical.x, ptLogical.y, & pt.x, & pt.y);
3346
3347 return pt;
3348 }
3349
3350 /// Transform physical to logical
3351 wxPoint wxRichTextCtrl::GetLogicalPoint(const wxPoint& ptPhysical) const
3352 {
3353 wxPoint pt;
3354 CalcUnscrolledPosition(ptPhysical.x, ptPhysical.y, & pt.x, & pt.y);
3355
3356 return pt;
3357 }
3358
3359 /// Position the caret
3360 void wxRichTextCtrl::PositionCaret(wxRichTextParagraphLayoutBox* container)
3361 {
3362 if (!GetCaret())
3363 return;
3364
3365 //wxLogDebug(wxT("PositionCaret"));
3366
3367 wxRect caretRect;
3368 if (GetCaretPositionForIndex(GetCaretPosition(), caretRect, container))
3369 {
3370 wxPoint newPt = caretRect.GetPosition();
3371 wxSize newSz = caretRect.GetSize();
3372 wxPoint pt = GetPhysicalPoint(newPt);
3373 if (GetCaret()->GetPosition() != pt || GetCaret()->GetSize() != newSz)
3374 {
3375 GetCaret()->Hide();
3376 if (GetCaret()->GetSize() != newSz)
3377 GetCaret()->SetSize(newSz);
3378
3379 int halfSize = newSz.y/2;
3380 // If the caret is beyond the margin, hide it by moving it out of the way
3381 if (((pt.y + halfSize) < GetBuffer().GetTopMargin()) || ((pt.y + halfSize) > (GetClientSize().y - GetBuffer().GetBottomMargin())))
3382 {
3383 pt.x = -200;
3384 pt.y = -200;
3385 }
3386
3387 GetCaret()->Move(pt);
3388 GetCaret()->Show();
3389 }
3390 }
3391 }
3392
3393 /// Get the caret height and position for the given character position
3394 bool wxRichTextCtrl::GetCaretPositionForIndex(long position, wxRect& rect, wxRichTextParagraphLayoutBox* container)
3395 {
3396 wxClientDC dc(this);
3397 dc.SetFont(GetFont());
3398
3399 PrepareDC(dc);
3400
3401 wxPoint pt;
3402 int height = 0;
3403
3404 if (!container)
3405 container = GetFocusObject();
3406
3407 if (container->FindPosition(dc, position, pt, & height, m_caretAtLineStart))
3408 {
3409 // Caret height can't be zero
3410 if (height == 0)
3411 height = dc.GetCharHeight();
3412
3413 rect = wxRect(pt, wxSize(wxRICHTEXT_DEFAULT_CARET_WIDTH, height));
3414 return true;
3415 }
3416
3417 return false;
3418 }
3419
3420 /// Gets the line for the visible caret position. If the caret is
3421 /// shown at the very end of the line, it means the next character is actually
3422 /// on the following line. So let's get the line we're expecting to find
3423 /// if this is the case.
3424 wxRichTextLine* wxRichTextCtrl::GetVisibleLineForCaretPosition(long caretPosition) const
3425 {
3426 wxRichTextLine* line = GetFocusObject()->GetLineAtPosition(caretPosition, true);
3427 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(caretPosition, true);
3428 if (line)
3429 {
3430 wxRichTextRange lineRange = line->GetAbsoluteRange();
3431 if (caretPosition == lineRange.GetStart()-1 &&
3432 (para->GetRange().GetStart() != lineRange.GetStart()))
3433 {
3434 if (!m_caretAtLineStart)
3435 line = GetFocusObject()->GetLineAtPosition(caretPosition-1, true);
3436 }
3437 }
3438 return line;
3439 }
3440
3441
3442 /// Move the caret to the given character position
3443 bool wxRichTextCtrl::MoveCaret(long pos, bool showAtLineStart, wxRichTextParagraphLayoutBox* container)
3444 {
3445 if (GetBuffer().IsDirty())
3446 LayoutContent();
3447
3448 if (!container)
3449 container = GetFocusObject();
3450
3451 if (pos <= container->GetOwnRange().GetEnd())
3452 {
3453 SetCaretPosition(pos, showAtLineStart);
3454
3455 PositionCaret(container);
3456
3457 return true;
3458 }
3459 else
3460 return false;
3461 }
3462
3463 /// Layout the buffer: which we must do before certain operations, such as
3464 /// setting the caret position.
3465 bool wxRichTextCtrl::LayoutContent(bool onlyVisibleRect)
3466 {
3467 if (GetBuffer().IsDirty() || onlyVisibleRect)
3468 {
3469 wxRect availableSpace(GetClientSize());
3470 if (availableSpace.width == 0)
3471 availableSpace.width = 10;
3472 if (availableSpace.height == 0)
3473 availableSpace.height = 10;
3474
3475 int flags = wxRICHTEXT_FIXED_WIDTH|wxRICHTEXT_VARIABLE_HEIGHT;
3476 if (onlyVisibleRect)
3477 {
3478 flags |= wxRICHTEXT_LAYOUT_SPECIFIED_RECT;
3479 availableSpace.SetPosition(GetLogicalPoint(wxPoint(0, 0)));
3480 }
3481
3482 wxClientDC dc(this);
3483 dc.SetFont(GetFont());
3484
3485 PrepareDC(dc);
3486
3487 GetBuffer().Defragment();
3488 GetBuffer().UpdateRanges(); // If items were deleted, ranges need recalculation
3489 GetBuffer().Layout(dc, availableSpace, flags);
3490 GetBuffer().Invalidate(wxRICHTEXT_NONE);
3491
3492 if (!IsFrozen())
3493 SetupScrollbars();
3494 }
3495
3496 return true;
3497 }
3498
3499 /// Is all of the selection bold?
3500 bool wxRichTextCtrl::IsSelectionBold()
3501 {
3502 if (HasSelection())
3503 {
3504 wxRichTextAttr attr;
3505 wxRichTextRange range = GetSelectionRange();
3506 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
3507 attr.SetFontWeight(wxFONTWEIGHT_BOLD);
3508
3509 return HasCharacterAttributes(range, attr);
3510 }
3511 else
3512 {
3513 // If no selection, then we need to combine current style with default style
3514 // to see what the effect would be if we started typing.
3515 wxRichTextAttr attr;
3516 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
3517
3518 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3519 if (GetStyle(pos, attr))
3520 {
3521 if (IsDefaultStyleShowing())
3522 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
3523 return attr.GetFontWeight() == wxFONTWEIGHT_BOLD;
3524 }
3525 }
3526 return false;
3527 }
3528
3529 /// Is all of the selection italics?
3530 bool wxRichTextCtrl::IsSelectionItalics()
3531 {
3532 if (HasSelection())
3533 {
3534 wxRichTextRange range = GetSelectionRange();
3535 wxRichTextAttr attr;
3536 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
3537 attr.SetFontStyle(wxFONTSTYLE_ITALIC);
3538
3539 return HasCharacterAttributes(range, attr);
3540 }
3541 else
3542 {
3543 // If no selection, then we need to combine current style with default style
3544 // to see what the effect would be if we started typing.
3545 wxRichTextAttr attr;
3546 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
3547
3548 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3549 if (GetStyle(pos, attr))
3550 {
3551 if (IsDefaultStyleShowing())
3552 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
3553 return attr.GetFontStyle() == wxFONTSTYLE_ITALIC;
3554 }
3555 }
3556 return false;
3557 }
3558
3559 /// Is all of the selection underlined?
3560 bool wxRichTextCtrl::IsSelectionUnderlined()
3561 {
3562 if (HasSelection())
3563 {
3564 wxRichTextRange range = GetSelectionRange();
3565 wxRichTextAttr attr;
3566 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
3567 attr.SetFontUnderlined(true);
3568
3569 return HasCharacterAttributes(range, attr);
3570 }
3571 else
3572 {
3573 // If no selection, then we need to combine current style with default style
3574 // to see what the effect would be if we started typing.
3575 wxRichTextAttr attr;
3576 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
3577 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3578
3579 if (GetStyle(pos, attr))
3580 {
3581 if (IsDefaultStyleShowing())
3582 wxRichTextApplyStyle(attr, GetDefaultStyleEx());
3583 return attr.GetFontUnderlined();
3584 }
3585 }
3586 return false;
3587 }
3588
3589 /// Apply bold to the selection
3590 bool wxRichTextCtrl::ApplyBoldToSelection()
3591 {
3592 wxRichTextAttr attr;
3593 attr.SetFlags(wxTEXT_ATTR_FONT_WEIGHT);
3594 attr.SetFontWeight(IsSelectionBold() ? wxFONTWEIGHT_NORMAL : wxFONTWEIGHT_BOLD);
3595
3596 if (HasSelection())
3597 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3598 else
3599 {
3600 wxRichTextAttr current = GetDefaultStyleEx();
3601 current.Apply(attr);
3602 SetAndShowDefaultStyle(current);
3603 }
3604 return true;
3605 }
3606
3607 /// Apply italic to the selection
3608 bool wxRichTextCtrl::ApplyItalicToSelection()
3609 {
3610 wxRichTextAttr attr;
3611 attr.SetFlags(wxTEXT_ATTR_FONT_ITALIC);
3612 attr.SetFontStyle(IsSelectionItalics() ? wxFONTSTYLE_NORMAL : wxFONTSTYLE_ITALIC);
3613
3614 if (HasSelection())
3615 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3616 else
3617 {
3618 wxRichTextAttr current = GetDefaultStyleEx();
3619 current.Apply(attr);
3620 SetAndShowDefaultStyle(current);
3621 }
3622 return true;
3623 }
3624
3625 /// Apply underline to the selection
3626 bool wxRichTextCtrl::ApplyUnderlineToSelection()
3627 {
3628 wxRichTextAttr attr;
3629 attr.SetFlags(wxTEXT_ATTR_FONT_UNDERLINE);
3630 attr.SetFontUnderlined(!IsSelectionUnderlined());
3631
3632 if (HasSelection())
3633 return SetStyleEx(GetSelectionRange(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_CHARACTERS_ONLY);
3634 else
3635 {
3636 wxRichTextAttr current = GetDefaultStyleEx();
3637 current.Apply(attr);
3638 SetAndShowDefaultStyle(current);
3639 }
3640 return true;
3641 }
3642
3643 /// Is all of the selection aligned according to the specified flag?
3644 bool wxRichTextCtrl::IsSelectionAligned(wxTextAttrAlignment alignment)
3645 {
3646 wxRichTextRange range;
3647 if (HasSelection())
3648 range = GetSelectionRange();
3649 else
3650 range = wxRichTextRange(GetCaretPosition()+1, GetCaretPosition()+2);
3651
3652 wxRichTextAttr attr;
3653 attr.SetAlignment(alignment);
3654
3655 return HasParagraphAttributes(range, attr);
3656 }
3657
3658 /// Apply alignment to the selection
3659 bool wxRichTextCtrl::ApplyAlignmentToSelection(wxTextAttrAlignment alignment)
3660 {
3661 wxRichTextAttr attr;
3662 attr.SetAlignment(alignment);
3663 if (HasSelection())
3664 return SetStyle(GetSelectionRange(), attr);
3665 else
3666 {
3667 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(GetCaretPosition()+1);
3668 if (para)
3669 return SetStyleEx(para->GetRange().FromInternal(), attr, wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY);
3670 }
3671 return true;
3672 }
3673
3674 /// Apply a named style to the selection
3675 bool wxRichTextCtrl::ApplyStyle(wxRichTextStyleDefinition* def)
3676 {
3677 // Flags are defined within each definition, so only certain
3678 // attributes are applied.
3679 wxRichTextAttr attr(GetStyleSheet() ? def->GetStyleMergedWithBase(GetStyleSheet()) : def->GetStyle());
3680
3681 int flags = wxRICHTEXT_SETSTYLE_WITH_UNDO|wxRICHTEXT_SETSTYLE_OPTIMIZE|wxRICHTEXT_SETSTYLE_RESET;
3682
3683 if (def->IsKindOf(CLASSINFO(wxRichTextListStyleDefinition)))
3684 {
3685 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
3686
3687 wxRichTextRange range;
3688
3689 if (HasSelection())
3690 range = GetSelectionRange();
3691 else
3692 {
3693 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3694 range = wxRichTextRange(pos, pos+1);
3695 }
3696
3697 return SetListStyle(range, (wxRichTextListStyleDefinition*) def, flags);
3698 }
3699
3700 bool isPara = false;
3701
3702 // Make sure the attr has the style name
3703 if (def->IsKindOf(CLASSINFO(wxRichTextParagraphStyleDefinition)))
3704 {
3705 isPara = true;
3706 attr.SetParagraphStyleName(def->GetName());
3707
3708 // If applying a paragraph style, we only want the paragraph nodes to adopt these
3709 // attributes, and not the leaf nodes. This will allow the content (e.g. text)
3710 // to change its style independently.
3711 flags |= wxRICHTEXT_SETSTYLE_PARAGRAPHS_ONLY;
3712 }
3713 else
3714 attr.SetCharacterStyleName(def->GetName());
3715
3716 if (HasSelection())
3717 return SetStyleEx(GetSelectionRange(), attr, flags);
3718 else
3719 {
3720 wxRichTextAttr current = GetDefaultStyleEx();
3721 wxRichTextAttr defaultStyle(attr);
3722 if (isPara)
3723 {
3724 // Don't apply extra character styles since they are already implied
3725 // in the paragraph style
3726 defaultStyle.SetFlags(defaultStyle.GetFlags() & ~wxTEXT_ATTR_CHARACTER);
3727 }
3728 current.Apply(defaultStyle);
3729 SetAndShowDefaultStyle(current);
3730
3731 // If it's a paragraph style, we want to apply the style to the
3732 // current paragraph even if we didn't select any text.
3733 if (isPara)
3734 {
3735 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3736 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(pos);
3737 if (para)
3738 {
3739 return SetStyleEx(para->GetRange().FromInternal(), attr, flags);
3740 }
3741 }
3742 return true;
3743 }
3744 }
3745
3746 /// Apply the style sheet to the buffer, for example if the styles have changed.
3747 bool wxRichTextCtrl::ApplyStyleSheet(wxRichTextStyleSheet* styleSheet)
3748 {
3749 if (!styleSheet)
3750 styleSheet = GetBuffer().GetStyleSheet();
3751 if (!styleSheet)
3752 return false;
3753
3754 if (GetBuffer().ApplyStyleSheet(styleSheet))
3755 {
3756 GetBuffer().Invalidate(wxRICHTEXT_ALL);
3757 Refresh(false);
3758 return true;
3759 }
3760 else
3761 return false;
3762 }
3763
3764 /// Sets the default style to the style under the cursor
3765 bool wxRichTextCtrl::SetDefaultStyleToCursorStyle()
3766 {
3767 wxRichTextAttr attr;
3768 attr.SetFlags(wxTEXT_ATTR_CHARACTER);
3769
3770 // If at the start of a paragraph, use the next position.
3771 long pos = GetAdjustedCaretPosition(GetCaretPosition());
3772
3773 if (GetUncombinedStyle(pos, attr))
3774 {
3775 SetDefaultStyle(attr);
3776 return true;
3777 }
3778
3779 return false;
3780 }
3781
3782 /// Returns the first visible position in the current view
3783 long wxRichTextCtrl::GetFirstVisiblePosition() const
3784 {
3785 wxRichTextLine* line = GetFocusObject()->GetLineAtYPosition(GetLogicalPoint(wxPoint(0, 0)).y);
3786 if (line)
3787 return line->GetAbsoluteRange().GetStart();
3788 else
3789 return 0;
3790 }
3791
3792 /// Get the first visible point in the window
3793 wxPoint wxRichTextCtrl::GetFirstVisiblePoint() const
3794 {
3795 int ppuX, ppuY;
3796 int startXUnits, startYUnits;
3797
3798 GetScrollPixelsPerUnit(& ppuX, & ppuY);
3799 GetViewStart(& startXUnits, & startYUnits);
3800
3801 return wxPoint(startXUnits * ppuX, startYUnits * ppuY);
3802 }
3803
3804 /// The adjusted caret position is the character position adjusted to take
3805 /// into account whether we're at the start of a paragraph, in which case
3806 /// style information should be taken from the next position, not current one.
3807 long wxRichTextCtrl::GetAdjustedCaretPosition(long caretPos) const
3808 {
3809 wxRichTextParagraph* para = GetFocusObject()->GetParagraphAtPosition(caretPos+1);
3810
3811 if (para && (caretPos+1 == para->GetRange().GetStart()))
3812 caretPos ++;
3813 return caretPos;
3814 }
3815
3816 /// Get/set the selection range in character positions. -1, -1 means no selection.
3817 /// The range is in API convention, i.e. a single character selection is denoted
3818 /// by (n, n+1)
3819 wxRichTextRange wxRichTextCtrl::GetSelectionRange() const
3820 {
3821 wxRichTextRange range = GetInternalSelectionRange();
3822 if (range != wxRichTextRange(-2,-2) && range != wxRichTextRange(-1,-1))
3823 range.SetEnd(range.GetEnd() + 1);
3824 return range;
3825 }
3826
3827 void wxRichTextCtrl::SetSelectionRange(const wxRichTextRange& range)
3828 {
3829 SetSelection(range.GetStart(), range.GetEnd());
3830 }
3831
3832 /// Set list style
3833 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
3834 {
3835 return GetFocusObject()->SetListStyle(range.ToInternal(), def, flags, startFrom, specifiedLevel);
3836 }
3837
3838 bool wxRichTextCtrl::SetListStyle(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
3839 {
3840 return GetFocusObject()->SetListStyle(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
3841 }
3842
3843 /// Clear list for given range
3844 bool wxRichTextCtrl::ClearListStyle(const wxRichTextRange& range, int flags)
3845 {
3846 return GetFocusObject()->ClearListStyle(range.ToInternal(), flags);
3847 }
3848
3849 /// Number/renumber any list elements in the given range
3850 bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int startFrom, int specifiedLevel)
3851 {
3852 return GetFocusObject()->NumberList(range.ToInternal(), def, flags, startFrom, specifiedLevel);
3853 }
3854
3855 bool wxRichTextCtrl::NumberList(const wxRichTextRange& range, const wxString& defName, int flags, int startFrom, int specifiedLevel)
3856 {
3857 return GetFocusObject()->NumberList(range.ToInternal(), defName, flags, startFrom, specifiedLevel);
3858 }
3859
3860 /// Promote the list items within the given range. promoteBy can be a positive or negative number, e.g. 1 or -1
3861 bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, wxRichTextListStyleDefinition* def, int flags, int specifiedLevel)
3862 {
3863 return GetFocusObject()->PromoteList(promoteBy, range.ToInternal(), def, flags, specifiedLevel);
3864 }
3865
3866 bool wxRichTextCtrl::PromoteList(int promoteBy, const wxRichTextRange& range, const wxString& defName, int flags, int specifiedLevel)
3867 {
3868 return GetFocusObject()->PromoteList(promoteBy, range.ToInternal(), defName, flags, specifiedLevel);
3869 }
3870
3871 /// Deletes the content in the given range
3872 bool wxRichTextCtrl::Delete(const wxRichTextRange& range)
3873 {
3874 return GetFocusObject()->DeleteRangeWithUndo(range.ToInternal(), this, & GetBuffer());
3875 }
3876
3877 const wxArrayString& wxRichTextCtrl::GetAvailableFontNames()
3878 {
3879 if (sm_availableFontNames.GetCount() == 0)
3880 {
3881 sm_availableFontNames = wxFontEnumerator::GetFacenames();
3882 sm_availableFontNames.Sort();
3883 }
3884 return sm_availableFontNames;
3885 }
3886
3887 void wxRichTextCtrl::ClearAvailableFontNames()
3888 {
3889 sm_availableFontNames.Clear();
3890 }
3891
3892 void wxRichTextCtrl::OnSysColourChanged(wxSysColourChangedEvent& WXUNUSED(event))
3893 {
3894 //wxLogDebug(wxT("wxRichTextCtrl::OnSysColourChanged"));
3895
3896 wxTextAttrEx basicStyle = GetBasicStyle();
3897 basicStyle.SetTextColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
3898 SetBasicStyle(basicStyle);
3899 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
3900
3901 Refresh();
3902 }
3903
3904 // Refresh the area affected by a selection change
3905 bool wxRichTextCtrl::RefreshForSelectionChange(const wxRichTextSelection& oldSelection, const wxRichTextSelection& newSelection)
3906 {
3907 // If the selection is not part of the focus object, or we have multiple ranges, then the chances are that
3908 // the selection contains whole containers rather than just text, so refresh everything
3909 // for now as it would be hard to compute the rectangle bounding all selections.
3910 // TODO: improve on this.
3911 if ((oldSelection.IsValid() && (oldSelection.GetContainer() != GetFocusObject() || oldSelection.GetCount() > 1)) ||
3912 (newSelection.IsValid() && (newSelection.GetContainer() != GetFocusObject() || newSelection.GetCount() > 1)))
3913 {
3914 Refresh(false);
3915 return true;
3916 }
3917
3918 wxRichTextRange oldRange, newRange;
3919 if (oldSelection.IsValid())
3920 oldRange = oldSelection.GetRange();
3921 else
3922 oldRange = wxRICHTEXT_NO_SELECTION;
3923 if (newSelection.IsValid())
3924 newRange = newSelection.GetRange();
3925 else
3926 newRange = wxRICHTEXT_NO_SELECTION;
3927
3928 // Calculate the refresh rectangle - just the affected lines
3929 long firstPos, lastPos;
3930 if (oldRange.GetStart() == -2 && newRange.GetStart() != -2)
3931 {
3932 firstPos = newRange.GetStart();
3933 lastPos = newRange.GetEnd();
3934 }
3935 else if (oldRange.GetStart() != -2 && newRange.GetStart() == -2)
3936 {
3937 firstPos = oldRange.GetStart();
3938 lastPos = oldRange.GetEnd();
3939 }
3940 else if (oldRange.GetStart() == -2 && newRange.GetStart() == -2)
3941 {
3942 return false;
3943 }
3944 else
3945 {
3946 firstPos = wxMin(oldRange.GetStart(), newRange.GetStart());
3947 lastPos = wxMax(oldRange.GetEnd(), newRange.GetEnd());
3948 }
3949
3950 wxRichTextLine* firstLine = GetFocusObject()->GetLineAtPosition(firstPos);
3951 wxRichTextLine* lastLine = GetFocusObject()->GetLineAtPosition(lastPos);
3952
3953 if (firstLine && lastLine)
3954 {
3955 wxSize clientSize = GetClientSize();
3956 wxPoint pt1 = GetPhysicalPoint(firstLine->GetAbsolutePosition());
3957 wxPoint pt2 = GetPhysicalPoint(lastLine->GetAbsolutePosition()) + wxPoint(0, lastLine->GetSize().y);
3958
3959 pt1.x = 0;
3960 pt1.y = wxMax(0, pt1.y);
3961 pt2.x = 0;
3962 pt2.y = wxMin(clientSize.y, pt2.y);
3963
3964 wxRect rect(pt1, wxSize(clientSize.x, pt2.y - pt1.y));
3965 RefreshRect(rect, false);
3966 }
3967 else
3968 Refresh(false);
3969
3970 return true;
3971 }
3972
3973 // margins functions
3974 bool wxRichTextCtrl::DoSetMargins(const wxPoint& pt)
3975 {
3976 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().SetValue(pt.x, wxTEXT_ATTR_UNITS_PIXELS);
3977 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetRight().SetValue(pt.x, wxTEXT_ATTR_UNITS_PIXELS);
3978 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().SetValue(pt.y, wxTEXT_ATTR_UNITS_PIXELS);
3979 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetBottom().SetValue(pt.y, wxTEXT_ATTR_UNITS_PIXELS);
3980
3981 return true;
3982 }
3983
3984 wxPoint wxRichTextCtrl::DoGetMargins() const
3985 {
3986 return wxPoint(GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetLeft().GetValue(),
3987 GetBuffer().GetAttributes().GetTextBoxAttr().GetMargins().GetTop().GetValue());
3988 }
3989
3990 bool wxRichTextCtrl::SetFocusObject(wxRichTextParagraphLayoutBox* obj, bool setCaretPosition)
3991 {
3992 if (obj && !obj->AcceptsFocus())
3993 return false;
3994
3995 wxRichTextParagraphLayoutBox* oldContainer = GetFocusObject();
3996 bool changingContainer = (m_focusObject != obj);
3997
3998 m_focusObject = obj;
3999
4000 if (!obj)
4001 m_focusObject = & m_buffer;
4002
4003 if (setCaretPosition && changingContainer)
4004 {
4005 m_selection.Reset();
4006 m_selectionAnchor = -2;
4007 m_selectionAnchorObject = NULL;
4008 m_selectionState = wxRichTextCtrlSelectionState_Normal;
4009
4010 long pos = -1;
4011
4012 m_caretAtLineStart = false;
4013 MoveCaret(pos, m_caretAtLineStart);
4014 SetDefaultStyleToCursorStyle();
4015
4016 wxRichTextEvent cmdEvent(
4017 wxEVT_COMMAND_RICHTEXT_FOCUS_OBJECT_CHANGED,
4018 GetId());
4019 cmdEvent.SetEventObject(this);
4020 cmdEvent.SetPosition(m_caretPosition+1);
4021 cmdEvent.SetOldContainer(oldContainer);
4022 cmdEvent.SetContainer(m_focusObject);
4023
4024 GetEventHandler()->ProcessEvent(cmdEvent);
4025 }
4026 return true;
4027 }
4028
4029 #if wxRICHTEXT_USE_OWN_CARET
4030
4031 // ----------------------------------------------------------------------------
4032 // initialization and destruction
4033 // ----------------------------------------------------------------------------
4034
4035 void wxRichTextCaret::Init()
4036 {
4037 m_hasFocus = true;
4038
4039 m_xOld =
4040 m_yOld = -1;
4041 m_richTextCtrl = NULL;
4042 m_needsUpdate = false;
4043 m_flashOn = true;
4044 }
4045
4046 wxRichTextCaret::~wxRichTextCaret()
4047 {
4048 if (m_timer.IsRunning())
4049 m_timer.Stop();
4050 }
4051
4052 // ----------------------------------------------------------------------------
4053 // showing/hiding/moving the caret (base class interface)
4054 // ----------------------------------------------------------------------------
4055
4056 void wxRichTextCaret::DoShow()
4057 {
4058 m_flashOn = true;
4059
4060 if (!m_timer.IsRunning())
4061 m_timer.Start(GetBlinkTime());
4062
4063 Refresh();
4064 }
4065
4066 void wxRichTextCaret::DoHide()
4067 {
4068 if (m_timer.IsRunning())
4069 m_timer.Stop();
4070
4071 Refresh();
4072 }
4073
4074 void wxRichTextCaret::DoMove()
4075 {
4076 if (IsVisible())
4077 {
4078 Refresh();
4079
4080 if (m_xOld != -1 && m_yOld != -1)
4081 {
4082 if (m_richTextCtrl)
4083 {
4084 wxRect rect(GetPosition(), GetSize());
4085 m_richTextCtrl->RefreshRect(rect, false);
4086 }
4087 }
4088 }
4089
4090 m_xOld = m_x;
4091 m_yOld = m_y;
4092 }
4093
4094 void wxRichTextCaret::DoSize()
4095 {
4096 int countVisible = m_countVisible;
4097 if (countVisible > 0)
4098 {
4099 m_countVisible = 0;
4100 DoHide();
4101 }
4102
4103 if (countVisible > 0)
4104 {
4105 m_countVisible = countVisible;
4106 DoShow();
4107 }
4108 }
4109
4110 // ----------------------------------------------------------------------------
4111 // handling the focus
4112 // ----------------------------------------------------------------------------
4113
4114 void wxRichTextCaret::OnSetFocus()
4115 {
4116 m_hasFocus = true;
4117
4118 if ( IsVisible() )
4119 Refresh();
4120 }
4121
4122 void wxRichTextCaret::OnKillFocus()
4123 {
4124 m_hasFocus = false;
4125 }
4126
4127 // ----------------------------------------------------------------------------
4128 // drawing the caret
4129 // ----------------------------------------------------------------------------
4130
4131 void wxRichTextCaret::Refresh()
4132 {
4133 if (m_richTextCtrl)
4134 {
4135 wxRect rect(GetPosition(), GetSize());
4136 m_richTextCtrl->RefreshRect(rect, false);
4137 }
4138 }
4139
4140 void wxRichTextCaret::DoDraw(wxDC *dc)
4141 {
4142 dc->SetPen( *wxBLACK_PEN );
4143
4144 dc->SetBrush(*(m_hasFocus ? wxBLACK_BRUSH : wxTRANSPARENT_BRUSH));
4145 dc->SetPen(*wxBLACK_PEN);
4146
4147 wxPoint pt(m_x, m_y);
4148
4149 if (m_richTextCtrl)
4150 {
4151 pt = m_richTextCtrl->GetLogicalPoint(pt);
4152 }
4153 if (IsVisible() && m_flashOn)
4154 dc->DrawRectangle(pt.x, pt.y, m_width, m_height);
4155 }
4156
4157 void wxRichTextCaret::Notify()
4158 {
4159 m_flashOn = !m_flashOn;
4160 Refresh();
4161 }
4162
4163 void wxRichTextCaretTimer::Notify()
4164 {
4165 m_caret->Notify();
4166 }
4167 #endif
4168 // wxRICHTEXT_USE_OWN_CARET
4169
4170 // Add an item
4171 bool wxRichTextContextMenuPropertiesInfo::AddItem(const wxString& label, wxRichTextObject* obj)
4172 {
4173 if (GetCount() < 3)
4174 {
4175 m_labels.Add(label);
4176 m_objects.Add(obj);
4177 return true;
4178 }
4179 else
4180 return false;
4181 }
4182
4183 // Returns number of menu items were added.
4184 int wxRichTextContextMenuPropertiesInfo::AddMenuItems(wxMenu* menu, int startCmd) const
4185 {
4186 wxMenuItem* item = menu->FindItem(startCmd);
4187 // If none of the standard properties identifiers are in the menu, assume it's
4188 // a custom menu without properties commands, and don't add them.
4189 if (item)
4190 {
4191 // If no items, to add just set the text to something generic
4192 if (GetCount() == 0)
4193 {
4194 menu->SetLabel(startCmd, _("&Properties"));
4195
4196 // Delete the others if necessary
4197 int i;
4198 for (i = startCmd+1; i < startCmd+3; i++)
4199 {
4200 if (menu->FindItem(i))
4201 {
4202 menu->Delete(i);
4203 }
4204 }
4205 }
4206 else
4207 {
4208 int i;
4209 int pos = -1;
4210 // Find the position of the first properties item
4211 for (i = 0; i < (int) menu->GetMenuItemCount(); i++)
4212 {
4213 wxMenuItem* item = menu->FindItemByPosition(i);
4214 if (item && item->GetId() == startCmd)
4215 {
4216 pos = i;
4217 break;
4218 }
4219 }
4220
4221 if (pos != -1)
4222 {
4223 int insertBefore = pos+1;
4224 for (i = startCmd; i < startCmd+GetCount(); i++)
4225 {
4226 if (menu->FindItem(i))
4227 {
4228 menu->SetLabel(i, m_labels[i - startCmd]);
4229 }
4230 else
4231 {
4232 if (insertBefore >= (int) menu->GetMenuItemCount())
4233 menu->Append(i, m_labels[i - startCmd]);
4234 else
4235 menu->Insert(insertBefore, i, m_labels[i - startCmd]);
4236 }
4237 insertBefore ++;
4238 }
4239
4240 // Delete any old items still left on the menu
4241 for (i = startCmd + GetCount(); i < startCmd+3; i++)
4242 {
4243 if (menu->FindItem(i))
4244 {
4245 menu->Delete(i);
4246 }
4247 }
4248 }
4249 }
4250 }
4251
4252 return GetCount();
4253 }
4254
4255 // Add appropriate menu items for the current container and clicked on object
4256 // (and container's parent, if appropriate).
4257 int wxRichTextContextMenuPropertiesInfo::AddItems(wxRichTextObject* container, wxRichTextObject* obj)
4258 {
4259 Clear();
4260 if (obj && obj->CanEditProperties())
4261 AddItem(obj->GetPropertiesMenuLabel(), obj);
4262
4263 if (container && container != obj && container->CanEditProperties() && m_labels.Index(container->GetPropertiesMenuLabel()) == wxNOT_FOUND)
4264 AddItem(container->GetPropertiesMenuLabel(), container);
4265
4266 if (container && container->GetParent() && container->GetParent()->CanEditProperties() && m_labels.Index(container->GetParent()->GetPropertiesMenuLabel()) == wxNOT_FOUND)
4267 AddItem(container->GetParent()->GetPropertiesMenuLabel(), container->GetParent());
4268
4269 return GetCount();
4270 }
4271
4272 #endif
4273 // wxUSE_RICHTEXT