1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/univ/textctrl.cpp
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 2000 SciTech Software, Inc. (www.scitechsoft.com)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
15 + 1. update vert scrollbar when any line length changes for WrapLines()
16 + 2. cursor movement ("Hello,^" -> "^verse!" on Arrow Down)?
17 -> maybe save the x position and use it instead of current in handling
18 DOWN/UP actions (this would make up/down always return the cursor to
20 3. split file into chunks
21 +? 4. rewrite Replace() refresh logic to deal with wrapping lines
22 +? 5. cache info found by GetPartOfWrappedLine() - performance must be horrible
25 6. backspace refreshes too much (until end of line)
29 Optimisation hints from PureQuantify:
31 +1. wxStringTokenize is the slowest part of Replace
32 2. GetDC/ReleaseDC are very slow, avoid calling them several times
33 +3. GetCharHeight() should be cached too
34 4. wxClientDC construction/destruction in HitTestLine is horribly expensive
36 For line wrapping controls HitTest2 takes 50% of program time. The results
37 of GetRowsPerLine and GetPartOfWrappedLine *MUST* be cached.
39 Search for "OPT!" for things which must be optimized.
45 Everywhere in this file LINE refers to a logical line of text, and ROW to a
46 physical line of text on the display. They are the same unless WrapLines()
47 is true in which case a single LINE may correspond to multiple ROWs.
49 A text position is an unsigned int (which for reasons of compatibility is
50 still a long as wxTextPos) from 0 to GetLastPosition() inclusive. The positions
51 correspond to the gaps between the letters so the position 0 is just
52 before the first character and the last position is the one beyond the last
53 character. For an empty text control GetLastPosition() returns 0.
55 Lines and columns returned/accepted by XYToPosition() and PositionToXY()
56 start from 0. The y coordinate is a LINE, not a ROW. Columns correspond to
57 the characters, the first column of a line is the first character in it,
58 the last one is length(line text). For compatibility, again, lines and
59 columns are also longs.
61 When translating lines/column coordinates to/from positions, the line and
62 column give the character after the given position. Thus, GetLastPosition()
63 doesn't have any corresponding column.
65 An example of positions and lines/columns for a control without wrapping
66 containing the text "Hello, Universe!\nGoodbye"
69 pos: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
70 H e l l o , U n i v e r s e ! line 0
71 col: 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1
80 The same example for a control with line wrap assuming "Universe" is too
81 long to fit on the same line with "Hello,":
84 H e l l o , line 0 (row 0)
88 pos: 6 7 8 9 0 1 2 3 4 5 6
89 U n i v e r s e ! line 0 (row 1)
90 col: 6 7 8 9 1 1 1 1 1 1
93 (line 1 == row 2 same as above)
95 Note that there is still the same number of columns and positions and that
96 there is no (logical) position at the end of the first ROW. This position
97 is identified with the preceding one (which is not how Windows does it: it
98 identifies it with the next one, i.e. the first position of the next line,
99 but much more logical IMHO).
103 Search for "OPT" for possible optimizations
105 A possible global optimization would be to always store the coords in the
106 text in triplets (pos, col, line) and update them simultaneously instead of
107 recalculating col and line from pos each time it is needed. Currently we
108 only do it for the current position but we might also do it for the
109 selection start and end.
112 // ============================================================================
114 // ============================================================================
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
120 #include "wx/wxprec.h"
128 #include "wx/textctrl.h"
132 #include "wx/dcclient.h"
133 #include "wx/validate.h"
134 #include "wx/dataobj.h"
139 #include "wx/clipbrd.h"
141 #include "wx/textfile.h"
143 #include "wx/caret.h"
145 #include "wx/univ/inphand.h"
146 #include "wx/univ/renderer.h"
147 #include "wx/univ/colschem.h"
148 #include "wx/univ/theme.h"
150 #include "wx/cmdproc.h"
152 // turn extra wxTextCtrl-specific debugging on/off
155 // turn wxTextCtrl::Replace() debugging on (slows down code a *lot*!)
156 #define WXDEBUG_TEXT_REPLACE
160 #undef WXDEBUG_TEXT_REPLACE
163 // wxStringTokenize only needed for debug checks
164 #ifdef WXDEBUG_TEXT_REPLACE
165 #include "wx/tokenzr.h"
166 #endif // WXDEBUG_TEXT_REPLACE
168 // ----------------------------------------------------------------------------
169 // wxStdTextCtrlInputHandler: this control handles only the mouse/kbd actions
170 // common to Win32 and GTK, platform-specific things are implemented elsewhere
171 // ----------------------------------------------------------------------------
173 class WXDLLEXPORT wxStdTextCtrlInputHandler
: public wxStdInputHandler
176 wxStdTextCtrlInputHandler(wxInputHandler
*inphand
);
178 virtual bool HandleKey(wxInputConsumer
*consumer
,
179 const wxKeyEvent
& event
,
181 virtual bool HandleMouse(wxInputConsumer
*consumer
,
182 const wxMouseEvent
& event
);
183 virtual bool HandleMouseMove(wxInputConsumer
*consumer
,
184 const wxMouseEvent
& event
);
185 virtual bool HandleFocus(wxInputConsumer
*consumer
, const wxFocusEvent
& event
);
188 // get the position of the mouse click
189 static wxTextPos
HitTest(const wxTextCtrl
*text
, const wxPoint
& pos
);
192 wxTextCtrl
*m_winCapture
;
195 // ----------------------------------------------------------------------------
197 // ----------------------------------------------------------------------------
199 // exchange two positions so that from is always less than or equal to to
200 static inline void OrderPositions(wxTextPos
& from
, wxTextPos
& to
)
204 wxTextPos tmp
= from
;
210 // ----------------------------------------------------------------------------
212 // ----------------------------------------------------------------------------
214 // names of text ctrl commands
215 #define wxTEXT_COMMAND_INSERT _T("insert")
216 #define wxTEXT_COMMAND_REMOVE _T("remove")
218 // the value which is never used for text position, even not -1 which is
219 // sometimes used for some special meaning
220 static const wxTextPos INVALID_POS_VALUE
= wxInvalidTextCoord
;
222 // overlap between pages (when using PageUp/Dn) in lines
223 static const size_t PAGE_OVERLAP_IN_LINES
= 1;
225 // ----------------------------------------------------------------------------
226 // private data of wxTextCtrl
227 // ----------------------------------------------------------------------------
229 // the data only used by single line text controls
230 struct wxTextSingleLineData
232 // the position of the first visible pixel and the first visible column
234 wxTextCoord m_colStart
;
236 // and the last ones (m_posLastVisible is the width but m_colLastVisible
237 // is an absolute value)
238 wxCoord m_posLastVisible
;
239 wxTextCoord m_colLastVisible
;
242 wxTextSingleLineData()
247 m_colLastVisible
= -1;
248 m_posLastVisible
= -1;
253 // the data only used by multi line text controls
254 struct wxTextMultiLineData
257 wxArrayString m_lines
;
259 // the current ranges of the scrollbars
263 // should we adjust the horz/vert scrollbar?
264 bool m_updateScrollbarX
,
267 // the max line length in pixels
270 // the index of the line which has the length of m_widthMax
271 wxTextCoord m_lineLongest
;
273 // the rect in which text appears: it is even less than m_rectText because
274 // only the last _complete_ line is shown, hence there is an unoccupied
275 // horizontal band at the bottom of it
276 wxRect m_rectTextReal
;
278 // the x-coordinate of the caret before we started moving it vertically:
279 // this is used to ensure that moving the caret up and then down will
280 // return it to the same position as if we always round it in one direction
281 // we would shift it in that direction
283 // when m_xCaret == -1, we don't have any remembered position
287 wxTextMultiLineData()
293 m_updateScrollbarY
= false;
302 // the data only used by multi line text controls in line wrap mode
303 class wxWrappedLineData
305 // these functions set all our values, so give them access to them
306 friend void wxTextCtrl::LayoutLine(wxTextCoord line
,
307 wxWrappedLineData
& lineData
) const;
308 friend void wxTextCtrl::LayoutLines(wxTextCoord
) const;
317 // get the start of any row (remember that accessing m_rowsStart doesn't work
318 // for the first one)
319 wxTextCoord
GetRowStart(wxTextCoord row
) const
321 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
323 return row
? m_rowsStart
[row
- 1] : 0;
326 // get the length of the row (using the total line length which we don't
327 // have here but need to calculate the length of the last row, so it must
329 wxTextCoord
GetRowLength(wxTextCoord row
, wxTextCoord lenLine
) const
331 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
333 // note that m_rowsStart[row] is the same as GetRowStart(row + 1) (but
334 // slightly more efficient) and lenLine is the same as the start of the
335 // first row of the next line
336 return ((size_t)row
== m_rowsStart
.GetCount() ? lenLine
: m_rowsStart
[row
])
340 // return the width of the row in pixels
341 wxCoord
GetRowWidth(wxTextCoord row
) const
343 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
345 return m_rowsWidth
[row
];
348 // return the number of rows
349 size_t GetRowCount() const
351 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
353 return m_rowsStart
.GetCount() + 1;
356 // return the number of additional (i.e. after the first one) rows
357 size_t GetExtraRowCount() const
359 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
361 return m_rowsStart
.GetCount();
364 // return the first row of this line
365 wxTextCoord
GetFirstRow() const
367 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
372 // return the first row of the next line
373 wxTextCoord
GetNextRow() const
375 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
377 return m_rowFirst
+ m_rowsStart
.GetCount() + 1;
380 // this just provides direct access to m_rowsStart aerray for efficiency
381 wxTextCoord
GetExtraRowStart(wxTextCoord row
) const
383 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
385 return m_rowsStart
[row
];
388 // this code is unused any longer
390 // return true if the column is in the start of the last row (hence the row
391 // it is in is not wrapped)
392 bool IsLastRow(wxTextCoord colRowStart
) const
394 return colRowStart
== GetRowStart(m_rowsStart
.GetCount());
397 // return true if the column is the last column of the row starting in
399 bool IsLastColInRow(wxTextCoord colRowStart
,
400 wxTextCoord colRowEnd
,
401 wxTextCoord lenLine
) const
403 // find the row which starts with colRowStart
404 size_t nRows
= GetRowCount();
405 for ( size_t n
= 0; n
< nRows
; n
++ )
407 if ( GetRowStart(n
) == colRowStart
)
409 wxTextCoord colNextRowStart
= n
== nRows
- 1
411 : GetRowStart(n
+ 1);
413 wxASSERT_MSG( colRowEnd
< colNextRowStart
,
414 _T("this column is not in this row at all!") );
416 return colRowEnd
== colNextRowStart
- 1;
420 // caller got it wrong
421 wxFAIL_MSG( _T("this column is not in the start of the row!") );
427 // is this row the last one in its line?
428 bool IsLastRow(wxTextCoord row
) const
430 return (size_t)row
== GetExtraRowCount();
433 // the line is valid if it had been laid out correctly: note that just
434 // shiwting the line (because one of previous lines changed) doesn't make
436 bool IsValid() const { return !m_rowsWidth
.IsEmpty(); }
438 // invalidating line will relayout it
439 void Invalidate() { m_rowsWidth
.Empty(); }
442 // for each line we remember the starting columns of all its rows after the
443 // first one (which always starts at 0), i.e. if a line is wrapped twice
444 // (== takes 3 rows) its m_rowsStart[0] may be 10 and m_rowsStart[1] == 15
445 wxArrayLong m_rowsStart
;
447 // and the width of each row in pixels (this array starts from 0, as usual)
448 wxArrayInt m_rowsWidth
;
450 // and also its starting row (0 for the first line, first lines'
451 // m_rowsStart.GetCount() + 1 for the second &c): it is set to -1 initially
452 // and this means that the struct hadn't yet been initialized
453 wxTextCoord m_rowFirst
;
455 // the last modification "time"-stamp used by LayoutLines()
459 WX_DECLARE_OBJARRAY(wxWrappedLineData
, wxArrayWrappedLinesData
);
460 #include "wx/arrimpl.cpp"
461 WX_DEFINE_OBJARRAY(wxArrayWrappedLinesData
);
463 struct wxTextWrappedData
: public wxTextMultiLineData
465 // the width of the column to the right of the text rect used for the
466 // indicator mark display for the wrapped lines
469 // the data for each line
470 wxArrayWrappedLinesData m_linesData
;
472 // flag telling us to recalculate all starting rows starting from this line
473 // (if it is -1, we don't have to recalculate anything) - it is set when
474 // the number of the rows in the middle of the control changes
475 wxTextCoord m_rowFirstInvalid
;
477 // the current timestamp used by LayoutLines()
480 // invalidate starting rows of all lines (NOT rows!) after this one
481 void InvalidateLinesBelow(wxTextCoord line
)
483 if ( m_rowFirstInvalid
== -1 || m_rowFirstInvalid
> line
)
485 m_rowFirstInvalid
= line
;
489 // check if this line is valid: i.e. before the first invalid one
490 bool IsValidLine(wxTextCoord line
) const
492 return ((m_rowFirstInvalid
== -1) || (line
< m_rowFirstInvalid
)) &&
493 m_linesData
[line
].IsValid();
500 m_rowFirstInvalid
= -1;
505 // ----------------------------------------------------------------------------
506 // private classes for undo/redo management
507 // ----------------------------------------------------------------------------
510 We use custom versions of wxWidgets command processor to implement undo/redo
511 as we want to avoid storing the backpointer to wxTextCtrl in wxCommand
512 itself: this is a waste of memory as all commands in the given command
513 processor always have the same associated wxTextCtrl and so it makes sense
514 to store the backpointer there.
516 As for the rest of the implementation, it's fairly standard: we have 2
517 command classes corresponding to adding and removing text.
520 // a command corresponding to a wxTextCtrl action
521 class wxTextCtrlCommand
: public wxCommand
524 wxTextCtrlCommand(const wxString
& name
) : wxCommand(true, name
) { }
526 // we don't use these methods as they don't make sense for us as we need a
527 // wxTextCtrl to be applied
528 virtual bool Do() { wxFAIL_MSG(_T("shouldn't be called")); return false; }
529 virtual bool Undo() { wxFAIL_MSG(_T("shouldn't be called")); return false; }
531 // instead, our command processor uses these methods
532 virtual bool Do(wxTextCtrl
*text
) = 0;
533 virtual bool Undo(wxTextCtrl
*text
) = 0;
536 // insert text command
537 class wxTextCtrlInsertCommand
: public wxTextCtrlCommand
540 wxTextCtrlInsertCommand(const wxString
& textToInsert
)
541 : wxTextCtrlCommand(wxTEXT_COMMAND_INSERT
), m_text(textToInsert
)
546 // combine the 2 commands together
547 void Append(wxTextCtrlInsertCommand
*other
);
549 virtual bool CanUndo() const;
550 virtual bool Do(wxTextCtrl
*text
);
551 virtual bool Do() { return wxTextCtrlCommand::Do(); }
552 virtual bool Undo() { return wxTextCtrlCommand::Undo(); }
553 virtual bool Undo(wxTextCtrl
*text
);
556 // the text we insert
559 // the position where we inserted the text
563 // remove text command
564 class wxTextCtrlRemoveCommand
: public wxTextCtrlCommand
567 wxTextCtrlRemoveCommand(wxTextPos from
, wxTextPos to
)
568 : wxTextCtrlCommand(wxTEXT_COMMAND_REMOVE
)
574 virtual bool CanUndo() const;
575 virtual bool Do(wxTextCtrl
*text
);
576 virtual bool Do() { return wxTextCtrlCommand::Do(); }
577 virtual bool Undo() { return wxTextCtrlCommand::Undo(); }
578 virtual bool Undo(wxTextCtrl
*text
);
581 // the range of text to delete
585 // the text which was deleted when this command was Do()ne
586 wxString m_textDeleted
;
589 // a command processor for a wxTextCtrl
590 class wxTextCtrlCommandProcessor
: public wxCommandProcessor
593 wxTextCtrlCommandProcessor(wxTextCtrl
*text
)
595 m_compressInserts
= false;
600 // override Store() to compress multiple wxTextCtrlInsertCommand into one
601 virtual void Store(wxCommand
*command
);
603 // stop compressing insert commands when this is called
604 void StopCompressing() { m_compressInserts
= false; }
607 wxTextCtrl
*GetTextCtrl() const { return m_text
; }
608 bool IsCompressing() const { return m_compressInserts
; }
611 virtual bool DoCommand(wxCommand
& cmd
)
612 { return ((wxTextCtrlCommand
&)cmd
).Do(m_text
); }
613 virtual bool UndoCommand(wxCommand
& cmd
)
614 { return ((wxTextCtrlCommand
&)cmd
).Undo(m_text
); }
616 // check if this command is a wxTextCtrlInsertCommand and return it casted
617 // to the right type if it is or NULL otherwise
618 wxTextCtrlInsertCommand
*IsInsertCommand(wxCommand
*cmd
);
621 // the control we're associated with
624 // if the flag is true we're compressing subsequent insert commands into
625 // one so that the entire typing could be undone in one call to Undo()
626 bool m_compressInserts
;
629 // ============================================================================
631 // ============================================================================
633 BEGIN_EVENT_TABLE(wxTextCtrl
, wxTextCtrlBase
)
634 EVT_CHAR(wxTextCtrl::OnChar
)
636 EVT_SIZE(wxTextCtrl::OnSize
)
639 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl
, wxTextCtrlBase
)
641 // ----------------------------------------------------------------------------
643 // ----------------------------------------------------------------------------
645 void wxTextCtrl::Init()
651 m_isModified
= false;
662 // init the undo manager
663 m_cmdProcessor
= new wxTextCtrlCommandProcessor(this);
669 bool wxTextCtrl::Create(wxWindow
*parent
,
671 const wxString
& value
,
675 const wxValidator
& validator
,
676 const wxString
&name
)
678 if ( style
& wxTE_MULTILINE
)
680 // for compatibility with wxMSW we create the controls with vertical
681 // scrollbar always shown unless they have wxTE_RICH style (because
682 // Windows text controls always has vert scrollbar but richedit one
684 if ( !(style
& wxTE_RICH
) )
686 style
|= wxALWAYS_SHOW_SB
;
689 // wrapping style: wxTE_DONTWRAP == wxHSCROLL so if it's _not_ given,
690 // we won't have horizontal scrollbar automatically, no need to do
693 // TODO: support wxTE_NO_VSCROLL (?)
695 // create data object for normal multiline or for controls with line
697 if ( style
& wxHSCROLL
)
698 m_data
.mdata
= new wxTextMultiLineData
;
700 m_data
.wdata
= new wxTextWrappedData
;
704 // this doesn't make sense for single line controls
707 // create data object for single line controls
708 m_data
.sdata
= new wxTextSingleLineData
;
711 #if wxUSE_TWO_WINDOWS
712 if ((style
& wxBORDER_MASK
) == 0)
713 style
|= wxBORDER_SUNKEN
;
716 if ( !wxControl::Create(parent
, id
, pos
, size
, style
,
722 SetCursor(wxCURSOR_IBEAM
);
724 if ( style
& wxTE_MULTILINE
)
726 // we should always have at least one line in a multiline control
727 MData().m_lines
.Add(wxEmptyString
);
729 if ( !(style
& wxHSCROLL
) )
731 WData().m_linesData
.Add(new wxWrappedLineData
);
732 WData().InvalidateLinesBelow(0);
735 // we might support it but it's quite useless and other ports don't
737 wxASSERT_MSG( !(style
& wxTE_PASSWORD
),
738 _T("wxTE_PASSWORD can't be used with multiline ctrls") );
745 m_isEditable
= !(style
& wxTE_READONLY
);
748 InitInsertionPoint();
750 // we can't show caret right now as we're not shown yet and so it would
751 // result in garbage on the screen - we'll do it after first OnPaint()
754 CreateInputHandler(wxINP_HANDLER_TEXTCTRL
);
756 wxSizeEvent
sizeEvent(GetSize(), GetId());
757 GetEventHandler()->ProcessEvent(sizeEvent
);
762 wxTextCtrl::~wxTextCtrl()
764 delete m_cmdProcessor
;
768 if ( IsSingleLine() )
770 else if ( WrapLines() )
777 // ----------------------------------------------------------------------------
779 // ----------------------------------------------------------------------------
781 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
783 if ( IsSingleLine() && (value
== GetValue()) )
789 Replace(0, GetLastPosition(), value
);
791 if ( IsSingleLine() )
793 SetInsertionPoint(0);
796 if ( flags
& SetValue_SendEvent
)
797 SendTextUpdatedEvent();
800 const wxArrayString
& wxTextCtrl::GetLines() const
802 return MData().m_lines
;
805 size_t wxTextCtrl::GetLineCount() const
807 return MData().m_lines
.GetCount();
810 wxString
wxTextCtrl::GetValue() const
812 // for multiline controls we don't always store the total value but only
813 // recompute it when asked - and to invalidate it we just empty it in
815 if ( !IsSingleLine() && m_value
.empty() )
817 // recalculate: note that we always do it for empty multilien control,
818 // but then it's so quick that it's not important
820 // the first line is special as there is no \n before it, so it's
822 const wxArrayString
& lines
= GetLines();
823 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
824 self
->m_value
<< lines
[0u];
825 size_t count
= lines
.GetCount();
826 for ( size_t n
= 1; n
< count
; n
++ )
828 self
->m_value
<< _T('\n') << lines
[n
];
835 void wxTextCtrl::Clear()
837 SetValue(wxEmptyString
);
840 bool wxTextCtrl::ReplaceLine(wxTextCoord line
,
841 const wxString
& text
)
845 // first, we have to relayout the line entirely
847 // OPT: we might try not to recalc the unchanged part of line
849 wxWrappedLineData
& lineData
= WData().m_linesData
[line
];
851 // if we had some number of rows before, use this number, otherwise
852 // just make sure that the test below (rowsNew != rowsOld) will be true
854 if ( lineData
.IsValid() )
856 rowsOld
= lineData
.GetExtraRowCount();
858 else // line wasn't laid out yet
860 // assume it changed entirely as we can't do anything better
864 // now change the line
865 MData().m_lines
[line
] = text
;
867 // OPT: we choose to lay it our immediately instead of delaying it
868 // until it is needed because it allows us to avoid invalidating
869 // lines further down if the number of rows didn't chnage, but
870 // maybe we can imporve this even further?
871 LayoutLine(line
, lineData
);
873 int rowsNew
= lineData
.GetExtraRowCount();
875 if ( rowsNew
!= rowsOld
)
877 // we have to update the line wrap marks as this is normally done
878 // by LayoutLines() which we bypassed by calling LayoutLine()
880 wxTextCoord rowFirst
= lineData
.GetFirstRow(),
881 rowCount
= wxMax(rowsOld
, rowsNew
);
882 RefreshLineWrapMarks(rowFirst
, rowFirst
+ rowCount
);
884 // next, if this is not the last line, as the number of rows in it
885 // changed, we need to shift all the lines below it
886 if ( (size_t)line
< WData().m_linesData
.GetCount() )
888 // number of rows changed shifting all lines below
889 WData().InvalidateLinesBelow(line
+ 1);
892 // the number of rows changed
898 MData().m_lines
[line
] = text
;
901 // the number of rows didn't change
905 void wxTextCtrl::RemoveLine(wxTextCoord line
)
907 MData().m_lines
.RemoveAt(line
);
910 // we need to recalculate all the starting rows from this line, but we
911 // can avoid doing it if this line was never calculated: this means
912 // that we will recalculate all lines below it anyhow later if needed
913 if ( WData().IsValidLine(line
) )
915 WData().InvalidateLinesBelow(line
);
918 WData().m_linesData
.RemoveAt(line
);
922 void wxTextCtrl::InsertLine(wxTextCoord line
, const wxString
& text
)
924 MData().m_lines
.Insert(text
, line
);
927 WData().m_linesData
.Insert(new wxWrappedLineData
, line
);
929 // invalidate everything below it
930 WData().InvalidateLinesBelow(line
);
934 void wxTextCtrl::Replace(wxTextPos from
, wxTextPos to
, const wxString
& text
)
936 wxTextCoord colStart
, colEnd
,
940 !PositionToXY(from
, &colStart
, &lineStart
) ||
941 !PositionToXY(to
, &colEnd
, &lineEnd
) )
943 wxFAIL_MSG(_T("invalid range in wxTextCtrl::Replace"));
948 #ifdef WXDEBUG_TEXT_REPLACE
949 // a straighforward (but very inefficient) way of calculating what the new
951 wxString textTotal
= GetValue();
952 wxString
textTotalNew(textTotal
, (size_t)from
);
953 textTotalNew
+= text
;
954 if ( (size_t)to
< textTotal
.length() )
955 textTotalNew
+= textTotal
.c_str() + (size_t)to
;
956 #endif // WXDEBUG_TEXT_REPLACE
958 // remember the old selection and reset it immediately: we must do it
959 // before calling Refresh(anything) as, at least under GTK, this leads to
960 // an _immediate_ repaint (under MSW it is delayed) and hence parts of
961 // text would be redrawn as selected if we didn't reset the selection
962 int selStartOld
= m_selStart
,
963 selEndOld
= m_selEnd
;
968 if ( IsSingleLine() )
970 // replace the part of the text with the new value
971 wxString
valueNew(m_value
, (size_t)from
);
973 // remember it for later use
974 wxCoord startNewText
= GetTextWidth(valueNew
);
977 if ( (size_t)to
< m_value
.length() )
979 valueNew
+= m_value
.c_str() + (size_t)to
;
982 // we usually refresh till the end of line except of the most common case
983 // when some text is appended to the end of the string in which case we
985 wxCoord widthNewText
;
987 if ( (size_t)from
< m_value
.length() )
989 // refresh till the end of line
992 else // text appended, not replaced
994 // refresh only the new text
995 widthNewText
= GetTextWidth(text
);
1000 // force SData().m_colLastVisible update
1001 SData().m_colLastVisible
= -1;
1004 RefreshPixelRange(0, startNewText
, widthNewText
);
1008 //OPT: special case for replacements inside single line?
1011 Join all the lines in the replacement range into one string, then
1012 replace a part of it with the new text and break it into lines again.
1015 // (0) we want to know if this replacement changes the number of rows
1016 // as if it does we need to refresh everything below the changed
1017 // text (it will be shifted...) and we can avoid it if there is no
1019 bool rowsNumberChanged
= false;
1022 const wxArrayString
& linesOld
= GetLines();
1025 for ( line
= lineStart
; line
<= lineEnd
; line
++ )
1027 if ( line
> lineStart
)
1029 // from the previous line
1030 textOrig
+= _T('\n');
1033 textOrig
+= linesOld
[line
];
1036 // we need to append the '\n' for the last line unless there is no
1038 size_t countOld
= linesOld
.GetCount();
1040 // (2) replace text in the combined string
1042 // (2a) leave the part before replaced area unchanged
1043 wxString
textNew(textOrig
, colStart
);
1045 // these values will be used to refresh the changed area below
1046 wxCoord widthNewText
,
1047 startNewText
= GetTextWidth(textNew
);
1048 if ( (size_t)colStart
== linesOld
[lineStart
].length() )
1050 // text appended, refresh just enough to show the new text
1051 widthNewText
= GetTextWidth(text
.BeforeFirst(_T('\n')));
1053 else // text inserted, refresh till the end of line
1058 // (2b) insert new text
1061 // (2c) and append the end of the old text
1063 // adjust for index shift: to is relative to colStart, not 0
1064 size_t toRel
= (size_t)((to
- from
) + colStart
);
1065 if ( toRel
< textOrig
.length() )
1067 textNew
+= textOrig
.c_str() + toRel
;
1070 // (3) break it into lines
1072 wxArrayString lines
;
1073 const wxChar
*curLineStart
= textNew
.c_str();
1074 for ( const wxChar
*p
= textNew
.c_str(); ; p
++ )
1076 // end of line/text?
1077 if ( !*p
|| *p
== _T('\n') )
1079 lines
.Add(wxString(curLineStart
, p
));
1083 curLineStart
= p
+ 1;
1087 #ifdef WXDEBUG_TEXT_REPLACE
1088 // (3a) all empty tokens should be counted as replacing with "foo" and
1089 // with "foo\n" should have different effects
1090 wxArrayString lines2
= wxStringTokenize(textNew
, _T("\n"),
1091 wxTOKEN_RET_EMPTY_ALL
);
1093 if ( lines2
.IsEmpty() )
1095 lines2
.Add(wxEmptyString
);
1098 wxASSERT_MSG( lines
.GetCount() == lines2
.GetCount(),
1099 _T("Replace() broken") );
1100 for ( size_t n
= 0; n
< lines
.GetCount(); n
++ )
1102 wxASSERT_MSG( lines
[n
] == lines2
[n
], _T("Replace() broken") );
1104 #endif // WXDEBUG_TEXT_REPLACE
1106 // (3b) special case: if we replace everything till the end we need to
1107 // keep an empty line or the lines would disappear completely
1108 // (this also takes care of never leaving m_lines empty)
1109 if ( ((size_t)lineEnd
== countOld
- 1) && lines
.IsEmpty() )
1111 lines
.Add(wxEmptyString
);
1114 size_t nReplaceCount
= lines
.GetCount(),
1117 // (4) merge into the array
1120 for ( line
= lineStart
; line
<= lineEnd
; line
++, nReplaceLine
++ )
1122 if ( nReplaceLine
< nReplaceCount
)
1124 // we have the replacement line for this one
1125 if ( ReplaceLine(line
, lines
[nReplaceLine
]) )
1127 rowsNumberChanged
= true;
1130 UpdateMaxWidth(line
);
1132 else // no more replacement lines
1134 // (4b) delete all extra lines (note that we need to delete
1135 // them backwards because indices shift while we do it)
1136 bool deletedLongestLine
= false;
1137 for ( wxTextCoord lineDel
= lineEnd
; lineDel
>= line
; lineDel
-- )
1139 if ( lineDel
== MData().m_lineLongest
)
1141 // we will need to recalc the max line width
1142 deletedLongestLine
= true;
1145 RemoveLine(lineDel
);
1148 if ( deletedLongestLine
)
1153 // even the line number changed
1154 rowsNumberChanged
= true;
1156 // update line to exit the loop
1161 // (4c) insert the new lines
1162 if ( nReplaceLine
< nReplaceCount
)
1164 // even the line number changed
1165 rowsNumberChanged
= true;
1169 InsertLine(++lineEnd
, lines
[nReplaceLine
++]);
1171 UpdateMaxWidth(lineEnd
);
1173 while ( nReplaceLine
< nReplaceCount
);
1176 // (5) now refresh the changed area
1178 // update the (cached) last position first as refresh functions use it
1179 m_posLast
+= text
.length() - to
+ from
;
1181 // we may optimize refresh if the number of rows didn't change - but if
1182 // it did we have to refresh everything below the part we chanegd as
1183 // well as it might have moved
1184 if ( !rowsNumberChanged
)
1186 // refresh the line we changed
1189 RefreshPixelRange(lineStart
++, startNewText
, widthNewText
);
1193 //OPT: we shouldn't refresh the unchanged part of the line in
1194 // this case, but instead just refresh the tail of it - the
1195 // trouble is that we don't know here where does this tail
1199 // number of rows didn't change, refresh the updated rows and the
1201 if ( lineStart
<= lineEnd
)
1202 RefreshLineRange(lineStart
, lineEnd
);
1204 else // rows number did change
1208 // refresh only part of the first line
1209 RefreshPixelRange(lineStart
++, startNewText
, widthNewText
);
1211 //else: we have to refresh everything as some part of the text
1212 // could be in the previous row before but moved to the next
1213 // one now (due to word wrap)
1215 wxTextCoord lineEnd
= GetLines().GetCount() - 1;
1216 if ( lineStart
<= lineEnd
)
1217 RefreshLineRange(lineStart
, lineEnd
);
1219 // refresh text rect left below
1220 RefreshLineRange(lineEnd
+ 1, 0);
1222 // the vert scrollbar might [dis]appear
1223 MData().m_updateScrollbarY
= true;
1226 // must recalculate it - will do later
1230 #ifdef WXDEBUG_TEXT_REPLACE
1231 // optimized code above should give the same result as straightforward
1232 // computation in the beginning
1233 wxASSERT_MSG( GetValue() == textTotalNew
, _T("error in Replace()") );
1234 #endif // WXDEBUG_TEXT_REPLACE
1236 // update the current position: note that we always put the cursor at the
1237 // end of the replacement text
1238 DoSetInsertionPoint(from
+ text
.length());
1240 // and the selection: this is complicated by the fact that selection coords
1241 // must be first updated to reflect change in text coords, i.e. if we had
1242 // selection from 17 to 19 and we just removed this range, we don't have to
1243 // refresh anything, so we can't just use ClearSelection() here
1244 if ( selStartOld
!= -1 )
1246 // refresh the parst of the selection outside the changed text (which
1247 // we already refreshed)
1248 if ( selStartOld
< from
)
1249 RefreshTextRange(selStartOld
, from
);
1250 if ( to
< selEndOld
)
1251 RefreshTextRange(to
, selEndOld
);
1255 // now call it to do the rest (not related to refreshing)
1259 void wxTextCtrl::Remove(wxTextPos from
, wxTextPos to
)
1261 // Replace() only works with correctly ordered arguments, so exchange them
1263 OrderPositions(from
, to
);
1265 Replace(from
, to
, wxEmptyString
);
1268 void wxTextCtrl::WriteText(const wxString
& text
)
1270 // replace the selection with the new text
1273 Replace(m_curPos
, m_curPos
, text
);
1276 void wxTextCtrl::AppendText(const wxString
& text
)
1278 SetInsertionPointEnd();
1282 // ----------------------------------------------------------------------------
1284 // ----------------------------------------------------------------------------
1286 void wxTextCtrl::SetInsertionPoint(wxTextPos pos
)
1288 wxCHECK_RET( pos
>= 0 && pos
<= GetLastPosition(),
1289 _T("insertion point position out of range") );
1291 // don't do anything if it didn't change
1292 if ( pos
!= m_curPos
)
1294 DoSetInsertionPoint(pos
);
1297 if ( !IsSingleLine() )
1299 // moving cursor should reset the stored abscissa (even if the cursor
1300 // position didn't actually change!)
1301 MData().m_xCaret
= -1;
1307 void wxTextCtrl::InitInsertionPoint()
1309 // so far always put it in the beginning
1310 DoSetInsertionPoint(0);
1312 // this will also set the selection anchor correctly
1316 void wxTextCtrl::MoveInsertionPoint(wxTextPos pos
)
1318 wxASSERT_MSG( pos
>= 0 && pos
<= GetLastPosition(),
1319 _T("DoSetInsertionPoint() can only be called with valid pos") );
1322 PositionToXY(m_curPos
, &m_curCol
, &m_curRow
);
1325 void wxTextCtrl::DoSetInsertionPoint(wxTextPos pos
)
1327 MoveInsertionPoint(pos
);
1332 void wxTextCtrl::SetInsertionPointEnd()
1334 SetInsertionPoint(GetLastPosition());
1337 wxTextPos
wxTextCtrl::GetInsertionPoint() const
1342 wxTextPos
wxTextCtrl::GetLastPosition() const
1345 if ( IsSingleLine() )
1347 pos
= m_value
.length();
1353 size_t nLineCount
= GetLineCount();
1354 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
1356 // +1 is because the positions at the end of this line and of the
1357 // start of the next one are different
1358 pos
+= GetLines()[nLine
].length() + 1;
1363 // the last position is at the end of the last line, not in the
1364 // beginning of the next line after it
1368 // more probable reason of this would be to forget to update m_posLast
1369 wxASSERT_MSG( pos
== m_posLast
, _T("bug in GetLastPosition()") );
1370 #endif // WXDEBUG_TEXT
1378 // ----------------------------------------------------------------------------
1380 // ----------------------------------------------------------------------------
1382 void wxTextCtrl::GetSelection(wxTextPos
* from
, wxTextPos
* to
) const
1390 wxString
wxTextCtrl::GetSelectionText() const
1394 if ( HasSelection() )
1396 if ( IsSingleLine() )
1398 sel
= m_value
.Mid(m_selStart
, m_selEnd
- m_selStart
);
1402 wxTextCoord colStart
, lineStart
,
1404 PositionToXY(m_selStart
, &colStart
, &lineStart
);
1405 PositionToXY(m_selEnd
, &colEnd
, &lineEnd
);
1407 // as always, we need to check for the special case when the start
1408 // and end line are the same
1409 if ( lineEnd
== lineStart
)
1411 sel
= GetLines()[lineStart
].Mid(colStart
, colEnd
- colStart
);
1413 else // sel on multiple lines
1415 // take the end of the first line
1416 sel
= GetLines()[lineStart
].c_str() + colStart
;
1419 // all intermediate ones
1420 for ( wxTextCoord line
= lineStart
+ 1; line
< lineEnd
; line
++ )
1422 sel
<< GetLines()[line
] << _T('\n');
1425 // and the start of the last one
1426 sel
+= GetLines()[lineEnd
].Left(colEnd
);
1434 void wxTextCtrl::SetSelection(wxTextPos from
, wxTextPos to
)
1436 // selecting till -1 is the same as selecting to the end
1437 if ( to
== -1 && from
!= -1 )
1439 to
= GetLastPosition();
1442 if ( from
== -1 || to
== from
)
1446 else // valid sel range
1448 // remember the 'to' position as the current position, used to move the
1449 // caret there later
1450 wxTextPos toOrig
= to
;
1452 OrderPositions(from
, to
);
1454 wxCHECK_RET( to
<= GetLastPosition(),
1455 _T("invalid range in wxTextCtrl::SetSelection") );
1457 if ( from
!= m_selStart
|| to
!= m_selEnd
)
1459 // we need to use temp vars as RefreshTextRange() may call DoDraw()
1460 // directly and so m_selStart/End must be reset by then
1461 wxTextPos selStartOld
= m_selStart
,
1462 selEndOld
= m_selEnd
;
1467 wxLogTrace(_T("text"), _T("Selection range is %ld-%ld"),
1468 m_selStart
, m_selEnd
);
1470 // refresh only the part of text which became (un)selected if
1472 if ( selStartOld
== m_selStart
)
1474 RefreshTextRange(selEndOld
, m_selEnd
);
1476 else if ( selEndOld
== m_selEnd
)
1478 RefreshTextRange(m_selStart
, selStartOld
);
1482 // OPT: could check for other cases too but it is probably not
1483 // worth it as the two above are the most common ones
1484 if ( selStartOld
!= -1 )
1485 RefreshTextRange(selStartOld
, selEndOld
);
1486 if ( m_selStart
!= -1 )
1487 RefreshTextRange(m_selStart
, m_selEnd
);
1490 // we need to fully repaint the invalidated areas of the window
1491 // before scrolling it (from DoSetInsertionPoint which is typically
1492 // called after SetSelection()), otherwise they may stay unpainted
1493 m_targetWindow
->Update();
1495 //else: nothing to do
1497 // the insertion point is put at the location where the caret was moved
1498 DoSetInsertionPoint(toOrig
);
1502 void wxTextCtrl::ClearSelection()
1504 if ( HasSelection() )
1506 // we need to use temp vars as RefreshTextRange() may call DoDraw()
1507 // directly (see above as well)
1508 wxTextPos selStart
= m_selStart
,
1511 // no selection any more
1515 // refresh the old selection
1516 RefreshTextRange(selStart
, selEnd
);
1519 // the anchor should be moved even if there was no selection previously
1520 m_selAnchor
= m_curPos
;
1523 void wxTextCtrl::RemoveSelection()
1525 if ( !HasSelection() )
1528 Remove(m_selStart
, m_selEnd
);
1531 bool wxTextCtrl::GetSelectedPartOfLine(wxTextCoord line
,
1532 wxTextPos
*start
, wxTextPos
*end
) const
1539 if ( !HasSelection() )
1541 // no selection at all, hence no selection in this line
1545 wxTextCoord lineStart
, colStart
;
1546 PositionToXY(m_selStart
, &colStart
, &lineStart
);
1547 if ( lineStart
> line
)
1549 // this line is entirely above the selection
1553 wxTextCoord lineEnd
, colEnd
;
1554 PositionToXY(m_selEnd
, &colEnd
, &lineEnd
);
1555 if ( lineEnd
< line
)
1557 // this line is entirely below the selection
1561 if ( line
== lineStart
)
1566 *end
= lineEnd
== lineStart
? colEnd
: GetLineLength(line
);
1568 else if ( line
== lineEnd
)
1571 *start
= lineEnd
== lineStart
? colStart
: 0;
1575 else // the line is entirely inside the selection
1580 *end
= GetLineLength(line
);
1586 // ----------------------------------------------------------------------------
1588 // ----------------------------------------------------------------------------
1590 bool wxTextCtrl::IsModified() const
1592 return m_isModified
;
1595 bool wxTextCtrl::IsEditable() const
1597 // disabled control can never be edited
1598 return m_isEditable
&& IsEnabled();
1601 void wxTextCtrl::MarkDirty()
1603 m_isModified
= true;
1606 void wxTextCtrl::DiscardEdits()
1608 m_isModified
= false;
1611 void wxTextCtrl::SetEditable(bool editable
)
1613 if ( editable
!= m_isEditable
)
1615 m_isEditable
= editable
;
1617 // the caret (dis)appears
1620 // the appearance of the control might have changed
1625 // ----------------------------------------------------------------------------
1626 // col/lines <-> position correspondence
1627 // ----------------------------------------------------------------------------
1630 A few remarks about this stuff:
1632 o The numbering of the text control columns/rows starts from 0.
1633 o Start of first line is position 0, its last position is line.length()
1634 o Start of the next line is the last position of the previous line + 1
1637 int wxTextCtrl::GetLineLength(wxTextCoord line
) const
1639 if ( IsSingleLine() )
1641 wxASSERT_MSG( line
== 0, _T("invalid GetLineLength() parameter") );
1643 return m_value
.length();
1647 wxCHECK_MSG( (size_t)line
< GetLineCount(), -1,
1648 _T("line index out of range") );
1650 return GetLines()[line
].length();
1654 wxString
wxTextCtrl::GetLineText(wxTextCoord line
) const
1656 if ( IsSingleLine() )
1658 wxASSERT_MSG( line
== 0, _T("invalid GetLineLength() parameter") );
1664 //this is called during DoGetBestSize
1665 if (line
== 0 && GetLineCount() == 0) return wxEmptyString
;
1667 wxCHECK_MSG( (size_t)line
< GetLineCount(), wxEmptyString
,
1668 _T("line index out of range") );
1670 return GetLines()[line
];
1674 int wxTextCtrl::GetNumberOfLines() const
1676 // there is always 1 line, even if the text is empty
1677 return IsSingleLine() ? 1 : GetLineCount();
1680 wxTextPos
wxTextCtrl::XYToPosition(wxTextCoord x
, wxTextCoord y
) const
1682 // note that this method should accept any values of x and y and return -1
1683 // if they are out of range
1684 if ( IsSingleLine() )
1686 return ( x
> GetLastPosition() || y
> 0 ) ? wxOutOfRangeTextCoord
: x
;
1690 if ( (size_t)y
>= GetLineCount() )
1692 // this position is below the text
1693 return GetLastPosition();
1697 for ( size_t nLine
= 0; nLine
< (size_t)y
; nLine
++ )
1699 // +1 is because the positions at the end of this line and of the
1700 // start of the next one are different
1701 pos
+= GetLines()[nLine
].length() + 1;
1704 // take into account also the position in line
1705 if ( (size_t)x
> GetLines()[y
].length() )
1707 // don't return position in the next line
1708 x
= GetLines()[y
].length();
1715 bool wxTextCtrl::PositionToXY(wxTextPos pos
,
1716 wxTextCoord
*x
, wxTextCoord
*y
) const
1718 if ( IsSingleLine() )
1720 if ( (size_t)pos
> m_value
.length() )
1732 wxTextPos posCur
= 0;
1733 size_t nLineCount
= GetLineCount();
1734 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
1736 // +1 is because the start the start of the next line is one
1737 // position after the end of this one
1738 wxTextPos posNew
= posCur
+ GetLines()[nLine
].length() + 1;
1741 // we've found the line, now just calc the column
1749 wxASSERT_MSG( XYToPosition(pos
- posCur
, nLine
) == pos
,
1750 _T("XYToPosition() or PositionToXY() broken") );
1751 #endif // WXDEBUG_TEXT
1755 else // go further down
1761 // beyond the last line
1766 wxTextCoord
wxTextCtrl::GetRowsPerLine(wxTextCoord line
) const
1768 // a normal line has one row
1769 wxTextCoord numRows
= 1;
1773 // add the number of additional rows
1774 numRows
+= WData().m_linesData
[line
].GetExtraRowCount();
1780 wxTextCoord
wxTextCtrl::GetRowCount() const
1782 wxTextCoord count
= GetLineCount();
1787 count
= GetFirstRowOfLine(count
- 1) +
1788 WData().m_linesData
[count
- 1].GetRowCount();
1794 wxTextCoord
wxTextCtrl::GetRowAfterLine(wxTextCoord line
) const
1799 if ( !WData().IsValidLine(line
) )
1804 return WData().m_linesData
[line
].GetNextRow();
1807 wxTextCoord
wxTextCtrl::GetFirstRowOfLine(wxTextCoord line
) const
1812 if ( !WData().IsValidLine(line
) )
1817 return WData().m_linesData
[line
].GetFirstRow();
1820 bool wxTextCtrl::PositionToLogicalXY(wxTextPos pos
,
1822 wxCoord
*yOut
) const
1824 wxTextCoord col
, line
;
1826 // optimization for special (but common) case when we already have the col
1828 if ( pos
== m_curPos
)
1833 else // must really calculate col/line from pos
1835 if ( !PositionToXY(pos
, &col
, &line
) )
1839 int hLine
= GetLineHeight();
1841 wxString textLine
= GetLineText(line
);
1842 if ( IsSingleLine() || !WrapLines() )
1844 x
= GetTextWidth(textLine
.Left(col
));
1847 else // difficult case: multline control with line wrap
1849 y
= GetFirstRowOfLine(line
);
1851 wxTextCoord colRowStart
;
1852 y
+= GetRowInLine(line
, col
, &colRowStart
);
1856 // x is the width of the text before this position in this row
1857 x
= GetTextWidth(textLine
.Mid(colRowStart
, col
- colRowStart
));
1868 bool wxTextCtrl::PositionToDeviceXY(wxTextPos pos
,
1870 wxCoord
*yOut
) const
1873 if ( !PositionToLogicalXY(pos
, &x
, &y
) )
1876 // finally translate the logical text rect coords into physical client
1878 CalcScrolledPosition(m_rectText
.x
+ x
, m_rectText
.y
+ y
, xOut
, yOut
);
1883 wxPoint
wxTextCtrl::GetCaretPosition() const
1885 wxCoord xCaret
, yCaret
;
1886 if ( !PositionToDeviceXY(m_curPos
, &xCaret
, &yCaret
) )
1888 wxFAIL_MSG( _T("Caret can't be beyond the text!") );
1891 return wxPoint(xCaret
, yCaret
);
1894 // pos may be -1 to show the current position
1895 void wxTextCtrl::ShowPosition(wxTextPos pos
)
1897 bool showCaret
= GetCaret() && GetCaret()->IsVisible();
1901 if ( IsSingleLine() )
1903 ShowHorzPosition(GetTextWidth(m_value
.Left(pos
)));
1905 else if ( MData().m_scrollRangeX
|| MData().m_scrollRangeY
) // multiline with scrollbars
1908 GetViewStart(&xStart
, &yStart
);
1914 PositionToLogicalXY(pos
, &x
, &y
);
1916 wxRect rectText
= GetRealTextArea();
1918 // scroll the position vertically into view: if it is currently above
1919 // it, make it the first one, otherwise the last one
1920 if ( MData().m_scrollRangeY
)
1922 y
/= GetLineHeight();
1928 else // we are currently in or below the view area
1930 // find the last row currently shown
1935 // to find the last row we need to use the generic HitTest
1938 // OPT this is a bit silly: we undo this in HitTest(), so
1939 // it would be better to factor out the common
1940 // functionality into a separate function (OTOH it
1941 // won't probably save us that much)
1942 wxPoint
pt(0, rectText
.height
- 1);
1943 pt
+= GetClientAreaOrigin();
1944 pt
+= m_rectText
.GetPosition();
1945 HitTest(pt
, &col
, &yEnd
);
1947 // find the row inside the line
1948 yEnd
= GetFirstRowOfLine(yEnd
) + GetRowInLine(yEnd
, col
);
1952 // finding the last line is easy if each line has exactly
1954 yEnd
= yStart
+ rectText
.height
/ GetLineHeight() - 1;
1959 // scroll down: the current item should appear at the
1960 // bottom of the view
1961 Scroll(0, y
- (yEnd
- yStart
));
1966 // scroll the position horizontally into view
1968 // we follow what I believe to be Windows behaviour here, that is if
1969 // the position is already entirely in the view we do nothing, but if
1970 // we do have to scroll the window to bring it into view, we scroll it
1971 // not just enough to show the position but slightly more so that this
1972 // position is at 1/3 of the window width from the closest border to it
1973 // (I'm not sure that Windows does exactly this but it looks like this)
1974 if ( MData().m_scrollRangeX
)
1976 // unlike for the rows, xStart doesn't correspond to the starting
1977 // column as they all have different widths, so we need to
1978 // translate everything to pixels
1980 // we want the text between x and x2 be entirely inside the view
1981 // (i.e. the current character)
1983 // make xStart the first visible pixel (and not position)
1984 int wChar
= GetAverageWidth();
1989 // we want the position of this column be 1/3 to the right of
1991 x
-= rectText
.width
/ 3;
1994 Scroll(x
/ wChar
, y
);
1996 else // maybe we're beyond the right border of the view?
1998 wxTextCoord col
, row
;
1999 if ( PositionToXY(pos
, &col
, &row
) )
2001 wxString lineText
= GetLineText(row
);
2002 wxCoord x2
= x
+ GetTextWidth(lineText
[(size_t)col
]);
2003 if ( x2
> xStart
+ rectText
.width
)
2005 // we want the position of this column be 1/3 to the
2006 // left of the right edge, i.e. 2/3 right of the left
2008 x2
-= (2*rectText
.width
)/3;
2011 Scroll(x2
/ wChar
, row
);
2017 //else: multiline but no scrollbars, hence nothing to do
2023 // ----------------------------------------------------------------------------
2025 // ----------------------------------------------------------------------------
2028 TODO: we could have (easy to do) vi-like options for word movement, i.e.
2029 distinguish between inlusive/exclusive words and between words and
2030 WORDS (in vim sense) and also, finally, make the set of characters
2031 which make up a word configurable - currently we use the exclusive
2032 WORDS only (coincidentally, this is what Windows edit control does)
2034 For future references, here is what vim help says:
2036 A word consists of a sequence of letters, digits and underscores, or
2037 a sequence of other non-blank characters, separated with white space
2038 (spaces, tabs, <EOL>). This can be changed with the 'iskeyword'
2041 A WORD consists of a sequence of non-blank characters, separated with
2042 white space. An empty line is also considered to be a word and a
2046 static inline bool IsWordChar(wxChar ch
)
2048 return !wxIsspace(ch
);
2051 wxTextPos
wxTextCtrl::GetWordStart() const
2053 if ( m_curPos
== -1 || m_curPos
== 0 )
2056 if ( m_curCol
== 0 )
2058 // go to the end of the previous line
2059 return m_curPos
- 1;
2062 // it shouldn't be possible to learn where the word starts in the password
2067 // start at the previous position
2068 const wxChar
*p0
= GetLineText(m_curRow
).c_str();
2069 const wxChar
*p
= p0
+ m_curCol
- 1;
2071 // find the end of the previous word
2072 while ( (p
> p0
) && !IsWordChar(*p
) )
2075 // now find the beginning of this word
2076 while ( (p
> p0
) && IsWordChar(*p
) )
2079 // we might have gone too far
2080 if ( !IsWordChar(*p
) )
2083 return (m_curPos
- m_curCol
) + p
- p0
;
2086 wxTextPos
wxTextCtrl::GetWordEnd() const
2088 if ( m_curPos
== -1 )
2091 wxString line
= GetLineText(m_curRow
);
2092 if ( (size_t)m_curCol
== line
.length() )
2094 // if we're on the last position in the line, go to the next one - if
2096 wxTextPos pos
= m_curPos
;
2097 if ( pos
< GetLastPosition() )
2103 // it shouldn't be possible to learn where the word ends in the password
2106 return GetLastPosition();
2108 // start at the current position
2109 const wxChar
*p0
= line
.c_str();
2110 const wxChar
*p
= p0
+ m_curCol
;
2112 // find the start of the next word
2113 while ( *p
&& !IsWordChar(*p
) )
2116 // now find the end of it
2117 while ( *p
&& IsWordChar(*p
) )
2120 // and find the start of the next word
2121 while ( *p
&& !IsWordChar(*p
) )
2124 return (m_curPos
- m_curCol
) + p
- p0
;
2127 // ----------------------------------------------------------------------------
2129 // ----------------------------------------------------------------------------
2131 void wxTextCtrl::Copy()
2134 if ( HasSelection() )
2136 wxClipboardLocker clipLock
;
2138 // wxTextFile::Translate() is needed to transform all '\n' into "\r\n"
2139 wxString text
= wxTextFile::Translate(GetTextToShow(GetSelectionText()));
2140 wxTextDataObject
*data
= new wxTextDataObject(text
);
2141 wxTheClipboard
->SetData(data
);
2143 #endif // wxUSE_CLIPBOARD
2146 void wxTextCtrl::Cut()
2151 bool wxTextCtrl::DoCut()
2153 if ( !HasSelection() )
2163 void wxTextCtrl::Paste()
2168 bool wxTextCtrl::DoPaste()
2171 wxClipboardLocker clipLock
;
2173 wxTextDataObject data
;
2174 if ( wxTheClipboard
->IsSupported(data
.GetFormat())
2175 && wxTheClipboard
->GetData(data
) )
2177 // reverse transformation: '\r\n\" -> '\n'
2178 wxString text
= wxTextFile::Translate(data
.GetText(),
2179 wxTextFileType_Unix
);
2180 if ( !text
.empty() )
2187 #endif // wxUSE_CLIPBOARD
2192 // ----------------------------------------------------------------------------
2194 // ----------------------------------------------------------------------------
2196 wxTextCtrlInsertCommand
*
2197 wxTextCtrlCommandProcessor::IsInsertCommand(wxCommand
*command
)
2199 return (wxTextCtrlInsertCommand
*)
2200 (command
&& (command
->GetName() == wxTEXT_COMMAND_INSERT
)
2204 void wxTextCtrlCommandProcessor::Store(wxCommand
*command
)
2206 wxTextCtrlInsertCommand
*cmdIns
= IsInsertCommand(command
);
2209 if ( IsCompressing() )
2211 wxTextCtrlInsertCommand
*
2212 cmdInsLast
= IsInsertCommand(GetCurrentCommand());
2214 // it is possible that we don't have any last command at all if,
2215 // for example, it was undone since the last Store(), so deal with
2219 cmdInsLast
->Append(cmdIns
);
2223 // don't need to call the base class version
2228 // append the following insert commands to this one
2229 m_compressInserts
= true;
2231 // let the base class version will do the job normally
2233 else // not an insert command
2235 // stop compressing insert commands - this won't work with the last
2236 // command not being an insert one anyhow
2239 // let the base class version will do the job normally
2242 wxCommandProcessor::Store(command
);
2245 void wxTextCtrlInsertCommand::Append(wxTextCtrlInsertCommand
*other
)
2247 m_text
+= other
->m_text
;
2250 bool wxTextCtrlInsertCommand::CanUndo() const
2252 return m_from
!= -1;
2255 bool wxTextCtrlInsertCommand::Do(wxTextCtrl
*text
)
2257 // the text is going to be inserted at the current position, remember where
2259 m_from
= text
->GetInsertionPoint();
2261 // and now do insert it
2262 text
->WriteText(m_text
);
2267 bool wxTextCtrlInsertCommand::Undo(wxTextCtrl
*text
)
2269 wxCHECK_MSG( CanUndo(), false, _T("impossible to undo insert cmd") );
2271 // remove the text from where we inserted it
2272 text
->Remove(m_from
, m_from
+ m_text
.length());
2277 bool wxTextCtrlRemoveCommand::CanUndo() const
2279 // if we were executed, we should have the text we removed
2280 return !m_textDeleted
.empty();
2283 bool wxTextCtrlRemoveCommand::Do(wxTextCtrl
*text
)
2285 text
->SetSelection(m_from
, m_to
);
2286 m_textDeleted
= text
->GetSelectionText();
2287 text
->RemoveSelection();
2292 bool wxTextCtrlRemoveCommand::Undo(wxTextCtrl
*text
)
2294 // it is possible that the text was deleted and that we can't restore text
2295 // at the same position we removed it any more
2296 wxTextPos posLast
= text
->GetLastPosition();
2297 text
->SetInsertionPoint(m_from
> posLast
? posLast
: m_from
);
2298 text
->WriteText(m_textDeleted
);
2303 void wxTextCtrl::Undo()
2305 // the caller must check it
2306 wxASSERT_MSG( CanUndo(), _T("can't call Undo() if !CanUndo()") );
2308 m_cmdProcessor
->Undo();
2311 void wxTextCtrl::Redo()
2313 // the caller must check it
2314 wxASSERT_MSG( CanRedo(), _T("can't call Undo() if !CanUndo()") );
2316 m_cmdProcessor
->Redo();
2319 bool wxTextCtrl::CanUndo() const
2321 return IsEditable() && m_cmdProcessor
->CanUndo();
2324 bool wxTextCtrl::CanRedo() const
2326 return IsEditable() && m_cmdProcessor
->CanRedo();
2329 // ----------------------------------------------------------------------------
2331 // ----------------------------------------------------------------------------
2333 wxSize
wxTextCtrl::DoGetBestClientSize() const
2335 // when we're called for the very first time from Create() we must
2336 // calculate the font metrics here because we can't do it before calling
2337 // Create() (there is no window yet and wxGTK crashes) but we need them
2339 if ( m_heightLine
== -1 )
2341 wxConstCast(this, wxTextCtrl
)->RecalcFontMetrics();
2345 GetTextExtent(GetTextToShow(GetLineText(0)), &w
, &h
);
2347 int wChar
= GetAverageWidth(),
2348 hChar
= GetLineHeight();
2350 int widthMin
= wxMax(10*wChar
, 100);
2356 if ( !IsSingleLine() )
2358 // let the control have a reasonable number of lines
2359 int lines
= GetNumberOfLines();
2362 else if ( lines
> 10 )
2369 rectText
.height
= h
;
2370 wxRect rectTotal
= GetRenderer()->GetTextTotalArea(this, rectText
);
2371 return wxSize(rectTotal
.width
, rectTotal
.height
);
2374 void wxTextCtrl::UpdateTextRect()
2376 wxRect
rectTotal(GetClientSize());
2377 wxCoord
*extraSpace
= WrapLines() ? &WData().m_widthMark
: NULL
;
2378 m_rectText
= GetRenderer()->GetTextClientArea(this, rectTotal
, extraSpace
);
2380 // code elsewhere is confused by negative rect size
2381 if ( m_rectText
.width
<= 0 )
2382 m_rectText
.width
= 1;
2383 if ( m_rectText
.height
<= 0 )
2384 m_rectText
.height
= 1;
2386 if ( !IsSingleLine() )
2388 // invalidate it so that GetRealTextArea() will recalc it
2389 MData().m_rectTextReal
.width
= 0;
2391 // only scroll this rect when the window is scrolled: note that we have
2392 // to scroll not only the text but the line wrap marks too if we show
2394 wxRect rectText
= GetRealTextArea();
2395 if ( extraSpace
&& *extraSpace
)
2397 rectText
.width
+= *extraSpace
;
2399 SetTargetRect(rectText
);
2401 // relayout all lines
2404 WData().m_rowFirstInvalid
= 0;
2406 // increase timestamp: this means that the lines which had been
2407 // laid out before will be relayd out the next time LayoutLines()
2408 // is called because their timestamp will be smaller than the
2410 WData().m_timestamp
++;
2414 UpdateLastVisible();
2417 void wxTextCtrl::UpdateLastVisible()
2419 // this method is only used for horizontal "scrollbarless" scrolling which
2420 // is used only with single line controls
2421 if ( !IsSingleLine() )
2424 // use (efficient) HitTestLine to find the last visible character
2425 wxString text
= m_value
.Mid((size_t)SData().m_colStart
/* to the end */);
2427 switch ( HitTestLine(text
, m_rectText
.width
, &col
) )
2429 case wxTE_HT_BEYOND
:
2430 // everything is visible
2431 SData().m_colLastVisible
= text
.length();
2434 SData().m_posLastVisible
= -1;
2438 case wxTE_HT_BEFORE:
2442 wxFAIL_MSG(_T("unexpected HitTestLine() return value"));
2445 case wxTE_HT_ON_TEXT
:
2448 // the last entirely seen character is the previous one because
2449 // this one is only partly visible - unless the width of the
2450 // string is exactly the max width
2451 SData().m_posLastVisible
= GetTextWidth(text
.Truncate(col
+ 1));
2452 if ( SData().m_posLastVisible
> m_rectText
.width
)
2454 // this character is not entirely visible, take the
2459 SData().m_posLastVisible
= -1;
2461 //else: we can just see it
2463 SData().m_colLastVisible
= col
;
2468 // calculate the width of the text really shown
2469 if ( SData().m_posLastVisible
== -1 )
2471 SData().m_posLastVisible
= GetTextWidth(text
.Truncate(SData().m_colLastVisible
+ 1));
2474 // current value is relative the start of the string text which starts at
2475 // SData().m_colStart, we need an absolute offset into string
2476 SData().m_colLastVisible
+= SData().m_colStart
;
2478 wxLogTrace(_T("text"), _T("Last visible column/position is %d/%ld"),
2479 (int) SData().m_colLastVisible
, (long) SData().m_posLastVisible
);
2482 void wxTextCtrl::OnSize(wxSizeEvent
& event
)
2486 if ( !IsSingleLine() )
2489 // update them immediately because if we are called for the first time,
2490 // we need to create them in order for the base class version to
2491 // position the scrollbars correctly - if we don't do it now, it won't
2492 // happen at all if we don't get more size events
2496 MData().m_updateScrollbarX
=
2497 MData().m_updateScrollbarY
= true;
2503 wxCoord
wxTextCtrl::GetTotalWidth() const
2506 CalcUnscrolledPosition(m_rectText
.width
, 0, &w
, NULL
);
2510 wxCoord
wxTextCtrl::GetTextWidth(const wxString
& text
) const
2513 GetTextExtent(GetTextToShow(text
), &w
, NULL
);
2517 wxRect
wxTextCtrl::GetRealTextArea() const
2519 // for single line text control it's just the same as text rect
2520 if ( IsSingleLine() )
2523 // the real text area always holds an entire number of lines, so the only
2524 // difference with the text area is a narrow strip along the bottom border
2525 wxRect rectText
= MData().m_rectTextReal
;
2526 if ( !rectText
.width
)
2529 rectText
= m_rectText
;
2531 // when we're called for the very first time, the line height might not
2532 // had been calculated yet, so do get it now
2533 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
2534 self
->RecalcFontMetrics();
2536 int hLine
= GetLineHeight();
2537 rectText
.height
= (m_rectText
.height
/ hLine
) * hLine
;
2540 self
->MData().m_rectTextReal
= rectText
;
2546 wxTextCoord
wxTextCtrl::GetRowInLine(wxTextCoord line
,
2548 wxTextCoord
*colRowStart
) const
2550 wxASSERT_MSG( WrapLines(), _T("shouldn't be called") );
2552 const wxWrappedLineData
& lineData
= WData().m_linesData
[line
];
2554 if ( !WData().IsValidLine(line
) )
2557 // row is here counted a bit specially: 0 is the 2nd row of the line (1st
2560 rowMax
= lineData
.GetExtraRowCount();
2564 while ( (row
< rowMax
) && (col
>= lineData
.GetExtraRowStart(row
)) )
2567 // it's ok here that row is 1 greater than needed: like this, it is
2568 // counted as a normal (and not extra) row
2570 //else: only one row anyhow
2574 // +1 because we need a real row number, not the extra row one
2575 *colRowStart
= lineData
.GetRowStart(row
);
2577 // this can't happen, of course
2578 wxASSERT_MSG( *colRowStart
<= col
, _T("GetRowInLine() is broken") );
2584 void wxTextCtrl::LayoutLine(wxTextCoord line
, wxWrappedLineData
& lineData
) const
2586 // FIXME: this uses old GetPartOfWrappedLine() which is not used anywhere
2587 // else now and has rather awkward interface for our needs here
2589 lineData
.m_rowsStart
.Empty();
2590 lineData
.m_rowsWidth
.Empty();
2592 const wxString
& text
= GetLineText(line
);
2594 size_t colRowStart
= 0;
2597 size_t lenRow
= GetPartOfWrappedLine
2599 text
.c_str() + colRowStart
,
2603 // remember the start of this row (not for the first one as
2604 // it's always 0) and its width
2606 lineData
.m_rowsStart
.Add(colRowStart
);
2607 lineData
.m_rowsWidth
.Add(widthRow
);
2609 colRowStart
+= lenRow
;
2611 while ( colRowStart
< text
.length() );
2613 // put the current timestamp on it
2614 lineData
.m_timestamp
= WData().m_timestamp
;
2617 void wxTextCtrl::LayoutLines(wxTextCoord lineLast
) const
2619 wxASSERT_MSG( WrapLines(), _T("should only be used for line wrapping") );
2621 // if we were called, some line was dirty and if it was dirty we must have
2622 // had m_rowFirstInvalid set to something too
2623 wxTextCoord lineFirst
= WData().m_rowFirstInvalid
;
2624 wxASSERT_MSG( lineFirst
!= -1, _T("nothing to layout?") );
2626 wxTextCoord rowFirst
, rowCur
;
2629 // start after the last known valid line
2630 const wxWrappedLineData
& lineData
= WData().m_linesData
[lineFirst
- 1];
2631 rowFirst
= lineData
.GetFirstRow() + lineData
.GetRowCount();
2633 else // no valid lines, start at row 0
2639 for ( wxTextCoord line
= lineFirst
; line
<= lineLast
; line
++ )
2641 // set the starting row for this line
2642 wxWrappedLineData
& lineData
= WData().m_linesData
[line
];
2643 lineData
.m_rowFirst
= rowCur
;
2645 // had the line been already broken into rows?
2647 // if so, compare its timestamp with the current one: if nothing has
2648 // been changed, don't relayout it
2649 if ( !lineData
.IsValid() ||
2650 (lineData
.m_timestamp
< WData().m_timestamp
) )
2652 // now do break it in rows
2653 LayoutLine(line
, lineData
);
2656 rowCur
+= lineData
.GetRowCount();
2659 // we are now valid at least up to this line, but if it is the last one we
2660 // just don't have any more invalid rows at all
2661 if ( (size_t)lineLast
== WData().m_linesData
.GetCount() -1 )
2666 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
2667 self
->WData().m_rowFirstInvalid
= lineLast
;
2669 // also refresh the line end indicators (FIXME shouldn't do it always!)
2670 self
->RefreshLineWrapMarks(rowFirst
, rowCur
);
2673 size_t wxTextCtrl::GetPartOfWrappedLine(const wxChar
* text
,
2674 wxCoord
*widthReal
) const
2676 // this function is slow, it shouldn't be called unless really needed
2677 wxASSERT_MSG( WrapLines(), _T("shouldn't be called") );
2681 wxCoord wReal
= wxDefaultCoord
;
2682 switch ( HitTestLine(s
, m_rectText
.width
, &col
) )
2685 case wxTE_HT_BEFORE:
2689 wxFAIL_MSG(_T("unexpected HitTestLine() return value"));
2692 case wxTE_HT_ON_TEXT
:
2695 // the last entirely seen character is the previous one because
2696 // this one is only partly visible - unless the width of the
2697 // string is exactly the max width
2698 wReal
= GetTextWidth(s
.Truncate(col
+ 1));
2699 if ( wReal
> m_rectText
.width
)
2701 // this character is not entirely visible, take the
2706 wReal
= wxDefaultCoord
;
2708 //else: we can just see it
2710 // wrap at any character or only at words boundaries?
2711 if ( !(GetWindowStyle() & wxTE_CHARWRAP
) )
2713 // find the (last) not word char before this word
2714 wxTextCoord colWordStart
;
2715 for ( colWordStart
= col
;
2716 colWordStart
&& IsWordChar(s
[(size_t)colWordStart
]);
2720 if ( colWordStart
> 0 )
2722 if ( colWordStart
!= col
)
2724 // will have to recalc the real width
2725 wReal
= wxDefaultCoord
;
2730 //else: only a single word, have to wrap it here
2735 case wxTE_HT_BEYOND
:
2739 // we return the number of characters, not the index of the last one
2740 if ( (size_t)col
< s
.length() )
2742 // but don't return more than this (empty) string has
2748 if ( wReal
== wxDefaultCoord
)
2750 // calc it if not done yet
2751 wReal
= GetTextWidth(s
.Truncate(col
));
2757 // VZ: old, horribly inefficient code which can still be used for checking
2758 // the result (in line, not word, wrap mode only) - to be removed later
2760 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
2761 wxClientDC
dc(self
);
2762 dc
.SetFont(GetFont());
2763 self
->DoPrepareDC(dc
);
2765 wxCoord widthMax
= m_rectText
.width
;
2767 // the text which we can keep in this ROW
2770 for ( wOld
= w
= 0; *text
&& (w
<= widthMax
); )
2774 dc
.GetTextExtent(str
, &w
, NULL
);
2779 // if we wrapped, the last letter was one too much
2780 if ( str
.length() > 1 )
2783 str
.erase(str
.length() - 1, 1);
2785 else // but always keep at least one letter in each row
2787 // the real width then is the last value of w and not teh one
2792 else // we didn't wrap
2797 wxASSERT( col
== str
.length() );
2801 wxASSERT( *widthReal
== wOld
);
2806 //return str.length();
2812 // OPT: this function is called a lot - would be nice to optimize it but I
2813 // don't really know how yet
2814 wxTextCtrlHitTestResult
wxTextCtrl::HitTestLine(const wxString
& line
,
2816 wxTextCoord
*colOut
) const
2818 wxTextCtrlHitTestResult res
= wxTE_HT_ON_TEXT
;
2821 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
2822 wxClientDC
dc(self
);
2823 dc
.SetFont(GetFont());
2824 self
->DoPrepareDC(dc
);
2827 dc
.GetTextExtent(line
, &width
, NULL
);
2830 // clicking beyond the end of line is equivalent to clicking at
2831 // the end of it, so return the last line column
2832 col
= line
.length();
2835 // unless the line is empty and so doesn't have any column at all -
2836 // in this case return 0, what else can we do?
2840 res
= wxTE_HT_BEYOND
;
2846 res
= wxTE_HT_BEFORE
;
2848 else // we're inside the line
2850 // now calculate the column: first, approximate it with fixed-width
2851 // value and then calculate the correct value iteratively: note that
2852 // we use the first character of the line instead of (average)
2853 // GetCharWidth(): it is common to have lines of dashes, for example,
2854 // and this should give us much better approximation in such case
2856 // OPT: maybe using (cache) m_widthAvg would be still faster? profile!
2857 dc
.GetTextExtent(line
[0], &width
, NULL
);
2864 else if ( (size_t)col
> line
.length() )
2866 col
= line
.length();
2869 // matchDir is the direction in which we should move to reach the
2870 // character containing the given position
2876 } matchDir
= Match_None
;
2879 // check that we didn't go beyond the line boundary
2885 if ( (size_t)col
> line
.length() )
2887 col
= line
.length();
2891 wxString
strBefore(line
, (size_t)col
);
2892 dc
.GetTextExtent(strBefore
, &width
, NULL
);
2895 if ( matchDir
== Match_Right
)
2897 // we were going to the right and, finally, moved beyond
2898 // the original position - stop on the previous one
2904 if ( matchDir
== Match_None
)
2906 // we just started iterating, now we know that we should
2908 matchDir
= Match_Left
;
2910 //else: we are still to the right of the target, continue
2914 // invert the logic above
2915 if ( matchDir
== Match_Left
)
2917 // with the exception that we don't need to backtrack here
2921 if ( matchDir
== Match_None
)
2924 matchDir
= Match_Right
;
2928 // this is not supposed to happen
2929 wxASSERT_MSG( matchDir
, _T("logic error in wxTextCtrl::HitTest") );
2931 if ( matchDir
== Match_Right
)
2938 // check that we calculated it correctly
2940 if ( res
== wxTE_HT_ON_TEXT
)
2943 wxString text
= line
.Left(col
);
2944 dc
.GetTextExtent(text
, &width1
, NULL
);
2945 if ( (size_t)col
< line
.length() )
2950 dc
.GetTextExtent(text
, &width2
, NULL
);
2952 wxASSERT_MSG( (width1
<= x
) && (x
< width2
),
2953 _T("incorrect HitTestLine() result") );
2955 else // we return last char
2957 wxASSERT_MSG( x
>= width1
, _T("incorrect HitTestLine() result") );
2960 #endif // WXDEBUG_TEXT
2968 wxTextCtrlHitTestResult
wxTextCtrl::HitTest(const wxPoint
& pt
, long *pos
) const
2971 wxTextCtrlHitTestResult rc
= HitTest(pt
, &x
, &y
);
2972 if ( rc
!= wxTE_HT_UNKNOWN
&& pos
)
2974 *pos
= XYToPosition(x
, y
);
2980 wxTextCtrlHitTestResult
wxTextCtrl::HitTest(const wxPoint
& pos
,
2981 wxTextCoord
*colOut
,
2982 wxTextCoord
*rowOut
) const
2984 return HitTest2(pos
.y
, pos
.x
, 0, rowOut
, colOut
, NULL
, NULL
);
2987 wxTextCtrlHitTestResult
wxTextCtrl::HitTestLogical(const wxPoint
& pos
,
2988 wxTextCoord
*colOut
,
2989 wxTextCoord
*rowOut
) const
2991 return HitTest2(pos
.y
, pos
.x
, 0, rowOut
, colOut
, NULL
, NULL
, false);
2994 wxTextCtrlHitTestResult
wxTextCtrl::HitTest2(wxCoord y0
,
2997 wxTextCoord
*rowOut
,
2998 wxTextCoord
*colStart
,
2999 wxTextCoord
*colEnd
,
3000 wxTextCoord
*colRowStartOut
,
3001 bool deviceCoords
) const
3003 // is the point in the text area or to the right or below it?
3004 wxTextCtrlHitTestResult res
= wxTE_HT_ON_TEXT
;
3006 // translate the window coords x0 and y0 into the client coords in the text
3007 // area by adjusting for both the client and text area offsets (unless this
3008 // was already done)
3012 wxPoint pt
= GetClientAreaOrigin() + m_rectText
.GetPosition();
3013 CalcUnscrolledPosition(x10
- pt
.x
, y0
- pt
.y
, &x1
, &y
);
3021 // calculate the row (it is really a LINE, not a ROW)
3024 // these vars are used only for WrapLines() case
3025 wxTextCoord colRowStart
= 0;
3028 if ( colRowStartOut
)
3029 *colRowStartOut
= 0;
3031 int hLine
= GetLineHeight();
3034 // and clicking before it is the same as clicking on the first one
3037 res
= wxTE_HT_BEFORE
;
3041 wxTextCoord rowLast
= GetNumberOfLines() - 1;
3043 if ( IsSingleLine() || !WrapLines() )
3045 // in this case row calculation is simple as all lines have the
3046 // same height and so row is the same as line
3047 if ( row
> rowLast
)
3049 // clicking below the text is the same as clicking on the last
3053 res
= wxTE_HT_BELOW
;
3056 else // multline control with line wrap
3058 // use binary search to find the line containing this row
3059 const wxArrayWrappedLinesData
& linesData
= WData().m_linesData
;
3061 hi
= linesData
.GetCount(),
3066 const wxWrappedLineData
& lineData
= linesData
[cur
];
3067 if ( !WData().IsValidLine(cur
) )
3069 wxTextCoord rowFirst
= lineData
.GetFirstRow();
3071 if ( row
< rowFirst
)
3077 // our row is after the first row of the cur line:
3078 // obviously, if cur is the last line, it contains this
3079 // row, otherwise we have to test that it is before the
3080 // first row of the next line
3081 bool found
= cur
== linesData
.GetCount() - 1;
3084 // if the row is beyond the end of text, adjust it to
3085 // be the last one and set res accordingly
3086 if ( (size_t)(row
- rowFirst
) >= lineData
.GetRowCount() )
3088 res
= wxTE_HT_BELOW
;
3090 row
= lineData
.GetRowCount() + rowFirst
- 1;
3093 else // not the last row
3095 const wxWrappedLineData
&
3096 lineNextData
= linesData
[cur
+ 1];
3097 if ( !WData().IsValidLine(cur
+ 1) )
3098 LayoutLines(cur
+ 1);
3099 found
= row
< lineNextData
.GetFirstRow();
3104 colRowStart
= lineData
.GetRowStart(row
- rowFirst
);
3105 rowLen
= lineData
.GetRowLength(row
- rowFirst
,
3106 GetLines()[cur
].length());
3120 if ( res
== wxTE_HT_ON_TEXT
)
3122 // now find the position in the line
3123 wxString lineText
= GetLineText(row
),
3126 if ( colRowStart
|| rowLen
)
3128 // look in this row only, not in whole line
3129 rowText
= lineText
.Mid(colRowStart
, rowLen
);
3133 // just take the whole string
3139 res
= HitTestLine(GetTextToShow(rowText
), x1
, colStart
);
3143 if ( colRowStartOut
)
3145 // give them the column offset in this ROW in pixels
3146 *colRowStartOut
= colRowStart
;
3149 // take into account that the ROW doesn't start in the
3150 // beginning of the LINE
3151 *colStart
+= colRowStart
;
3156 // the hit test result we return is for x1, so throw out
3157 // the result for x2 here
3158 int x2
= x1
+ x20
- x10
;
3159 (void)HitTestLine(GetTextToShow(rowText
), x2
, colEnd
);
3161 *colEnd
+= colRowStart
;
3165 else // before/after vertical text span
3169 // fill the column with the first/last position in the
3170 // corresponding line
3171 if ( res
== wxTE_HT_BEFORE
)
3173 else // res == wxTE_HT_BELOW
3174 *colStart
= GetLineText(GetNumberOfLines() - 1).length();
3180 // give them the row in text coords (as is)
3187 bool wxTextCtrl::GetLineAndRow(wxTextCoord row
,
3188 wxTextCoord
*lineOut
,
3189 wxTextCoord
*rowInLineOut
) const
3197 int nLines
= GetNumberOfLines();
3200 const wxArrayWrappedLinesData
& linesData
= WData().m_linesData
;
3201 for ( line
= 0; line
< nLines
; line
++ )
3203 if ( !WData().IsValidLine(line
) )
3206 if ( row
< linesData
[line
].GetNextRow() )
3208 // we found the right line
3209 rowInLine
= row
- linesData
[line
].GetFirstRow();
3215 if ( line
== nLines
)
3217 // the row is out of range
3221 else // no line wrapping, everything is easy
3223 if ( row
>= nLines
)
3232 *rowInLineOut
= rowInLine
;
3237 // ----------------------------------------------------------------------------
3239 // ----------------------------------------------------------------------------
3242 wxTextCtrl has not one but two scrolling mechanisms: one is semi-automatic
3243 scrolling in both horizontal and vertical direction implemented using
3244 wxScrollHelper and the second one is manual scrolling implemented using
3245 SData().m_ofsHorz and used by the single line controls without scroll bar.
3247 The first version (the standard one) always scrolls by fixed amount which is
3248 fine for vertical scrolling as all lines have the same height but is rather
3249 ugly for horizontal scrolling if proportional font is used. This is why we
3250 manually update and use SData().m_ofsHorz which contains the length of the string
3251 which is hidden beyond the left borde. An important property of text
3252 controls using this kind of scrolling is that an entire number of characters
3253 is always shown and that parts of characters never appear on display -
3254 neither in the leftmost nor rightmost positions.
3256 Once again, for multi line controls SData().m_ofsHorz is always 0 and scrolling is
3257 done as usual for wxScrollWindow.
3260 void wxTextCtrl::ShowHorzPosition(wxCoord pos
)
3262 wxASSERT_MSG( IsSingleLine(), _T("doesn't work for multiline") );
3264 // pos is the logical position to show
3266 // SData().m_ofsHorz is the fisrt logical position shown
3267 if ( pos
< SData().m_ofsHorz
)
3271 HitTestLine(m_value
, pos
, &col
);
3276 wxCoord width
= m_rectText
.width
;
3279 // if we are called from the ctor, m_rectText is not initialized
3280 // yet, so do it now
3282 width
= m_rectText
.width
;
3285 // SData().m_ofsHorz + width is the last logical position shown
3286 if ( pos
> SData().m_ofsHorz
+ width
)
3290 HitTestLine(m_value
, pos
- width
, &col
);
3291 ScrollText(col
+ 1);
3296 // scroll the window horizontally so that the first visible character becomes
3297 // the one at this position
3298 void wxTextCtrl::ScrollText(wxTextCoord col
)
3300 wxASSERT_MSG( IsSingleLine(),
3301 _T("ScrollText() is for single line controls only") );
3303 // never scroll beyond the left border
3307 // OPT: could only get the extent of the part of the string between col
3308 // and SData().m_colStart
3309 wxCoord ofsHorz
= GetTextWidth(GetLineText(0).Left(col
));
3311 if ( ofsHorz
!= SData().m_ofsHorz
)
3313 // remember the last currently used pixel
3314 int posLastVisible
= SData().m_posLastVisible
;
3315 if ( posLastVisible
== -1 )
3317 // this may happen when we're called very early, during the
3318 // controls construction
3319 UpdateLastVisible();
3321 posLastVisible
= SData().m_posLastVisible
;
3324 // NB1: to scroll to the right, offset must be negative, hence the
3325 // order of operands
3326 int dx
= SData().m_ofsHorz
- ofsHorz
;
3328 // NB2: we call Refresh() below which results in a call to
3329 // DoDraw(), so we must update SData().m_ofsHorz before calling it
3330 SData().m_ofsHorz
= ofsHorz
;
3331 SData().m_colStart
= col
;
3333 // after changing m_colStart, recalc the last visible position: we need
3334 // to recalc the last visible position beore scrolling in order to make
3335 // it appear exactly at the right edge of the text area after scrolling
3336 UpdateLastVisible();
3341 // we want to force the update of it after scrolling
3342 SData().m_colLastVisible
= -1;
3346 // scroll only the rectangle inside which there is the text
3347 wxRect rect
= m_rectText
;
3348 rect
.width
= posLastVisible
;
3350 rect
= ScrollNoRefresh(dx
, 0, &rect
);
3353 we need to manually refresh the part which ScrollWindow() doesn't
3354 refresh (with new API this means the part outside the rect returned
3355 by ScrollNoRefresh): indeed, if we had this:
3359 where '*' is text and 'o' is blank area at the end (too small to
3360 hold the next char) then after scrolling by 2 positions to the left
3365 where 'R' is the area refreshed by ScrollWindow() - but we still
3366 need to refresh the 'o' at the end as it may be now big enough to
3367 hold the new character shifted into view.
3369 when we are scrolling to the right, we need to update this rect as
3370 well because it might have contained something before but doesn't
3371 contain anything any more
3374 // we can combine both rectangles into one when scrolling to the left,
3375 // but we need two separate Refreshes() otherwise
3378 // refresh the uncovered part on the left
3379 Refresh(true, &rect
);
3381 // and now the area on the right
3382 rect
.x
= m_rectText
.x
+ posLastVisible
;
3383 rect
.width
= m_rectText
.width
- posLastVisible
;
3385 else // scrolling to the left
3387 // just extend the rect covering the uncovered area to the edge of
3389 rect
.width
+= m_rectText
.width
- posLastVisible
;
3392 Refresh(true, &rect
);
3394 // I don't know exactly why is this needed here but without it we may
3395 // scroll the window again (from the same method) before the previously
3396 // invalidated area is repainted when typing *very* quickly - and this
3397 // may lead to the display corruption
3402 void wxTextCtrl::CalcUnscrolledPosition(int x
, int y
, int *xx
, int *yy
) const
3404 if ( IsSingleLine() )
3406 // we don't use wxScrollHelper
3408 *xx
= x
+ SData().m_ofsHorz
;
3414 // let the base class do it
3415 wxScrollHelper::CalcUnscrolledPosition(x
, y
, xx
, yy
);
3419 void wxTextCtrl::CalcScrolledPosition(int x
, int y
, int *xx
, int *yy
) const
3421 if ( IsSingleLine() )
3423 // we don't use wxScrollHelper
3425 *xx
= x
- SData().m_ofsHorz
;
3431 // let the base class do it
3432 wxScrollHelper::CalcScrolledPosition(x
, y
, xx
, yy
);
3436 void wxTextCtrl::DoPrepareDC(wxDC
& dc
)
3438 // for single line controls we only have to deal with SData().m_ofsHorz and it's
3439 // useless to call base class version as they don't use normal scrolling
3440 if ( IsSingleLine() && SData().m_ofsHorz
)
3442 // adjust the DC origin if the text is shifted
3443 wxPoint pt
= dc
.GetDeviceOrigin();
3444 dc
.SetDeviceOrigin(pt
.x
- SData().m_ofsHorz
, pt
.y
);
3448 wxScrollHelper::DoPrepareDC(dc
);
3452 void wxTextCtrl::UpdateMaxWidth(wxTextCoord line
)
3456 // check if the max width changes after this line was modified
3457 wxCoord widthMaxOld
= MData().m_widthMax
,
3459 GetTextExtent(GetLineText(line
), &width
, NULL
);
3461 if ( line
== MData().m_lineLongest
)
3463 // this line was the longest one, is it still?
3464 if ( width
> MData().m_widthMax
)
3466 MData().m_widthMax
= width
;
3468 else if ( width
< MData().m_widthMax
)
3470 // we need to find the new longest line
3473 //else: its length didn't change, nothing to do
3475 else // it wasn't the longest line, but maybe it became it?
3477 // GetMaxWidth() and not MData().m_widthMax as it might be not calculated yet
3478 if ( width
> GetMaxWidth() )
3480 MData().m_widthMax
= width
;
3481 MData().m_lineLongest
= line
;
3485 MData().m_updateScrollbarX
= MData().m_widthMax
!= widthMaxOld
;
3488 void wxTextCtrl::RecalcFontMetrics()
3490 m_heightLine
= GetCharHeight();
3491 m_widthAvg
= GetCharWidth();
3494 void wxTextCtrl::RecalcMaxWidth()
3496 wxASSERT_MSG( !IsSingleLine(), _T("only used for multiline") );
3498 MData().m_widthMax
= -1;
3499 (void)GetMaxWidth();
3502 wxCoord
wxTextCtrl::GetMaxWidth() const
3504 if ( MData().m_widthMax
== -1 )
3508 // OPT: should we remember the widths of all the lines?
3510 wxTextCtrl
*self
= wxConstCast(this, wxTextCtrl
);
3511 wxClientDC
dc(self
);
3512 dc
.SetFont(GetFont());
3514 self
->MData().m_widthMax
= 0;
3516 size_t count
= GetLineCount();
3517 for ( size_t n
= 0; n
< count
; n
++ )
3520 dc
.GetTextExtent(GetLines()[n
], &width
, NULL
);
3521 if ( width
> MData().m_widthMax
)
3523 // remember the width and the line which has it
3524 self
->MData().m_widthMax
= width
;
3525 self
->MData().m_lineLongest
= n
;
3530 wxASSERT_MSG( MData().m_widthMax
!= -1, _T("should have at least 1 line") );
3532 return MData().m_widthMax
;
3535 void wxTextCtrl::UpdateScrollbars()
3537 wxASSERT_MSG( !IsSingleLine(), _T("only used for multiline") );
3539 wxSize size
= GetRealTextArea().GetSize();
3541 // is our height enough to show all items?
3542 wxTextCoord nRows
= GetRowCount();
3543 wxCoord lineHeight
= GetLineHeight();
3544 bool showScrollbarY
= nRows
*lineHeight
> size
.y
;
3546 // is our width enough to show the longest line?
3547 wxCoord charWidth
, maxWidth
;
3548 bool showScrollbarX
;
3551 charWidth
= GetAverageWidth();
3552 maxWidth
= GetMaxWidth();
3553 showScrollbarX
= maxWidth
> size
.x
;
3555 else // never show the horz scrollbar
3557 // just to suppress compiler warnings about using uninit vars below
3558 charWidth
= maxWidth
= 0;
3560 showScrollbarX
= false;
3563 // calc the scrollbars ranges
3564 int scrollRangeX
= showScrollbarX
3565 ? (maxWidth
+ 2*charWidth
- 1) / charWidth
3567 int scrollRangeY
= showScrollbarY
? nRows
: 0;
3569 int scrollRangeXOld
= MData().m_scrollRangeX
,
3570 scrollRangeYOld
= MData().m_scrollRangeY
;
3571 if ( (scrollRangeY
!= scrollRangeYOld
) || (scrollRangeX
!= scrollRangeXOld
) )
3574 GetViewStart(&x
, &y
);
3577 // we want to leave the scrollbars at the same position which means
3578 // that x and y have to be adjusted as the number of positions may have
3581 // the number of positions is calculated from knowing that last
3582 // position = range - thumbSize and thumbSize == pageSize which is
3583 // equal to the window width / pixelsPerLine
3584 if ( scrollRangeXOld
)
3586 x
*= scrollRangeX
- m_rectText
.width
/ charWidth
;
3587 x
/= scrollRangeXOld
- m_rectText
.width
/ charWidth
;
3590 if ( scrollRangeYOld
)
3591 y
*= scrollRangeY
/ scrollRangeYOld
;
3594 SetScrollbars(charWidth
, lineHeight
,
3595 scrollRangeX
, scrollRangeY
,
3597 true /* no refresh */);
3599 if ( scrollRangeXOld
)
3601 x
*= scrollRangeX
- m_rectText
.width
/ charWidth
;
3602 x
/= scrollRangeXOld
- m_rectText
.width
/ charWidth
;
3606 MData().m_scrollRangeX
= scrollRangeX
;
3607 MData().m_scrollRangeY
= scrollRangeY
;
3609 // bring the current position in view
3613 MData().m_updateScrollbarX
=
3614 MData().m_updateScrollbarY
= false;
3617 void wxTextCtrl::OnInternalIdle()
3619 // notice that single line text control never has scrollbars
3620 if ( !IsSingleLine() &&
3621 (MData().m_updateScrollbarX
|| MData().m_updateScrollbarY
) )
3625 wxControl::OnInternalIdle();
3628 bool wxTextCtrl::SendAutoScrollEvents(wxScrollWinEvent
& event
) const
3630 bool forward
= event
.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN
;
3631 if ( event
.GetOrientation() == wxHORIZONTAL
)
3633 return forward
? m_curCol
<= GetLineLength(m_curRow
) : m_curCol
> 0;
3637 return forward
? m_curRow
< GetNumberOfLines() : m_curRow
> 0;
3641 // ----------------------------------------------------------------------------
3643 // ----------------------------------------------------------------------------
3645 void wxTextCtrl::RefreshSelection()
3647 if ( HasSelection() )
3649 RefreshTextRange(m_selStart
, m_selEnd
);
3653 void wxTextCtrl::RefreshLineRange(wxTextCoord lineFirst
, wxTextCoord lineLast
)
3655 wxASSERT_MSG( lineFirst
<= lineLast
|| !lineLast
,
3656 _T("no lines to refresh") );
3659 // rect.x is already 0
3660 rect
.width
= m_rectText
.width
;
3661 wxCoord h
= GetLineHeight();
3663 wxTextCoord rowFirst
;
3664 if ( lineFirst
< GetNumberOfLines() )
3666 rowFirst
= GetFirstRowOfLine(lineFirst
);
3668 else // lineFirst == GetNumberOfLines()
3670 // lineFirst may be beyond the last line only if we refresh till
3671 // the end, otherwise it's illegal
3672 wxASSERT_MSG( lineFirst
== GetNumberOfLines() && !lineLast
,
3673 _T("invalid line range") );
3675 rowFirst
= GetRowAfterLine(lineFirst
- 1);
3678 rect
.y
= rowFirst
*h
;
3682 // refresh till this line (inclusive)
3683 wxTextCoord rowLast
= GetRowAfterLine(lineLast
);
3685 rect
.height
= (rowLast
- rowFirst
+ 1)*h
;
3687 else // lineLast == 0 means to refresh till the end
3689 // FIXME: calc it exactly
3690 rect
.height
= 32000;
3693 RefreshTextRect(rect
);
3696 void wxTextCtrl::RefreshTextRange(wxTextPos start
, wxTextPos end
)
3698 wxCHECK_RET( start
!= -1 && end
!= -1,
3699 _T("invalid RefreshTextRange() arguments") );
3701 // accept arguments in any order as it is more conenient for the caller
3702 OrderPositions(start
, end
);
3704 // this is acceptable but we don't do anything in this case
3708 wxTextPos colStart
, lineStart
;
3709 if ( !PositionToXY(start
, &colStart
, &lineStart
) )
3711 // the range is entirely beyond the end of the text, nothing to do
3715 wxTextCoord colEnd
, lineEnd
;
3716 if ( !PositionToXY(end
, &colEnd
, &lineEnd
) )
3718 // the range spans beyond the end of text, refresh to the end
3720 lineEnd
= GetNumberOfLines() - 1;
3723 // refresh all lines one by one
3724 for ( wxTextCoord line
= lineStart
; line
<= lineEnd
; line
++ )
3726 // refresh the first line from the start of the range to the end, the
3727 // intermediate ones entirely and the last one from the beginning to
3728 // the end of the range
3729 wxTextPos posStart
= line
== lineStart
? colStart
: 0;
3731 if ( (line
!= lineEnd
) || (colEnd
== -1) )
3733 // intermediate line or the last one but we need to refresh it
3734 // until the end anyhow - do it
3735 posCount
= wxString::npos
;
3739 // refresh just the positions in between the start and the end one
3740 posCount
= colEnd
- posStart
;
3744 RefreshColRange(line
, posStart
, posCount
);
3748 void wxTextCtrl::RefreshColRange(wxTextCoord line
,
3752 wxString text
= GetLineText(line
);
3754 wxASSERT_MSG( (size_t)start
<= text
.length() && count
,
3755 _T("invalid RefreshColRange() parameter") );
3757 RefreshPixelRange(line
,
3758 GetTextWidth(text
.Left((size_t)start
)),
3759 GetTextWidth(text
.Mid((size_t)start
, (size_t)count
)));
3762 // this method accepts "logical" coords in the sense that they are coordinates
3763 // in a logical line but it can span several rows if we wrap lines and
3764 // RefreshPixelRange() will then refresh several rows
3765 void wxTextCtrl::RefreshPixelRange(wxTextCoord line
,
3769 // we will use line text only in line wrap case
3773 text
= GetLineText(line
);
3776 // special case: width == 0 means to refresh till the end of line
3779 // refresh till the end of visible line
3780 width
= GetTotalWidth();
3784 // refresh till the end of text
3785 wxCoord widthAll
= GetTextWidth(text
);
3787 // extend width to the end of ROW
3788 width
= widthAll
- widthAll
% width
+ width
;
3791 // no need to refresh beyond the end of line
3794 //else: just refresh the specified part
3796 wxCoord h
= GetLineHeight();
3799 rect
.y
= GetFirstRowOfLine(line
)*h
;
3804 // (1) skip all rows which we don't touch at all
3805 const wxWrappedLineData
& lineData
= WData().m_linesData
[line
];
3806 if ( !WData().IsValidLine(line
) )
3809 wxCoord wLine
= 0; // suppress compiler warning about uninit var
3810 size_t rowLast
= lineData
.GetRowCount(),
3812 while ( (row
< rowLast
) &&
3813 (rect
.x
> (wLine
= lineData
.GetRowWidth(row
++))) )
3819 // (2) now refresh all lines except the last one: note that the first
3820 // line is refreshed from the given start to the end, all the next
3822 while ( (row
< rowLast
) && (width
> wLine
- rect
.x
) )
3824 rect
.width
= GetTotalWidth() - rect
.x
;
3825 RefreshTextRect(rect
);
3827 width
-= wLine
- rect
.x
;
3831 wLine
= lineData
.GetRowWidth(row
++);
3834 // (3) the code below will refresh the last line
3839 RefreshTextRect(rect
);
3842 void wxTextCtrl::RefreshTextRect(const wxRect
& rectClient
, bool textOnly
)
3845 CalcScrolledPosition(rectClient
.x
, rectClient
.y
, &rect
.x
, &rect
.y
);
3846 rect
.width
= rectClient
.width
;
3847 rect
.height
= rectClient
.height
;
3849 // account for the text area offset
3850 rect
.Offset(m_rectText
.GetPosition());
3852 // don't refresh beyond the text area unless we're refreshing the line wrap
3853 // marks in which case textOnly is false
3856 if ( rect
.GetRight() > m_rectText
.GetRight() )
3858 rect
.SetRight(m_rectText
.GetRight());
3860 if ( rect
.width
<= 0 )
3862 // nothing to refresh
3868 // check the bottom boundary always, even for the line wrap marks
3869 if ( rect
.GetBottom() > m_rectText
.GetBottom() )
3871 rect
.SetBottom(m_rectText
.GetBottom());
3873 if ( rect
.height
<= 0 )
3875 // nothing to refresh
3880 // never refresh before the visible rect
3881 if ( rect
.x
< m_rectText
.x
)
3882 rect
.x
= m_rectText
.x
;
3884 if ( rect
.y
< m_rectText
.y
)
3885 rect
.y
= m_rectText
.y
;
3887 wxLogTrace(_T("text"), _T("Refreshing (%d, %d)-(%d, %d)"),
3888 rect
.x
, rect
.y
, rect
.x
+ rect
.width
, rect
.y
+ rect
.height
);
3890 Refresh(true, &rect
);
3893 void wxTextCtrl::RefreshLineWrapMarks(wxTextCoord rowFirst
,
3894 wxTextCoord rowLast
)
3896 if ( WData().m_widthMark
)
3899 rectMarks
.x
= m_rectText
.width
;
3900 rectMarks
.width
= WData().m_widthMark
;
3901 rectMarks
.y
= rowFirst
*GetLineHeight();
3902 rectMarks
.height
= (rowLast
- rowFirst
)*GetLineHeight();
3904 RefreshTextRect(rectMarks
, false /* don't limit to text area */);
3908 // ----------------------------------------------------------------------------
3910 // ----------------------------------------------------------------------------
3912 void wxTextCtrl::DoDrawBorder(wxDC
& dc
, const wxRect
& rect
)
3914 m_renderer
->DrawTextBorder(dc
, GetBorder(), rect
, GetStateFlags());
3917 // ----------------------------------------------------------------------------
3918 // client area drawing
3919 // ----------------------------------------------------------------------------
3922 Several remarks about wxTextCtrl redraw logic:
3924 1. only the regions which must be updated are redrawn, this means that we
3925 never Refresh() the entire window but use RefreshPixelRange() and
3926 ScrollWindow() which only refresh small parts of it and iterate over the
3927 update region in our DoDraw()
3929 2. the text displayed on the screen is obtained using GetTextToShow(): it
3930 should be used for all drawing/measuring
3933 wxString
wxTextCtrl::GetTextToShow(const wxString
& text
) const
3937 textShown
= wxString(_T('*'), text
.length());
3944 void wxTextCtrl::DoDrawTextInRect(wxDC
& dc
, const wxRect
& rectUpdate
)
3946 // debugging trick to see the update rect visually
3948 static int s_countUpdates
= -1;
3949 if ( s_countUpdates
!= -1 )
3951 wxWindowDC
dc(this);
3952 dc
.SetBrush(*(++s_countUpdates
% 2 ? wxRED_BRUSH
: wxGREEN_BRUSH
));
3953 dc
.SetPen(*wxTRANSPARENT_PEN
);
3954 dc
.DrawRectangle(rectUpdate
);
3956 #endif // WXDEBUG_TEXT
3958 // calculate the range lineStart..lineEnd of lines to redraw
3959 wxTextCoord lineStart
, lineEnd
;
3960 if ( IsSingleLine() )
3967 wxPoint pt
= rectUpdate
.GetPosition();
3968 (void)HitTest(pt
, NULL
, &lineStart
);
3970 pt
.y
+= rectUpdate
.height
;
3971 (void)HitTest(pt
, NULL
, &lineEnd
);
3974 // prepare for drawing
3975 wxCoord hLine
= GetLineHeight();
3977 // these vars will be used for hit testing of the current row
3978 wxCoord y
= rectUpdate
.y
;
3979 const wxCoord x1
= rectUpdate
.x
;
3980 const wxCoord x2
= rectUpdate
.x
+ rectUpdate
.width
;
3983 rectText
.height
= hLine
;
3984 wxCoord yClient
= y
- GetClientAreaOrigin().y
;
3986 // we want to always start at the top of the line, otherwise if we redraw a
3987 // rect whose top is in the middle of a line, we'd draw this line shifted
3988 yClient
-= (yClient
- m_rectText
.y
) % hLine
;
3990 if ( IsSingleLine() )
3992 rectText
.y
= yClient
;
3994 else // multiline, adjust for scrolling
3996 CalcUnscrolledPosition(0, yClient
, NULL
, &rectText
.y
);
3999 wxRenderer
*renderer
= GetRenderer();
4001 // do draw the invalidated parts of each line: note that we iterate here
4002 // over ROWs, not over LINEs
4003 for ( wxTextCoord line
= lineStart
;
4004 y
< rectUpdate
.y
+ rectUpdate
.height
;
4006 rectText
.y
+= hLine
)
4008 // calculate the update rect in text positions for this line
4009 wxTextCoord colStart
, colEnd
, colRowStart
;
4010 wxTextCtrlHitTestResult ht
= HitTest2(y
, x1
, x2
,
4011 &line
, &colStart
, &colEnd
,
4014 if ( (ht
== wxTE_HT_BEYOND
) || (ht
== wxTE_HT_BELOW
) )
4016 wxASSERT_MSG( line
<= lineEnd
, _T("how did we get that far?") );
4018 if ( line
== lineEnd
)
4020 // we redrew everything
4024 // the update rect is beyond the end of line, no need to redraw
4025 // anything on this line - but continue with the remaining ones
4029 // for single line controls we may additionally cut off everything
4030 // which is to the right of the last visible position
4031 if ( IsSingleLine() )
4033 // don't show the columns which are scrolled out to the left
4034 if ( colStart
< SData().m_colStart
)
4035 colStart
= SData().m_colStart
;
4037 // colEnd may be less than colStart if colStart was changed by the
4039 if ( colEnd
< colStart
)
4042 // don't draw the chars beyond the rightmost one
4043 if ( SData().m_colLastVisible
== -1 )
4045 // recalculate this rightmost column
4046 UpdateLastVisible();
4049 if ( colStart
> SData().m_colLastVisible
)
4051 // don't bother redrawing something that is beyond the last
4056 if ( colEnd
> SData().m_colLastVisible
)
4058 colEnd
= SData().m_colLastVisible
;
4062 // extract the part of line we need to redraw
4063 wxString textLine
= GetTextToShow(GetLineText(line
));
4064 wxString text
= textLine
.Mid(colStart
, colEnd
- colStart
+ 1);
4066 // now deal with the selection: only do something if at least part of
4067 // the line is selected
4068 wxTextPos selStart
, selEnd
;
4069 if ( GetSelectedPartOfLine(line
, &selStart
, &selEnd
) )
4071 // and if this part is (at least partly) in the current row
4072 if ( (selStart
<= colEnd
) &&
4073 (selEnd
>= wxMax(colStart
, colRowStart
)) )
4075 // these values are relative to the start of the line while the
4076 // string passed to DrawTextLine() is only part of it, so
4077 // adjust the selection range accordingly
4078 selStart
-= colStart
;
4084 if ( (size_t)selEnd
>= text
.length() )
4085 selEnd
= text
.length();
4089 // reset selStart and selEnd to avoid passing them to
4090 // DrawTextLine() below
4096 // calculate the text coords on screen
4097 wxASSERT_MSG( colStart
>= colRowStart
, _T("invalid string part") );
4098 wxCoord ofsStart
= GetTextWidth(
4099 textLine
.Mid(colRowStart
,
4100 colStart
- colRowStart
));
4101 rectText
.x
= m_rectText
.x
+ ofsStart
;
4102 rectText
.width
= GetTextWidth(text
);
4105 renderer
->DrawTextLine(dc
, text
, rectText
, selStart
, selEnd
,
4107 wxLogTrace(_T("text"), _T("Line %ld: positions %ld-%ld redrawn."),
4108 line
, colStart
, colEnd
);
4112 void wxTextCtrl::DoDrawLineWrapMarks(wxDC
& dc
, const wxRect
& rectUpdate
)
4114 wxASSERT_MSG( WrapLines() && WData().m_widthMark
,
4115 _T("shouldn't be called at all") );
4117 wxRenderer
*renderer
= GetRenderer();
4120 rectMark
.x
= rectUpdate
.x
;
4121 rectMark
.width
= rectUpdate
.width
;
4122 wxCoord yTop
= GetClientAreaOrigin().y
;
4123 CalcUnscrolledPosition(0, rectUpdate
.y
- yTop
, NULL
, &rectMark
.y
);
4124 wxCoord hLine
= GetLineHeight();
4125 rectMark
.height
= hLine
;
4127 wxTextCoord line
, rowInLine
;
4130 CalcUnscrolledPosition(0, rectUpdate
.GetBottom() - yTop
, NULL
, &yBottom
);
4131 for ( ; rectMark
.y
< yBottom
; rectMark
.y
+= hLine
)
4133 if ( !GetLineAndRow(rectMark
.y
/ hLine
, &line
, &rowInLine
) )
4135 // we went beyond the end of text
4139 // is this row continued on the next one?
4140 if ( !WData().m_linesData
[line
].IsLastRow(rowInLine
) )
4142 renderer
->DrawLineWrapMark(dc
, rectMark
);
4147 void wxTextCtrl::DoDraw(wxControlRenderer
*renderer
)
4149 // hide the caret while we're redrawing the window and show it after we are
4151 wxCaretSuspend
cs(this);
4154 wxDC
& dc
= renderer
->GetDC();
4155 dc
.SetFont(GetFont());
4156 dc
.SetTextForeground(GetForegroundColour());
4158 // get the intersection of the update region with the text area: note that
4159 // the update region is in window coords and text area is in the client
4160 // ones, so it must be shifted before computing intersection
4161 wxRegion rgnUpdate
= GetUpdateRegion();
4163 wxRect rectTextArea
= GetRealTextArea();
4164 wxPoint pt
= GetClientAreaOrigin();
4165 wxRect rectTextAreaAdjusted
= rectTextArea
;
4166 rectTextAreaAdjusted
.x
+= pt
.x
;
4167 rectTextAreaAdjusted
.y
+= pt
.y
;
4168 rgnUpdate
.Intersect(rectTextAreaAdjusted
);
4170 // even though the drawing is already clipped to the update region, we must
4171 // explicitly clip it to the rect we will use as otherwise parts of letters
4172 // might be drawn outside of it (if even a small part of a charater is
4173 // inside, HitTest() will return its column and DrawText() can't draw only
4174 // the part of the character, of course)
4176 // FIXME: is this really a bug in wxMSW?
4177 rectTextArea
.width
--;
4179 dc
.SetClippingRegion(rectTextArea
);
4181 // adjust for scrolling
4184 // and now refresh the invalidated parts of the window
4185 wxRegionIterator
iter(rgnUpdate
);
4186 for ( ; iter
.HaveRects(); iter
++ )
4188 wxRect r
= iter
.GetRect();
4190 // this is a workaround for wxGTK::wxRegion bug
4192 if ( !r
.width
|| !r
.height
)
4194 // ignore invalid rect
4199 DoDrawTextInRect(dc
, r
);
4202 // now redraw the line wrap marks (if we draw them)
4203 if ( WrapLines() && WData().m_widthMark
)
4205 // this is the rect inside which line wrap marks are drawn
4207 rectMarks
.x
= rectTextAreaAdjusted
.GetRight() + 1;
4208 rectMarks
.y
= rectTextAreaAdjusted
.y
;
4209 rectMarks
.width
= WData().m_widthMark
;
4210 rectMarks
.height
= rectTextAreaAdjusted
.height
;
4212 rgnUpdate
= GetUpdateRegion();
4213 rgnUpdate
.Intersect(rectMarks
);
4215 wxRect rectUpdate
= rgnUpdate
.GetBox();
4216 if ( rectUpdate
.width
&& rectUpdate
.height
)
4218 // the marks are outside previously set clipping region
4219 dc
.DestroyClippingRegion();
4221 DoDrawLineWrapMarks(dc
, rectUpdate
);
4225 // show caret first time only: we must show it after drawing the text or
4226 // the display can be corrupted when it's hidden
4227 if ( !m_hasCaret
&& GetCaret() && (FindFocus() == this) )
4235 // ----------------------------------------------------------------------------
4237 // ----------------------------------------------------------------------------
4239 bool wxTextCtrl::SetFont(const wxFont
& font
)
4241 if ( !wxControl::SetFont(font
) )
4244 // and refresh everything, of course
4245 InitInsertionPoint();
4248 // update geometry parameters
4250 RecalcFontMetrics();
4251 if ( !IsSingleLine() )
4257 // recreate it, in fact
4265 bool wxTextCtrl::Enable(bool enable
)
4267 if ( !wxTextCtrlBase::Enable(enable
) )
4270 if (FindFocus() == this && GetCaret() &&
4271 ((enable
&& !GetCaret()->IsVisible()) ||
4272 (!enable
&& GetCaret()->IsVisible())))
4278 void wxTextCtrl::CreateCaret()
4284 // FIXME use renderer
4285 caret
= new wxCaret(this, 1, GetLineHeight());
4289 // read only controls don't have the caret
4290 caret
= (wxCaret
*)NULL
;
4293 // SetCaret() will delete the old caret if any
4297 void wxTextCtrl::ShowCaret(bool show
)
4299 wxCaret
*caret
= GetCaret();
4302 // (re)position caret correctly
4303 caret
->Move(GetCaretPosition());
4305 // and show it there
4306 if ((show
&& !caret
->IsVisible()) ||
4307 (!show
&& caret
->IsVisible()))
4312 // ----------------------------------------------------------------------------
4313 // vertical scrolling (multiline only)
4314 // ----------------------------------------------------------------------------
4316 size_t wxTextCtrl::GetLinesPerPage() const
4318 if ( IsSingleLine() )
4321 return GetRealTextArea().height
/ GetLineHeight();
4324 wxTextPos
wxTextCtrl::GetPositionAbove()
4326 wxCHECK_MSG( !IsSingleLine(), INVALID_POS_VALUE
,
4327 _T("can't move cursor vertically in a single line control") );
4329 // move the cursor up by one ROW not by one LINE: this means that
4330 // we should really use HitTest() and not just go to the same
4331 // position in the previous line
4332 wxPoint pt
= GetCaretPosition() - m_rectText
.GetPosition();
4333 if ( MData().m_xCaret
== -1 )
4335 // remember the initial cursor abscissa
4336 MData().m_xCaret
= pt
.x
;
4340 // use the remembered abscissa
4341 pt
.x
= MData().m_xCaret
;
4344 CalcUnscrolledPosition(pt
.x
, pt
.y
, &pt
.x
, &pt
.y
);
4345 pt
.y
-= GetLineHeight();
4347 wxTextCoord col
, row
;
4348 if ( HitTestLogical(pt
, &col
, &row
) == wxTE_HT_BEFORE
)
4350 // can't move further
4351 return INVALID_POS_VALUE
;
4354 return XYToPosition(col
, row
);
4357 wxTextPos
wxTextCtrl::GetPositionBelow()
4359 wxCHECK_MSG( !IsSingleLine(), INVALID_POS_VALUE
,
4360 _T("can't move cursor vertically in a single line control") );
4362 // see comments for wxACTION_TEXT_UP
4363 wxPoint pt
= GetCaretPosition() - m_rectText
.GetPosition();
4364 if ( MData().m_xCaret
== -1 )
4366 // remember the initial cursor abscissa
4367 MData().m_xCaret
= pt
.x
;
4371 // use the remembered abscissa
4372 pt
.x
= MData().m_xCaret
;
4375 CalcUnscrolledPosition(pt
.x
, pt
.y
, &pt
.x
, &pt
.y
);
4376 pt
.y
+= GetLineHeight();
4378 wxTextCoord col
, row
;
4379 if ( HitTestLogical(pt
, &col
, &row
) == wxTE_HT_BELOW
)
4381 // can't go further down
4382 return INVALID_POS_VALUE
;
4385 // note that wxTE_HT_BEYOND is ok: it happens when we go down
4386 // from a longer line to a shorter one, for example (OTOH
4387 // wxTE_HT_BEFORE can never happen)
4388 return XYToPosition(col
, row
);
4391 // ----------------------------------------------------------------------------
4393 // ----------------------------------------------------------------------------
4395 bool wxTextCtrl::PerformAction(const wxControlAction
& actionOrig
,
4397 const wxString
& strArg
)
4399 // has the text changed as result of this action?
4400 bool textChanged
= false;
4402 // the remembered cursor abscissa for multiline text controls is usually
4403 // reset after each user action but for ones which do use it (UP and DOWN
4404 // for example) we shouldn't do it - as indicated by this flag
4405 bool rememberAbscissa
= false;
4407 // the command this action corresponds to or NULL if this action doesn't
4408 // change text at all or can't be undone
4409 wxTextCtrlCommand
*command
= (wxTextCtrlCommand
*)NULL
;
4414 if ( actionOrig
.StartsWith(wxACTION_TEXT_PREFIX_DEL
, &action
) )
4419 else if ( actionOrig
.StartsWith(wxACTION_TEXT_PREFIX_SEL
, &action
) )
4423 else // not selection nor delete action
4425 action
= actionOrig
;
4428 // set newPos to -2 as it can't become equal to it in the assignments below
4429 // (but it can become -1)
4430 wxTextPos newPos
= INVALID_POS_VALUE
;
4432 if ( action
== wxACTION_TEXT_HOME
)
4434 newPos
= m_curPos
- m_curCol
;
4436 else if ( action
== wxACTION_TEXT_END
)
4438 newPos
= m_curPos
+ GetLineLength(m_curRow
) - m_curCol
;
4440 else if ( (action
== wxACTION_TEXT_GOTO
) ||
4441 (action
== wxACTION_TEXT_FIRST
) ||
4442 (action
== wxACTION_TEXT_LAST
) )
4444 if ( action
== wxACTION_TEXT_FIRST
)
4446 else if ( action
== wxACTION_TEXT_LAST
)
4447 numArg
= GetLastPosition();
4448 //else: numArg already contains the position
4452 else if ( action
== wxACTION_TEXT_UP
)
4454 if ( !IsSingleLine() )
4456 newPos
= GetPositionAbove();
4458 if ( newPos
!= INVALID_POS_VALUE
)
4460 // remember where the cursor original had been
4461 rememberAbscissa
= true;
4465 else if ( action
== wxACTION_TEXT_DOWN
)
4467 if ( !IsSingleLine() )
4469 newPos
= GetPositionBelow();
4471 if ( newPos
!= INVALID_POS_VALUE
)
4473 // remember where the cursor original had been
4474 rememberAbscissa
= true;
4478 else if ( action
== wxACTION_TEXT_LEFT
)
4480 newPos
= m_curPos
- 1;
4482 else if ( action
== wxACTION_TEXT_WORD_LEFT
)
4484 newPos
= GetWordStart();
4486 else if ( action
== wxACTION_TEXT_RIGHT
)
4488 newPos
= m_curPos
+ 1;
4490 else if ( action
== wxACTION_TEXT_WORD_RIGHT
)
4492 newPos
= GetWordEnd();
4494 else if ( action
== wxACTION_TEXT_INSERT
)
4496 if ( IsEditable() && !strArg
.empty() )
4498 // inserting text can be undone
4499 command
= new wxTextCtrlInsertCommand(strArg
);
4504 else if ( (action
== wxACTION_TEXT_PAGE_UP
) ||
4505 (action
== wxACTION_TEXT_PAGE_DOWN
) )
4507 if ( !IsSingleLine() )
4509 size_t count
= GetLinesPerPage();
4510 if ( count
> PAGE_OVERLAP_IN_LINES
)
4512 // pages should overlap slightly to allow the reader to keep
4513 // orientation in the text
4514 count
-= PAGE_OVERLAP_IN_LINES
;
4517 // remember where the cursor original had been
4518 rememberAbscissa
= true;
4520 bool goUp
= action
== wxACTION_TEXT_PAGE_UP
;
4521 for ( size_t line
= 0; line
< count
; line
++ )
4523 wxTextPos pos
= goUp
? GetPositionAbove() : GetPositionBelow();
4524 if ( pos
== INVALID_POS_VALUE
)
4526 // can't move further
4530 MoveInsertionPoint(pos
);
4534 // we implement the Unix scrolling model here: cursor will always
4535 // be on the first line after Page Down and on the last one after
4538 // Windows programs usually keep the cursor line offset constant
4539 // but do we really need it?
4543 // find the line such that when it is the first one, the
4544 // current position is in the last line
4546 for ( size_t line
= 0; line
< count
; line
++ )
4548 pos
= GetPositionAbove();
4549 if ( pos
== INVALID_POS_VALUE
)
4552 MoveInsertionPoint(pos
);
4555 MoveInsertionPoint(newPos
);
4557 PositionToLogicalXY(pos
, NULL
, &y
);
4559 else // scrolled down
4561 PositionToLogicalXY(newPos
, NULL
, &y
);
4564 // scroll vertically only
4565 Scroll(wxDefaultCoord
, y
);
4568 else if ( action
== wxACTION_TEXT_SEL_WORD
)
4570 SetSelection(GetWordStart(), GetWordEnd());
4572 else if ( action
== wxACTION_TEXT_ANCHOR_SEL
)
4576 else if ( action
== wxACTION_TEXT_EXTEND_SEL
)
4578 SetSelection(m_selAnchor
, numArg
);
4580 else if ( action
== wxACTION_TEXT_COPY
)
4584 else if ( action
== wxACTION_TEXT_CUT
)
4589 else if ( action
== wxACTION_TEXT_PASTE
)
4594 else if ( action
== wxACTION_TEXT_UNDO
)
4599 else if ( action
== wxACTION_TEXT_REDO
)
4606 return wxControl::PerformAction(action
, numArg
, strArg
);
4609 if ( newPos
!= INVALID_POS_VALUE
)
4611 // bring the new position into the range
4615 wxTextPos posLast
= GetLastPosition();
4616 if ( newPos
> posLast
)
4621 // if we have the selection, remove just it
4623 if ( HasSelection() )
4630 // otherwise delete everything between current position and
4632 if ( m_curPos
!= newPos
)
4637 else // nothing to delete
4639 // prevent test below from working
4640 from
= INVALID_POS_VALUE
;
4642 // and this is just to silent the compiler warning
4647 if ( from
!= INVALID_POS_VALUE
)
4649 command
= new wxTextCtrlRemoveCommand(from
, to
);
4652 else // cursor movement command
4655 DoSetInsertionPoint(newPos
);
4659 SetSelection(m_selAnchor
, m_curPos
);
4661 else // simple movement
4663 // clear the existing selection
4668 if ( !rememberAbscissa
&& !IsSingleLine() )
4670 MData().m_xCaret
= -1;
4676 // execute and remember it to be able to undo it later
4677 m_cmdProcessor
->Submit(command
);
4679 // undoable commands always change text
4682 else // no undoable command
4684 // m_cmdProcessor->StopCompressing()
4689 wxASSERT_MSG( IsEditable(), _T("non editable control changed?") );
4691 wxCommandEvent
event(wxEVT_COMMAND_TEXT_UPDATED
, GetId());
4692 InitCommandEvent(event
);
4693 GetEventHandler()->ProcessEvent(event
);
4695 // as the text changed...
4696 m_isModified
= true;
4702 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
4704 // only process the key events from "simple keys" here
4705 if ( !event
.HasModifiers() )
4707 int keycode
= event
.GetKeyCode();
4709 wxChar unicode
= event
.GetUnicodeKey();
4711 if ( keycode
== WXK_RETURN
)
4713 if ( IsSingleLine() || (GetWindowStyle() & wxTE_PROCESS_ENTER
) )
4715 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
, GetId());
4716 InitCommandEvent(event
);
4717 event
.SetString(GetValue());
4718 GetEventHandler()->ProcessEvent(event
);
4720 else // interpret <Enter> normally: insert new line
4722 PerformAction(wxACTION_TEXT_INSERT
, -1, _T('\n'));
4725 else if ( keycode
< 255 && isprint(keycode
) )
4727 PerformAction(wxACTION_TEXT_INSERT
, -1, (wxChar
)keycode
);
4729 // skip event.Skip() below
4733 else if (unicode
> 0)
4735 PerformAction(wxACTION_TEXT_INSERT
, -1, unicode
);
4742 // Ctrl-R refreshes the control in debug mode
4743 else if ( event
.ControlDown() && event
.GetKeyCode() == 'r' )
4745 #endif // __WXDEBUG__
4751 wxInputHandler
*wxTextCtrl::GetStdInputHandler(wxInputHandler
*handlerDef
)
4753 static wxStdTextCtrlInputHandler
s_handler(handlerDef
);
4758 // ----------------------------------------------------------------------------
4759 // wxStdTextCtrlInputHandler
4760 // ----------------------------------------------------------------------------
4762 wxStdTextCtrlInputHandler::wxStdTextCtrlInputHandler(wxInputHandler
*inphand
)
4763 : wxStdInputHandler(inphand
)
4765 m_winCapture
= (wxTextCtrl
*)NULL
;
4769 wxTextPos
wxStdTextCtrlInputHandler::HitTest(const wxTextCtrl
*text
,
4772 wxTextCoord col
, row
;
4773 wxTextCtrlHitTestResult ht
= text
->HitTest(pt
, &col
, &row
);
4775 wxTextPos pos
= text
->XYToPosition(col
, row
);
4777 // if the point is after the last column we must adjust the position to be
4778 // the last position in the line (unless it is already the last)
4779 if ( (ht
== wxTE_HT_BEYOND
) && (pos
< text
->GetLastPosition()) )
4787 bool wxStdTextCtrlInputHandler::HandleKey(wxInputConsumer
*consumer
,
4788 const wxKeyEvent
& event
,
4791 // we're only interested in key presses
4795 int keycode
= event
.GetKeyCode();
4797 wxControlAction action
;
4799 bool ctrlDown
= event
.ControlDown(),
4800 shiftDown
= event
.ShiftDown();
4803 action
= wxACTION_TEXT_PREFIX_SEL
;
4806 // the only key combination with Alt we recognize is Alt-Bksp for undo, so
4807 // treat it first separately
4808 if ( event
.AltDown() )
4810 if ( keycode
== WXK_BACK
&& !ctrlDown
&& !shiftDown
)
4811 action
= wxACTION_TEXT_UNDO
;
4813 else switch ( keycode
)
4817 action
<< (ctrlDown
? wxACTION_TEXT_FIRST
4818 : wxACTION_TEXT_HOME
);
4822 action
<< (ctrlDown
? wxACTION_TEXT_LAST
4823 : wxACTION_TEXT_END
);
4828 action
<< wxACTION_TEXT_UP
;
4833 action
<< wxACTION_TEXT_DOWN
;
4837 action
<< (ctrlDown
? wxACTION_TEXT_WORD_LEFT
4838 : wxACTION_TEXT_LEFT
);
4842 action
<< (ctrlDown
? wxACTION_TEXT_WORD_RIGHT
4843 : wxACTION_TEXT_RIGHT
);
4847 // we don't map Ctrl-PgUp/Dn to anything special - what should it
4848 // to? for now, it's the same as without control
4849 action
<< wxACTION_TEXT_PAGE_DOWN
;
4853 action
<< wxACTION_TEXT_PAGE_UP
;
4859 action
<< wxACTION_TEXT_PREFIX_DEL
<< wxACTION_TEXT_RIGHT
;
4864 action
<< wxACTION_TEXT_PREFIX_DEL
<< wxACTION_TEXT_LEFT
;
4869 // reset the action as it could be already set to one of the
4871 action
= wxACTION_NONE
;
4878 action
= wxACTION_TEXT_REDO
;
4882 action
= wxACTION_TEXT_COPY
;
4886 action
= wxACTION_TEXT_PASTE
;
4890 action
= wxACTION_TEXT_CUT
;
4894 action
= wxACTION_TEXT_UNDO
;
4900 if ( (action
!= wxACTION_NONE
) && (action
!= wxACTION_TEXT_PREFIX_SEL
) )
4902 consumer
->PerformAction(action
, -1, str
);
4907 return wxStdInputHandler::HandleKey(consumer
, event
, pressed
);
4910 bool wxStdTextCtrlInputHandler::HandleMouse(wxInputConsumer
*consumer
,
4911 const wxMouseEvent
& event
)
4913 if ( event
.LeftDown() )
4915 wxASSERT_MSG( !m_winCapture
, _T("left button going down twice?") );
4917 wxTextCtrl
*text
= wxStaticCast(consumer
->GetInputWindow(), wxTextCtrl
);
4919 m_winCapture
= text
;
4920 m_winCapture
->CaptureMouse();
4924 wxTextPos pos
= HitTest(text
, event
.GetPosition());
4927 text
->PerformAction(wxACTION_TEXT_ANCHOR_SEL
, pos
);
4930 else if ( event
.LeftDClick() )
4932 // select the word the cursor is on
4933 consumer
->PerformAction(wxACTION_TEXT_SEL_WORD
);
4935 else if ( event
.LeftUp() )
4939 m_winCapture
->ShowCaret();
4941 m_winCapture
->ReleaseMouse();
4942 m_winCapture
= (wxTextCtrl
*)NULL
;
4946 return wxStdInputHandler::HandleMouse(consumer
, event
);
4949 bool wxStdTextCtrlInputHandler::HandleMouseMove(wxInputConsumer
*consumer
,
4950 const wxMouseEvent
& event
)
4955 wxTextCtrl
*text
= wxStaticCast(m_winCapture
, wxTextCtrl
);
4956 wxTextPos pos
= HitTest(text
, event
.GetPosition());
4959 text
->PerformAction(wxACTION_TEXT_EXTEND_SEL
, pos
);
4963 return wxStdInputHandler::HandleMouseMove(consumer
, event
);
4967 wxStdTextCtrlInputHandler::HandleFocus(wxInputConsumer
*consumer
,
4968 const wxFocusEvent
& event
)
4970 wxTextCtrl
*text
= wxStaticCast(consumer
->GetInputWindow(), wxTextCtrl
);
4972 // the selection appearance changes depending on whether we have the focus
4973 text
->RefreshSelection();
4975 if (event
.GetEventType() == wxEVT_SET_FOCUS
)
4977 if (text
->GetCaret() && !text
->GetCaret()->IsVisible())
4982 if (text
->GetCaret() && text
->GetCaret()->IsVisible())
4986 // never refresh entirely
4990 #endif // wxUSE_TEXTCTRL