1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textentry.cpp
3 // Purpose: wxTextEntry implementation for wxMSW
4 // Author: Vadim Zeitlin
7 // Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwindows.org>
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
27 #include "wx/arrstr.h"
28 #include "wx/string.h"
31 #if wxUSE_TEXTCTRL || wxUSE_COMBOBOX
33 #include "wx/textentry.h"
34 #include "wx/textcompleter.h"
35 #include "wx/dynlib.h"
37 #include "wx/msw/private.h"
40 #include "wx/msw/uxtheme.h"
43 #define GetEditHwnd() ((HWND)(GetEditHWND()))
45 // ----------------------------------------------------------------------------
46 // wxIEnumString implements IEnumString interface
47 // ----------------------------------------------------------------------------
49 // standard VC6 SDK (WINVER == 0x0400) does not know about IAutoComplete
50 #if wxUSE_OLE && (WINVER >= 0x0500)
51 #define HAS_AUTOCOMPLETE
54 #ifdef HAS_AUTOCOMPLETE
56 #include "wx/msw/ole/oleutils.h"
60 #if defined(__MINGW32__) || defined (__WATCOMC__) || defined(__CYGWIN__)
61 // needed for IID_IAutoComplete, IID_IAutoComplete2 and ACO_AUTOSUGGEST
65 #ifndef ACO_UPDOWNKEYDROPSLIST
66 #define ACO_UPDOWNKEYDROPSLIST 0x20
69 #ifndef SHACF_FILESYS_ONLY
70 #define SHACF_FILESYS_ONLY 0x00000010
73 DEFINE_GUID(CLSID_AutoComplete
,
74 0x00bb2763, 0x6a77, 0x11d0, 0xa5, 0x35, 0x00, 0xc0, 0x4f, 0xd7, 0xd0, 0x62);
76 class wxIEnumString
: public IEnumString
84 wxIEnumString(const wxIEnumString
& other
)
85 : m_strings(other
.m_strings
),
86 m_index(other
.m_index
)
90 DECLARE_IUNKNOWN_METHODS
;
92 virtual HRESULT STDMETHODCALLTYPE
Next(ULONG celt
,
96 if ( !rgelt
|| (!pceltFetched
&& celt
> 1) )
99 ULONG pceltFetchedDummy
;
101 pceltFetched
= &pceltFetchedDummy
;
105 for ( const unsigned count
= m_strings
.size(); celt
--; ++m_index
)
107 if ( m_index
== count
)
110 const wxWX2WCbuf wcbuf
= m_strings
[m_index
].wc_str();
111 const size_t size
= (wcslen(wcbuf
) + 1)*sizeof(wchar_t);
112 void *olestr
= CoTaskMemAlloc(size
);
114 return E_OUTOFMEMORY
;
116 memcpy(olestr
, wcbuf
, size
);
118 *rgelt
++ = static_cast<LPOLESTR
>(olestr
);
126 virtual HRESULT STDMETHODCALLTYPE
Skip(ULONG celt
)
129 if ( m_index
> m_strings
.size() )
131 m_index
= m_strings
.size();
138 virtual HRESULT STDMETHODCALLTYPE
Reset()
145 virtual HRESULT STDMETHODCALLTYPE
Clone(IEnumString
**ppEnum
)
150 wxIEnumString
*e
= new wxIEnumString(*this);
159 // dtor doesn't have to be virtual as we're only ever deleted from our own
160 // Release() and are not meant to be derived form anyhow, but making it
161 // virtual silences gcc warnings; making it private makes it impossible to
162 // (mistakenly) delete us directly instead of calling Release()
163 virtual ~wxIEnumString() { }
166 wxArrayString m_strings
;
169 friend class wxTextAutoCompleteData
;
171 wxDECLARE_NO_ASSIGN_CLASS(wxIEnumString
);
174 BEGIN_IID_TABLE(wxIEnumString
)
179 IMPLEMENT_IUNKNOWN_METHODS(wxIEnumString
)
182 // This class gathers the auto-complete-related we use. It is allocated on
183 // demand by wxTextEntry when AutoComplete() is called.
184 class wxTextAutoCompleteData wxBIND_OR_CONNECT_HACK_ONLY_BASE_CLASS
187 // The constructor associates us with the given text entry.
188 wxTextAutoCompleteData(wxTextEntry
*entry
)
190 m_win(entry
->GetEditableWindow())
192 m_autoComplete
= NULL
;
193 m_autoCompleteDropDown
= NULL
;
194 m_enumStrings
= NULL
;
195 m_customCompleter
= NULL
;
197 m_connectedCharEvent
= false;
199 // Create an object exposing IAutoComplete interface which we'll later
200 // use to get IAutoComplete2 as the latter can't be created directly,
202 HRESULT hr
= CoCreateInstance
206 CLSCTX_INPROC_SERVER
,
208 reinterpret_cast<void **>(&m_autoComplete
)
212 wxLogApiError(wxT("CoCreateInstance(CLSID_AutoComplete)"), hr
);
216 // Create a string enumerator and initialize the completer with it.
217 m_enumStrings
= new wxIEnumString
;
218 m_enumStrings
->AddRef();
219 hr
= m_autoComplete
->Init(m_entry
->GetEditHWND(), m_enumStrings
,
223 wxLogApiError(wxT("IAutoComplete::Init"), hr
);
225 m_enumStrings
->Release();
226 m_enumStrings
= NULL
;
231 // As explained in DoRefresh(), we need to call IAutoCompleteDropDown::
232 // ResetEnumerator() if we want to be able to change the completions on
233 // the fly. In principle we could live without it, i.e. return true
234 // from IsOk() even if this QueryInterface() fails, but it doesn't look
235 // like this is ever going to have in practice anyhow as the shell-
236 // provided IAutoComplete always implements IAutoCompleteDropDown too.
237 hr
= m_autoComplete
->QueryInterface
239 IID_IAutoCompleteDropDown
,
240 reinterpret_cast<void **>(&m_autoCompleteDropDown
)
244 wxLogApiError(wxT("IAutoComplete::QI(IAutoCompleteDropDown)"), hr
);
248 // Finally set the completion options using IAutoComplete2.
249 IAutoComplete2
*pAutoComplete2
= NULL
;
250 hr
= m_autoComplete
->QueryInterface
253 reinterpret_cast<void **>(&pAutoComplete2
)
257 pAutoComplete2
->SetOptions(ACO_AUTOSUGGEST
|
259 ACO_UPDOWNKEYDROPSLIST
);
260 pAutoComplete2
->Release();
264 ~wxTextAutoCompleteData()
266 delete m_customCompleter
;
269 m_enumStrings
->Release();
270 if ( m_autoCompleteDropDown
)
271 m_autoCompleteDropDown
->Release();
272 if ( m_autoComplete
)
273 m_autoComplete
->Release();
276 // Must be called after creating this object to verify if initializing it
280 return m_autoComplete
&& m_autoCompleteDropDown
&& m_enumStrings
;
283 void ChangeStrings(const wxArrayString
& strings
)
285 m_enumStrings
->m_strings
= strings
;
290 // Takes ownership of the pointer if it is non-NULL.
291 bool ChangeCustomCompleter(wxTextCompleter
*completer
)
293 delete m_customCompleter
;
294 m_customCompleter
= completer
;
296 if ( m_customCompleter
)
298 // We postpone connecting to this event until we really need to do
299 // it (however we don't disconnect from it when we don't need it
300 // any more because we don't have wxUNBIND_OR_DISCONNECT_HACK...).
301 if ( !m_connectedCharEvent
)
303 m_connectedCharEvent
= true;
305 // Use the special wxEVT_AFTER_CHAR and not the usual
306 // wxEVT_CHAR here because we need to have the updated value of
307 // the text control in this handler in order to provide
308 // completions for the correct prefix and unfortunately we
309 // don't have any way to let DefWindowProc() run from our
310 // wxEVT_CHAR handler (as we must also let the other handlers
311 // defined at wx level run first).
313 // Notice that we can't use wxEVT_COMMAND_TEXT_UPDATED here
314 // neither as, due to our use of ACO_AUTOAPPEND, we get
315 // EN_CHANGE notifications from the control every time
316 // IAutoComplete auto-appends something to it.
317 wxBIND_OR_CONNECT_HACK(m_win
, wxEVT_AFTER_CHAR
,
319 wxTextAutoCompleteData::OnAfterChar
,
323 UpdateStringsFromCustomCompleter();
329 void DisableCompletion()
331 // We currently simply reset the list of possible strings as this seems
332 // to effectively disable auto-completion just fine. We could (and
333 // probably should) use IAutoComplete::Enable(FALSE) for this too but
334 // then we'd need to call Enable(TRUE) to turn it on back again later.
336 m_enumStrings
->m_strings
.clear();
337 m_enumStrings
->Reset();
339 ChangeCustomCompleter(NULL
);
343 // Must be called after changing wxIEnumString::m_strings to really make
344 // the changes stick.
347 m_enumStrings
->Reset();
349 // This is completely and utterly not documented and in fact the
350 // current MSDN seems to try to discourage us from using it by saying
351 // that "there is no reason to use this method unless the drop-down
352 // list is currently visible" but actually we absolutely must call it
353 // to force the auto-completer (and not just its drop-down!) to refresh
354 // the list of completions which could have changed now. Without this
355 // call the new choices returned by GetCompletions() that hadn't been
356 // returned by it before are simply silently ignored.
357 m_autoCompleteDropDown
->ResetEnumerator();
360 // Update the strings returned by our string enumerator to correspond to
361 // the currently valid choices according to the custom completer.
362 void UpdateStringsFromCustomCompleter()
364 // As we use ACO_AUTOAPPEND, the selected part of the text is usually
365 // the one appended by us so don't consider it as part of the
366 // user-entered prefix.
368 m_entry
->GetSelection(&from
, &to
);
371 from
= m_entry
->GetLastPosition(); // Take all if no selection.
373 const wxString prefix
= m_entry
->GetRange(0, from
);
375 // For efficiency we access m_strings directly instead of creating
376 // another wxArrayString, normally this should save us an unnecessary
377 // memory allocation on the subsequent calls.
378 m_enumStrings
->m_strings
.clear();
379 m_customCompleter
->GetCompletions(prefix
, m_enumStrings
->m_strings
);
384 void OnAfterChar(wxKeyEvent
& event
)
386 // Notice that we must not refresh the completions when the user
387 // presses Backspace as this would result in adding back the just
388 // erased character(s) because of ACO_AUTOAPPEND option we use.
389 if ( m_customCompleter
&& event
.GetKeyCode() != WXK_BACK
)
390 UpdateStringsFromCustomCompleter();
396 // The text entry we're associated with.
397 wxTextEntry
* const m_entry
;
399 // The window of this text entry.
400 wxWindow
* const m_win
;
402 // The auto-completer object itself.
403 IAutoComplete
*m_autoComplete
;
405 // Its IAutoCompleteDropDown interface needed for ResetEnumerator() call.
406 IAutoCompleteDropDown
*m_autoCompleteDropDown
;
408 // Enumerator for strings currently used for auto-completion.
409 wxIEnumString
*m_enumStrings
;
411 // Custom completer or NULL if none.
412 wxTextCompleter
*m_customCompleter
;
414 // Initially false, set to true after connecting OnTextChanged() handler.
415 bool m_connectedCharEvent
;
418 wxDECLARE_NO_COPY_CLASS(wxTextAutoCompleteData
);
421 #endif // HAS_AUTOCOMPLETE
423 // ============================================================================
424 // wxTextEntry implementation
425 // ============================================================================
427 // ----------------------------------------------------------------------------
428 // initialization and destruction
429 // ----------------------------------------------------------------------------
431 wxTextEntry::wxTextEntry()
433 #ifdef HAS_AUTOCOMPLETE
434 m_autoCompleteData
= NULL
;
435 #endif // HAS_AUTOCOMPLETE
438 wxTextEntry::~wxTextEntry()
440 #ifdef HAS_AUTOCOMPLETE
441 delete m_autoCompleteData
;
442 #endif // HAS_AUTOCOMPLETE
445 // ----------------------------------------------------------------------------
446 // operations on text
447 // ----------------------------------------------------------------------------
449 void wxTextEntry::WriteText(const wxString
& text
)
451 ::SendMessage(GetEditHwnd(), EM_REPLACESEL
, 0, (LPARAM
)text
.wx_str());
454 wxString
wxTextEntry::DoGetValue() const
456 return wxGetWindowText(GetEditHWND());
459 void wxTextEntry::Remove(long from
, long to
)
461 DoSetSelection(from
, to
, SetSel_NoScroll
);
462 WriteText(wxString());
465 // ----------------------------------------------------------------------------
466 // clipboard operations
467 // ----------------------------------------------------------------------------
469 void wxTextEntry::Copy()
471 ::SendMessage(GetEditHwnd(), WM_COPY
, 0, 0);
474 void wxTextEntry::Cut()
476 ::SendMessage(GetEditHwnd(), WM_CUT
, 0, 0);
479 void wxTextEntry::Paste()
481 ::SendMessage(GetEditHwnd(), WM_PASTE
, 0, 0);
484 // ----------------------------------------------------------------------------
486 // ----------------------------------------------------------------------------
488 void wxTextEntry::Undo()
490 ::SendMessage(GetEditHwnd(), EM_UNDO
, 0, 0);
493 void wxTextEntry::Redo()
495 // same as Undo, since Undo undoes the undo
500 bool wxTextEntry::CanUndo() const
502 return ::SendMessage(GetEditHwnd(), EM_CANUNDO
, 0, 0) != 0;
505 bool wxTextEntry::CanRedo() const
507 // see comment in Redo()
511 // ----------------------------------------------------------------------------
512 // insertion point and selection
513 // ----------------------------------------------------------------------------
515 void wxTextEntry::SetInsertionPoint(long pos
)
517 // calling DoSetSelection(-1, -1) would select everything which is not what
520 pos
= GetLastPosition();
522 // be careful to call DoSetSelection() which is overridden in wxTextCtrl
523 // and not just SetSelection() here
524 DoSetSelection(pos
, pos
);
527 long wxTextEntry::GetInsertionPoint() const
530 GetSelection(&from
, NULL
);
534 long wxTextEntry::GetLastPosition() const
536 return ::SendMessage(GetEditHwnd(), EM_LINELENGTH
, 0, 0);
539 void wxTextEntry::DoSetSelection(long from
, long to
, int WXUNUSED(flags
))
541 // if from and to are both -1, it means (in wxWidgets) that all text should
542 // be selected, translate this into Windows convention
543 if ( (from
== -1) && (to
== -1) )
548 ::SendMessage(GetEditHwnd(), EM_SETSEL
, from
, to
);
551 void wxTextEntry::GetSelection(long *from
, long *to
) const
553 DWORD dwStart
, dwEnd
;
554 ::SendMessage(GetEditHwnd(), EM_GETSEL
, (WPARAM
)&dwStart
, (LPARAM
)&dwEnd
);
562 // ----------------------------------------------------------------------------
564 // ----------------------------------------------------------------------------
568 #ifdef HAS_AUTOCOMPLETE
570 bool wxTextEntry::DoAutoCompleteFileNames()
572 typedef HRESULT (WINAPI
*SHAutoComplete_t
)(HWND
, DWORD
);
573 static SHAutoComplete_t s_pfnSHAutoComplete
= (SHAutoComplete_t
)-1;
574 static wxDynamicLibrary s_dllShlwapi
;
575 if ( s_pfnSHAutoComplete
== (SHAutoComplete_t
)-1 )
577 if ( !s_dllShlwapi
.Load(wxT("shlwapi.dll"), wxDL_VERBATIM
| wxDL_QUIET
) )
579 s_pfnSHAutoComplete
= NULL
;
583 wxDL_INIT_FUNC(s_pfn
, SHAutoComplete
, s_dllShlwapi
);
587 if ( !s_pfnSHAutoComplete
)
590 HRESULT hr
= (*s_pfnSHAutoComplete
)(GetEditHwnd(), SHACF_FILESYS_ONLY
);
593 wxLogApiError(wxT("SHAutoComplete()"), hr
);
598 // Disable the other kinds of completion now that we use the built-in file
600 if ( m_autoCompleteData
)
601 m_autoCompleteData
->DisableCompletion();
606 wxTextAutoCompleteData
*wxTextEntry::GetOrCreateCompleter()
608 if ( !m_autoCompleteData
)
610 wxTextAutoCompleteData
* const ac
= new wxTextAutoCompleteData(this);
612 m_autoCompleteData
= ac
;
617 return m_autoCompleteData
;
620 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
622 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
626 ac
->ChangeStrings(choices
);
631 bool wxTextEntry::DoAutoCompleteCustom(wxTextCompleter
*completer
)
633 // First deal with the case when we just want to disable auto-completion.
636 if ( m_autoCompleteData
)
637 m_autoCompleteData
->DisableCompletion();
638 //else: Nothing to do, we hadn't used auto-completion even before.
640 else // Have a valid completer.
642 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
645 // Delete the custom completer for consistency with the case when
646 // we succeed to avoid memory leaks in user code.
651 // This gives ownership of the custom completer to m_autoCompleteData.
652 if ( !ac
->ChangeCustomCompleter(completer
) )
659 #else // !HAS_AUTOCOMPLETE
661 // We still need to define stubs as we declared these overrides in the header.
663 bool wxTextEntry::DoAutoCompleteFileNames()
665 return wxTextEntryBase::DoAutoCompleteFileNames();
668 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
670 return wxTextEntryBase::DoAutoCompleteStrings(choices
);
673 #endif // HAS_AUTOCOMPLETE/!HAS_AUTOCOMPLETE
677 // ----------------------------------------------------------------------------
679 // ----------------------------------------------------------------------------
681 bool wxTextEntry::IsEditable() const
683 return !(::GetWindowLong(GetEditHwnd(), GWL_STYLE
) & ES_READONLY
);
686 void wxTextEntry::SetEditable(bool editable
)
688 ::SendMessage(GetEditHwnd(), EM_SETREADONLY
, !editable
, 0);
691 // ----------------------------------------------------------------------------
693 // ----------------------------------------------------------------------------
695 void wxTextEntry::SetMaxLength(unsigned long len
)
699 // this will set it to a platform-dependent maximum (much more
700 // than 64Kb under NT)
704 ::SendMessage(GetEditHwnd(), EM_LIMITTEXT
, len
, 0);
707 // ----------------------------------------------------------------------------
709 // ----------------------------------------------------------------------------
713 #ifndef EM_SETCUEBANNER
714 #define EM_SETCUEBANNER 0x1501
715 #define EM_GETCUEBANNER 0x1502
718 bool wxTextEntry::SetHint(const wxString
& hint
)
720 if ( wxUxThemeEngine::GetIfActive() )
722 // notice that this message always works with Unicode strings
724 // we always use TRUE for wParam to show the hint even when the window
725 // has focus, otherwise there would be no way to show the hint for the
726 // initially focused window
727 if ( ::SendMessage(GetEditHwnd(), EM_SETCUEBANNER
,
728 TRUE
, (LPARAM
)(const wchar_t *)hint
.wc_str()) )
732 return wxTextEntryBase::SetHint(hint
);
735 wxString
wxTextEntry::GetHint() const
737 if ( wxUxThemeEngine::GetIfActive() )
740 if ( ::SendMessage(GetEditHwnd(), EM_GETCUEBANNER
,
741 (WPARAM
)buf
, WXSIZEOF(buf
)) )
742 return wxString(buf
);
745 return wxTextEntryBase::GetHint();
749 #endif // wxUSE_UXTHEME
751 // ----------------------------------------------------------------------------
753 // ----------------------------------------------------------------------------
755 bool wxTextEntry::DoSetMargins(const wxPoint
& margins
)
757 #if !defined(__WXWINCE__)
760 if ( margins
.x
!= -1 )
763 ::SendMessage(GetEditHwnd(), EM_SETMARGINS
,
764 EC_LEFTMARGIN
, MAKELONG(margins
.x
, 0));
767 if ( margins
.y
!= -1 )
778 wxPoint
wxTextEntry::DoGetMargins() const
780 #if !defined(__WXWINCE__)
781 LRESULT lResult
= ::SendMessage(GetEditHwnd(), EM_GETMARGINS
,
783 int left
= LOWORD(lResult
);
785 return wxPoint(left
, top
);
787 return wxPoint(-1, -1);
791 #endif // wxUSE_TEXTCTRL || wxUSE_COMBOBOX