1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/msw/wince/textctrlce.cpp
3 // Purpose:     wxTextCtrl implementation for smart phones driven by WinCE
4 // Author:      Wlodzimierz ABX Skiba
5 // Modified by:
6 // Created:     30.08.2004
7 // Copyright:   (c) Wlodzimierz Skiba
8 // Licence:     wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
10 
11 // ============================================================================
12 // declarations
13 // ============================================================================
14 
15 // ----------------------------------------------------------------------------
16 // headers
17 // ----------------------------------------------------------------------------
18 
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21 
22 #ifdef __BORLANDC__
23     #pragma hdrstop
24 #endif
25 
26 #if wxUSE_TEXTCTRL && defined(__SMARTPHONE__) && defined(__WXWINCE__)
27 
28 #include "wx/textctrl.h"
29 
30 #ifndef WX_PRECOMP
31     #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
32 #endif
33 
34 #include "wx/spinbutt.h"
35 #include "wx/textfile.h"
36 
37 #define GetBuddyHwnd()      (HWND)(m_hwndBuddy)
38 
39 #define IsVertical(wxStyle) (true)
40 
41 // ----------------------------------------------------------------------------
42 // event tables and other macros
43 // ----------------------------------------------------------------------------
44 
45 BEGIN_EVENT_TABLE(wxTextCtrl, wxControl)
46     EVT_CHAR(wxTextCtrl::OnChar)
47 
48     EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
49     EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
50     EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
51     EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
52     EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
53     EVT_MENU(wxID_CLEAR, wxTextCtrl::OnDelete)
54     EVT_MENU(wxID_SELECTALL, wxTextCtrl::OnSelectAll)
55 
56     EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
57     EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
58     EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
59     EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
60     EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
61     EVT_UPDATE_UI(wxID_CLEAR, wxTextCtrl::OnUpdateDelete)
62     EVT_UPDATE_UI(wxID_SELECTALL, wxTextCtrl::OnUpdateSelectAll)
63 
64     EVT_SET_FOCUS(wxTextCtrl::OnSetFocus)
65 END_EVENT_TABLE()
66 
67 // ----------------------------------------------------------------------------
68 // constants
69 // ----------------------------------------------------------------------------
70 
71 // the margin between the up-down control and its buddy (can be arbitrary,
72 // choose what you like - or may be decide during run-time depending on the
73 // font size?)
74 static const int MARGIN_BETWEEN = 0;
75 
76 // ============================================================================
77 // implementation
78 // ============================================================================
79 
80 wxArrayTextSpins wxTextCtrl::ms_allTextSpins;
81 
82 // ----------------------------------------------------------------------------
83 // wnd proc for the buddy text ctrl
84 // ----------------------------------------------------------------------------
85 
wxBuddyTextCtrlWndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)86 LRESULT APIENTRY _EXPORT wxBuddyTextCtrlWndProc(HWND hwnd,
87                                                 UINT message,
88                                                 WPARAM wParam,
89                                                 LPARAM lParam)
90 {
91     wxTextCtrl *spin = (wxTextCtrl *)wxGetWindowUserData(hwnd);
92 
93     // forward some messages (the key and focus ones only so far) to
94     // the spin ctrl
95     switch ( message )
96     {
97         case WM_SETFOCUS:
98             // if the focus comes from the spin control itself, don't set it
99             // back to it -- we don't want to go into an infinite loop
100             if ( (WXHWND)wParam == spin->GetHWND() )
101                 break;
102             //else: fall through
103 
104         case WM_KILLFOCUS:
105         case WM_CHAR:
106         case WM_DEADCHAR:
107         case WM_KEYUP:
108         case WM_KEYDOWN:
109             spin->MSWWindowProc(message, wParam, lParam);
110 
111             // The control may have been deleted at this point, so check.
112             if ( !::IsWindow(hwnd) || wxGetWindowUserData(hwnd) != spin )
113                 return 0;
114             break;
115 
116         case WM_GETDLGCODE:
117             // we want to get WXK_RETURN in order to generate the event for it
118             return DLGC_WANTCHARS;
119     }
120 
121     return ::CallWindowProc(CASTWNDPROC spin->GetBuddyWndProc(),
122                             hwnd, message, wParam, lParam);
123 }
124 
125 // ----------------------------------------------------------------------------
126 // creation
127 // ----------------------------------------------------------------------------
128 
Init()129 void wxTextCtrl::Init()
130 {
131     m_suppressNextUpdate = false;
132     m_isNativeCaretShown = true;
133 }
134 
~wxTextCtrl()135 wxTextCtrl::~wxTextCtrl()
136 {
137 }
138 
Create(wxWindow * parent,wxWindowID id,const wxString & value,const wxPoint & pos,const wxSize & size,long style,const wxValidator & validator,const wxString & name)139 bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id,
140                         const wxString& value,
141                         const wxPoint& pos,
142                         const wxSize& size,
143                         long style,
144                         const wxValidator& validator,
145                         const wxString& name)
146 {
147     if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT )
148         style |= wxBORDER_SIMPLE;
149 
150     SetWindowStyle(style);
151 
152     WXDWORD exStyle = 0;
153     WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ;
154 
155     wxSize sizeText(size), sizeBtn(size);
156     sizeBtn.x = GetBestSpinnerSize(IsVertical(style)).x / 2;
157 
158     if ( sizeText.x == wxDefaultCoord )
159     {
160         // DEFAULT_ITEM_WIDTH is the default width for the text control
161         sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x;
162     }
163 
164     sizeText.x -= sizeBtn.x + MARGIN_BETWEEN;
165     if ( sizeText.x <= 0 )
166     {
167         wxLogDebug(wxT("not enough space for wxSpinCtrl!"));
168     }
169 
170     wxPoint posBtn(pos);
171     posBtn.x += sizeText.x + MARGIN_BETWEEN;
172 
173     // we need to turn '\n's into "\r\n"s for the multiline controls
174     wxString valueWin;
175     if ( m_windowStyle & wxTE_MULTILINE )
176     {
177         valueWin = wxTextFile::Translate(value, wxTextFileType_Dos);
178     }
179     else // single line
180     {
181         valueWin = value;
182     }
183 
184     // we must create the list control before the spin button for the purpose
185     // of the dialog navigation: if there is a static text just before the spin
186     // control, activating it by Alt-letter should give focus to the text
187     // control, not the spin and the dialog navigation code will give focus to
188     // the next control (at Windows level), not the one after it
189 
190     // create the text window
191 
192     m_hwndBuddy = (WXHWND)::CreateWindowEx
193                     (
194                      exStyle,                // sunken border
195                      wxT("EDIT"),             // window class
196                      valueWin,               // no window title
197                      msStyle,                // style (will be shown later)
198                      pos.x, pos.y,           // position
199                      0, 0,                   // size (will be set later)
200                      GetHwndOf(parent),      // parent
201                      (HMENU)-1,              // control id
202                      wxGetInstance(),        // app instance
203                      NULL                    // unused client data
204                     );
205 
206     if ( !m_hwndBuddy )
207     {
208         wxLogLastError(wxT("CreateWindow(buddy text window)"));
209 
210         return false;
211     }
212 
213     // initialize wxControl
214     if ( !CreateControl(parent, id, posBtn, sizeBtn, style, validator, name) )
215         return false;
216 
217     // now create the real HWND
218     WXDWORD spiner_style = WS_VISIBLE |
219                            UDS_ALIGNRIGHT |
220                            UDS_EXPANDABLE |
221                            UDS_NOSCROLL;
222 
223     if ( !IsVertical(style) )
224         spiner_style |= UDS_HORZ;
225 
226     if ( style & wxSP_WRAP )
227         spiner_style |= UDS_WRAP;
228 
229     if ( !MSWCreateControl(UPDOWN_CLASS, spiner_style, posBtn, sizeBtn, wxT(""), 0) )
230         return false;
231 
232     // subclass the text ctrl to be able to intercept some events
233     wxSetWindowUserData(GetBuddyHwnd(), this);
234     m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(),
235                                                 wxBuddyTextCtrlWndProc);
236 
237     // set up fonts and colours  (This is nomally done in MSWCreateControl)
238     InheritAttributes();
239     if (!m_hasFont)
240         SetFont(GetDefaultAttributes().font);
241 
242     // set the size of the text window - can do it only now, because we
243     // couldn't call DoGetBestSize() before as font wasn't set
244     if ( sizeText.y <= 0 )
245     {
246         int cx, cy;
247         wxGetCharSize(GetHWND(), &cx, &cy, GetFont());
248 
249         sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
250     }
251 
252     SetInitialSize(size);
253 
254     (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW);
255 
256     // associate the list window with the spin button
257     (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)GetBuddyHwnd(), 0);
258 
259     // do it after finishing with m_hwndBuddy creation to avoid generating
260     // initial wxEVT_TEXT message
261     ms_allTextSpins.Add(this);
262 
263     return true;
264 }
265 
266 // Make sure the window style (etc.) reflects the HWND style (roughly)
AdoptAttributesFromHWND()267 void wxTextCtrl::AdoptAttributesFromHWND()
268 {
269     wxWindow::AdoptAttributesFromHWND();
270 
271     long style = ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE);
272 
273     if (style & ES_MULTILINE)
274         m_windowStyle |= wxTE_MULTILINE;
275     if (style & ES_PASSWORD)
276         m_windowStyle |= wxTE_PASSWORD;
277     if (style & ES_READONLY)
278         m_windowStyle |= wxTE_READONLY;
279     if (style & ES_WANTRETURN)
280         m_windowStyle |= wxTE_PROCESS_ENTER;
281     if (style & ES_CENTER)
282         m_windowStyle |= wxTE_CENTRE;
283     if (style & ES_RIGHT)
284         m_windowStyle |= wxTE_RIGHT;
285 }
286 
MSWGetStyle(long style,WXDWORD * exstyle) const287 WXDWORD wxTextCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const
288 {
289     // we never have an external border
290     WXDWORD msStyle = wxControl::MSWGetStyle
291                       (
292                         (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
293                       );
294 
295     msStyle |= WS_VISIBLE;
296 
297     // styles which we alaways add by default
298     if ( style & wxTE_MULTILINE )
299     {
300         wxASSERT_MSG( !(style & wxTE_PROCESS_ENTER),
301                       wxT("wxTE_PROCESS_ENTER style is ignored for multiline text controls (they always process it)") );
302 
303         msStyle |= ES_MULTILINE | ES_WANTRETURN;
304         if ( !(style & wxTE_NO_VSCROLL) )
305         {
306             // always adjust the vertical scrollbar automatically if we have it
307             msStyle |= WS_VSCROLL | ES_AUTOVSCROLL;
308         }
309 
310         style |= wxTE_PROCESS_ENTER;
311     }
312     else // !multiline
313     {
314         // there is really no reason to not have this style for single line
315         // text controls
316         msStyle |= ES_AUTOHSCROLL;
317     }
318 
319     // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
320     // scrollbar, there is no wrapping -- which makes sense
321     if ( style & wxTE_DONTWRAP )
322     {
323         // automatically scroll the control horizontally as necessary
324         //
325         // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
326         //     show horz scrollbar at all, even in spite of WS_HSCROLL, and as
327         //     it doesn't seem to do any harm for plain edit controls, add it
328         //     always
329         msStyle |= WS_HSCROLL | ES_AUTOHSCROLL;
330     }
331 
332     if ( style & wxTE_READONLY )
333         msStyle |= ES_READONLY;
334 
335     if ( style & wxTE_PASSWORD )
336         msStyle |= ES_PASSWORD;
337 
338     if ( style & wxTE_NOHIDESEL )
339         msStyle |= ES_NOHIDESEL;
340 
341     // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
342     if ( style & wxTE_CENTRE )
343         msStyle |= ES_CENTER;
344     else if ( style & wxTE_RIGHT )
345         msStyle |= ES_RIGHT;
346     else
347         msStyle |= ES_LEFT; // ES_LEFT is 0 as well but for consistency...
348 
349     return msStyle;
350 }
351 
352 // ----------------------------------------------------------------------------
353 // set/get the controls text
354 // ----------------------------------------------------------------------------
355 
GetValue() const356 wxString wxTextCtrl::GetValue() const
357 {
358     // range 0..-1 is special for GetRange() and means to retrieve all text
359     return GetRange(0, -1);
360 }
361 
GetRange(long from,long to) const362 wxString wxTextCtrl::GetRange(long from, long to) const
363 {
364     wxString str;
365 
366     if ( from >= to && to != -1 )
367     {
368         // nothing to retrieve
369         return str;
370     }
371 
372     // retrieve all text
373     str = wxGetWindowText(GetBuddyHwnd());
374 
375     // need only a range?
376     if ( from < to )
377     {
378         str = str.Mid(from, to - from);
379     }
380 
381     // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
382     // canonical one (same one as above) for consistency with the other kinds
383     // of controls and, more importantly, with the other ports
384     str = wxTextFile::Translate(str, wxTextFileType_Unix);
385 
386     return str;
387 }
388 
DoSetValue(const wxString & value,int flags)389 void wxTextCtrl::DoSetValue(const wxString& value, int flags)
390 {
391     // if the text is long enough, it's faster to just set it instead of first
392     // comparing it with the old one (chances are that it will be different
393     // anyhow, this comparison is there to avoid flicker for small single-line
394     // edit controls mostly)
395     if ( (value.length() > 0x400) || (value != GetValue()) )
396     {
397         DoWriteText(value, flags);
398 
399         // for compatibility, don't move the cursor when doing SetValue()
400         SetInsertionPoint(0);
401     }
402     else // same text
403     {
404         // still send an event for consistency
405         if ( flags & SetValue_SendEvent )
406             SendUpdateEvent();
407     }
408 
409     // we should reset the modified flag even if the value didn't really change
410 
411     // mark the control as being not dirty - we changed its text, not the
412     // user
413     DiscardEdits();
414 }
415 
WriteText(const wxString & value)416 void wxTextCtrl::WriteText(const wxString& value)
417 {
418     DoWriteText(value);
419 }
420 
DoWriteText(const wxString & value,int flags)421 void wxTextCtrl::DoWriteText(const wxString& value, int flags)
422 {
423     bool selectionOnly = (flags & SetValue_SelectionOnly) != 0;
424     wxString valueDos;
425     if ( m_windowStyle & wxTE_MULTILINE )
426         valueDos = wxTextFile::Translate(value, wxTextFileType_Dos);
427     else
428         valueDos = value;
429 
430     // in some cases we get 2 EN_CHANGE notifications after the SendMessage
431     // call below which is confusing for the client code and so should be
432     // avoided
433     //
434     if ( selectionOnly && HasSelection() )
435     {
436         m_suppressNextUpdate = true;
437     }
438 
439     ::SendMessage(GetBuddyHwnd(), selectionOnly ? EM_REPLACESEL : WM_SETTEXT,
440                   0, (LPARAM)valueDos.c_str());
441 
442     if ( !selectionOnly && !( flags & SetValue_SendEvent ) )
443     {
444         // Windows already sends an update event for single-line
445         // controls.
446         if ( m_windowStyle & wxTE_MULTILINE )
447             SendUpdateEvent();
448     }
449 
450     AdjustSpaceLimit();
451 }
452 
AppendText(const wxString & text)453 void wxTextCtrl::AppendText(const wxString& text)
454 {
455     SetInsertionPointEnd();
456 
457     WriteText(text);
458 }
459 
Clear()460 void wxTextCtrl::Clear()
461 {
462     ::SetWindowText(GetBuddyHwnd(), wxEmptyString);
463 
464     // Windows already sends an update event for single-line
465     // controls.
466     if ( m_windowStyle & wxTE_MULTILINE )
467         SendUpdateEvent();
468 }
469 
470 // ----------------------------------------------------------------------------
471 // Clipboard operations
472 // ----------------------------------------------------------------------------
473 
Copy()474 void wxTextCtrl::Copy()
475 {
476     if (CanCopy())
477     {
478         ::SendMessage(GetBuddyHwnd(), WM_COPY, 0, 0L);
479     }
480 }
481 
Cut()482 void wxTextCtrl::Cut()
483 {
484     if (CanCut())
485     {
486         ::SendMessage(GetBuddyHwnd(), WM_CUT, 0, 0L);
487     }
488 }
489 
Paste()490 void wxTextCtrl::Paste()
491 {
492     if (CanPaste())
493     {
494         ::SendMessage(GetBuddyHwnd(), WM_PASTE, 0, 0L);
495     }
496 }
497 
HasSelection() const498 bool wxTextCtrl::HasSelection() const
499 {
500     long from, to;
501     GetSelection(&from, &to);
502     return from != to;
503 }
504 
CanCopy() const505 bool wxTextCtrl::CanCopy() const
506 {
507     // Can copy if there's a selection
508     return HasSelection();
509 }
510 
CanCut() const511 bool wxTextCtrl::CanCut() const
512 {
513     return CanCopy() && IsEditable();
514 }
515 
CanPaste() const516 bool wxTextCtrl::CanPaste() const
517 {
518     if ( !IsEditable() )
519         return false;
520 
521     // Standard edit control: check for straight text on clipboard
522     if ( !::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) )
523         return false;
524 
525     bool isTextAvailable = ::IsClipboardFormatAvailable(CF_TEXT) != 0;
526     ::CloseClipboard();
527 
528     return isTextAvailable;
529 }
530 
531 // ----------------------------------------------------------------------------
532 // Accessors
533 // ----------------------------------------------------------------------------
534 
SetEditable(bool editable)535 void wxTextCtrl::SetEditable(bool editable)
536 {
537     ::SendMessage(GetBuddyHwnd(), EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
538 }
539 
SetInsertionPoint(long pos)540 void wxTextCtrl::SetInsertionPoint(long pos)
541 {
542     DoSetSelection(pos, pos);
543 }
544 
SetInsertionPointEnd()545 void wxTextCtrl::SetInsertionPointEnd()
546 {
547     if ( GetInsertionPoint() != GetLastPosition() )
548         SetInsertionPoint(GetLastPosition());
549 }
550 
GetInsertionPoint() const551 long wxTextCtrl::GetInsertionPoint() const
552 {
553     DWORD Pos = (DWORD)::SendMessage(GetBuddyHwnd(), EM_GETSEL, 0, 0L);
554     return Pos & 0xFFFF;
555 }
556 
GetLastPosition() const557 wxTextPos wxTextCtrl::GetLastPosition() const
558 {
559     int numLines = GetNumberOfLines();
560     long posStartLastLine = XYToPosition(0, numLines - 1);
561 
562     long lenLastLine = GetLengthOfLineContainingPos(posStartLastLine);
563 
564     return posStartLastLine + lenLastLine;
565 }
566 
GetSelection(long * from,long * to) const567 void wxTextCtrl::GetSelection(long* from, long* to) const
568 {
569     DWORD dwStart, dwEnd;
570     ::SendMessage(GetBuddyHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
571 
572     *from = dwStart;
573     *to = dwEnd;
574 }
575 
IsEditable() const576 bool wxTextCtrl::IsEditable() const
577 {
578     if ( !GetBuddyHwnd() )
579         return true;
580 
581     long style = ::GetWindowLong(GetBuddyHwnd(), GWL_STYLE);
582 
583     return (style & ES_READONLY) == 0;
584 }
585 
586 // ----------------------------------------------------------------------------
587 // selection
588 // ----------------------------------------------------------------------------
589 
SetSelection(long from,long to)590 void wxTextCtrl::SetSelection(long from, long to)
591 {
592     // if from and to are both -1, it means (in wxWidgets) that all text should
593     // be selected - translate into Windows convention
594     if ( (from == -1) && (to == -1) )
595     {
596         from = 0;
597         to = -1;
598     }
599 
600     DoSetSelection(from, to);
601 }
602 
DoSetSelection(long from,long to,bool scrollCaret)603 void wxTextCtrl::DoSetSelection(long from, long to, bool scrollCaret)
604 {
605     ::SendMessage(GetBuddyHwnd(), EM_SETSEL, (WPARAM)from, (LPARAM)to);
606 
607     if ( scrollCaret )
608     {
609         ::SendMessage(GetBuddyHwnd(), EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
610     }
611 }
612 
613 // ----------------------------------------------------------------------------
614 // Working with files
615 // ----------------------------------------------------------------------------
616 
LoadFile(const wxString & file)617 bool wxTextCtrl::LoadFile(const wxString& file)
618 {
619     if ( wxTextCtrlBase::LoadFile(file) )
620     {
621         // update the size limit if needed
622         AdjustSpaceLimit();
623 
624         return true;
625     }
626 
627     return false;
628 }
629 
630 // ----------------------------------------------------------------------------
631 // Editing
632 // ----------------------------------------------------------------------------
633 
Replace(long from,long to,const wxString & value)634 void wxTextCtrl::Replace(long from, long to, const wxString& value)
635 {
636     // Set selection and remove it
637     DoSetSelection(from, to, false);
638 
639     DoWriteText(value, SetValue_SelectionOnly);
640 }
641 
Remove(long from,long to)642 void wxTextCtrl::Remove(long from, long to)
643 {
644     Replace(from, to, wxEmptyString);
645 }
646 
IsModified() const647 bool wxTextCtrl::IsModified() const
648 {
649     return ::SendMessage(GetBuddyHwnd(), EM_GETMODIFY, 0, 0) != 0;
650 }
651 
MarkDirty()652 void wxTextCtrl::MarkDirty()
653 {
654     ::SendMessage(GetBuddyHwnd(), EM_SETMODIFY, TRUE, 0L);
655 }
656 
DiscardEdits()657 void wxTextCtrl::DiscardEdits()
658 {
659     ::SendMessage(GetBuddyHwnd(), EM_SETMODIFY, FALSE, 0L);
660 }
661 
GetNumberOfLines() const662 int wxTextCtrl::GetNumberOfLines() const
663 {
664     return (int)::SendMessage(GetBuddyHwnd(), EM_GETLINECOUNT, 0, 0L);
665 }
666 
667 // ----------------------------------------------------------------------------
668 // Positions <-> coords
669 // ----------------------------------------------------------------------------
670 
XYToPosition(long x,long y) const671 long wxTextCtrl::XYToPosition(long x, long y) const
672 {
673     // This gets the char index for the _beginning_ of this line
674     long charIndex = ::SendMessage(GetBuddyHwnd(), EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
675 
676     return charIndex + x;
677 }
678 
PositionToXY(long pos,long * x,long * y) const679 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
680 {
681     // This gets the line number containing the character
682     long lineNo = ::SendMessage(GetBuddyHwnd(), EM_LINEFROMCHAR, (WPARAM)pos, 0);
683 
684     if ( lineNo == -1 )
685     {
686         // no such line
687         return false;
688     }
689 
690     // This gets the char index for the _beginning_ of this line
691     long charIndex = ::SendMessage(GetBuddyHwnd(), EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
692     if ( charIndex == -1 )
693     {
694         return false;
695     }
696 
697     // The X position must therefore be the different between pos and charIndex
698     if ( x )
699         *x = pos - charIndex;
700     if ( y )
701         *y = lineNo;
702 
703     return true;
704 }
705 
706 wxTextCtrlHitTestResult
HitTest(const wxPoint & pt,long * posOut) const707 wxTextCtrl::HitTest(const wxPoint& pt, long *posOut) const
708 {
709     // first get the position from Windows
710     // for the plain ones, we are limited to 16 bit positions which are
711     // combined in a single 32 bit value
712     LPARAM lParam = MAKELPARAM(pt.x, pt.y);
713 
714     LRESULT pos = ::SendMessage(GetBuddyHwnd(), EM_CHARFROMPOS, 0, lParam);
715 
716     if ( pos == -1 )
717     {
718         // this seems to indicate an error...
719         return wxTE_HT_UNKNOWN;
720     }
721 
722     // for plain EDIT controls the higher word contains something else
723     pos = LOWORD(pos);
724 
725 
726     // next determine where it is relatively to our point: EM_CHARFROMPOS
727     // always returns the closest character but we need to be more precise, so
728     // double check that we really are where it pretends
729     POINTL ptReal;
730 
731     LRESULT lRc = ::SendMessage(GetBuddyHwnd(), EM_POSFROMCHAR, pos, 0);
732 
733     if ( lRc == -1 )
734     {
735         // this is apparently returned when pos corresponds to the last
736         // position
737         ptReal.x =
738         ptReal.y = 0;
739     }
740     else
741     {
742         ptReal.x = LOWORD(lRc);
743         ptReal.y = HIWORD(lRc);
744     }
745 
746     wxTextCtrlHitTestResult rc;
747 
748     if ( pt.y > ptReal.y + GetCharHeight() )
749         rc = wxTE_HT_BELOW;
750     else if ( pt.x > ptReal.x + GetCharWidth() )
751         rc = wxTE_HT_BEYOND;
752     else
753         rc = wxTE_HT_ON_TEXT;
754 
755     if ( posOut )
756         *posOut = pos;
757 
758     return rc;
759 }
760 
ShowPosition(long pos)761 void wxTextCtrl::ShowPosition(long pos)
762 {
763     int currentLineLineNo = (int)::SendMessage(GetBuddyHwnd(), EM_GETFIRSTVISIBLELINE, 0, 0L);
764 
765     int specifiedLineLineNo = (int)::SendMessage(GetBuddyHwnd(), EM_LINEFROMCHAR, (WPARAM)pos, 0L);
766 
767     int linesToScroll = specifiedLineLineNo - currentLineLineNo;
768 
769     if (linesToScroll != 0)
770         (void)::SendMessage(GetBuddyHwnd(), EM_LINESCROLL, 0, (LPARAM)linesToScroll);
771 }
772 
GetLengthOfLineContainingPos(long pos) const773 long wxTextCtrl::GetLengthOfLineContainingPos(long pos) const
774 {
775     return ::SendMessage(GetBuddyHwnd(), EM_LINELENGTH, (WPARAM)pos, 0L);
776 }
777 
GetLineLength(long lineNo) const778 int wxTextCtrl::GetLineLength(long lineNo) const
779 {
780     long pos = XYToPosition(0, lineNo);
781 
782     return GetLengthOfLineContainingPos(pos);
783 }
784 
GetLineText(long lineNo) const785 wxString wxTextCtrl::GetLineText(long lineNo) const
786 {
787     size_t len = (size_t)GetLineLength(lineNo) + 1;
788 
789     // there must be at least enough place for the length WORD in the
790     // buffer
791     len += sizeof(WORD);
792 
793     wxString str;
794     {
795         wxStringBufferLength tmp(str, len);
796         wxChar *buf = tmp;
797 
798         *(WORD *)buf = (WORD)len;
799         len = (size_t)::SendMessage(GetBuddyHwnd(), EM_GETLINE, lineNo, (LPARAM)buf);
800 
801         // remove the '\n' at the end, if any (this is how this function is
802         // supposed to work according to the docs)
803         if ( buf[len - 1] == wxT('\n') )
804         {
805             len--;
806         }
807 
808         buf[len] = 0;
809         tmp.SetLength(len);
810     }
811 
812     return str;
813 }
814 
SetMaxLength(unsigned long len)815 void wxTextCtrl::SetMaxLength(unsigned long len)
816 {
817     ::SendMessage(GetBuddyHwnd(), EM_LIMITTEXT, len, 0);
818 }
819 
820 // ----------------------------------------------------------------------------
821 // Undo/redo
822 // ----------------------------------------------------------------------------
823 
Undo()824 void wxTextCtrl::Undo()
825 {
826     if (CanUndo())
827     {
828         ::SendMessage(GetBuddyHwnd(), EM_UNDO, 0, 0);
829     }
830 }
831 
Redo()832 void wxTextCtrl::Redo()
833 {
834     if (CanRedo())
835     {
836         ::SendMessage(GetBuddyHwnd(), EM_UNDO, 0, 0);
837     }
838 }
839 
CanUndo() const840 bool wxTextCtrl::CanUndo() const
841 {
842     return ::SendMessage(GetBuddyHwnd(), EM_CANUNDO, 0, 0) != 0;
843 }
844 
CanRedo() const845 bool wxTextCtrl::CanRedo() const
846 {
847     return ::SendMessage(GetBuddyHwnd(), EM_CANUNDO, 0, 0) != 0;
848 }
849 
850 // ----------------------------------------------------------------------------
851 // caret handling
852 // ----------------------------------------------------------------------------
853 
854 // ----------------------------------------------------------------------------
855 // implemenation details
856 // ----------------------------------------------------------------------------
857 
Command(wxCommandEvent & event)858 void wxTextCtrl::Command(wxCommandEvent & event)
859 {
860     SetValue(event.GetString());
861     ProcessCommand (event);
862 }
863 
864 // ----------------------------------------------------------------------------
865 // kbd input processing
866 // ----------------------------------------------------------------------------
867 
OnChar(wxKeyEvent & event)868 void wxTextCtrl::OnChar(wxKeyEvent& event)
869 {
870     switch ( event.GetKeyCode() )
871     {
872         case WXK_RETURN:
873             if ( !HasFlag(wxTE_MULTILINE) )
874             {
875                 wxCommandEvent event(wxEVT_TEXT_ENTER, m_windowId);
876                 InitCommandEvent(event);
877                 event.SetString(GetValue());
878                 if ( GetEventHandler()->ProcessEvent(event) )
879                     return;
880             }
881             //else: multiline controls need Enter for themselves
882 
883             break;
884 
885         case WXK_TAB:
886             // ok, so this is getting absolutely ridiculous but I don't see
887             // any other way to fix this bug: when a multiline text control is
888             // inside a wxFrame, we need to generate the navigation event as
889             // otherwise nothing happens at all, but when the same control is
890             // created inside a dialog, IsDialogMessage() *does* switch focus
891             // all by itself and so if we do it here as well, it is advanced
892             // twice and goes to the next control... to prevent this from
893             // happening we're doing this ugly check, the logic being that if
894             // we don't have focus then it had been already changed to the next
895             // control
896             //
897             // the right thing to do would, of course, be to understand what
898             // the hell is IsDialogMessage() doing but this is beyond my feeble
899             // forces at the moment unfortunately
900             if ( !(m_windowStyle & wxTE_PROCESS_TAB))
901             {
902                 if ( FindFocus() == this )
903                 {
904                     int flags = 0;
905                     if (!event.ShiftDown())
906                         flags |= wxNavigationKeyEvent::IsForward ;
907                     if (event.ControlDown())
908                         flags |= wxNavigationKeyEvent::WinChange ;
909                     if (Navigate(flags))
910                         return;
911                 }
912             }
913             else
914             {
915                 // Insert tab since calling the default Windows handler
916                 // doesn't seem to do it
917                 WriteText(wxT("\t"));
918             }
919             break;
920     }
921 
922     // no, we didn't process it
923     event.Skip();
924 }
925 
MSWWindowProc(WXUINT nMsg,WXWPARAM wParam,WXLPARAM lParam)926 WXLRESULT wxTextCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
927 {
928     WXLRESULT lRc = wxTextCtrlBase::MSWWindowProc(nMsg, wParam, lParam);
929 
930     if ( nMsg == WM_GETDLGCODE )
931     {
932         // we always want the chars and the arrows: the arrows for navigation
933         // and the chars because we want Ctrl-C to work even in a read only
934         // control
935         long lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS;
936 
937         if ( IsEditable() )
938         {
939             // we may have several different cases:
940             // 1. normal case: both TAB and ENTER are used for dlg navigation
941             // 2. ctrl which wants TAB for itself: ENTER is used to pass to the
942             //    next control in the dialog
943             // 3. ctrl which wants ENTER for itself: TAB is used for dialog
944             //    navigation
945             // 4. ctrl which wants both TAB and ENTER: Ctrl-ENTER is used to go
946             //    to the next control
947 
948             // the multiline edit control should always get <Return> for itself
949             if ( HasFlag(wxTE_PROCESS_ENTER) || HasFlag(wxTE_MULTILINE) )
950                 lDlgCode |= DLGC_WANTMESSAGE;
951 
952             if ( HasFlag(wxTE_PROCESS_TAB) )
953                 lDlgCode |= DLGC_WANTTAB;
954 
955             lRc |= lDlgCode;
956         }
957         else // !editable
958         {
959             // NB: use "=", not "|=" as the base class version returns the
960             //     same flags is this state as usual (i.e. including
961             //     DLGC_WANTMESSAGE). This is strange (how does it work in the
962             //     native Win32 apps?) but for now live with it.
963             lRc = lDlgCode;
964         }
965     }
966 
967     return lRc;
968 }
969 
970 // ----------------------------------------------------------------------------
971 // text control event processing
972 // ----------------------------------------------------------------------------
973 
SendUpdateEvent()974 bool wxTextCtrl::SendUpdateEvent()
975 {
976     // is event reporting suspended?
977     if ( m_suppressNextUpdate )
978     {
979         // do process the next one
980         m_suppressNextUpdate = false;
981 
982         return false;
983     }
984 
985     wxCommandEvent event(wxEVT_TEXT, GetId());
986     InitCommandEvent(event);
987     event.SetString(GetValue());
988 
989     return ProcessCommand(event);
990 }
991 
MSWCommand(WXUINT param,WXWORD WXUNUSED (id))992 bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
993 {
994     switch ( param )
995     {
996         case EN_SETFOCUS:
997         case EN_KILLFOCUS:
998             {
999                 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
1000                                                          : wxEVT_SET_FOCUS,
1001                                    m_windowId);
1002                 event.SetEventObject(this);
1003                 GetEventHandler()->ProcessEvent(event);
1004             }
1005             break;
1006 
1007         case EN_CHANGE:
1008             SendUpdateEvent();
1009             break;
1010 
1011         case EN_MAXTEXT:
1012             // the text size limit has been hit -- try to increase it
1013             if ( !AdjustSpaceLimit() )
1014             {
1015                 wxCommandEvent event(wxEVT_TEXT_MAXLEN, m_windowId);
1016                 InitCommandEvent(event);
1017                 event.SetString(GetValue());
1018                 ProcessCommand(event);
1019             }
1020             break;
1021 
1022             // the other edit notification messages are not processed
1023         default:
1024             return false;
1025     }
1026 
1027     // processed
1028     return true;
1029 }
1030 
AdjustSpaceLimit()1031 bool wxTextCtrl::AdjustSpaceLimit()
1032 {
1033     unsigned int limit = ::SendMessage(GetBuddyHwnd(), EM_GETLIMITTEXT, 0, 0);
1034 
1035     // HACK: we try to automatically extend the limit for the amount of text
1036     //       to allow (interactively) entering more than 64Kb of text under
1037     //       Win9x but we shouldn't reset the text limit which was previously
1038     //       set explicitly with SetMaxLength()
1039     //
1040     //       we could solve this by storing the limit we set in wxTextCtrl but
1041     //       to save space we prefer to simply test here the actual limit
1042     //       value: we consider that SetMaxLength() can only be called for
1043     //       values < 32Kb
1044     if ( limit < 0x8000 )
1045     {
1046         // we've got more text than limit set by SetMaxLength()
1047         return false;
1048     }
1049 
1050     unsigned int len = ::GetWindowTextLength(GetBuddyHwnd());
1051     if ( len >= limit )
1052     {
1053         limit = len + 0x8000;    // 32Kb
1054 
1055         if ( limit > 0xffff )
1056         {
1057             // this will set it to a platform-dependent maximum (much more
1058             // than 64Kb under NT)
1059             limit = 0;
1060         }
1061 
1062         ::SendMessage(GetBuddyHwnd(), EM_LIMITTEXT, limit, 0L);
1063     }
1064 
1065     // we changed the limit
1066     return true;
1067 }
1068 
AcceptsFocus() const1069 bool wxTextCtrl::AcceptsFocus() const
1070 {
1071     // we don't want focus if we can't be edited unless we're a multiline
1072     // control because then it might be still nice to get focus from keyboard
1073     // to be able to scroll it without mouse
1074     return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
1075 }
1076 
DoMoveWindow(int x,int y,int width,int height)1077 void wxTextCtrl::DoMoveWindow(int x, int y, int width, int height)
1078 {
1079     int widthBtn = GetBestSpinnerSize(IsVertical(GetWindowStyle())).x / 2;
1080     int widthText = width - widthBtn - MARGIN_BETWEEN;
1081     if ( widthText <= 0 )
1082     {
1083         wxLogDebug(wxT("not enough space for wxSpinCtrl!"));
1084     }
1085 
1086     if ( !::MoveWindow(GetBuddyHwnd(), x, y, widthText, height, TRUE) )
1087     {
1088         wxLogLastError(wxT("MoveWindow(buddy)"));
1089     }
1090 
1091     x += widthText + MARGIN_BETWEEN;
1092     if ( !::MoveWindow(GetHwnd(), x, y, widthBtn, height, TRUE) )
1093     {
1094         wxLogLastError(wxT("MoveWindow"));
1095     }
1096 }
1097 
DoGetBestSize() const1098 wxSize wxTextCtrl::DoGetBestSize() const
1099 {
1100     int cx, cy;
1101     wxGetCharSize(GetBuddyHwnd(), &cx, &cy, GetFont());
1102 
1103     int wText = DEFAULT_ITEM_WIDTH;
1104 
1105     int hText = cy;
1106     if ( m_windowStyle & wxTE_MULTILINE )
1107     {
1108         hText *= wxMax(GetNumberOfLines(), 5);
1109     }
1110     //else: for single line control everything is ok
1111 
1112     // we have to add the adjustments for the control height only once, not
1113     // once per line, so do it after multiplication above
1114     hText += EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy) - cy;
1115 
1116     return wxSize(wText, hText);
1117 }
1118 
1119 // ----------------------------------------------------------------------------
1120 // standard handlers for standard edit menu events
1121 // ----------------------------------------------------------------------------
1122 
OnCut(wxCommandEvent & WXUNUSED (event))1123 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
1124 {
1125     Cut();
1126 }
1127 
OnCopy(wxCommandEvent & WXUNUSED (event))1128 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
1129 {
1130     Copy();
1131 }
1132 
OnPaste(wxCommandEvent & WXUNUSED (event))1133 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
1134 {
1135     Paste();
1136 }
1137 
OnUndo(wxCommandEvent & WXUNUSED (event))1138 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
1139 {
1140     Undo();
1141 }
1142 
OnRedo(wxCommandEvent & WXUNUSED (event))1143 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
1144 {
1145     Redo();
1146 }
1147 
OnDelete(wxCommandEvent & WXUNUSED (event))1148 void wxTextCtrl::OnDelete(wxCommandEvent& WXUNUSED(event))
1149 {
1150     long from, to;
1151     GetSelection(& from, & to);
1152     if (from != -1 && to != -1)
1153         Remove(from, to);
1154 }
1155 
OnSelectAll(wxCommandEvent & WXUNUSED (event))1156 void wxTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
1157 {
1158     SetSelection(-1, -1);
1159 }
1160 
OnUpdateCut(wxUpdateUIEvent & event)1161 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1162 {
1163     event.Enable( CanCut() );
1164 }
1165 
OnUpdateCopy(wxUpdateUIEvent & event)1166 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1167 {
1168     event.Enable( CanCopy() );
1169 }
1170 
OnUpdatePaste(wxUpdateUIEvent & event)1171 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1172 {
1173     event.Enable( CanPaste() );
1174 }
1175 
OnUpdateUndo(wxUpdateUIEvent & event)1176 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1177 {
1178     event.Enable( CanUndo() );
1179 }
1180 
OnUpdateRedo(wxUpdateUIEvent & event)1181 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1182 {
1183     event.Enable( CanRedo() );
1184 }
1185 
OnUpdateDelete(wxUpdateUIEvent & event)1186 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent& event)
1187 {
1188     long from, to;
1189     GetSelection(& from, & to);
1190     event.Enable(from != -1 && to != -1 && from != to && IsEditable()) ;
1191 }
1192 
OnUpdateSelectAll(wxUpdateUIEvent & event)1193 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
1194 {
1195     event.Enable(GetLastPosition() > 0);
1196 }
1197 
OnSetFocus(wxFocusEvent & WXUNUSED (event))1198 void wxTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
1199 {
1200     // be sure the caret remains invisible if the user had hidden it
1201     if ( !m_isNativeCaretShown )
1202     {
1203         ::HideCaret(GetBuddyHwnd());
1204     }
1205 }
1206 
1207 #endif // wxUSE_TEXTCTRL && __SMARTPHONE__ && __WXWINCE__
1208