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 forwards to wxTextCompleter associated with it.
105 // Notice that Next() method of this class is called by IAutoComplete
106 // background thread and so we must care about thread safety here.
107 class wxIEnumString
: public IEnumString
115 void ChangeCompleter(wxTextCompleter
*completer
)
117 // Indicate to Next() that it should bail out as soon as possible.
119 CSLock
lock(m_csRestart
);
124 // Now try to enter this critical section to ensure that Next() doesn't
125 // use the old pointer any more before changing it (this is vital as
126 // the old pointer will be destroyed after we return).
127 CSLock
lock(m_csCompleter
);
129 m_completer
= completer
;
132 void UpdatePrefix(const wxString
& prefix
)
134 CSLock
lock(m_csRestart
);
136 // We simply store the prefix here and will really update during the
137 // next call to our Next() method as we want to call Start() from the
138 // worker thread to prevent the main UI thread from blocking while the
139 // completions are generated.
144 virtual HRESULT STDMETHODCALLTYPE
Next(ULONG celt
,
148 if ( !rgelt
|| (!pceltFetched
&& celt
> 1) )
151 ULONG pceltFetchedDummy
;
153 pceltFetched
= &pceltFetchedDummy
;
157 CSLock
lock(m_csCompleter
);
159 if ( !RestartIfNeeded() )
164 // Stop iterating if we need to update completions anyhow.
168 const wxString s
= m_completer
->GetNext();
172 const wxWX2WCbuf wcbuf
= s
.wc_str();
173 const size_t size
= (wcslen(wcbuf
) + 1)*sizeof(wchar_t);
174 void *olestr
= CoTaskMemAlloc(size
);
176 return E_OUTOFMEMORY
;
178 memcpy(olestr
, wcbuf
, size
);
180 *rgelt
++ = static_cast<LPOLESTR
>(olestr
);
188 virtual HRESULT STDMETHODCALLTYPE
Skip(ULONG celt
)
193 CSLock
lock(m_csCompleter
);
195 if ( !RestartIfNeeded() )
203 if ( m_completer
->GetNext().empty() )
210 virtual HRESULT STDMETHODCALLTYPE
Reset()
212 CSLock
lock(m_csRestart
);
219 virtual HRESULT STDMETHODCALLTYPE
Clone(IEnumString
**ppEnum
)
224 CSLock
lock(m_csCompleter
);
226 wxIEnumString
* const e
= new wxIEnumString
;
229 e
->ChangeCompleter(m_completer
);
236 DECLARE_IUNKNOWN_METHODS
;
239 // dtor doesn't have to be virtual as we're only ever deleted from our own
240 // Release() and are not meant to be derived form anyhow, but making it
241 // virtual silences gcc warnings; making it private makes it impossible to
242 // (mistakenly) delete us directly instead of calling Release()
243 virtual ~wxIEnumString()
245 ::DeleteCriticalSection(&m_csRestart
);
246 ::DeleteCriticalSection(&m_csCompleter
);
249 // Common part of all ctors.
252 ::InitializeCriticalSection(&m_csCompleter
);
253 ::InitializeCriticalSection(&m_csRestart
);
259 // Restart completions generation if needed. Should be only called from
260 // inside m_csCompleter.
262 // If false is returned, it means that there are no completions and that
263 // wxTextCompleter::GetNext() shouldn't be called at all.
264 bool RestartIfNeeded()
272 CSLock
lock(m_csRestart
);
278 } // Release m_csRestart before calling Start() to avoid blocking
279 // the main thread in UpdatePrefix() during its execution.
284 rc
= m_completer
->Start(prefix
);
291 // Critical section protecting m_completer itself. It must be entered when
292 // using the pointer to ensure that we don't continue using a dangling one
293 // after it is destroyed.
294 CRITICAL_SECTION m_csCompleter
;
296 // The completer we delegate to for the completions generation. It is never
297 // NULL after the initial ChangeCompleter() call.
298 wxTextCompleter
*m_completer
;
301 // Critical section m_prefix and m_restart. It should be only entered for
302 // short periods of time, i.e. we shouldn't call any wxTextCompleter
303 // methods from inside, to prevent the main thread from blocking on it in
305 CRITICAL_SECTION m_csRestart
;
307 // If m_restart is true, we need to call wxTextCompleter::Start() with the
308 // given prefix to restart generating the completions.
311 // Notice that we use LONG and not bool here to ensure that reading this
312 // value is atomic (32 bit reads are atomic operations under all Windows
313 // versions but reading bool isn't necessarily).
317 wxDECLARE_NO_COPY_CLASS(wxIEnumString
);
320 BEGIN_IID_TABLE(wxIEnumString
)
325 IMPLEMENT_IUNKNOWN_METHODS(wxIEnumString
)
328 // This class gathers the all auto-complete-related stuff we use. It is
329 // allocated on demand by wxTextEntry when AutoComplete() is called.
330 class wxTextAutoCompleteData wxBIND_OR_CONNECT_HACK_ONLY_BASE_CLASS
333 // The constructor associates us with the given text entry.
334 wxTextAutoCompleteData(wxTextEntry
*entry
)
336 m_win(entry
->GetEditableWindow())
338 m_autoComplete
= NULL
;
339 m_autoCompleteDropDown
= NULL
;
340 m_enumStrings
= NULL
;
342 m_fixedCompleter
= NULL
;
343 m_customCompleter
= NULL
;
345 m_connectedCharEvent
= false;
347 // Create an object exposing IAutoComplete interface which we'll later
348 // use to get IAutoComplete2 as the latter can't be created directly,
350 HRESULT hr
= CoCreateInstance
354 CLSCTX_INPROC_SERVER
,
356 reinterpret_cast<void **>(&m_autoComplete
)
360 wxLogApiError(wxT("CoCreateInstance(CLSID_AutoComplete)"), hr
);
364 // Create a string enumerator and initialize the completer with it.
365 m_enumStrings
= new wxIEnumString
;
366 m_enumStrings
->AddRef();
367 hr
= m_autoComplete
->Init(m_entry
->GetEditHWND(), m_enumStrings
,
371 wxLogApiError(wxT("IAutoComplete::Init"), hr
);
373 m_enumStrings
->Release();
374 m_enumStrings
= NULL
;
379 // As explained in DoRefresh(), we need to call IAutoCompleteDropDown::
380 // ResetEnumerator() if we want to be able to change the completions on
381 // the fly. In principle we could live without it, i.e. return true
382 // from IsOk() even if this QueryInterface() fails, but it doesn't look
383 // like this is ever going to have in practice anyhow as the shell-
384 // provided IAutoComplete always implements IAutoCompleteDropDown too.
385 hr
= m_autoComplete
->QueryInterface
387 IID_IAutoCompleteDropDown
,
388 reinterpret_cast<void **>(&m_autoCompleteDropDown
)
392 wxLogApiError(wxT("IAutoComplete::QI(IAutoCompleteDropDown)"), hr
);
396 // Finally set the completion options using IAutoComplete2.
397 IAutoComplete2
*pAutoComplete2
= NULL
;
398 hr
= m_autoComplete
->QueryInterface
401 reinterpret_cast<void **>(&pAutoComplete2
)
405 pAutoComplete2
->SetOptions(ACO_AUTOSUGGEST
|
407 ACO_UPDOWNKEYDROPSLIST
);
408 pAutoComplete2
->Release();
412 ~wxTextAutoCompleteData()
414 delete m_customCompleter
;
415 delete m_fixedCompleter
;
418 m_enumStrings
->Release();
419 if ( m_autoCompleteDropDown
)
420 m_autoCompleteDropDown
->Release();
421 if ( m_autoComplete
)
422 m_autoComplete
->Release();
425 // Must be called after creating this object to verify if initializing it
429 return m_autoComplete
&& m_autoCompleteDropDown
&& m_enumStrings
;
432 void ChangeStrings(const wxArrayString
& strings
)
434 if ( !m_fixedCompleter
)
435 m_fixedCompleter
= new wxTextCompleterFixed
;
437 m_fixedCompleter
->SetCompletions(strings
);
439 m_enumStrings
->ChangeCompleter(m_fixedCompleter
);
444 // Takes ownership of the pointer if it is non-NULL.
445 bool ChangeCustomCompleter(wxTextCompleter
*completer
)
447 // Ensure that the old completer is not used any more before deleting
449 m_enumStrings
->ChangeCompleter(completer
);
451 delete m_customCompleter
;
452 m_customCompleter
= completer
;
454 if ( m_customCompleter
)
456 // We postpone connecting to this event until we really need to do
457 // it (however we don't disconnect from it when we don't need it
458 // any more because we don't have wxUNBIND_OR_DISCONNECT_HACK...).
459 if ( !m_connectedCharEvent
)
461 m_connectedCharEvent
= true;
463 // Use the special wxEVT_AFTER_CHAR and not the usual
464 // wxEVT_CHAR here because we need to have the updated value of
465 // the text control in this handler in order to provide
466 // completions for the correct prefix and unfortunately we
467 // don't have any way to let DefWindowProc() run from our
468 // wxEVT_CHAR handler (as we must also let the other handlers
469 // defined at wx level run first).
471 // Notice that we can't use wxEVT_COMMAND_TEXT_UPDATED here
472 // neither as, due to our use of ACO_AUTOAPPEND, we get
473 // EN_CHANGE notifications from the control every time
474 // IAutoComplete auto-appends something to it.
475 wxBIND_OR_CONNECT_HACK(m_win
, wxEVT_AFTER_CHAR
,
477 wxTextAutoCompleteData::OnAfterChar
,
481 UpdateStringsFromCustomCompleter();
487 void DisableCompletion()
489 // We currently simply reset the list of possible strings as this seems
490 // to effectively disable auto-completion just fine. We could (and
491 // probably should) use IAutoComplete::Enable(FALSE) for this too but
492 // then we'd need to call Enable(TRUE) to turn it on back again later.
493 ChangeStrings(wxArrayString());
497 // Trivial wxTextCompleter implementation which always returns the same
498 // fixed array of completions.
499 class wxTextCompleterFixed
: public wxTextCompleterSimple
502 void SetCompletions(const wxArrayString
& strings
)
507 virtual void GetCompletions(const wxString
& WXUNUSED(prefix
),
514 wxArrayString m_strings
;
518 // Must be called after changing the values to be returned by wxIEnumString
519 // to really make the changes stick.
522 m_enumStrings
->Reset();
524 // This is completely and utterly not documented and in fact the
525 // current MSDN seems to try to discourage us from using it by saying
526 // that "there is no reason to use this method unless the drop-down
527 // list is currently visible" but actually we absolutely must call it
528 // to force the auto-completer (and not just its drop-down!) to refresh
529 // the list of completions which could have changed now. Without this
530 // call the new choices returned by GetCompletions() that hadn't been
531 // returned by it before are simply silently ignored.
532 m_autoCompleteDropDown
->ResetEnumerator();
535 // Update the strings returned by our string enumerator to correspond to
536 // the currently valid choices according to the custom completer.
537 void UpdateStringsFromCustomCompleter()
539 // As we use ACO_AUTOAPPEND, the selected part of the text is usually
540 // the one appended by us so don't consider it as part of the
541 // user-entered prefix.
543 m_entry
->GetSelection(&from
, &to
);
546 from
= m_entry
->GetLastPosition(); // Take all if no selection.
548 const wxString prefix
= m_entry
->GetRange(0, from
);
550 m_enumStrings
->UpdatePrefix(prefix
);
555 void OnAfterChar(wxKeyEvent
& event
)
557 // Notice that we must not refresh the completions when the user
558 // presses Backspace as this would result in adding back the just
559 // erased character(s) because of ACO_AUTOAPPEND option we use.
560 if ( m_customCompleter
&& event
.GetKeyCode() != WXK_BACK
)
561 UpdateStringsFromCustomCompleter();
567 // The text entry we're associated with.
568 wxTextEntry
* const m_entry
;
570 // The window of this text entry.
571 wxWindow
* const m_win
;
573 // The auto-completer object itself.
574 IAutoComplete
*m_autoComplete
;
576 // Its IAutoCompleteDropDown interface needed for ResetEnumerator() call.
577 IAutoCompleteDropDown
*m_autoCompleteDropDown
;
579 // Enumerator for strings currently used for auto-completion.
580 wxIEnumString
*m_enumStrings
;
582 // Fixed string completer or NULL if none.
583 wxTextCompleterFixed
*m_fixedCompleter
;
585 // Custom completer or NULL if none.
586 wxTextCompleter
*m_customCompleter
;
588 // Initially false, set to true after connecting OnTextChanged() handler.
589 bool m_connectedCharEvent
;
592 wxDECLARE_NO_COPY_CLASS(wxTextAutoCompleteData
);
595 #endif // HAS_AUTOCOMPLETE
597 // ============================================================================
598 // wxTextEntry implementation
599 // ============================================================================
601 // ----------------------------------------------------------------------------
602 // initialization and destruction
603 // ----------------------------------------------------------------------------
605 wxTextEntry::wxTextEntry()
607 #ifdef HAS_AUTOCOMPLETE
608 m_autoCompleteData
= NULL
;
609 #endif // HAS_AUTOCOMPLETE
612 wxTextEntry::~wxTextEntry()
614 #ifdef HAS_AUTOCOMPLETE
615 delete m_autoCompleteData
;
616 #endif // HAS_AUTOCOMPLETE
619 // ----------------------------------------------------------------------------
620 // operations on text
621 // ----------------------------------------------------------------------------
623 void wxTextEntry::WriteText(const wxString
& text
)
625 ::SendMessage(GetEditHwnd(), EM_REPLACESEL
, 0, (LPARAM
)text
.wx_str());
628 wxString
wxTextEntry::DoGetValue() const
630 return wxGetWindowText(GetEditHWND());
633 void wxTextEntry::Remove(long from
, long to
)
635 DoSetSelection(from
, to
, SetSel_NoScroll
);
636 WriteText(wxString());
639 // ----------------------------------------------------------------------------
640 // clipboard operations
641 // ----------------------------------------------------------------------------
643 void wxTextEntry::Copy()
645 ::SendMessage(GetEditHwnd(), WM_COPY
, 0, 0);
648 void wxTextEntry::Cut()
650 ::SendMessage(GetEditHwnd(), WM_CUT
, 0, 0);
653 void wxTextEntry::Paste()
655 ::SendMessage(GetEditHwnd(), WM_PASTE
, 0, 0);
658 // ----------------------------------------------------------------------------
660 // ----------------------------------------------------------------------------
662 void wxTextEntry::Undo()
664 ::SendMessage(GetEditHwnd(), EM_UNDO
, 0, 0);
667 void wxTextEntry::Redo()
669 // same as Undo, since Undo undoes the undo
674 bool wxTextEntry::CanUndo() const
676 return ::SendMessage(GetEditHwnd(), EM_CANUNDO
, 0, 0) != 0;
679 bool wxTextEntry::CanRedo() const
681 // see comment in Redo()
685 // ----------------------------------------------------------------------------
686 // insertion point and selection
687 // ----------------------------------------------------------------------------
689 void wxTextEntry::SetInsertionPoint(long pos
)
691 // calling DoSetSelection(-1, -1) would select everything which is not what
694 pos
= GetLastPosition();
696 // be careful to call DoSetSelection() which is overridden in wxTextCtrl
697 // and not just SetSelection() here
698 DoSetSelection(pos
, pos
);
701 long wxTextEntry::GetInsertionPoint() const
704 GetSelection(&from
, NULL
);
708 long wxTextEntry::GetLastPosition() const
710 return ::SendMessage(GetEditHwnd(), EM_LINELENGTH
, 0, 0);
713 void wxTextEntry::DoSetSelection(long from
, long to
, int WXUNUSED(flags
))
715 // if from and to are both -1, it means (in wxWidgets) that all text should
716 // be selected, translate this into Windows convention
717 if ( (from
== -1) && (to
== -1) )
722 ::SendMessage(GetEditHwnd(), EM_SETSEL
, from
, to
);
725 void wxTextEntry::GetSelection(long *from
, long *to
) const
727 DWORD dwStart
, dwEnd
;
728 ::SendMessage(GetEditHwnd(), EM_GETSEL
, (WPARAM
)&dwStart
, (LPARAM
)&dwEnd
);
736 // ----------------------------------------------------------------------------
738 // ----------------------------------------------------------------------------
742 #ifdef HAS_AUTOCOMPLETE
744 bool wxTextEntry::DoAutoCompleteFileNames()
746 typedef HRESULT (WINAPI
*SHAutoComplete_t
)(HWND
, DWORD
);
747 static SHAutoComplete_t s_pfnSHAutoComplete
= (SHAutoComplete_t
)-1;
748 static wxDynamicLibrary s_dllShlwapi
;
749 if ( s_pfnSHAutoComplete
== (SHAutoComplete_t
)-1 )
751 if ( !s_dllShlwapi
.Load(wxT("shlwapi.dll"), wxDL_VERBATIM
| wxDL_QUIET
) )
753 s_pfnSHAutoComplete
= NULL
;
757 wxDL_INIT_FUNC(s_pfn
, SHAutoComplete
, s_dllShlwapi
);
761 if ( !s_pfnSHAutoComplete
)
764 HRESULT hr
= (*s_pfnSHAutoComplete
)(GetEditHwnd(), SHACF_FILESYS_ONLY
);
767 wxLogApiError(wxT("SHAutoComplete()"), hr
);
772 // Disable the other kinds of completion now that we use the built-in file
774 if ( m_autoCompleteData
)
775 m_autoCompleteData
->DisableCompletion();
780 wxTextAutoCompleteData
*wxTextEntry::GetOrCreateCompleter()
782 if ( !m_autoCompleteData
)
784 wxTextAutoCompleteData
* const ac
= new wxTextAutoCompleteData(this);
786 m_autoCompleteData
= ac
;
791 return m_autoCompleteData
;
794 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
796 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
800 ac
->ChangeStrings(choices
);
805 bool wxTextEntry::DoAutoCompleteCustom(wxTextCompleter
*completer
)
807 // First deal with the case when we just want to disable auto-completion.
810 if ( m_autoCompleteData
)
811 m_autoCompleteData
->DisableCompletion();
812 //else: Nothing to do, we hadn't used auto-completion even before.
814 else // Have a valid completer.
816 wxTextAutoCompleteData
* const ac
= GetOrCreateCompleter();
819 // Delete the custom completer for consistency with the case when
820 // we succeed to avoid memory leaks in user code.
825 // This gives ownership of the custom completer to m_autoCompleteData.
826 if ( !ac
->ChangeCustomCompleter(completer
) )
833 #else // !HAS_AUTOCOMPLETE
835 // We still need to define stubs as we declared these overrides in the header.
837 bool wxTextEntry::DoAutoCompleteFileNames()
839 return wxTextEntryBase::DoAutoCompleteFileNames();
842 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString
& choices
)
844 return wxTextEntryBase::DoAutoCompleteStrings(choices
);
847 bool wxTextEntry::DoAutoCompleteCustom(wxTextCompleter
*completer
)
849 return wxTextCompleter::DoAutoCompleteCustom(completer
);
852 #endif // HAS_AUTOCOMPLETE/!HAS_AUTOCOMPLETE
856 // ----------------------------------------------------------------------------
858 // ----------------------------------------------------------------------------
860 bool wxTextEntry::IsEditable() const
862 return !(::GetWindowLong(GetEditHwnd(), GWL_STYLE
) & ES_READONLY
);
865 void wxTextEntry::SetEditable(bool editable
)
867 ::SendMessage(GetEditHwnd(), EM_SETREADONLY
, !editable
, 0);
870 // ----------------------------------------------------------------------------
872 // ----------------------------------------------------------------------------
874 void wxTextEntry::SetMaxLength(unsigned long len
)
878 // this will set it to a platform-dependent maximum (much more
879 // than 64Kb under NT)
883 ::SendMessage(GetEditHwnd(), EM_LIMITTEXT
, len
, 0);
886 // ----------------------------------------------------------------------------
888 // ----------------------------------------------------------------------------
892 #ifndef EM_SETCUEBANNER
893 #define EM_SETCUEBANNER 0x1501
894 #define EM_GETCUEBANNER 0x1502
897 bool wxTextEntry::SetHint(const wxString
& hint
)
899 if ( wxUxThemeEngine::GetIfActive() )
901 // notice that this message always works with Unicode strings
903 // we always use TRUE for wParam to show the hint even when the window
904 // has focus, otherwise there would be no way to show the hint for the
905 // initially focused window
906 if ( ::SendMessage(GetEditHwnd(), EM_SETCUEBANNER
,
907 TRUE
, (LPARAM
)(const wchar_t *)hint
.wc_str()) )
911 return wxTextEntryBase::SetHint(hint
);
914 wxString
wxTextEntry::GetHint() const
916 if ( wxUxThemeEngine::GetIfActive() )
919 if ( ::SendMessage(GetEditHwnd(), EM_GETCUEBANNER
,
920 (WPARAM
)buf
, WXSIZEOF(buf
)) )
921 return wxString(buf
);
924 return wxTextEntryBase::GetHint();
928 #endif // wxUSE_UXTHEME
930 // ----------------------------------------------------------------------------
932 // ----------------------------------------------------------------------------
934 bool wxTextEntry::DoSetMargins(const wxPoint
& margins
)
936 #if !defined(__WXWINCE__)
939 if ( margins
.x
!= -1 )
942 ::SendMessage(GetEditHwnd(), EM_SETMARGINS
,
943 EC_LEFTMARGIN
, MAKELONG(margins
.x
, 0));
946 if ( margins
.y
!= -1 )
957 wxPoint
wxTextEntry::DoGetMargins() const
959 #if !defined(__WXWINCE__)
960 LRESULT lResult
= ::SendMessage(GetEditHwnd(), EM_GETMARGINS
,
962 int left
= LOWORD(lResult
);
964 return wxPoint(left
, top
);
966 return wxPoint(-1, -1);
970 #endif // wxUSE_TEXTCTRL || wxUSE_COMBOBOX