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>
68 #include "wx/dynlib.h"
71 // old mingw32 has richedit stuff directly in windows.h and doesn't have
73 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
77 #endif // wxUSE_RICHEDIT
79 #include "wx/msw/missing.h"
81 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
83 // dummy value used for m_dropTarget, different from any valid pointer value
84 // (which are all even under Windows) and NULL
86 wxRICHTEXT_DEFAULT_DROPTARGET
= reinterpret_cast<wxDropTarget
*>(1);
88 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
96 // this module initializes RichEdit DLL(s) if needed
97 class wxRichEditModule
: public wxModule
102 Version_1
, // riched32.dll
103 Version_2or3
, // both use riched20.dll
104 Version_41
, // msftedit.dll (XP SP1 and Windows 2003)
108 virtual bool OnInit();
109 virtual void OnExit();
111 // load the richedit DLL for the specified version of rich edit
112 static bool Load(Version version
);
115 // load the InkEdit library
116 static bool LoadInkEdit();
120 // the handles to richedit 1.0 and 2.0 (or 3.0) DLLs
121 static HINSTANCE ms_hRichEdit
[Version_Max
];
124 static wxDynamicLibrary ms_inkEditLib
;
125 static bool ms_inkEditLibLoadAttemped
;
128 DECLARE_DYNAMIC_CLASS(wxRichEditModule
)
131 HINSTANCE
wxRichEditModule::ms_hRichEdit
[Version_Max
] = { NULL
, NULL
, NULL
};
134 wxDynamicLibrary
wxRichEditModule::ms_inkEditLib
;
135 bool wxRichEditModule::ms_inkEditLibLoadAttemped
= false;
138 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule
, wxModule
)
140 #endif // wxUSE_RICHEDIT
142 // a small class used to set m_updatesCount to 0 (to filter duplicate events if
143 // necessary) and to reset it back to -1 afterwards
144 class UpdatesCountFilter
147 UpdatesCountFilter(int& count
)
150 wxASSERT_MSG( m_count
== -1 || m_count
== -2,
151 wxT("wrong initial m_updatesCount value") );
155 //else: we don't want to count how many update events we get as we're going
156 // to ignore all of them
159 ~UpdatesCountFilter()
164 // return true if an event has been received
165 bool GotUpdate() const
173 wxDECLARE_NO_COPY_CLASS(UpdatesCountFilter
);
176 // ----------------------------------------------------------------------------
177 // event tables and other macros
178 // ----------------------------------------------------------------------------
180 BEGIN_EVENT_TABLE(wxTextCtrl
, wxTextCtrlBase
)
181 EVT_CHAR(wxTextCtrl::OnChar
)
182 EVT_KEY_DOWN(wxTextCtrl::OnKeyDown
)
183 EVT_DROP_FILES(wxTextCtrl::OnDropFiles
)
186 EVT_CONTEXT_MENU(wxTextCtrl::OnContextMenu
)
189 EVT_MENU(wxID_CUT
, wxTextCtrl::OnCut
)
190 EVT_MENU(wxID_COPY
, wxTextCtrl::OnCopy
)
191 EVT_MENU(wxID_PASTE
, wxTextCtrl::OnPaste
)
192 EVT_MENU(wxID_UNDO
, wxTextCtrl::OnUndo
)
193 EVT_MENU(wxID_REDO
, wxTextCtrl::OnRedo
)
194 EVT_MENU(wxID_CLEAR
, wxTextCtrl::OnDelete
)
195 EVT_MENU(wxID_SELECTALL
, wxTextCtrl::OnSelectAll
)
197 EVT_UPDATE_UI(wxID_CUT
, wxTextCtrl::OnUpdateCut
)
198 EVT_UPDATE_UI(wxID_COPY
, wxTextCtrl::OnUpdateCopy
)
199 EVT_UPDATE_UI(wxID_PASTE
, wxTextCtrl::OnUpdatePaste
)
200 EVT_UPDATE_UI(wxID_UNDO
, wxTextCtrl::OnUpdateUndo
)
201 EVT_UPDATE_UI(wxID_REDO
, wxTextCtrl::OnUpdateRedo
)
202 EVT_UPDATE_UI(wxID_CLEAR
, wxTextCtrl::OnUpdateDelete
)
203 EVT_UPDATE_UI(wxID_SELECTALL
, wxTextCtrl::OnUpdateSelectAll
)
205 EVT_SET_FOCUS(wxTextCtrl::OnSetFocus
)
208 // ============================================================================
210 // ============================================================================
212 // ----------------------------------------------------------------------------
214 // ----------------------------------------------------------------------------
216 void wxTextCtrl::Init()
220 #endif // wxUSE_RICHEDIT
222 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
226 m_privateContextMenu
= NULL
;
228 m_isNativeCaretShown
= true;
231 wxTextCtrl::~wxTextCtrl()
233 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
234 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
236 // don't try to destroy this dummy pointer in the base class dtor
239 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
241 delete m_privateContextMenu
;
244 bool wxTextCtrl::Create(wxWindow
*parent
,
246 const wxString
& value
,
250 const wxValidator
& validator
,
251 const wxString
& name
)
253 // base initialization
254 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
257 if ( !MSWCreateText(value
, pos
, size
) )
260 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
263 // rich text controls have a default associated drop target which
264 // allows them to receive (rich) text dropped on them, which is nice,
265 // but prevents us from associating a user-defined drop target with
266 // them as we need to unregister the old one first
268 // to make it work, we set m_dropTarget to this special value initially
269 // and check for it in our SetDropTarget()
270 m_dropTarget
= wxRICHTEXT_DEFAULT_DROPTARGET
;
272 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
277 // returns true if the platform should explicitly apply a theme border
278 bool wxTextCtrl::CanApplyThemeBorder() const
283 // Standard text control already handles theming
284 return ((GetWindowStyle() & (wxTE_RICH
|wxTE_RICH2
)) != 0);
288 bool wxTextCtrl::MSWCreateText(const wxString
& value
,
292 // translate wxWin style flags to MSW ones
293 WXDWORD msStyle
= MSWGetCreateWindowFlags();
295 // do create the control - either an EDIT or RICHEDIT
296 wxString windowClass
= wxT("EDIT");
298 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
299 // A control that capitalizes the first letter
300 if ( HasFlag(wxTE_CAPITALIZE
) )
301 windowClass
= wxT("CAPEDIT");
305 if ( m_windowStyle
& wxTE_AUTO_URL
)
307 // automatic URL detection only works in RichEdit 2.0+
308 m_windowStyle
|= wxTE_RICH2
;
311 if ( m_windowStyle
& wxTE_RICH2
)
313 // using richedit 2.0 implies using wxTE_RICH
314 m_windowStyle
|= wxTE_RICH
;
317 // we need to load the richedit DLL before creating the rich edit control
318 if ( m_windowStyle
& wxTE_RICH
)
320 // versions 2.0, 3.0 and 4.1 of rich edit are mostly compatible with
321 // each other but not with version 1.0, so we have separate flags for
322 // the version 1.0 and the others (and so m_verRichEdit may be 0 (plain
323 // EDIT control), 1 for version 1.0 or 2 for any higher version)
325 // notice that 1.0 has no Unicode support at all so in Unicode build we
326 // must use another version
330 #else // !wxUSE_UNICODE
331 m_verRichEdit
= m_windowStyle
& wxTE_RICH2
? 2 : 1;
332 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
335 // First test if we can load an ink edit control. Normally, all edit
336 // controls will be made ink edit controls if a tablet environment is
337 // found (or if msw.inkedit != 0 and the InkEd.dll is present).
338 // However, an application can veto ink edit controls by either specifying
339 // msw.inkedit = 0 or by removing wxTE_RICH[2] from the style.
341 if ((wxSystemSettings::HasFeature(wxSYS_TABLET_PRESENT
) || wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) != 0) &&
342 !(wxSystemOptions::HasOption(wxT("msw.inkedit")) && wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) == 0))
344 if (wxRichEditModule::LoadInkEdit())
346 windowClass
= INKEDIT_CLASS
;
348 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
352 // Fake rich text version for other calls
360 #endif // wxUSE_INKEDIT
362 if ( m_verRichEdit
== 2 )
364 if ( wxRichEditModule::Load(wxRichEditModule::Version_41
) )
366 // yes, class name for version 4.1 really is 5.0
367 windowClass
= wxT("RICHEDIT50W");
371 else if ( wxRichEditModule::Load(wxRichEditModule::Version_2or3
) )
373 windowClass
= wxT("RichEdit20")
378 #endif // Unicode/ANSI
380 else // failed to load msftedit.dll and riched20.dll
386 if ( m_verRichEdit
== 1 )
388 if ( wxRichEditModule::Load(wxRichEditModule::Version_1
) )
390 windowClass
= wxT("RICHEDIT");
392 else // failed to load any richedit control DLL
394 // only give the error msg once if the DLL can't be loaded
395 static bool s_errorGiven
= false; // MT ok as only used by GUI
399 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
409 #endif // wxUSE_RICHEDIT
411 // we need to turn '\n's into "\r\n"s for the multiline controls
413 if ( m_windowStyle
& wxTE_MULTILINE
)
415 valueWin
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
422 // suppress events sent during control creation: we're called either from
423 // the ctor and then we shouldn't generate any events for compatibility
424 // with the other ports, or from SetWindowStyleFlag() and then we shouldn't
425 // generate the events because our text doesn't really change, the fact
426 // that we (sometimes) need to recreate the control is just an
427 // implementation detail
430 if ( !MSWCreateControl(windowClass
.wx_str(), msStyle
, pos
, size
, valueWin
) )
441 // Pass IEM_InsertText (0) as wParam, in order to have the ink always
442 // converted to text.
443 ::SendMessage(GetHwnd(), EM_SETINKINSERTMODE
, 0, 0);
445 // Make sure the mouse can be used for input
446 ::SendMessage(GetHwnd(), EM_SETUSEMOUSEFORINPUT
, 1, 0);
450 // enable the events we're interested in: we want to get EN_CHANGE as
451 // for the normal controls
452 LPARAM mask
= ENM_CHANGE
;
454 if (GetRichVersion() == 1 && !IsInkEdit())
456 // we also need EN_MSGFILTER for richedit 1.0 for the reasons
457 // explained in its handler
458 mask
|= ENM_MOUSEEVENTS
;
460 // we also need to force the appearance of the vertical scrollbar
461 // initially as otherwise the control doesn't refresh correctly
462 // after resize: but once the vertical scrollbar had been shown
463 // (even if it's subsequently hidden) it does
465 // this is clearly a bug and for now it has been only noticed under
466 // Windows XP, so if we're sure it works correctly under other
467 // systems we could do this only for XP
468 SetSize(-1, 1); // 1 is small enough to force vert scrollbar
469 SetInitialSize(size
);
471 else if ( m_windowStyle
& wxTE_AUTO_URL
)
475 ::SendMessage(GetHwnd(), EM_AUTOURLDETECT
, TRUE
, 0);
478 ::SendMessage(GetHwnd(), EM_SETEVENTMASK
, 0, mask
);
481 #endif // wxUSE_RICHEDIT
482 if ( HasFlag(wxTE_MULTILINE
) && HasFlag(wxTE_READONLY
) )
484 // non-rich read-only multiline controls have grey background by
485 // default under MSW but this is not always appropriate, so forcefully
486 // reset the background colour to normal default
488 // this is not ideal but, after a long discussion on wx-dev (see
489 // http://thread.gmane.org/gmane.comp.lib.wxwidgets.devel/116360/) it
490 // was finally deemed to be the best behaviour by default (and ideally
491 // we'd have a way to change this, see #11521)
492 SetBackgroundColour(GetClassDefaultAttributes().colBg
);
496 // Without this, if we pass the size in the constructor and then don't change it,
497 // the themed borders will be drawn incorrectly.
498 SetWindowPos(GetHwnd(), NULL
, 0, 0, 0, 0,
499 SWP_NOZORDER
|SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOACTIVATE
|
506 // Make sure the window style (etc.) reflects the HWND style (roughly)
507 void wxTextCtrl::AdoptAttributesFromHWND()
509 wxWindow::AdoptAttributesFromHWND();
511 HWND hWnd
= GetHwnd();
512 long style
= ::GetWindowLong(hWnd
, GWL_STYLE
);
514 // retrieve the style to see whether this is an edit or richedit ctrl
516 wxString classname
= wxGetWindowClass(GetHWND());
518 if ( classname
.IsSameAs(wxT("EDIT"), false /* no case */) )
525 if ( wxSscanf(classname
, wxT("RichEdit%d0%c"), &m_verRichEdit
, &c
) != 2 )
527 wxLogDebug(wxT("Unknown edit control '%s'."), classname
.c_str());
532 #endif // wxUSE_RICHEDIT
534 if (style
& ES_MULTILINE
)
535 m_windowStyle
|= wxTE_MULTILINE
;
536 if (style
& ES_PASSWORD
)
537 m_windowStyle
|= wxTE_PASSWORD
;
538 if (style
& ES_READONLY
)
539 m_windowStyle
|= wxTE_READONLY
;
540 if (style
& ES_WANTRETURN
)
541 m_windowStyle
|= wxTE_PROCESS_ENTER
;
542 if (style
& ES_CENTER
)
543 m_windowStyle
|= wxTE_CENTRE
;
544 if (style
& ES_RIGHT
)
545 m_windowStyle
|= wxTE_RIGHT
;
548 WXDWORD
wxTextCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
550 long msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
552 // styles which we always add by default
553 if ( style
& wxTE_MULTILINE
)
555 msStyle
|= ES_MULTILINE
| ES_WANTRETURN
;
556 if ( !(style
& wxTE_NO_VSCROLL
) )
558 // always adjust the vertical scrollbar automatically if we have it
559 msStyle
|= WS_VSCROLL
| ES_AUTOVSCROLL
;
562 // we have to use this style for the rich edit controls because
563 // without it the vertical scrollbar never appears at all in
564 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
565 if ( style
& wxTE_RICH2
)
567 msStyle
|= ES_DISABLENOSCROLL
;
569 #endif // wxUSE_RICHEDIT
572 style
|= wxTE_PROCESS_ENTER
;
576 // there is really no reason to not have this style for single line
578 msStyle
|= ES_AUTOHSCROLL
;
581 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
582 // scrollbar, there is no wrapping -- which makes sense
583 if ( style
& wxTE_DONTWRAP
)
585 // automatically scroll the control horizontally as necessary
587 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
588 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
589 // it doesn't seem to do any harm for plain edit controls, add it
591 msStyle
|= WS_HSCROLL
| ES_AUTOHSCROLL
;
594 if ( style
& wxTE_READONLY
)
595 msStyle
|= ES_READONLY
;
597 if ( style
& wxTE_PASSWORD
)
598 msStyle
|= ES_PASSWORD
;
600 if ( style
& wxTE_NOHIDESEL
)
601 msStyle
|= ES_NOHIDESEL
;
603 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
604 if ( style
& wxTE_CENTRE
)
605 msStyle
|= ES_CENTER
;
606 else if ( style
& wxTE_RIGHT
)
609 msStyle
|= ES_LEFT
; // ES_LEFT is 0 as well but for consistency...
614 void wxTextCtrl::SetWindowStyleFlag(long style
)
616 // changing the alignment of the control dynamically works under Win2003
617 // (but not older Windows version: it seems to work under some versions of
618 // XP but not other ones, and we have no way to determine it so be
619 // conservative here) and only for plain EDIT controls (not RICH ones) and
620 // we have to recreate the control to make it always work
621 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003
)
623 const long alignMask
= wxTE_LEFT
| wxTE_CENTRE
| wxTE_RIGHT
;
624 if ( (style
& alignMask
) != (GetWindowStyle() & alignMask
) )
626 const wxString value
= GetValue();
627 const wxPoint pos
= GetPosition();
628 const wxSize size
= GetSize();
630 // delete the old window
631 HWND hwnd
= GetHwnd();
633 ::DestroyWindow(hwnd
);
635 // create the new one with the updated flags
636 m_windowStyle
= style
;
637 MSWCreateText(value
, pos
, size
);
639 // and make sure it has the same attributes as before
642 // calling SetFont(m_font) would do nothing as the code would
643 // notice that the font didn't change, so force it to believe
645 wxFont font
= m_font
;
652 wxColour colFg
= m_foregroundColour
;
653 m_foregroundColour
= wxNullColour
;
654 SetForegroundColour(colFg
);
659 wxColour colBg
= m_backgroundColour
;
660 m_backgroundColour
= wxNullColour
;
661 SetBackgroundColour(colBg
);
664 // note that text styles are lost but this is probably not a big
665 // problem: if you use styles, you probably don't use nor change
666 // alignment flags anyhow
673 // we have to deal with some styles separately because they can't be
674 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
675 // using richedit-specific EM_SETOPTIONS
677 ((style
& wxTE_NOHIDESEL
) != (GetWindowStyle() & wxTE_NOHIDESEL
)) )
679 bool set
= (style
& wxTE_NOHIDESEL
) != 0;
681 ::SendMessage(GetHwnd(), EM_SETOPTIONS
, set
? ECOOP_OR
: ECOOP_AND
,
682 set
? ECO_NOHIDESEL
: ~ECO_NOHIDESEL
);
684 #endif // wxUSE_RICHEDIT
686 wxControl::SetWindowStyleFlag(style
);
689 // ----------------------------------------------------------------------------
690 // set/get the controls text
691 // ----------------------------------------------------------------------------
693 bool wxTextCtrl::IsEmpty() const
695 // this is an optimization for multiline controls containing a lot of text
696 if ( IsMultiLine() && GetNumberOfLines() != 1 )
699 return wxTextCtrlBase::IsEmpty();
702 wxString
wxTextCtrl::GetValue() const
704 // range 0..-1 is special for GetRange() and means to retrieve all text
705 return GetRange(0, -1);
708 wxString
wxTextCtrl::GetRange(long from
, long to
) const
712 if ( from
>= to
&& to
!= -1 )
714 // nothing to retrieve
721 int len
= GetWindowTextLength(GetHwnd());
728 // we must use EM_STREAMOUT if we don't want to lose all characters
729 // not representable in the current character set (EM_GETTEXTRANGE
730 // simply replaces them with question marks...)
731 if ( GetRichVersion() > 1 )
733 // we must have some encoding, otherwise any 8bit chars in the
734 // control are simply *lost* (replaced by '?')
735 wxFontEncoding encoding
= wxFONTENCODING_SYSTEM
;
737 wxFont font
= m_defaultStyle
.GetFont();
743 encoding
= font
.GetEncoding();
747 if ( encoding
== wxFONTENCODING_SYSTEM
)
749 encoding
= wxLocale::GetSystemEncoding();
753 if ( encoding
== wxFONTENCODING_SYSTEM
)
755 encoding
= wxFONTENCODING_ISO8859_1
;
758 str
= StreamOut(encoding
);
762 // we have to manually extract the required part, luckily
763 // this is easy in this case as EOL characters in str are
764 // just LFs because we remove CRs in wxRichEditStreamOut
765 str
= str
.Mid(from
, to
- from
);
769 // StreamOut() wasn't used or failed, try to do it in normal way
771 #endif // !wxUSE_UNICODE
773 // alloc one extra WORD as needed by the control
774 wxStringBuffer
tmp(str
, ++len
);
778 textRange
.chrg
.cpMin
= from
;
779 textRange
.chrg
.cpMax
= to
;
780 textRange
.lpstrText
= p
;
782 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE
,
783 0, (LPARAM
)&textRange
);
785 if ( m_verRichEdit
> 1 )
787 // RichEdit 2.0 uses just CR ('\r') for the
788 // newlines which is neither Unix nor Windows
789 // style - convert it to something reasonable
792 if ( *p
== wxT('\r') )
798 if ( m_verRichEdit
== 1 )
800 // convert to the canonical form - see comment below
801 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
804 //else: no text at all, leave the string empty
807 #endif // wxUSE_RICHEDIT
809 // retrieve all text: wxTextEntry method works even for multiline
810 // controls and must be used for single line ones to account for hints
811 str
= wxTextEntry::GetValue();
813 // need only a range?
816 str
= str
.Mid(from
, to
- from
);
819 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
820 // canonical one (same one as above) for consistency with the other kinds
821 // of controls and, more importantly, with the other ports
822 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
828 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
830 // if the text is long enough, it's faster to just set it instead of first
831 // comparing it with the old one (chances are that it will be different
832 // anyhow, this comparison is there to avoid flicker for small single-line
833 // edit controls mostly)
834 if ( (value
.length() > 0x400) || (value
!= DoGetValue()) )
836 DoWriteText(value
, flags
/* doesn't include SelectionOnly here */);
838 // mark the control as being not dirty - we changed its text, not the
842 // for compatibility, don't move the cursor when doing SetValue()
843 SetInsertionPoint(0);
847 // still reset the modified flag even if the value didn't really change
848 // because now it comes from the program and not the user (and do it
849 // before generating the event so that the event handler could get the
850 // expected value from IsModified())
853 // still send an event for consistency
854 if (flags
& SetValue_SendEvent
)
859 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
861 // TODO: using memcpy() would improve performance a lot for big amounts of text
864 wxRichEditStreamIn(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
868 const wchar_t ** const ppws
= (const wchar_t **)dwCookie
;
870 wchar_t *wbuf
= (wchar_t *)buf
;
871 const wchar_t *wpc
= *ppws
;
876 cb
-= sizeof(wchar_t);
877 (*pcb
) += sizeof(wchar_t);
885 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
886 struct wxStreamOutData
893 wxRichEditStreamOut(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
897 wxStreamOutData
*data
= (wxStreamOutData
*)dwCookie
;
899 const wchar_t *wbuf
= (const wchar_t *)buf
;
900 wchar_t *wpc
= data
->wpc
;
903 wchar_t wch
= *wbuf
++;
905 // turn "\r\n" into "\n" on the fly
911 cb
-= sizeof(wchar_t);
912 (*pcb
) += sizeof(wchar_t);
921 #if wxUSE_UNICODE_MSLU
922 #define UNUSED_IF_MSLU(param)
924 #define UNUSED_IF_MSLU(param) param
928 wxTextCtrl::StreamIn(const wxString
& value
,
929 wxFontEncoding
UNUSED_IF_MSLU(encoding
),
932 #if wxUSE_UNICODE_MSLU
933 const wchar_t *wpc
= value
.c_str();
934 #else // !wxUSE_UNICODE_MSLU
935 wxCSConv
conv(encoding
);
937 const size_t len
= conv
.MB2WC(NULL
, value
.mb_str(), value
.length());
939 if (len
== wxCONV_FAILED
)
942 wxWCharBuffer
wchBuf(len
); // allocates one extra character
943 wchar_t *wpc
= wchBuf
.data();
945 conv
.MB2WC(wpc
, value
.mb_str(), len
+ 1);
946 #endif // wxUSE_UNICODE_MSLU
948 // finally, stream it in the control
951 eds
.dwCookie
= (DWORD_PTR
)&wpc
;
952 // the cast below is needed for broken (very) old mingw32 headers
953 eds
.pfnCallback
= (EDITSTREAMCALLBACK
)wxRichEditStreamIn
;
955 // same problem as in DoWriteText(): we can get multiple events here
956 UpdatesCountFilter
ucf(m_updatesCount
);
958 ::SendMessage(GetHwnd(), EM_STREAMIN
,
961 (selectionOnly
? SFF_SELECTION
: 0),
964 // It's okay for EN_UPDATE to not be sent if the selection is empty and
965 // the text is empty, otherwise warn the programmer about it.
966 wxASSERT_MSG( ucf
.GotUpdate() || ( !HasSelection() && value
.empty() ),
967 wxT("EM_STREAMIN didn't send EN_UPDATE?") );
971 wxLogLastError(wxT("EM_STREAMIN"));
977 #if !wxUSE_UNICODE_MSLU
980 wxTextCtrl::StreamOut(wxFontEncoding encoding
, bool selectionOnly
) const
984 const int len
= GetWindowTextLength(GetHwnd());
986 wxWCharBuffer
wchBuf(len
);
987 wchar_t *wpc
= wchBuf
.data();
989 wxStreamOutData data
;
995 eds
.dwCookie
= (DWORD
)&data
;
996 eds
.pfnCallback
= wxRichEditStreamOut
;
1002 SF_TEXT
| SF_UNICODE
| (selectionOnly
? SFF_SELECTION
: 0),
1008 wxLogLastError(wxT("EM_STREAMOUT"));
1010 else // streamed out ok
1012 // NUL-terminate the string because its length could have been
1013 // decreased by wxRichEditStreamOut
1014 *(wchBuf
.data() + data
.len
) = L
'\0';
1016 // now convert to the given encoding (this is a possibly lossful
1017 // conversion but what else can we do)
1018 wxCSConv
conv(encoding
);
1019 size_t lenNeeded
= conv
.WC2MB(NULL
, wchBuf
, 0);
1021 if ( lenNeeded
!= wxCONV_FAILED
&& lenNeeded
++ )
1023 conv
.WC2MB(wxStringBuffer(out
, lenNeeded
), wchBuf
, lenNeeded
);
1030 #endif // !wxUSE_UNICODE_MSLU
1032 #endif // wxUSE_RICHEDIT
1034 void wxTextCtrl::WriteText(const wxString
& value
)
1039 void wxTextCtrl::DoWriteText(const wxString
& value
, int flags
)
1041 bool selectionOnly
= (flags
& SetValue_SelectionOnly
) != 0;
1043 if ( m_windowStyle
& wxTE_MULTILINE
)
1044 valueDos
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
1049 // there are several complications with the rich edit controls here
1053 // first, ensure that the new text will be in the default style
1054 if ( !m_defaultStyle
.IsDefault() )
1057 GetSelection(&start
, &end
);
1058 SetStyle(start
, end
, m_defaultStyle
);
1061 #if wxUSE_UNICODE_MSLU
1062 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1063 // but EM_STREAMIN works
1064 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1066 done
= StreamIn(valueDos
, wxFONTENCODING_SYSTEM
, selectionOnly
);
1068 #endif // wxUSE_UNICODE_MSLU
1071 // next check if the text we're inserting must be shown in a non
1072 // default charset -- this only works for RichEdit > 1.0
1073 if ( GetRichVersion() > 1 )
1075 wxFont font
= m_defaultStyle
.GetFont();
1081 wxFontEncoding encoding
= font
.GetEncoding();
1082 if ( encoding
!= wxFONTENCODING_SYSTEM
)
1084 // we have to use EM_STREAMIN to force richedit control 2.0+
1085 // to show any text in the non default charset -- otherwise
1086 // it thinks it knows better than we do and always shows it
1087 // in the default one
1088 done
= StreamIn(valueDos
, encoding
, selectionOnly
);
1092 #endif // !wxUSE_UNICODE
1096 #endif // wxUSE_RICHEDIT
1098 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1099 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1100 // -- undetermined -- conditions with rich edit) and sometimes we don't
1101 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1102 // we generate exactly one of them by ignoring all but the first one in
1103 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1104 // notifications from Windows
1105 if ( !(flags
& SetValue_SendEvent
) )
1106 m_updatesCount
= -2; // suppress any update event
1108 UpdatesCountFilter
ucf(m_updatesCount
);
1110 ::SendMessage(GetHwnd(), selectionOnly
? EM_REPLACESEL
: WM_SETTEXT
,
1111 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1112 selectionOnly
? 1 : 0, (LPARAM
)valueDos
.wx_str());
1114 if ( !ucf
.GotUpdate() && (flags
& SetValue_SendEvent
) )
1121 void wxTextCtrl::AppendText(const wxString
& text
)
1123 wxTextEntry::AppendText(text
);
1126 // don't do this if we're frozen, saves some time
1127 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1129 ::SendMessage(GetHwnd(), WM_VSCROLL
, SB_BOTTOM
, (LPARAM
)NULL
);
1131 #endif // wxUSE_RICHEDIT
1134 void wxTextCtrl::Clear()
1136 ::SetWindowText(GetHwnd(), wxEmptyString
);
1138 if ( IsMultiLine() && !IsRich() )
1140 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1141 // but the normal ones don't -- make Clear() behaviour consistent by
1142 // always sending this event
1149 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent
& event
)
1153 size_t lenOld
= GetValue().length();
1155 wxUint32 code
= event
.GetRawKeyCode();
1156 ::keybd_event((BYTE
)code
, 0, 0 /* key press */, 0);
1157 ::keybd_event((BYTE
)code
, 0, KEYEVENTF_KEYUP
, 0);
1159 // assume that any alphanumeric key changes the total number of characters
1160 // in the control - this should work in 99% of cases
1161 return GetValue().length() != lenOld
;
1166 // ----------------------------------------------------------------------------
1168 // ----------------------------------------------------------------------------
1170 void wxTextCtrl::SetInsertionPointEnd()
1172 // we must not do anything if the caret is already there because calling
1173 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1174 // if it doesn't actually move the caret anywhere and so the simple fact of
1175 // doing it results in horrible flicker when appending big amounts of text
1176 // to the control in a few chunks (see DoAddText() test in the text sample)
1177 const wxTextPos lastPosition
= GetLastPosition();
1178 if ( GetInsertionPoint() == lastPosition
)
1183 SetInsertionPoint(lastPosition
);
1186 long wxTextCtrl::GetInsertionPoint() const
1194 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &range
);
1197 #endif // wxUSE_RICHEDIT
1199 return wxTextEntry::GetInsertionPoint();
1202 wxTextPos
wxTextCtrl::GetLastPosition() const
1204 if ( IsMultiLine() )
1206 int numLines
= GetNumberOfLines();
1207 long posStartLastLine
= XYToPosition(0, numLines
- 1);
1209 long lenLastLine
= GetLengthOfLineContainingPos(posStartLastLine
);
1211 return posStartLastLine
+ lenLastLine
;
1214 return wxTextEntry::GetLastPosition();
1217 // If the return values from and to are the same, there is no
1219 void wxTextCtrl::GetSelection(long *from
, long *to
) const
1224 CHARRANGE charRange
;
1225 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &charRange
);
1227 *from
= charRange
.cpMin
;
1228 *to
= charRange
.cpMax
;
1231 #endif // !wxUSE_RICHEDIT
1233 wxTextEntry::GetSelection(from
, to
);
1237 // ----------------------------------------------------------------------------
1239 // ----------------------------------------------------------------------------
1241 void wxTextCtrl::DoSetSelection(long from
, long to
, int flags
)
1243 HWND hWnd
= GetHwnd();
1248 // if from and to are both -1, it means (in wxWidgets) that all text
1249 // should be selected, translate this into Windows convention
1250 if ( (from
== -1) && (to
== -1) )
1258 ::SendMessage(hWnd
, EM_EXSETSEL
, 0, (LPARAM
)&range
);
1261 #endif // wxUSE_RICHEDIT
1263 wxTextEntry::DoSetSelection(from
, to
, flags
);
1266 if ( (flags
& SetSel_Scroll
) && !IsFrozen() )
1269 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1270 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1271 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1272 // option is set (but it does work ok in richedit 1.0 mode...)
1274 // so to make it work we either need to give focus to it here which
1275 // will probably create many problems (dummy focus events; window
1276 // containing the text control being brought to foreground
1277 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1278 // create other problems too -- and in fact it does because if we turn
1279 // on/off this style while appending the text to the control, the
1280 // vertical scrollbar never appears in it even if we append tons of
1281 // text and to work around this the only solution I found was to use
1282 // ES_DISABLENOSCROLL
1284 // this is very ugly but I don't see any other way to make this work
1286 if ( GetRichVersion() > 1 )
1288 if ( !HasFlag(wxTE_NOHIDESEL
) )
1290 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1291 // others, remember the style so we can reset it later if needed
1292 style
= ::GetWindowLong(GetHwnd(), GWL_STYLE
);
1293 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1294 ECOOP_OR
, ECO_NOHIDESEL
);
1296 //else: everything is already ok
1298 #endif // wxUSE_RICHEDIT
1300 ::SendMessage(hWnd
, EM_SCROLLCARET
, 0, (LPARAM
)0);
1303 // restore ECO_NOHIDESEL if we changed it
1304 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL
) )
1306 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1307 ECOOP_AND
, ~ECO_NOHIDESEL
);
1308 if ( style
!= ::GetWindowLong(GetHwnd(), GWL_STYLE
) )
1309 ::SetWindowLong(GetHwnd(), GWL_STYLE
, style
);
1311 #endif // wxUSE_RICHEDIT
1315 // ----------------------------------------------------------------------------
1316 // Working with files
1317 // ----------------------------------------------------------------------------
1319 bool wxTextCtrl::DoLoadFile(const wxString
& file
, int fileType
)
1321 if ( wxTextCtrlBase::DoLoadFile(file
, fileType
) )
1323 // update the size limit if needed
1332 // ----------------------------------------------------------------------------
1334 // ----------------------------------------------------------------------------
1336 bool wxTextCtrl::IsModified() const
1338 return ::SendMessage(GetHwnd(), EM_GETMODIFY
, 0, 0) != 0;
1341 void wxTextCtrl::MarkDirty()
1343 ::SendMessage(GetHwnd(), EM_SETMODIFY
, TRUE
, 0);
1346 void wxTextCtrl::DiscardEdits()
1348 ::SendMessage(GetHwnd(), EM_SETMODIFY
, FALSE
, 0);
1351 // ----------------------------------------------------------------------------
1352 // Positions <-> coords
1353 // ----------------------------------------------------------------------------
1355 int wxTextCtrl::GetNumberOfLines() const
1357 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT
, 0, 0);
1360 long wxTextCtrl::XYToPosition(long x
, long y
) const
1362 // This gets the char index for the _beginning_ of this line
1363 long charIndex
= ::SendMessage(GetHwnd(), EM_LINEINDEX
, y
, 0);
1365 return charIndex
+ x
;
1368 bool wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
1370 HWND hWnd
= GetHwnd();
1372 // This gets the line number containing the character
1377 lineNo
= ::SendMessage(hWnd
, EM_EXLINEFROMCHAR
, 0, pos
);
1380 #endif // wxUSE_RICHEDIT
1382 lineNo
= ::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1391 // This gets the char index for the _beginning_ of this line
1392 long charIndex
= ::SendMessage(hWnd
, EM_LINEINDEX
, lineNo
, 0);
1393 if ( charIndex
== -1 )
1398 // The X position must therefore be the different between pos and charIndex
1400 *x
= pos
- charIndex
;
1407 wxTextCtrlHitTestResult
1408 wxTextCtrl::HitTest(const wxPoint
& pt
, long *posOut
) const
1410 // first get the position from Windows
1417 // for rich edit controls the position is passed iva the struct fields
1420 lParam
= (LPARAM
)&ptl
;
1423 #endif // wxUSE_RICHEDIT
1425 // for the plain ones, we are limited to 16 bit positions which are
1426 // combined in a single 32 bit value
1427 lParam
= MAKELPARAM(pt
.x
, pt
.y
);
1430 LRESULT pos
= ::SendMessage(GetHwnd(), EM_CHARFROMPOS
, 0, lParam
);
1434 // this seems to indicate an error...
1435 return wxTE_HT_UNKNOWN
;
1440 #endif // wxUSE_RICHEDIT
1442 // for plain EDIT controls the higher word contains something else
1447 // next determine where it is relatively to our point: EM_CHARFROMPOS
1448 // always returns the closest character but we need to be more precise, so
1449 // double check that we really are where it pretends
1453 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1454 // we don't know how to do it
1457 ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&ptReal
, pos
);
1460 #endif // wxUSE_RICHEDIT
1462 LRESULT lRc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1466 // this is apparently returned when pos corresponds to the last
1473 ptReal
.x
= LOWORD(lRc
);
1474 ptReal
.y
= HIWORD(lRc
);
1478 wxTextCtrlHitTestResult rc
;
1480 if ( pt
.y
> ptReal
.y
+ GetCharHeight() )
1482 else if ( pt
.x
> ptReal
.x
+ GetCharWidth() )
1483 rc
= wxTE_HT_BEYOND
;
1485 rc
= wxTE_HT_ON_TEXT
;
1493 wxPoint
wxTextCtrl::DoPositionToCoords(long pos
) const
1495 // FIXME: This code is broken for rich edit version 2.0 as it uses the same
1496 // API as plain edit i.e. the coordinates are returned directly instead of
1497 // filling the POINT passed as WPARAM with them but we can't distinguish
1498 // between 2.0 and 3.0 unfortunately (see also the use of EM_POSFROMCHAR
1504 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&pt
, pos
);
1506 return wxPoint(pt
.x
, pt
.y
);
1509 #endif // wxUSE_RICHEDIT
1511 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1514 // Finding coordinates for the last position of the control fails
1515 // in plain EDIT control, try to compensate for it by finding it
1516 // ourselves from the position of the previous character.
1517 if ( pos
< GetLastPosition() )
1519 // It's not the expected correctable failure case so just fail.
1520 return wxDefaultPosition
;
1525 // We're being asked the coordinates of the first (and last and
1526 // only) position in an empty control. There is no way to get
1527 // it directly with EM_POSFROMCHAR but EM_GETMARGINS returns
1528 // the correct value for at least the horizontal offset.
1529 rc
= ::SendMessage(GetHwnd(), EM_GETMARGINS
, 0, 0);
1531 // Text control seems to effectively add 1 to margin.
1532 return wxPoint(LOWORD(rc
) + 1, 1);
1535 // We do have a previous character, try to get its coordinates.
1536 rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
- 1, 0);
1539 // If getting coordinates of the previous character failed as
1540 // well, just give up.
1541 return wxDefaultPosition
;
1544 wxString prevChar
= GetRange(pos
- 1, pos
);
1545 wxSize prevCharSize
= GetTextExtent(prevChar
);
1547 if ( prevChar
== wxT("\n" ))
1549 // 'pos' is at the beginning of a new line so its X coordinate
1550 // should be the same as X coordinate of the first character of
1551 // any other line while its Y coordinate will be approximately
1552 // (but we can't compute it exactly...) one character height
1553 // more than that of the previous character.
1554 LRESULT coords0
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, 0, 0);
1555 if ( coords0
== -1 )
1556 return wxDefaultPosition
;
1558 rc
= MAKELPARAM(LOWORD(coords0
), HIWORD(rc
) + prevCharSize
.y
);
1562 // Simple case: previous character is in the same line so this
1563 // one is just after it.
1564 rc
+= MAKELPARAM(prevCharSize
.x
, 0);
1568 // Notice that {LO,HI}WORD macros return WORDs, i.e. unsigned shorts,
1569 // while we want to have signed values here (the y coordinate of any
1570 // position above the first currently visible line is negative, for
1571 // example), hence the need for casts.
1572 return wxPoint(static_cast<short>(LOWORD(rc
)),
1573 static_cast<short>(HIWORD(rc
)));
1576 return wxDefaultPosition
;
1580 // ----------------------------------------------------------------------------
1582 // ----------------------------------------------------------------------------
1584 void wxTextCtrl::ShowPosition(long pos
)
1586 HWND hWnd
= GetHwnd();
1588 // To scroll to a position, we pass the number of lines and characters
1589 // to scroll *by*. This means that we need to:
1590 // (1) Find the line position of the current line.
1591 // (2) Find the line position of pos.
1592 // (3) Scroll by (pos - current).
1593 // For now, ignore the horizontal scrolling.
1595 // Is this where scrolling is relative to - the line containing the caret?
1596 // Or is the first visible line??? Try first visible line.
1597 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, -1, 0L);
1599 int currentLineLineNo
= (int)::SendMessage(hWnd
, EM_GETFIRSTVISIBLELINE
, 0, 0);
1601 int specifiedLineLineNo
= (int)::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1603 int linesToScroll
= specifiedLineLineNo
- currentLineLineNo
;
1605 if (linesToScroll
!= 0)
1606 ::SendMessage(hWnd
, EM_LINESCROLL
, 0, linesToScroll
);
1609 long wxTextCtrl::GetLengthOfLineContainingPos(long pos
) const
1611 return ::SendMessage(GetHwnd(), EM_LINELENGTH
, pos
, 0);
1614 int wxTextCtrl::GetLineLength(long lineNo
) const
1616 long pos
= XYToPosition(0, lineNo
);
1618 return GetLengthOfLineContainingPos(pos
);
1621 wxString
wxTextCtrl::GetLineText(long lineNo
) const
1623 size_t len
= (size_t)GetLineLength(lineNo
) + 1;
1625 // there must be at least enough place for the length WORD in the
1627 len
+= sizeof(WORD
);
1631 wxStringBufferLength
tmp(str
, len
);
1634 *(WORD
*)buf
= (WORD
)len
;
1635 len
= (size_t)::SendMessage(GetHwnd(), EM_GETLINE
, lineNo
, (LPARAM
)buf
);
1640 // remove the '\r' returned by the rich edit control, the user code
1641 // should never see it
1642 if ( buf
[len
- 2] == wxT('\r') && buf
[len
- 1] == wxT('\n') )
1644 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1645 // here and "\n" below
1646 buf
[len
- 2] = wxT('\n');
1649 else if ( buf
[len
- 1] == wxT('\r') )
1651 // richedit 2.0+ uses only "\r", replace it with "\n"
1652 buf
[len
- 1] = wxT('\n');
1655 #endif // wxUSE_RICHEDIT
1657 // remove the '\n' at the end, if any (this is how this function is
1658 // supposed to work according to the docs)
1659 if ( buf
[len
- 1] == wxT('\n') )
1671 void wxTextCtrl::SetMaxLength(unsigned long len
)
1676 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT
, 0, len
? len
: 0x7fffffff);
1679 #endif // wxUSE_RICHEDIT
1681 wxTextEntry::SetMaxLength(len
);
1685 // ----------------------------------------------------------------------------
1687 // ----------------------------------------------------------------------------
1689 void wxTextCtrl::Redo()
1692 if ( GetRichVersion() > 1 )
1694 ::SendMessage(GetHwnd(), EM_REDO
, 0, 0);
1697 #endif // wxUSE_RICHEDIT
1699 wxTextEntry::Redo();
1702 bool wxTextCtrl::CanRedo() const
1705 if ( GetRichVersion() > 1 )
1706 return ::SendMessage(GetHwnd(), EM_CANREDO
, 0, 0) != 0;
1707 #endif // wxUSE_RICHEDIT
1709 return wxTextEntry::CanRedo();
1712 // ----------------------------------------------------------------------------
1713 // caret handling (Windows only)
1714 // ----------------------------------------------------------------------------
1716 bool wxTextCtrl::ShowNativeCaret(bool show
)
1718 if ( show
!= m_isNativeCaretShown
)
1720 if ( !(show
? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1722 // not an error, may simply indicate that it's not shown/hidden
1723 // yet (i.e. it had been hidden/shown 2 times before)
1727 m_isNativeCaretShown
= show
;
1733 // ----------------------------------------------------------------------------
1734 // implementation details
1735 // ----------------------------------------------------------------------------
1737 void wxTextCtrl::Command(wxCommandEvent
& event
)
1739 SetValue(event
.GetString());
1740 ProcessCommand (event
);
1743 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
1745 // By default, load the first file into the text window.
1746 if (event
.GetNumberOfFiles() > 0)
1748 LoadFile(event
.GetFiles()[0]);
1752 // ----------------------------------------------------------------------------
1753 // kbd input processing
1754 // ----------------------------------------------------------------------------
1756 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1758 // check for our special keys here: if we don't do it and the parent frame
1759 // uses them as accelerators, they wouldn't work at all, so we disable
1760 // usual preprocessing for them
1761 if ( msg
->message
== WM_KEYDOWN
)
1763 const WPARAM vkey
= msg
->wParam
;
1764 if ( HIWORD(msg
->lParam
) & KF_ALTDOWN
)
1766 // Alt-Backspace is accelerator for "Undo"
1767 if ( vkey
== VK_BACK
)
1772 // we want to process some Ctrl-foo and Shift-bar but no key
1773 // combinations without either Ctrl or Shift nor with both of them
1775 const int ctrl
= wxIsCtrlDown(),
1776 shift
= wxIsShiftDown();
1777 switch ( ctrl
+ shift
)
1780 wxFAIL_MSG( wxT("how many modifiers have we got?") );
1787 // This one is only special for multi line controls.
1788 if ( !IsMultiLine() )
1802 // either Ctrl or Shift pressed
1817 else // Shift is pressed
1819 if ( vkey
== VK_INSERT
|| vkey
== VK_DELETE
)
1826 return wxControl::MSWShouldPreProcessMessage(msg
);
1829 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
1831 switch ( event
.GetKeyCode() )
1835 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
, m_windowId
);
1836 InitCommandEvent(event
);
1837 event
.SetString(GetValue());
1838 if ( HandleWindowEvent(event
) )
1839 if ( !HasFlag(wxTE_MULTILINE
) )
1841 //else: multiline controls need Enter for themselves
1846 // ok, so this is getting absolutely ridiculous but I don't see
1847 // any other way to fix this bug: when a multiline text control is
1848 // inside a wxFrame, we need to generate the navigation event as
1849 // otherwise nothing happens at all, but when the same control is
1850 // created inside a dialog, IsDialogMessage() *does* switch focus
1851 // all by itself and so if we do it here as well, it is advanced
1852 // twice and goes to the next control... to prevent this from
1853 // happening we're doing this ugly check, the logic being that if
1854 // we don't have focus then it had been already changed to the next
1857 // the right thing to do would, of course, be to understand what
1858 // the hell is IsDialogMessage() doing but this is beyond my feeble
1859 // forces at the moment unfortunately
1860 if ( !(m_windowStyle
& wxTE_PROCESS_TAB
))
1862 if ( FindFocus() == this )
1865 if (!event
.ShiftDown())
1866 flags
|= wxNavigationKeyEvent::IsForward
;
1867 if (event
.ControlDown())
1868 flags
|= wxNavigationKeyEvent::WinChange
;
1869 if (Navigate(flags
))
1875 // Insert tab since calling the default Windows handler
1876 // doesn't seem to do it
1877 WriteText(wxT("\t"));
1883 // no, we didn't process it
1887 void wxTextCtrl::OnKeyDown(wxKeyEvent
& event
)
1889 // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages
1890 // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent
1891 // from working. So we work around it by intercepting these shortcuts
1892 // ourselves and emitting clipboard events (which richedit will handle,
1893 // so everything works as before, including pasting of rich text):
1894 if ( event
.GetModifiers() == wxMOD_CONTROL
&& IsRich() )
1896 switch ( event
.GetKeyCode() )
1912 // Default window procedure of multiline edit controls posts WM_CLOSE to
1913 // the parent window when it gets Escape key press for some reason, prevent
1914 // it from doing this as this resulted in dialog boxes being closed on
1915 // Escape even when they shouldn't be (we do handle Escape ourselves
1916 // correctly in the situations when it should close them).
1917 if ( event
.GetKeyCode() == WXK_ESCAPE
&& IsMultiLine() )
1920 // no, we didn't process it
1924 WXLRESULT
wxTextCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1926 WXLRESULT lRc
= wxTextCtrlBase::MSWWindowProc(nMsg
, wParam
, lParam
);
1932 // we always want the chars and the arrows: the arrows for
1933 // navigation and the chars because we want Ctrl-C to work even
1934 // in a read only control
1935 long lDlgCode
= DLGC_WANTCHARS
| DLGC_WANTARROWS
;
1939 // we may have several different cases:
1940 // 1. normal: both TAB and ENTER are used for navigation
1941 // 2. ctrl wants TAB for itself: ENTER is used to pass to
1942 // the next control in the dialog
1943 // 3. ctrl wants ENTER for itself: TAB is used for dialog
1945 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
1946 // go to the next control (we need some way to do it)
1948 // multiline controls should always get ENTER for themselves
1949 if ( HasFlag(wxTE_PROCESS_ENTER
) || HasFlag(wxTE_MULTILINE
) )
1950 lDlgCode
|= DLGC_WANTMESSAGE
;
1952 if ( HasFlag(wxTE_PROCESS_TAB
) )
1953 lDlgCode
|= DLGC_WANTTAB
;
1959 // NB: use "=", not "|=" as the base class version returns
1960 // the same flags in the disabled state as usual (i.e.
1961 // including DLGC_WANTMESSAGE). This is strange (how
1962 // does it work in the native Win32 apps?) but for now
1967 // Clear the DLGC_HASSETSEL bit from the return value
1968 lRc
&= ~DLGC_HASSETSEL
;
1974 // rich text controls seem to have a bug and don't change the
1975 // cursor to the standard arrow one from the I-beam cursor usually
1976 // used by them even when a popup menu is shown (this works fine
1977 // for plain EDIT controls though), so explicitly work around this
1980 extern wxMenu
*wxCurrentPopupMenu
;
1981 if ( wxCurrentPopupMenu
&&
1982 wxCurrentPopupMenu
->GetInvokingWindow() == this )
1983 ::SetCursor(GetHcursorOf(*wxSTANDARD_CURSOR
));
1985 #endif // wxUSE_MENUS
1991 // ----------------------------------------------------------------------------
1992 // text control event processing
1993 // ----------------------------------------------------------------------------
1995 bool wxTextCtrl::SendUpdateEvent()
1997 switch ( m_updatesCount
)
2000 // remember that we've got an update
2005 // we had already sent one event since the last control modification
2009 wxFAIL_MSG( wxT("unexpected wxTextCtrl::m_updatesCount value") );
2013 // we hadn't updated the control ourselves, this event comes from
2014 // the user, don't need to ignore it nor update the count
2018 // the control was updated programmatically and we do NOT want to
2023 return SendTextUpdatedEvent();
2026 bool wxTextCtrl::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
2035 // the text size limit has been hit -- try to increase it
2036 if ( !AdjustSpaceLimit() )
2038 wxCommandEvent
event(wxEVT_COMMAND_TEXT_MAXLEN
, m_windowId
);
2039 InitCommandEvent(event
);
2040 event
.SetString(GetValue());
2041 ProcessCommand(event
);
2045 // the other edit notification messages are not processed (or, in
2046 // the case of EN_{SET/KILL}FOCUS were already handled at WM_SET/
2056 WXHBRUSH
wxTextCtrl::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
2058 if ( !IsThisEnabled() && !HasFlag(wxTE_MULTILINE
) )
2059 return MSWControlColorDisabled(hDC
);
2061 return wxTextCtrlBase::MSWControlColor(hDC
, hWnd
);
2064 bool wxTextCtrl::HasSpaceLimit(unsigned int *len
) const
2066 // HACK: we try to automatically extend the limit for the amount of text
2067 // to allow (interactively) entering more than 64Kb of text under
2068 // Win9x but we shouldn't reset the text limit which was previously
2069 // set explicitly with SetMaxLength()
2071 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2072 // know the limit we set (if any). We could solve this by storing the
2073 // limit we set in wxTextCtrl but to save space we prefer to simply
2074 // test here the actual limit value: we consider that SetMaxLength()
2075 // can only be called for small values while EN_MAXTEXT is only sent
2076 // for large values (in practice the default limit seems to be 30000
2077 // but make it smaller just to be on the safe side)
2078 *len
= ::SendMessage(GetHwnd(), EM_GETLIMITTEXT
, 0, 0);
2079 return *len
< 10001;
2083 bool wxTextCtrl::AdjustSpaceLimit()
2086 if ( HasSpaceLimit(&limit
) )
2089 unsigned int len
= ::GetWindowTextLength(GetHwnd());
2092 // increment in 32Kb chunks
2093 SetMaxLength(len
+ 0x8000);
2096 // we changed the limit
2100 bool wxTextCtrl::AcceptsFocusFromKeyboard() const
2102 // we don't want focus if we can't be edited unless we're a multiline
2103 // control because then it might be still nice to get focus from keyboard
2104 // to be able to scroll it without mouse
2105 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2108 wxSize
wxTextCtrl::DoGetBestSize() const
2111 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
2113 int wText
= DEFAULT_ITEM_WIDTH
;
2116 if ( m_windowStyle
& wxTE_MULTILINE
)
2118 hText
*= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2120 //else: for single line control everything is ok
2122 // Text controls without border are special and have the same height as
2123 // static labels (they also have the same appearance when they're disable
2124 // and are often used as a sort of copyable to the clipboard label so it's
2125 // important that they have the same height as the normal labels to not
2127 if ( !HasFlag(wxBORDER_NONE
) )
2129 // we have to add the adjustments for the control height only once, not
2130 // once per line, so do it after multiplication above
2131 hText
+= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
) - cy
;
2134 return wxSize(wText
, hText
);
2137 // ----------------------------------------------------------------------------
2138 // standard handlers for standard edit menu events
2139 // ----------------------------------------------------------------------------
2141 void wxTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
2146 void wxTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
2151 void wxTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
2156 void wxTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
2161 void wxTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
2166 void wxTextCtrl::OnDelete(wxCommandEvent
& WXUNUSED(event
))
2171 void wxTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
2176 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
2178 event
.Enable( CanCut() );
2181 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
2183 event
.Enable( CanCopy() );
2186 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
2188 event
.Enable( CanPaste() );
2191 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
2193 event
.Enable( CanUndo() );
2196 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
2198 event
.Enable( CanRedo() );
2201 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent
& event
)
2203 event
.Enable( HasSelection() && IsEditable() );
2206 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
2208 event
.Enable( !IsEmpty() );
2211 void wxTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
2216 if (!m_privateContextMenu
)
2218 m_privateContextMenu
= new wxMenu
;
2219 m_privateContextMenu
->Append(wxID_UNDO
, _("&Undo"));
2220 m_privateContextMenu
->Append(wxID_REDO
, _("&Redo"));
2221 m_privateContextMenu
->AppendSeparator();
2222 m_privateContextMenu
->Append(wxID_CUT
, _("Cu&t"));
2223 m_privateContextMenu
->Append(wxID_COPY
, _("&Copy"));
2224 m_privateContextMenu
->Append(wxID_PASTE
, _("&Paste"));
2225 m_privateContextMenu
->Append(wxID_CLEAR
, _("&Delete"));
2226 m_privateContextMenu
->AppendSeparator();
2227 m_privateContextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
2229 PopupMenu(m_privateContextMenu
);
2237 void wxTextCtrl::OnSetFocus(wxFocusEvent
& event
)
2239 // be sure the caret remains invisible if the user had hidden it
2240 if ( !m_isNativeCaretShown
)
2242 ::HideCaret(GetHwnd());
2248 // the rest of the file only deals with the rich edit controls
2251 // ----------------------------------------------------------------------------
2252 // EN_LINK processing
2253 // ----------------------------------------------------------------------------
2255 bool wxTextCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2257 NMHDR
*hdr
= (NMHDR
* )lParam
;
2258 switch ( hdr
->code
)
2262 const MSGFILTER
*msgf
= (MSGFILTER
*)lParam
;
2263 UINT msg
= msgf
->msg
;
2265 // this is a bit crazy but richedit 1.0 sends us all mouse
2266 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2267 // generate the wxWin events for this message manually
2269 // NB: in fact, this is still not totally correct as it does
2270 // send us WM_LBUTTONUP if the selection was cleared by the
2271 // last click -- so currently we get 2 events in this case,
2272 // but as I don't see any obvious way to check for this I
2273 // leave this code in place because it's still better than
2274 // not getting left up events at all
2275 if ( msg
== WM_LBUTTONUP
)
2277 WXUINT flags
= msgf
->wParam
;
2278 int x
= GET_X_LPARAM(msgf
->lParam
),
2279 y
= GET_Y_LPARAM(msgf
->lParam
);
2281 HandleMouseEvent(msg
, x
, y
, flags
);
2285 // return true to process the event (and false to ignore it)
2290 const ENLINK
*enlink
= (ENLINK
*)hdr
;
2292 switch ( enlink
->msg
)
2295 // ok, so it is hardcoded - do we really nee to
2298 wxCursor
cur(wxCURSOR_HAND
);
2299 ::SetCursor(GetHcursorOf(cur
));
2305 case WM_LBUTTONDOWN
:
2307 case WM_LBUTTONDBLCLK
:
2308 case WM_RBUTTONDOWN
:
2310 case WM_RBUTTONDBLCLK
:
2311 // send a mouse event
2313 static const wxEventType eventsMouse
[] =
2324 // the event ids are consecutive
2326 evtMouse(eventsMouse
[enlink
->msg
- WM_MOUSEMOVE
]);
2328 InitMouseEvent(evtMouse
,
2329 GET_X_LPARAM(enlink
->lParam
),
2330 GET_Y_LPARAM(enlink
->lParam
),
2333 wxTextUrlEvent
event(m_windowId
, evtMouse
,
2335 enlink
->chrg
.cpMax
);
2337 InitCommandEvent(event
);
2339 *result
= ProcessCommand(event
);
2347 // not processed, leave it to the base class
2348 return wxTextCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
2351 #if wxUSE_DRAG_AND_DROP
2353 void wxTextCtrl::SetDropTarget(wxDropTarget
*dropTarget
)
2355 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
2357 // get rid of the built-in drop target
2358 ::RevokeDragDrop(GetHwnd());
2359 m_dropTarget
= NULL
;
2362 wxTextCtrlBase::SetDropTarget(dropTarget
);
2365 #endif // wxUSE_DRAG_AND_DROP
2367 // ----------------------------------------------------------------------------
2368 // colour setting for the rich edit controls
2369 // ----------------------------------------------------------------------------
2371 bool wxTextCtrl::SetBackgroundColour(const wxColour
& colour
)
2373 if ( !wxTextCtrlBase::SetBackgroundColour(colour
) )
2375 // colour didn't really change
2381 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2382 // EM_SETBKGNDCOLOR additionally
2383 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR
, 0, wxColourToRGB(colour
));
2389 bool wxTextCtrl::SetForegroundColour(const wxColour
& colour
)
2391 if ( !wxTextCtrlBase::SetForegroundColour(colour
) )
2393 // colour didn't really change
2399 // change the colour of everything
2400 WinStruct
<CHARFORMAT
> cf
;
2401 cf
.dwMask
= CFM_COLOR
;
2402 cf
.crTextColor
= wxColourToRGB(colour
);
2403 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, SCF_ALL
, (LPARAM
)&cf
);
2409 bool wxTextCtrl::SetFont(const wxFont
& font
)
2411 if ( !wxTextCtrlBase::SetFont(font
) )
2414 if ( GetRichVersion() >= 4 )
2416 // Using WM_SETFONT is not enough with RichEdit 4.1: it does work but
2417 // for ASCII characters only and inserting a non-ASCII one into it
2418 // later reverts to the default font so use EM_SETCHARFORMAT to change
2419 // the default font for it.
2422 SetStyle(-1, -1, attr
);
2428 // ----------------------------------------------------------------------------
2429 // styling support for rich edit controls
2430 // ----------------------------------------------------------------------------
2432 bool wxTextCtrl::MSWSetCharFormat(const wxTextAttr
& style
, long start
, long end
)
2434 // initialize CHARFORMAT struct
2443 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2444 // CHARFORMAT in that case
2446 if ( m_verRichEdit
== 1 )
2448 // this is the only thing the control is going to grok
2449 cf
.cbSize
= sizeof(CHARFORMAT
);
2454 // CHARFORMAT or CHARFORMAT2
2455 cf
.cbSize
= sizeof(cf
);
2458 if ( style
.HasFont() )
2460 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2461 // but using it doesn't seem to hurt neither so leaving it for now
2463 cf
.dwMask
|= CFM_FACE
| CFM_SIZE
| CFM_CHARSET
|
2464 CFM_ITALIC
| CFM_BOLD
| CFM_UNDERLINE
;
2466 // fill in data from LOGFONT but recalculate lfHeight because we need
2467 // the real height in twips and not the negative number which
2468 // wxFillLogFont() returns (this is correct in general and works with
2469 // the Windows font mapper, but not here)
2471 wxFont
font(style
.GetFont());
2474 wxFillLogFont(&lf
, &font
);
2475 cf
.yHeight
= 20*font
.GetPointSize(); // 1 pt = 20 twips
2476 cf
.bCharSet
= lf
.lfCharSet
;
2477 cf
.bPitchAndFamily
= lf
.lfPitchAndFamily
;
2478 wxStrlcpy(cf
.szFaceName
, lf
.lfFaceName
, WXSIZEOF(cf
.szFaceName
));
2480 // also deal with underline/italic/bold attributes: note that we must
2481 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2482 // style to allow clearing it
2485 cf
.dwEffects
|= CFE_ITALIC
;
2488 if ( lf
.lfWeight
== FW_BOLD
)
2490 cf
.dwEffects
|= CFE_BOLD
;
2493 if ( lf
.lfUnderline
)
2495 cf
.dwEffects
|= CFE_UNDERLINE
;
2498 // strikeout fonts are not supported by wxWidgets
2501 if ( style
.HasTextColour() )
2503 cf
.dwMask
|= CFM_COLOR
;
2504 cf
.crTextColor
= wxColourToRGB(style
.GetTextColour());
2508 if ( m_verRichEdit
!= 1 && style
.HasBackgroundColour() )
2510 cf
.dwMask
|= CFM_BACKCOLOR
;
2511 cf
.crBackColor
= wxColourToRGB(style
.GetBackgroundColour());
2513 #endif // wxUSE_RICHEDIT2
2515 // Apply the style either to the selection or to the entire control.
2517 if ( start
!= -1 || end
!= -1 )
2519 DoSetSelection(start
, end
, SetSel_NoScroll
);
2520 selMode
= SCF_SELECTION
;
2527 if ( !::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, selMode
, (LPARAM
)&cf
) )
2529 wxLogLastError(wxT("SendMessage(EM_SETCHARFORMAT)"));
2536 bool wxTextCtrl::MSWSetParaFormat(const wxTextAttr
& style
, long start
, long end
)
2546 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2547 // PARAFORMAT in that case
2549 if ( m_verRichEdit
== 1 )
2551 // this is the only thing the control is going to grok
2552 pf
.cbSize
= sizeof(PARAFORMAT
);
2557 // PARAFORMAT or PARAFORMAT2
2558 pf
.cbSize
= sizeof(pf
);
2561 if (style
.HasAlignment())
2563 pf
.dwMask
|= PFM_ALIGNMENT
;
2564 if (style
.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
2565 pf
.wAlignment
= PFA_RIGHT
;
2566 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
2567 pf
.wAlignment
= PFA_CENTER
;
2568 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED
)
2569 pf
.wAlignment
= PFA_JUSTIFY
;
2571 pf
.wAlignment
= PFA_LEFT
;
2574 if (style
.HasLeftIndent())
2576 pf
.dwMask
|= PFM_STARTINDENT
| PFM_OFFSET
;
2578 // Convert from 1/10 mm to TWIPS
2579 pf
.dxStartIndent
= (int) (((double) style
.GetLeftIndent()) * mm2twips
/ 10.0) ;
2580 pf
.dxOffset
= (int) (((double) style
.GetLeftSubIndent()) * mm2twips
/ 10.0) ;
2583 if (style
.HasRightIndent())
2585 pf
.dwMask
|= PFM_RIGHTINDENT
;
2587 // Convert from 1/10 mm to TWIPS
2588 pf
.dxRightIndent
= (int) (((double) style
.GetRightIndent()) * mm2twips
/ 10.0) ;
2591 if (style
.HasTabs())
2593 pf
.dwMask
|= PFM_TABSTOPS
;
2595 const wxArrayInt
& tabs
= style
.GetTabs();
2597 pf
.cTabCount
= (SHORT
)wxMin(tabs
.GetCount(), MAX_TAB_STOPS
);
2599 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2601 // Convert from 1/10 mm to TWIPS
2602 pf
.rgxTabs
[i
] = (int) (((double) tabs
[i
]) * mm2twips
/ 10.0) ;
2607 if ( m_verRichEdit
> 1 )
2609 if ( wxTheApp
->GetLayoutDirection() == wxLayout_RightToLeft
)
2611 // Use RTL paragraphs in RTL mode to get proper layout
2612 pf
.dwMask
|= PFM_RTLPARA
;
2613 pf
.wEffects
|= PFE_RTLPARA
;
2616 #endif // wxUSE_RICHEDIT2
2620 // Do format the selection.
2621 DoSetSelection(start
, end
, SetSel_NoScroll
);
2623 if ( !::SendMessage(GetHwnd(), EM_SETPARAFORMAT
, 0, (LPARAM
) &pf
) )
2625 wxLogLastError(wxT("SendMessage(EM_SETPARAFORMAT)"));
2634 bool wxTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
2638 // can't do it with normal text control
2642 // the richedit 1.0 doesn't handle setting background colour, so don't
2643 // even try to do anything if it's the only thing we want to change
2644 if ( m_verRichEdit
== 1 && !style
.HasFont() && !style
.HasTextColour() &&
2645 !style
.HasLeftIndent() && !style
.HasRightIndent() && !style
.HasAlignment() &&
2648 // nothing to do: return true if there was really nothing to do and
2649 // false if we failed to set bg colour
2650 return !style
.HasBackgroundColour();
2653 // order the range if needed
2657 // we can only change the format of the selection, so select the range we
2658 // want and restore the old selection later, after MSWSetXXXFormat()
2659 // functions (possibly) change it.
2660 long startOld
, endOld
;
2661 GetSelection(&startOld
, &endOld
);
2663 bool ok
= MSWSetCharFormat(style
, start
, end
);
2664 if ( !MSWSetParaFormat(style
, start
, end
) )
2667 if ( start
!= startOld
|| end
!= endOld
)
2669 // restore the original selection
2670 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2676 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
2678 if ( !wxTextCtrlBase::SetDefaultStyle(style
) )
2683 // we have to do this or the style wouldn't apply for the text typed by
2685 wxTextPos posLast
= GetLastPosition();
2686 SetStyle(posLast
, posLast
, m_defaultStyle
);
2692 bool wxTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
2696 // can't do it with normal text control
2700 // initialize CHARFORMAT struct
2709 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2710 // CHARFORMAT in that case
2712 if ( m_verRichEdit
== 1 )
2714 // this is the only thing the control is going to grok
2715 cf
.cbSize
= sizeof(CHARFORMAT
);
2720 // CHARFORMAT or CHARFORMAT2
2721 cf
.cbSize
= sizeof(cf
);
2723 // we can only change the format of the selection, so select the range we
2724 // want and restore the old selection later
2725 long startOld
, endOld
;
2726 GetSelection(&startOld
, &endOld
);
2728 // but do we really have to change the selection?
2729 bool changeSel
= position
!= startOld
|| position
!= endOld
;
2733 DoSetSelection(position
, position
+ 1, SetSel_NoScroll
);
2736 // get the selection formatting
2737 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT
,
2738 SCF_SELECTION
, (LPARAM
)&cf
) ;
2742 // Convert the height from the units of 1/20th of the point in which
2743 // CHARFORMAT stores it to pixel-based units used by LOGFONT.
2744 const wxCoord ppi
= wxClientDC(this).GetPPI().y
;
2745 lf
.lfHeight
= -MulDiv(cf
.yHeight
/20, ppi
, 72);
2747 lf
.lfCharSet
= ANSI_CHARSET
; // FIXME: how to get correct charset?
2748 lf
.lfClipPrecision
= 0;
2749 lf
.lfEscapement
= 0;
2750 wxStrcpy(lf
.lfFaceName
, cf
.szFaceName
);
2752 //NOTE: we _MUST_ set each of these values to _something_ since we
2753 //do not call wxZeroMemory on the LOGFONT lf
2754 if (cf
.dwEffects
& CFE_ITALIC
)
2757 lf
.lfItalic
= FALSE
;
2759 lf
.lfOrientation
= 0;
2760 lf
.lfPitchAndFamily
= cf
.bPitchAndFamily
;
2763 if (cf
.dwEffects
& CFE_STRIKEOUT
)
2764 lf
.lfStrikeOut
= TRUE
;
2766 lf
.lfStrikeOut
= FALSE
;
2768 if (cf
.dwEffects
& CFE_UNDERLINE
)
2769 lf
.lfUnderline
= TRUE
;
2771 lf
.lfUnderline
= FALSE
;
2773 if (cf
.dwEffects
& CFE_BOLD
)
2774 lf
.lfWeight
= FW_BOLD
;
2776 lf
.lfWeight
= FW_NORMAL
;
2778 wxFont font
= wxCreateFontFromLogFont(& lf
);
2781 style
.SetFont(font
);
2783 style
.SetTextColour(wxColour(cf
.crTextColor
));
2786 if ( m_verRichEdit
!= 1 )
2788 // cf.dwMask |= CFM_BACKCOLOR;
2789 style
.SetBackgroundColour(wxColour(cf
.crBackColor
));
2791 #endif // wxUSE_RICHEDIT2
2793 // now get the paragraph formatting
2796 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2797 // PARAFORMAT in that case
2799 if ( m_verRichEdit
== 1 )
2801 // this is the only thing the control is going to grok
2802 pf
.cbSize
= sizeof(PARAFORMAT
);
2807 // PARAFORMAT or PARAFORMAT2
2808 pf
.cbSize
= sizeof(pf
);
2811 // do format the selection
2812 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT
, 0, (LPARAM
) &pf
) ;
2814 style
.SetLeftIndent( (int) ((double) pf
.dxStartIndent
* twips2mm
* 10.0), (int) ((double) pf
.dxOffset
* twips2mm
* 10.0) );
2815 style
.SetRightIndent( (int) ((double) pf
.dxRightIndent
* twips2mm
* 10.0) );
2817 if (pf
.wAlignment
== PFA_CENTER
)
2818 style
.SetAlignment(wxTEXT_ALIGNMENT_CENTRE
);
2819 else if (pf
.wAlignment
== PFA_RIGHT
)
2820 style
.SetAlignment(wxTEXT_ALIGNMENT_RIGHT
);
2821 else if (pf
.wAlignment
== PFA_JUSTIFY
)
2822 style
.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED
);
2824 style
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
2826 wxArrayInt tabStops
;
2828 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2830 tabStops
.Add( (int) ((double) (pf
.rgxTabs
[i
] & 0xFFFF) * twips2mm
* 10.0) );
2835 // restore the original selection
2836 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2842 // ----------------------------------------------------------------------------
2844 // ----------------------------------------------------------------------------
2846 static const HINSTANCE INVALID_HINSTANCE
= (HINSTANCE
)-1;
2848 bool wxRichEditModule::OnInit()
2850 // don't do anything - we will load it when needed
2854 void wxRichEditModule::OnExit()
2856 for ( size_t i
= 0; i
< WXSIZEOF(ms_hRichEdit
); i
++ )
2858 if ( ms_hRichEdit
[i
] && ms_hRichEdit
[i
] != INVALID_HINSTANCE
)
2860 ::FreeLibrary(ms_hRichEdit
[i
]);
2861 ms_hRichEdit
[i
] = NULL
;
2865 if (ms_inkEditLib
.IsLoaded())
2866 ms_inkEditLib
.Unload();
2871 bool wxRichEditModule::Load(Version version
)
2873 if ( ms_hRichEdit
[version
] == INVALID_HINSTANCE
)
2875 // we had already tried to load it and failed
2879 if ( ms_hRichEdit
[version
] )
2881 // we've already got this one
2885 static const wxChar
*const dllnames
[] =
2892 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames
) == Version_Max
,
2893 RichEditDllNamesVersionsMismatch
);
2895 ms_hRichEdit
[version
] = ::LoadLibrary(dllnames
[version
]);
2897 if ( !ms_hRichEdit
[version
] )
2899 ms_hRichEdit
[version
] = INVALID_HINSTANCE
;
2908 // load the InkEdit library
2909 bool wxRichEditModule::LoadInkEdit()
2911 if (ms_inkEditLibLoadAttemped
)
2912 return ms_inkEditLib
.IsLoaded();
2914 ms_inkEditLibLoadAttemped
= true;
2917 return ms_inkEditLib
.Load(wxT("inked"));
2919 #endif // wxUSE_INKEDIT
2922 #endif // wxUSE_RICHEDIT
2924 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)