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