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