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 // Classes used by auto-completion implementation.
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);
79 // Small helper class which can be used to ensure thread safety even when
80 // wxUSE_THREADS==0 (and hence wxCriticalSection does nothing).
84 CSLock(CRITICAL_SECTION
& cs
) : m_cs(&cs
)
86 ::EnterCriticalSection(m_cs
);
91 ::LeaveCriticalSection(m_cs
);
95 CRITICAL_SECTION
* const m_cs
;
97 wxDECLARE_NO_COPY_CLASS(CSLock
);
100 } // anonymity namespace
102 // Implementation of string enumerator used by wxTextAutoCompleteData. This
103 // class simply iterates over its strings except that it also can be told to
104 // update them from the custom completer if one is used.
106 // Notice that Next() method of this class is called by IAutoComplete
107 // background thread and so we must care about thread safety here.
108 class wxIEnumString
: public IEnumString
118 wxIEnumString(const wxIEnumString
& other
)
119 : m_strings(other
.m_strings
),
120 m_index(other
.m_index
)
125 void ChangeStrings(const wxArrayString
& strings
)
127 CSLock
lock(m_csStrings
);
133 void UpdateStringsFromCompleter(wxTextCompleter
*completer
,
134 const wxString
& prefix
)
136 CSLock
lock(m_csUpdate
);
138 // We simply store the pointer here and will really update during the
139 // next call to our Next() method as we want to call GetCompletions()
140 // from the worker thread to prevent the main UI thread from blocking
141 // while the completions are generated.
142 m_completer
= completer
;
146 virtual HRESULT STDMETHODCALLTYPE
Next(ULONG celt
,
150 if ( !rgelt
|| (!pceltFetched
&& celt
> 1) )
153 ULONG pceltFetchedDummy
;
155 pceltFetched
= &pceltFetchedDummy
;
159 CSLock
lock(m_csStrings
);
163 for ( const unsigned count
= m_strings
.size(); celt
--; ++m_index
)
165 if ( m_index
== count
)
168 const wxWX2WCbuf wcbuf
= m_strings
[m_index
].wc_str();
169 const size_t size
= (wcslen(wcbuf
) + 1)*sizeof(wchar_t);
170 void *olestr
= CoTaskMemAlloc(size
);
172 return E_OUTOFMEMORY
;
174 memcpy(olestr
, wcbuf
, size
);
176 *rgelt
++ = static_cast<LPOLESTR
>(olestr
);
184 virtual HRESULT STDMETHODCALLTYPE
Skip(ULONG celt
)
186 CSLock
lock(m_csStrings
);
189 if ( m_index
> m_strings
.size() )
191 m_index
= m_strings
.size();
198 virtual HRESULT STDMETHODCALLTYPE
Reset()
201 CSLock
lock(m_csUpdate
);
205 // We will update the string from completer soon (or maybe are
206 // already in process of doing it) so don't do anything now, it
207 // is useless at best and could also result in a deadlock if
208 // m_csStrings is already locked by Next().
213 CSLock
lock(m_csStrings
);
220 virtual HRESULT STDMETHODCALLTYPE
Clone(IEnumString
**ppEnum
)
225 CSLock
lock(m_csStrings
);
227 wxIEnumString
*e
= new wxIEnumString(*this);
235 DECLARE_IUNKNOWN_METHODS
;
238 // dtor doesn't have to be virtual as we're only ever deleted from our own
239 // Release() and are not meant to be derived form anyhow, but making it
240 // virtual silences gcc warnings; making it private makes it impossible to
241 // (mistakenly) delete us directly instead of calling Release()
242 virtual ~wxIEnumString()
244 ::DeleteCriticalSection(&m_csStrings
);
245 ::DeleteCriticalSection(&m_csUpdate
);
248 // Common part of all ctors.
251 ::InitializeCriticalSection(&m_csUpdate
);
252 ::InitializeCriticalSection(&m_csStrings
);
257 void DoUpdateIfNeeded()
259 wxTextCompleter
*completer
;
262 CSLock
lock(m_csUpdate
);
264 completer
= m_completer
;
269 } // Unlock m_csUpdate to allow the main thread to call our
270 // UpdateStringsFromCompleter() without blocking while we are
271 // generating completions.
273 // Notice that m_csStrings is locked by our caller already so no need
274 // to enter it again.
277 completer
->GetCompletions(prefix
, m_strings
);
280 CSLock
lock(m_csUpdate
);
282 if ( m_completer
== completer
&& m_prefix
== prefix
)
284 // There were no calls to UpdateStringsFromCompleter() while we
285 // generated the completions, so our completions are still
290 //else: Our completions are already out of date, regenerate them
296 // Critical section protecting m_strings and m_index.
297 CRITICAL_SECTION m_csStrings
;
299 // The strings we iterate over and the current iteration index.
300 wxArrayString m_strings
;
303 // This one protects just m_completer, it is different from m_csStrings
304 // because the main thread should be able to update our completer prefix
305 // without blocking (as this would freeze the UI) even while we're inside a
306 // possibly long process of updating m_strings.
307 CRITICAL_SECTION m_csUpdate
;
309 // If completer pointer is non-NULL, we must use it by calling its
310 // GetCompletions() method with the specified prefix to update the list of
311 // strings we iterate over when our Next() is called the next time.
312 wxTextCompleter
*m_completer
;
316 wxDECLARE_NO_ASSIGN_CLASS(wxIEnumString
);
319 BEGIN_IID_TABLE(wxIEnumString
)
324 IMPLEMENT_IUNKNOWN_METHODS(wxIEnumString
)
327 // This class gathers the auto-complete-related we use. It is allocated on
328 // demand by wxTextEntry when AutoComplete() is called.
329 class wxTextAutoCompleteData wxBIND_OR_CONNECT_HACK_ONLY_BASE_CLASS
332 // The constructor associates us with the given text entry.
333 wxTextAutoCompleteData(wxTextEntry
*entry
)
335 m_win(entry
->GetEditableWindow())
337 m_autoComplete
= NULL
;
338 m_autoCompleteDropDown
= NULL
;
339 m_enumStrings
= NULL
;
340 m_customCompleter
= NULL
;
342 m_connectedCharEvent
= false;
344 // Create an object exposing IAutoComplete interface which we'll later
345 // use to get IAutoComplete2 as the latter can't be created directly,
347 HRESULT hr
= CoCreateInstance
351 CLSCTX_INPROC_SERVER
,
353 reinterpret_cast<void **>(&m_autoComplete
)
357 wxLogApiError(wxT("CoCreateInstance(CLSID_AutoComplete)"), hr
);
361 // Create a string enumerator and initialize the completer with it.
362 m_enumStrings
= new wxIEnumString
;
363 m_enumStrings
->AddRef();
364 hr
= m_autoComplete
->Init(m_entry
->GetEditHWND(), m_enumStrings
,
368 wxLogApiError(wxT("IAutoComplete::Init"), hr
);
370 m_enumStrings
->Release();
371 m_enumStrings
= NULL
;
376 // As explained in DoRefresh(), we need to call IAutoCompleteDropDown::
377 // ResetEnumerator() if we want to be able to change the completions on
378 // the fly. In principle we could live without it, i.e. return true
379 // from IsOk() even if this QueryInterface() fails, but it doesn't look
380 // like this is ever going to have in practice anyhow as the shell-
381 // provided IAutoComplete always implements IAutoCompleteDropDown too.
382 hr
= m_autoComplete
->QueryInterface
384 IID_IAutoCompleteDropDown
,
385 reinterpret_cast<void **>(&m_autoCompleteDropDown
)
389 wxLogApiError(wxT("IAutoComplete::QI(IAutoCompleteDropDown)"), hr
);
393 // Finally set the completion options using IAutoComplete2.
394 IAutoComplete2
*pAutoComplete2
= NULL
;
395 hr
= m_autoComplete
->QueryInterface
398 reinterpret_cast<void **>(&pAutoComplete2
)
402 pAutoComplete2
->SetOptions(ACO_AUTOSUGGEST
|
404 ACO_UPDOWNKEYDROPSLIST
);
405 pAutoComplete2
->Release();
409 ~wxTextAutoCompleteData()
411 delete m_customCompleter
;
414 m_enumStrings
->Release();
415 if ( m_autoCompleteDropDown
)
416 m_autoCompleteDropDown
->Release();
417 if ( m_autoComplete
)
418 m_autoComplete
->Release();
421 // Must be called after creating this object to verify if initializing it
425 return m_autoComplete
&& m_autoCompleteDropDown
&& m_enumStrings
;
428 void ChangeStrings(const wxArrayString
& strings
)
430 m_enumStrings
->ChangeStrings(strings
);
435 // Takes ownership of the pointer if it is non-NULL.
436 bool ChangeCustomCompleter(wxTextCompleter
*completer
)
438 delete m_customCompleter
;
439 m_customCompleter
= completer
;
441 if ( m_customCompleter
)
443 // We postpone connecting to this event until we really need to do
444 // it (however we don't disconnect from it when we don't need it
445 // any more because we don't have wxUNBIND_OR_DISCONNECT_HACK...).
446 if ( !m_connectedCharEvent
)
448 m_connectedCharEvent
= true;
450 // Use the special wxEVT_AFTER_CHAR and not the usual
451 // wxEVT_CHAR here because we need to have the updated value of
452 // the text control in this handler in order to provide
453 // completions for the correct prefix and unfortunately we
454 // don't have any way to let DefWindowProc() run from our
455 // wxEVT_CHAR handler (as we must also let the other handlers
456 // defined at wx level run first).
458 // Notice that we can't use wxEVT_COMMAND_TEXT_UPDATED here
459 // neither as, due to our use of ACO_AUTOAPPEND, we get
460 // EN_CHANGE notifications from the control every time
461 // IAutoComplete auto-appends something to it.
462 wxBIND_OR_CONNECT_HACK(m_win
, wxEVT_AFTER_CHAR
,
464 wxTextAutoCompleteData::OnAfterChar
,
468 UpdateStringsFromCustomCompleter();
474 void DisableCompletion()
476 // We currently simply reset the list of possible strings as this seems
477 // to effectively disable auto-completion just fine. We could (and
478 // probably should) use IAutoComplete::Enable(FALSE) for this too but
479 // then we'd need to call Enable(TRUE) to turn it on back again later.
481 m_enumStrings
->ChangeStrings(wxArrayString());
483 ChangeCustomCompleter(NULL
);
487 // Must be called after changing wxIEnumString::m_strings to really make
488 // the changes stick.
491 m_enumStrings
->Reset();
493 // This is completely and utterly not documented and in fact the
494 // current MSDN seems to try to discourage us from using it by saying
495 // that "there is no reason to use this method unless the drop-down
496 // list is currently visible" but actually we absolutely must call it
497 // to force the auto-completer (and not just its drop-down!) to refresh
498 // the list of completions which could have changed now. Without this
499 // call the new choices returned by GetCompletions() that hadn't been
500 // returned by it before are simply silently ignored.
501 m_autoCompleteDropDown
->ResetEnumerator();
504 // Update the strings returned by our string enumerator to correspond to
505 // the currently valid choices according to the custom completer.
506 void UpdateStringsFromCustomCompleter()
508 // As we use ACO_AUTOAPPEND, the selected part of the text is usually
509 // the one appended by us so don't consider it as part of the
510 // user-entered prefix.
512 m_entry
->GetSelection(&from
, &to
);
515 from
= m_entry
->GetLastPosition(); // Take all if no selection.
517 const wxString prefix
= m_entry
->GetRange(0, from
);
519 m_enumStrings
->UpdateStringsFromCompleter(m_customCompleter
, prefix
);
524 void OnAfterChar(wxKeyEvent
& event
)
526 // Notice that we must not refresh the completions when the user
527 // presses Backspace as this would result in adding back the just
528 // erased character(s) because of ACO_AUTOAPPEND option we use.
529 if ( m_customCompleter
&& event
.GetKeyCode() != WXK_BACK
)
530 UpdateStringsFromCustomCompleter();
536 // The text entry we're associated with.
537 wxTextEntry
* const m_entry
;
539 // The window of this text entry.
540 wxWindow
* const m_win
;
542 // The auto-completer object itself.
543 IAutoComplete
*m_autoComplete
;
545 // Its IAutoCompleteDropDown interface needed for ResetEnumerator() call.
546 IAutoCompleteDropDown
*m_autoCompleteDropDown
;
548 // Enumerator for strings currently used for auto-completion.
549 wxIEnumString
*m_enumStrings
;
551 // Custom completer or NULL if none.
552 wxTextCompleter
*m_customCompleter
;
554 // Initially false, set to true after connecting OnTextChanged() handler.
555 bool m_connectedCharEvent
;
558 wxDECLARE_NO_COPY_CLASS(wxTextAutoCompleteData
);
561 #endif // HAS_AUTOCOMPLETE
563 // ============================================================================
564 // wxTextEntry implementation
565 // ============================================================================
567 // ----------------------------------------------------------------------------
568 // initialization and destruction
569 // ----------------------------------------------------------------------------
571 wxTextEntry::wxTextEntry()
573 #ifdef HAS_AUTOCOMPLETE
574 m_autoCompleteData
= NULL
;
575 #endif // HAS_AUTOCOMPLETE
578 wxTextEntry::~wxTextEntry()
580 #ifdef HAS_AUTOCOMPLETE
581 delete m_autoCompleteData
;
582 #endif // HAS_AUTOCOMPLETE
585 // ----------------------------------------------------------------------------
586 // operations on text
587 // ----------------------------------------------------------------------------
589 void wxTextEntry::WriteText(const wxString
& text
)
591 ::SendMessage(GetEditHwnd(), EM_REPLACESEL
, 0, (LPARAM
)text
.wx_str());
594 wxString
wxTextEntry::DoGetValue() const
596 return wxGetWindowText(GetEditHWND());
599 void wxTextEntry::Remove(long from
, long to
)
601 DoSetSelection(from
, to
, SetSel_NoScroll
);
602 WriteText(wxString());
605 // ----------------------------------------------------------------------------
606 // clipboard operations
607 // ----------------------------------------------------------------------------
609 void wxTextEntry::Copy()
611 ::SendMessage(GetEditHwnd(), WM_COPY
, 0, 0);
614 void wxTextEntry::Cut()
616 ::SendMessage(GetEditHwnd(), WM_CUT
, 0, 0);
619 void wxTextEntry::Paste()
621 ::SendMessage(GetEditHwnd(), WM_PASTE
, 0, 0);
624 // ----------------------------------------------------------------------------
626 // ----------------------------------------------------------------------------
628 void wxTextEntry::Undo()
630 ::SendMessage(GetEditHwnd(), EM_UNDO
, 0, 0);
633 void wxTextEntry::Redo()
635 // same as Undo, since Undo undoes the undo
640 bool wxTextEntry::CanUndo() const
642 return ::SendMessage(GetEditHwnd(), EM_CANUNDO
, 0, 0) != 0;
645 bool wxTextEntry::CanRedo() const
647 // see comment in Redo()
651 // ----------------------------------------------------------------------------
652 // insertion point and selection
653 // ----------------------------------------------------------------------------
655 void wxTextEntry::SetInsertionPoint(long pos
)
657 // calling DoSetSelection(-1, -1) would select everything which is not what
660 pos
= GetLastPosition();
662 // be careful to call DoSetSelection() which is overridden in wxTextCtrl
663 // and not just SetSelection() here
664 DoSetSelection(pos
, pos
);
667 long wxTextEntry::GetInsertionPoint() const
670 GetSelection(&from
, NULL
);
674 long wxTextEntry::GetLastPosition() const
676 return ::SendMessage(GetEditHwnd(), EM_LINELENGTH
, 0, 0);
679 void wxTextEntry::DoSetSelection(long from
, long to
, int WXUNUSED(flags
))
681 // if from and to are both -1, it means (in wxWidgets) that all text should
682 // be selected, translate this into Windows convention
683 if ( (from
== -1) && (to
== -1) )
688 ::SendMessage(GetEditHwnd(), EM_SETSEL
, from
, to
);
691 void wxTextEntry::GetSelection(long *from
, long *to
) const
693 DWORD dwStart
, dwEnd
;
694 ::SendMessage(GetEditHwnd(), EM_GETSEL
, (WPARAM
)&dwStart
, (LPARAM
)&dwEnd
);
702 // ----------------------------------------------------------------------------
704 // ----------------------------------------------------------------------------
708 #ifdef HAS_AUTOCOMPLETE
710 bool wxTextEntry::DoAutoCompleteFileNames()
712 typedef HRESULT (WINAPI
*SHAutoComplete_t
)(HWND
, DWORD
);
713 static SHAutoComplete_t s_pfnSHAutoComplete
= (SHAutoComplete_t
)-1;
714 static wxDynamicLibrary s_dllShlwapi
;
715 if ( s_pfnSHAutoComplete
== (SHAutoComplete_t
)-1 )
717 if ( !s_dllShlwapi
.Load(wxT("shlwapi.dll"), wxDL_VERBATIM
| wxDL_QUIET
) )
719 s_pfnSHAutoComplete
= NULL
;
723 wxDL_INIT_FUNC(s_pfn
, SHAutoComplete
, s_dllShlwapi
);
727 if ( !s_pfnSHAutoComplete
)
730 HRESULT hr
= (*s_pfnSHAutoComplete
)(GetEditHwnd(), SHACF_FILESYS_ONLY
);
733 wxLogApiError(wxT("SHAutoComplete()"), hr
);
738 // Disable the other kinds of completion now that we use the built-in file
740 if ( m_autoCompleteData
)
741 m_autoCompleteData
->DisableCompletion();
746 wxTextAutoCompleteData
*wxTextEntry::GetOrCreateCompleter()
748 if ( !m_autoCompleteData
)
750 wxTextAutoCompleteData
* const ac
= new wxTextAutoCompleteData(this);
752 m_autoCompleteData
= ac
;
757 return m_autoCompleteData
;
760 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
762 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
766 ac
->ChangeStrings(choices
);
771 bool wxTextEntry::DoAutoCompleteCustom(wxTextCompleter
*completer
)
773 // First deal with the case when we just want to disable auto-completion.
776 if ( m_autoCompleteData
)
777 m_autoCompleteData
->DisableCompletion();
778 //else: Nothing to do, we hadn't used auto-completion even before.
780 else // Have a valid completer.
782 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
785 // Delete the custom completer for consistency with the case when
786 // we succeed to avoid memory leaks in user code.
791 // This gives ownership of the custom completer to m_autoCompleteData.
792 if ( !ac
->ChangeCustomCompleter(completer
) )
799 #else // !HAS_AUTOCOMPLETE
801 // We still need to define stubs as we declared these overrides in the header.
803 bool wxTextEntry::DoAutoCompleteFileNames()
805 return wxTextEntryBase::DoAutoCompleteFileNames();
808 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
810 return wxTextEntryBase::DoAutoCompleteStrings(choices
);
813 #endif // HAS_AUTOCOMPLETE/!HAS_AUTOCOMPLETE
817 // ----------------------------------------------------------------------------
819 // ----------------------------------------------------------------------------
821 bool wxTextEntry::IsEditable() const
823 return !(::GetWindowLong(GetEditHwnd(), GWL_STYLE
) & ES_READONLY
);
826 void wxTextEntry::SetEditable(bool editable
)
828 ::SendMessage(GetEditHwnd(), EM_SETREADONLY
, !editable
, 0);
831 // ----------------------------------------------------------------------------
833 // ----------------------------------------------------------------------------
835 void wxTextEntry::SetMaxLength(unsigned long len
)
839 // this will set it to a platform-dependent maximum (much more
840 // than 64Kb under NT)
844 ::SendMessage(GetEditHwnd(), EM_LIMITTEXT
, len
, 0);
847 // ----------------------------------------------------------------------------
849 // ----------------------------------------------------------------------------
853 #ifndef EM_SETCUEBANNER
854 #define EM_SETCUEBANNER 0x1501
855 #define EM_GETCUEBANNER 0x1502
858 bool wxTextEntry::SetHint(const wxString
& hint
)
860 if ( wxUxThemeEngine::GetIfActive() )
862 // notice that this message always works with Unicode strings
864 // we always use TRUE for wParam to show the hint even when the window
865 // has focus, otherwise there would be no way to show the hint for the
866 // initially focused window
867 if ( ::SendMessage(GetEditHwnd(), EM_SETCUEBANNER
,
868 TRUE
, (LPARAM
)(const wchar_t *)hint
.wc_str()) )
872 return wxTextEntryBase::SetHint(hint
);
875 wxString
wxTextEntry::GetHint() const
877 if ( wxUxThemeEngine::GetIfActive() )
880 if ( ::SendMessage(GetEditHwnd(), EM_GETCUEBANNER
,
881 (WPARAM
)buf
, WXSIZEOF(buf
)) )
882 return wxString(buf
);
885 return wxTextEntryBase::GetHint();
889 #endif // wxUSE_UXTHEME
891 // ----------------------------------------------------------------------------
893 // ----------------------------------------------------------------------------
895 bool wxTextEntry::DoSetMargins(const wxPoint
& margins
)
897 #if !defined(__WXWINCE__)
900 if ( margins
.x
!= -1 )
903 ::SendMessage(GetEditHwnd(), EM_SETMARGINS
,
904 EC_LEFTMARGIN
, MAKELONG(margins
.x
, 0));
907 if ( margins
.y
!= -1 )
918 wxPoint
wxTextEntry::DoGetMargins() const
920 #if !defined(__WXWINCE__)
921 LRESULT lResult
= ::SendMessage(GetEditHwnd(), EM_GETMARGINS
,
923 int left
= LOWORD(lResult
);
925 return wxPoint(left
, top
);
927 return wxPoint(-1, -1);
931 #endif // wxUSE_TEXTCTRL || wxUSE_COMBOBOX