]> git.saurik.com Git - wxWidgets.git/blame - src/univ/textctrl.cpp
update frm Ivan Masar
[wxWidgets.git] / src / univ / textctrl.cpp
CommitLineData
1e6feb95 1/////////////////////////////////////////////////////////////////////////////
faa94f3e 2// Name: src/univ/textctrl.cpp
1e6feb95
VZ
3// Purpose: wxTextCtrl
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 15.09.00
7// RCS-ID: $Id$
442b35b5 8// Copyright: (c) 2000 SciTech Software, Inc. (www.scitechsoft.com)
65571936 9// Licence: wxWindows licence
1e6feb95
VZ
10/////////////////////////////////////////////////////////////////////////////
11
12/*
13 TODO
14
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
19 the same location)?
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
23 with lots of text
24
25 6. backspace refreshes too much (until end of line)
26 */
27
28/*
29 Optimisation hints from PureQuantify:
30
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
35
36 For line wrapping controls HitTest2 takes 50% of program time. The results
37 of GetRowsPerLine and GetPartOfWrappedLine *MUST* be cached.
38
39 Search for "OPT!" for things which must be optimized.
40 */
41
42/*
43 Some terminology:
44
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()
a290fa5a 47 is true in which case a single LINE may correspond to multiple ROWs.
1e6feb95
VZ
48
49 A text position is an unsigned int (which for reasons of compatibility is
7d8268a1 50 still a long as wxTextPos) from 0 to GetLastPosition() inclusive. The positions
1e6feb95
VZ
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.
54
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.
60
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.
64
65 An example of positions and lines/columns for a control without wrapping
66 containing the text "Hello, Universe!\nGoodbye"
67
68 1 1 1 1 1 1 1
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
72 0 1 2 3 4 5
73
74 pos: 1 1 1 2 2 2 2 2
75 7 8 9 0 1 2 3 4
76 G o o d b y e line 1
77 col: 0 1 2 3 4 5 6
78
79
80 The same example for a control with line wrap assuming "Universe" is too
81 long to fit on the same line with "Hello,":
82
83 pos: 0 1 2 3 4 5
84 H e l l o , line 0 (row 0)
85 col: 0 1 2 3 4 5
86
87 1 1 1 1 1 1 1
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
91 0 1 2 3 4 5
92
93 (line 1 == row 2 same as above)
94
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).
100 */
101
102/*
103 Search for "OPT" for possible optimizations
104
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.
110 */
111
112// ============================================================================
113// declarations
114// ============================================================================
115
116// ----------------------------------------------------------------------------
117// headers
118// ----------------------------------------------------------------------------
119
1e6feb95
VZ
120#include "wx/wxprec.h"
121
122#ifdef __BORLANDC__
123 #pragma hdrstop
124#endif
125
126#if wxUSE_TEXTCTRL
127
fec9cc08 128#include "wx/textctrl.h"
28a34fc7 129
1e6feb95
VZ
130#ifndef WX_PRECOMP
131 #include "wx/log.h"
1e6feb95
VZ
132 #include "wx/dcclient.h"
133 #include "wx/validate.h"
28f92d74 134 #include "wx/dataobj.h"
1e6feb95
VZ
135#endif
136
fec9cc08
WS
137#include <ctype.h>
138
1e6feb95 139#include "wx/clipbrd.h"
21709999 140
1e6feb95
VZ
141#include "wx/textfile.h"
142
143#include "wx/caret.h"
144
145#include "wx/univ/inphand.h"
146#include "wx/univ/renderer.h"
147#include "wx/univ/colschem.h"
148#include "wx/univ/theme.h"
149
150#include "wx/cmdproc.h"
151
152// turn extra wxTextCtrl-specific debugging on/off
153#define WXDEBUG_TEXT
154
155// turn wxTextCtrl::Replace() debugging on (slows down code a *lot*!)
156#define WXDEBUG_TEXT_REPLACE
157
158#ifndef __WXDEBUG__
159 #undef WXDEBUG_TEXT
160 #undef WXDEBUG_TEXT_REPLACE
161#endif
162
163// wxStringTokenize only needed for debug checks
164#ifdef WXDEBUG_TEXT_REPLACE
165 #include "wx/tokenzr.h"
166#endif // WXDEBUG_TEXT_REPLACE
167
9467bdb7
VZ
168// ----------------------------------------------------------------------------
169// wxStdTextCtrlInputHandler: this control handles only the mouse/kbd actions
170// common to Win32 and GTK, platform-specific things are implemented elsewhere
171// ----------------------------------------------------------------------------
172
173class WXDLLEXPORT wxStdTextCtrlInputHandler : public wxStdInputHandler
174{
175public:
176 wxStdTextCtrlInputHandler(wxInputHandler *inphand);
177
178 virtual bool HandleKey(wxInputConsumer *consumer,
179 const wxKeyEvent& event,
180 bool pressed);
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);
186
187protected:
188 // get the position of the mouse click
189 static wxTextPos HitTest(const wxTextCtrl *text, const wxPoint& pos);
190
191 // capture data
192 wxTextCtrl *m_winCapture;
193};
194
1e6feb95
VZ
195// ----------------------------------------------------------------------------
196// private functions
197// ----------------------------------------------------------------------------
198
199// exchange two positions so that from is always less than or equal to to
200static inline void OrderPositions(wxTextPos& from, wxTextPos& to)
201{
202 if ( from > to )
203 {
204 wxTextPos tmp = from;
205 from = to;
206 to = tmp;
207 }
208}
209
210// ----------------------------------------------------------------------------
211// constants
212// ----------------------------------------------------------------------------
213
214// names of text ctrl commands
215#define wxTEXT_COMMAND_INSERT _T("insert")
216#define wxTEXT_COMMAND_REMOVE _T("remove")
217
218// the value which is never used for text position, even not -1 which is
219// sometimes used for some special meaning
7d8268a1 220static const wxTextPos INVALID_POS_VALUE = wxInvalidTextCoord;
1e6feb95
VZ
221
222// overlap between pages (when using PageUp/Dn) in lines
223static const size_t PAGE_OVERLAP_IN_LINES = 1;
224
225// ----------------------------------------------------------------------------
226// private data of wxTextCtrl
227// ----------------------------------------------------------------------------
228
229// the data only used by single line text controls
a685dd31 230struct wxTextSingleLineData
1e6feb95
VZ
231{
232 // the position of the first visible pixel and the first visible column
233 wxCoord m_ofsHorz;
234 wxTextCoord m_colStart;
235
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;
240
241 // def ctor
242 wxTextSingleLineData()
243 {
244 m_colStart = 0;
245 m_ofsHorz = 0;
246
247 m_colLastVisible = -1;
248 m_posLastVisible = -1;
249 }
250
251};
252
253// the data only used by multi line text controls
a685dd31 254struct wxTextMultiLineData
1e6feb95
VZ
255{
256 // the lines of text
257 wxArrayString m_lines;
258
259 // the current ranges of the scrollbars
260 int m_scrollRangeX,
261 m_scrollRangeY;
262
263 // should we adjust the horz/vert scrollbar?
264 bool m_updateScrollbarX,
265 m_updateScrollbarY;
266
267 // the max line length in pixels
268 wxCoord m_widthMax;
269
270 // the index of the line which has the length of m_widthMax
271 wxTextCoord m_lineLongest;
272
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;
277
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
282 //
283 // when m_xCaret == -1, we don't have any remembered position
284 wxCoord m_xCaret;
285
286 // the def ctor
287 wxTextMultiLineData()
288 {
289 m_scrollRangeX =
290 m_scrollRangeY = 0;
291
292 m_updateScrollbarX =
a290fa5a 293 m_updateScrollbarY = false;
1e6feb95
VZ
294
295 m_widthMax = -1;
296 m_lineLongest = 0;
297
298 m_xCaret = -1;
299 }
300};
301
302// the data only used by multi line text controls in line wrap mode
a685dd31 303class wxWrappedLineData
1e6feb95
VZ
304{
305 // these functions set all our values, so give them access to them
306friend void wxTextCtrl::LayoutLine(wxTextCoord line,
307 wxWrappedLineData& lineData) const;
308friend void wxTextCtrl::LayoutLines(wxTextCoord) const;
309
310public:
311 // def ctor
312 wxWrappedLineData()
313 {
314 m_rowFirst = -1;
315 }
316
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
320 {
321 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
322
323 return row ? m_rowsStart[row - 1] : 0;
324 }
325
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
328 // be given to us)
329 wxTextCoord GetRowLength(wxTextCoord row, wxTextCoord lenLine) const
330 {
331 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
332
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])
337 - GetRowStart(row);
338 }
339
340 // return the width of the row in pixels
341 wxCoord GetRowWidth(wxTextCoord row) const
342 {
343 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
344
345 return m_rowsWidth[row];
346 }
347
348 // return the number of rows
349 size_t GetRowCount() const
350 {
351 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
352
353 return m_rowsStart.GetCount() + 1;
354 }
355
356 // return the number of additional (i.e. after the first one) rows
357 size_t GetExtraRowCount() const
358 {
359 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
360
361 return m_rowsStart.GetCount();
362 }
363
364 // return the first row of this line
365 wxTextCoord GetFirstRow() const
366 {
367 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
368
369 return m_rowFirst;
370 }
371
372 // return the first row of the next line
373 wxTextCoord GetNextRow() const
374 {
375 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
376
377 return m_rowFirst + m_rowsStart.GetCount() + 1;
378 }
379
380 // this just provides direct access to m_rowsStart aerray for efficiency
381 wxTextCoord GetExtraRowStart(wxTextCoord row) const
382 {
383 wxASSERT_MSG( IsValid(), _T("this line hadn't been laid out") );
384
385 return m_rowsStart[row];
386 }
387
388 // this code is unused any longer
389#if 0
a290fa5a 390 // return true if the column is in the start of the last row (hence the row
1e6feb95
VZ
391 // it is in is not wrapped)
392 bool IsLastRow(wxTextCoord colRowStart) const
393 {
394 return colRowStart == GetRowStart(m_rowsStart.GetCount());
395 }
396
a290fa5a 397 // return true if the column is the last column of the row starting in
1e6feb95
VZ
398 // colRowStart
399 bool IsLastColInRow(wxTextCoord colRowStart,
400 wxTextCoord colRowEnd,
401 wxTextCoord lenLine) const
402 {
403 // find the row which starts with colRowStart
404 size_t nRows = GetRowCount();
405 for ( size_t n = 0; n < nRows; n++ )
406 {
407 if ( GetRowStart(n) == colRowStart )
408 {
409 wxTextCoord colNextRowStart = n == nRows - 1
410 ? lenLine
411 : GetRowStart(n + 1);
412
413 wxASSERT_MSG( colRowEnd < colNextRowStart,
414 _T("this column is not in this row at all!") );
415
416 return colRowEnd == colNextRowStart - 1;
417 }
418 }
419
420 // caller got it wrong
421 wxFAIL_MSG( _T("this column is not in the start of the row!") );
422
a290fa5a 423 return false;
1e6feb95
VZ
424 }
425#endif // 0
426
427 // is this row the last one in its line?
428 bool IsLastRow(wxTextCoord row) const
429 {
430 return (size_t)row == GetExtraRowCount();
431 }
432
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
435 // it invalid
436 bool IsValid() const { return !m_rowsWidth.IsEmpty(); }
437
438 // invalidating line will relayout it
439 void Invalidate() { m_rowsWidth.Empty(); }
440
441private:
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;
446
447 // and the width of each row in pixels (this array starts from 0, as usual)
448 wxArrayInt m_rowsWidth;
449
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;
454
455 // the last modification "time"-stamp used by LayoutLines()
456 size_t m_timestamp;
457};
458
459WX_DECLARE_OBJARRAY(wxWrappedLineData, wxArrayWrappedLinesData);
460#include "wx/arrimpl.cpp"
461WX_DEFINE_OBJARRAY(wxArrayWrappedLinesData);
462
a685dd31 463struct wxTextWrappedData : public wxTextMultiLineData
1e6feb95
VZ
464{
465 // the width of the column to the right of the text rect used for the
466 // indicator mark display for the wrapped lines
467 wxCoord m_widthMark;
468
469 // the data for each line
470 wxArrayWrappedLinesData m_linesData;
471
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;
476
477 // the current timestamp used by LayoutLines()
478 size_t m_timestamp;
479
480 // invalidate starting rows of all lines (NOT rows!) after this one
481 void InvalidateLinesBelow(wxTextCoord line)
482 {
483 if ( m_rowFirstInvalid == -1 || m_rowFirstInvalid > line )
484 {
485 m_rowFirstInvalid = line;
486 }
487 }
488
489 // check if this line is valid: i.e. before the first invalid one
490 bool IsValidLine(wxTextCoord line) const
491 {
492 return ((m_rowFirstInvalid == -1) || (line < m_rowFirstInvalid)) &&
493 m_linesData[line].IsValid();
494 }
495
496 // def ctor
497 wxTextWrappedData()
498 {
499 m_widthMark = 0;
500 m_rowFirstInvalid = -1;
501 m_timestamp = 0;
502 }
503};
504
505// ----------------------------------------------------------------------------
506// private classes for undo/redo management
507// ----------------------------------------------------------------------------
508
509/*
77ffb593 510 We use custom versions of wxWidgets command processor to implement undo/redo
1e6feb95
VZ
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.
515
516 As for the rest of the implementation, it's fairly standard: we have 2
517 command classes corresponding to adding and removing text.
518 */
519
520// a command corresponding to a wxTextCtrl action
521class wxTextCtrlCommand : public wxCommand
522{
523public:
a290fa5a 524 wxTextCtrlCommand(const wxString& name) : wxCommand(true, name) { }
1e6feb95
VZ
525
526 // we don't use these methods as they don't make sense for us as we need a
527 // wxTextCtrl to be applied
a290fa5a
WS
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; }
1e6feb95
VZ
530
531 // instead, our command processor uses these methods
532 virtual bool Do(wxTextCtrl *text) = 0;
533 virtual bool Undo(wxTextCtrl *text) = 0;
534};
535
536// insert text command
537class wxTextCtrlInsertCommand : public wxTextCtrlCommand
538{
539public:
540 wxTextCtrlInsertCommand(const wxString& textToInsert)
541 : wxTextCtrlCommand(wxTEXT_COMMAND_INSERT), m_text(textToInsert)
542 {
543 m_from = -1;
544 }
545
546 // combine the 2 commands together
547 void Append(wxTextCtrlInsertCommand *other);
548
549 virtual bool CanUndo() const;
550 virtual bool Do(wxTextCtrl *text);
8a39593e
JS
551 virtual bool Do() { return wxTextCtrlCommand::Do(); }
552 virtual bool Undo() { return wxTextCtrlCommand::Undo(); }
1e6feb95
VZ
553 virtual bool Undo(wxTextCtrl *text);
554
555private:
556 // the text we insert
557 wxString m_text;
558
559 // the position where we inserted the text
560 wxTextPos m_from;
561};
562
563// remove text command
564class wxTextCtrlRemoveCommand : public wxTextCtrlCommand
565{
566public:
567 wxTextCtrlRemoveCommand(wxTextPos from, wxTextPos to)
568 : wxTextCtrlCommand(wxTEXT_COMMAND_REMOVE)
569 {
570 m_from = from;
571 m_to = to;
572 }
573
574 virtual bool CanUndo() const;
575 virtual bool Do(wxTextCtrl *text);
8a39593e
JS
576 virtual bool Do() { return wxTextCtrlCommand::Do(); }
577 virtual bool Undo() { return wxTextCtrlCommand::Undo(); }
1e6feb95
VZ
578 virtual bool Undo(wxTextCtrl *text);
579
580private:
581 // the range of text to delete
582 wxTextPos m_from,
583 m_to;
584
585 // the text which was deleted when this command was Do()ne
586 wxString m_textDeleted;
587};
588
589// a command processor for a wxTextCtrl
590class wxTextCtrlCommandProcessor : public wxCommandProcessor
591{
592public:
593 wxTextCtrlCommandProcessor(wxTextCtrl *text)
594 {
a290fa5a 595 m_compressInserts = false;
1e6feb95
VZ
596
597 m_text = text;
598 }
599
600 // override Store() to compress multiple wxTextCtrlInsertCommand into one
601 virtual void Store(wxCommand *command);
602
603 // stop compressing insert commands when this is called
a290fa5a 604 void StopCompressing() { m_compressInserts = false; }
1e6feb95
VZ
605
606 // accessors
607 wxTextCtrl *GetTextCtrl() const { return m_text; }
608 bool IsCompressing() const { return m_compressInserts; }
609
610protected:
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); }
615
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);
619
620private:
621 // the control we're associated with
622 wxTextCtrl *m_text;
623
a290fa5a 624 // if the flag is true we're compressing subsequent insert commands into
1e6feb95
VZ
625 // one so that the entire typing could be undone in one call to Undo()
626 bool m_compressInserts;
627};
628
629// ============================================================================
630// implementation
631// ============================================================================
632
9d112688 633BEGIN_EVENT_TABLE(wxTextCtrl, wxTextCtrlBase)
1e6feb95
VZ
634 EVT_CHAR(wxTextCtrl::OnChar)
635
636 EVT_SIZE(wxTextCtrl::OnSize)
1e6feb95
VZ
637END_EVENT_TABLE()
638
9d112688 639IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxTextCtrlBase)
1e6feb95
VZ
640
641// ----------------------------------------------------------------------------
642// creation
643// ----------------------------------------------------------------------------
644
645void wxTextCtrl::Init()
646{
647 m_selAnchor =
648 m_selStart =
649 m_selEnd = -1;
650
a290fa5a
WS
651 m_isModified = false;
652 m_isEditable = true;
ccc20afa 653 m_wrapLines = false;
1e6feb95
VZ
654
655 m_posLast =
656 m_curPos =
657 m_curCol =
658 m_curRow = 0;
659
660 m_heightLine =
661 m_widthAvg = -1;
662
1e6feb95
VZ
663 // init the undo manager
664 m_cmdProcessor = new wxTextCtrlCommandProcessor(this);
665
666 // no data yet
667 m_data.data = NULL;
668}
669
670bool wxTextCtrl::Create(wxWindow *parent,
671 wxWindowID id,
672 const wxString& value,
673 const wxPoint& pos,
674 const wxSize& size,
675 long style,
676 const wxValidator& validator,
677 const wxString &name)
678{
679 if ( style & wxTE_MULTILINE )
680 {
681 // for compatibility with wxMSW we create the controls with vertical
682 // scrollbar always shown unless they have wxTE_RICH style (because
683 // Windows text controls always has vert scrollbar but richedit one
684 // doesn't)
685 if ( !(style & wxTE_RICH) )
686 {
687 style |= wxALWAYS_SHOW_SB;
688 }
689
fb4888a6
VZ
690 // wrapping style: wxTE_DONTWRAP == wxHSCROLL so if it's _not_ given,
691 // we won't have horizontal scrollbar automatically, no need to do
692 // anything
1e6feb95
VZ
693
694 // TODO: support wxTE_NO_VSCROLL (?)
695
696 // create data object for normal multiline or for controls with line
697 // wrap as needed
698 if ( style & wxHSCROLL )
ccc20afa 699 {
1e6feb95 700 m_data.mdata = new wxTextMultiLineData;
ccc20afa
VZ
701 }
702 else // we must wrap lines if we don't have horizontal scrollbar
703 {
704 // NB: we can't rely on HasFlag(wxHSCROLL) as the flags can change
705 // later and even wxWindow::Create() itself temporarily resets
706 // wxHSCROLL in wxUniv, so remember that we have a wrapped data
707 // and not just a multi line data in a separate variable
708 m_wrapLines = true;
1e6feb95 709 m_data.wdata = new wxTextWrappedData;
ccc20afa 710 }
1e6feb95
VZ
711 }
712 else
713 {
714 // this doesn't make sense for single line controls
715 style &= ~wxHSCROLL;
716
717 // create data object for single line controls
718 m_data.sdata = new wxTextSingleLineData;
719 }
34158fee 720
372c2812
RR
721#if wxUSE_TWO_WINDOWS
722 if ((style & wxBORDER_MASK) == 0)
723 style |= wxBORDER_SUNKEN;
724#endif
1e6feb95
VZ
725
726 if ( !wxControl::Create(parent, id, pos, size, style,
727 validator, name) )
728 {
a290fa5a 729 return false;
1e6feb95
VZ
730 }
731
732 SetCursor(wxCURSOR_IBEAM);
733
734 if ( style & wxTE_MULTILINE )
735 {
736 // we should always have at least one line in a multiline control
737 MData().m_lines.Add(wxEmptyString);
738
739 if ( !(style & wxHSCROLL) )
740 {
741 WData().m_linesData.Add(new wxWrappedLineData);
742 WData().InvalidateLinesBelow(0);
743 }
744
745 // we might support it but it's quite useless and other ports don't
746 // support it anyhow
747 wxASSERT_MSG( !(style & wxTE_PASSWORD),
748 _T("wxTE_PASSWORD can't be used with multiline ctrls") );
749 }
750
751 RecalcFontMetrics();
752 SetValue(value);
170acdc9 753 SetInitialSize(size);
1e6feb95
VZ
754
755 m_isEditable = !(style & wxTE_READONLY);
756
757 CreateCaret();
758 InitInsertionPoint();
759
760 // we can't show caret right now as we're not shown yet and so it would
761 // result in garbage on the screen - we'll do it after first OnPaint()
a290fa5a 762 m_hasCaret = false;
1e6feb95
VZ
763
764 CreateInputHandler(wxINP_HANDLER_TEXTCTRL);
765
e28c2d15
JS
766 wxSizeEvent sizeEvent(GetSize(), GetId());
767 GetEventHandler()->ProcessEvent(sizeEvent);
768
a290fa5a 769 return true;
1e6feb95
VZ
770}
771
772wxTextCtrl::~wxTextCtrl()
773{
774 delete m_cmdProcessor;
775
776 if ( m_data.data )
777 {
778 if ( IsSingleLine() )
779 delete m_data.sdata;
780 else if ( WrapLines() )
781 delete m_data.wdata;
782 else
783 delete m_data.mdata;
784 }
785}
786
787// ----------------------------------------------------------------------------
788// set/get the value
789// ----------------------------------------------------------------------------
790
ee2ec18e 791void wxTextCtrl::DoSetValue(const wxString& value, int flags)
1e6feb95
VZ
792{
793 if ( IsSingleLine() && (value == GetValue()) )
794 {
795 // nothing changed
796 return;
797 }
798
799 Replace(0, GetLastPosition(), value);
800
801 if ( IsSingleLine() )
802 {
803 SetInsertionPoint(0);
804 }
805
ee2ec18e
VZ
806 if ( flags & SetValue_SendEvent )
807 SendTextUpdatedEvent();
1e6feb95
VZ
808}
809
810const wxArrayString& wxTextCtrl::GetLines() const
811{
812 return MData().m_lines;
813}
814
815size_t wxTextCtrl::GetLineCount() const
816{
817 return MData().m_lines.GetCount();
818}
819
820wxString wxTextCtrl::GetValue() const
821{
822 // for multiline controls we don't always store the total value but only
823 // recompute it when asked - and to invalidate it we just empty it in
824 // Replace()
825 if ( !IsSingleLine() && m_value.empty() )
826 {
827 // recalculate: note that we always do it for empty multilien control,
828 // but then it's so quick that it's not important
829
830 // the first line is special as there is no \n before it, so it's
831 // outside the loop
832 const wxArrayString& lines = GetLines();
833 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
834 self->m_value << lines[0u];
835 size_t count = lines.GetCount();
836 for ( size_t n = 1; n < count; n++ )
837 {
838 self->m_value << _T('\n') << lines[n];
839 }
840 }
841
842 return m_value;
843}
844
845void wxTextCtrl::Clear()
846{
0966aee3 847 SetValue(wxEmptyString);
1e6feb95
VZ
848}
849
850bool wxTextCtrl::ReplaceLine(wxTextCoord line,
851 const wxString& text)
852{
853 if ( WrapLines() )
854 {
855 // first, we have to relayout the line entirely
856 //
857 // OPT: we might try not to recalc the unchanged part of line
858
859 wxWrappedLineData& lineData = WData().m_linesData[line];
860
861 // if we had some number of rows before, use this number, otherwise
862 // just make sure that the test below (rowsNew != rowsOld) will be true
863 int rowsOld;
864 if ( lineData.IsValid() )
865 {
866 rowsOld = lineData.GetExtraRowCount();
867 }
868 else // line wasn't laid out yet
869 {
870 // assume it changed entirely as we can't do anything better
871 rowsOld = -1;
872 }
873
874 // now change the line
875 MData().m_lines[line] = text;
876
877 // OPT: we choose to lay it our immediately instead of delaying it
878 // until it is needed because it allows us to avoid invalidating
879 // lines further down if the number of rows didn't chnage, but
880 // maybe we can imporve this even further?
881 LayoutLine(line, lineData);
882
883 int rowsNew = lineData.GetExtraRowCount();
884
885 if ( rowsNew != rowsOld )
886 {
887 // we have to update the line wrap marks as this is normally done
888 // by LayoutLines() which we bypassed by calling LayoutLine()
889 // directly
890 wxTextCoord rowFirst = lineData.GetFirstRow(),
891 rowCount = wxMax(rowsOld, rowsNew);
892 RefreshLineWrapMarks(rowFirst, rowFirst + rowCount);
893
894 // next, if this is not the last line, as the number of rows in it
895 // changed, we need to shift all the lines below it
896 if ( (size_t)line < WData().m_linesData.GetCount() )
897 {
898 // number of rows changed shifting all lines below
899 WData().InvalidateLinesBelow(line + 1);
900 }
901
902 // the number of rows changed
a290fa5a 903 return true;
1e6feb95
VZ
904 }
905 }
906 else // no line wrap
907 {
908 MData().m_lines[line] = text;
909 }
910
911 // the number of rows didn't change
a290fa5a 912 return false;
1e6feb95
VZ
913}
914
915void wxTextCtrl::RemoveLine(wxTextCoord line)
916{
917 MData().m_lines.RemoveAt(line);
918 if ( WrapLines() )
919 {
920 // we need to recalculate all the starting rows from this line, but we
921 // can avoid doing it if this line was never calculated: this means
922 // that we will recalculate all lines below it anyhow later if needed
923 if ( WData().IsValidLine(line) )
924 {
925 WData().InvalidateLinesBelow(line);
926 }
927
928 WData().m_linesData.RemoveAt(line);
929 }
930}
931
932void wxTextCtrl::InsertLine(wxTextCoord line, const wxString& text)
933{
934 MData().m_lines.Insert(text, line);
935 if ( WrapLines() )
936 {
937 WData().m_linesData.Insert(new wxWrappedLineData, line);
938
939 // invalidate everything below it
940 WData().InvalidateLinesBelow(line);
941 }
942}
943
944void wxTextCtrl::Replace(wxTextPos from, wxTextPos to, const wxString& text)
945{
946 wxTextCoord colStart, colEnd,
947 lineStart, lineEnd;
948
949 if ( (from > to) ||
950 !PositionToXY(from, &colStart, &lineStart) ||
951 !PositionToXY(to, &colEnd, &lineEnd) )
952 {
953 wxFAIL_MSG(_T("invalid range in wxTextCtrl::Replace"));
954
955 return;
956 }
957
958#ifdef WXDEBUG_TEXT_REPLACE
959 // a straighforward (but very inefficient) way of calculating what the new
960 // value should be
961 wxString textTotal = GetValue();
962 wxString textTotalNew(textTotal, (size_t)from);
963 textTotalNew += text;
964 if ( (size_t)to < textTotal.length() )
965 textTotalNew += textTotal.c_str() + (size_t)to;
966#endif // WXDEBUG_TEXT_REPLACE
967
968 // remember the old selection and reset it immediately: we must do it
969 // before calling Refresh(anything) as, at least under GTK, this leads to
970 // an _immediate_ repaint (under MSW it is delayed) and hence parts of
971 // text would be redrawn as selected if we didn't reset the selection
972 int selStartOld = m_selStart,
973 selEndOld = m_selEnd;
974
975 m_selStart =
976 m_selEnd = -1;
977
978 if ( IsSingleLine() )
979 {
980 // replace the part of the text with the new value
981 wxString valueNew(m_value, (size_t)from);
982
983 // remember it for later use
984 wxCoord startNewText = GetTextWidth(valueNew);
985
986 valueNew += text;
987 if ( (size_t)to < m_value.length() )
988 {
989 valueNew += m_value.c_str() + (size_t)to;
990 }
991
992 // we usually refresh till the end of line except of the most common case
993 // when some text is appended to the end of the string in which case we
994 // refresh just it
995 wxCoord widthNewText;
996
997 if ( (size_t)from < m_value.length() )
998 {
999 // refresh till the end of line
1000 widthNewText = 0;
1001 }
1002 else // text appended, not replaced
1003 {
1004 // refresh only the new text
1005 widthNewText = GetTextWidth(text);
1006 }
1007
1008 m_value = valueNew;
1009
1010 // force SData().m_colLastVisible update
1011 SData().m_colLastVisible = -1;
1012
1013 // repaint
1014 RefreshPixelRange(0, startNewText, widthNewText);
1015 }
1016 else // multiline
1017 {
1018 //OPT: special case for replacements inside single line?
1019
1020 /*
1021 Join all the lines in the replacement range into one string, then
1022 replace a part of it with the new text and break it into lines again.
1023 */
1024
1025 // (0) we want to know if this replacement changes the number of rows
1026 // as if it does we need to refresh everything below the changed
1027 // text (it will be shifted...) and we can avoid it if there is no
1028 // row relayout
a290fa5a 1029 bool rowsNumberChanged = false;
1e6feb95
VZ
1030
1031 // (1) join lines
1032 const wxArrayString& linesOld = GetLines();
1033 wxString textOrig;
1034 wxTextCoord line;
1035 for ( line = lineStart; line <= lineEnd; line++ )
1036 {
1037 if ( line > lineStart )
1038 {
1039 // from the previous line
1040 textOrig += _T('\n');
1041 }
1042
1043 textOrig += linesOld[line];
1044 }
1045
1046 // we need to append the '\n' for the last line unless there is no
1047 // following line
1048 size_t countOld = linesOld.GetCount();
1049
1050 // (2) replace text in the combined string
1051
1052 // (2a) leave the part before replaced area unchanged
1053 wxString textNew(textOrig, colStart);
1054
1055 // these values will be used to refresh the changed area below
1056 wxCoord widthNewText,
1057 startNewText = GetTextWidth(textNew);
1058 if ( (size_t)colStart == linesOld[lineStart].length() )
1059 {
1060 // text appended, refresh just enough to show the new text
1061 widthNewText = GetTextWidth(text.BeforeFirst(_T('\n')));
1062 }
1063 else // text inserted, refresh till the end of line
1064 {
1065 widthNewText = 0;
1066 }
1067
1068 // (2b) insert new text
1069 textNew += text;
1070
1071 // (2c) and append the end of the old text
1072
1073 // adjust for index shift: to is relative to colStart, not 0
1074 size_t toRel = (size_t)((to - from) + colStart);
1075 if ( toRel < textOrig.length() )
1076 {
1077 textNew += textOrig.c_str() + toRel;
1078 }
1079
1080 // (3) break it into lines
1081
1082 wxArrayString lines;
1083 const wxChar *curLineStart = textNew.c_str();
1084 for ( const wxChar *p = textNew.c_str(); ; p++ )
1085 {
1086 // end of line/text?
1087 if ( !*p || *p == _T('\n') )
1088 {
1089 lines.Add(wxString(curLineStart, p));
1090 if ( !*p )
1091 break;
1092
1093 curLineStart = p + 1;
1094 }
1095 }
1096
1097#ifdef WXDEBUG_TEXT_REPLACE
1098 // (3a) all empty tokens should be counted as replacing with "foo" and
1099 // with "foo\n" should have different effects
1100 wxArrayString lines2 = wxStringTokenize(textNew, _T("\n"),
1101 wxTOKEN_RET_EMPTY_ALL);
1102
1103 if ( lines2.IsEmpty() )
1104 {
1105 lines2.Add(wxEmptyString);
1106 }
1107
1108 wxASSERT_MSG( lines.GetCount() == lines2.GetCount(),
1109 _T("Replace() broken") );
1110 for ( size_t n = 0; n < lines.GetCount(); n++ )
1111 {
1112 wxASSERT_MSG( lines[n] == lines2[n], _T("Replace() broken") );
1113 }
1114#endif // WXDEBUG_TEXT_REPLACE
1115
1116 // (3b) special case: if we replace everything till the end we need to
1117 // keep an empty line or the lines would disappear completely
1118 // (this also takes care of never leaving m_lines empty)
1119 if ( ((size_t)lineEnd == countOld - 1) && lines.IsEmpty() )
1120 {
1121 lines.Add(wxEmptyString);
1122 }
1123
1124 size_t nReplaceCount = lines.GetCount(),
1125 nReplaceLine = 0;
1126
1127 // (4) merge into the array
1128
1129 // (4a) replace
1130 for ( line = lineStart; line <= lineEnd; line++, nReplaceLine++ )
1131 {
1132 if ( nReplaceLine < nReplaceCount )
1133 {
1134 // we have the replacement line for this one
1135 if ( ReplaceLine(line, lines[nReplaceLine]) )
1136 {
a290fa5a 1137 rowsNumberChanged = true;
1e6feb95
VZ
1138 }
1139
1140 UpdateMaxWidth(line);
1141 }
1142 else // no more replacement lines
1143 {
1144 // (4b) delete all extra lines (note that we need to delete
1145 // them backwards because indices shift while we do it)
a290fa5a 1146 bool deletedLongestLine = false;
1e6feb95
VZ
1147 for ( wxTextCoord lineDel = lineEnd; lineDel >= line; lineDel-- )
1148 {
1149 if ( lineDel == MData().m_lineLongest )
1150 {
1151 // we will need to recalc the max line width
a290fa5a 1152 deletedLongestLine = true;
1e6feb95
VZ
1153 }
1154
1155 RemoveLine(lineDel);
1156 }
1157
1158 if ( deletedLongestLine )
1159 {
1160 RecalcMaxWidth();
1161 }
1162
1163 // even the line number changed
a290fa5a 1164 rowsNumberChanged = true;
1e6feb95
VZ
1165
1166 // update line to exit the loop
1167 line = lineEnd + 1;
1168 }
1169 }
1170
1171 // (4c) insert the new lines
1172 if ( nReplaceLine < nReplaceCount )
1173 {
1174 // even the line number changed
a290fa5a 1175 rowsNumberChanged = true;
1e6feb95
VZ
1176
1177 do
1178 {
1179 InsertLine(++lineEnd, lines[nReplaceLine++]);
1180
1181 UpdateMaxWidth(lineEnd);
1182 }
1183 while ( nReplaceLine < nReplaceCount );
1184 }
1185
1186 // (5) now refresh the changed area
1187
1188 // update the (cached) last position first as refresh functions use it
1189 m_posLast += text.length() - to + from;
1190
1191 // we may optimize refresh if the number of rows didn't change - but if
1192 // it did we have to refresh everything below the part we chanegd as
1193 // well as it might have moved
1194 if ( !rowsNumberChanged )
1195 {
1196 // refresh the line we changed
1197 if ( !WrapLines() )
1198 {
1199 RefreshPixelRange(lineStart++, startNewText, widthNewText);
1200 }
1201 else
1202 {
1203 //OPT: we shouldn't refresh the unchanged part of the line in
1204 // this case, but instead just refresh the tail of it - the
1205 // trouble is that we don't know here where does this tail
1206 // start
1207 }
1208
1209 // number of rows didn't change, refresh the updated rows and the
1210 // last one
1211 if ( lineStart <= lineEnd )
1212 RefreshLineRange(lineStart, lineEnd);
1213 }
1214 else // rows number did change
1215 {
1216 if ( !WrapLines() )
1217 {
1218 // refresh only part of the first line
1219 RefreshPixelRange(lineStart++, startNewText, widthNewText);
1220 }
1221 //else: we have to refresh everything as some part of the text
1222 // could be in the previous row before but moved to the next
1223 // one now (due to word wrap)
1224
1225 wxTextCoord lineEnd = GetLines().GetCount() - 1;
1226 if ( lineStart <= lineEnd )
1227 RefreshLineRange(lineStart, lineEnd);
1228
1229 // refresh text rect left below
1230 RefreshLineRange(lineEnd + 1, 0);
1231
1232 // the vert scrollbar might [dis]appear
a290fa5a 1233 MData().m_updateScrollbarY = true;
1e6feb95
VZ
1234 }
1235
1236 // must recalculate it - will do later
1237 m_value.clear();
1238 }
1239
1240#ifdef WXDEBUG_TEXT_REPLACE
1241 // optimized code above should give the same result as straightforward
1242 // computation in the beginning
1243 wxASSERT_MSG( GetValue() == textTotalNew, _T("error in Replace()") );
1244#endif // WXDEBUG_TEXT_REPLACE
1245
1246 // update the current position: note that we always put the cursor at the
1247 // end of the replacement text
1248 DoSetInsertionPoint(from + text.length());
1249
1250 // and the selection: this is complicated by the fact that selection coords
1251 // must be first updated to reflect change in text coords, i.e. if we had
1252 // selection from 17 to 19 and we just removed this range, we don't have to
1253 // refresh anything, so we can't just use ClearSelection() here
1254 if ( selStartOld != -1 )
1255 {
1256 // refresh the parst of the selection outside the changed text (which
1257 // we already refreshed)
1258 if ( selStartOld < from )
1259 RefreshTextRange(selStartOld, from);
1260 if ( to < selEndOld )
1261 RefreshTextRange(to, selEndOld);
1262
1263 }
1264
1265 // now call it to do the rest (not related to refreshing)
1266 ClearSelection();
1267}
1268
1269void wxTextCtrl::Remove(wxTextPos from, wxTextPos to)
1270{
1271 // Replace() only works with correctly ordered arguments, so exchange them
1272 // if necessary
1273 OrderPositions(from, to);
1274
0966aee3 1275 Replace(from, to, wxEmptyString);
1e6feb95
VZ
1276}
1277
1278void wxTextCtrl::WriteText(const wxString& text)
1279{
1280 // replace the selection with the new text
1281 RemoveSelection();
1282
1283 Replace(m_curPos, m_curPos, text);
1284}
1285
1286void wxTextCtrl::AppendText(const wxString& text)
1287{
1288 SetInsertionPointEnd();
1289 WriteText(text);
1290}
1291
1292// ----------------------------------------------------------------------------
1293// current position
1294// ----------------------------------------------------------------------------
1295
1296void wxTextCtrl::SetInsertionPoint(wxTextPos pos)
1297{
1298 wxCHECK_RET( pos >= 0 && pos <= GetLastPosition(),
1299 _T("insertion point position out of range") );
1300
1301 // don't do anything if it didn't change
1302 if ( pos != m_curPos )
1303 {
1304 DoSetInsertionPoint(pos);
1305 }
1306
1307 if ( !IsSingleLine() )
1308 {
1309 // moving cursor should reset the stored abscissa (even if the cursor
1310 // position didn't actually change!)
1311 MData().m_xCaret = -1;
1312 }
1313
1314 ClearSelection();
1315}
1316
1317void wxTextCtrl::InitInsertionPoint()
1318{
1319 // so far always put it in the beginning
1320 DoSetInsertionPoint(0);
1321
1322 // this will also set the selection anchor correctly
1323 ClearSelection();
1324}
1325
1326void wxTextCtrl::MoveInsertionPoint(wxTextPos pos)
1327{
1328 wxASSERT_MSG( pos >= 0 && pos <= GetLastPosition(),
1329 _T("DoSetInsertionPoint() can only be called with valid pos") );
1330
1331 m_curPos = pos;
1332 PositionToXY(m_curPos, &m_curCol, &m_curRow);
1333}
1334
1335void wxTextCtrl::DoSetInsertionPoint(wxTextPos pos)
1336{
1337 MoveInsertionPoint(pos);
1338
1339 ShowPosition(pos);
1340}
1341
1342void wxTextCtrl::SetInsertionPointEnd()
1343{
1344 SetInsertionPoint(GetLastPosition());
1345}
1346
1347wxTextPos wxTextCtrl::GetInsertionPoint() const
1348{
1349 return m_curPos;
1350}
1351
1352wxTextPos wxTextCtrl::GetLastPosition() const
1353{
1354 wxTextPos pos;
1355 if ( IsSingleLine() )
1356 {
1357 pos = m_value.length();
1358 }
1359 else // multiline
1360 {
1361#ifdef WXDEBUG_TEXT
1362 pos = 0;
1363 size_t nLineCount = GetLineCount();
1364 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
1365 {
1366 // +1 is because the positions at the end of this line and of the
1367 // start of the next one are different
1368 pos += GetLines()[nLine].length() + 1;
1369 }
1370
1371 if ( pos > 0 )
1372 {
1373 // the last position is at the end of the last line, not in the
1374 // beginning of the next line after it
1375 pos--;
1376 }
1377
1378 // more probable reason of this would be to forget to update m_posLast
1379 wxASSERT_MSG( pos == m_posLast, _T("bug in GetLastPosition()") );
1380#endif // WXDEBUG_TEXT
1381
1382 pos = m_posLast;
1383 }
1384
1385 return pos;
1386}
1387
1388// ----------------------------------------------------------------------------
1389// selection
1390// ----------------------------------------------------------------------------
1391
1392void wxTextCtrl::GetSelection(wxTextPos* from, wxTextPos* to) const
1393{
1394 if ( from )
1395 *from = m_selStart;
1396 if ( to )
1397 *to = m_selEnd;
1398}
1399
1400wxString wxTextCtrl::GetSelectionText() const
1401{
1402 wxString sel;
1403
1404 if ( HasSelection() )
1405 {
1406 if ( IsSingleLine() )
1407 {
1408 sel = m_value.Mid(m_selStart, m_selEnd - m_selStart);
1409 }
1410 else // multiline
1411 {
1412 wxTextCoord colStart, lineStart,
1413 colEnd, lineEnd;
1414 PositionToXY(m_selStart, &colStart, &lineStart);
1415 PositionToXY(m_selEnd, &colEnd, &lineEnd);
1416
1417 // as always, we need to check for the special case when the start
1418 // and end line are the same
1419 if ( lineEnd == lineStart )
1420 {
1421 sel = GetLines()[lineStart].Mid(colStart, colEnd - colStart);
1422 }
1423 else // sel on multiple lines
1424 {
1425 // take the end of the first line
1426 sel = GetLines()[lineStart].c_str() + colStart;
1427 sel += _T('\n');
1428
1429 // all intermediate ones
1430 for ( wxTextCoord line = lineStart + 1; line < lineEnd; line++ )
1431 {
1432 sel << GetLines()[line] << _T('\n');
1433 }
1434
1435 // and the start of the last one
1436 sel += GetLines()[lineEnd].Left(colEnd);
1437 }
1438 }
1439 }
1440
1441 return sel;
1442}
1443
1444void wxTextCtrl::SetSelection(wxTextPos from, wxTextPos to)
1445{
1446 // selecting till -1 is the same as selecting to the end
b5a3a81b 1447 if ( to == -1 )
1e6feb95 1448 {
b5a3a81b
VZ
1449 // and selecting (-1, -1) range is the same as selecting everything, by
1450 // convention
1451 if ( from == -1 )
1452 from = 0;
1e6feb95
VZ
1453 to = GetLastPosition();
1454 }
1455
1456 if ( from == -1 || to == from )
1457 {
1458 ClearSelection();
1459 }
1460 else // valid sel range
1461 {
3febfc6b
VZ
1462 // remember the 'to' position as the current position, used to move the
1463 // caret there later
1464 wxTextPos toOrig = to;
1465
1e6feb95
VZ
1466 OrderPositions(from, to);
1467
1468 wxCHECK_RET( to <= GetLastPosition(),
1469 _T("invalid range in wxTextCtrl::SetSelection") );
1470
1471 if ( from != m_selStart || to != m_selEnd )
1472 {
1473 // we need to use temp vars as RefreshTextRange() may call DoDraw()
1474 // directly and so m_selStart/End must be reset by then
1475 wxTextPos selStartOld = m_selStart,
1476 selEndOld = m_selEnd;
1477
1478 m_selStart = from;
1479 m_selEnd = to;
1480
1481 wxLogTrace(_T("text"), _T("Selection range is %ld-%ld"),
1482 m_selStart, m_selEnd);
1483
1484 // refresh only the part of text which became (un)selected if
1485 // possible
1486 if ( selStartOld == m_selStart )
1487 {
1488 RefreshTextRange(selEndOld, m_selEnd);
1489 }
1490 else if ( selEndOld == m_selEnd )
1491 {
1492 RefreshTextRange(m_selStart, selStartOld);
1493 }
1494 else
1495 {
1496 // OPT: could check for other cases too but it is probably not
1497 // worth it as the two above are the most common ones
1498 if ( selStartOld != -1 )
1499 RefreshTextRange(selStartOld, selEndOld);
1500 if ( m_selStart != -1 )
1501 RefreshTextRange(m_selStart, m_selEnd);
1502 }
1503
1504 // we need to fully repaint the invalidated areas of the window
1505 // before scrolling it (from DoSetInsertionPoint which is typically
1506 // called after SetSelection()), otherwise they may stay unpainted
1507 m_targetWindow->Update();
1508 }
1509 //else: nothing to do
1510
3febfc6b
VZ
1511 // the insertion point is put at the location where the caret was moved
1512 DoSetInsertionPoint(toOrig);
1e6feb95
VZ
1513 }
1514}
1515
1516void wxTextCtrl::ClearSelection()
1517{
1518 if ( HasSelection() )
1519 {
1520 // we need to use temp vars as RefreshTextRange() may call DoDraw()
1521 // directly (see above as well)
1522 wxTextPos selStart = m_selStart,
1523 selEnd = m_selEnd;
1524
1525 // no selection any more
1526 m_selStart =
1527 m_selEnd = -1;
1528
1529 // refresh the old selection
1530 RefreshTextRange(selStart, selEnd);
1531 }
1532
1533 // the anchor should be moved even if there was no selection previously
1534 m_selAnchor = m_curPos;
1535}
1536
1537void wxTextCtrl::RemoveSelection()
1538{
1539 if ( !HasSelection() )
1540 return;
1541
1542 Remove(m_selStart, m_selEnd);
1543}
1544
1545bool wxTextCtrl::GetSelectedPartOfLine(wxTextCoord line,
1546 wxTextPos *start, wxTextPos *end) const
1547{
1548 if ( start )
1549 *start = -1;
1550 if ( end )
1551 *end = -1;
1552
1553 if ( !HasSelection() )
1554 {
1555 // no selection at all, hence no selection in this line
a290fa5a 1556 return false;
1e6feb95
VZ
1557 }
1558
1559 wxTextCoord lineStart, colStart;
1560 PositionToXY(m_selStart, &colStart, &lineStart);
1561 if ( lineStart > line )
1562 {
1563 // this line is entirely above the selection
a290fa5a 1564 return false;
1e6feb95
VZ
1565 }
1566
1567 wxTextCoord lineEnd, colEnd;
1568 PositionToXY(m_selEnd, &colEnd, &lineEnd);
1569 if ( lineEnd < line )
1570 {
1571 // this line is entirely below the selection
a290fa5a 1572 return false;
1e6feb95
VZ
1573 }
1574
1575 if ( line == lineStart )
1576 {
1577 if ( start )
1578 *start = colStart;
1579 if ( end )
1580 *end = lineEnd == lineStart ? colEnd : GetLineLength(line);
1581 }
1582 else if ( line == lineEnd )
1583 {
1584 if ( start )
1585 *start = lineEnd == lineStart ? colStart : 0;
1586 if ( end )
1587 *end = colEnd;
1588 }
1589 else // the line is entirely inside the selection
1590 {
1591 if ( start )
1592 *start = 0;
1593 if ( end )
1594 *end = GetLineLength(line);
1595 }
1596
a290fa5a 1597 return true;
1e6feb95
VZ
1598}
1599
1600// ----------------------------------------------------------------------------
1601// flags
1602// ----------------------------------------------------------------------------
1603
1604bool wxTextCtrl::IsModified() const
1605{
1606 return m_isModified;
1607}
1608
1609bool wxTextCtrl::IsEditable() const
1610{
1611 // disabled control can never be edited
1612 return m_isEditable && IsEnabled();
1613}
1614
3a9fa0d6
VZ
1615void wxTextCtrl::MarkDirty()
1616{
a290fa5a 1617 m_isModified = true;
3a9fa0d6
VZ
1618}
1619
1e6feb95
VZ
1620void wxTextCtrl::DiscardEdits()
1621{
a290fa5a 1622 m_isModified = false;
1e6feb95
VZ
1623}
1624
1625void wxTextCtrl::SetEditable(bool editable)
1626{
1627 if ( editable != m_isEditable )
1628 {
1629 m_isEditable = editable;
1630
1631 // the caret (dis)appears
1632 CreateCaret();
1633
1634 // the appearance of the control might have changed
1635 Refresh();
1636 }
1637}
1638
1639// ----------------------------------------------------------------------------
1640// col/lines <-> position correspondence
1641// ----------------------------------------------------------------------------
1642
1643/*
1644 A few remarks about this stuff:
1645
1646 o The numbering of the text control columns/rows starts from 0.
1647 o Start of first line is position 0, its last position is line.length()
1648 o Start of the next line is the last position of the previous line + 1
1649 */
1650
1651int wxTextCtrl::GetLineLength(wxTextCoord line) const
1652{
1653 if ( IsSingleLine() )
1654 {
1655 wxASSERT_MSG( line == 0, _T("invalid GetLineLength() parameter") );
1656
1657 return m_value.length();
1658 }
1659 else // multiline
1660 {
1661 wxCHECK_MSG( (size_t)line < GetLineCount(), -1,
1662 _T("line index out of range") );
1663
1664 return GetLines()[line].length();
1665 }
1666}
1667
1668wxString wxTextCtrl::GetLineText(wxTextCoord line) const
1669{
1670 if ( IsSingleLine() )
1671 {
1672 wxASSERT_MSG( line == 0, _T("invalid GetLineLength() parameter") );
1673
1674 return m_value;
1675 }
1676 else // multiline
1677 {
290e4c83
CE
1678 //this is called during DoGetBestSize
1679 if (line == 0 && GetLineCount() == 0) return wxEmptyString ;
34158fee 1680
0966aee3 1681 wxCHECK_MSG( (size_t)line < GetLineCount(), wxEmptyString,
1e6feb95
VZ
1682 _T("line index out of range") );
1683
1684 return GetLines()[line];
1685 }
1686}
1687
1688int wxTextCtrl::GetNumberOfLines() const
1689{
1690 // there is always 1 line, even if the text is empty
1691 return IsSingleLine() ? 1 : GetLineCount();
1692}
1693
1694wxTextPos wxTextCtrl::XYToPosition(wxTextCoord x, wxTextCoord y) const
1695{
1696 // note that this method should accept any values of x and y and return -1
1697 // if they are out of range
1698 if ( IsSingleLine() )
1699 {
7d8268a1 1700 return ( x > GetLastPosition() || y > 0 ) ? wxOutOfRangeTextCoord : x;
1e6feb95
VZ
1701 }
1702 else // multiline
1703 {
1704 if ( (size_t)y >= GetLineCount() )
1705 {
1706 // this position is below the text
1707 return GetLastPosition();
1708 }
1709
1710 wxTextPos pos = 0;
1711 for ( size_t nLine = 0; nLine < (size_t)y; nLine++ )
1712 {
1713 // +1 is because the positions at the end of this line and of the
1714 // start of the next one are different
1715 pos += GetLines()[nLine].length() + 1;
1716 }
1717
1718 // take into account also the position in line
1719 if ( (size_t)x > GetLines()[y].length() )
1720 {
1721 // don't return position in the next line
1722 x = GetLines()[y].length();
1723 }
1724
1725 return pos + x;
1726 }
1727}
1728
1729bool wxTextCtrl::PositionToXY(wxTextPos pos,
1730 wxTextCoord *x, wxTextCoord *y) const
1731{
1732 if ( IsSingleLine() )
1733 {
1734 if ( (size_t)pos > m_value.length() )
a290fa5a 1735 return false;
1e6feb95
VZ
1736
1737 if ( x )
1738 *x = pos;
1739 if ( y )
1740 *y = 0;
1741
a290fa5a 1742 return true;
1e6feb95
VZ
1743 }
1744 else // multiline
1745 {
1746 wxTextPos posCur = 0;
1747 size_t nLineCount = GetLineCount();
1748 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
1749 {
1750 // +1 is because the start the start of the next line is one
1751 // position after the end of this one
1752 wxTextPos posNew = posCur + GetLines()[nLine].length() + 1;
1753 if ( posNew > pos )
1754 {
1755 // we've found the line, now just calc the column
1756 if ( x )
1757 *x = pos - posCur;
1758
1759 if ( y )
1760 *y = nLine;
1761
1762#ifdef WXDEBUG_TEXT
1763 wxASSERT_MSG( XYToPosition(pos - posCur, nLine) == pos,
1764 _T("XYToPosition() or PositionToXY() broken") );
1765#endif // WXDEBUG_TEXT
1766
a290fa5a 1767 return true;
1e6feb95
VZ
1768 }
1769 else // go further down
1770 {
1771 posCur = posNew;
1772 }
1773 }
1774
1775 // beyond the last line
a290fa5a 1776 return false;
1e6feb95
VZ
1777 }
1778}
1779
1780wxTextCoord wxTextCtrl::GetRowsPerLine(wxTextCoord line) const
1781{
1782 // a normal line has one row
1783 wxTextCoord numRows = 1;
1784
1785 if ( WrapLines() )
1786 {
1787 // add the number of additional rows
1788 numRows += WData().m_linesData[line].GetExtraRowCount();
1789 }
1790
1791 return numRows;
1792}
1793
1794wxTextCoord wxTextCtrl::GetRowCount() const
1795{
1796 wxTextCoord count = GetLineCount();
1a77875b
JS
1797 if (count == 0)
1798 return 0;
1e6feb95
VZ
1799 if ( WrapLines() )
1800 {
1801 count = GetFirstRowOfLine(count - 1) +
1802 WData().m_linesData[count - 1].GetRowCount();
1803 }
1804
1805 return count;
1806}
1807
1808wxTextCoord wxTextCtrl::GetRowAfterLine(wxTextCoord line) const
1809{
1810 if ( !WrapLines() )
1811 return line + 1;
1812
1813 if ( !WData().IsValidLine(line) )
1814 {
1815 LayoutLines(line);
1816 }
1817
1818 return WData().m_linesData[line].GetNextRow();
1819}
1820
1821wxTextCoord wxTextCtrl::GetFirstRowOfLine(wxTextCoord line) const
1822{
1823 if ( !WrapLines() )
1824 return line;
1825
1826 if ( !WData().IsValidLine(line) )
1827 {
1828 LayoutLines(line);
1829 }
1830
1831 return WData().m_linesData[line].GetFirstRow();
1832}
1833
1834bool wxTextCtrl::PositionToLogicalXY(wxTextPos pos,
1835 wxCoord *xOut,
1836 wxCoord *yOut) const
1837{
1838 wxTextCoord col, line;
1839
1840 // optimization for special (but common) case when we already have the col
1841 // and line
1842 if ( pos == m_curPos )
1843 {
1844 col = m_curCol;
1845 line = m_curRow;
1846 }
1847 else // must really calculate col/line from pos
1848 {
1849 if ( !PositionToXY(pos, &col, &line) )
a290fa5a 1850 return false;
1e6feb95
VZ
1851 }
1852
1853 int hLine = GetLineHeight();
1854 wxCoord x, y;
1855 wxString textLine = GetLineText(line);
1856 if ( IsSingleLine() || !WrapLines() )
1857 {
1858 x = GetTextWidth(textLine.Left(col));
1859 y = line*hLine;
1860 }
1861 else // difficult case: multline control with line wrap
1862 {
1863 y = GetFirstRowOfLine(line);
1864
1865 wxTextCoord colRowStart;
1866 y += GetRowInLine(line, col, &colRowStart);
1867
1868 y *= hLine;
1869
1870 // x is the width of the text before this position in this row
1871 x = GetTextWidth(textLine.Mid(colRowStart, col - colRowStart));
1872 }
1873
1874 if ( xOut )
1875 *xOut = x;
1876 if ( yOut )
1877 *yOut = y;
1878
a290fa5a 1879 return true;
1e6feb95
VZ
1880}
1881
1882bool wxTextCtrl::PositionToDeviceXY(wxTextPos pos,
1883 wxCoord *xOut,
1884 wxCoord *yOut) const
1885{
1886 wxCoord x, y;
1887 if ( !PositionToLogicalXY(pos, &x, &y) )
a290fa5a 1888 return false;
1e6feb95
VZ
1889
1890 // finally translate the logical text rect coords into physical client
1891 // coords
1892 CalcScrolledPosition(m_rectText.x + x, m_rectText.y + y, xOut, yOut);
1893
a290fa5a 1894 return true;
1e6feb95
VZ
1895}
1896
1897wxPoint wxTextCtrl::GetCaretPosition() const
1898{
1899 wxCoord xCaret, yCaret;
1900 if ( !PositionToDeviceXY(m_curPos, &xCaret, &yCaret) )
1901 {
1902 wxFAIL_MSG( _T("Caret can't be beyond the text!") );
1903 }
1904
1905 return wxPoint(xCaret, yCaret);
1906}
1907
1908// pos may be -1 to show the current position
1909void wxTextCtrl::ShowPosition(wxTextPos pos)
1910{
e28c2d15
JS
1911 bool showCaret = GetCaret() && GetCaret()->IsVisible();
1912 if (showCaret)
1913 HideCaret();
1e6feb95
VZ
1914
1915 if ( IsSingleLine() )
1916 {
1917 ShowHorzPosition(GetTextWidth(m_value.Left(pos)));
1918 }
1919 else if ( MData().m_scrollRangeX || MData().m_scrollRangeY ) // multiline with scrollbars
1920 {
1921 int xStart, yStart;
1922 GetViewStart(&xStart, &yStart);
1923
1924 if ( pos == -1 )
1925 pos = m_curPos;
1926
1927 wxCoord x, y;
1928 PositionToLogicalXY(pos, &x, &y);
1929
1930 wxRect rectText = GetRealTextArea();
1931
1932 // scroll the position vertically into view: if it is currently above
1933 // it, make it the first one, otherwise the last one
1934 if ( MData().m_scrollRangeY )
1935 {
1936 y /= GetLineHeight();
1937
1938 if ( y < yStart )
1939 {
1940 Scroll(0, y);
1941 }
1942 else // we are currently in or below the view area
1943 {
1944 // find the last row currently shown
1945 wxTextCoord yEnd;
1946
1947 if ( WrapLines() )
1948 {
1949 // to find the last row we need to use the generic HitTest
1950 wxTextCoord col;
1951
1952 // OPT this is a bit silly: we undo this in HitTest(), so
1953 // it would be better to factor out the common
1954 // functionality into a separate function (OTOH it
1955 // won't probably save us that much)
1956 wxPoint pt(0, rectText.height - 1);
1957 pt += GetClientAreaOrigin();
1958 pt += m_rectText.GetPosition();
1959 HitTest(pt, &col, &yEnd);
1960
1961 // find the row inside the line
1962 yEnd = GetFirstRowOfLine(yEnd) + GetRowInLine(yEnd, col);
1963 }
1964 else
1965 {
1966 // finding the last line is easy if each line has exactly
1967 // one row
1968 yEnd = yStart + rectText.height / GetLineHeight() - 1;
1969 }
1970
1971 if ( yEnd < y )
1972 {
1973 // scroll down: the current item should appear at the
1974 // bottom of the view
1975 Scroll(0, y - (yEnd - yStart));
1976 }
1977 }
1978 }
1979
1980 // scroll the position horizontally into view
1981 //
1982 // we follow what I believe to be Windows behaviour here, that is if
1983 // the position is already entirely in the view we do nothing, but if
1984 // we do have to scroll the window to bring it into view, we scroll it
1985 // not just enough to show the position but slightly more so that this
1986 // position is at 1/3 of the window width from the closest border to it
1987 // (I'm not sure that Windows does exactly this but it looks like this)
1988 if ( MData().m_scrollRangeX )
1989 {
1990 // unlike for the rows, xStart doesn't correspond to the starting
1991 // column as they all have different widths, so we need to
1992 // translate everything to pixels
1993
1994 // we want the text between x and x2 be entirely inside the view
1995 // (i.e. the current character)
1996
1997 // make xStart the first visible pixel (and not position)
1998 int wChar = GetAverageWidth();
1999 xStart *= wChar;
2000
2001 if ( x < xStart )
2002 {
2003 // we want the position of this column be 1/3 to the right of
2004 // the left edge
2005 x -= rectText.width / 3;
2006 if ( x < 0 )
2007 x = 0;
2008 Scroll(x / wChar, y);
2009 }
2010 else // maybe we're beyond the right border of the view?
2011 {
2012 wxTextCoord col, row;
2013 if ( PositionToXY(pos, &col, &row) )
2014 {
2015 wxString lineText = GetLineText(row);
2016 wxCoord x2 = x + GetTextWidth(lineText[(size_t)col]);
2017 if ( x2 > xStart + rectText.width )
2018 {
2019 // we want the position of this column be 1/3 to the
2020 // left of the right edge, i.e. 2/3 right of the left
2021 // one
2022 x2 -= (2*rectText.width)/3;
2023 if ( x2 < 0 )
2024 x2 = 0;
2025 Scroll(x2 / wChar, row);
2026 }
2027 }
2028 }
2029 }
2030 }
2031 //else: multiline but no scrollbars, hence nothing to do
2032
e28c2d15
JS
2033 if (showCaret)
2034 ShowCaret();
1e6feb95
VZ
2035}
2036
2037// ----------------------------------------------------------------------------
2038// word stuff
2039// ----------------------------------------------------------------------------
2040
2041/*
2042 TODO: we could have (easy to do) vi-like options for word movement, i.e.
2043 distinguish between inlusive/exclusive words and between words and
2044 WORDS (in vim sense) and also, finally, make the set of characters
2045 which make up a word configurable - currently we use the exclusive
2046 WORDS only (coincidentally, this is what Windows edit control does)
2047
2048 For future references, here is what vim help says:
2049
2050 A word consists of a sequence of letters, digits and underscores, or
2051 a sequence of other non-blank characters, separated with white space
2052 (spaces, tabs, <EOL>). This can be changed with the 'iskeyword'
2053 option.
2054
2055 A WORD consists of a sequence of non-blank characters, separated with
2056 white space. An empty line is also considered to be a word and a
2057 WORD.
2058 */
2059
2060static inline bool IsWordChar(wxChar ch)
2061{
2062 return !wxIsspace(ch);
2063}
2064
2065wxTextPos wxTextCtrl::GetWordStart() const
2066{
2067 if ( m_curPos == -1 || m_curPos == 0 )
2068 return 0;
2069
2070 if ( m_curCol == 0 )
2071 {
2072 // go to the end of the previous line
2073 return m_curPos - 1;
2074 }
2075
2076 // it shouldn't be possible to learn where the word starts in the password
2077 // text entry zone
2078 if ( IsPassword() )
2079 return 0;
2080
2081 // start at the previous position
2082 const wxChar *p0 = GetLineText(m_curRow).c_str();
2083 const wxChar *p = p0 + m_curCol - 1;
2084
2085 // find the end of the previous word
2086 while ( (p > p0) && !IsWordChar(*p) )
2087 p--;
2088
2089 // now find the beginning of this word
2090 while ( (p > p0) && IsWordChar(*p) )
2091 p--;
2092
2093 // we might have gone too far
2094 if ( !IsWordChar(*p) )
2095 p++;
2096
2097 return (m_curPos - m_curCol) + p - p0;
2098}
2099
2100wxTextPos wxTextCtrl::GetWordEnd() const
2101{
2102 if ( m_curPos == -1 )
2103 return 0;
2104
2105 wxString line = GetLineText(m_curRow);
2106 if ( (size_t)m_curCol == line.length() )
2107 {
2108 // if we're on the last position in the line, go to the next one - if
2109 // it exists
2110 wxTextPos pos = m_curPos;
2111 if ( pos < GetLastPosition() )
2112 pos++;
2113
2114 return pos;
2115 }
2116
2117 // it shouldn't be possible to learn where the word ends in the password
2118 // text entry zone
2119 if ( IsPassword() )
2120 return GetLastPosition();
2121
2122 // start at the current position
2123 const wxChar *p0 = line.c_str();
2124 const wxChar *p = p0 + m_curCol;
2125
2126 // find the start of the next word
2127 while ( *p && !IsWordChar(*p) )
2128 p++;
2129
2130 // now find the end of it
2131 while ( *p && IsWordChar(*p) )
2132 p++;
2133
2134 // and find the start of the next word
2135 while ( *p && !IsWordChar(*p) )
2136 p++;
2137
2138 return (m_curPos - m_curCol) + p - p0;
2139}
2140
2141// ----------------------------------------------------------------------------
2142// clipboard stuff
2143// ----------------------------------------------------------------------------
2144
2145void wxTextCtrl::Copy()
2146{
2147#if wxUSE_CLIPBOARD
2148 if ( HasSelection() )
2149 {
2150 wxClipboardLocker clipLock;
2151
2152 // wxTextFile::Translate() is needed to transform all '\n' into "\r\n"
2153 wxString text = wxTextFile::Translate(GetTextToShow(GetSelectionText()));
2154 wxTextDataObject *data = new wxTextDataObject(text);
2155 wxTheClipboard->SetData(data);
2156 }
2157#endif // wxUSE_CLIPBOARD
2158}
2159
2160void wxTextCtrl::Cut()
2161{
2162 (void)DoCut();
2163}
2164
2165bool wxTextCtrl::DoCut()
2166{
2167 if ( !HasSelection() )
a290fa5a 2168 return false;
1e6feb95
VZ
2169
2170 Copy();
2171
2172 RemoveSelection();
2173
a290fa5a 2174 return true;
1e6feb95
VZ
2175}
2176
2177void wxTextCtrl::Paste()
2178{
2179 (void)DoPaste();
2180}
2181
2182bool wxTextCtrl::DoPaste()
2183{
2184#if wxUSE_CLIPBOARD
2185 wxClipboardLocker clipLock;
2186
2187 wxTextDataObject data;
2188 if ( wxTheClipboard->IsSupported(data.GetFormat())
2189 && wxTheClipboard->GetData(data) )
2190 {
2191 // reverse transformation: '\r\n\" -> '\n'
2192 wxString text = wxTextFile::Translate(data.GetText(),
2193 wxTextFileType_Unix);
2194 if ( !text.empty() )
2195 {
2196 WriteText(text);
2197
a290fa5a 2198 return true;
1e6feb95
VZ
2199 }
2200 }
2201#endif // wxUSE_CLIPBOARD
2202
a290fa5a 2203 return false;
1e6feb95
VZ
2204}
2205
2206// ----------------------------------------------------------------------------
2207// Undo and redo
2208// ----------------------------------------------------------------------------
2209
2210wxTextCtrlInsertCommand *
2211wxTextCtrlCommandProcessor::IsInsertCommand(wxCommand *command)
2212{
2213 return (wxTextCtrlInsertCommand *)
2214 (command && (command->GetName() == wxTEXT_COMMAND_INSERT)
2215 ? command : NULL);
2216}
2217
2218void wxTextCtrlCommandProcessor::Store(wxCommand *command)
2219{
2220 wxTextCtrlInsertCommand *cmdIns = IsInsertCommand(command);
2221 if ( cmdIns )
2222 {
2223 if ( IsCompressing() )
2224 {
2225 wxTextCtrlInsertCommand *
2226 cmdInsLast = IsInsertCommand(GetCurrentCommand());
2227
2228 // it is possible that we don't have any last command at all if,
2229 // for example, it was undone since the last Store(), so deal with
2230 // this case too
2231 if ( cmdInsLast )
2232 {
2233 cmdInsLast->Append(cmdIns);
2234
2235 delete cmdIns;
2236
2237 // don't need to call the base class version
2238 return;
2239 }
2240 }
2241
2242 // append the following insert commands to this one
a290fa5a 2243 m_compressInserts = true;
1e6feb95
VZ
2244
2245 // let the base class version will do the job normally
2246 }
2247 else // not an insert command
2248 {
2249 // stop compressing insert commands - this won't work with the last
2250 // command not being an insert one anyhow
2251 StopCompressing();
2252
2253 // let the base class version will do the job normally
2254 }
2255
2256 wxCommandProcessor::Store(command);
2257}
2258
2259void wxTextCtrlInsertCommand::Append(wxTextCtrlInsertCommand *other)
2260{
2261 m_text += other->m_text;
2262}
2263
2264bool wxTextCtrlInsertCommand::CanUndo() const
2265{
2266 return m_from != -1;
2267}
2268
2269bool wxTextCtrlInsertCommand::Do(wxTextCtrl *text)
2270{
2271 // the text is going to be inserted at the current position, remember where
2272 // exactly it is
2273 m_from = text->GetInsertionPoint();
2274
2275 // and now do insert it
2276 text->WriteText(m_text);
2277
a290fa5a 2278 return true;
1e6feb95
VZ
2279}
2280
2281bool wxTextCtrlInsertCommand::Undo(wxTextCtrl *text)
2282{
a290fa5a 2283 wxCHECK_MSG( CanUndo(), false, _T("impossible to undo insert cmd") );
1e6feb95
VZ
2284
2285 // remove the text from where we inserted it
2286 text->Remove(m_from, m_from + m_text.length());
2287
a290fa5a 2288 return true;
1e6feb95
VZ
2289}
2290
2291bool wxTextCtrlRemoveCommand::CanUndo() const
2292{
2293 // if we were executed, we should have the text we removed
2294 return !m_textDeleted.empty();
2295}
2296
2297bool wxTextCtrlRemoveCommand::Do(wxTextCtrl *text)
2298{
2299 text->SetSelection(m_from, m_to);
2300 m_textDeleted = text->GetSelectionText();
2301 text->RemoveSelection();
2302
a290fa5a 2303 return true;
1e6feb95
VZ
2304}
2305
2306bool wxTextCtrlRemoveCommand::Undo(wxTextCtrl *text)
2307{
2308 // it is possible that the text was deleted and that we can't restore text
2309 // at the same position we removed it any more
2310 wxTextPos posLast = text->GetLastPosition();
2311 text->SetInsertionPoint(m_from > posLast ? posLast : m_from);
2312 text->WriteText(m_textDeleted);
2313
a290fa5a 2314 return true;
1e6feb95
VZ
2315}
2316
2317void wxTextCtrl::Undo()
2318{
2319 // the caller must check it
2320 wxASSERT_MSG( CanUndo(), _T("can't call Undo() if !CanUndo()") );
2321
2322 m_cmdProcessor->Undo();
2323}
2324
2325void wxTextCtrl::Redo()
2326{
2327 // the caller must check it
2328 wxASSERT_MSG( CanRedo(), _T("can't call Undo() if !CanUndo()") );
2329
2330 m_cmdProcessor->Redo();
2331}
2332
2333bool wxTextCtrl::CanUndo() const
2334{
2335 return IsEditable() && m_cmdProcessor->CanUndo();
2336}
2337
2338bool wxTextCtrl::CanRedo() const
2339{
2340 return IsEditable() && m_cmdProcessor->CanRedo();
2341}
2342
2343// ----------------------------------------------------------------------------
2344// geometry
2345// ----------------------------------------------------------------------------
2346
2347wxSize wxTextCtrl::DoGetBestClientSize() const
2348{
2349 // when we're called for the very first time from Create() we must
2350 // calculate the font metrics here because we can't do it before calling
2351 // Create() (there is no window yet and wxGTK crashes) but we need them
2352 // here
2353 if ( m_heightLine == -1 )
2354 {
2355 wxConstCast(this, wxTextCtrl)->RecalcFontMetrics();
2356 }
2357
2358 wxCoord w, h;
2359 GetTextExtent(GetTextToShow(GetLineText(0)), &w, &h);
2360
2361 int wChar = GetAverageWidth(),
2362 hChar = GetLineHeight();
2363
2364 int widthMin = wxMax(10*wChar, 100);
2365 if ( w < widthMin )
2366 w = widthMin;
2367 if ( h < hChar )
2368 h = hChar;
2369
2370 if ( !IsSingleLine() )
2371 {
2372 // let the control have a reasonable number of lines
2373 int lines = GetNumberOfLines();
2374 if ( lines < 5 )
2375 lines = 5;
2376 else if ( lines > 10 )
2377 lines = 10;
999836aa 2378 h *= lines;
1e6feb95
VZ
2379 }
2380
2381 wxRect rectText;
2382 rectText.width = w;
2383 rectText.height = h;
2384 wxRect rectTotal = GetRenderer()->GetTextTotalArea(this, rectText);
2385 return wxSize(rectTotal.width, rectTotal.height);
2386}
2387
2388void wxTextCtrl::UpdateTextRect()
2389{
34158fee 2390 wxRect rectTotal(GetClientSize());
1e6feb95
VZ
2391 wxCoord *extraSpace = WrapLines() ? &WData().m_widthMark : NULL;
2392 m_rectText = GetRenderer()->GetTextClientArea(this, rectTotal, extraSpace);
2393
2394 // code elsewhere is confused by negative rect size
2395 if ( m_rectText.width <= 0 )
2396 m_rectText.width = 1;
2397 if ( m_rectText.height <= 0 )
2398 m_rectText.height = 1;
2399
2400 if ( !IsSingleLine() )
2401 {
2402 // invalidate it so that GetRealTextArea() will recalc it
2403 MData().m_rectTextReal.width = 0;
2404
2405 // only scroll this rect when the window is scrolled: note that we have
2406 // to scroll not only the text but the line wrap marks too if we show
2407 // them
2408 wxRect rectText = GetRealTextArea();
2409 if ( extraSpace && *extraSpace )
2410 {
2411 rectText.width += *extraSpace;
2412 }
2413 SetTargetRect(rectText);
2414
2415 // relayout all lines
2416 if ( WrapLines() )
2417 {
2418 WData().m_rowFirstInvalid = 0;
2419
2420 // increase timestamp: this means that the lines which had been
2421 // laid out before will be relayd out the next time LayoutLines()
2422 // is called because their timestamp will be smaller than the
2423 // current one
2424 WData().m_timestamp++;
2425 }
2426 }
2427
2428 UpdateLastVisible();
2429}
2430
2431void wxTextCtrl::UpdateLastVisible()
2432{
2433 // this method is only used for horizontal "scrollbarless" scrolling which
2434 // is used only with single line controls
2435 if ( !IsSingleLine() )
2436 return;
2437
2438 // use (efficient) HitTestLine to find the last visible character
2439 wxString text = m_value.Mid((size_t)SData().m_colStart /* to the end */);
2440 wxTextCoord col;
2441 switch ( HitTestLine(text, m_rectText.width, &col) )
2442 {
2443 case wxTE_HT_BEYOND:
2444 // everything is visible
2445 SData().m_colLastVisible = text.length();
2446
2447 // calc it below
2448 SData().m_posLastVisible = -1;
2449 break;
2450
2451 /*
2452 case wxTE_HT_BEFORE:
2453 case wxTE_HT_BELOW:
2454 */
2455 default:
2456 wxFAIL_MSG(_T("unexpected HitTestLine() return value"));
2457 // fall through
2458
2459 case wxTE_HT_ON_TEXT:
2460 if ( col > 0 )
2461 {
2462 // the last entirely seen character is the previous one because
2463 // this one is only partly visible - unless the width of the
2464 // string is exactly the max width
2465 SData().m_posLastVisible = GetTextWidth(text.Truncate(col + 1));
2466 if ( SData().m_posLastVisible > m_rectText.width )
2467 {
2468 // this character is not entirely visible, take the
2469 // previous one
2470 col--;
2471
2472 // recalc it
2473 SData().m_posLastVisible = -1;
2474 }
2475 //else: we can just see it
2476
2477 SData().m_colLastVisible = col;
2478 }
2479 break;
2480 }
2481
2482 // calculate the width of the text really shown
2483 if ( SData().m_posLastVisible == -1 )
2484 {
2485 SData().m_posLastVisible = GetTextWidth(text.Truncate(SData().m_colLastVisible + 1));
2486 }
2487
2488 // current value is relative the start of the string text which starts at
2489 // SData().m_colStart, we need an absolute offset into string
2490 SData().m_colLastVisible += SData().m_colStart;
2491
2492 wxLogTrace(_T("text"), _T("Last visible column/position is %d/%ld"),
47cd6610 2493 (int) SData().m_colLastVisible, (long) SData().m_posLastVisible);
1e6feb95
VZ
2494}
2495
2496void wxTextCtrl::OnSize(wxSizeEvent& event)
2497{
2498 UpdateTextRect();
2499
2500 if ( !IsSingleLine() )
2501 {
2502#if 0
2503 // update them immediately because if we are called for the first time,
2504 // we need to create them in order for the base class version to
2505 // position the scrollbars correctly - if we don't do it now, it won't
2506 // happen at all if we don't get more size events
2507 UpdateScrollbars();
2508#endif // 0
2509
2510 MData().m_updateScrollbarX =
a290fa5a 2511 MData().m_updateScrollbarY = true;
1e6feb95
VZ
2512 }
2513
2514 event.Skip();
2515}
2516
2517wxCoord wxTextCtrl::GetTotalWidth() const
2518{
2519 wxCoord w;
2520 CalcUnscrolledPosition(m_rectText.width, 0, &w, NULL);
2521 return w;
2522}
2523
2524wxCoord wxTextCtrl::GetTextWidth(const wxString& text) const
2525{
2526 wxCoord w;
2527 GetTextExtent(GetTextToShow(text), &w, NULL);
2528 return w;
2529}
2530
2531wxRect wxTextCtrl::GetRealTextArea() const
2532{
2533 // for single line text control it's just the same as text rect
2534 if ( IsSingleLine() )
2535 return m_rectText;
2536
2537 // the real text area always holds an entire number of lines, so the only
2538 // difference with the text area is a narrow strip along the bottom border
2539 wxRect rectText = MData().m_rectTextReal;
2540 if ( !rectText.width )
2541 {
2542 // recalculate it
2543 rectText = m_rectText;
2544
2545 // when we're called for the very first time, the line height might not
2546 // had been calculated yet, so do get it now
2547 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
2548 self->RecalcFontMetrics();
2549
2550 int hLine = GetLineHeight();
2551 rectText.height = (m_rectText.height / hLine) * hLine;
2552
2553 // cache the result
2554 self->MData().m_rectTextReal = rectText;
2555 }
2556
2557 return rectText;
2558}
2559
2560wxTextCoord wxTextCtrl::GetRowInLine(wxTextCoord line,
2561 wxTextCoord col,
2562 wxTextCoord *colRowStart) const
2563{
2564 wxASSERT_MSG( WrapLines(), _T("shouldn't be called") );
2565
2566 const wxWrappedLineData& lineData = WData().m_linesData[line];
2567
2568 if ( !WData().IsValidLine(line) )
2569 LayoutLines(line);
2570
2571 // row is here counted a bit specially: 0 is the 2nd row of the line (1st
2572 // extra row)
2573 size_t row = 0,
2574 rowMax = lineData.GetExtraRowCount();
2575 if ( rowMax )
2576 {
2577 row = 0;
2578 while ( (row < rowMax) && (col >= lineData.GetExtraRowStart(row)) )
2579 row++;
2580
2581 // it's ok here that row is 1 greater than needed: like this, it is
2582 // counted as a normal (and not extra) row
2583 }
2584 //else: only one row anyhow
2585
2586 if ( colRowStart )
2587 {
2588 // +1 because we need a real row number, not the extra row one
2589 *colRowStart = lineData.GetRowStart(row);
2590
2591 // this can't happen, of course
2592 wxASSERT_MSG( *colRowStart <= col, _T("GetRowInLine() is broken") );
2593 }
2594
2595 return row;
2596}
2597
2598void wxTextCtrl::LayoutLine(wxTextCoord line, wxWrappedLineData& lineData) const
2599{
2600 // FIXME: this uses old GetPartOfWrappedLine() which is not used anywhere
2601 // else now and has rather awkward interface for our needs here
2602
2603 lineData.m_rowsStart.Empty();
2604 lineData.m_rowsWidth.Empty();
2605
2606 const wxString& text = GetLineText(line);
2607 wxCoord widthRow;
2608 size_t colRowStart = 0;
2609 do
2610 {
2611 size_t lenRow = GetPartOfWrappedLine
2612 (
2613 text.c_str() + colRowStart,
2614 &widthRow
2615 );
2616
2617 // remember the start of this row (not for the first one as
2618 // it's always 0) and its width
2619 if ( colRowStart )
2620 lineData.m_rowsStart.Add(colRowStart);
2621 lineData.m_rowsWidth.Add(widthRow);
2622
2623 colRowStart += lenRow;
2624 }
2625 while ( colRowStart < text.length() );
2626
2627 // put the current timestamp on it
2628 lineData.m_timestamp = WData().m_timestamp;
2629}
2630
2631void wxTextCtrl::LayoutLines(wxTextCoord lineLast) const
2632{
2633 wxASSERT_MSG( WrapLines(), _T("should only be used for line wrapping") );
2634
2635 // if we were called, some line was dirty and if it was dirty we must have
2636 // had m_rowFirstInvalid set to something too
2637 wxTextCoord lineFirst = WData().m_rowFirstInvalid;
2638 wxASSERT_MSG( lineFirst != -1, _T("nothing to layout?") );
2639
2640 wxTextCoord rowFirst, rowCur;
2641 if ( lineFirst )
2642 {
2643 // start after the last known valid line
2644 const wxWrappedLineData& lineData = WData().m_linesData[lineFirst - 1];
2645 rowFirst = lineData.GetFirstRow() + lineData.GetRowCount();
2646 }
2647 else // no valid lines, start at row 0
2648 {
2649 rowFirst = 0;
2650 }
2651
2652 rowCur = rowFirst;
2653 for ( wxTextCoord line = lineFirst; line <= lineLast; line++ )
2654 {
2655 // set the starting row for this line
2656 wxWrappedLineData& lineData = WData().m_linesData[line];
2657 lineData.m_rowFirst = rowCur;
2658
2659 // had the line been already broken into rows?
2660 //
2661 // if so, compare its timestamp with the current one: if nothing has
2662 // been changed, don't relayout it
2663 if ( !lineData.IsValid() ||
2664 (lineData.m_timestamp < WData().m_timestamp) )
2665 {
2666 // now do break it in rows
2667 LayoutLine(line, lineData);
2668 }
2669
2670 rowCur += lineData.GetRowCount();
2671 }
2672
2673 // we are now valid at least up to this line, but if it is the last one we
2674 // just don't have any more invalid rows at all
2675 if ( (size_t)lineLast == WData().m_linesData.GetCount() -1 )
2676 {
2677 lineLast = -1;
2678 }
2679
2680 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
2681 self->WData().m_rowFirstInvalid = lineLast;
2682
2683 // also refresh the line end indicators (FIXME shouldn't do it always!)
2684 self->RefreshLineWrapMarks(rowFirst, rowCur);
2685}
2686
2687size_t wxTextCtrl::GetPartOfWrappedLine(const wxChar* text,
2688 wxCoord *widthReal) const
2689{
2690 // this function is slow, it shouldn't be called unless really needed
2691 wxASSERT_MSG( WrapLines(), _T("shouldn't be called") );
2692
2693 wxString s(text);
2694 wxTextCoord col;
a290fa5a 2695 wxCoord wReal = wxDefaultCoord;
1e6feb95
VZ
2696 switch ( HitTestLine(s, m_rectText.width, &col) )
2697 {
2698 /*
2699 case wxTE_HT_BEFORE:
2700 case wxTE_HT_BELOW:
2701 */
2702 default:
2703 wxFAIL_MSG(_T("unexpected HitTestLine() return value"));
2704 // fall through
2705
2706 case wxTE_HT_ON_TEXT:
2707 if ( col > 0 )
2708 {
2709 // the last entirely seen character is the previous one because
2710 // this one is only partly visible - unless the width of the
2711 // string is exactly the max width
2712 wReal = GetTextWidth(s.Truncate(col + 1));
2713 if ( wReal > m_rectText.width )
2714 {
2715 // this character is not entirely visible, take the
2716 // previous one
2717 col--;
2718
2719 // recalc the width
a290fa5a 2720 wReal = wxDefaultCoord;
1e6feb95
VZ
2721 }
2722 //else: we can just see it
2723
2724 // wrap at any character or only at words boundaries?
40ff126a 2725 if ( !(GetWindowStyle() & wxTE_CHARWRAP) )
1e6feb95
VZ
2726 {
2727 // find the (last) not word char before this word
2728 wxTextCoord colWordStart;
2729 for ( colWordStart = col;
2730 colWordStart && IsWordChar(s[(size_t)colWordStart]);
2731 colWordStart-- )
2732 ;
2733
2734 if ( colWordStart > 0 )
2735 {
2736 if ( colWordStart != col )
2737 {
2738 // will have to recalc the real width
a290fa5a 2739 wReal = wxDefaultCoord;
1e6feb95
VZ
2740
2741 col = colWordStart;
2742 }
2743 }
2744 //else: only a single word, have to wrap it here
2745 }
2746 }
2747 break;
2748
2749 case wxTE_HT_BEYOND:
2750 break;
2751 }
2752
2753 // we return the number of characters, not the index of the last one
2754 if ( (size_t)col < s.length() )
2755 {
2756 // but don't return more than this (empty) string has
2757 col++;
2758 }
2759
2760 if ( widthReal )
2761 {
a290fa5a 2762 if ( wReal == wxDefaultCoord )
1e6feb95
VZ
2763 {
2764 // calc it if not done yet
2765 wReal = GetTextWidth(s.Truncate(col));
2766 }
2767
2768 *widthReal = wReal;
2769 }
2770
2771 // VZ: old, horribly inefficient code which can still be used for checking
2772 // the result (in line, not word, wrap mode only) - to be removed later
2773#if 0
2774 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
2775 wxClientDC dc(self);
2776 dc.SetFont(GetFont());
2777 self->DoPrepareDC(dc);
2778
2779 wxCoord widthMax = m_rectText.width;
2780
2781 // the text which we can keep in this ROW
2782 wxString str;
2783 wxCoord w, wOld;
2784 for ( wOld = w = 0; *text && (w <= widthMax); )
2785 {
2786 wOld = w;
2787 str += *text++;
2788 dc.GetTextExtent(str, &w, NULL);
2789 }
2790
2791 if ( w > widthMax )
2792 {
2793 // if we wrapped, the last letter was one too much
2794 if ( str.length() > 1 )
2795 {
2796 // remove it
2797 str.erase(str.length() - 1, 1);
2798 }
2799 else // but always keep at least one letter in each row
2800 {
2801 // the real width then is the last value of w and not teh one
2802 // before last
2803 wOld = w;
2804 }
2805 }
2806 else // we didn't wrap
2807 {
2808 wOld = w;
2809 }
2810
2811 wxASSERT( col == str.length() );
2812
2813 if ( widthReal )
2814 {
2815 wxASSERT( *widthReal == wOld );
2816
2817 *widthReal = wOld;
2818 }
2819
2820 //return str.length();
2821#endif
2822
2823 return col;
2824}
2825
2826// OPT: this function is called a lot - would be nice to optimize it but I
2827// don't really know how yet
2828wxTextCtrlHitTestResult wxTextCtrl::HitTestLine(const wxString& line,
2829 wxCoord x,
2830 wxTextCoord *colOut) const
2831{
2832 wxTextCtrlHitTestResult res = wxTE_HT_ON_TEXT;
2833
2834 int col;
2835 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
2836 wxClientDC dc(self);
2837 dc.SetFont(GetFont());
2838 self->DoPrepareDC(dc);
2839
2840 wxCoord width;
2841 dc.GetTextExtent(line, &width, NULL);
2842 if ( x >= width )
2843 {
2844 // clicking beyond the end of line is equivalent to clicking at
2845 // the end of it, so return the last line column
2846 col = line.length();
2847 if ( col )
2848 {
2849 // unless the line is empty and so doesn't have any column at all -
2850 // in this case return 0, what else can we do?
2851 col--;
2852 }
2853
2854 res = wxTE_HT_BEYOND;
2855 }
2856 else if ( x < 0 )
2857 {
2858 col = 0;
2859
2860 res = wxTE_HT_BEFORE;
2861 }
2862 else // we're inside the line
2863 {
2864 // now calculate the column: first, approximate it with fixed-width
2865 // value and then calculate the correct value iteratively: note that
2866 // we use the first character of the line instead of (average)
2867 // GetCharWidth(): it is common to have lines of dashes, for example,
2868 // and this should give us much better approximation in such case
2869 //
2870 // OPT: maybe using (cache) m_widthAvg would be still faster? profile!
2871 dc.GetTextExtent(line[0], &width, NULL);
2872
2873 col = x / width;
2874 if ( col < 0 )
2875 {
2876 col = 0;
2877 }
2878 else if ( (size_t)col > line.length() )
2879 {
2880 col = line.length();
2881 }
2882
2883 // matchDir is the direction in which we should move to reach the
2884 // character containing the given position
2885 enum
2886 {
2887 Match_Left = -1,
2888 Match_None = 0,
2889 Match_Right = 1
2890 } matchDir = Match_None;
2891 for ( ;; )
2892 {
2893 // check that we didn't go beyond the line boundary
2894 if ( col < 0 )
2895 {
2896 col = 0;
2897 break;
2898 }
2899 if ( (size_t)col > line.length() )
2900 {
2901 col = line.length();
2902 break;
2903 }
2904
2905 wxString strBefore(line, (size_t)col);
2906 dc.GetTextExtent(strBefore, &width, NULL);
2907 if ( width > x )
2908 {
2909 if ( matchDir == Match_Right )
2910 {
2911 // we were going to the right and, finally, moved beyond
2912 // the original position - stop on the previous one
2913 col--;
2914
2915 break;
2916 }
2917
2918 if ( matchDir == Match_None )
2919 {
2920 // we just started iterating, now we know that we should
2921 // move to the left
2922 matchDir = Match_Left;
2923 }
2924 //else: we are still to the right of the target, continue
2925 }
2926 else // width < x
2927 {
2928 // invert the logic above
2929 if ( matchDir == Match_Left )
2930 {
2931 // with the exception that we don't need to backtrack here
2932 break;
2933 }
2934
2935 if ( matchDir == Match_None )
2936 {
2937 // go to the right
2938 matchDir = Match_Right;
2939 }
2940 }
2941
2942 // this is not supposed to happen
2943 wxASSERT_MSG( matchDir, _T("logic error in wxTextCtrl::HitTest") );
2944
2945 if ( matchDir == Match_Right )
2946 col++;
2947 else
2948 col--;
2949 }
2950 }
2951
2952 // check that we calculated it correctly
2953#ifdef WXDEBUG_TEXT
2954 if ( res == wxTE_HT_ON_TEXT )
2955 {
2956 wxCoord width1;
2957 wxString text = line.Left(col);
2958 dc.GetTextExtent(text, &width1, NULL);
2959 if ( (size_t)col < line.length() )
2960 {
2961 wxCoord width2;
2962
2963 text += line[col];
2964 dc.GetTextExtent(text, &width2, NULL);
2965
2966 wxASSERT_MSG( (width1 <= x) && (x < width2),
2967 _T("incorrect HitTestLine() result") );
2968 }
2969 else // we return last char
2970 {
2971 wxASSERT_MSG( x >= width1, _T("incorrect HitTestLine() result") );
2972 }
2973 }
2974#endif // WXDEBUG_TEXT
2975
2976 if ( colOut )
2977 *colOut = col;
2978
2979 return res;
2980}
2981
692c9b86
VZ
2982wxTextCtrlHitTestResult wxTextCtrl::HitTest(const wxPoint& pt, long *pos) const
2983{
2984 wxTextCoord x, y;
2985 wxTextCtrlHitTestResult rc = HitTest(pt, &x, &y);
2986 if ( rc != wxTE_HT_UNKNOWN && pos )
2987 {
2988 *pos = XYToPosition(x, y);
2989 }
2990
2991 return rc;
2992}
2993
1e6feb95
VZ
2994wxTextCtrlHitTestResult wxTextCtrl::HitTest(const wxPoint& pos,
2995 wxTextCoord *colOut,
2996 wxTextCoord *rowOut) const
2997{
2998 return HitTest2(pos.y, pos.x, 0, rowOut, colOut, NULL, NULL);
2999}
3000
3001wxTextCtrlHitTestResult wxTextCtrl::HitTestLogical(const wxPoint& pos,
3002 wxTextCoord *colOut,
3003 wxTextCoord *rowOut) const
3004{
a290fa5a 3005 return HitTest2(pos.y, pos.x, 0, rowOut, colOut, NULL, NULL, false);
1e6feb95
VZ
3006}
3007
3008wxTextCtrlHitTestResult wxTextCtrl::HitTest2(wxCoord y0,
3009 wxCoord x10,
3010 wxCoord x20,
3011 wxTextCoord *rowOut,
3012 wxTextCoord *colStart,
3013 wxTextCoord *colEnd,
3014 wxTextCoord *colRowStartOut,
3015 bool deviceCoords) const
3016{
3017 // is the point in the text area or to the right or below it?
3018 wxTextCtrlHitTestResult res = wxTE_HT_ON_TEXT;
3019
3020 // translate the window coords x0 and y0 into the client coords in the text
3021 // area by adjusting for both the client and text area offsets (unless this
3022 // was already done)
3023 int x1, y;
3024 if ( deviceCoords )
3025 {
3026 wxPoint pt = GetClientAreaOrigin() + m_rectText.GetPosition();
3027 CalcUnscrolledPosition(x10 - pt.x, y0 - pt.y, &x1, &y);
3028 }
3029 else
3030 {
3031 y = y0;
3032 x1 = x10;
3033 }
3034
3035 // calculate the row (it is really a LINE, not a ROW)
3036 wxTextCoord row;
3037
3038 // these vars are used only for WrapLines() case
3039 wxTextCoord colRowStart = 0;
3040 size_t rowLen = 0;
3041
3042 if ( colRowStartOut )
3043 *colRowStartOut = 0;
3044
3045 int hLine = GetLineHeight();
3046 if ( y < 0 )
3047 {
3048 // and clicking before it is the same as clicking on the first one
3049 row = 0;
3050
3051 res = wxTE_HT_BEFORE;
3052 }
3053 else // y >= 0
3054 {
3055 wxTextCoord rowLast = GetNumberOfLines() - 1;
3056 row = y / hLine;
3057 if ( IsSingleLine() || !WrapLines() )
3058 {
3059 // in this case row calculation is simple as all lines have the
3060 // same height and so row is the same as line
3061 if ( row > rowLast )
3062 {
3063 // clicking below the text is the same as clicking on the last
3064 // line
3065 row = rowLast;
3066
3067 res = wxTE_HT_BELOW;
3068 }
3069 }
3070 else // multline control with line wrap
3071 {
3072 // use binary search to find the line containing this row
3073 const wxArrayWrappedLinesData& linesData = WData().m_linesData;
3074 size_t lo = 0,
3075 hi = linesData.GetCount(),
3076 cur;
3077 while ( lo < hi )
3078 {
3079 cur = (lo + hi)/2;
3080 const wxWrappedLineData& lineData = linesData[cur];
3081 if ( !WData().IsValidLine(cur) )
3082 LayoutLines(cur);
3083 wxTextCoord rowFirst = lineData.GetFirstRow();
3084
3085 if ( row < rowFirst )
3086 {
3087 hi = cur;
3088 }
3089 else
3090 {
3091 // our row is after the first row of the cur line:
3092 // obviously, if cur is the last line, it contains this
3093 // row, otherwise we have to test that it is before the
3094 // first row of the next line
3095 bool found = cur == linesData.GetCount() - 1;
3096 if ( found )
3097 {
3098 // if the row is beyond the end of text, adjust it to
3099 // be the last one and set res accordingly
3100 if ( (size_t)(row - rowFirst) >= lineData.GetRowCount() )
3101 {
3102 res = wxTE_HT_BELOW;
3103
3104 row = lineData.GetRowCount() + rowFirst - 1;
3105 }
3106 }
3107 else // not the last row
3108 {
3109 const wxWrappedLineData&
3110 lineNextData = linesData[cur + 1];
3111 if ( !WData().IsValidLine(cur + 1) )
3112 LayoutLines(cur + 1);
3113 found = row < lineNextData.GetFirstRow();
3114 }
3115
3116 if ( found )
3117 {
3118 colRowStart = lineData.GetRowStart(row - rowFirst);
3119 rowLen = lineData.GetRowLength(row - rowFirst,
3120 GetLines()[cur].length());
3121 row = cur;
3122
3123 break;
3124 }
3125 else
3126 {
3127 lo = cur;
3128 }
3129 }
3130 }
3131 }
3132 }
3133
3134 if ( res == wxTE_HT_ON_TEXT )
3135 {
3136 // now find the position in the line
3137 wxString lineText = GetLineText(row),
3138 rowText;
3139
3140 if ( colRowStart || rowLen )
3141 {
3142 // look in this row only, not in whole line
3143 rowText = lineText.Mid(colRowStart, rowLen);
3144 }
3145 else
3146 {
3147 // just take the whole string
3148 rowText = lineText;
3149 }
3150
3151 if ( colStart )
3152 {
3153 res = HitTestLine(GetTextToShow(rowText), x1, colStart);
3154
3155 if ( colRowStart )
3156 {
3157 if ( colRowStartOut )
3158 {
3159 // give them the column offset in this ROW in pixels
3160 *colRowStartOut = colRowStart;
3161 }
3162
3163 // take into account that the ROW doesn't start in the
3164 // beginning of the LINE
3165 *colStart += colRowStart;
3166 }
3167
3168 if ( colEnd )
3169 {
3170 // the hit test result we return is for x1, so throw out
3171 // the result for x2 here
3172 int x2 = x1 + x20 - x10;
3173 (void)HitTestLine(GetTextToShow(rowText), x2, colEnd);
3174
3175 *colEnd += colRowStart;
3176 }
3177 }
3178 }
3179 else // before/after vertical text span
3180 {
3181 if ( colStart )
3182 {
3183 // fill the column with the first/last position in the
3184 // corresponding line
3185 if ( res == wxTE_HT_BEFORE )
3186 *colStart = 0;
3187 else // res == wxTE_HT_BELOW
3188 *colStart = GetLineText(GetNumberOfLines() - 1).length();
3189 }
3190 }
3191
3192 if ( rowOut )
3193 {
3194 // give them the row in text coords (as is)
3195 *rowOut = row;
3196 }
3197
3198 return res;
3199}
3200
3201bool wxTextCtrl::GetLineAndRow(wxTextCoord row,
3202 wxTextCoord *lineOut,
3203 wxTextCoord *rowInLineOut) const
3204{
3205 wxTextCoord line,
3206 rowInLine = 0;
3207
3208 if ( row < 0 )
a290fa5a 3209 return false;
1e6feb95
VZ
3210
3211 int nLines = GetNumberOfLines();
3212 if ( WrapLines() )
3213 {
3214 const wxArrayWrappedLinesData& linesData = WData().m_linesData;
3215 for ( line = 0; line < nLines; line++ )
3216 {
3217 if ( !WData().IsValidLine(line) )
3218 LayoutLines(line);
3219
3220 if ( row < linesData[line].GetNextRow() )
3221 {
3222 // we found the right line
3223 rowInLine = row - linesData[line].GetFirstRow();
3224
3225 break;
3226 }
3227 }
3228
3229 if ( line == nLines )
3230 {
3231 // the row is out of range
a290fa5a 3232 return false;
1e6feb95
VZ
3233 }
3234 }
3235 else // no line wrapping, everything is easy
3236 {
3237 if ( row >= nLines )
a290fa5a 3238 return false;
1e6feb95
VZ
3239
3240 line = row;
3241 }
3242
3243 if ( lineOut )
3244 *lineOut = line;
3245 if ( rowInLineOut )
3246 *rowInLineOut = rowInLine;
3247
a290fa5a 3248 return true;
1e6feb95
VZ
3249}
3250
3251// ----------------------------------------------------------------------------
3252// scrolling
3253// ----------------------------------------------------------------------------
3254
3255/*
3256 wxTextCtrl has not one but two scrolling mechanisms: one is semi-automatic
3257 scrolling in both horizontal and vertical direction implemented using
3258 wxScrollHelper and the second one is manual scrolling implemented using
3259 SData().m_ofsHorz and used by the single line controls without scroll bar.
3260
3261 The first version (the standard one) always scrolls by fixed amount which is
3262 fine for vertical scrolling as all lines have the same height but is rather
3263 ugly for horizontal scrolling if proportional font is used. This is why we
3264 manually update and use SData().m_ofsHorz which contains the length of the string
3265 which is hidden beyond the left borde. An important property of text
3266 controls using this kind of scrolling is that an entire number of characters
3267 is always shown and that parts of characters never appear on display -
3268 neither in the leftmost nor rightmost positions.
3269
3270 Once again, for multi line controls SData().m_ofsHorz is always 0 and scrolling is
3271 done as usual for wxScrollWindow.
3272 */
3273
3274void wxTextCtrl::ShowHorzPosition(wxCoord pos)
3275{
3276 wxASSERT_MSG( IsSingleLine(), _T("doesn't work for multiline") );
3277
3278 // pos is the logical position to show
3279
3280 // SData().m_ofsHorz is the fisrt logical position shown
3281 if ( pos < SData().m_ofsHorz )
3282 {
3283 // scroll backwards
3284 wxTextCoord col;
3285 HitTestLine(m_value, pos, &col);
3286 ScrollText(col);
3287 }
3288 else
3289 {
3290 wxCoord width = m_rectText.width;
3291 if ( !width )
3292 {
3293 // if we are called from the ctor, m_rectText is not initialized
3294 // yet, so do it now
3295 UpdateTextRect();
3296 width = m_rectText.width;
3297 }
3298
3299 // SData().m_ofsHorz + width is the last logical position shown
3300 if ( pos > SData().m_ofsHorz + width)
3301 {
3302 // scroll forward
3303 wxTextCoord col;
3304 HitTestLine(m_value, pos - width, &col);
3305 ScrollText(col + 1);
3306 }
3307 }
3308}
3309
3310// scroll the window horizontally so that the first visible character becomes
3311// the one at this position
3312void wxTextCtrl::ScrollText(wxTextCoord col)
3313{
3314 wxASSERT_MSG( IsSingleLine(),
3315 _T("ScrollText() is for single line controls only") );
3316
3317 // never scroll beyond the left border
3318 if ( col < 0 )
3319 col = 0;
3320
3321 // OPT: could only get the extent of the part of the string between col
3322 // and SData().m_colStart
3323 wxCoord ofsHorz = GetTextWidth(GetLineText(0).Left(col));
3324
3325 if ( ofsHorz != SData().m_ofsHorz )
3326 {
3327 // remember the last currently used pixel
3328 int posLastVisible = SData().m_posLastVisible;
3329 if ( posLastVisible == -1 )
3330 {
3331 // this may happen when we're called very early, during the
3332 // controls construction
3333 UpdateLastVisible();
3334
3335 posLastVisible = SData().m_posLastVisible;
3336 }
3337
3338 // NB1: to scroll to the right, offset must be negative, hence the
3339 // order of operands
3340 int dx = SData().m_ofsHorz - ofsHorz;
3341
3342 // NB2: we call Refresh() below which results in a call to
3343 // DoDraw(), so we must update SData().m_ofsHorz before calling it
3344 SData().m_ofsHorz = ofsHorz;
3345 SData().m_colStart = col;
3346
3347 // after changing m_colStart, recalc the last visible position: we need
3348 // to recalc the last visible position beore scrolling in order to make
3349 // it appear exactly at the right edge of the text area after scrolling
3350 UpdateLastVisible();
3351
3352#if 0 // do we?
3353 if ( dx < 0 )
3354 {
3355 // we want to force the update of it after scrolling
3356 SData().m_colLastVisible = -1;
3357 }
3358#endif
3359
3360 // scroll only the rectangle inside which there is the text
3361 wxRect rect = m_rectText;
3362 rect.width = posLastVisible;
3363
3364 rect = ScrollNoRefresh(dx, 0, &rect);
3365
3366 /*
3367 we need to manually refresh the part which ScrollWindow() doesn't
3368 refresh (with new API this means the part outside the rect returned
3369 by ScrollNoRefresh): indeed, if we had this:
3370
3371 ********o
3372
3373 where '*' is text and 'o' is blank area at the end (too small to
3374 hold the next char) then after scrolling by 2 positions to the left
3375 we're going to have
3376
3377 ******RRo
3378
3379 where 'R' is the area refreshed by ScrollWindow() - but we still
3380 need to refresh the 'o' at the end as it may be now big enough to
3381 hold the new character shifted into view.
3382
3383 when we are scrolling to the right, we need to update this rect as
3384 well because it might have contained something before but doesn't
3385 contain anything any more
3386 */
3387
3388 // we can combine both rectangles into one when scrolling to the left,
3389 // but we need two separate Refreshes() otherwise
3390 if ( dx > 0 )
3391 {
3392 // refresh the uncovered part on the left
a290fa5a 3393 Refresh(true, &rect);
1e6feb95
VZ
3394
3395 // and now the area on the right
3396 rect.x = m_rectText.x + posLastVisible;
3397 rect.width = m_rectText.width - posLastVisible;
3398 }
3399 else // scrolling to the left
3400 {
3401 // just extend the rect covering the uncovered area to the edge of
3402 // the text rect
3403 rect.width += m_rectText.width - posLastVisible;
3404 }
3405
a290fa5a 3406 Refresh(true, &rect);
1e6feb95
VZ
3407
3408 // I don't know exactly why is this needed here but without it we may
3409 // scroll the window again (from the same method) before the previously
3410 // invalidated area is repainted when typing *very* quickly - and this
3411 // may lead to the display corruption
3412 Update();
3413 }
3414}
3415
3416void wxTextCtrl::CalcUnscrolledPosition(int x, int y, int *xx, int *yy) const
3417{
3418 if ( IsSingleLine() )
3419 {
3420 // we don't use wxScrollHelper
3421 if ( xx )
3422 *xx = x + SData().m_ofsHorz;
3423 if ( yy )
3424 *yy = y;
3425 }
3426 else
3427 {
3428 // let the base class do it
3429 wxScrollHelper::CalcUnscrolledPosition(x, y, xx, yy);
3430 }
3431}
3432
3433void wxTextCtrl::CalcScrolledPosition(int x, int y, int *xx, int *yy) const
3434{
3435 if ( IsSingleLine() )
3436 {
3437 // we don't use wxScrollHelper
3438 if ( xx )
3439 *xx = x - SData().m_ofsHorz;
3440 if ( yy )
3441 *yy = y;
3442 }
3443 else
3444 {
3445 // let the base class do it
3446 wxScrollHelper::CalcScrolledPosition(x, y, xx, yy);
3447 }
3448}
3449
3450void wxTextCtrl::DoPrepareDC(wxDC& dc)
3451{
3452 // for single line controls we only have to deal with SData().m_ofsHorz and it's
3453 // useless to call base class version as they don't use normal scrolling
3454 if ( IsSingleLine() && SData().m_ofsHorz )
3455 {
3456 // adjust the DC origin if the text is shifted
3457 wxPoint pt = dc.GetDeviceOrigin();
3458 dc.SetDeviceOrigin(pt.x - SData().m_ofsHorz, pt.y);
3459 }
3460 else
3461 {
3462 wxScrollHelper::DoPrepareDC(dc);
3463 }
3464}
3465
3466void wxTextCtrl::UpdateMaxWidth(wxTextCoord line)
3467{
3468 // OPT!
3469
3470 // check if the max width changes after this line was modified
3471 wxCoord widthMaxOld = MData().m_widthMax,
3472 width;
3473 GetTextExtent(GetLineText(line), &width, NULL);
3474
3475 if ( line == MData().m_lineLongest )
3476 {
3477 // this line was the longest one, is it still?
3478 if ( width > MData().m_widthMax )
3479 {
3480 MData().m_widthMax = width;
3481 }
3482 else if ( width < MData().m_widthMax )
3483 {
3484 // we need to find the new longest line
3485 RecalcMaxWidth();
3486 }
3487 //else: its length didn't change, nothing to do
3488 }
3489 else // it wasn't the longest line, but maybe it became it?
3490 {
3491 // GetMaxWidth() and not MData().m_widthMax as it might be not calculated yet
3492 if ( width > GetMaxWidth() )
3493 {
3494 MData().m_widthMax = width;
3495 MData().m_lineLongest = line;
3496 }
3497 }
3498
3499 MData().m_updateScrollbarX = MData().m_widthMax != widthMaxOld;
3500}
3501
3502void wxTextCtrl::RecalcFontMetrics()
3503{
3504 m_heightLine = GetCharHeight();
3505 m_widthAvg = GetCharWidth();
3506}
3507
3508void wxTextCtrl::RecalcMaxWidth()
3509{
3510 wxASSERT_MSG( !IsSingleLine(), _T("only used for multiline") );
3511
3512 MData().m_widthMax = -1;
3513 (void)GetMaxWidth();
3514}
3515
3516wxCoord wxTextCtrl::GetMaxWidth() const
3517{
3518 if ( MData().m_widthMax == -1 )
3519 {
3520 // recalculate it
3521
3522 // OPT: should we remember the widths of all the lines?
3523
3524 wxTextCtrl *self = wxConstCast(this, wxTextCtrl);
3525 wxClientDC dc(self);
3526 dc.SetFont(GetFont());
3527
3528 self->MData().m_widthMax = 0;
3529
3530 size_t count = GetLineCount();
3531 for ( size_t n = 0; n < count; n++ )
3532 {
3533 wxCoord width;
3534 dc.GetTextExtent(GetLines()[n], &width, NULL);
3535 if ( width > MData().m_widthMax )
3536 {
3537 // remember the width and the line which has it
3538 self->MData().m_widthMax = width;
3539 self->MData().m_lineLongest = n;
3540 }
3541 }
3542 }
3543
3544 wxASSERT_MSG( MData().m_widthMax != -1, _T("should have at least 1 line") );
3545
3546 return MData().m_widthMax;
3547}
3548
3549void wxTextCtrl::UpdateScrollbars()
3550{
3551 wxASSERT_MSG( !IsSingleLine(), _T("only used for multiline") );
3552
3553 wxSize size = GetRealTextArea().GetSize();
3554
3555 // is our height enough to show all items?
3556 wxTextCoord nRows = GetRowCount();
3557 wxCoord lineHeight = GetLineHeight();
3558 bool showScrollbarY = nRows*lineHeight > size.y;
3559
3560 // is our width enough to show the longest line?
3561 wxCoord charWidth, maxWidth;
3562 bool showScrollbarX;
3563 if ( !WrapLines() )
3564 {
3565 charWidth = GetAverageWidth();
3566 maxWidth = GetMaxWidth();
3567 showScrollbarX = maxWidth > size.x;
3568 }
3569 else // never show the horz scrollbar
3570 {
3571 // just to suppress compiler warnings about using uninit vars below
3572 charWidth = maxWidth = 0;
3573
a290fa5a 3574 showScrollbarX = false;
1e6feb95
VZ
3575 }
3576
3577 // calc the scrollbars ranges
3578 int scrollRangeX = showScrollbarX
3579 ? (maxWidth + 2*charWidth - 1) / charWidth
3580 : 0;
3581 int scrollRangeY = showScrollbarY ? nRows : 0;
3582
3583 int scrollRangeXOld = MData().m_scrollRangeX,
3584 scrollRangeYOld = MData().m_scrollRangeY;
3585 if ( (scrollRangeY != scrollRangeYOld) || (scrollRangeX != scrollRangeXOld) )
3586 {
3587 int x, y;
3588 GetViewStart(&x, &y);
3589
3590#if 0
3591 // we want to leave the scrollbars at the same position which means
3592 // that x and y have to be adjusted as the number of positions may have
3593 // changed
3594 //
3595 // the number of positions is calculated from knowing that last
3596 // position = range - thumbSize and thumbSize == pageSize which is
3597 // equal to the window width / pixelsPerLine
3598 if ( scrollRangeXOld )
3599 {
3600 x *= scrollRangeX - m_rectText.width / charWidth;
3601 x /= scrollRangeXOld - m_rectText.width / charWidth;
3602 }
3603
3604 if ( scrollRangeYOld )
3605 y *= scrollRangeY / scrollRangeYOld;
3606#endif // 0
3607
3608 SetScrollbars(charWidth, lineHeight,
3609 scrollRangeX, scrollRangeY,
3610 x, y,
a290fa5a 3611 true /* no refresh */);
1e6feb95
VZ
3612
3613 if ( scrollRangeXOld )
3614 {
3615 x *= scrollRangeX - m_rectText.width / charWidth;
3616 x /= scrollRangeXOld - m_rectText.width / charWidth;
3617 Scroll(x, y);
3618 }
3619
3620 MData().m_scrollRangeX = scrollRangeX;
3621 MData().m_scrollRangeY = scrollRangeY;
3622
3623 // bring the current position in view
3624 ShowPosition(-1);
3625 }
3626
3627 MData().m_updateScrollbarX =
a290fa5a 3628 MData().m_updateScrollbarY = false;
1e6feb95
VZ
3629}
3630
e39af974 3631void wxTextCtrl::OnInternalIdle()
1e6feb95
VZ
3632{
3633 // notice that single line text control never has scrollbars
3634 if ( !IsSingleLine() &&
3635 (MData().m_updateScrollbarX || MData().m_updateScrollbarY) )
3636 {
3637 UpdateScrollbars();
3638 }
47cd6610 3639 wxControl::OnInternalIdle();
1e6feb95
VZ
3640}
3641
3642bool wxTextCtrl::SendAutoScrollEvents(wxScrollWinEvent& event) const
3643{
3644 bool forward = event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN;
3645 if ( event.GetOrientation() == wxHORIZONTAL )
3646 {
3647 return forward ? m_curCol <= GetLineLength(m_curRow) : m_curCol > 0;
3648 }
3649 else // wxVERTICAL
3650 {
3651 return forward ? m_curRow < GetNumberOfLines() : m_curRow > 0;
3652 }
3653}
3654
3655// ----------------------------------------------------------------------------
3656// refresh
3657// ----------------------------------------------------------------------------
3658
3659void wxTextCtrl::RefreshSelection()
3660{
3661 if ( HasSelection() )
3662 {
3663 RefreshTextRange(m_selStart, m_selEnd);
3664 }
3665}
3666
3667void wxTextCtrl::RefreshLineRange(wxTextCoord lineFirst, wxTextCoord lineLast)
3668{
3669 wxASSERT_MSG( lineFirst <= lineLast || !lineLast,
3670 _T("no lines to refresh") );
3671
3672 wxRect rect;
3673 // rect.x is already 0
3674 rect.width = m_rectText.width;
3675 wxCoord h = GetLineHeight();
3676
3677 wxTextCoord rowFirst;
3678 if ( lineFirst < GetNumberOfLines() )
3679 {
3680 rowFirst = GetFirstRowOfLine(lineFirst);
3681 }
3682 else // lineFirst == GetNumberOfLines()
3683 {
3684 // lineFirst may be beyond the last line only if we refresh till
3685 // the end, otherwise it's illegal
3686 wxASSERT_MSG( lineFirst == GetNumberOfLines() && !lineLast,
3687 _T("invalid line range") );
3688
3689 rowFirst = GetRowAfterLine(lineFirst - 1);
3690 }
3691
3692 rect.y = rowFirst*h;
3693
3694 if ( lineLast )
3695 {
3696 // refresh till this line (inclusive)
3697 wxTextCoord rowLast = GetRowAfterLine(lineLast);
3698
3699 rect.height = (rowLast - rowFirst + 1)*h;
3700 }
3701 else // lineLast == 0 means to refresh till the end
3702 {
3703 // FIXME: calc it exactly
3704 rect.height = 32000;
3705 }
3706
3707 RefreshTextRect(rect);
3708}
3709
3710void wxTextCtrl::RefreshTextRange(wxTextPos start, wxTextPos end)
3711{
3712 wxCHECK_RET( start != -1 && end != -1,
3713 _T("invalid RefreshTextRange() arguments") );
3714
3715 // accept arguments in any order as it is more conenient for the caller
3716 OrderPositions(start, end);
3717
3718 // this is acceptable but we don't do anything in this case
3719 if ( start == end )
3720 return;
3721
3722 wxTextPos colStart, lineStart;
3723 if ( !PositionToXY(start, &colStart, &lineStart) )
3724 {
3725 // the range is entirely beyond the end of the text, nothing to do
3726 return;
3727 }
3728
3729 wxTextCoord colEnd, lineEnd;
3730 if ( !PositionToXY(end, &colEnd, &lineEnd) )
3731 {
3732 // the range spans beyond the end of text, refresh to the end
3733 colEnd = -1;
3734 lineEnd = GetNumberOfLines() - 1;
3735 }
3736
3737 // refresh all lines one by one
3738 for ( wxTextCoord line = lineStart; line <= lineEnd; line++ )
3739 {
3740 // refresh the first line from the start of the range to the end, the
3741 // intermediate ones entirely and the last one from the beginning to
3742 // the end of the range
3743 wxTextPos posStart = line == lineStart ? colStart : 0;
3744 size_t posCount;
3745 if ( (line != lineEnd) || (colEnd == -1) )
3746 {
3747 // intermediate line or the last one but we need to refresh it
3748 // until the end anyhow - do it
f10ccf9e 3749 posCount = wxString::npos;
1e6feb95
VZ
3750 }
3751 else // last line
3752 {
3753 // refresh just the positions in between the start and the end one
3754 posCount = colEnd - posStart;
3755 }
3756
3757 if ( posCount )
3758 RefreshColRange(line, posStart, posCount);
3759 }
3760}
3761
3762void wxTextCtrl::RefreshColRange(wxTextCoord line,
3763 wxTextPos start,
3764 size_t count)
3765{
3766 wxString text = GetLineText(line);
3767
3768 wxASSERT_MSG( (size_t)start <= text.length() && count,
3769 _T("invalid RefreshColRange() parameter") );
3770
3771 RefreshPixelRange(line,
3772 GetTextWidth(text.Left((size_t)start)),
3773 GetTextWidth(text.Mid((size_t)start, (size_t)count)));
3774}
3775
3776// this method accepts "logical" coords in the sense that they are coordinates
3777// in a logical line but it can span several rows if we wrap lines and
3778// RefreshPixelRange() will then refresh several rows
3779void wxTextCtrl::RefreshPixelRange(wxTextCoord line,
3780 wxCoord start,
3781 wxCoord width)
3782{
3783 // we will use line text only in line wrap case
3784 wxString text;
3785 if ( WrapLines() )
3786 {
3787 text = GetLineText(line);
3788 }
3789
3790 // special case: width == 0 means to refresh till the end of line
3791 if ( width == 0 )
3792 {
3793 // refresh till the end of visible line
3794 width = GetTotalWidth();
3795
3796 if ( WrapLines() )
3797 {
3798 // refresh till the end of text
3799 wxCoord widthAll = GetTextWidth(text);
3800
3801 // extend width to the end of ROW
3802 width = widthAll - widthAll % width + width;
3803 }
3804
3805 // no need to refresh beyond the end of line
3806 width -= start;
3807 }
3808 //else: just refresh the specified part
3809
3810 wxCoord h = GetLineHeight();
3811 wxRect rect;
3812 rect.x = start;
3813 rect.y = GetFirstRowOfLine(line)*h;
3814 rect.height = h;
3815
3816 if ( WrapLines() )
3817 {
3818 // (1) skip all rows which we don't touch at all
3819 const wxWrappedLineData& lineData = WData().m_linesData[line];
3820 if ( !WData().IsValidLine(line) )
3821 LayoutLines(line);
3822
3823 wxCoord wLine = 0; // suppress compiler warning about uninit var
3824 size_t rowLast = lineData.GetRowCount(),
3825 row = 0;
3826 while ( (row < rowLast) &&
3827 (rect.x > (wLine = lineData.GetRowWidth(row++))) )
3828 {
3829 rect.x -= wLine;
3830 rect.y += h;
3831 }
3832
3833 // (2) now refresh all lines except the last one: note that the first
3834 // line is refreshed from the given start to the end, all the next
3835 // ones - entirely
3836 while ( (row < rowLast) && (width > wLine - rect.x) )
3837 {
3838 rect.width = GetTotalWidth() - rect.x;
3839 RefreshTextRect(rect);
3840
3841 width -= wLine - rect.x;
3842 rect.x = 0;
3843 rect.y += h;
3844
3845 wLine = lineData.GetRowWidth(row++);
3846 }
3847
3848 // (3) the code below will refresh the last line
3849 }
3850
3851 rect.width = width;
3852
3853 RefreshTextRect(rect);
3854}
3855
3856void wxTextCtrl::RefreshTextRect(const wxRect& rectClient, bool textOnly)
3857{
3858 wxRect rect;
3859 CalcScrolledPosition(rectClient.x, rectClient.y, &rect.x, &rect.y);
3860 rect.width = rectClient.width;
3861 rect.height = rectClient.height;
3862
3863 // account for the text area offset
3864 rect.Offset(m_rectText.GetPosition());
3865
3866 // don't refresh beyond the text area unless we're refreshing the line wrap
a290fa5a 3867 // marks in which case textOnly is false
1e6feb95
VZ
3868 if ( textOnly )
3869 {
3870 if ( rect.GetRight() > m_rectText.GetRight() )
3871 {
3872 rect.SetRight(m_rectText.GetRight());
3873
3874 if ( rect.width <= 0 )
3875 {
3876 // nothing to refresh
3877 return;
3878 }
3879 }
3880 }
3881
3882 // check the bottom boundary always, even for the line wrap marks
3883 if ( rect.GetBottom() > m_rectText.GetBottom() )
3884 {
3885 rect.SetBottom(m_rectText.GetBottom());
3886
3887 if ( rect.height <= 0 )
3888 {
3889 // nothing to refresh
3890 return;
3891 }
3892 }
3893
3894 // never refresh before the visible rect
3895 if ( rect.x < m_rectText.x )
3896 rect.x = m_rectText.x;
3897
3898 if ( rect.y < m_rectText.y )
3899 rect.y = m_rectText.y;
3900
3901 wxLogTrace(_T("text"), _T("Refreshing (%d, %d)-(%d, %d)"),
3902 rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
3903
a290fa5a 3904 Refresh(true, &rect);
1e6feb95
VZ
3905}
3906
3907void wxTextCtrl::RefreshLineWrapMarks(wxTextCoord rowFirst,
3908 wxTextCoord rowLast)
3909{
3910 if ( WData().m_widthMark )
3911 {
3912 wxRect rectMarks;
3913 rectMarks.x = m_rectText.width;
3914 rectMarks.width = WData().m_widthMark;
3915 rectMarks.y = rowFirst*GetLineHeight();
3916 rectMarks.height = (rowLast - rowFirst)*GetLineHeight();
3917
a290fa5a 3918 RefreshTextRect(rectMarks, false /* don't limit to text area */);
1e6feb95
VZ
3919 }
3920}
3921
3922// ----------------------------------------------------------------------------
3923// border drawing
3924// ----------------------------------------------------------------------------
3925
3926void wxTextCtrl::DoDrawBorder(wxDC& dc, const wxRect& rect)
3927{
3928 m_renderer->DrawTextBorder(dc, GetBorder(), rect, GetStateFlags());
3929}
3930
3931// ----------------------------------------------------------------------------
3932// client area drawing
3933// ----------------------------------------------------------------------------
3934
3935/*
3936 Several remarks about wxTextCtrl redraw logic:
3937
3938 1. only the regions which must be updated are redrawn, this means that we
3939 never Refresh() the entire window but use RefreshPixelRange() and
3940 ScrollWindow() which only refresh small parts of it and iterate over the
3941 update region in our DoDraw()
3942
3943 2. the text displayed on the screen is obtained using GetTextToShow(): it
3944 should be used for all drawing/measuring
3945 */
3946
3947wxString wxTextCtrl::GetTextToShow(const wxString& text) const
3948{
3949 wxString textShown;
3950 if ( IsPassword() )
3951 textShown = wxString(_T('*'), text.length());
3952 else
3953 textShown = text;
3954
3955 return textShown;
3956}
3957
3958void wxTextCtrl::DoDrawTextInRect(wxDC& dc, const wxRect& rectUpdate)
3959{
3960 // debugging trick to see the update rect visually
3961#ifdef WXDEBUG_TEXT
3962 static int s_countUpdates = -1;
3963 if ( s_countUpdates != -1 )
3964 {
3965 wxWindowDC dc(this);
3966 dc.SetBrush(*(++s_countUpdates % 2 ? wxRED_BRUSH : wxGREEN_BRUSH));
3967 dc.SetPen(*wxTRANSPARENT_PEN);
3968 dc.DrawRectangle(rectUpdate);
3969 }
3970#endif // WXDEBUG_TEXT
3971
3972 // calculate the range lineStart..lineEnd of lines to redraw
3973 wxTextCoord lineStart, lineEnd;
3974 if ( IsSingleLine() )
3975 {
3976 lineStart =
3977 lineEnd = 0;
3978 }
3979 else // multiline
3980 {
3981 wxPoint pt = rectUpdate.GetPosition();
3982 (void)HitTest(pt, NULL, &lineStart);
3983
3984 pt.y += rectUpdate.height;
3985 (void)HitTest(pt, NULL, &lineEnd);
3986 }
3987
3988 // prepare for drawing
3989 wxCoord hLine = GetLineHeight();
3990
3991 // these vars will be used for hit testing of the current row
3992 wxCoord y = rectUpdate.y;
3993 const wxCoord x1 = rectUpdate.x;
3994 const wxCoord x2 = rectUpdate.x + rectUpdate.width;
3995
3996 wxRect rectText;
3997 rectText.height = hLine;
3998 wxCoord yClient = y - GetClientAreaOrigin().y;
3999
4000 // we want to always start at the top of the line, otherwise if we redraw a
4001 // rect whose top is in the middle of a line, we'd draw this line shifted
4002 yClient -= (yClient - m_rectText.y) % hLine;
4003
4004 if ( IsSingleLine() )
4005 {
4006 rectText.y = yClient;
4007 }
4008 else // multiline, adjust for scrolling
4009 {
4010 CalcUnscrolledPosition(0, yClient, NULL, &rectText.y);
4011 }
4012
4013 wxRenderer *renderer = GetRenderer();
4014
4015 // do draw the invalidated parts of each line: note that we iterate here
4016 // over ROWs, not over LINEs
4017 for ( wxTextCoord line = lineStart;
4018 y < rectUpdate.y + rectUpdate.height;
4019 y += hLine,
4020 rectText.y += hLine )
4021 {
4022 // calculate the update rect in text positions for this line
4023 wxTextCoord colStart, colEnd, colRowStart;
4024 wxTextCtrlHitTestResult ht = HitTest2(y, x1, x2,
4025 &line, &colStart, &colEnd,
4026 &colRowStart);
4027
4028 if ( (ht == wxTE_HT_BEYOND) || (ht == wxTE_HT_BELOW) )
4029 {
4030 wxASSERT_MSG( line <= lineEnd, _T("how did we get that far?") );
4031
4032 if ( line == lineEnd )
4033 {
4034 // we redrew everything
4035 break;
4036 }
4037
4038 // the update rect is beyond the end of line, no need to redraw
4039 // anything on this line - but continue with the remaining ones
4040 continue;
4041 }
4042
4043 // for single line controls we may additionally cut off everything
4044 // which is to the right of the last visible position
4045 if ( IsSingleLine() )
4046 {
4047 // don't show the columns which are scrolled out to the left
4048 if ( colStart < SData().m_colStart )
4049 colStart = SData().m_colStart;
4050
4051 // colEnd may be less than colStart if colStart was changed by the
4052 // assignment above
4053 if ( colEnd < colStart )
4054 colEnd = colStart;
4055
4056 // don't draw the chars beyond the rightmost one
4057 if ( SData().m_colLastVisible == -1 )
4058 {
4059 // recalculate this rightmost column
4060 UpdateLastVisible();
4061 }
4062
4063 if ( colStart > SData().m_colLastVisible )
4064 {
4065 // don't bother redrawing something that is beyond the last
4066 // visible position
4067 continue;
4068 }
4069
4070 if ( colEnd > SData().m_colLastVisible )
4071 {
4072 colEnd = SData().m_colLastVisible;
4073 }
4074 }
4075
4076 // extract the part of line we need to redraw
4077 wxString textLine = GetTextToShow(GetLineText(line));
4078 wxString text = textLine.Mid(colStart, colEnd - colStart + 1);
4079
4080 // now deal with the selection: only do something if at least part of
4081 // the line is selected
4082 wxTextPos selStart, selEnd;
4083 if ( GetSelectedPartOfLine(line, &selStart, &selEnd) )
4084 {
4085 // and if this part is (at least partly) in the current row
4086 if ( (selStart <= colEnd) &&
4087 (selEnd >= wxMax(colStart, colRowStart)) )
4088 {
4089 // these values are relative to the start of the line while the
4090 // string passed to DrawTextLine() is only part of it, so
4091 // adjust the selection range accordingly
4092 selStart -= colStart;
4093 selEnd -= colStart;
4094
4095 if ( selStart < 0 )
4096 selStart = 0;
4097
4098 if ( (size_t)selEnd >= text.length() )
4099 selEnd = text.length();
4100 }
4101 else
4102 {
4103 // reset selStart and selEnd to avoid passing them to
4104 // DrawTextLine() below
4105 selStart =
4106 selEnd = -1;
4107 }
4108 }
4109
4110 // calculate the text coords on screen
4111 wxASSERT_MSG( colStart >= colRowStart, _T("invalid string part") );
4112 wxCoord ofsStart = GetTextWidth(
4113 textLine.Mid(colRowStart,
4114 colStart - colRowStart));
4115 rectText.x = m_rectText.x + ofsStart;
4116 rectText.width = GetTextWidth(text);
4117
4118 // do draw the text
4119 renderer->DrawTextLine(dc, text, rectText, selStart, selEnd,
4120 GetStateFlags());
4121 wxLogTrace(_T("text"), _T("Line %ld: positions %ld-%ld redrawn."),
4122 line, colStart, colEnd);
4123 }
4124}
4125
4126void wxTextCtrl::DoDrawLineWrapMarks(wxDC& dc, const wxRect& rectUpdate)
4127{
4128 wxASSERT_MSG( WrapLines() && WData().m_widthMark,
4129 _T("shouldn't be called at all") );
4130
4131 wxRenderer *renderer = GetRenderer();
4132
4133 wxRect rectMark;
4134 rectMark.x = rectUpdate.x;
4135 rectMark.width = rectUpdate.width;
4136 wxCoord yTop = GetClientAreaOrigin().y;
4137 CalcUnscrolledPosition(0, rectUpdate.y - yTop, NULL, &rectMark.y);
4138 wxCoord hLine = GetLineHeight();
4139 rectMark.height = hLine;
4140
4141 wxTextCoord line, rowInLine;
4142
4143 wxCoord yBottom;
4144 CalcUnscrolledPosition(0, rectUpdate.GetBottom() - yTop, NULL, &yBottom);
4145 for ( ; rectMark.y < yBottom; rectMark.y += hLine )
4146 {
4147 if ( !GetLineAndRow(rectMark.y / hLine, &line, &rowInLine) )
4148 {
4149 // we went beyond the end of text
4150 break;
4151 }
4152
4153 // is this row continued on the next one?
4154 if ( !WData().m_linesData[line].IsLastRow(rowInLine) )
4155 {
4156 renderer->DrawLineWrapMark(dc, rectMark);
4157 }
4158 }
4159}
4160
4161void wxTextCtrl::DoDraw(wxControlRenderer *renderer)
4162{
4163 // hide the caret while we're redrawing the window and show it after we are
4164 // done with it
4165 wxCaretSuspend cs(this);
4166
4167 // prepare the DC
4168 wxDC& dc = renderer->GetDC();
4169 dc.SetFont(GetFont());
4170 dc.SetTextForeground(GetForegroundColour());
4171
4172 // get the intersection of the update region with the text area: note that
4173 // the update region is in window coords and text area is in the client
4174 // ones, so it must be shifted before computing intersection
4175 wxRegion rgnUpdate = GetUpdateRegion();
34158fee 4176
1e6feb95
VZ
4177 wxRect rectTextArea = GetRealTextArea();
4178 wxPoint pt = GetClientAreaOrigin();
4179 wxRect rectTextAreaAdjusted = rectTextArea;
4180 rectTextAreaAdjusted.x += pt.x;
4181 rectTextAreaAdjusted.y += pt.y;
4182 rgnUpdate.Intersect(rectTextAreaAdjusted);
4183
4184 // even though the drawing is already clipped to the update region, we must
4185 // explicitly clip it to the rect we will use as otherwise parts of letters
4186 // might be drawn outside of it (if even a small part of a charater is
4187 // inside, HitTest() will return its column and DrawText() can't draw only
4188 // the part of the character, of course)
4189#ifdef __WXMSW__
4190 // FIXME: is this really a bug in wxMSW?
4191 rectTextArea.width--;
4192#endif // __WXMSW__
4193 dc.SetClippingRegion(rectTextArea);
4194
4195 // adjust for scrolling
4196 DoPrepareDC(dc);
4197
4198 // and now refresh the invalidated parts of the window
4199 wxRegionIterator iter(rgnUpdate);
4200 for ( ; iter.HaveRects(); iter++ )
4201 {
4202 wxRect r = iter.GetRect();
4203
4204 // this is a workaround for wxGTK::wxRegion bug
4205#ifdef __WXGTK__
4206 if ( !r.width || !r.height )
4207 {
4208 // ignore invalid rect
4209 continue;
4210 }
4211#endif // __WXGTK__
4212
4213 DoDrawTextInRect(dc, r);
4214 }
4215
4216 // now redraw the line wrap marks (if we draw them)
4217 if ( WrapLines() && WData().m_widthMark )
4218 {
4219 // this is the rect inside which line wrap marks are drawn
4220 wxRect rectMarks;
4221 rectMarks.x = rectTextAreaAdjusted.GetRight() + 1;
4222 rectMarks.y = rectTextAreaAdjusted.y;
4223 rectMarks.width = WData().m_widthMark;
4224 rectMarks.height = rectTextAreaAdjusted.height;
4225
4226 rgnUpdate = GetUpdateRegion();
4227 rgnUpdate.Intersect(rectMarks);
4228
4229 wxRect rectUpdate = rgnUpdate.GetBox();
4230 if ( rectUpdate.width && rectUpdate.height )
4231 {
4232 // the marks are outside previously set clipping region
4233 dc.DestroyClippingRegion();
4234
4235 DoDrawLineWrapMarks(dc, rectUpdate);
4236 }
4237 }
4238
4239 // show caret first time only: we must show it after drawing the text or
4240 // the display can be corrupted when it's hidden
e28c2d15 4241 if ( !m_hasCaret && GetCaret() && (FindFocus() == this) )
1e6feb95
VZ
4242 {
4243 ShowCaret();
4244
a290fa5a 4245 m_hasCaret = true;
1e6feb95
VZ
4246 }
4247}
4248
4249// ----------------------------------------------------------------------------
4250// caret
4251// ----------------------------------------------------------------------------
4252
4253bool wxTextCtrl::SetFont(const wxFont& font)
4254{
4255 if ( !wxControl::SetFont(font) )
a290fa5a 4256 return false;
1e6feb95
VZ
4257
4258 // and refresh everything, of course
4259 InitInsertionPoint();
4260 ClearSelection();
4261
4262 // update geometry parameters
4263 UpdateTextRect();
4264 RecalcFontMetrics();
4265 if ( !IsSingleLine() )
4266 {
4267 UpdateScrollbars();
4268 RecalcMaxWidth();
4269 }
4270
4271 // recreate it, in fact
4272 CreateCaret();
4273
4274 Refresh();
4275
a290fa5a 4276 return true;
1e6feb95
VZ
4277}
4278
4279bool wxTextCtrl::Enable(bool enable)
4280{
4281 if ( !wxTextCtrlBase::Enable(enable) )
a290fa5a 4282 return false;
1e6feb95 4283
e28c2d15
JS
4284 if (FindFocus() == this && GetCaret() &&
4285 ((enable && !GetCaret()->IsVisible()) ||
4286 (!enable && GetCaret()->IsVisible())))
4287 ShowCaret(enable);
1e6feb95 4288
a290fa5a 4289 return true;
1e6feb95
VZ
4290}
4291
4292void wxTextCtrl::CreateCaret()
4293{
4294 wxCaret *caret;
4295
4296 if ( IsEditable() )
4297 {
4298 // FIXME use renderer
4299 caret = new wxCaret(this, 1, GetLineHeight());
1e6feb95
VZ
4300 }
4301 else
4302 {
4303 // read only controls don't have the caret
4304 caret = (wxCaret *)NULL;
4305 }
4306
4307 // SetCaret() will delete the old caret if any
4308 SetCaret(caret);
4309}
4310
4311void wxTextCtrl::ShowCaret(bool show)
4312{
4313 wxCaret *caret = GetCaret();
4314 if ( caret )
4315 {
4316 // (re)position caret correctly
4317 caret->Move(GetCaretPosition());
4318
4319 // and show it there
e28c2d15
JS
4320 if ((show && !caret->IsVisible()) ||
4321 (!show && caret->IsVisible()))
4322 caret->Show(show);
1e6feb95
VZ
4323 }
4324}
4325
4326// ----------------------------------------------------------------------------
4327// vertical scrolling (multiline only)
4328// ----------------------------------------------------------------------------
4329
4330size_t wxTextCtrl::GetLinesPerPage() const
4331{
4332 if ( IsSingleLine() )
4333 return 1;
4334
4335 return GetRealTextArea().height / GetLineHeight();
4336}
4337
4338wxTextPos wxTextCtrl::GetPositionAbove()
4339{
4340 wxCHECK_MSG( !IsSingleLine(), INVALID_POS_VALUE,
4341 _T("can't move cursor vertically in a single line control") );
4342
4343 // move the cursor up by one ROW not by one LINE: this means that
4344 // we should really use HitTest() and not just go to the same
4345 // position in the previous line
4346 wxPoint pt = GetCaretPosition() - m_rectText.GetPosition();
4347 if ( MData().m_xCaret == -1 )
4348 {
4349 // remember the initial cursor abscissa
4350 MData().m_xCaret = pt.x;
4351 }
4352 else
4353 {
4354 // use the remembered abscissa
4355 pt.x = MData().m_xCaret;
4356 }
4357
4358 CalcUnscrolledPosition(pt.x, pt.y, &pt.x, &pt.y);
4359 pt.y -= GetLineHeight();
4360
4361 wxTextCoord col, row;
4362 if ( HitTestLogical(pt, &col, &row) == wxTE_HT_BEFORE )
4363 {
4364 // can't move further
4365 return INVALID_POS_VALUE;
4366 }
4367
4368 return XYToPosition(col, row);
4369}
4370
4371wxTextPos wxTextCtrl::GetPositionBelow()
4372{
4373 wxCHECK_MSG( !IsSingleLine(), INVALID_POS_VALUE,
4374 _T("can't move cursor vertically in a single line control") );
4375
4376 // see comments for wxACTION_TEXT_UP
4377 wxPoint pt = GetCaretPosition() - m_rectText.GetPosition();
4378 if ( MData().m_xCaret == -1 )
4379 {
4380 // remember the initial cursor abscissa
4381 MData().m_xCaret = pt.x;
4382 }
4383 else
4384 {
4385 // use the remembered abscissa
4386 pt.x = MData().m_xCaret;
4387 }
4388
4389 CalcUnscrolledPosition(pt.x, pt.y, &pt.x, &pt.y);
4390 pt.y += GetLineHeight();
4391
4392 wxTextCoord col, row;
4393 if ( HitTestLogical(pt, &col, &row) == wxTE_HT_BELOW )
4394 {
4395 // can't go further down
4396 return INVALID_POS_VALUE;
4397 }
4398
4399 // note that wxTE_HT_BEYOND is ok: it happens when we go down
4400 // from a longer line to a shorter one, for example (OTOH
4401 // wxTE_HT_BEFORE can never happen)
4402 return XYToPosition(col, row);
4403}
4404
4405// ----------------------------------------------------------------------------
4406// input
4407// ----------------------------------------------------------------------------
4408
4409bool wxTextCtrl::PerformAction(const wxControlAction& actionOrig,
4410 long numArg,
4411 const wxString& strArg)
4412{
4413 // has the text changed as result of this action?
a290fa5a 4414 bool textChanged = false;
1e6feb95
VZ
4415
4416 // the remembered cursor abscissa for multiline text controls is usually
4417 // reset after each user action but for ones which do use it (UP and DOWN
4418 // for example) we shouldn't do it - as indicated by this flag
a290fa5a 4419 bool rememberAbscissa = false;
1e6feb95
VZ
4420
4421 // the command this action corresponds to or NULL if this action doesn't
4422 // change text at all or can't be undone
4423 wxTextCtrlCommand *command = (wxTextCtrlCommand *)NULL;
4424
4425 wxString action;
a290fa5a
WS
4426 bool del = false,
4427 sel = false;
1e6feb95
VZ
4428 if ( actionOrig.StartsWith(wxACTION_TEXT_PREFIX_DEL, &action) )
4429 {
4430 if ( IsEditable() )
a290fa5a 4431 del = true;
1e6feb95
VZ
4432 }
4433 else if ( actionOrig.StartsWith(wxACTION_TEXT_PREFIX_SEL, &action) )
4434 {
a290fa5a 4435 sel = true;
1e6feb95
VZ
4436 }
4437 else // not selection nor delete action
4438 {
4439 action = actionOrig;
4440 }
4441
4442 // set newPos to -2 as it can't become equal to it in the assignments below
4443 // (but it can become -1)
4444 wxTextPos newPos = INVALID_POS_VALUE;
4445
4446 if ( action == wxACTION_TEXT_HOME )
4447 {
4448 newPos = m_curPos - m_curCol;
4449 }
4450 else if ( action == wxACTION_TEXT_END )
4451 {
4452 newPos = m_curPos + GetLineLength(m_curRow) - m_curCol;
4453 }
4454 else if ( (action == wxACTION_TEXT_GOTO) ||
4455 (action == wxACTION_TEXT_FIRST) ||
4456 (action == wxACTION_TEXT_LAST) )
4457 {
4458 if ( action == wxACTION_TEXT_FIRST )
4459 numArg = 0;
4460 else if ( action == wxACTION_TEXT_LAST )
4461 numArg = GetLastPosition();
4462 //else: numArg already contains the position
4463
4464 newPos = numArg;
4465 }
4466 else if ( action == wxACTION_TEXT_UP )
4467 {
4468 if ( !IsSingleLine() )
4469 {
4470 newPos = GetPositionAbove();
4471
4472 if ( newPos != INVALID_POS_VALUE )
4473 {
4474 // remember where the cursor original had been
a290fa5a 4475 rememberAbscissa = true;
1e6feb95
VZ
4476 }
4477 }
4478 }
4479 else if ( action == wxACTION_TEXT_DOWN )
4480 {
4481 if ( !IsSingleLine() )
4482 {
4483 newPos = GetPositionBelow();
4484
4485 if ( newPos != INVALID_POS_VALUE )
4486 {
4487 // remember where the cursor original had been
a290fa5a 4488 rememberAbscissa = true;
1e6feb95
VZ
4489 }
4490 }
4491 }
4492 else if ( action == wxACTION_TEXT_LEFT )
4493 {
4494 newPos = m_curPos - 1;
4495 }
4496 else if ( action == wxACTION_TEXT_WORD_LEFT )
4497 {
4498 newPos = GetWordStart();
4499 }
4500 else if ( action == wxACTION_TEXT_RIGHT )
4501 {
4502 newPos = m_curPos + 1;
4503 }
4504 else if ( action == wxACTION_TEXT_WORD_RIGHT )
4505 {
4506 newPos = GetWordEnd();
4507 }
4508 else if ( action == wxACTION_TEXT_INSERT )
4509 {
4510 if ( IsEditable() && !strArg.empty() )
4511 {
4512 // inserting text can be undone
4513 command = new wxTextCtrlInsertCommand(strArg);
4514
a290fa5a 4515 textChanged = true;
1e6feb95
VZ
4516 }
4517 }
4518 else if ( (action == wxACTION_TEXT_PAGE_UP) ||
4519 (action == wxACTION_TEXT_PAGE_DOWN) )
4520 {
4521 if ( !IsSingleLine() )
4522 {
4523 size_t count = GetLinesPerPage();
4524 if ( count > PAGE_OVERLAP_IN_LINES )
4525 {
4526 // pages should overlap slightly to allow the reader to keep
4527 // orientation in the text
4528 count -= PAGE_OVERLAP_IN_LINES;
4529 }
4530
4531 // remember where the cursor original had been
a290fa5a 4532 rememberAbscissa = true;
1e6feb95
VZ
4533
4534 bool goUp = action == wxACTION_TEXT_PAGE_UP;
4535 for ( size_t line = 0; line < count; line++ )
4536 {
4537 wxTextPos pos = goUp ? GetPositionAbove() : GetPositionBelow();
4538 if ( pos == INVALID_POS_VALUE )
4539 {
4540 // can't move further
4541 break;
4542 }
4543
4544 MoveInsertionPoint(pos);
4545 newPos = pos;
4546 }
4547
4548 // we implement the Unix scrolling model here: cursor will always
4549 // be on the first line after Page Down and on the last one after
4550 // Page Up
4551 //
4552 // Windows programs usually keep the cursor line offset constant
4553 // but do we really need it?
4554 wxCoord y;
4555 if ( goUp )
4556 {
4557 // find the line such that when it is the first one, the
4558 // current position is in the last line
4559 wxTextPos pos = 0;
4560 for ( size_t line = 0; line < count; line++ )
4561 {
4562 pos = GetPositionAbove();
4563 if ( pos == INVALID_POS_VALUE )
4564 break;
4565
4566 MoveInsertionPoint(pos);
4567 }
4568
4569 MoveInsertionPoint(newPos);
4570
4571 PositionToLogicalXY(pos, NULL, &y);
4572 }
4573 else // scrolled down
4574 {
4575 PositionToLogicalXY(newPos, NULL, &y);
4576 }
4577
4578 // scroll vertically only
a290fa5a 4579 Scroll(wxDefaultCoord, y);
1e6feb95
VZ
4580 }
4581 }
4582 else if ( action == wxACTION_TEXT_SEL_WORD )
4583 {
4584 SetSelection(GetWordStart(), GetWordEnd());
4585 }
4586 else if ( action == wxACTION_TEXT_ANCHOR_SEL )
4587 {
4588 newPos = numArg;
4589 }
4590 else if ( action == wxACTION_TEXT_EXTEND_SEL )
4591 {
4592 SetSelection(m_selAnchor, numArg);
4593 }
4594 else if ( action == wxACTION_TEXT_COPY )
4595 {
4596 Copy();
4597 }
4598 else if ( action == wxACTION_TEXT_CUT )
4599 {
4600 if ( IsEditable() )
4601 Cut();
4602 }
4603 else if ( action == wxACTION_TEXT_PASTE )
4604 {
4605 if ( IsEditable() )
4606 Paste();
4607 }
4608 else if ( action == wxACTION_TEXT_UNDO )
4609 {
4610 if ( CanUndo() )
4611 Undo();
4612 }
4613 else if ( action == wxACTION_TEXT_REDO )
4614 {
4615 if ( CanRedo() )
4616 Redo();
4617 }
4618 else
4619 {
4620 return wxControl::PerformAction(action, numArg, strArg);
4621 }
4622
4623 if ( newPos != INVALID_POS_VALUE )
4624 {
4625 // bring the new position into the range
4626 if ( newPos < 0 )
4627 newPos = 0;
4628
4629 wxTextPos posLast = GetLastPosition();
4630 if ( newPos > posLast )
4631 newPos = posLast;
4632
4633 if ( del )
4634 {
4635 // if we have the selection, remove just it
4636 wxTextPos from, to;
4637 if ( HasSelection() )
4638 {
4639 from = m_selStart;
4640 to = m_selEnd;
4641 }
4642 else
4643 {
4644 // otherwise delete everything between current position and
4645 // the new one
4646 if ( m_curPos != newPos )
4647 {
4648 from = m_curPos;
4649 to = newPos;
4650 }
4651 else // nothing to delete
4652 {
4653 // prevent test below from working
4654 from = INVALID_POS_VALUE;
4655
4656 // and this is just to silent the compiler warning
4657 to = 0;
4658 }
4659 }
4660
4661 if ( from != INVALID_POS_VALUE )
4662 {
4663 command = new wxTextCtrlRemoveCommand(from, to);
4664 }
4665 }
4666 else // cursor movement command
4667 {
4668 // just go there
4669 DoSetInsertionPoint(newPos);
4670
4671 if ( sel )
4672 {
4673 SetSelection(m_selAnchor, m_curPos);
4674 }
4675 else // simple movement
4676 {
4677 // clear the existing selection
4678 ClearSelection();
4679 }
4680 }
4681
4682 if ( !rememberAbscissa && !IsSingleLine() )
4683 {
4684 MData().m_xCaret = -1;
4685 }
4686 }
4687
4688 if ( command )
4689 {
4690 // execute and remember it to be able to undo it later
4691 m_cmdProcessor->Submit(command);
4692
4693 // undoable commands always change text
a290fa5a 4694 textChanged = true;
1e6feb95
VZ
4695 }
4696 else // no undoable command
4697 {
4698 // m_cmdProcessor->StopCompressing()
4699 }
4700
4701 if ( textChanged )
4702 {
4703 wxASSERT_MSG( IsEditable(), _T("non editable control changed?") );
4704
4705 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
4706 InitCommandEvent(event);
1e6feb95
VZ
4707 GetEventHandler()->ProcessEvent(event);
4708
4709 // as the text changed...
a290fa5a 4710 m_isModified = true;
1e6feb95
VZ
4711 }
4712
a290fa5a 4713 return true;
1e6feb95
VZ
4714}
4715
4716void wxTextCtrl::OnChar(wxKeyEvent& event)
4717{
4718 // only process the key events from "simple keys" here
4719 if ( !event.HasModifiers() )
4720 {
4721 int keycode = event.GetKeyCode();
568c0346
JS
4722#if wxUSE_UNICODE
4723 wxChar unicode = event.GetUnicodeKey();
faa94f3e 4724#endif
1e6feb95
VZ
4725 if ( keycode == WXK_RETURN )
4726 {
4727 if ( IsSingleLine() || (GetWindowStyle() & wxTE_PROCESS_ENTER) )
4728 {
4729 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, GetId());
4730 InitCommandEvent(event);
4731 event.SetString(GetValue());
4732 GetEventHandler()->ProcessEvent(event);
4733 }
4734 else // interpret <Enter> normally: insert new line
4735 {
4736 PerformAction(wxACTION_TEXT_INSERT, -1, _T('\n'));
4737 }
4738 }
4739 else if ( keycode < 255 && isprint(keycode) )
4740 {
4741 PerformAction(wxACTION_TEXT_INSERT, -1, (wxChar)keycode);
4742
4743 // skip event.Skip() below
4744 return;
4745 }
568c0346
JS
4746#if wxUSE_UNICODE
4747 else if (unicode > 0)
4748 {
4749 PerformAction(wxACTION_TEXT_INSERT, -1, unicode);
4750
4751 return;
4752 }
faa94f3e 4753#endif
1e6feb95
VZ
4754 }
4755#ifdef __WXDEBUG__
4756 // Ctrl-R refreshes the control in debug mode
4757 else if ( event.ControlDown() && event.GetKeyCode() == 'r' )
4758 Refresh();
4759#endif // __WXDEBUG__
4760
4761 event.Skip();
4762}
4763
9467bdb7
VZ
4764/* static */
4765wxInputHandler *wxTextCtrl::GetStdInputHandler(wxInputHandler *handlerDef)
4766{
4767 static wxStdTextCtrlInputHandler s_handler(handlerDef);
4768
4769 return &s_handler;
4770}
4771
1e6feb95
VZ
4772// ----------------------------------------------------------------------------
4773// wxStdTextCtrlInputHandler
4774// ----------------------------------------------------------------------------
4775
4776wxStdTextCtrlInputHandler::wxStdTextCtrlInputHandler(wxInputHandler *inphand)
4777 : wxStdInputHandler(inphand)
4778{
4779 m_winCapture = (wxTextCtrl *)NULL;
4780}
4781
4782/* static */
4783wxTextPos wxStdTextCtrlInputHandler::HitTest(const wxTextCtrl *text,
4784 const wxPoint& pt)
4785{
4786 wxTextCoord col, row;
4787 wxTextCtrlHitTestResult ht = text->HitTest(pt, &col, &row);
4788
4789 wxTextPos pos = text->XYToPosition(col, row);
4790
4791 // if the point is after the last column we must adjust the position to be
4792 // the last position in the line (unless it is already the last)
4793 if ( (ht == wxTE_HT_BEYOND) && (pos < text->GetLastPosition()) )
4794 {
4795 pos++;
4796 }
4797
4798 return pos;
4799}
4800
23645bfa 4801bool wxStdTextCtrlInputHandler::HandleKey(wxInputConsumer *consumer,
1e6feb95
VZ
4802 const wxKeyEvent& event,
4803 bool pressed)
4804{
4805 // we're only interested in key presses
4806 if ( !pressed )
a290fa5a 4807 return false;
1e6feb95
VZ
4808
4809 int keycode = event.GetKeyCode();
4810
4811 wxControlAction action;
4812 wxString str;
4813 bool ctrlDown = event.ControlDown(),
4814 shiftDown = event.ShiftDown();
4815 if ( shiftDown )
4816 {
4817 action = wxACTION_TEXT_PREFIX_SEL;
4818 }
4819
4820 // the only key combination with Alt we recognize is Alt-Bksp for undo, so
4821 // treat it first separately
4822 if ( event.AltDown() )
4823 {
4824 if ( keycode == WXK_BACK && !ctrlDown && !shiftDown )
4825 action = wxACTION_TEXT_UNDO;
4826 }
4827 else switch ( keycode )
4828 {
4829 // cursor movement
4830 case WXK_HOME:
4831 action << (ctrlDown ? wxACTION_TEXT_FIRST
4832 : wxACTION_TEXT_HOME);
4833 break;
4834
4835 case WXK_END:
4836 action << (ctrlDown ? wxACTION_TEXT_LAST
4837 : wxACTION_TEXT_END);
4838 break;
4839
4840 case WXK_UP:
4841 if ( !ctrlDown )
4842 action << wxACTION_TEXT_UP;
4843 break;
4844
4845 case WXK_DOWN:
4846 if ( !ctrlDown )
4847 action << wxACTION_TEXT_DOWN;
4848 break;
4849
4850 case WXK_LEFT:
4851 action << (ctrlDown ? wxACTION_TEXT_WORD_LEFT
4852 : wxACTION_TEXT_LEFT);
4853 break;
4854
4855 case WXK_RIGHT:
4856 action << (ctrlDown ? wxACTION_TEXT_WORD_RIGHT
4857 : wxACTION_TEXT_RIGHT);
4858 break;
4859
4860 case WXK_PAGEDOWN:
1e6feb95
VZ
4861 // we don't map Ctrl-PgUp/Dn to anything special - what should it
4862 // to? for now, it's the same as without control
4863 action << wxACTION_TEXT_PAGE_DOWN;
4864 break;
4865
4866 case WXK_PAGEUP:
1e6feb95
VZ
4867 action << wxACTION_TEXT_PAGE_UP;
4868 break;
4869
4870 // delete
4871 case WXK_DELETE:
4872 if ( !ctrlDown )
4873 action << wxACTION_TEXT_PREFIX_DEL << wxACTION_TEXT_RIGHT;
4874 break;
4875
4876 case WXK_BACK:
4877 if ( !ctrlDown )
4878 action << wxACTION_TEXT_PREFIX_DEL << wxACTION_TEXT_LEFT;
4879 break;
4880
4881 // something else
4882 default:
4883 // reset the action as it could be already set to one of the
4884 // prefixes
4885 action = wxACTION_NONE;
4886
4887 if ( ctrlDown )
4888 {
4889 switch ( keycode )
4890 {
4891 case 'A':
4892 action = wxACTION_TEXT_REDO;
4893 break;
4894
4895 case 'C':
4896 action = wxACTION_TEXT_COPY;
4897 break;
4898
4899 case 'V':
4900 action = wxACTION_TEXT_PASTE;
4901 break;
4902
4903 case 'X':
4904 action = wxACTION_TEXT_CUT;
4905 break;
4906
4907 case 'Z':
4908 action = wxACTION_TEXT_UNDO;
4909 break;
4910 }
4911 }
4912 }
4913
4914 if ( (action != wxACTION_NONE) && (action != wxACTION_TEXT_PREFIX_SEL) )
4915 {
23645bfa 4916 consumer->PerformAction(action, -1, str);
1e6feb95 4917
a290fa5a 4918 return true;
1e6feb95
VZ
4919 }
4920
23645bfa 4921 return wxStdInputHandler::HandleKey(consumer, event, pressed);
1e6feb95
VZ
4922}
4923
23645bfa 4924bool wxStdTextCtrlInputHandler::HandleMouse(wxInputConsumer *consumer,
1e6feb95
VZ
4925 const wxMouseEvent& event)
4926{
4927 if ( event.LeftDown() )
4928 {
4929 wxASSERT_MSG( !m_winCapture, _T("left button going down twice?") );
4930
23645bfa 4931 wxTextCtrl *text = wxStaticCast(consumer->GetInputWindow(), wxTextCtrl);
1e6feb95
VZ
4932
4933 m_winCapture = text;
4934 m_winCapture->CaptureMouse();
4935
4936 text->HideCaret();
4937
4938 wxTextPos pos = HitTest(text, event.GetPosition());
4939 if ( pos != -1 )
4940 {
4941 text->PerformAction(wxACTION_TEXT_ANCHOR_SEL, pos);
4942 }
4943 }
4944 else if ( event.LeftDClick() )
4945 {
4946 // select the word the cursor is on
23645bfa 4947 consumer->PerformAction(wxACTION_TEXT_SEL_WORD);
1e6feb95
VZ
4948 }
4949 else if ( event.LeftUp() )
4950 {
4951 if ( m_winCapture )
4952 {
4953 m_winCapture->ShowCaret();
4954
4955 m_winCapture->ReleaseMouse();
4956 m_winCapture = (wxTextCtrl *)NULL;
4957 }
4958 }
4959
23645bfa 4960 return wxStdInputHandler::HandleMouse(consumer, event);
1e6feb95
VZ
4961}
4962
23645bfa 4963bool wxStdTextCtrlInputHandler::HandleMouseMove(wxInputConsumer *consumer,
1e6feb95
VZ
4964 const wxMouseEvent& event)
4965{
4966 if ( m_winCapture )
4967 {
4968 // track it
4969 wxTextCtrl *text = wxStaticCast(m_winCapture, wxTextCtrl);
4970 wxTextPos pos = HitTest(text, event.GetPosition());
4971 if ( pos != -1 )
4972 {
4973 text->PerformAction(wxACTION_TEXT_EXTEND_SEL, pos);
4974 }
4975 }
4976
23645bfa 4977 return wxStdInputHandler::HandleMouseMove(consumer, event);
1e6feb95
VZ
4978}
4979
61fef19b
VZ
4980bool
4981wxStdTextCtrlInputHandler::HandleFocus(wxInputConsumer *consumer,
e28c2d15 4982 const wxFocusEvent& event)
1e6feb95 4983{
23645bfa 4984 wxTextCtrl *text = wxStaticCast(consumer->GetInputWindow(), wxTextCtrl);
1e6feb95
VZ
4985
4986 // the selection appearance changes depending on whether we have the focus
4987 text->RefreshSelection();
4988
e28c2d15
JS
4989 if (event.GetEventType() == wxEVT_SET_FOCUS)
4990 {
4991 if (text->GetCaret() && !text->GetCaret()->IsVisible())
4992 text->ShowCaret();
4993 }
4994 else
4995 {
4996 if (text->GetCaret() && text->GetCaret()->IsVisible())
4997 text->HideCaret();
4998 }
4999
1e6feb95 5000 // never refresh entirely
a290fa5a 5001 return false;
1e6feb95
VZ
5002}
5003
5004#endif // wxUSE_TEXTCTRL