1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textctrl.cpp
4 // Author: Julian Smart
7 // Copyright: (c) Julian Smart
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
26 #if wxUSE_TEXTCTRL && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
29 #include "wx/textctrl.h"
30 #include "wx/settings.h"
32 #include "wx/dcclient.h"
39 #include "wx/module.h"
40 #include "wx/wxcrtvararg.h"
43 #include "wx/sysopt.h"
46 #include "wx/clipbrd.h"
49 #include "wx/textfile.h"
53 #include "wx/msw/private.h"
54 #include "wx/msw/winundef.h"
55 #include "wx/msw/mslu.h"
61 #include <sys/types.h>
66 // old mingw32 has richedit stuff directly in windows.h and doesn't have
68 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
72 #endif // wxUSE_RICHEDIT
74 #include "wx/msw/missing.h"
76 // FIXME-VC6: This seems to be only missing from VC6 headers.
77 #ifndef SPI_GETCARETWIDTH
78 #define SPI_GETCARETWIDTH 0x2006
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
.t_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
|
502 if ( IsSingleLine() )
504 // If we don't set the margins explicitly, their size depends on the
505 // control initial size, see #2438. So explicitly set them to something
506 // consistent. And for this we have 2 candidates: EC_USEFONTINFO (which
507 // sets the left margin to 3 pixels, at least under Windows 7) or 0. We
508 // use the former because it looks like it was meant to be used as the
509 // default (what else would it be there for?) and 0 looks bad in
510 // classic mode, i.e. without themes. Also, the margin can be reset to
511 // 0 easily by calling SetMargins() explicitly but setting it to the
512 // default value is not currently supported.
514 // Finally, notice that EC_USEFONTINFO is used differently for plain
515 // and rich text controls.
520 wParam
= EC_USEFONTINFO
;
523 else // plain EDIT, EC_USEFONTINFO is used in lParam with them.
525 wParam
= EC_LEFTMARGIN
| EC_RIGHTMARGIN
;
526 lParam
= MAKELPARAM(EC_USEFONTINFO
, EC_USEFONTINFO
);
529 ::SendMessage(GetHwnd(), EM_SETMARGINS
, wParam
, lParam
);
531 #endif // !__WXWINCE__
536 // Make sure the window style (etc.) reflects the HWND style (roughly)
537 void wxTextCtrl::AdoptAttributesFromHWND()
539 wxWindow::AdoptAttributesFromHWND();
541 HWND hWnd
= GetHwnd();
542 long style
= ::GetWindowLong(hWnd
, GWL_STYLE
);
544 // retrieve the style to see whether this is an edit or richedit ctrl
546 wxString classname
= wxGetWindowClass(GetHWND());
548 if ( classname
.IsSameAs(wxT("EDIT"), false /* no case */) )
555 if ( wxSscanf(classname
, wxT("RichEdit%d0%c"), &m_verRichEdit
, &c
) != 2 )
557 wxLogDebug(wxT("Unknown edit control '%s'."), classname
.c_str());
562 #endif // wxUSE_RICHEDIT
564 if (style
& ES_MULTILINE
)
565 m_windowStyle
|= wxTE_MULTILINE
;
566 if (style
& ES_PASSWORD
)
567 m_windowStyle
|= wxTE_PASSWORD
;
568 if (style
& ES_READONLY
)
569 m_windowStyle
|= wxTE_READONLY
;
570 if (style
& ES_WANTRETURN
)
571 m_windowStyle
|= wxTE_PROCESS_ENTER
;
572 if (style
& ES_CENTER
)
573 m_windowStyle
|= wxTE_CENTRE
;
574 if (style
& ES_RIGHT
)
575 m_windowStyle
|= wxTE_RIGHT
;
578 WXDWORD
wxTextCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
580 long msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
582 // styles which we always add by default
583 if ( style
& wxTE_MULTILINE
)
585 msStyle
|= ES_MULTILINE
| ES_WANTRETURN
;
586 if ( !(style
& wxTE_NO_VSCROLL
) )
588 // always adjust the vertical scrollbar automatically if we have it
589 msStyle
|= WS_VSCROLL
| ES_AUTOVSCROLL
;
592 // we have to use this style for the rich edit controls because
593 // without it the vertical scrollbar never appears at all in
594 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
595 if ( style
& wxTE_RICH2
)
597 msStyle
|= ES_DISABLENOSCROLL
;
599 #endif // wxUSE_RICHEDIT
602 style
|= wxTE_PROCESS_ENTER
;
606 // there is really no reason to not have this style for single line
608 msStyle
|= ES_AUTOHSCROLL
;
611 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
612 // scrollbar, there is no wrapping -- which makes sense
613 if ( style
& wxTE_DONTWRAP
)
615 // automatically scroll the control horizontally as necessary
617 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
618 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
619 // it doesn't seem to do any harm for plain edit controls, add it
621 msStyle
|= WS_HSCROLL
| ES_AUTOHSCROLL
;
624 if ( style
& wxTE_READONLY
)
625 msStyle
|= ES_READONLY
;
627 if ( style
& wxTE_PASSWORD
)
628 msStyle
|= ES_PASSWORD
;
630 if ( style
& wxTE_NOHIDESEL
)
631 msStyle
|= ES_NOHIDESEL
;
633 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
634 if ( style
& wxTE_CENTRE
)
635 msStyle
|= ES_CENTER
;
636 else if ( style
& wxTE_RIGHT
)
639 msStyle
|= ES_LEFT
; // ES_LEFT is 0 as well but for consistency...
644 void wxTextCtrl::SetWindowStyleFlag(long style
)
646 // changing the alignment of the control dynamically works under Win2003
647 // (but not older Windows version: it seems to work under some versions of
648 // XP but not other ones, and we have no way to determine it so be
649 // conservative here) and only for plain EDIT controls (not RICH ones) and
650 // we have to recreate the control to make it always work
651 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003
)
653 const long alignMask
= wxTE_LEFT
| wxTE_CENTRE
| wxTE_RIGHT
;
654 if ( (style
& alignMask
) != (GetWindowStyle() & alignMask
) )
656 const wxString value
= GetValue();
657 const wxPoint pos
= GetPosition();
658 const wxSize size
= GetSize();
660 // delete the old window
661 HWND hwnd
= GetHwnd();
663 ::DestroyWindow(hwnd
);
665 // create the new one with the updated flags
666 m_windowStyle
= style
;
667 MSWCreateText(value
, pos
, size
);
669 // and make sure it has the same attributes as before
672 // calling SetFont(m_font) would do nothing as the code would
673 // notice that the font didn't change, so force it to believe
675 wxFont font
= m_font
;
682 wxColour colFg
= m_foregroundColour
;
683 m_foregroundColour
= wxNullColour
;
684 SetForegroundColour(colFg
);
689 wxColour colBg
= m_backgroundColour
;
690 m_backgroundColour
= wxNullColour
;
691 SetBackgroundColour(colBg
);
694 // note that text styles are lost but this is probably not a big
695 // problem: if you use styles, you probably don't use nor change
696 // alignment flags anyhow
703 // we have to deal with some styles separately because they can't be
704 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
705 // using richedit-specific EM_SETOPTIONS
707 ((style
& wxTE_NOHIDESEL
) != (GetWindowStyle() & wxTE_NOHIDESEL
)) )
709 bool set
= (style
& wxTE_NOHIDESEL
) != 0;
711 ::SendMessage(GetHwnd(), EM_SETOPTIONS
, set
? ECOOP_OR
: ECOOP_AND
,
712 set
? ECO_NOHIDESEL
: ~ECO_NOHIDESEL
);
714 #endif // wxUSE_RICHEDIT
716 wxControl::SetWindowStyleFlag(style
);
719 // ----------------------------------------------------------------------------
720 // set/get the controls text
721 // ----------------------------------------------------------------------------
723 bool wxTextCtrl::IsEmpty() const
725 // this is an optimization for multiline controls containing a lot of text
726 if ( IsMultiLine() && GetNumberOfLines() != 1 )
729 return wxTextCtrlBase::IsEmpty();
732 wxString
wxTextCtrl::GetValue() const
734 // range 0..-1 is special for GetRange() and means to retrieve all text
735 return GetRange(0, -1);
738 wxString
wxTextCtrl::GetRange(long from
, long to
) const
742 if ( from
>= to
&& to
!= -1 )
744 // nothing to retrieve
751 int len
= GetWindowTextLength(GetHwnd());
758 // we must use EM_STREAMOUT if we don't want to lose all characters
759 // not representable in the current character set (EM_GETTEXTRANGE
760 // simply replaces them with question marks...)
761 if ( GetRichVersion() > 1 )
763 // we must have some encoding, otherwise any 8bit chars in the
764 // control are simply *lost* (replaced by '?')
765 wxFontEncoding encoding
= wxFONTENCODING_SYSTEM
;
767 wxFont font
= m_defaultStyle
.GetFont();
773 encoding
= font
.GetEncoding();
777 if ( encoding
== wxFONTENCODING_SYSTEM
)
779 encoding
= wxLocale::GetSystemEncoding();
783 if ( encoding
== wxFONTENCODING_SYSTEM
)
785 encoding
= wxFONTENCODING_ISO8859_1
;
788 str
= StreamOut(encoding
);
792 // we have to manually extract the required part, luckily
793 // this is easy in this case as EOL characters in str are
794 // just LFs because we remove CRs in wxRichEditStreamOut
795 str
= str
.Mid(from
, to
- from
);
799 // StreamOut() wasn't used or failed, try to do it in normal way
801 #endif // !wxUSE_UNICODE
803 // alloc one extra WORD as needed by the control
804 wxStringBuffer
tmp(str
, ++len
);
808 textRange
.chrg
.cpMin
= from
;
809 textRange
.chrg
.cpMax
= to
;
810 textRange
.lpstrText
= p
;
812 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE
,
813 0, (LPARAM
)&textRange
);
815 if ( m_verRichEdit
> 1 )
817 // RichEdit 2.0 uses just CR ('\r') for the
818 // newlines which is neither Unix nor Windows
819 // style - convert it to something reasonable
822 if ( *p
== wxT('\r') )
828 if ( m_verRichEdit
== 1 )
830 // convert to the canonical form - see comment below
831 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
834 //else: no text at all, leave the string empty
837 #endif // wxUSE_RICHEDIT
839 // retrieve all text: wxTextEntry method works even for multiline
840 // controls and must be used for single line ones to account for hints
841 str
= wxTextEntry::GetValue();
843 // need only a range?
846 str
= str
.Mid(from
, to
- from
);
849 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
850 // canonical one (same one as above) for consistency with the other kinds
851 // of controls and, more importantly, with the other ports
852 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
858 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
860 // if the text is long enough, it's faster to just set it instead of first
861 // comparing it with the old one (chances are that it will be different
862 // anyhow, this comparison is there to avoid flicker for small single-line
863 // edit controls mostly)
864 if ( (value
.length() > 0x400) || (value
!= DoGetValue()) )
866 DoWriteText(value
, flags
/* doesn't include SelectionOnly here */);
868 // mark the control as being not dirty - we changed its text, not the
872 // for compatibility, don't move the cursor when doing SetValue()
873 SetInsertionPoint(0);
877 // still reset the modified flag even if the value didn't really change
878 // because now it comes from the program and not the user (and do it
879 // before generating the event so that the event handler could get the
880 // expected value from IsModified())
883 // still send an event for consistency
884 if (flags
& SetValue_SendEvent
)
889 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
891 // TODO: using memcpy() would improve performance a lot for big amounts of text
894 wxRichEditStreamIn(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
898 const wchar_t ** const ppws
= (const wchar_t **)dwCookie
;
900 wchar_t *wbuf
= (wchar_t *)buf
;
901 const wchar_t *wpc
= *ppws
;
906 cb
-= sizeof(wchar_t);
907 (*pcb
) += sizeof(wchar_t);
915 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
916 struct wxStreamOutData
923 wxRichEditStreamOut(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
927 wxStreamOutData
*data
= (wxStreamOutData
*)dwCookie
;
929 const wchar_t *wbuf
= (const wchar_t *)buf
;
930 wchar_t *wpc
= data
->wpc
;
933 wchar_t wch
= *wbuf
++;
935 // turn "\r\n" into "\n" on the fly
941 cb
-= sizeof(wchar_t);
942 (*pcb
) += sizeof(wchar_t);
951 #if wxUSE_UNICODE_MSLU
952 #define UNUSED_IF_MSLU(param)
954 #define UNUSED_IF_MSLU(param) param
958 wxTextCtrl::StreamIn(const wxString
& value
,
959 wxFontEncoding
UNUSED_IF_MSLU(encoding
),
962 #if wxUSE_UNICODE_MSLU
963 const wchar_t *wpc
= value
.c_str();
964 #else // !wxUSE_UNICODE_MSLU
965 wxCSConv
conv(encoding
);
967 const size_t len
= conv
.MB2WC(NULL
, value
.mb_str(), value
.length());
969 if (len
== wxCONV_FAILED
)
972 wxWCharBuffer
wchBuf(len
); // allocates one extra character
973 wchar_t *wpc
= wchBuf
.data();
975 conv
.MB2WC(wpc
, value
.mb_str(), len
+ 1);
976 #endif // wxUSE_UNICODE_MSLU
978 // finally, stream it in the control
981 eds
.dwCookie
= (DWORD_PTR
)&wpc
;
982 // the cast below is needed for broken (very) old mingw32 headers
983 eds
.pfnCallback
= (EDITSTREAMCALLBACK
)wxRichEditStreamIn
;
985 // same problem as in DoWriteText(): we can get multiple events here
986 UpdatesCountFilter
ucf(m_updatesCount
);
988 ::SendMessage(GetHwnd(), EM_STREAMIN
,
991 (selectionOnly
? SFF_SELECTION
: 0),
994 // It's okay for EN_UPDATE to not be sent if the selection is empty and
995 // the text is empty, otherwise warn the programmer about it.
996 wxASSERT_MSG( ucf
.GotUpdate() || ( !HasSelection() && value
.empty() ),
997 wxT("EM_STREAMIN didn't send EN_UPDATE?") );
1001 wxLogLastError(wxT("EM_STREAMIN"));
1007 #if !wxUSE_UNICODE_MSLU
1010 wxTextCtrl::StreamOut(wxFontEncoding encoding
, bool selectionOnly
) const
1014 const int len
= GetWindowTextLength(GetHwnd());
1016 wxWCharBuffer
wchBuf(len
);
1017 wchar_t *wpc
= wchBuf
.data();
1019 wxStreamOutData data
;
1025 eds
.dwCookie
= (DWORD_PTR
)&data
;
1026 eds
.pfnCallback
= wxRichEditStreamOut
;
1032 SF_TEXT
| SF_UNICODE
| (selectionOnly
? SFF_SELECTION
: 0),
1038 wxLogLastError(wxT("EM_STREAMOUT"));
1040 else // streamed out ok
1042 // NUL-terminate the string because its length could have been
1043 // decreased by wxRichEditStreamOut
1044 *(wchBuf
.data() + data
.len
) = L
'\0';
1046 // now convert to the given encoding (this is a possibly lossful
1047 // conversion but what else can we do)
1048 wxCSConv
conv(encoding
);
1049 size_t lenNeeded
= conv
.WC2MB(NULL
, wchBuf
, 0);
1051 if ( lenNeeded
!= wxCONV_FAILED
&& lenNeeded
++ )
1053 conv
.WC2MB(wxStringBuffer(out
, lenNeeded
), wchBuf
, lenNeeded
);
1060 #endif // !wxUSE_UNICODE_MSLU
1062 #endif // wxUSE_RICHEDIT
1064 void wxTextCtrl::WriteText(const wxString
& value
)
1069 void wxTextCtrl::DoWriteText(const wxString
& value
, int flags
)
1071 bool selectionOnly
= (flags
& SetValue_SelectionOnly
) != 0;
1073 if ( m_windowStyle
& wxTE_MULTILINE
)
1074 valueDos
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
1079 // there are several complications with the rich edit controls here
1083 // first, ensure that the new text will be in the default style
1084 if ( !m_defaultStyle
.IsDefault() )
1087 GetSelection(&start
, &end
);
1088 SetStyle(start
, end
, m_defaultStyle
);
1091 #if wxUSE_UNICODE_MSLU
1092 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1093 // but EM_STREAMIN works
1094 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1096 done
= StreamIn(valueDos
, wxFONTENCODING_SYSTEM
, selectionOnly
);
1098 #endif // wxUSE_UNICODE_MSLU
1101 // next check if the text we're inserting must be shown in a non
1102 // default charset -- this only works for RichEdit > 1.0
1103 if ( GetRichVersion() > 1 )
1105 wxFont font
= m_defaultStyle
.GetFont();
1111 wxFontEncoding encoding
= font
.GetEncoding();
1112 if ( encoding
!= wxFONTENCODING_SYSTEM
)
1114 // we have to use EM_STREAMIN to force richedit control 2.0+
1115 // to show any text in the non default charset -- otherwise
1116 // it thinks it knows better than we do and always shows it
1117 // in the default one
1118 done
= StreamIn(valueDos
, encoding
, selectionOnly
);
1122 #endif // !wxUSE_UNICODE
1126 #endif // wxUSE_RICHEDIT
1128 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1129 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1130 // -- undetermined -- conditions with rich edit) and sometimes we don't
1131 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1132 // we generate exactly one of them by ignoring all but the first one in
1133 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1134 // notifications from Windows
1135 if ( !(flags
& SetValue_SendEvent
) )
1136 m_updatesCount
= -2; // suppress any update event
1138 UpdatesCountFilter
ucf(m_updatesCount
);
1140 ::SendMessage(GetHwnd(), selectionOnly
? EM_REPLACESEL
: WM_SETTEXT
,
1141 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1142 selectionOnly
? 1 : 0, wxMSW_CONV_LPARAM(valueDos
));
1144 if ( !ucf
.GotUpdate() && (flags
& SetValue_SendEvent
) )
1151 void wxTextCtrl::AppendText(const wxString
& text
)
1153 wxTextEntry::AppendText(text
);
1156 // don't do this if we're frozen, saves some time
1157 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1159 ::SendMessage(GetHwnd(), WM_VSCROLL
, SB_BOTTOM
, (LPARAM
)NULL
);
1161 #endif // wxUSE_RICHEDIT
1164 void wxTextCtrl::Clear()
1166 ::SetWindowText(GetHwnd(), wxEmptyString
);
1168 if ( IsMultiLine() && !IsRich() )
1170 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1171 // but the normal ones don't -- make Clear() behaviour consistent by
1172 // always sending this event
1179 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent
& event
)
1183 size_t lenOld
= GetValue().length();
1185 wxUint32 code
= event
.GetRawKeyCode();
1186 ::keybd_event((BYTE
)code
, 0, 0 /* key press */, 0);
1187 ::keybd_event((BYTE
)code
, 0, KEYEVENTF_KEYUP
, 0);
1189 // assume that any alphanumeric key changes the total number of characters
1190 // in the control - this should work in 99% of cases
1191 return GetValue().length() != lenOld
;
1196 // ----------------------------------------------------------------------------
1198 // ----------------------------------------------------------------------------
1200 void wxTextCtrl::SetInsertionPointEnd()
1202 // we must not do anything if the caret is already there because calling
1203 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1204 // if it doesn't actually move the caret anywhere and so the simple fact of
1205 // doing it results in horrible flicker when appending big amounts of text
1206 // to the control in a few chunks (see DoAddText() test in the text sample)
1207 const wxTextPos lastPosition
= GetLastPosition();
1208 if ( GetInsertionPoint() == lastPosition
)
1213 SetInsertionPoint(lastPosition
);
1216 long wxTextCtrl::GetInsertionPoint() const
1224 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &range
);
1227 #endif // wxUSE_RICHEDIT
1229 return wxTextEntry::GetInsertionPoint();
1232 wxTextPos
wxTextCtrl::GetLastPosition() const
1234 if ( IsMultiLine() )
1236 int numLines
= GetNumberOfLines();
1237 long posStartLastLine
= XYToPosition(0, numLines
- 1);
1239 long lenLastLine
= GetLengthOfLineContainingPos(posStartLastLine
);
1241 return posStartLastLine
+ lenLastLine
;
1244 return wxTextEntry::GetLastPosition();
1247 // If the return values from and to are the same, there is no
1249 void wxTextCtrl::GetSelection(long *from
, long *to
) const
1254 CHARRANGE charRange
;
1255 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &charRange
);
1257 *from
= charRange
.cpMin
;
1258 *to
= charRange
.cpMax
;
1261 #endif // !wxUSE_RICHEDIT
1263 wxTextEntry::GetSelection(from
, to
);
1267 // ----------------------------------------------------------------------------
1269 // ----------------------------------------------------------------------------
1271 void wxTextCtrl::DoSetSelection(long from
, long to
, int flags
)
1273 HWND hWnd
= GetHwnd();
1278 // if from and to are both -1, it means (in wxWidgets) that all text
1279 // should be selected, translate this into Windows convention
1280 if ( (from
== -1) && (to
== -1) )
1288 ::SendMessage(hWnd
, EM_EXSETSEL
, 0, (LPARAM
)&range
);
1291 #endif // wxUSE_RICHEDIT
1293 wxTextEntry::DoSetSelection(from
, to
, flags
);
1296 if ( (flags
& SetSel_Scroll
) && !IsFrozen() )
1299 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1300 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1301 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1302 // option is set (but it does work ok in richedit 1.0 mode...)
1304 // so to make it work we either need to give focus to it here which
1305 // will probably create many problems (dummy focus events; window
1306 // containing the text control being brought to foreground
1307 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1308 // create other problems too -- and in fact it does because if we turn
1309 // on/off this style while appending the text to the control, the
1310 // vertical scrollbar never appears in it even if we append tons of
1311 // text and to work around this the only solution I found was to use
1312 // ES_DISABLENOSCROLL
1314 // this is very ugly but I don't see any other way to make this work
1316 if ( GetRichVersion() > 1 )
1318 if ( !HasFlag(wxTE_NOHIDESEL
) )
1320 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1321 // others, remember the style so we can reset it later if needed
1322 style
= ::GetWindowLong(GetHwnd(), GWL_STYLE
);
1323 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1324 ECOOP_OR
, ECO_NOHIDESEL
);
1326 //else: everything is already ok
1328 #endif // wxUSE_RICHEDIT
1330 ::SendMessage(hWnd
, EM_SCROLLCARET
, 0, (LPARAM
)0);
1333 // restore ECO_NOHIDESEL if we changed it
1334 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL
) )
1336 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1337 ECOOP_AND
, ~ECO_NOHIDESEL
);
1338 if ( style
!= ::GetWindowLong(GetHwnd(), GWL_STYLE
) )
1339 ::SetWindowLong(GetHwnd(), GWL_STYLE
, style
);
1341 #endif // wxUSE_RICHEDIT
1345 // ----------------------------------------------------------------------------
1346 // Working with files
1347 // ----------------------------------------------------------------------------
1349 bool wxTextCtrl::DoLoadFile(const wxString
& file
, int fileType
)
1351 if ( wxTextCtrlBase::DoLoadFile(file
, fileType
) )
1353 // update the size limit if needed
1362 // ----------------------------------------------------------------------------
1364 // ----------------------------------------------------------------------------
1366 bool wxTextCtrl::IsModified() const
1368 return ::SendMessage(GetHwnd(), EM_GETMODIFY
, 0, 0) != 0;
1371 void wxTextCtrl::MarkDirty()
1373 ::SendMessage(GetHwnd(), EM_SETMODIFY
, TRUE
, 0);
1376 void wxTextCtrl::DiscardEdits()
1378 ::SendMessage(GetHwnd(), EM_SETMODIFY
, FALSE
, 0);
1381 // ----------------------------------------------------------------------------
1382 // Positions <-> coords
1383 // ----------------------------------------------------------------------------
1385 int wxTextCtrl::GetNumberOfLines() const
1387 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT
, 0, 0);
1390 long wxTextCtrl::XYToPosition(long x
, long y
) const
1392 // This gets the char index for the _beginning_ of this line
1393 long charIndex
= ::SendMessage(GetHwnd(), EM_LINEINDEX
, y
, 0);
1395 return charIndex
+ x
;
1398 bool wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
1400 HWND hWnd
= GetHwnd();
1402 // This gets the line number containing the character
1407 lineNo
= ::SendMessage(hWnd
, EM_EXLINEFROMCHAR
, 0, pos
);
1410 #endif // wxUSE_RICHEDIT
1412 lineNo
= ::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1421 // This gets the char index for the _beginning_ of this line
1422 long charIndex
= ::SendMessage(hWnd
, EM_LINEINDEX
, lineNo
, 0);
1423 if ( charIndex
== -1 )
1428 // The X position must therefore be the different between pos and charIndex
1430 *x
= pos
- charIndex
;
1437 wxTextCtrlHitTestResult
1438 wxTextCtrl::HitTest(const wxPoint
& pt
, long *posOut
) const
1440 // first get the position from Windows
1447 // for rich edit controls the position is passed iva the struct fields
1450 lParam
= (LPARAM
)&ptl
;
1453 #endif // wxUSE_RICHEDIT
1455 // for the plain ones, we are limited to 16 bit positions which are
1456 // combined in a single 32 bit value
1457 lParam
= MAKELPARAM(pt
.x
, pt
.y
);
1460 LRESULT pos
= ::SendMessage(GetHwnd(), EM_CHARFROMPOS
, 0, lParam
);
1464 // this seems to indicate an error...
1465 return wxTE_HT_UNKNOWN
;
1470 #endif // wxUSE_RICHEDIT
1472 // for plain EDIT controls the higher word contains something else
1477 // next determine where it is relatively to our point: EM_CHARFROMPOS
1478 // always returns the closest character but we need to be more precise, so
1479 // double check that we really are where it pretends
1483 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1484 // we don't know how to do it
1487 ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&ptReal
, pos
);
1490 #endif // wxUSE_RICHEDIT
1492 LRESULT lRc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1496 // this is apparently returned when pos corresponds to the last
1503 ptReal
.x
= LOWORD(lRc
);
1504 ptReal
.y
= HIWORD(lRc
);
1508 wxTextCtrlHitTestResult rc
;
1510 if ( pt
.y
> ptReal
.y
+ GetCharHeight() )
1512 else if ( pt
.x
> ptReal
.x
+ GetCharWidth() )
1513 rc
= wxTE_HT_BEYOND
;
1515 rc
= wxTE_HT_ON_TEXT
;
1523 wxPoint
wxTextCtrl::DoPositionToCoords(long pos
) const
1525 // FIXME: This code is broken for rich edit version 2.0 as it uses the same
1526 // API as plain edit i.e. the coordinates are returned directly instead of
1527 // filling the POINT passed as WPARAM with them but we can't distinguish
1528 // between 2.0 and 3.0 unfortunately (see also the use of EM_POSFROMCHAR
1534 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&pt
, pos
);
1536 return wxPoint(pt
.x
, pt
.y
);
1539 #endif // wxUSE_RICHEDIT
1541 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1544 // Finding coordinates for the last position of the control fails
1545 // in plain EDIT control, try to compensate for it by finding it
1546 // ourselves from the position of the previous character.
1547 if ( pos
< GetLastPosition() )
1549 // It's not the expected correctable failure case so just fail.
1550 return wxDefaultPosition
;
1555 // We're being asked the coordinates of the first (and last and
1556 // only) position in an empty control. There is no way to get
1557 // it directly with EM_POSFROMCHAR but EM_GETMARGINS returns
1558 // the correct value for at least the horizontal offset.
1559 rc
= ::SendMessage(GetHwnd(), EM_GETMARGINS
, 0, 0);
1561 // Text control seems to effectively add 1 to margin.
1562 return wxPoint(LOWORD(rc
) + 1, 1);
1565 // We do have a previous character, try to get its coordinates.
1566 rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
- 1, 0);
1569 // If getting coordinates of the previous character failed as
1570 // well, just give up.
1571 return wxDefaultPosition
;
1574 wxString prevChar
= GetRange(pos
- 1, pos
);
1575 wxSize prevCharSize
= GetTextExtent(prevChar
);
1577 if ( prevChar
== wxT("\n" ))
1579 // 'pos' is at the beginning of a new line so its X coordinate
1580 // should be the same as X coordinate of the first character of
1581 // any other line while its Y coordinate will be approximately
1582 // (but we can't compute it exactly...) one character height
1583 // more than that of the previous character.
1584 LRESULT coords0
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, 0, 0);
1585 if ( coords0
== -1 )
1586 return wxDefaultPosition
;
1588 rc
= MAKELPARAM(LOWORD(coords0
), HIWORD(rc
) + prevCharSize
.y
);
1592 // Simple case: previous character is in the same line so this
1593 // one is just after it.
1594 rc
+= MAKELPARAM(prevCharSize
.x
, 0);
1598 // Notice that {LO,HI}WORD macros return WORDs, i.e. unsigned shorts,
1599 // while we want to have signed values here (the y coordinate of any
1600 // position above the first currently visible line is negative, for
1601 // example), hence the need for casts.
1602 return wxPoint(static_cast<short>(LOWORD(rc
)),
1603 static_cast<short>(HIWORD(rc
)));
1606 return wxDefaultPosition
;
1610 // ----------------------------------------------------------------------------
1612 // ----------------------------------------------------------------------------
1614 void wxTextCtrl::ShowPosition(long pos
)
1616 HWND hWnd
= GetHwnd();
1618 // To scroll to a position, we pass the number of lines and characters
1619 // to scroll *by*. This means that we need to:
1620 // (1) Find the line position of the current line.
1621 // (2) Find the line position of pos.
1622 // (3) Scroll by (pos - current).
1623 // For now, ignore the horizontal scrolling.
1625 // Is this where scrolling is relative to - the line containing the caret?
1626 // Or is the first visible line??? Try first visible line.
1627 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, -1, 0L);
1629 int currentLineLineNo
= (int)::SendMessage(hWnd
, EM_GETFIRSTVISIBLELINE
, 0, 0);
1631 int specifiedLineLineNo
= (int)::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1633 int linesToScroll
= specifiedLineLineNo
- currentLineLineNo
;
1635 if (linesToScroll
!= 0)
1636 ::SendMessage(hWnd
, EM_LINESCROLL
, 0, linesToScroll
);
1639 long wxTextCtrl::GetLengthOfLineContainingPos(long pos
) const
1641 return ::SendMessage(GetHwnd(), EM_LINELENGTH
, pos
, 0);
1644 int wxTextCtrl::GetLineLength(long lineNo
) const
1646 long pos
= XYToPosition(0, lineNo
);
1648 return GetLengthOfLineContainingPos(pos
);
1651 wxString
wxTextCtrl::GetLineText(long lineNo
) const
1653 size_t len
= (size_t)GetLineLength(lineNo
) + 1;
1655 // there must be at least enough place for the length WORD in the
1657 len
+= sizeof(WORD
);
1661 wxStringBufferLength
tmp(str
, len
);
1664 *(WORD
*)buf
= (WORD
)len
;
1665 len
= (size_t)::SendMessage(GetHwnd(), EM_GETLINE
, lineNo
, (LPARAM
)buf
);
1670 // remove the '\r' returned by the rich edit control, the user code
1671 // should never see it
1672 if ( buf
[len
- 2] == wxT('\r') && buf
[len
- 1] == wxT('\n') )
1674 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1675 // here and "\n" below
1676 buf
[len
- 2] = wxT('\n');
1679 else if ( buf
[len
- 1] == wxT('\r') )
1681 // richedit 2.0+ uses only "\r", replace it with "\n"
1682 buf
[len
- 1] = wxT('\n');
1685 #endif // wxUSE_RICHEDIT
1687 // remove the '\n' at the end, if any (this is how this function is
1688 // supposed to work according to the docs)
1689 if ( buf
[len
- 1] == wxT('\n') )
1701 void wxTextCtrl::SetMaxLength(unsigned long len
)
1706 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT
, 0, len
? len
: 0x7fffffff);
1709 #endif // wxUSE_RICHEDIT
1711 wxTextEntry::SetMaxLength(len
);
1715 // ----------------------------------------------------------------------------
1717 // ----------------------------------------------------------------------------
1719 void wxTextCtrl::Redo()
1722 if ( GetRichVersion() > 1 )
1724 ::SendMessage(GetHwnd(), EM_REDO
, 0, 0);
1727 #endif // wxUSE_RICHEDIT
1729 wxTextEntry::Redo();
1732 bool wxTextCtrl::CanRedo() const
1735 if ( GetRichVersion() > 1 )
1736 return ::SendMessage(GetHwnd(), EM_CANREDO
, 0, 0) != 0;
1737 #endif // wxUSE_RICHEDIT
1739 return wxTextEntry::CanRedo();
1742 // ----------------------------------------------------------------------------
1743 // caret handling (Windows only)
1744 // ----------------------------------------------------------------------------
1746 bool wxTextCtrl::ShowNativeCaret(bool show
)
1748 if ( show
!= m_isNativeCaretShown
)
1750 if ( !(show
? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1752 // not an error, may simply indicate that it's not shown/hidden
1753 // yet (i.e. it had been hidden/shown 2 times before)
1757 m_isNativeCaretShown
= show
;
1763 // ----------------------------------------------------------------------------
1764 // implementation details
1765 // ----------------------------------------------------------------------------
1767 void wxTextCtrl::Command(wxCommandEvent
& event
)
1769 SetValue(event
.GetString());
1770 ProcessCommand (event
);
1773 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
1775 // By default, load the first file into the text window.
1776 if (event
.GetNumberOfFiles() > 0)
1778 LoadFile(event
.GetFiles()[0]);
1782 // ----------------------------------------------------------------------------
1783 // kbd input processing
1784 // ----------------------------------------------------------------------------
1786 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1788 // check for our special keys here: if we don't do it and the parent frame
1789 // uses them as accelerators, they wouldn't work at all, so we disable
1790 // usual preprocessing for them
1791 if ( msg
->message
== WM_KEYDOWN
)
1793 const WPARAM vkey
= msg
->wParam
;
1794 if ( HIWORD(msg
->lParam
) & KF_ALTDOWN
)
1796 // Alt-Backspace is accelerator for "Undo"
1797 if ( vkey
== VK_BACK
)
1802 // we want to process some Ctrl-foo and Shift-bar but no key
1803 // combinations without either Ctrl or Shift nor with both of them
1805 const int ctrl
= wxIsCtrlDown(),
1806 shift
= wxIsShiftDown();
1807 switch ( ctrl
+ shift
)
1810 wxFAIL_MSG( wxT("how many modifiers have we got?") );
1817 // This one is only special for multi line controls.
1818 if ( !IsMultiLine() )
1832 // either Ctrl or Shift pressed
1847 else // Shift is pressed
1849 if ( vkey
== VK_INSERT
|| vkey
== VK_DELETE
)
1856 return wxControl::MSWShouldPreProcessMessage(msg
);
1859 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
1861 switch ( event
.GetKeyCode() )
1865 wxCommandEvent
event(wxEVT_TEXT_ENTER
, m_windowId
);
1866 InitCommandEvent(event
);
1867 event
.SetString(GetValue());
1868 if ( HandleWindowEvent(event
) )
1869 if ( !HasFlag(wxTE_MULTILINE
) )
1871 //else: multiline controls need Enter for themselves
1876 // ok, so this is getting absolutely ridiculous but I don't see
1877 // any other way to fix this bug: when a multiline text control is
1878 // inside a wxFrame, we need to generate the navigation event as
1879 // otherwise nothing happens at all, but when the same control is
1880 // created inside a dialog, IsDialogMessage() *does* switch focus
1881 // all by itself and so if we do it here as well, it is advanced
1882 // twice and goes to the next control... to prevent this from
1883 // happening we're doing this ugly check, the logic being that if
1884 // we don't have focus then it had been already changed to the next
1887 // the right thing to do would, of course, be to understand what
1888 // the hell is IsDialogMessage() doing but this is beyond my feeble
1889 // forces at the moment unfortunately
1890 if ( !(m_windowStyle
& wxTE_PROCESS_TAB
))
1892 if ( FindFocus() == this )
1895 if (!event
.ShiftDown())
1896 flags
|= wxNavigationKeyEvent::IsForward
;
1897 if (event
.ControlDown())
1898 flags
|= wxNavigationKeyEvent::WinChange
;
1899 if (Navigate(flags
))
1905 // Insert tab since calling the default Windows handler
1906 // doesn't seem to do it
1907 WriteText(wxT("\t"));
1913 // no, we didn't process it
1917 void wxTextCtrl::OnKeyDown(wxKeyEvent
& event
)
1919 // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages
1920 // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent
1921 // from working. So we work around it by intercepting these shortcuts
1922 // ourselves and emitting clipboard events (which richedit will handle,
1923 // so everything works as before, including pasting of rich text):
1924 if ( event
.GetModifiers() == wxMOD_CONTROL
&& IsRich() )
1926 switch ( event
.GetKeyCode() )
1942 // Default window procedure of multiline edit controls posts WM_CLOSE to
1943 // the parent window when it gets Escape key press for some reason, prevent
1944 // it from doing this as this resulted in dialog boxes being closed on
1945 // Escape even when they shouldn't be (we do handle Escape ourselves
1946 // correctly in the situations when it should close them).
1947 if ( event
.GetKeyCode() == WXK_ESCAPE
&& IsMultiLine() )
1950 // no, we didn't process it
1954 WXLRESULT
wxTextCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1956 WXLRESULT lRc
= wxTextCtrlBase::MSWWindowProc(nMsg
, wParam
, lParam
);
1962 // we always want the chars and the arrows: the arrows for
1963 // navigation and the chars because we want Ctrl-C to work even
1964 // in a read only control
1965 long lDlgCode
= DLGC_WANTCHARS
| DLGC_WANTARROWS
;
1969 // we may have several different cases:
1970 // 1. normal: both TAB and ENTER are used for navigation
1971 // 2. ctrl wants TAB for itself: ENTER is used to pass to
1972 // the next control in the dialog
1973 // 3. ctrl wants ENTER for itself: TAB is used for dialog
1975 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
1976 // go to the next control (we need some way to do it)
1978 // multiline controls should always get ENTER for themselves
1979 if ( HasFlag(wxTE_PROCESS_ENTER
) || HasFlag(wxTE_MULTILINE
) )
1980 lDlgCode
|= DLGC_WANTMESSAGE
;
1982 if ( HasFlag(wxTE_PROCESS_TAB
) )
1983 lDlgCode
|= DLGC_WANTTAB
;
1989 // NB: use "=", not "|=" as the base class version returns
1990 // the same flags in the disabled state as usual (i.e.
1991 // including DLGC_WANTMESSAGE). This is strange (how
1992 // does it work in the native Win32 apps?) but for now
1997 // Clear the DLGC_HASSETSEL bit from the return value
1998 lRc
&= ~DLGC_HASSETSEL
;
2004 // rich text controls seem to have a bug and don't change the
2005 // cursor to the standard arrow one from the I-beam cursor usually
2006 // used by them even when a popup menu is shown (this works fine
2007 // for plain EDIT controls though), so explicitly work around this
2010 extern wxMenu
*wxCurrentPopupMenu
;
2011 if ( wxCurrentPopupMenu
&&
2012 wxCurrentPopupMenu
->GetInvokingWindow() == this )
2013 ::SetCursor(GetHcursorOf(*wxSTANDARD_CURSOR
));
2015 #endif // wxUSE_MENUS
2021 // ----------------------------------------------------------------------------
2022 // text control event processing
2023 // ----------------------------------------------------------------------------
2025 bool wxTextCtrl::SendUpdateEvent()
2027 switch ( m_updatesCount
)
2030 // remember that we've got an update
2035 // we had already sent one event since the last control modification
2039 wxFAIL_MSG( wxT("unexpected wxTextCtrl::m_updatesCount value") );
2043 // we hadn't updated the control ourselves, this event comes from
2044 // the user, don't need to ignore it nor update the count
2048 // the control was updated programmatically and we do NOT want to
2053 return SendTextUpdatedEvent();
2056 bool wxTextCtrl::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
2065 // the text size limit has been hit -- try to increase it
2066 if ( !AdjustSpaceLimit() )
2068 wxCommandEvent
event(wxEVT_TEXT_MAXLEN
, m_windowId
);
2069 InitCommandEvent(event
);
2070 event
.SetString(GetValue());
2071 ProcessCommand(event
);
2075 // the other edit notification messages are not processed (or, in
2076 // the case of EN_{SET/KILL}FOCUS were already handled at WM_SET/
2086 WXHBRUSH
wxTextCtrl::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
2088 if ( !IsThisEnabled() && !HasFlag(wxTE_MULTILINE
) )
2089 return MSWControlColorDisabled(hDC
);
2091 return wxTextCtrlBase::MSWControlColor(hDC
, hWnd
);
2094 bool wxTextCtrl::HasSpaceLimit(unsigned int *len
) const
2096 // HACK: we try to automatically extend the limit for the amount of text
2097 // to allow (interactively) entering more than 64Kb of text under
2098 // Win9x but we shouldn't reset the text limit which was previously
2099 // set explicitly with SetMaxLength()
2101 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2102 // know the limit we set (if any). We could solve this by storing the
2103 // limit we set in wxTextCtrl but to save space we prefer to simply
2104 // test here the actual limit value: we consider that SetMaxLength()
2105 // can only be called for small values while EN_MAXTEXT is only sent
2106 // for large values (in practice the default limit seems to be 30000
2107 // but make it smaller just to be on the safe side)
2108 *len
= ::SendMessage(GetHwnd(), EM_GETLIMITTEXT
, 0, 0);
2109 return *len
< 10001;
2113 bool wxTextCtrl::AdjustSpaceLimit()
2116 if ( HasSpaceLimit(&limit
) )
2119 unsigned int len
= ::GetWindowTextLength(GetHwnd());
2122 // increment in 32Kb chunks
2123 SetMaxLength(len
+ 0x8000);
2126 // we changed the limit
2130 bool wxTextCtrl::AcceptsFocusFromKeyboard() const
2132 // we don't want focus if we can't be edited unless we're a multiline
2133 // control because then it might be still nice to get focus from keyboard
2134 // to be able to scroll it without mouse
2135 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2138 wxSize
wxTextCtrl::DoGetBestSize() const
2140 return DoGetSizeFromTextSize( DEFAULT_ITEM_WIDTH
);
2143 wxSize
wxTextCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
2146 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
2149 ::SystemParametersInfo(SPI_GETCARETWIDTH
, 0, &wText
, 0);
2153 if ( m_windowStyle
& wxTE_MULTILINE
)
2155 // add space for vertical scrollbar
2156 if ( !(m_windowStyle
& wxTE_NO_VSCROLL
) )
2157 wText
+= ::GetSystemMetrics(SM_CXVSCROLL
);
2161 hText
*= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2162 // add space for horizontal scrollbar
2163 if ( m_windowStyle
& wxHSCROLL
)
2164 hText
+= ::GetSystemMetrics(SM_CYHSCROLL
);
2167 // for single line control cy (height + external leading) is ok
2170 // Add the margins we have previously set
2171 wxPoint
marg( GetMargins() );
2172 wText
+= wxMax(0, marg
.x
);
2173 hText
+= wxMax(0, marg
.y
);
2176 // Text controls without border are special and have the same height as
2177 // static labels (they also have the same appearance when they're disable
2178 // and are often used as a sort of copyable to the clipboard label so it's
2179 // important that they have the same height as the normal labels to not
2181 if ( !HasFlag(wxBORDER_NONE
) )
2183 wText
+= 9; // borders and inner margins
2185 // we have to add the adjustments for the control height only once, not
2186 // once per line, so do it after multiplication above
2187 hText
+= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
) - cy
;
2190 // Perhaps the user wants something different from CharHeight, or ylen
2191 // is used as the height of a multiline text.
2193 hText
+= ylen
- GetCharHeight();
2195 return wxSize(wText
, hText
);
2198 // ----------------------------------------------------------------------------
2199 // standard handlers for standard edit menu events
2200 // ----------------------------------------------------------------------------
2202 void wxTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
2207 void wxTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
2212 void wxTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
2217 void wxTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
2222 void wxTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
2227 void wxTextCtrl::OnDelete(wxCommandEvent
& WXUNUSED(event
))
2232 void wxTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
2237 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
2239 event
.Enable( CanCut() );
2242 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
2244 event
.Enable( CanCopy() );
2247 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
2249 event
.Enable( CanPaste() );
2252 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
2254 event
.Enable( CanUndo() );
2257 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
2259 event
.Enable( CanRedo() );
2262 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent
& event
)
2264 event
.Enable( HasSelection() && IsEditable() );
2267 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
2269 event
.Enable( !IsEmpty() );
2272 void wxTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
2277 if (!m_privateContextMenu
)
2279 m_privateContextMenu
= new wxMenu
;
2280 m_privateContextMenu
->Append(wxID_UNDO
, _("&Undo"));
2281 m_privateContextMenu
->Append(wxID_REDO
, _("&Redo"));
2282 m_privateContextMenu
->AppendSeparator();
2283 m_privateContextMenu
->Append(wxID_CUT
, _("Cu&t"));
2284 m_privateContextMenu
->Append(wxID_COPY
, _("&Copy"));
2285 m_privateContextMenu
->Append(wxID_PASTE
, _("&Paste"));
2286 m_privateContextMenu
->Append(wxID_CLEAR
, _("&Delete"));
2287 m_privateContextMenu
->AppendSeparator();
2288 m_privateContextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
2290 PopupMenu(m_privateContextMenu
);
2298 void wxTextCtrl::OnSetFocus(wxFocusEvent
& event
)
2300 // be sure the caret remains invisible if the user had hidden it
2301 if ( !m_isNativeCaretShown
)
2303 ::HideCaret(GetHwnd());
2309 // the rest of the file only deals with the rich edit controls
2312 // ----------------------------------------------------------------------------
2313 // EN_LINK processing
2314 // ----------------------------------------------------------------------------
2316 bool wxTextCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2318 NMHDR
*hdr
= (NMHDR
* )lParam
;
2319 switch ( hdr
->code
)
2323 const MSGFILTER
*msgf
= (MSGFILTER
*)lParam
;
2324 UINT msg
= msgf
->msg
;
2326 // this is a bit crazy but richedit 1.0 sends us all mouse
2327 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2328 // generate the wxWin events for this message manually
2330 // NB: in fact, this is still not totally correct as it does
2331 // send us WM_LBUTTONUP if the selection was cleared by the
2332 // last click -- so currently we get 2 events in this case,
2333 // but as I don't see any obvious way to check for this I
2334 // leave this code in place because it's still better than
2335 // not getting left up events at all
2336 if ( msg
== WM_LBUTTONUP
)
2338 WXUINT flags
= msgf
->wParam
;
2339 int x
= GET_X_LPARAM(msgf
->lParam
),
2340 y
= GET_Y_LPARAM(msgf
->lParam
);
2342 HandleMouseEvent(msg
, x
, y
, flags
);
2346 // return true to process the event (and false to ignore it)
2351 const ENLINK
*enlink
= (ENLINK
*)hdr
;
2353 switch ( enlink
->msg
)
2356 // ok, so it is hardcoded - do we really nee to
2359 wxCursor
cur(wxCURSOR_HAND
);
2360 ::SetCursor(GetHcursorOf(cur
));
2366 case WM_LBUTTONDOWN
:
2368 case WM_LBUTTONDBLCLK
:
2369 case WM_RBUTTONDOWN
:
2371 case WM_RBUTTONDBLCLK
:
2372 // send a mouse event
2374 static const wxEventType eventsMouse
[] =
2385 // the event ids are consecutive
2387 evtMouse(eventsMouse
[enlink
->msg
- WM_MOUSEMOVE
]);
2389 InitMouseEvent(evtMouse
,
2390 GET_X_LPARAM(enlink
->lParam
),
2391 GET_Y_LPARAM(enlink
->lParam
),
2394 wxTextUrlEvent
event(m_windowId
, evtMouse
,
2396 enlink
->chrg
.cpMax
);
2398 InitCommandEvent(event
);
2400 *result
= ProcessCommand(event
);
2408 // not processed, leave it to the base class
2409 return wxTextCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
2412 #if wxUSE_DRAG_AND_DROP
2414 void wxTextCtrl::SetDropTarget(wxDropTarget
*dropTarget
)
2416 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
2418 // get rid of the built-in drop target
2419 ::RevokeDragDrop(GetHwnd());
2420 m_dropTarget
= NULL
;
2423 wxTextCtrlBase::SetDropTarget(dropTarget
);
2426 #endif // wxUSE_DRAG_AND_DROP
2428 // ----------------------------------------------------------------------------
2429 // colour setting for the rich edit controls
2430 // ----------------------------------------------------------------------------
2432 bool wxTextCtrl::SetBackgroundColour(const wxColour
& colour
)
2434 if ( !wxTextCtrlBase::SetBackgroundColour(colour
) )
2436 // colour didn't really change
2442 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2443 // EM_SETBKGNDCOLOR additionally
2444 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR
, 0, wxColourToRGB(colour
));
2450 bool wxTextCtrl::SetForegroundColour(const wxColour
& colour
)
2452 if ( !wxTextCtrlBase::SetForegroundColour(colour
) )
2454 // colour didn't really change
2460 // change the colour of everything
2461 WinStruct
<CHARFORMAT
> cf
;
2462 cf
.dwMask
= CFM_COLOR
;
2463 cf
.crTextColor
= wxColourToRGB(colour
);
2464 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, SCF_ALL
, (LPARAM
)&cf
);
2470 bool wxTextCtrl::SetFont(const wxFont
& font
)
2472 if ( !wxTextCtrlBase::SetFont(font
) )
2475 if ( GetRichVersion() >= 4 )
2477 // Using WM_SETFONT is not enough with RichEdit 4.1: it does work but
2478 // for ASCII characters only and inserting a non-ASCII one into it
2479 // later reverts to the default font so use EM_SETCHARFORMAT to change
2480 // the default font for it.
2483 SetStyle(-1, -1, attr
);
2489 // ----------------------------------------------------------------------------
2490 // styling support for rich edit controls
2491 // ----------------------------------------------------------------------------
2493 bool wxTextCtrl::MSWSetCharFormat(const wxTextAttr
& style
, long start
, long end
)
2495 // initialize CHARFORMAT struct
2504 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2505 // CHARFORMAT in that case
2507 if ( m_verRichEdit
== 1 )
2509 // this is the only thing the control is going to grok
2510 cf
.cbSize
= sizeof(CHARFORMAT
);
2515 // CHARFORMAT or CHARFORMAT2
2516 cf
.cbSize
= sizeof(cf
);
2519 if ( style
.HasFont() )
2521 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2522 // but using it doesn't seem to hurt neither so leaving it for now
2524 cf
.dwMask
|= CFM_FACE
| CFM_SIZE
| CFM_CHARSET
|
2525 CFM_ITALIC
| CFM_BOLD
| CFM_UNDERLINE
;
2527 // fill in data from LOGFONT but recalculate lfHeight because we need
2528 // the real height in twips and not the negative number which
2529 // wxFillLogFont() returns (this is correct in general and works with
2530 // the Windows font mapper, but not here)
2532 wxFont
font(style
.GetFont());
2535 wxFillLogFont(&lf
, &font
);
2536 cf
.yHeight
= 20*font
.GetPointSize(); // 1 pt = 20 twips
2537 cf
.bCharSet
= lf
.lfCharSet
;
2538 cf
.bPitchAndFamily
= lf
.lfPitchAndFamily
;
2539 wxStrlcpy(cf
.szFaceName
, lf
.lfFaceName
, WXSIZEOF(cf
.szFaceName
));
2541 // also deal with underline/italic/bold attributes: note that we must
2542 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2543 // style to allow clearing it
2546 cf
.dwEffects
|= CFE_ITALIC
;
2549 if ( lf
.lfWeight
== FW_BOLD
)
2551 cf
.dwEffects
|= CFE_BOLD
;
2554 if ( lf
.lfUnderline
)
2556 cf
.dwEffects
|= CFE_UNDERLINE
;
2559 // strikeout fonts are not supported by wxWidgets
2562 if ( style
.HasTextColour() )
2564 cf
.dwMask
|= CFM_COLOR
;
2565 cf
.crTextColor
= wxColourToRGB(style
.GetTextColour());
2569 if ( m_verRichEdit
!= 1 && style
.HasBackgroundColour() )
2571 cf
.dwMask
|= CFM_BACKCOLOR
;
2572 cf
.crBackColor
= wxColourToRGB(style
.GetBackgroundColour());
2574 #endif // wxUSE_RICHEDIT2
2576 // Apply the style either to the selection or to the entire control.
2578 if ( start
!= -1 || end
!= -1 )
2580 DoSetSelection(start
, end
, SetSel_NoScroll
);
2581 selMode
= SCF_SELECTION
;
2588 if ( !::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, selMode
, (LPARAM
)&cf
) )
2590 wxLogLastError(wxT("SendMessage(EM_SETCHARFORMAT)"));
2597 bool wxTextCtrl::MSWSetParaFormat(const wxTextAttr
& style
, long start
, long end
)
2607 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2608 // PARAFORMAT in that case
2610 if ( m_verRichEdit
== 1 )
2612 // this is the only thing the control is going to grok
2613 pf
.cbSize
= sizeof(PARAFORMAT
);
2618 // PARAFORMAT or PARAFORMAT2
2619 pf
.cbSize
= sizeof(pf
);
2622 if (style
.HasAlignment())
2624 pf
.dwMask
|= PFM_ALIGNMENT
;
2625 if (style
.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
2626 pf
.wAlignment
= PFA_RIGHT
;
2627 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
2628 pf
.wAlignment
= PFA_CENTER
;
2629 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED
)
2630 pf
.wAlignment
= PFA_JUSTIFY
;
2632 pf
.wAlignment
= PFA_LEFT
;
2635 if (style
.HasLeftIndent())
2637 pf
.dwMask
|= PFM_STARTINDENT
| PFM_OFFSET
;
2639 // Convert from 1/10 mm to TWIPS
2640 pf
.dxStartIndent
= (int) (((double) style
.GetLeftIndent()) * mm2twips
/ 10.0) ;
2641 pf
.dxOffset
= (int) (((double) style
.GetLeftSubIndent()) * mm2twips
/ 10.0) ;
2644 if (style
.HasRightIndent())
2646 pf
.dwMask
|= PFM_RIGHTINDENT
;
2648 // Convert from 1/10 mm to TWIPS
2649 pf
.dxRightIndent
= (int) (((double) style
.GetRightIndent()) * mm2twips
/ 10.0) ;
2652 if (style
.HasTabs())
2654 pf
.dwMask
|= PFM_TABSTOPS
;
2656 const wxArrayInt
& tabs
= style
.GetTabs();
2658 pf
.cTabCount
= (SHORT
)wxMin(tabs
.GetCount(), MAX_TAB_STOPS
);
2660 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2662 // Convert from 1/10 mm to TWIPS
2663 pf
.rgxTabs
[i
] = (int) (((double) tabs
[i
]) * mm2twips
/ 10.0) ;
2668 if ( m_verRichEdit
> 1 )
2670 if ( wxTheApp
->GetLayoutDirection() == wxLayout_RightToLeft
)
2672 // Use RTL paragraphs in RTL mode to get proper layout
2673 pf
.dwMask
|= PFM_RTLPARA
;
2674 pf
.wEffects
|= PFE_RTLPARA
;
2677 #endif // wxUSE_RICHEDIT2
2681 // Do format the selection.
2682 DoSetSelection(start
, end
, SetSel_NoScroll
);
2684 if ( !::SendMessage(GetHwnd(), EM_SETPARAFORMAT
, 0, (LPARAM
) &pf
) )
2686 wxLogLastError(wxT("SendMessage(EM_SETPARAFORMAT)"));
2695 bool wxTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
2699 // can't do it with normal text control
2703 // the richedit 1.0 doesn't handle setting background colour, so don't
2704 // even try to do anything if it's the only thing we want to change
2705 if ( m_verRichEdit
== 1 && !style
.HasFont() && !style
.HasTextColour() &&
2706 !style
.HasLeftIndent() && !style
.HasRightIndent() && !style
.HasAlignment() &&
2709 // nothing to do: return true if there was really nothing to do and
2710 // false if we failed to set bg colour
2711 return !style
.HasBackgroundColour();
2714 // order the range if needed
2718 // we can only change the format of the selection, so select the range we
2719 // want and restore the old selection later, after MSWSetXXXFormat()
2720 // functions (possibly) change it.
2721 long startOld
, endOld
;
2722 GetSelection(&startOld
, &endOld
);
2724 bool ok
= MSWSetCharFormat(style
, start
, end
);
2725 if ( !MSWSetParaFormat(style
, start
, end
) )
2728 if ( start
!= startOld
|| end
!= endOld
)
2730 // restore the original selection
2731 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2737 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
2739 if ( !wxTextCtrlBase::SetDefaultStyle(style
) )
2744 // we have to do this or the style wouldn't apply for the text typed by
2746 wxTextPos posLast
= GetLastPosition();
2747 SetStyle(posLast
, posLast
, m_defaultStyle
);
2753 bool wxTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
2757 // can't do it with normal text control
2761 // initialize CHARFORMAT struct
2770 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2771 // CHARFORMAT in that case
2773 if ( m_verRichEdit
== 1 )
2775 // this is the only thing the control is going to grok
2776 cf
.cbSize
= sizeof(CHARFORMAT
);
2781 // CHARFORMAT or CHARFORMAT2
2782 cf
.cbSize
= sizeof(cf
);
2784 // we can only change the format of the selection, so select the range we
2785 // want and restore the old selection later
2786 long startOld
, endOld
;
2787 GetSelection(&startOld
, &endOld
);
2789 // but do we really have to change the selection?
2790 bool changeSel
= position
!= startOld
|| position
!= endOld
;
2794 DoSetSelection(position
, position
+ 1, SetSel_NoScroll
);
2797 // get the selection formatting
2798 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT
,
2799 SCF_SELECTION
, (LPARAM
)&cf
) ;
2803 // Convert the height from the units of 1/20th of the point in which
2804 // CHARFORMAT stores it to pixel-based units used by LOGFONT.
2805 const wxCoord ppi
= wxClientDC(this).GetPPI().y
;
2806 lf
.lfHeight
= -MulDiv(cf
.yHeight
/20, ppi
, 72);
2808 lf
.lfCharSet
= ANSI_CHARSET
; // FIXME: how to get correct charset?
2809 lf
.lfClipPrecision
= 0;
2810 lf
.lfEscapement
= 0;
2811 wxStrcpy(lf
.lfFaceName
, cf
.szFaceName
);
2813 //NOTE: we _MUST_ set each of these values to _something_ since we
2814 //do not call wxZeroMemory on the LOGFONT lf
2815 if (cf
.dwEffects
& CFE_ITALIC
)
2818 lf
.lfItalic
= FALSE
;
2820 lf
.lfOrientation
= 0;
2821 lf
.lfPitchAndFamily
= cf
.bPitchAndFamily
;
2824 if (cf
.dwEffects
& CFE_STRIKEOUT
)
2825 lf
.lfStrikeOut
= TRUE
;
2827 lf
.lfStrikeOut
= FALSE
;
2829 if (cf
.dwEffects
& CFE_UNDERLINE
)
2830 lf
.lfUnderline
= TRUE
;
2832 lf
.lfUnderline
= FALSE
;
2834 if (cf
.dwEffects
& CFE_BOLD
)
2835 lf
.lfWeight
= FW_BOLD
;
2837 lf
.lfWeight
= FW_NORMAL
;
2839 wxFont font
= wxCreateFontFromLogFont(& lf
);
2842 style
.SetFont(font
);
2844 style
.SetTextColour(wxColour(cf
.crTextColor
));
2847 if ( m_verRichEdit
!= 1 )
2849 // cf.dwMask |= CFM_BACKCOLOR;
2850 style
.SetBackgroundColour(wxColour(cf
.crBackColor
));
2852 #endif // wxUSE_RICHEDIT2
2854 // now get the paragraph formatting
2857 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2858 // PARAFORMAT in that case
2860 if ( m_verRichEdit
== 1 )
2862 // this is the only thing the control is going to grok
2863 pf
.cbSize
= sizeof(PARAFORMAT
);
2868 // PARAFORMAT or PARAFORMAT2
2869 pf
.cbSize
= sizeof(pf
);
2872 // do format the selection
2873 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT
, 0, (LPARAM
) &pf
) ;
2875 style
.SetLeftIndent( (int) ((double) pf
.dxStartIndent
* twips2mm
* 10.0), (int) ((double) pf
.dxOffset
* twips2mm
* 10.0) );
2876 style
.SetRightIndent( (int) ((double) pf
.dxRightIndent
* twips2mm
* 10.0) );
2878 if (pf
.wAlignment
== PFA_CENTER
)
2879 style
.SetAlignment(wxTEXT_ALIGNMENT_CENTRE
);
2880 else if (pf
.wAlignment
== PFA_RIGHT
)
2881 style
.SetAlignment(wxTEXT_ALIGNMENT_RIGHT
);
2882 else if (pf
.wAlignment
== PFA_JUSTIFY
)
2883 style
.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED
);
2885 style
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
2887 wxArrayInt tabStops
;
2889 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2891 tabStops
.Add( (int) ((double) (pf
.rgxTabs
[i
] & 0xFFFF) * twips2mm
* 10.0) );
2896 // restore the original selection
2897 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2903 // ----------------------------------------------------------------------------
2905 // ----------------------------------------------------------------------------
2907 static const HINSTANCE INVALID_HINSTANCE
= (HINSTANCE
)-1;
2909 bool wxRichEditModule::OnInit()
2911 // don't do anything - we will load it when needed
2915 void wxRichEditModule::OnExit()
2917 for ( size_t i
= 0; i
< WXSIZEOF(ms_hRichEdit
); i
++ )
2919 if ( ms_hRichEdit
[i
] && ms_hRichEdit
[i
] != INVALID_HINSTANCE
)
2921 ::FreeLibrary(ms_hRichEdit
[i
]);
2922 ms_hRichEdit
[i
] = NULL
;
2926 if (ms_inkEditLib
.IsLoaded())
2927 ms_inkEditLib
.Unload();
2932 bool wxRichEditModule::Load(Version version
)
2934 if ( ms_hRichEdit
[version
] == INVALID_HINSTANCE
)
2936 // we had already tried to load it and failed
2940 if ( ms_hRichEdit
[version
] )
2942 // we've already got this one
2946 static const wxChar
*const dllnames
[] =
2953 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames
) == Version_Max
,
2954 RichEditDllNamesVersionsMismatch
);
2956 ms_hRichEdit
[version
] = ::LoadLibrary(dllnames
[version
]);
2958 if ( !ms_hRichEdit
[version
] )
2960 ms_hRichEdit
[version
] = INVALID_HINSTANCE
;
2969 // load the InkEdit library
2970 bool wxRichEditModule::LoadInkEdit()
2972 if (ms_inkEditLibLoadAttemped
)
2973 return ms_inkEditLib
.IsLoaded();
2975 ms_inkEditLibLoadAttemped
= true;
2978 return ms_inkEditLib
.Load(wxT("inked"));
2980 #endif // wxUSE_INKEDIT
2983 #endif // wxUSE_RICHEDIT
2985 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)