]> git.saurik.com Git - wxWidgets.git/blob - src/msw/textentry.cpp
161035b59ff5131cc0fd40c019be685ad3fb3f20
[wxWidgets.git] / src / msw / textentry.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textentry.cpp
3 // Purpose: wxTextEntry implementation for wxMSW
4 // Author: Vadim Zeitlin
5 // Created: 2007-09-26
6 // RCS-ID: $Id$
7 // Copyright: (c) 2007 Vadim Zeitlin <vadim@wxwindows.org>
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 #ifndef WX_PRECOMP
27 #include "wx/arrstr.h"
28 #include "wx/string.h"
29 #endif // WX_PRECOMP
30
31 #if wxUSE_TEXTCTRL || wxUSE_COMBOBOX
32
33 #include "wx/textentry.h"
34 #include "wx/textcompleter.h"
35 #include "wx/dynlib.h"
36
37 #include "wx/msw/private.h"
38
39 #if wxUSE_UXTHEME
40 #include "wx/msw/uxtheme.h"
41 #endif
42
43 #define GetEditHwnd() ((HWND)(GetEditHWND()))
44
45 // ----------------------------------------------------------------------------
46 // wxIEnumString implements IEnumString interface
47 // ----------------------------------------------------------------------------
48
49 // standard VC6 SDK (WINVER == 0x0400) does not know about IAutoComplete
50 #if wxUSE_OLE && (WINVER >= 0x0500)
51 #define HAS_AUTOCOMPLETE
52 #endif
53
54 #ifdef HAS_AUTOCOMPLETE
55
56 #include "wx/msw/ole/oleutils.h"
57 #include <shldisp.h>
58 #include <shobjidl.h>
59
60 #if defined(__MINGW32__) || defined (__WATCOMC__) || defined(__CYGWIN__)
61 // needed for IID_IAutoComplete, IID_IAutoComplete2 and ACO_AUTOSUGGEST
62 #include <shlguid.h>
63 #endif
64
65 #ifndef ACO_UPDOWNKEYDROPSLIST
66 #define ACO_UPDOWNKEYDROPSLIST 0x20
67 #endif
68
69 #ifndef SHACF_FILESYS_ONLY
70 #define SHACF_FILESYS_ONLY 0x00000010
71 #endif
72
73 DEFINE_GUID(CLSID_AutoComplete,
74 0x00bb2763, 0x6a77, 0x11d0, 0xa5, 0x35, 0x00, 0xc0, 0x4f, 0xd7, 0xd0, 0x62);
75
76 class wxIEnumString : public IEnumString
77 {
78 public:
79 wxIEnumString()
80 {
81 m_index = 0;
82 }
83
84 wxIEnumString(const wxIEnumString& other)
85 : m_strings(other.m_strings),
86 m_index(other.m_index)
87 {
88 }
89
90 DECLARE_IUNKNOWN_METHODS;
91
92 virtual HRESULT STDMETHODCALLTYPE Next(ULONG celt,
93 LPOLESTR *rgelt,
94 ULONG *pceltFetched)
95 {
96 if ( !rgelt || (!pceltFetched && celt > 1) )
97 return E_POINTER;
98
99 ULONG pceltFetchedDummy;
100 if ( !pceltFetched )
101 pceltFetched = &pceltFetchedDummy;
102
103 *pceltFetched = 0;
104
105 for ( const unsigned count = m_strings.size(); celt--; ++m_index )
106 {
107 if ( m_index == count )
108 return S_FALSE;
109
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);
113 if ( !olestr )
114 return E_OUTOFMEMORY;
115
116 memcpy(olestr, wcbuf, size);
117
118 *rgelt++ = static_cast<LPOLESTR>(olestr);
119
120 ++(*pceltFetched);
121 }
122
123 return S_OK;
124 }
125
126 virtual HRESULT STDMETHODCALLTYPE Skip(ULONG celt)
127 {
128 m_index += celt;
129 if ( m_index > m_strings.size() )
130 {
131 m_index = m_strings.size();
132 return S_FALSE;
133 }
134
135 return S_OK;
136 }
137
138 virtual HRESULT STDMETHODCALLTYPE Reset()
139 {
140 m_index = 0;
141
142 return S_OK;
143 }
144
145 virtual HRESULT STDMETHODCALLTYPE Clone(IEnumString **ppEnum)
146 {
147 if ( !ppEnum )
148 return E_POINTER;
149
150 wxIEnumString *e = new wxIEnumString(*this);
151
152 e->AddRef();
153 *ppEnum = e;
154
155 return S_OK;
156 }
157
158 private:
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() { }
164
165
166 wxArrayString m_strings;
167 unsigned m_index;
168
169 friend class wxTextAutoCompleteData;
170
171 wxDECLARE_NO_ASSIGN_CLASS(wxIEnumString);
172 };
173
174 BEGIN_IID_TABLE(wxIEnumString)
175 ADD_IID(Unknown)
176 ADD_IID(EnumString)
177 END_IID_TABLE;
178
179 IMPLEMENT_IUNKNOWN_METHODS(wxIEnumString)
180
181
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
185 {
186 public:
187 // The constructor associates us with the given text entry.
188 wxTextAutoCompleteData(wxTextEntry *entry)
189 : m_entry(entry),
190 m_win(entry->GetEditableWindow())
191 {
192 m_autoComplete = NULL;
193 m_autoCompleteDropDown = NULL;
194 m_enumStrings = NULL;
195 m_customCompleter = NULL;
196
197 m_connectedTextChangedEvent = false;
198
199 // Create an object exposing IAutoComplete interface which we'll later
200 // use to get IAutoComplete2 as the latter can't be created directly,
201 // apparently.
202 HRESULT hr = CoCreateInstance
203 (
204 CLSID_AutoComplete,
205 NULL,
206 CLSCTX_INPROC_SERVER,
207 IID_IAutoComplete,
208 reinterpret_cast<void **>(&m_autoComplete)
209 );
210 if ( FAILED(hr) )
211 {
212 wxLogApiError(wxT("CoCreateInstance(CLSID_AutoComplete)"), hr);
213 return;
214 }
215
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,
220 NULL, NULL);
221 if ( FAILED(hr) )
222 {
223 wxLogApiError(wxT("IAutoComplete::Init"), hr);
224
225 m_enumStrings->Release();
226 m_enumStrings = NULL;
227
228 return;
229 }
230
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
238 (
239 IID_IAutoCompleteDropDown,
240 reinterpret_cast<void **>(&m_autoCompleteDropDown)
241 );
242 if ( FAILED(hr) )
243 {
244 wxLogApiError(wxT("IAutoComplete::QI(IAutoCompleteDropDown)"), hr);
245 return;
246 }
247
248 // Finally set the completion options using IAutoComplete2.
249 IAutoComplete2 *pAutoComplete2 = NULL;
250 hr = m_autoComplete->QueryInterface
251 (
252 IID_IAutoComplete2,
253 reinterpret_cast<void **>(&pAutoComplete2)
254 );
255 if ( SUCCEEDED(hr) )
256 {
257 pAutoComplete2->SetOptions(ACO_AUTOSUGGEST |
258 ACO_UPDOWNKEYDROPSLIST);
259 pAutoComplete2->Release();
260 }
261 }
262
263 ~wxTextAutoCompleteData()
264 {
265 delete m_customCompleter;
266
267 if ( m_enumStrings )
268 m_enumStrings->Release();
269 if ( m_autoCompleteDropDown )
270 m_autoCompleteDropDown->Release();
271 if ( m_autoComplete )
272 m_autoComplete->Release();
273 }
274
275 // Must be called after creating this object to verify if initializing it
276 // succeeded.
277 bool IsOk() const
278 {
279 return m_autoComplete && m_autoCompleteDropDown && m_enumStrings;
280 }
281
282 void ChangeStrings(const wxArrayString& strings)
283 {
284 m_enumStrings->m_strings = strings;
285
286 DoRefresh();
287 }
288
289 // Takes ownership of the pointer if it is non-NULL.
290 bool ChangeCustomCompleter(wxTextCompleter *completer)
291 {
292 delete m_customCompleter;
293 m_customCompleter = completer;
294
295 if ( m_customCompleter )
296 {
297 // We postpone connecting to this event until we really need to do
298 // it (however we don't disconnect from it when we don't need it
299 // any more because we don't have wxUNBIND_OR_DISCONNECT_HACK...).
300 if ( !m_connectedTextChangedEvent )
301 {
302 m_connectedTextChangedEvent = true;
303
304 wxBIND_OR_CONNECT_HACK(m_win, wxEVT_COMMAND_TEXT_UPDATED,
305 wxCommandEventHandler,
306 wxTextAutoCompleteData::OnTextChanged,
307 this);
308 }
309
310 UpdateStringsFromCustomCompleter();
311 }
312
313 return true;
314 }
315
316 void DisableCompletion()
317 {
318 // We currently simply reset the list of possible strings as this seems
319 // to effectively disable auto-completion just fine. We could (and
320 // probably should) use IAutoComplete::Enable(FALSE) for this too but
321 // then we'd need to call Enable(TRUE) to turn it on back again later.
322
323 m_enumStrings->m_strings.clear();
324 m_enumStrings->Reset();
325
326 ChangeCustomCompleter(NULL);
327 }
328
329 private:
330 // Must be called after changing wxIEnumString::m_strings to really make
331 // the changes stick.
332 void DoRefresh()
333 {
334 m_enumStrings->Reset();
335
336 // This is completely and utterly not documented and in fact the
337 // current MSDN seems to try to discourage us from using it by saying
338 // that "there is no reason to use this method unless the drop-down
339 // list is currently visible" but actually we absolutely must call it
340 // to force the auto-completer (and not just its drop-down!) to refresh
341 // the list of completions which could have changed now. Without this
342 // call the new choices returned by GetCompletions() that hadn't been
343 // returned by it before are simply silently ignored.
344 m_autoCompleteDropDown->ResetEnumerator();
345 }
346
347 // Update the strings returned by our string enumerator to correspond to
348 // the currently valid choices according to the custom completer.
349 void UpdateStringsFromCustomCompleter()
350 {
351 // For efficiency we access m_strings directly instead of creating
352 // another wxArrayString, normally this should save us an unnecessary
353 // memory allocation on the subsequent calls.
354 m_enumStrings->m_strings.clear();
355 m_customCompleter->GetCompletions(m_entry->GetValue(),
356 m_enumStrings->m_strings);
357
358 DoRefresh();
359 }
360
361 void OnTextChanged(wxCommandEvent& event)
362 {
363 if ( m_customCompleter )
364 UpdateStringsFromCustomCompleter();
365
366 event.Skip();
367 }
368
369
370 // The text entry we're associated with.
371 wxTextEntry * const m_entry;
372
373 // The window of this text entry.
374 wxWindow * const m_win;
375
376 // The auto-completer object itself.
377 IAutoComplete *m_autoComplete;
378
379 // Its IAutoCompleteDropDown interface needed for ResetEnumerator() call.
380 IAutoCompleteDropDown *m_autoCompleteDropDown;
381
382 // Enumerator for strings currently used for auto-completion.
383 wxIEnumString *m_enumStrings;
384
385 // Custom completer or NULL if none.
386 wxTextCompleter *m_customCompleter;
387
388 // Initially false, set to true after connecting OnTextChanged() handler.
389 bool m_connectedTextChangedEvent;
390
391
392 wxDECLARE_NO_COPY_CLASS(wxTextAutoCompleteData);
393 };
394
395 #endif // HAS_AUTOCOMPLETE
396
397 // ============================================================================
398 // wxTextEntry implementation
399 // ============================================================================
400
401 // ----------------------------------------------------------------------------
402 // initialization and destruction
403 // ----------------------------------------------------------------------------
404
405 wxTextEntry::wxTextEntry()
406 {
407 #ifdef HAS_AUTOCOMPLETE
408 m_autoCompleteData = NULL;
409 #endif // HAS_AUTOCOMPLETE
410 }
411
412 wxTextEntry::~wxTextEntry()
413 {
414 #ifdef HAS_AUTOCOMPLETE
415 delete m_autoCompleteData;
416 #endif // HAS_AUTOCOMPLETE
417 }
418
419 // ----------------------------------------------------------------------------
420 // operations on text
421 // ----------------------------------------------------------------------------
422
423 void wxTextEntry::WriteText(const wxString& text)
424 {
425 ::SendMessage(GetEditHwnd(), EM_REPLACESEL, 0, (LPARAM)text.wx_str());
426 }
427
428 wxString wxTextEntry::DoGetValue() const
429 {
430 return wxGetWindowText(GetEditHWND());
431 }
432
433 void wxTextEntry::Remove(long from, long to)
434 {
435 DoSetSelection(from, to, SetSel_NoScroll);
436 WriteText(wxString());
437 }
438
439 // ----------------------------------------------------------------------------
440 // clipboard operations
441 // ----------------------------------------------------------------------------
442
443 void wxTextEntry::Copy()
444 {
445 ::SendMessage(GetEditHwnd(), WM_COPY, 0, 0);
446 }
447
448 void wxTextEntry::Cut()
449 {
450 ::SendMessage(GetEditHwnd(), WM_CUT, 0, 0);
451 }
452
453 void wxTextEntry::Paste()
454 {
455 ::SendMessage(GetEditHwnd(), WM_PASTE, 0, 0);
456 }
457
458 // ----------------------------------------------------------------------------
459 // undo/redo
460 // ----------------------------------------------------------------------------
461
462 void wxTextEntry::Undo()
463 {
464 ::SendMessage(GetEditHwnd(), EM_UNDO, 0, 0);
465 }
466
467 void wxTextEntry::Redo()
468 {
469 // same as Undo, since Undo undoes the undo
470 Undo();
471 return;
472 }
473
474 bool wxTextEntry::CanUndo() const
475 {
476 return ::SendMessage(GetEditHwnd(), EM_CANUNDO, 0, 0) != 0;
477 }
478
479 bool wxTextEntry::CanRedo() const
480 {
481 // see comment in Redo()
482 return CanUndo();
483 }
484
485 // ----------------------------------------------------------------------------
486 // insertion point and selection
487 // ----------------------------------------------------------------------------
488
489 void wxTextEntry::SetInsertionPoint(long pos)
490 {
491 // calling DoSetSelection(-1, -1) would select everything which is not what
492 // we want here
493 if ( pos == -1 )
494 pos = GetLastPosition();
495
496 // be careful to call DoSetSelection() which is overridden in wxTextCtrl
497 // and not just SetSelection() here
498 DoSetSelection(pos, pos);
499 }
500
501 long wxTextEntry::GetInsertionPoint() const
502 {
503 long from;
504 GetSelection(&from, NULL);
505 return from;
506 }
507
508 long wxTextEntry::GetLastPosition() const
509 {
510 return ::SendMessage(GetEditHwnd(), EM_LINELENGTH, 0, 0);
511 }
512
513 void wxTextEntry::DoSetSelection(long from, long to, int WXUNUSED(flags))
514 {
515 // if from and to are both -1, it means (in wxWidgets) that all text should
516 // be selected, translate this into Windows convention
517 if ( (from == -1) && (to == -1) )
518 {
519 from = 0;
520 }
521
522 ::SendMessage(GetEditHwnd(), EM_SETSEL, from, to);
523 }
524
525 void wxTextEntry::GetSelection(long *from, long *to) const
526 {
527 DWORD dwStart, dwEnd;
528 ::SendMessage(GetEditHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
529
530 if ( from )
531 *from = dwStart;
532 if ( to )
533 *to = dwEnd;
534 }
535
536 // ----------------------------------------------------------------------------
537 // auto-completion
538 // ----------------------------------------------------------------------------
539
540 #if wxUSE_OLE
541
542 #ifdef HAS_AUTOCOMPLETE
543
544 bool wxTextEntry::DoAutoCompleteFileNames()
545 {
546 typedef HRESULT (WINAPI *SHAutoComplete_t)(HWND, DWORD);
547 static SHAutoComplete_t s_pfnSHAutoComplete = (SHAutoComplete_t)-1;
548 static wxDynamicLibrary s_dllShlwapi;
549 if ( s_pfnSHAutoComplete == (SHAutoComplete_t)-1 )
550 {
551 if ( !s_dllShlwapi.Load(wxT("shlwapi.dll"), wxDL_VERBATIM | wxDL_QUIET) )
552 {
553 s_pfnSHAutoComplete = NULL;
554 }
555 else
556 {
557 wxDL_INIT_FUNC(s_pfn, SHAutoComplete, s_dllShlwapi);
558 }
559 }
560
561 if ( !s_pfnSHAutoComplete )
562 return false;
563
564 HRESULT hr = (*s_pfnSHAutoComplete)(GetEditHwnd(), SHACF_FILESYS_ONLY);
565 if ( FAILED(hr) )
566 {
567 wxLogApiError(wxT("SHAutoComplete()"), hr);
568
569 return false;
570 }
571
572 // Disable the other kinds of completion now that we use the built-in file
573 // names completion.
574 if ( m_autoCompleteData )
575 m_autoCompleteData->DisableCompletion();
576
577 return true;
578 }
579
580 wxTextAutoCompleteData *wxTextEntry::GetOrCreateCompleter()
581 {
582 if ( !m_autoCompleteData )
583 {
584 wxTextAutoCompleteData * const ac = new wxTextAutoCompleteData(this);
585 if ( ac->IsOk() )
586 m_autoCompleteData = ac;
587 else
588 delete ac;
589 }
590
591 return m_autoCompleteData;
592 }
593
594 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString& choices)
595 {
596 wxTextAutoCompleteData * const ac = GetOrCreateCompleter();
597 if ( !ac )
598 return false;
599
600 ac->ChangeStrings(choices);
601
602 return true;
603 }
604
605 bool wxTextEntry::DoAutoCompleteCustom(wxTextCompleter *completer)
606 {
607 // First deal with the case when we just want to disable auto-completion.
608 if ( !completer )
609 {
610 if ( m_autoCompleteData )
611 m_autoCompleteData->DisableCompletion();
612 //else: Nothing to do, we hadn't used auto-completion even before.
613 }
614 else // Have a valid completer.
615 {
616 wxTextAutoCompleteData * const ac = GetOrCreateCompleter();
617 if ( !ac )
618 {
619 // Delete the custom completer for consistency with the case when
620 // we succeed to avoid memory leaks in user code.
621 delete completer;
622 return false;
623 }
624
625 // This gives ownership of the custom completer to m_autoCompleteData.
626 if ( !ac->ChangeCustomCompleter(completer) )
627 return false;
628 }
629
630 return true;
631 }
632
633 #else // !HAS_AUTOCOMPLETE
634
635 // We still need to define stubs as we declared these overrides in the header.
636
637 bool wxTextEntry::DoAutoCompleteFileNames()
638 {
639 return wxTextEntryBase::DoAutoCompleteFileNames();
640 }
641
642 bool wxTextEntry::DoAutoCompleteStrings(const wxArrayString& choices)
643 {
644 return wxTextEntryBase::DoAutoCompleteStrings(choices);
645 }
646
647 #endif // HAS_AUTOCOMPLETE/!HAS_AUTOCOMPLETE
648
649 #endif // wxUSE_OLE
650
651 // ----------------------------------------------------------------------------
652 // editable state
653 // ----------------------------------------------------------------------------
654
655 bool wxTextEntry::IsEditable() const
656 {
657 return !(::GetWindowLong(GetEditHwnd(), GWL_STYLE) & ES_READONLY);
658 }
659
660 void wxTextEntry::SetEditable(bool editable)
661 {
662 ::SendMessage(GetEditHwnd(), EM_SETREADONLY, !editable, 0);
663 }
664
665 // ----------------------------------------------------------------------------
666 // max length
667 // ----------------------------------------------------------------------------
668
669 void wxTextEntry::SetMaxLength(unsigned long len)
670 {
671 if ( len >= 0xffff )
672 {
673 // this will set it to a platform-dependent maximum (much more
674 // than 64Kb under NT)
675 len = 0;
676 }
677
678 ::SendMessage(GetEditHwnd(), EM_LIMITTEXT, len, 0);
679 }
680
681 // ----------------------------------------------------------------------------
682 // hints
683 // ----------------------------------------------------------------------------
684
685 #if wxUSE_UXTHEME
686
687 #ifndef EM_SETCUEBANNER
688 #define EM_SETCUEBANNER 0x1501
689 #define EM_GETCUEBANNER 0x1502
690 #endif
691
692 bool wxTextEntry::SetHint(const wxString& hint)
693 {
694 if ( wxUxThemeEngine::GetIfActive() )
695 {
696 // notice that this message always works with Unicode strings
697 //
698 // we always use TRUE for wParam to show the hint even when the window
699 // has focus, otherwise there would be no way to show the hint for the
700 // initially focused window
701 if ( ::SendMessage(GetEditHwnd(), EM_SETCUEBANNER,
702 TRUE, (LPARAM)(const wchar_t *)hint.wc_str()) )
703 return true;
704 }
705
706 return wxTextEntryBase::SetHint(hint);
707 }
708
709 wxString wxTextEntry::GetHint() const
710 {
711 if ( wxUxThemeEngine::GetIfActive() )
712 {
713 wchar_t buf[256];
714 if ( ::SendMessage(GetEditHwnd(), EM_GETCUEBANNER,
715 (WPARAM)buf, WXSIZEOF(buf)) )
716 return wxString(buf);
717 }
718
719 return wxTextEntryBase::GetHint();
720 }
721
722
723 #endif // wxUSE_UXTHEME
724
725 // ----------------------------------------------------------------------------
726 // margins support
727 // ----------------------------------------------------------------------------
728
729 bool wxTextEntry::DoSetMargins(const wxPoint& margins)
730 {
731 #if !defined(__WXWINCE__)
732 bool res = true;
733
734 if ( margins.x != -1 )
735 {
736 // left margin
737 ::SendMessage(GetEditHwnd(), EM_SETMARGINS,
738 EC_LEFTMARGIN, MAKELONG(margins.x, 0));
739 }
740
741 if ( margins.y != -1 )
742 {
743 res = false;
744 }
745
746 return res;
747 #else
748 return false;
749 #endif
750 }
751
752 wxPoint wxTextEntry::DoGetMargins() const
753 {
754 #if !defined(__WXWINCE__)
755 LRESULT lResult = ::SendMessage(GetEditHwnd(), EM_GETMARGINS,
756 0, 0);
757 int left = LOWORD(lResult);
758 int top = -1;
759 return wxPoint(left, top);
760 #else
761 return wxPoint(-1, -1);
762 #endif
763 }
764
765 #endif // wxUSE_TEXTCTRL || wxUSE_COMBOBOX