1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textctrl.cpp
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_TEXTCTRL && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
30 #include "wx/textctrl.h"
31 #include "wx/settings.h"
33 #include "wx/dcclient.h"
40 #include "wx/module.h"
41 #include "wx/wxcrtvararg.h"
44 #include "wx/sysopt.h"
47 #include "wx/clipbrd.h"
50 #include "wx/textfile.h"
54 #include "wx/msw/private.h"
55 #include "wx/msw/winundef.h"
56 #include "wx/msw/mslu.h"
62 #include <sys/types.h>
67 // old mingw32 has richedit stuff directly in windows.h and doesn't have
69 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
73 #endif // wxUSE_RICHEDIT
75 #include "wx/msw/missing.h"
77 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
79 // dummy value used for m_dropTarget, different from any valid pointer value
80 // (which are all even under Windows) and NULL
82 wxRICHTEXT_DEFAULT_DROPTARGET
= reinterpret_cast<wxDropTarget
*>(1);
84 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
92 // this module initializes RichEdit DLL(s) if needed
93 class wxRichEditModule
: public wxModule
98 Version_1
, // riched32.dll
99 Version_2or3
, // both use riched20.dll
100 Version_41
, // msftedit.dll (XP SP1 and Windows 2003)
104 virtual bool OnInit();
105 virtual void OnExit();
107 // load the richedit DLL for the specified version of rich edit
108 static bool Load(Version version
);
111 // load the InkEdit library
112 static bool LoadInkEdit();
116 // the handles to richedit 1.0 and 2.0 (or 3.0) DLLs
117 static HINSTANCE ms_hRichEdit
[Version_Max
];
120 static wxDynamicLibrary ms_inkEditLib
;
121 static bool ms_inkEditLibLoadAttemped
;
124 DECLARE_DYNAMIC_CLASS(wxRichEditModule
)
127 HINSTANCE
wxRichEditModule::ms_hRichEdit
[Version_Max
] = { NULL
, NULL
, NULL
};
130 wxDynamicLibrary
wxRichEditModule::ms_inkEditLib
;
131 bool wxRichEditModule::ms_inkEditLibLoadAttemped
= false;
134 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule
, wxModule
)
136 #endif // wxUSE_RICHEDIT
138 // a small class used to set m_updatesCount to 0 (to filter duplicate events if
139 // necessary) and to reset it back to -1 afterwards
140 class UpdatesCountFilter
143 UpdatesCountFilter(int& count
)
146 wxASSERT_MSG( m_count
== -1 || m_count
== -2,
147 wxT("wrong initial m_updatesCount value") );
151 //else: we don't want to count how many update events we get as we're going
152 // to ignore all of them
155 ~UpdatesCountFilter()
160 // return true if an event has been received
161 bool GotUpdate() const
169 wxDECLARE_NO_COPY_CLASS(UpdatesCountFilter
);
172 // ----------------------------------------------------------------------------
173 // event tables and other macros
174 // ----------------------------------------------------------------------------
176 BEGIN_EVENT_TABLE(wxTextCtrl
, wxTextCtrlBase
)
177 EVT_CHAR(wxTextCtrl::OnChar
)
178 EVT_KEY_DOWN(wxTextCtrl::OnKeyDown
)
179 EVT_DROP_FILES(wxTextCtrl::OnDropFiles
)
182 EVT_CONTEXT_MENU(wxTextCtrl::OnContextMenu
)
185 EVT_MENU(wxID_CUT
, wxTextCtrl::OnCut
)
186 EVT_MENU(wxID_COPY
, wxTextCtrl::OnCopy
)
187 EVT_MENU(wxID_PASTE
, wxTextCtrl::OnPaste
)
188 EVT_MENU(wxID_UNDO
, wxTextCtrl::OnUndo
)
189 EVT_MENU(wxID_REDO
, wxTextCtrl::OnRedo
)
190 EVT_MENU(wxID_CLEAR
, wxTextCtrl::OnDelete
)
191 EVT_MENU(wxID_SELECTALL
, wxTextCtrl::OnSelectAll
)
193 EVT_UPDATE_UI(wxID_CUT
, wxTextCtrl::OnUpdateCut
)
194 EVT_UPDATE_UI(wxID_COPY
, wxTextCtrl::OnUpdateCopy
)
195 EVT_UPDATE_UI(wxID_PASTE
, wxTextCtrl::OnUpdatePaste
)
196 EVT_UPDATE_UI(wxID_UNDO
, wxTextCtrl::OnUpdateUndo
)
197 EVT_UPDATE_UI(wxID_REDO
, wxTextCtrl::OnUpdateRedo
)
198 EVT_UPDATE_UI(wxID_CLEAR
, wxTextCtrl::OnUpdateDelete
)
199 EVT_UPDATE_UI(wxID_SELECTALL
, wxTextCtrl::OnUpdateSelectAll
)
201 EVT_SET_FOCUS(wxTextCtrl::OnSetFocus
)
204 // ============================================================================
206 // ============================================================================
208 // ----------------------------------------------------------------------------
210 // ----------------------------------------------------------------------------
212 void wxTextCtrl::Init()
216 #endif // wxUSE_RICHEDIT
218 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
222 m_privateContextMenu
= NULL
;
224 m_isNativeCaretShown
= true;
227 wxTextCtrl::~wxTextCtrl()
229 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
230 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
232 // don't try to destroy this dummy pointer in the base class dtor
235 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
237 delete m_privateContextMenu
;
240 bool wxTextCtrl::Create(wxWindow
*parent
,
242 const wxString
& value
,
246 const wxValidator
& validator
,
247 const wxString
& name
)
249 // base initialization
250 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
253 if ( !MSWCreateText(value
, pos
, size
) )
256 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
259 // rich text controls have a default associated drop target which
260 // allows them to receive (rich) text dropped on them, which is nice,
261 // but prevents us from associating a user-defined drop target with
262 // them as we need to unregister the old one first
264 // to make it work, we set m_dropTarget to this special value initially
265 // and check for it in our SetDropTarget()
266 m_dropTarget
= wxRICHTEXT_DEFAULT_DROPTARGET
;
268 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
273 // returns true if the platform should explicitly apply a theme border
274 bool wxTextCtrl::CanApplyThemeBorder() const
279 // Standard text control already handles theming
280 return ((GetWindowStyle() & (wxTE_RICH
|wxTE_RICH2
)) != 0);
284 bool wxTextCtrl::MSWCreateText(const wxString
& value
,
288 // translate wxWin style flags to MSW ones
289 WXDWORD msStyle
= MSWGetCreateWindowFlags();
291 // do create the control - either an EDIT or RICHEDIT
292 wxString windowClass
= wxT("EDIT");
294 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
295 // A control that capitalizes the first letter
296 if ( HasFlag(wxTE_CAPITALIZE
) )
297 windowClass
= wxT("CAPEDIT");
301 if ( m_windowStyle
& wxTE_AUTO_URL
)
303 // automatic URL detection only works in RichEdit 2.0+
304 m_windowStyle
|= wxTE_RICH2
;
307 if ( m_windowStyle
& wxTE_RICH2
)
309 // using richedit 2.0 implies using wxTE_RICH
310 m_windowStyle
|= wxTE_RICH
;
313 // we need to load the richedit DLL before creating the rich edit control
314 if ( m_windowStyle
& wxTE_RICH
)
316 // versions 2.0, 3.0 and 4.1 of rich edit are mostly compatible with
317 // each other but not with version 1.0, so we have separate flags for
318 // the version 1.0 and the others (and so m_verRichEdit may be 0 (plain
319 // EDIT control), 1 for version 1.0 or 2 for any higher version)
321 // notice that 1.0 has no Unicode support at all so in Unicode build we
322 // must use another version
326 #else // !wxUSE_UNICODE
327 m_verRichEdit
= m_windowStyle
& wxTE_RICH2
? 2 : 1;
328 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
331 // First test if we can load an ink edit control. Normally, all edit
332 // controls will be made ink edit controls if a tablet environment is
333 // found (or if msw.inkedit != 0 and the InkEd.dll is present).
334 // However, an application can veto ink edit controls by either specifying
335 // msw.inkedit = 0 or by removing wxTE_RICH[2] from the style.
337 if ((wxSystemSettings::HasFeature(wxSYS_TABLET_PRESENT
) || wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) != 0) &&
338 !(wxSystemOptions::HasOption(wxT("msw.inkedit")) && wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) == 0))
340 if (wxRichEditModule::LoadInkEdit())
342 windowClass
= INKEDIT_CLASS
;
344 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
348 // Fake rich text version for other calls
356 #endif // wxUSE_INKEDIT
358 if ( m_verRichEdit
== 2 )
360 if ( wxRichEditModule::Load(wxRichEditModule::Version_41
) )
362 // yes, class name for version 4.1 really is 5.0
363 windowClass
= wxT("RICHEDIT50W");
367 else if ( wxRichEditModule::Load(wxRichEditModule::Version_2or3
) )
369 windowClass
= wxT("RichEdit20")
374 #endif // Unicode/ANSI
376 else // failed to load msftedit.dll and riched20.dll
382 if ( m_verRichEdit
== 1 )
384 if ( wxRichEditModule::Load(wxRichEditModule::Version_1
) )
386 windowClass
= wxT("RICHEDIT");
388 else // failed to load any richedit control DLL
390 // only give the error msg once if the DLL can't be loaded
391 static bool s_errorGiven
= false; // MT ok as only used by GUI
395 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
405 #endif // wxUSE_RICHEDIT
407 // we need to turn '\n's into "\r\n"s for the multiline controls
409 if ( m_windowStyle
& wxTE_MULTILINE
)
411 valueWin
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
418 // suppress events sent during control creation: we're called either from
419 // the ctor and then we shouldn't generate any events for compatibility
420 // with the other ports, or from SetWindowStyleFlag() and then we shouldn't
421 // generate the events because our text doesn't really change, the fact
422 // that we (sometimes) need to recreate the control is just an
423 // implementation detail
426 if ( !MSWCreateControl(windowClass
.t_str(), msStyle
, pos
, size
, valueWin
) )
437 // Pass IEM_InsertText (0) as wParam, in order to have the ink always
438 // converted to text.
439 ::SendMessage(GetHwnd(), EM_SETINKINSERTMODE
, 0, 0);
441 // Make sure the mouse can be used for input
442 ::SendMessage(GetHwnd(), EM_SETUSEMOUSEFORINPUT
, 1, 0);
446 // enable the events we're interested in: we want to get EN_CHANGE as
447 // for the normal controls
448 LPARAM mask
= ENM_CHANGE
;
450 if (GetRichVersion() == 1 && !IsInkEdit())
452 // we also need EN_MSGFILTER for richedit 1.0 for the reasons
453 // explained in its handler
454 mask
|= ENM_MOUSEEVENTS
;
456 // we also need to force the appearance of the vertical scrollbar
457 // initially as otherwise the control doesn't refresh correctly
458 // after resize: but once the vertical scrollbar had been shown
459 // (even if it's subsequently hidden) it does
461 // this is clearly a bug and for now it has been only noticed under
462 // Windows XP, so if we're sure it works correctly under other
463 // systems we could do this only for XP
464 SetSize(-1, 1); // 1 is small enough to force vert scrollbar
465 SetInitialSize(size
);
467 else if ( m_windowStyle
& wxTE_AUTO_URL
)
471 ::SendMessage(GetHwnd(), EM_AUTOURLDETECT
, TRUE
, 0);
474 ::SendMessage(GetHwnd(), EM_SETEVENTMASK
, 0, mask
);
477 #endif // wxUSE_RICHEDIT
478 if ( HasFlag(wxTE_MULTILINE
) && HasFlag(wxTE_READONLY
) )
480 // non-rich read-only multiline controls have grey background by
481 // default under MSW but this is not always appropriate, so forcefully
482 // reset the background colour to normal default
484 // this is not ideal but, after a long discussion on wx-dev (see
485 // http://thread.gmane.org/gmane.comp.lib.wxwidgets.devel/116360/) it
486 // was finally deemed to be the best behaviour by default (and ideally
487 // we'd have a way to change this, see #11521)
488 SetBackgroundColour(GetClassDefaultAttributes().colBg
);
492 // Without this, if we pass the size in the constructor and then don't change it,
493 // the themed borders will be drawn incorrectly.
494 SetWindowPos(GetHwnd(), NULL
, 0, 0, 0, 0,
495 SWP_NOZORDER
|SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOACTIVATE
|
502 // Make sure the window style (etc.) reflects the HWND style (roughly)
503 void wxTextCtrl::AdoptAttributesFromHWND()
505 wxWindow::AdoptAttributesFromHWND();
507 HWND hWnd
= GetHwnd();
508 long style
= ::GetWindowLong(hWnd
, GWL_STYLE
);
510 // retrieve the style to see whether this is an edit or richedit ctrl
512 wxString classname
= wxGetWindowClass(GetHWND());
514 if ( classname
.IsSameAs(wxT("EDIT"), false /* no case */) )
521 if ( wxSscanf(classname
, wxT("RichEdit%d0%c"), &m_verRichEdit
, &c
) != 2 )
523 wxLogDebug(wxT("Unknown edit control '%s'."), classname
.c_str());
528 #endif // wxUSE_RICHEDIT
530 if (style
& ES_MULTILINE
)
531 m_windowStyle
|= wxTE_MULTILINE
;
532 if (style
& ES_PASSWORD
)
533 m_windowStyle
|= wxTE_PASSWORD
;
534 if (style
& ES_READONLY
)
535 m_windowStyle
|= wxTE_READONLY
;
536 if (style
& ES_WANTRETURN
)
537 m_windowStyle
|= wxTE_PROCESS_ENTER
;
538 if (style
& ES_CENTER
)
539 m_windowStyle
|= wxTE_CENTRE
;
540 if (style
& ES_RIGHT
)
541 m_windowStyle
|= wxTE_RIGHT
;
544 WXDWORD
wxTextCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
546 long msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
548 // styles which we always add by default
549 if ( style
& wxTE_MULTILINE
)
551 msStyle
|= ES_MULTILINE
| ES_WANTRETURN
;
552 if ( !(style
& wxTE_NO_VSCROLL
) )
554 // always adjust the vertical scrollbar automatically if we have it
555 msStyle
|= WS_VSCROLL
| ES_AUTOVSCROLL
;
558 // we have to use this style for the rich edit controls because
559 // without it the vertical scrollbar never appears at all in
560 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
561 if ( style
& wxTE_RICH2
)
563 msStyle
|= ES_DISABLENOSCROLL
;
565 #endif // wxUSE_RICHEDIT
568 style
|= wxTE_PROCESS_ENTER
;
572 // there is really no reason to not have this style for single line
574 msStyle
|= ES_AUTOHSCROLL
;
577 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
578 // scrollbar, there is no wrapping -- which makes sense
579 if ( style
& wxTE_DONTWRAP
)
581 // automatically scroll the control horizontally as necessary
583 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
584 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
585 // it doesn't seem to do any harm for plain edit controls, add it
587 msStyle
|= WS_HSCROLL
| ES_AUTOHSCROLL
;
590 if ( style
& wxTE_READONLY
)
591 msStyle
|= ES_READONLY
;
593 if ( style
& wxTE_PASSWORD
)
594 msStyle
|= ES_PASSWORD
;
596 if ( style
& wxTE_NOHIDESEL
)
597 msStyle
|= ES_NOHIDESEL
;
599 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
600 if ( style
& wxTE_CENTRE
)
601 msStyle
|= ES_CENTER
;
602 else if ( style
& wxTE_RIGHT
)
605 msStyle
|= ES_LEFT
; // ES_LEFT is 0 as well but for consistency...
610 void wxTextCtrl::SetWindowStyleFlag(long style
)
612 // changing the alignment of the control dynamically works under Win2003
613 // (but not older Windows version: it seems to work under some versions of
614 // XP but not other ones, and we have no way to determine it so be
615 // conservative here) and only for plain EDIT controls (not RICH ones) and
616 // we have to recreate the control to make it always work
617 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003
)
619 const long alignMask
= wxTE_LEFT
| wxTE_CENTRE
| wxTE_RIGHT
;
620 if ( (style
& alignMask
) != (GetWindowStyle() & alignMask
) )
622 const wxString value
= GetValue();
623 const wxPoint pos
= GetPosition();
624 const wxSize size
= GetSize();
626 // delete the old window
627 HWND hwnd
= GetHwnd();
629 ::DestroyWindow(hwnd
);
631 // create the new one with the updated flags
632 m_windowStyle
= style
;
633 MSWCreateText(value
, pos
, size
);
635 // and make sure it has the same attributes as before
638 // calling SetFont(m_font) would do nothing as the code would
639 // notice that the font didn't change, so force it to believe
641 wxFont font
= m_font
;
648 wxColour colFg
= m_foregroundColour
;
649 m_foregroundColour
= wxNullColour
;
650 SetForegroundColour(colFg
);
655 wxColour colBg
= m_backgroundColour
;
656 m_backgroundColour
= wxNullColour
;
657 SetBackgroundColour(colBg
);
660 // note that text styles are lost but this is probably not a big
661 // problem: if you use styles, you probably don't use nor change
662 // alignment flags anyhow
669 // we have to deal with some styles separately because they can't be
670 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
671 // using richedit-specific EM_SETOPTIONS
673 ((style
& wxTE_NOHIDESEL
) != (GetWindowStyle() & wxTE_NOHIDESEL
)) )
675 bool set
= (style
& wxTE_NOHIDESEL
) != 0;
677 ::SendMessage(GetHwnd(), EM_SETOPTIONS
, set
? ECOOP_OR
: ECOOP_AND
,
678 set
? ECO_NOHIDESEL
: ~ECO_NOHIDESEL
);
680 #endif // wxUSE_RICHEDIT
682 wxControl::SetWindowStyleFlag(style
);
685 // ----------------------------------------------------------------------------
686 // set/get the controls text
687 // ----------------------------------------------------------------------------
689 bool wxTextCtrl::IsEmpty() const
691 // this is an optimization for multiline controls containing a lot of text
692 if ( IsMultiLine() && GetNumberOfLines() != 1 )
695 return wxTextCtrlBase::IsEmpty();
698 wxString
wxTextCtrl::GetValue() const
700 // range 0..-1 is special for GetRange() and means to retrieve all text
701 return GetRange(0, -1);
704 wxString
wxTextCtrl::GetRange(long from
, long to
) const
708 if ( from
>= to
&& to
!= -1 )
710 // nothing to retrieve
717 int len
= GetWindowTextLength(GetHwnd());
724 // we must use EM_STREAMOUT if we don't want to lose all characters
725 // not representable in the current character set (EM_GETTEXTRANGE
726 // simply replaces them with question marks...)
727 if ( GetRichVersion() > 1 )
729 // we must have some encoding, otherwise any 8bit chars in the
730 // control are simply *lost* (replaced by '?')
731 wxFontEncoding encoding
= wxFONTENCODING_SYSTEM
;
733 wxFont font
= m_defaultStyle
.GetFont();
739 encoding
= font
.GetEncoding();
743 if ( encoding
== wxFONTENCODING_SYSTEM
)
745 encoding
= wxLocale::GetSystemEncoding();
749 if ( encoding
== wxFONTENCODING_SYSTEM
)
751 encoding
= wxFONTENCODING_ISO8859_1
;
754 str
= StreamOut(encoding
);
758 // we have to manually extract the required part, luckily
759 // this is easy in this case as EOL characters in str are
760 // just LFs because we remove CRs in wxRichEditStreamOut
761 str
= str
.Mid(from
, to
- from
);
765 // StreamOut() wasn't used or failed, try to do it in normal way
767 #endif // !wxUSE_UNICODE
769 // alloc one extra WORD as needed by the control
770 wxStringBuffer
tmp(str
, ++len
);
774 textRange
.chrg
.cpMin
= from
;
775 textRange
.chrg
.cpMax
= to
;
776 textRange
.lpstrText
= p
;
778 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE
,
779 0, (LPARAM
)&textRange
);
781 if ( m_verRichEdit
> 1 )
783 // RichEdit 2.0 uses just CR ('\r') for the
784 // newlines which is neither Unix nor Windows
785 // style - convert it to something reasonable
788 if ( *p
== wxT('\r') )
794 if ( m_verRichEdit
== 1 )
796 // convert to the canonical form - see comment below
797 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
800 //else: no text at all, leave the string empty
803 #endif // wxUSE_RICHEDIT
805 // retrieve all text: wxTextEntry method works even for multiline
806 // controls and must be used for single line ones to account for hints
807 str
= wxTextEntry::GetValue();
809 // need only a range?
812 str
= str
.Mid(from
, to
- from
);
815 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
816 // canonical one (same one as above) for consistency with the other kinds
817 // of controls and, more importantly, with the other ports
818 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
824 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
826 // if the text is long enough, it's faster to just set it instead of first
827 // comparing it with the old one (chances are that it will be different
828 // anyhow, this comparison is there to avoid flicker for small single-line
829 // edit controls mostly)
830 if ( (value
.length() > 0x400) || (value
!= DoGetValue()) )
832 DoWriteText(value
, flags
/* doesn't include SelectionOnly here */);
834 // mark the control as being not dirty - we changed its text, not the
838 // for compatibility, don't move the cursor when doing SetValue()
839 SetInsertionPoint(0);
843 // still reset the modified flag even if the value didn't really change
844 // because now it comes from the program and not the user (and do it
845 // before generating the event so that the event handler could get the
846 // expected value from IsModified())
849 // still send an event for consistency
850 if (flags
& SetValue_SendEvent
)
855 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
857 // TODO: using memcpy() would improve performance a lot for big amounts of text
860 wxRichEditStreamIn(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
864 const wchar_t ** const ppws
= (const wchar_t **)dwCookie
;
866 wchar_t *wbuf
= (wchar_t *)buf
;
867 const wchar_t *wpc
= *ppws
;
872 cb
-= sizeof(wchar_t);
873 (*pcb
) += sizeof(wchar_t);
881 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
882 struct wxStreamOutData
889 wxRichEditStreamOut(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
893 wxStreamOutData
*data
= (wxStreamOutData
*)dwCookie
;
895 const wchar_t *wbuf
= (const wchar_t *)buf
;
896 wchar_t *wpc
= data
->wpc
;
899 wchar_t wch
= *wbuf
++;
901 // turn "\r\n" into "\n" on the fly
907 cb
-= sizeof(wchar_t);
908 (*pcb
) += sizeof(wchar_t);
917 #if wxUSE_UNICODE_MSLU
918 #define UNUSED_IF_MSLU(param)
920 #define UNUSED_IF_MSLU(param) param
924 wxTextCtrl::StreamIn(const wxString
& value
,
925 wxFontEncoding
UNUSED_IF_MSLU(encoding
),
928 #if wxUSE_UNICODE_MSLU
929 const wchar_t *wpc
= value
.c_str();
930 #else // !wxUSE_UNICODE_MSLU
931 wxCSConv
conv(encoding
);
933 const size_t len
= conv
.MB2WC(NULL
, value
.mb_str(), value
.length());
935 if (len
== wxCONV_FAILED
)
938 wxWCharBuffer
wchBuf(len
); // allocates one extra character
939 wchar_t *wpc
= wchBuf
.data();
941 conv
.MB2WC(wpc
, value
.mb_str(), len
+ 1);
942 #endif // wxUSE_UNICODE_MSLU
944 // finally, stream it in the control
947 eds
.dwCookie
= (DWORD_PTR
)&wpc
;
948 // the cast below is needed for broken (very) old mingw32 headers
949 eds
.pfnCallback
= (EDITSTREAMCALLBACK
)wxRichEditStreamIn
;
951 // same problem as in DoWriteText(): we can get multiple events here
952 UpdatesCountFilter
ucf(m_updatesCount
);
954 ::SendMessage(GetHwnd(), EM_STREAMIN
,
957 (selectionOnly
? SFF_SELECTION
: 0),
960 // It's okay for EN_UPDATE to not be sent if the selection is empty and
961 // the text is empty, otherwise warn the programmer about it.
962 wxASSERT_MSG( ucf
.GotUpdate() || ( !HasSelection() && value
.empty() ),
963 wxT("EM_STREAMIN didn't send EN_UPDATE?") );
967 wxLogLastError(wxT("EM_STREAMIN"));
973 #if !wxUSE_UNICODE_MSLU
976 wxTextCtrl::StreamOut(wxFontEncoding encoding
, bool selectionOnly
) const
980 const int len
= GetWindowTextLength(GetHwnd());
982 wxWCharBuffer
wchBuf(len
);
983 wchar_t *wpc
= wchBuf
.data();
985 wxStreamOutData data
;
991 eds
.dwCookie
= (DWORD
)&data
;
992 eds
.pfnCallback
= wxRichEditStreamOut
;
998 SF_TEXT
| SF_UNICODE
| (selectionOnly
? SFF_SELECTION
: 0),
1004 wxLogLastError(wxT("EM_STREAMOUT"));
1006 else // streamed out ok
1008 // NUL-terminate the string because its length could have been
1009 // decreased by wxRichEditStreamOut
1010 *(wchBuf
.data() + data
.len
) = L
'\0';
1012 // now convert to the given encoding (this is a possibly lossful
1013 // conversion but what else can we do)
1014 wxCSConv
conv(encoding
);
1015 size_t lenNeeded
= conv
.WC2MB(NULL
, wchBuf
, 0);
1017 if ( lenNeeded
!= wxCONV_FAILED
&& lenNeeded
++ )
1019 conv
.WC2MB(wxStringBuffer(out
, lenNeeded
), wchBuf
, lenNeeded
);
1026 #endif // !wxUSE_UNICODE_MSLU
1028 #endif // wxUSE_RICHEDIT
1030 void wxTextCtrl::WriteText(const wxString
& value
)
1035 void wxTextCtrl::DoWriteText(const wxString
& value
, int flags
)
1037 bool selectionOnly
= (flags
& SetValue_SelectionOnly
) != 0;
1039 if ( m_windowStyle
& wxTE_MULTILINE
)
1040 valueDos
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
1045 // there are several complications with the rich edit controls here
1049 // first, ensure that the new text will be in the default style
1050 if ( !m_defaultStyle
.IsDefault() )
1053 GetSelection(&start
, &end
);
1054 SetStyle(start
, end
, m_defaultStyle
);
1057 #if wxUSE_UNICODE_MSLU
1058 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1059 // but EM_STREAMIN works
1060 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1062 done
= StreamIn(valueDos
, wxFONTENCODING_SYSTEM
, selectionOnly
);
1064 #endif // wxUSE_UNICODE_MSLU
1067 // next check if the text we're inserting must be shown in a non
1068 // default charset -- this only works for RichEdit > 1.0
1069 if ( GetRichVersion() > 1 )
1071 wxFont font
= m_defaultStyle
.GetFont();
1077 wxFontEncoding encoding
= font
.GetEncoding();
1078 if ( encoding
!= wxFONTENCODING_SYSTEM
)
1080 // we have to use EM_STREAMIN to force richedit control 2.0+
1081 // to show any text in the non default charset -- otherwise
1082 // it thinks it knows better than we do and always shows it
1083 // in the default one
1084 done
= StreamIn(valueDos
, encoding
, selectionOnly
);
1088 #endif // !wxUSE_UNICODE
1092 #endif // wxUSE_RICHEDIT
1094 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1095 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1096 // -- undetermined -- conditions with rich edit) and sometimes we don't
1097 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1098 // we generate exactly one of them by ignoring all but the first one in
1099 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1100 // notifications from Windows
1101 if ( !(flags
& SetValue_SendEvent
) )
1102 m_updatesCount
= -2; // suppress any update event
1104 UpdatesCountFilter
ucf(m_updatesCount
);
1106 ::SendMessage(GetHwnd(), selectionOnly
? EM_REPLACESEL
: WM_SETTEXT
,
1107 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1108 selectionOnly
? 1 : 0, wxMSW_CONV_LPARAM(valueDos
));
1110 if ( !ucf
.GotUpdate() && (flags
& SetValue_SendEvent
) )
1117 void wxTextCtrl::AppendText(const wxString
& text
)
1119 wxTextEntry::AppendText(text
);
1122 // don't do this if we're frozen, saves some time
1123 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1125 ::SendMessage(GetHwnd(), WM_VSCROLL
, SB_BOTTOM
, (LPARAM
)NULL
);
1127 #endif // wxUSE_RICHEDIT
1130 void wxTextCtrl::Clear()
1132 ::SetWindowText(GetHwnd(), wxEmptyString
);
1134 if ( IsMultiLine() && !IsRich() )
1136 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1137 // but the normal ones don't -- make Clear() behaviour consistent by
1138 // always sending this event
1145 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent
& event
)
1149 size_t lenOld
= GetValue().length();
1151 wxUint32 code
= event
.GetRawKeyCode();
1152 ::keybd_event((BYTE
)code
, 0, 0 /* key press */, 0);
1153 ::keybd_event((BYTE
)code
, 0, KEYEVENTF_KEYUP
, 0);
1155 // assume that any alphanumeric key changes the total number of characters
1156 // in the control - this should work in 99% of cases
1157 return GetValue().length() != lenOld
;
1162 // ----------------------------------------------------------------------------
1164 // ----------------------------------------------------------------------------
1166 void wxTextCtrl::SetInsertionPointEnd()
1168 // we must not do anything if the caret is already there because calling
1169 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1170 // if it doesn't actually move the caret anywhere and so the simple fact of
1171 // doing it results in horrible flicker when appending big amounts of text
1172 // to the control in a few chunks (see DoAddText() test in the text sample)
1173 const wxTextPos lastPosition
= GetLastPosition();
1174 if ( GetInsertionPoint() == lastPosition
)
1179 SetInsertionPoint(lastPosition
);
1182 long wxTextCtrl::GetInsertionPoint() const
1190 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &range
);
1193 #endif // wxUSE_RICHEDIT
1195 return wxTextEntry::GetInsertionPoint();
1198 wxTextPos
wxTextCtrl::GetLastPosition() const
1200 if ( IsMultiLine() )
1202 int numLines
= GetNumberOfLines();
1203 long posStartLastLine
= XYToPosition(0, numLines
- 1);
1205 long lenLastLine
= GetLengthOfLineContainingPos(posStartLastLine
);
1207 return posStartLastLine
+ lenLastLine
;
1210 return wxTextEntry::GetLastPosition();
1213 // If the return values from and to are the same, there is no
1215 void wxTextCtrl::GetSelection(long *from
, long *to
) const
1220 CHARRANGE charRange
;
1221 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &charRange
);
1223 *from
= charRange
.cpMin
;
1224 *to
= charRange
.cpMax
;
1227 #endif // !wxUSE_RICHEDIT
1229 wxTextEntry::GetSelection(from
, to
);
1233 // ----------------------------------------------------------------------------
1235 // ----------------------------------------------------------------------------
1237 void wxTextCtrl::DoSetSelection(long from
, long to
, int flags
)
1239 HWND hWnd
= GetHwnd();
1244 // if from and to are both -1, it means (in wxWidgets) that all text
1245 // should be selected, translate this into Windows convention
1246 if ( (from
== -1) && (to
== -1) )
1254 ::SendMessage(hWnd
, EM_EXSETSEL
, 0, (LPARAM
)&range
);
1257 #endif // wxUSE_RICHEDIT
1259 wxTextEntry::DoSetSelection(from
, to
, flags
);
1262 if ( (flags
& SetSel_Scroll
) && !IsFrozen() )
1265 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1266 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1267 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1268 // option is set (but it does work ok in richedit 1.0 mode...)
1270 // so to make it work we either need to give focus to it here which
1271 // will probably create many problems (dummy focus events; window
1272 // containing the text control being brought to foreground
1273 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1274 // create other problems too -- and in fact it does because if we turn
1275 // on/off this style while appending the text to the control, the
1276 // vertical scrollbar never appears in it even if we append tons of
1277 // text and to work around this the only solution I found was to use
1278 // ES_DISABLENOSCROLL
1280 // this is very ugly but I don't see any other way to make this work
1282 if ( GetRichVersion() > 1 )
1284 if ( !HasFlag(wxTE_NOHIDESEL
) )
1286 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1287 // others, remember the style so we can reset it later if needed
1288 style
= ::GetWindowLong(GetHwnd(), GWL_STYLE
);
1289 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1290 ECOOP_OR
, ECO_NOHIDESEL
);
1292 //else: everything is already ok
1294 #endif // wxUSE_RICHEDIT
1296 ::SendMessage(hWnd
, EM_SCROLLCARET
, 0, (LPARAM
)0);
1299 // restore ECO_NOHIDESEL if we changed it
1300 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL
) )
1302 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1303 ECOOP_AND
, ~ECO_NOHIDESEL
);
1304 if ( style
!= ::GetWindowLong(GetHwnd(), GWL_STYLE
) )
1305 ::SetWindowLong(GetHwnd(), GWL_STYLE
, style
);
1307 #endif // wxUSE_RICHEDIT
1311 // ----------------------------------------------------------------------------
1312 // Working with files
1313 // ----------------------------------------------------------------------------
1315 bool wxTextCtrl::DoLoadFile(const wxString
& file
, int fileType
)
1317 if ( wxTextCtrlBase::DoLoadFile(file
, fileType
) )
1319 // update the size limit if needed
1328 // ----------------------------------------------------------------------------
1330 // ----------------------------------------------------------------------------
1332 bool wxTextCtrl::IsModified() const
1334 return ::SendMessage(GetHwnd(), EM_GETMODIFY
, 0, 0) != 0;
1337 void wxTextCtrl::MarkDirty()
1339 ::SendMessage(GetHwnd(), EM_SETMODIFY
, TRUE
, 0);
1342 void wxTextCtrl::DiscardEdits()
1344 ::SendMessage(GetHwnd(), EM_SETMODIFY
, FALSE
, 0);
1347 // ----------------------------------------------------------------------------
1348 // Positions <-> coords
1349 // ----------------------------------------------------------------------------
1351 int wxTextCtrl::GetNumberOfLines() const
1353 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT
, 0, 0);
1356 long wxTextCtrl::XYToPosition(long x
, long y
) const
1358 // This gets the char index for the _beginning_ of this line
1359 long charIndex
= ::SendMessage(GetHwnd(), EM_LINEINDEX
, y
, 0);
1361 return charIndex
+ x
;
1364 bool wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
1366 HWND hWnd
= GetHwnd();
1368 // This gets the line number containing the character
1373 lineNo
= ::SendMessage(hWnd
, EM_EXLINEFROMCHAR
, 0, pos
);
1376 #endif // wxUSE_RICHEDIT
1378 lineNo
= ::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1387 // This gets the char index for the _beginning_ of this line
1388 long charIndex
= ::SendMessage(hWnd
, EM_LINEINDEX
, lineNo
, 0);
1389 if ( charIndex
== -1 )
1394 // The X position must therefore be the different between pos and charIndex
1396 *x
= pos
- charIndex
;
1403 wxTextCtrlHitTestResult
1404 wxTextCtrl::HitTest(const wxPoint
& pt
, long *posOut
) const
1406 // first get the position from Windows
1413 // for rich edit controls the position is passed iva the struct fields
1416 lParam
= (LPARAM
)&ptl
;
1419 #endif // wxUSE_RICHEDIT
1421 // for the plain ones, we are limited to 16 bit positions which are
1422 // combined in a single 32 bit value
1423 lParam
= MAKELPARAM(pt
.x
, pt
.y
);
1426 LRESULT pos
= ::SendMessage(GetHwnd(), EM_CHARFROMPOS
, 0, lParam
);
1430 // this seems to indicate an error...
1431 return wxTE_HT_UNKNOWN
;
1436 #endif // wxUSE_RICHEDIT
1438 // for plain EDIT controls the higher word contains something else
1443 // next determine where it is relatively to our point: EM_CHARFROMPOS
1444 // always returns the closest character but we need to be more precise, so
1445 // double check that we really are where it pretends
1449 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1450 // we don't know how to do it
1453 ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&ptReal
, pos
);
1456 #endif // wxUSE_RICHEDIT
1458 LRESULT lRc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1462 // this is apparently returned when pos corresponds to the last
1469 ptReal
.x
= LOWORD(lRc
);
1470 ptReal
.y
= HIWORD(lRc
);
1474 wxTextCtrlHitTestResult rc
;
1476 if ( pt
.y
> ptReal
.y
+ GetCharHeight() )
1478 else if ( pt
.x
> ptReal
.x
+ GetCharWidth() )
1479 rc
= wxTE_HT_BEYOND
;
1481 rc
= wxTE_HT_ON_TEXT
;
1489 wxPoint
wxTextCtrl::DoPositionToCoords(long pos
) const
1491 // FIXME: This code is broken for rich edit version 2.0 as it uses the same
1492 // API as plain edit i.e. the coordinates are returned directly instead of
1493 // filling the POINT passed as WPARAM with them but we can't distinguish
1494 // between 2.0 and 3.0 unfortunately (see also the use of EM_POSFROMCHAR
1500 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&pt
, pos
);
1502 return wxPoint(pt
.x
, pt
.y
);
1505 #endif // wxUSE_RICHEDIT
1507 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1510 // Finding coordinates for the last position of the control fails
1511 // in plain EDIT control, try to compensate for it by finding it
1512 // ourselves from the position of the previous character.
1513 if ( pos
< GetLastPosition() )
1515 // It's not the expected correctable failure case so just fail.
1516 return wxDefaultPosition
;
1521 // We're being asked the coordinates of the first (and last and
1522 // only) position in an empty control. There is no way to get
1523 // it directly with EM_POSFROMCHAR but EM_GETMARGINS returns
1524 // the correct value for at least the horizontal offset.
1525 rc
= ::SendMessage(GetHwnd(), EM_GETMARGINS
, 0, 0);
1527 // Text control seems to effectively add 1 to margin.
1528 return wxPoint(LOWORD(rc
) + 1, 1);
1531 // We do have a previous character, try to get its coordinates.
1532 rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
- 1, 0);
1535 // If getting coordinates of the previous character failed as
1536 // well, just give up.
1537 return wxDefaultPosition
;
1540 wxString prevChar
= GetRange(pos
- 1, pos
);
1541 wxSize prevCharSize
= GetTextExtent(prevChar
);
1543 if ( prevChar
== wxT("\n" ))
1545 // 'pos' is at the beginning of a new line so its X coordinate
1546 // should be the same as X coordinate of the first character of
1547 // any other line while its Y coordinate will be approximately
1548 // (but we can't compute it exactly...) one character height
1549 // more than that of the previous character.
1550 LRESULT coords0
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, 0, 0);
1551 if ( coords0
== -1 )
1552 return wxDefaultPosition
;
1554 rc
= MAKELPARAM(LOWORD(coords0
), HIWORD(rc
) + prevCharSize
.y
);
1558 // Simple case: previous character is in the same line so this
1559 // one is just after it.
1560 rc
+= MAKELPARAM(prevCharSize
.x
, 0);
1564 // Notice that {LO,HI}WORD macros return WORDs, i.e. unsigned shorts,
1565 // while we want to have signed values here (the y coordinate of any
1566 // position above the first currently visible line is negative, for
1567 // example), hence the need for casts.
1568 return wxPoint(static_cast<short>(LOWORD(rc
)),
1569 static_cast<short>(HIWORD(rc
)));
1572 return wxDefaultPosition
;
1576 // ----------------------------------------------------------------------------
1578 // ----------------------------------------------------------------------------
1580 void wxTextCtrl::ShowPosition(long pos
)
1582 HWND hWnd
= GetHwnd();
1584 // To scroll to a position, we pass the number of lines and characters
1585 // to scroll *by*. This means that we need to:
1586 // (1) Find the line position of the current line.
1587 // (2) Find the line position of pos.
1588 // (3) Scroll by (pos - current).
1589 // For now, ignore the horizontal scrolling.
1591 // Is this where scrolling is relative to - the line containing the caret?
1592 // Or is the first visible line??? Try first visible line.
1593 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, -1, 0L);
1595 int currentLineLineNo
= (int)::SendMessage(hWnd
, EM_GETFIRSTVISIBLELINE
, 0, 0);
1597 int specifiedLineLineNo
= (int)::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1599 int linesToScroll
= specifiedLineLineNo
- currentLineLineNo
;
1601 if (linesToScroll
!= 0)
1602 ::SendMessage(hWnd
, EM_LINESCROLL
, 0, linesToScroll
);
1605 long wxTextCtrl::GetLengthOfLineContainingPos(long pos
) const
1607 return ::SendMessage(GetHwnd(), EM_LINELENGTH
, pos
, 0);
1610 int wxTextCtrl::GetLineLength(long lineNo
) const
1612 long pos
= XYToPosition(0, lineNo
);
1614 return GetLengthOfLineContainingPos(pos
);
1617 wxString
wxTextCtrl::GetLineText(long lineNo
) const
1619 size_t len
= (size_t)GetLineLength(lineNo
) + 1;
1621 // there must be at least enough place for the length WORD in the
1623 len
+= sizeof(WORD
);
1627 wxStringBufferLength
tmp(str
, len
);
1630 *(WORD
*)buf
= (WORD
)len
;
1631 len
= (size_t)::SendMessage(GetHwnd(), EM_GETLINE
, lineNo
, (LPARAM
)buf
);
1636 // remove the '\r' returned by the rich edit control, the user code
1637 // should never see it
1638 if ( buf
[len
- 2] == wxT('\r') && buf
[len
- 1] == wxT('\n') )
1640 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1641 // here and "\n" below
1642 buf
[len
- 2] = wxT('\n');
1645 else if ( buf
[len
- 1] == wxT('\r') )
1647 // richedit 2.0+ uses only "\r", replace it with "\n"
1648 buf
[len
- 1] = wxT('\n');
1651 #endif // wxUSE_RICHEDIT
1653 // remove the '\n' at the end, if any (this is how this function is
1654 // supposed to work according to the docs)
1655 if ( buf
[len
- 1] == wxT('\n') )
1667 void wxTextCtrl::SetMaxLength(unsigned long len
)
1672 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT
, 0, len
? len
: 0x7fffffff);
1675 #endif // wxUSE_RICHEDIT
1677 wxTextEntry::SetMaxLength(len
);
1681 // ----------------------------------------------------------------------------
1683 // ----------------------------------------------------------------------------
1685 void wxTextCtrl::Redo()
1688 if ( GetRichVersion() > 1 )
1690 ::SendMessage(GetHwnd(), EM_REDO
, 0, 0);
1693 #endif // wxUSE_RICHEDIT
1695 wxTextEntry::Redo();
1698 bool wxTextCtrl::CanRedo() const
1701 if ( GetRichVersion() > 1 )
1702 return ::SendMessage(GetHwnd(), EM_CANREDO
, 0, 0) != 0;
1703 #endif // wxUSE_RICHEDIT
1705 return wxTextEntry::CanRedo();
1708 // ----------------------------------------------------------------------------
1709 // caret handling (Windows only)
1710 // ----------------------------------------------------------------------------
1712 bool wxTextCtrl::ShowNativeCaret(bool show
)
1714 if ( show
!= m_isNativeCaretShown
)
1716 if ( !(show
? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1718 // not an error, may simply indicate that it's not shown/hidden
1719 // yet (i.e. it had been hidden/shown 2 times before)
1723 m_isNativeCaretShown
= show
;
1729 // ----------------------------------------------------------------------------
1730 // implementation details
1731 // ----------------------------------------------------------------------------
1733 void wxTextCtrl::Command(wxCommandEvent
& event
)
1735 SetValue(event
.GetString());
1736 ProcessCommand (event
);
1739 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
1741 // By default, load the first file into the text window.
1742 if (event
.GetNumberOfFiles() > 0)
1744 LoadFile(event
.GetFiles()[0]);
1748 // ----------------------------------------------------------------------------
1749 // kbd input processing
1750 // ----------------------------------------------------------------------------
1752 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1754 // check for our special keys here: if we don't do it and the parent frame
1755 // uses them as accelerators, they wouldn't work at all, so we disable
1756 // usual preprocessing for them
1757 if ( msg
->message
== WM_KEYDOWN
)
1759 const WPARAM vkey
= msg
->wParam
;
1760 if ( HIWORD(msg
->lParam
) & KF_ALTDOWN
)
1762 // Alt-Backspace is accelerator for "Undo"
1763 if ( vkey
== VK_BACK
)
1768 // we want to process some Ctrl-foo and Shift-bar but no key
1769 // combinations without either Ctrl or Shift nor with both of them
1771 const int ctrl
= wxIsCtrlDown(),
1772 shift
= wxIsShiftDown();
1773 switch ( ctrl
+ shift
)
1776 wxFAIL_MSG( wxT("how many modifiers have we got?") );
1783 // This one is only special for multi line controls.
1784 if ( !IsMultiLine() )
1798 // either Ctrl or Shift pressed
1813 else // Shift is pressed
1815 if ( vkey
== VK_INSERT
|| vkey
== VK_DELETE
)
1822 return wxControl::MSWShouldPreProcessMessage(msg
);
1825 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
1827 switch ( event
.GetKeyCode() )
1831 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
, m_windowId
);
1832 InitCommandEvent(event
);
1833 event
.SetString(GetValue());
1834 if ( HandleWindowEvent(event
) )
1835 if ( !HasFlag(wxTE_MULTILINE
) )
1837 //else: multiline controls need Enter for themselves
1842 // ok, so this is getting absolutely ridiculous but I don't see
1843 // any other way to fix this bug: when a multiline text control is
1844 // inside a wxFrame, we need to generate the navigation event as
1845 // otherwise nothing happens at all, but when the same control is
1846 // created inside a dialog, IsDialogMessage() *does* switch focus
1847 // all by itself and so if we do it here as well, it is advanced
1848 // twice and goes to the next control... to prevent this from
1849 // happening we're doing this ugly check, the logic being that if
1850 // we don't have focus then it had been already changed to the next
1853 // the right thing to do would, of course, be to understand what
1854 // the hell is IsDialogMessage() doing but this is beyond my feeble
1855 // forces at the moment unfortunately
1856 if ( !(m_windowStyle
& wxTE_PROCESS_TAB
))
1858 if ( FindFocus() == this )
1861 if (!event
.ShiftDown())
1862 flags
|= wxNavigationKeyEvent::IsForward
;
1863 if (event
.ControlDown())
1864 flags
|= wxNavigationKeyEvent::WinChange
;
1865 if (Navigate(flags
))
1871 // Insert tab since calling the default Windows handler
1872 // doesn't seem to do it
1873 WriteText(wxT("\t"));
1879 // no, we didn't process it
1883 void wxTextCtrl::OnKeyDown(wxKeyEvent
& event
)
1885 // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages
1886 // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent
1887 // from working. So we work around it by intercepting these shortcuts
1888 // ourselves and emitting clipboard events (which richedit will handle,
1889 // so everything works as before, including pasting of rich text):
1890 if ( event
.GetModifiers() == wxMOD_CONTROL
&& IsRich() )
1892 switch ( event
.GetKeyCode() )
1908 // Default window procedure of multiline edit controls posts WM_CLOSE to
1909 // the parent window when it gets Escape key press for some reason, prevent
1910 // it from doing this as this resulted in dialog boxes being closed on
1911 // Escape even when they shouldn't be (we do handle Escape ourselves
1912 // correctly in the situations when it should close them).
1913 if ( event
.GetKeyCode() == WXK_ESCAPE
&& IsMultiLine() )
1916 // no, we didn't process it
1920 WXLRESULT
wxTextCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1922 WXLRESULT lRc
= wxTextCtrlBase::MSWWindowProc(nMsg
, wParam
, lParam
);
1928 // we always want the chars and the arrows: the arrows for
1929 // navigation and the chars because we want Ctrl-C to work even
1930 // in a read only control
1931 long lDlgCode
= DLGC_WANTCHARS
| DLGC_WANTARROWS
;
1935 // we may have several different cases:
1936 // 1. normal: both TAB and ENTER are used for navigation
1937 // 2. ctrl wants TAB for itself: ENTER is used to pass to
1938 // the next control in the dialog
1939 // 3. ctrl wants ENTER for itself: TAB is used for dialog
1941 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
1942 // go to the next control (we need some way to do it)
1944 // multiline controls should always get ENTER for themselves
1945 if ( HasFlag(wxTE_PROCESS_ENTER
) || HasFlag(wxTE_MULTILINE
) )
1946 lDlgCode
|= DLGC_WANTMESSAGE
;
1948 if ( HasFlag(wxTE_PROCESS_TAB
) )
1949 lDlgCode
|= DLGC_WANTTAB
;
1955 // NB: use "=", not "|=" as the base class version returns
1956 // the same flags in the disabled state as usual (i.e.
1957 // including DLGC_WANTMESSAGE). This is strange (how
1958 // does it work in the native Win32 apps?) but for now
1963 // Clear the DLGC_HASSETSEL bit from the return value
1964 lRc
&= ~DLGC_HASSETSEL
;
1970 // rich text controls seem to have a bug and don't change the
1971 // cursor to the standard arrow one from the I-beam cursor usually
1972 // used by them even when a popup menu is shown (this works fine
1973 // for plain EDIT controls though), so explicitly work around this
1976 extern wxMenu
*wxCurrentPopupMenu
;
1977 if ( wxCurrentPopupMenu
&&
1978 wxCurrentPopupMenu
->GetInvokingWindow() == this )
1979 ::SetCursor(GetHcursorOf(*wxSTANDARD_CURSOR
));
1981 #endif // wxUSE_MENUS
1987 // ----------------------------------------------------------------------------
1988 // text control event processing
1989 // ----------------------------------------------------------------------------
1991 bool wxTextCtrl::SendUpdateEvent()
1993 switch ( m_updatesCount
)
1996 // remember that we've got an update
2001 // we had already sent one event since the last control modification
2005 wxFAIL_MSG( wxT("unexpected wxTextCtrl::m_updatesCount value") );
2009 // we hadn't updated the control ourselves, this event comes from
2010 // the user, don't need to ignore it nor update the count
2014 // the control was updated programmatically and we do NOT want to
2019 return SendTextUpdatedEvent();
2022 bool wxTextCtrl::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
2031 // the text size limit has been hit -- try to increase it
2032 if ( !AdjustSpaceLimit() )
2034 wxCommandEvent
event(wxEVT_COMMAND_TEXT_MAXLEN
, m_windowId
);
2035 InitCommandEvent(event
);
2036 event
.SetString(GetValue());
2037 ProcessCommand(event
);
2041 // the other edit notification messages are not processed (or, in
2042 // the case of EN_{SET/KILL}FOCUS were already handled at WM_SET/
2052 WXHBRUSH
wxTextCtrl::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
2054 if ( !IsThisEnabled() && !HasFlag(wxTE_MULTILINE
) )
2055 return MSWControlColorDisabled(hDC
);
2057 return wxTextCtrlBase::MSWControlColor(hDC
, hWnd
);
2060 bool wxTextCtrl::HasSpaceLimit(unsigned int *len
) const
2062 // HACK: we try to automatically extend the limit for the amount of text
2063 // to allow (interactively) entering more than 64Kb of text under
2064 // Win9x but we shouldn't reset the text limit which was previously
2065 // set explicitly with SetMaxLength()
2067 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2068 // know the limit we set (if any). We could solve this by storing the
2069 // limit we set in wxTextCtrl but to save space we prefer to simply
2070 // test here the actual limit value: we consider that SetMaxLength()
2071 // can only be called for small values while EN_MAXTEXT is only sent
2072 // for large values (in practice the default limit seems to be 30000
2073 // but make it smaller just to be on the safe side)
2074 *len
= ::SendMessage(GetHwnd(), EM_GETLIMITTEXT
, 0, 0);
2075 return *len
< 10001;
2079 bool wxTextCtrl::AdjustSpaceLimit()
2082 if ( HasSpaceLimit(&limit
) )
2085 unsigned int len
= ::GetWindowTextLength(GetHwnd());
2088 // increment in 32Kb chunks
2089 SetMaxLength(len
+ 0x8000);
2092 // we changed the limit
2096 bool wxTextCtrl::AcceptsFocusFromKeyboard() const
2098 // we don't want focus if we can't be edited unless we're a multiline
2099 // control because then it might be still nice to get focus from keyboard
2100 // to be able to scroll it without mouse
2101 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2104 wxSize
wxTextCtrl::DoGetBestSize() const
2106 return DoGetSizeFromTextSize( DEFAULT_ITEM_WIDTH
);
2109 wxSize
wxTextCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
2112 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
2115 ::SystemParametersInfo(SPI_GETCARETWIDTH
, 0, &wText
, 0);
2119 if ( m_windowStyle
& wxTE_MULTILINE
)
2121 // add space for vertical scrollbar
2122 if ( !(m_windowStyle
& wxTE_NO_VSCROLL
) )
2123 wText
+= ::GetSystemMetrics(SM_CXVSCROLL
);
2127 hText
*= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2128 // add space for horizontal scrollbar
2129 if ( m_windowStyle
& wxHSCROLL
)
2130 hText
+= ::GetSystemMetrics(SM_CYHSCROLL
);
2133 // for single line control cy (height + external leading) is ok
2136 // Add the margins we have previously set
2137 wxPoint
marg( GetMargins() );
2138 wText
+= wxMax(0, marg
.x
);
2139 hText
+= wxMax(0, marg
.y
);
2142 // Text controls without border are special and have the same height as
2143 // static labels (they also have the same appearance when they're disable
2144 // and are often used as a sort of copyable to the clipboard label so it's
2145 // important that they have the same height as the normal labels to not
2147 if ( !HasFlag(wxBORDER_NONE
) )
2149 wText
+= 9; // borders and inner margins
2151 // we have to add the adjustments for the control height only once, not
2152 // once per line, so do it after multiplication above
2153 hText
+= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
) - cy
;
2156 // Perhaps the user wants something different from CharHeight, or ylen
2157 // is used as the height of a multiline text.
2159 hText
+= ylen
- GetCharHeight();
2161 return wxSize(wText
, hText
);
2164 // ----------------------------------------------------------------------------
2165 // standard handlers for standard edit menu events
2166 // ----------------------------------------------------------------------------
2168 void wxTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
2173 void wxTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
2178 void wxTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
2183 void wxTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
2188 void wxTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
2193 void wxTextCtrl::OnDelete(wxCommandEvent
& WXUNUSED(event
))
2198 void wxTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
2203 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
2205 event
.Enable( CanCut() );
2208 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
2210 event
.Enable( CanCopy() );
2213 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
2215 event
.Enable( CanPaste() );
2218 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
2220 event
.Enable( CanUndo() );
2223 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
2225 event
.Enable( CanRedo() );
2228 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent
& event
)
2230 event
.Enable( HasSelection() && IsEditable() );
2233 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
2235 event
.Enable( !IsEmpty() );
2238 void wxTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
2243 if (!m_privateContextMenu
)
2245 m_privateContextMenu
= new wxMenu
;
2246 m_privateContextMenu
->Append(wxID_UNDO
, _("&Undo"));
2247 m_privateContextMenu
->Append(wxID_REDO
, _("&Redo"));
2248 m_privateContextMenu
->AppendSeparator();
2249 m_privateContextMenu
->Append(wxID_CUT
, _("Cu&t"));
2250 m_privateContextMenu
->Append(wxID_COPY
, _("&Copy"));
2251 m_privateContextMenu
->Append(wxID_PASTE
, _("&Paste"));
2252 m_privateContextMenu
->Append(wxID_CLEAR
, _("&Delete"));
2253 m_privateContextMenu
->AppendSeparator();
2254 m_privateContextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
2256 PopupMenu(m_privateContextMenu
);
2264 void wxTextCtrl::OnSetFocus(wxFocusEvent
& event
)
2266 // be sure the caret remains invisible if the user had hidden it
2267 if ( !m_isNativeCaretShown
)
2269 ::HideCaret(GetHwnd());
2275 // the rest of the file only deals with the rich edit controls
2278 // ----------------------------------------------------------------------------
2279 // EN_LINK processing
2280 // ----------------------------------------------------------------------------
2282 bool wxTextCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2284 NMHDR
*hdr
= (NMHDR
* )lParam
;
2285 switch ( hdr
->code
)
2289 const MSGFILTER
*msgf
= (MSGFILTER
*)lParam
;
2290 UINT msg
= msgf
->msg
;
2292 // this is a bit crazy but richedit 1.0 sends us all mouse
2293 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2294 // generate the wxWin events for this message manually
2296 // NB: in fact, this is still not totally correct as it does
2297 // send us WM_LBUTTONUP if the selection was cleared by the
2298 // last click -- so currently we get 2 events in this case,
2299 // but as I don't see any obvious way to check for this I
2300 // leave this code in place because it's still better than
2301 // not getting left up events at all
2302 if ( msg
== WM_LBUTTONUP
)
2304 WXUINT flags
= msgf
->wParam
;
2305 int x
= GET_X_LPARAM(msgf
->lParam
),
2306 y
= GET_Y_LPARAM(msgf
->lParam
);
2308 HandleMouseEvent(msg
, x
, y
, flags
);
2312 // return true to process the event (and false to ignore it)
2317 const ENLINK
*enlink
= (ENLINK
*)hdr
;
2319 switch ( enlink
->msg
)
2322 // ok, so it is hardcoded - do we really nee to
2325 wxCursor
cur(wxCURSOR_HAND
);
2326 ::SetCursor(GetHcursorOf(cur
));
2332 case WM_LBUTTONDOWN
:
2334 case WM_LBUTTONDBLCLK
:
2335 case WM_RBUTTONDOWN
:
2337 case WM_RBUTTONDBLCLK
:
2338 // send a mouse event
2340 static const wxEventType eventsMouse
[] =
2351 // the event ids are consecutive
2353 evtMouse(eventsMouse
[enlink
->msg
- WM_MOUSEMOVE
]);
2355 InitMouseEvent(evtMouse
,
2356 GET_X_LPARAM(enlink
->lParam
),
2357 GET_Y_LPARAM(enlink
->lParam
),
2360 wxTextUrlEvent
event(m_windowId
, evtMouse
,
2362 enlink
->chrg
.cpMax
);
2364 InitCommandEvent(event
);
2366 *result
= ProcessCommand(event
);
2374 // not processed, leave it to the base class
2375 return wxTextCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
2378 #if wxUSE_DRAG_AND_DROP
2380 void wxTextCtrl::SetDropTarget(wxDropTarget
*dropTarget
)
2382 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
2384 // get rid of the built-in drop target
2385 ::RevokeDragDrop(GetHwnd());
2386 m_dropTarget
= NULL
;
2389 wxTextCtrlBase::SetDropTarget(dropTarget
);
2392 #endif // wxUSE_DRAG_AND_DROP
2394 // ----------------------------------------------------------------------------
2395 // colour setting for the rich edit controls
2396 // ----------------------------------------------------------------------------
2398 bool wxTextCtrl::SetBackgroundColour(const wxColour
& colour
)
2400 if ( !wxTextCtrlBase::SetBackgroundColour(colour
) )
2402 // colour didn't really change
2408 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2409 // EM_SETBKGNDCOLOR additionally
2410 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR
, 0, wxColourToRGB(colour
));
2416 bool wxTextCtrl::SetForegroundColour(const wxColour
& colour
)
2418 if ( !wxTextCtrlBase::SetForegroundColour(colour
) )
2420 // colour didn't really change
2426 // change the colour of everything
2427 WinStruct
<CHARFORMAT
> cf
;
2428 cf
.dwMask
= CFM_COLOR
;
2429 cf
.crTextColor
= wxColourToRGB(colour
);
2430 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, SCF_ALL
, (LPARAM
)&cf
);
2436 bool wxTextCtrl::SetFont(const wxFont
& font
)
2438 if ( !wxTextCtrlBase::SetFont(font
) )
2441 if ( GetRichVersion() >= 4 )
2443 // Using WM_SETFONT is not enough with RichEdit 4.1: it does work but
2444 // for ASCII characters only and inserting a non-ASCII one into it
2445 // later reverts to the default font so use EM_SETCHARFORMAT to change
2446 // the default font for it.
2449 SetStyle(-1, -1, attr
);
2455 // ----------------------------------------------------------------------------
2456 // styling support for rich edit controls
2457 // ----------------------------------------------------------------------------
2459 bool wxTextCtrl::MSWSetCharFormat(const wxTextAttr
& style
, long start
, long end
)
2461 // initialize CHARFORMAT struct
2470 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2471 // CHARFORMAT in that case
2473 if ( m_verRichEdit
== 1 )
2475 // this is the only thing the control is going to grok
2476 cf
.cbSize
= sizeof(CHARFORMAT
);
2481 // CHARFORMAT or CHARFORMAT2
2482 cf
.cbSize
= sizeof(cf
);
2485 if ( style
.HasFont() )
2487 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2488 // but using it doesn't seem to hurt neither so leaving it for now
2490 cf
.dwMask
|= CFM_FACE
| CFM_SIZE
| CFM_CHARSET
|
2491 CFM_ITALIC
| CFM_BOLD
| CFM_UNDERLINE
;
2493 // fill in data from LOGFONT but recalculate lfHeight because we need
2494 // the real height in twips and not the negative number which
2495 // wxFillLogFont() returns (this is correct in general and works with
2496 // the Windows font mapper, but not here)
2498 wxFont
font(style
.GetFont());
2501 wxFillLogFont(&lf
, &font
);
2502 cf
.yHeight
= 20*font
.GetPointSize(); // 1 pt = 20 twips
2503 cf
.bCharSet
= lf
.lfCharSet
;
2504 cf
.bPitchAndFamily
= lf
.lfPitchAndFamily
;
2505 wxStrlcpy(cf
.szFaceName
, lf
.lfFaceName
, WXSIZEOF(cf
.szFaceName
));
2507 // also deal with underline/italic/bold attributes: note that we must
2508 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2509 // style to allow clearing it
2512 cf
.dwEffects
|= CFE_ITALIC
;
2515 if ( lf
.lfWeight
== FW_BOLD
)
2517 cf
.dwEffects
|= CFE_BOLD
;
2520 if ( lf
.lfUnderline
)
2522 cf
.dwEffects
|= CFE_UNDERLINE
;
2525 // strikeout fonts are not supported by wxWidgets
2528 if ( style
.HasTextColour() )
2530 cf
.dwMask
|= CFM_COLOR
;
2531 cf
.crTextColor
= wxColourToRGB(style
.GetTextColour());
2535 if ( m_verRichEdit
!= 1 && style
.HasBackgroundColour() )
2537 cf
.dwMask
|= CFM_BACKCOLOR
;
2538 cf
.crBackColor
= wxColourToRGB(style
.GetBackgroundColour());
2540 #endif // wxUSE_RICHEDIT2
2542 // Apply the style either to the selection or to the entire control.
2544 if ( start
!= -1 || end
!= -1 )
2546 DoSetSelection(start
, end
, SetSel_NoScroll
);
2547 selMode
= SCF_SELECTION
;
2554 if ( !::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, selMode
, (LPARAM
)&cf
) )
2556 wxLogLastError(wxT("SendMessage(EM_SETCHARFORMAT)"));
2563 bool wxTextCtrl::MSWSetParaFormat(const wxTextAttr
& style
, long start
, long end
)
2573 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2574 // PARAFORMAT in that case
2576 if ( m_verRichEdit
== 1 )
2578 // this is the only thing the control is going to grok
2579 pf
.cbSize
= sizeof(PARAFORMAT
);
2584 // PARAFORMAT or PARAFORMAT2
2585 pf
.cbSize
= sizeof(pf
);
2588 if (style
.HasAlignment())
2590 pf
.dwMask
|= PFM_ALIGNMENT
;
2591 if (style
.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
2592 pf
.wAlignment
= PFA_RIGHT
;
2593 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
2594 pf
.wAlignment
= PFA_CENTER
;
2595 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED
)
2596 pf
.wAlignment
= PFA_JUSTIFY
;
2598 pf
.wAlignment
= PFA_LEFT
;
2601 if (style
.HasLeftIndent())
2603 pf
.dwMask
|= PFM_STARTINDENT
| PFM_OFFSET
;
2605 // Convert from 1/10 mm to TWIPS
2606 pf
.dxStartIndent
= (int) (((double) style
.GetLeftIndent()) * mm2twips
/ 10.0) ;
2607 pf
.dxOffset
= (int) (((double) style
.GetLeftSubIndent()) * mm2twips
/ 10.0) ;
2610 if (style
.HasRightIndent())
2612 pf
.dwMask
|= PFM_RIGHTINDENT
;
2614 // Convert from 1/10 mm to TWIPS
2615 pf
.dxRightIndent
= (int) (((double) style
.GetRightIndent()) * mm2twips
/ 10.0) ;
2618 if (style
.HasTabs())
2620 pf
.dwMask
|= PFM_TABSTOPS
;
2622 const wxArrayInt
& tabs
= style
.GetTabs();
2624 pf
.cTabCount
= (SHORT
)wxMin(tabs
.GetCount(), MAX_TAB_STOPS
);
2626 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2628 // Convert from 1/10 mm to TWIPS
2629 pf
.rgxTabs
[i
] = (int) (((double) tabs
[i
]) * mm2twips
/ 10.0) ;
2634 if ( m_verRichEdit
> 1 )
2636 if ( wxTheApp
->GetLayoutDirection() == wxLayout_RightToLeft
)
2638 // Use RTL paragraphs in RTL mode to get proper layout
2639 pf
.dwMask
|= PFM_RTLPARA
;
2640 pf
.wEffects
|= PFE_RTLPARA
;
2643 #endif // wxUSE_RICHEDIT2
2647 // Do format the selection.
2648 DoSetSelection(start
, end
, SetSel_NoScroll
);
2650 if ( !::SendMessage(GetHwnd(), EM_SETPARAFORMAT
, 0, (LPARAM
) &pf
) )
2652 wxLogLastError(wxT("SendMessage(EM_SETPARAFORMAT)"));
2661 bool wxTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
2665 // can't do it with normal text control
2669 // the richedit 1.0 doesn't handle setting background colour, so don't
2670 // even try to do anything if it's the only thing we want to change
2671 if ( m_verRichEdit
== 1 && !style
.HasFont() && !style
.HasTextColour() &&
2672 !style
.HasLeftIndent() && !style
.HasRightIndent() && !style
.HasAlignment() &&
2675 // nothing to do: return true if there was really nothing to do and
2676 // false if we failed to set bg colour
2677 return !style
.HasBackgroundColour();
2680 // order the range if needed
2684 // we can only change the format of the selection, so select the range we
2685 // want and restore the old selection later, after MSWSetXXXFormat()
2686 // functions (possibly) change it.
2687 long startOld
, endOld
;
2688 GetSelection(&startOld
, &endOld
);
2690 bool ok
= MSWSetCharFormat(style
, start
, end
);
2691 if ( !MSWSetParaFormat(style
, start
, end
) )
2694 if ( start
!= startOld
|| end
!= endOld
)
2696 // restore the original selection
2697 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2703 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
2705 if ( !wxTextCtrlBase::SetDefaultStyle(style
) )
2710 // we have to do this or the style wouldn't apply for the text typed by
2712 wxTextPos posLast
= GetLastPosition();
2713 SetStyle(posLast
, posLast
, m_defaultStyle
);
2719 bool wxTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
2723 // can't do it with normal text control
2727 // initialize CHARFORMAT struct
2736 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2737 // CHARFORMAT in that case
2739 if ( m_verRichEdit
== 1 )
2741 // this is the only thing the control is going to grok
2742 cf
.cbSize
= sizeof(CHARFORMAT
);
2747 // CHARFORMAT or CHARFORMAT2
2748 cf
.cbSize
= sizeof(cf
);
2750 // we can only change the format of the selection, so select the range we
2751 // want and restore the old selection later
2752 long startOld
, endOld
;
2753 GetSelection(&startOld
, &endOld
);
2755 // but do we really have to change the selection?
2756 bool changeSel
= position
!= startOld
|| position
!= endOld
;
2760 DoSetSelection(position
, position
+ 1, SetSel_NoScroll
);
2763 // get the selection formatting
2764 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT
,
2765 SCF_SELECTION
, (LPARAM
)&cf
) ;
2769 // Convert the height from the units of 1/20th of the point in which
2770 // CHARFORMAT stores it to pixel-based units used by LOGFONT.
2771 const wxCoord ppi
= wxClientDC(this).GetPPI().y
;
2772 lf
.lfHeight
= -MulDiv(cf
.yHeight
/20, ppi
, 72);
2774 lf
.lfCharSet
= ANSI_CHARSET
; // FIXME: how to get correct charset?
2775 lf
.lfClipPrecision
= 0;
2776 lf
.lfEscapement
= 0;
2777 wxStrcpy(lf
.lfFaceName
, cf
.szFaceName
);
2779 //NOTE: we _MUST_ set each of these values to _something_ since we
2780 //do not call wxZeroMemory on the LOGFONT lf
2781 if (cf
.dwEffects
& CFE_ITALIC
)
2784 lf
.lfItalic
= FALSE
;
2786 lf
.lfOrientation
= 0;
2787 lf
.lfPitchAndFamily
= cf
.bPitchAndFamily
;
2790 if (cf
.dwEffects
& CFE_STRIKEOUT
)
2791 lf
.lfStrikeOut
= TRUE
;
2793 lf
.lfStrikeOut
= FALSE
;
2795 if (cf
.dwEffects
& CFE_UNDERLINE
)
2796 lf
.lfUnderline
= TRUE
;
2798 lf
.lfUnderline
= FALSE
;
2800 if (cf
.dwEffects
& CFE_BOLD
)
2801 lf
.lfWeight
= FW_BOLD
;
2803 lf
.lfWeight
= FW_NORMAL
;
2805 wxFont font
= wxCreateFontFromLogFont(& lf
);
2808 style
.SetFont(font
);
2810 style
.SetTextColour(wxColour(cf
.crTextColor
));
2813 if ( m_verRichEdit
!= 1 )
2815 // cf.dwMask |= CFM_BACKCOLOR;
2816 style
.SetBackgroundColour(wxColour(cf
.crBackColor
));
2818 #endif // wxUSE_RICHEDIT2
2820 // now get the paragraph formatting
2823 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2824 // PARAFORMAT in that case
2826 if ( m_verRichEdit
== 1 )
2828 // this is the only thing the control is going to grok
2829 pf
.cbSize
= sizeof(PARAFORMAT
);
2834 // PARAFORMAT or PARAFORMAT2
2835 pf
.cbSize
= sizeof(pf
);
2838 // do format the selection
2839 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT
, 0, (LPARAM
) &pf
) ;
2841 style
.SetLeftIndent( (int) ((double) pf
.dxStartIndent
* twips2mm
* 10.0), (int) ((double) pf
.dxOffset
* twips2mm
* 10.0) );
2842 style
.SetRightIndent( (int) ((double) pf
.dxRightIndent
* twips2mm
* 10.0) );
2844 if (pf
.wAlignment
== PFA_CENTER
)
2845 style
.SetAlignment(wxTEXT_ALIGNMENT_CENTRE
);
2846 else if (pf
.wAlignment
== PFA_RIGHT
)
2847 style
.SetAlignment(wxTEXT_ALIGNMENT_RIGHT
);
2848 else if (pf
.wAlignment
== PFA_JUSTIFY
)
2849 style
.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED
);
2851 style
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
2853 wxArrayInt tabStops
;
2855 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2857 tabStops
.Add( (int) ((double) (pf
.rgxTabs
[i
] & 0xFFFF) * twips2mm
* 10.0) );
2862 // restore the original selection
2863 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2869 // ----------------------------------------------------------------------------
2871 // ----------------------------------------------------------------------------
2873 static const HINSTANCE INVALID_HINSTANCE
= (HINSTANCE
)-1;
2875 bool wxRichEditModule::OnInit()
2877 // don't do anything - we will load it when needed
2881 void wxRichEditModule::OnExit()
2883 for ( size_t i
= 0; i
< WXSIZEOF(ms_hRichEdit
); i
++ )
2885 if ( ms_hRichEdit
[i
] && ms_hRichEdit
[i
] != INVALID_HINSTANCE
)
2887 ::FreeLibrary(ms_hRichEdit
[i
]);
2888 ms_hRichEdit
[i
] = NULL
;
2892 if (ms_inkEditLib
.IsLoaded())
2893 ms_inkEditLib
.Unload();
2898 bool wxRichEditModule::Load(Version version
)
2900 if ( ms_hRichEdit
[version
] == INVALID_HINSTANCE
)
2902 // we had already tried to load it and failed
2906 if ( ms_hRichEdit
[version
] )
2908 // we've already got this one
2912 static const wxChar
*const dllnames
[] =
2919 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames
) == Version_Max
,
2920 RichEditDllNamesVersionsMismatch
);
2922 ms_hRichEdit
[version
] = ::LoadLibrary(dllnames
[version
]);
2924 if ( !ms_hRichEdit
[version
] )
2926 ms_hRichEdit
[version
] = INVALID_HINSTANCE
;
2935 // load the InkEdit library
2936 bool wxRichEditModule::LoadInkEdit()
2938 if (ms_inkEditLibLoadAttemped
)
2939 return ms_inkEditLib
.IsLoaded();
2941 ms_inkEditLibLoadAttemped
= true;
2944 return ms_inkEditLib
.Load(wxT("inked"));
2946 #endif // wxUSE_INKEDIT
2949 #endif // wxUSE_RICHEDIT
2951 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)