1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textctrl.cpp
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
27 #if wxUSE_TEXTCTRL && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
30 #include "wx/textctrl.h"
31 #include "wx/settings.h"
33 #include "wx/dcclient.h"
40 #include "wx/module.h"
41 #include "wx/wxcrtvararg.h"
44 #include "wx/sysopt.h"
47 #include "wx/clipbrd.h"
50 #include "wx/textfile.h"
54 #include "wx/msw/private.h"
55 #include "wx/msw/winundef.h"
56 #include "wx/msw/mslu.h"
62 #include <sys/types.h>
67 // old mingw32 has richedit stuff directly in windows.h and doesn't have
69 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
73 #endif // wxUSE_RICHEDIT
75 #include "wx/msw/missing.h"
77 // FIXME-VC6: This seems to be only missing from VC6 headers.
78 #ifndef SPI_GETCARETWIDTH
79 #define SPI_GETCARETWIDTH 0x2006
82 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
84 // dummy value used for m_dropTarget, different from any valid pointer value
85 // (which are all even under Windows) and NULL
87 wxRICHTEXT_DEFAULT_DROPTARGET
= reinterpret_cast<wxDropTarget
*>(1);
89 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
97 // this module initializes RichEdit DLL(s) if needed
98 class wxRichEditModule
: public wxModule
103 Version_1
, // riched32.dll
104 Version_2or3
, // both use riched20.dll
105 Version_41
, // msftedit.dll (XP SP1 and Windows 2003)
109 virtual bool OnInit();
110 virtual void OnExit();
112 // load the richedit DLL for the specified version of rich edit
113 static bool Load(Version version
);
116 // load the InkEdit library
117 static bool LoadInkEdit();
121 // the handles to richedit 1.0 and 2.0 (or 3.0) DLLs
122 static HINSTANCE ms_hRichEdit
[Version_Max
];
125 static wxDynamicLibrary ms_inkEditLib
;
126 static bool ms_inkEditLibLoadAttemped
;
129 DECLARE_DYNAMIC_CLASS(wxRichEditModule
)
132 HINSTANCE
wxRichEditModule::ms_hRichEdit
[Version_Max
] = { NULL
, NULL
, NULL
};
135 wxDynamicLibrary
wxRichEditModule::ms_inkEditLib
;
136 bool wxRichEditModule::ms_inkEditLibLoadAttemped
= false;
139 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule
, wxModule
)
141 #endif // wxUSE_RICHEDIT
143 // a small class used to set m_updatesCount to 0 (to filter duplicate events if
144 // necessary) and to reset it back to -1 afterwards
145 class UpdatesCountFilter
148 UpdatesCountFilter(int& count
)
151 wxASSERT_MSG( m_count
== -1 || m_count
== -2,
152 wxT("wrong initial m_updatesCount value") );
156 //else: we don't want to count how many update events we get as we're going
157 // to ignore all of them
160 ~UpdatesCountFilter()
165 // return true if an event has been received
166 bool GotUpdate() const
174 wxDECLARE_NO_COPY_CLASS(UpdatesCountFilter
);
177 // ----------------------------------------------------------------------------
178 // event tables and other macros
179 // ----------------------------------------------------------------------------
181 BEGIN_EVENT_TABLE(wxTextCtrl
, wxTextCtrlBase
)
182 EVT_CHAR(wxTextCtrl::OnChar
)
183 EVT_KEY_DOWN(wxTextCtrl::OnKeyDown
)
184 EVT_DROP_FILES(wxTextCtrl::OnDropFiles
)
187 EVT_CONTEXT_MENU(wxTextCtrl::OnContextMenu
)
190 EVT_MENU(wxID_CUT
, wxTextCtrl::OnCut
)
191 EVT_MENU(wxID_COPY
, wxTextCtrl::OnCopy
)
192 EVT_MENU(wxID_PASTE
, wxTextCtrl::OnPaste
)
193 EVT_MENU(wxID_UNDO
, wxTextCtrl::OnUndo
)
194 EVT_MENU(wxID_REDO
, wxTextCtrl::OnRedo
)
195 EVT_MENU(wxID_CLEAR
, wxTextCtrl::OnDelete
)
196 EVT_MENU(wxID_SELECTALL
, wxTextCtrl::OnSelectAll
)
198 EVT_UPDATE_UI(wxID_CUT
, wxTextCtrl::OnUpdateCut
)
199 EVT_UPDATE_UI(wxID_COPY
, wxTextCtrl::OnUpdateCopy
)
200 EVT_UPDATE_UI(wxID_PASTE
, wxTextCtrl::OnUpdatePaste
)
201 EVT_UPDATE_UI(wxID_UNDO
, wxTextCtrl::OnUpdateUndo
)
202 EVT_UPDATE_UI(wxID_REDO
, wxTextCtrl::OnUpdateRedo
)
203 EVT_UPDATE_UI(wxID_CLEAR
, wxTextCtrl::OnUpdateDelete
)
204 EVT_UPDATE_UI(wxID_SELECTALL
, wxTextCtrl::OnUpdateSelectAll
)
206 EVT_SET_FOCUS(wxTextCtrl::OnSetFocus
)
209 // ============================================================================
211 // ============================================================================
213 // ----------------------------------------------------------------------------
215 // ----------------------------------------------------------------------------
217 void wxTextCtrl::Init()
221 #endif // wxUSE_RICHEDIT
223 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
227 m_privateContextMenu
= NULL
;
229 m_isNativeCaretShown
= true;
232 wxTextCtrl::~wxTextCtrl()
234 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
235 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
237 // don't try to destroy this dummy pointer in the base class dtor
240 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
242 delete m_privateContextMenu
;
245 bool wxTextCtrl::Create(wxWindow
*parent
,
247 const wxString
& value
,
251 const wxValidator
& validator
,
252 const wxString
& name
)
254 // base initialization
255 if ( !CreateControl(parent
, id
, pos
, size
, style
, validator
, name
) )
258 if ( !MSWCreateText(value
, pos
, size
) )
261 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
264 // rich text controls have a default associated drop target which
265 // allows them to receive (rich) text dropped on them, which is nice,
266 // but prevents us from associating a user-defined drop target with
267 // them as we need to unregister the old one first
269 // to make it work, we set m_dropTarget to this special value initially
270 // and check for it in our SetDropTarget()
271 m_dropTarget
= wxRICHTEXT_DEFAULT_DROPTARGET
;
273 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
278 // returns true if the platform should explicitly apply a theme border
279 bool wxTextCtrl::CanApplyThemeBorder() const
284 // Standard text control already handles theming
285 return ((GetWindowStyle() & (wxTE_RICH
|wxTE_RICH2
)) != 0);
289 bool wxTextCtrl::MSWCreateText(const wxString
& value
,
293 // translate wxWin style flags to MSW ones
294 WXDWORD msStyle
= MSWGetCreateWindowFlags();
296 // do create the control - either an EDIT or RICHEDIT
297 wxString windowClass
= wxT("EDIT");
299 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
300 // A control that capitalizes the first letter
301 if ( HasFlag(wxTE_CAPITALIZE
) )
302 windowClass
= wxT("CAPEDIT");
306 if ( m_windowStyle
& wxTE_AUTO_URL
)
308 // automatic URL detection only works in RichEdit 2.0+
309 m_windowStyle
|= wxTE_RICH2
;
312 if ( m_windowStyle
& wxTE_RICH2
)
314 // using richedit 2.0 implies using wxTE_RICH
315 m_windowStyle
|= wxTE_RICH
;
318 // we need to load the richedit DLL before creating the rich edit control
319 if ( m_windowStyle
& wxTE_RICH
)
321 // versions 2.0, 3.0 and 4.1 of rich edit are mostly compatible with
322 // each other but not with version 1.0, so we have separate flags for
323 // the version 1.0 and the others (and so m_verRichEdit may be 0 (plain
324 // EDIT control), 1 for version 1.0 or 2 for any higher version)
326 // notice that 1.0 has no Unicode support at all so in Unicode build we
327 // must use another version
331 #else // !wxUSE_UNICODE
332 m_verRichEdit
= m_windowStyle
& wxTE_RICH2
? 2 : 1;
333 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
336 // First test if we can load an ink edit control. Normally, all edit
337 // controls will be made ink edit controls if a tablet environment is
338 // found (or if msw.inkedit != 0 and the InkEd.dll is present).
339 // However, an application can veto ink edit controls by either specifying
340 // msw.inkedit = 0 or by removing wxTE_RICH[2] from the style.
342 if ((wxSystemSettings::HasFeature(wxSYS_TABLET_PRESENT
) || wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) != 0) &&
343 !(wxSystemOptions::HasOption(wxT("msw.inkedit")) && wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) == 0))
345 if (wxRichEditModule::LoadInkEdit())
347 windowClass
= INKEDIT_CLASS
;
349 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
353 // Fake rich text version for other calls
361 #endif // wxUSE_INKEDIT
363 if ( m_verRichEdit
== 2 )
365 if ( wxRichEditModule::Load(wxRichEditModule::Version_41
) )
367 // yes, class name for version 4.1 really is 5.0
368 windowClass
= wxT("RICHEDIT50W");
372 else if ( wxRichEditModule::Load(wxRichEditModule::Version_2or3
) )
374 windowClass
= wxT("RichEdit20")
379 #endif // Unicode/ANSI
381 else // failed to load msftedit.dll and riched20.dll
387 if ( m_verRichEdit
== 1 )
389 if ( wxRichEditModule::Load(wxRichEditModule::Version_1
) )
391 windowClass
= wxT("RICHEDIT");
393 else // failed to load any richedit control DLL
395 // only give the error msg once if the DLL can't be loaded
396 static bool s_errorGiven
= false; // MT ok as only used by GUI
400 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
410 #endif // wxUSE_RICHEDIT
412 // we need to turn '\n's into "\r\n"s for the multiline controls
414 if ( m_windowStyle
& wxTE_MULTILINE
)
416 valueWin
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
423 // suppress events sent during control creation: we're called either from
424 // the ctor and then we shouldn't generate any events for compatibility
425 // with the other ports, or from SetWindowStyleFlag() and then we shouldn't
426 // generate the events because our text doesn't really change, the fact
427 // that we (sometimes) need to recreate the control is just an
428 // implementation detail
431 if ( !MSWCreateControl(windowClass
.t_str(), msStyle
, pos
, size
, valueWin
) )
442 // Pass IEM_InsertText (0) as wParam, in order to have the ink always
443 // converted to text.
444 ::SendMessage(GetHwnd(), EM_SETINKINSERTMODE
, 0, 0);
446 // Make sure the mouse can be used for input
447 ::SendMessage(GetHwnd(), EM_SETUSEMOUSEFORINPUT
, 1, 0);
451 // enable the events we're interested in: we want to get EN_CHANGE as
452 // for the normal controls
453 LPARAM mask
= ENM_CHANGE
;
455 if (GetRichVersion() == 1 && !IsInkEdit())
457 // we also need EN_MSGFILTER for richedit 1.0 for the reasons
458 // explained in its handler
459 mask
|= ENM_MOUSEEVENTS
;
461 // we also need to force the appearance of the vertical scrollbar
462 // initially as otherwise the control doesn't refresh correctly
463 // after resize: but once the vertical scrollbar had been shown
464 // (even if it's subsequently hidden) it does
466 // this is clearly a bug and for now it has been only noticed under
467 // Windows XP, so if we're sure it works correctly under other
468 // systems we could do this only for XP
469 SetSize(-1, 1); // 1 is small enough to force vert scrollbar
470 SetInitialSize(size
);
472 else if ( m_windowStyle
& wxTE_AUTO_URL
)
476 ::SendMessage(GetHwnd(), EM_AUTOURLDETECT
, TRUE
, 0);
479 ::SendMessage(GetHwnd(), EM_SETEVENTMASK
, 0, mask
);
482 #endif // wxUSE_RICHEDIT
483 if ( HasFlag(wxTE_MULTILINE
) && HasFlag(wxTE_READONLY
) )
485 // non-rich read-only multiline controls have grey background by
486 // default under MSW but this is not always appropriate, so forcefully
487 // reset the background colour to normal default
489 // this is not ideal but, after a long discussion on wx-dev (see
490 // http://thread.gmane.org/gmane.comp.lib.wxwidgets.devel/116360/) it
491 // was finally deemed to be the best behaviour by default (and ideally
492 // we'd have a way to change this, see #11521)
493 SetBackgroundColour(GetClassDefaultAttributes().colBg
);
497 // Without this, if we pass the size in the constructor and then don't change it,
498 // the themed borders will be drawn incorrectly.
499 SetWindowPos(GetHwnd(), NULL
, 0, 0, 0, 0,
500 SWP_NOZORDER
|SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOACTIVATE
|
507 // Make sure the window style (etc.) reflects the HWND style (roughly)
508 void wxTextCtrl::AdoptAttributesFromHWND()
510 wxWindow::AdoptAttributesFromHWND();
512 HWND hWnd
= GetHwnd();
513 long style
= ::GetWindowLong(hWnd
, GWL_STYLE
);
515 // retrieve the style to see whether this is an edit or richedit ctrl
517 wxString classname
= wxGetWindowClass(GetHWND());
519 if ( classname
.IsSameAs(wxT("EDIT"), false /* no case */) )
526 if ( wxSscanf(classname
, wxT("RichEdit%d0%c"), &m_verRichEdit
, &c
) != 2 )
528 wxLogDebug(wxT("Unknown edit control '%s'."), classname
.c_str());
533 #endif // wxUSE_RICHEDIT
535 if (style
& ES_MULTILINE
)
536 m_windowStyle
|= wxTE_MULTILINE
;
537 if (style
& ES_PASSWORD
)
538 m_windowStyle
|= wxTE_PASSWORD
;
539 if (style
& ES_READONLY
)
540 m_windowStyle
|= wxTE_READONLY
;
541 if (style
& ES_WANTRETURN
)
542 m_windowStyle
|= wxTE_PROCESS_ENTER
;
543 if (style
& ES_CENTER
)
544 m_windowStyle
|= wxTE_CENTRE
;
545 if (style
& ES_RIGHT
)
546 m_windowStyle
|= wxTE_RIGHT
;
549 WXDWORD
wxTextCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
551 long msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
553 // styles which we always add by default
554 if ( style
& wxTE_MULTILINE
)
556 msStyle
|= ES_MULTILINE
| ES_WANTRETURN
;
557 if ( !(style
& wxTE_NO_VSCROLL
) )
559 // always adjust the vertical scrollbar automatically if we have it
560 msStyle
|= WS_VSCROLL
| ES_AUTOVSCROLL
;
563 // we have to use this style for the rich edit controls because
564 // without it the vertical scrollbar never appears at all in
565 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
566 if ( style
& wxTE_RICH2
)
568 msStyle
|= ES_DISABLENOSCROLL
;
570 #endif // wxUSE_RICHEDIT
573 style
|= wxTE_PROCESS_ENTER
;
577 // there is really no reason to not have this style for single line
579 msStyle
|= ES_AUTOHSCROLL
;
582 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
583 // scrollbar, there is no wrapping -- which makes sense
584 if ( style
& wxTE_DONTWRAP
)
586 // automatically scroll the control horizontally as necessary
588 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
589 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
590 // it doesn't seem to do any harm for plain edit controls, add it
592 msStyle
|= WS_HSCROLL
| ES_AUTOHSCROLL
;
595 if ( style
& wxTE_READONLY
)
596 msStyle
|= ES_READONLY
;
598 if ( style
& wxTE_PASSWORD
)
599 msStyle
|= ES_PASSWORD
;
601 if ( style
& wxTE_NOHIDESEL
)
602 msStyle
|= ES_NOHIDESEL
;
604 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
605 if ( style
& wxTE_CENTRE
)
606 msStyle
|= ES_CENTER
;
607 else if ( style
& wxTE_RIGHT
)
610 msStyle
|= ES_LEFT
; // ES_LEFT is 0 as well but for consistency...
615 void wxTextCtrl::SetWindowStyleFlag(long style
)
617 // changing the alignment of the control dynamically works under Win2003
618 // (but not older Windows version: it seems to work under some versions of
619 // XP but not other ones, and we have no way to determine it so be
620 // conservative here) and only for plain EDIT controls (not RICH ones) and
621 // we have to recreate the control to make it always work
622 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003
)
624 const long alignMask
= wxTE_LEFT
| wxTE_CENTRE
| wxTE_RIGHT
;
625 if ( (style
& alignMask
) != (GetWindowStyle() & alignMask
) )
627 const wxString value
= GetValue();
628 const wxPoint pos
= GetPosition();
629 const wxSize size
= GetSize();
631 // delete the old window
632 HWND hwnd
= GetHwnd();
634 ::DestroyWindow(hwnd
);
636 // create the new one with the updated flags
637 m_windowStyle
= style
;
638 MSWCreateText(value
, pos
, size
);
640 // and make sure it has the same attributes as before
643 // calling SetFont(m_font) would do nothing as the code would
644 // notice that the font didn't change, so force it to believe
646 wxFont font
= m_font
;
653 wxColour colFg
= m_foregroundColour
;
654 m_foregroundColour
= wxNullColour
;
655 SetForegroundColour(colFg
);
660 wxColour colBg
= m_backgroundColour
;
661 m_backgroundColour
= wxNullColour
;
662 SetBackgroundColour(colBg
);
665 // note that text styles are lost but this is probably not a big
666 // problem: if you use styles, you probably don't use nor change
667 // alignment flags anyhow
674 // we have to deal with some styles separately because they can't be
675 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
676 // using richedit-specific EM_SETOPTIONS
678 ((style
& wxTE_NOHIDESEL
) != (GetWindowStyle() & wxTE_NOHIDESEL
)) )
680 bool set
= (style
& wxTE_NOHIDESEL
) != 0;
682 ::SendMessage(GetHwnd(), EM_SETOPTIONS
, set
? ECOOP_OR
: ECOOP_AND
,
683 set
? ECO_NOHIDESEL
: ~ECO_NOHIDESEL
);
685 #endif // wxUSE_RICHEDIT
687 wxControl::SetWindowStyleFlag(style
);
690 // ----------------------------------------------------------------------------
691 // set/get the controls text
692 // ----------------------------------------------------------------------------
694 bool wxTextCtrl::IsEmpty() const
696 // this is an optimization for multiline controls containing a lot of text
697 if ( IsMultiLine() && GetNumberOfLines() != 1 )
700 return wxTextCtrlBase::IsEmpty();
703 wxString
wxTextCtrl::GetValue() const
705 // range 0..-1 is special for GetRange() and means to retrieve all text
706 return GetRange(0, -1);
709 wxString
wxTextCtrl::GetRange(long from
, long to
) const
713 if ( from
>= to
&& to
!= -1 )
715 // nothing to retrieve
722 int len
= GetWindowTextLength(GetHwnd());
729 // we must use EM_STREAMOUT if we don't want to lose all characters
730 // not representable in the current character set (EM_GETTEXTRANGE
731 // simply replaces them with question marks...)
732 if ( GetRichVersion() > 1 )
734 // we must have some encoding, otherwise any 8bit chars in the
735 // control are simply *lost* (replaced by '?')
736 wxFontEncoding encoding
= wxFONTENCODING_SYSTEM
;
738 wxFont font
= m_defaultStyle
.GetFont();
744 encoding
= font
.GetEncoding();
748 if ( encoding
== wxFONTENCODING_SYSTEM
)
750 encoding
= wxLocale::GetSystemEncoding();
754 if ( encoding
== wxFONTENCODING_SYSTEM
)
756 encoding
= wxFONTENCODING_ISO8859_1
;
759 str
= StreamOut(encoding
);
763 // we have to manually extract the required part, luckily
764 // this is easy in this case as EOL characters in str are
765 // just LFs because we remove CRs in wxRichEditStreamOut
766 str
= str
.Mid(from
, to
- from
);
770 // StreamOut() wasn't used or failed, try to do it in normal way
772 #endif // !wxUSE_UNICODE
774 // alloc one extra WORD as needed by the control
775 wxStringBuffer
tmp(str
, ++len
);
779 textRange
.chrg
.cpMin
= from
;
780 textRange
.chrg
.cpMax
= to
;
781 textRange
.lpstrText
= p
;
783 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE
,
784 0, (LPARAM
)&textRange
);
786 if ( m_verRichEdit
> 1 )
788 // RichEdit 2.0 uses just CR ('\r') for the
789 // newlines which is neither Unix nor Windows
790 // style - convert it to something reasonable
793 if ( *p
== wxT('\r') )
799 if ( m_verRichEdit
== 1 )
801 // convert to the canonical form - see comment below
802 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
805 //else: no text at all, leave the string empty
808 #endif // wxUSE_RICHEDIT
810 // retrieve all text: wxTextEntry method works even for multiline
811 // controls and must be used for single line ones to account for hints
812 str
= wxTextEntry::GetValue();
814 // need only a range?
817 str
= str
.Mid(from
, to
- from
);
820 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
821 // canonical one (same one as above) for consistency with the other kinds
822 // of controls and, more importantly, with the other ports
823 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
829 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
831 // if the text is long enough, it's faster to just set it instead of first
832 // comparing it with the old one (chances are that it will be different
833 // anyhow, this comparison is there to avoid flicker for small single-line
834 // edit controls mostly)
835 if ( (value
.length() > 0x400) || (value
!= DoGetValue()) )
837 DoWriteText(value
, flags
/* doesn't include SelectionOnly here */);
839 // mark the control as being not dirty - we changed its text, not the
843 // for compatibility, don't move the cursor when doing SetValue()
844 SetInsertionPoint(0);
848 // still reset the modified flag even if the value didn't really change
849 // because now it comes from the program and not the user (and do it
850 // before generating the event so that the event handler could get the
851 // expected value from IsModified())
854 // still send an event for consistency
855 if (flags
& SetValue_SendEvent
)
860 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
862 // TODO: using memcpy() would improve performance a lot for big amounts of text
865 wxRichEditStreamIn(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
869 const wchar_t ** const ppws
= (const wchar_t **)dwCookie
;
871 wchar_t *wbuf
= (wchar_t *)buf
;
872 const wchar_t *wpc
= *ppws
;
877 cb
-= sizeof(wchar_t);
878 (*pcb
) += sizeof(wchar_t);
886 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
887 struct wxStreamOutData
894 wxRichEditStreamOut(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
898 wxStreamOutData
*data
= (wxStreamOutData
*)dwCookie
;
900 const wchar_t *wbuf
= (const wchar_t *)buf
;
901 wchar_t *wpc
= data
->wpc
;
904 wchar_t wch
= *wbuf
++;
906 // turn "\r\n" into "\n" on the fly
912 cb
-= sizeof(wchar_t);
913 (*pcb
) += sizeof(wchar_t);
922 #if wxUSE_UNICODE_MSLU
923 #define UNUSED_IF_MSLU(param)
925 #define UNUSED_IF_MSLU(param) param
929 wxTextCtrl::StreamIn(const wxString
& value
,
930 wxFontEncoding
UNUSED_IF_MSLU(encoding
),
933 #if wxUSE_UNICODE_MSLU
934 const wchar_t *wpc
= value
.c_str();
935 #else // !wxUSE_UNICODE_MSLU
936 wxCSConv
conv(encoding
);
938 const size_t len
= conv
.MB2WC(NULL
, value
.mb_str(), value
.length());
940 if (len
== wxCONV_FAILED
)
943 wxWCharBuffer
wchBuf(len
); // allocates one extra character
944 wchar_t *wpc
= wchBuf
.data();
946 conv
.MB2WC(wpc
, value
.mb_str(), len
+ 1);
947 #endif // wxUSE_UNICODE_MSLU
949 // finally, stream it in the control
952 eds
.dwCookie
= (DWORD_PTR
)&wpc
;
953 // the cast below is needed for broken (very) old mingw32 headers
954 eds
.pfnCallback
= (EDITSTREAMCALLBACK
)wxRichEditStreamIn
;
956 // same problem as in DoWriteText(): we can get multiple events here
957 UpdatesCountFilter
ucf(m_updatesCount
);
959 ::SendMessage(GetHwnd(), EM_STREAMIN
,
962 (selectionOnly
? SFF_SELECTION
: 0),
965 // It's okay for EN_UPDATE to not be sent if the selection is empty and
966 // the text is empty, otherwise warn the programmer about it.
967 wxASSERT_MSG( ucf
.GotUpdate() || ( !HasSelection() && value
.empty() ),
968 wxT("EM_STREAMIN didn't send EN_UPDATE?") );
972 wxLogLastError(wxT("EM_STREAMIN"));
978 #if !wxUSE_UNICODE_MSLU
981 wxTextCtrl::StreamOut(wxFontEncoding encoding
, bool selectionOnly
) const
985 const int len
= GetWindowTextLength(GetHwnd());
987 wxWCharBuffer
wchBuf(len
);
988 wchar_t *wpc
= wchBuf
.data();
990 wxStreamOutData data
;
996 eds
.dwCookie
= (DWORD
)&data
;
997 eds
.pfnCallback
= wxRichEditStreamOut
;
1003 SF_TEXT
| SF_UNICODE
| (selectionOnly
? SFF_SELECTION
: 0),
1009 wxLogLastError(wxT("EM_STREAMOUT"));
1011 else // streamed out ok
1013 // NUL-terminate the string because its length could have been
1014 // decreased by wxRichEditStreamOut
1015 *(wchBuf
.data() + data
.len
) = L
'\0';
1017 // now convert to the given encoding (this is a possibly lossful
1018 // conversion but what else can we do)
1019 wxCSConv
conv(encoding
);
1020 size_t lenNeeded
= conv
.WC2MB(NULL
, wchBuf
, 0);
1022 if ( lenNeeded
!= wxCONV_FAILED
&& lenNeeded
++ )
1024 conv
.WC2MB(wxStringBuffer(out
, lenNeeded
), wchBuf
, lenNeeded
);
1031 #endif // !wxUSE_UNICODE_MSLU
1033 #endif // wxUSE_RICHEDIT
1035 void wxTextCtrl::WriteText(const wxString
& value
)
1040 void wxTextCtrl::DoWriteText(const wxString
& value
, int flags
)
1042 bool selectionOnly
= (flags
& SetValue_SelectionOnly
) != 0;
1044 if ( m_windowStyle
& wxTE_MULTILINE
)
1045 valueDos
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
1050 // there are several complications with the rich edit controls here
1054 // first, ensure that the new text will be in the default style
1055 if ( !m_defaultStyle
.IsDefault() )
1058 GetSelection(&start
, &end
);
1059 SetStyle(start
, end
, m_defaultStyle
);
1062 #if wxUSE_UNICODE_MSLU
1063 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1064 // but EM_STREAMIN works
1065 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1067 done
= StreamIn(valueDos
, wxFONTENCODING_SYSTEM
, selectionOnly
);
1069 #endif // wxUSE_UNICODE_MSLU
1072 // next check if the text we're inserting must be shown in a non
1073 // default charset -- this only works for RichEdit > 1.0
1074 if ( GetRichVersion() > 1 )
1076 wxFont font
= m_defaultStyle
.GetFont();
1082 wxFontEncoding encoding
= font
.GetEncoding();
1083 if ( encoding
!= wxFONTENCODING_SYSTEM
)
1085 // we have to use EM_STREAMIN to force richedit control 2.0+
1086 // to show any text in the non default charset -- otherwise
1087 // it thinks it knows better than we do and always shows it
1088 // in the default one
1089 done
= StreamIn(valueDos
, encoding
, selectionOnly
);
1093 #endif // !wxUSE_UNICODE
1097 #endif // wxUSE_RICHEDIT
1099 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1100 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1101 // -- undetermined -- conditions with rich edit) and sometimes we don't
1102 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1103 // we generate exactly one of them by ignoring all but the first one in
1104 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1105 // notifications from Windows
1106 if ( !(flags
& SetValue_SendEvent
) )
1107 m_updatesCount
= -2; // suppress any update event
1109 UpdatesCountFilter
ucf(m_updatesCount
);
1111 ::SendMessage(GetHwnd(), selectionOnly
? EM_REPLACESEL
: WM_SETTEXT
,
1112 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1113 selectionOnly
? 1 : 0, wxMSW_CONV_LPARAM(valueDos
));
1115 if ( !ucf
.GotUpdate() && (flags
& SetValue_SendEvent
) )
1122 void wxTextCtrl::AppendText(const wxString
& text
)
1124 wxTextEntry::AppendText(text
);
1127 // don't do this if we're frozen, saves some time
1128 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1130 ::SendMessage(GetHwnd(), WM_VSCROLL
, SB_BOTTOM
, (LPARAM
)NULL
);
1132 #endif // wxUSE_RICHEDIT
1135 void wxTextCtrl::Clear()
1137 ::SetWindowText(GetHwnd(), wxEmptyString
);
1139 if ( IsMultiLine() && !IsRich() )
1141 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1142 // but the normal ones don't -- make Clear() behaviour consistent by
1143 // always sending this event
1150 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent
& event
)
1154 size_t lenOld
= GetValue().length();
1156 wxUint32 code
= event
.GetRawKeyCode();
1157 ::keybd_event((BYTE
)code
, 0, 0 /* key press */, 0);
1158 ::keybd_event((BYTE
)code
, 0, KEYEVENTF_KEYUP
, 0);
1160 // assume that any alphanumeric key changes the total number of characters
1161 // in the control - this should work in 99% of cases
1162 return GetValue().length() != lenOld
;
1167 // ----------------------------------------------------------------------------
1169 // ----------------------------------------------------------------------------
1171 void wxTextCtrl::SetInsertionPointEnd()
1173 // we must not do anything if the caret is already there because calling
1174 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1175 // if it doesn't actually move the caret anywhere and so the simple fact of
1176 // doing it results in horrible flicker when appending big amounts of text
1177 // to the control in a few chunks (see DoAddText() test in the text sample)
1178 const wxTextPos lastPosition
= GetLastPosition();
1179 if ( GetInsertionPoint() == lastPosition
)
1184 SetInsertionPoint(lastPosition
);
1187 long wxTextCtrl::GetInsertionPoint() const
1195 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &range
);
1198 #endif // wxUSE_RICHEDIT
1200 return wxTextEntry::GetInsertionPoint();
1203 wxTextPos
wxTextCtrl::GetLastPosition() const
1205 if ( IsMultiLine() )
1207 int numLines
= GetNumberOfLines();
1208 long posStartLastLine
= XYToPosition(0, numLines
- 1);
1210 long lenLastLine
= GetLengthOfLineContainingPos(posStartLastLine
);
1212 return posStartLastLine
+ lenLastLine
;
1215 return wxTextEntry::GetLastPosition();
1218 // If the return values from and to are the same, there is no
1220 void wxTextCtrl::GetSelection(long *from
, long *to
) const
1225 CHARRANGE charRange
;
1226 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &charRange
);
1228 *from
= charRange
.cpMin
;
1229 *to
= charRange
.cpMax
;
1232 #endif // !wxUSE_RICHEDIT
1234 wxTextEntry::GetSelection(from
, to
);
1238 // ----------------------------------------------------------------------------
1240 // ----------------------------------------------------------------------------
1242 void wxTextCtrl::DoSetSelection(long from
, long to
, int flags
)
1244 HWND hWnd
= GetHwnd();
1249 // if from and to are both -1, it means (in wxWidgets) that all text
1250 // should be selected, translate this into Windows convention
1251 if ( (from
== -1) && (to
== -1) )
1259 ::SendMessage(hWnd
, EM_EXSETSEL
, 0, (LPARAM
)&range
);
1262 #endif // wxUSE_RICHEDIT
1264 wxTextEntry::DoSetSelection(from
, to
, flags
);
1267 if ( (flags
& SetSel_Scroll
) && !IsFrozen() )
1270 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1271 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1272 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1273 // option is set (but it does work ok in richedit 1.0 mode...)
1275 // so to make it work we either need to give focus to it here which
1276 // will probably create many problems (dummy focus events; window
1277 // containing the text control being brought to foreground
1278 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1279 // create other problems too -- and in fact it does because if we turn
1280 // on/off this style while appending the text to the control, the
1281 // vertical scrollbar never appears in it even if we append tons of
1282 // text and to work around this the only solution I found was to use
1283 // ES_DISABLENOSCROLL
1285 // this is very ugly but I don't see any other way to make this work
1287 if ( GetRichVersion() > 1 )
1289 if ( !HasFlag(wxTE_NOHIDESEL
) )
1291 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1292 // others, remember the style so we can reset it later if needed
1293 style
= ::GetWindowLong(GetHwnd(), GWL_STYLE
);
1294 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1295 ECOOP_OR
, ECO_NOHIDESEL
);
1297 //else: everything is already ok
1299 #endif // wxUSE_RICHEDIT
1301 ::SendMessage(hWnd
, EM_SCROLLCARET
, 0, (LPARAM
)0);
1304 // restore ECO_NOHIDESEL if we changed it
1305 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL
) )
1307 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1308 ECOOP_AND
, ~ECO_NOHIDESEL
);
1309 if ( style
!= ::GetWindowLong(GetHwnd(), GWL_STYLE
) )
1310 ::SetWindowLong(GetHwnd(), GWL_STYLE
, style
);
1312 #endif // wxUSE_RICHEDIT
1316 // ----------------------------------------------------------------------------
1317 // Working with files
1318 // ----------------------------------------------------------------------------
1320 bool wxTextCtrl::DoLoadFile(const wxString
& file
, int fileType
)
1322 if ( wxTextCtrlBase::DoLoadFile(file
, fileType
) )
1324 // update the size limit if needed
1333 // ----------------------------------------------------------------------------
1335 // ----------------------------------------------------------------------------
1337 bool wxTextCtrl::IsModified() const
1339 return ::SendMessage(GetHwnd(), EM_GETMODIFY
, 0, 0) != 0;
1342 void wxTextCtrl::MarkDirty()
1344 ::SendMessage(GetHwnd(), EM_SETMODIFY
, TRUE
, 0);
1347 void wxTextCtrl::DiscardEdits()
1349 ::SendMessage(GetHwnd(), EM_SETMODIFY
, FALSE
, 0);
1352 // ----------------------------------------------------------------------------
1353 // Positions <-> coords
1354 // ----------------------------------------------------------------------------
1356 int wxTextCtrl::GetNumberOfLines() const
1358 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT
, 0, 0);
1361 long wxTextCtrl::XYToPosition(long x
, long y
) const
1363 // This gets the char index for the _beginning_ of this line
1364 long charIndex
= ::SendMessage(GetHwnd(), EM_LINEINDEX
, y
, 0);
1366 return charIndex
+ x
;
1369 bool wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
1371 HWND hWnd
= GetHwnd();
1373 // This gets the line number containing the character
1378 lineNo
= ::SendMessage(hWnd
, EM_EXLINEFROMCHAR
, 0, pos
);
1381 #endif // wxUSE_RICHEDIT
1383 lineNo
= ::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1392 // This gets the char index for the _beginning_ of this line
1393 long charIndex
= ::SendMessage(hWnd
, EM_LINEINDEX
, lineNo
, 0);
1394 if ( charIndex
== -1 )
1399 // The X position must therefore be the different between pos and charIndex
1401 *x
= pos
- charIndex
;
1408 wxTextCtrlHitTestResult
1409 wxTextCtrl::HitTest(const wxPoint
& pt
, long *posOut
) const
1411 // first get the position from Windows
1418 // for rich edit controls the position is passed iva the struct fields
1421 lParam
= (LPARAM
)&ptl
;
1424 #endif // wxUSE_RICHEDIT
1426 // for the plain ones, we are limited to 16 bit positions which are
1427 // combined in a single 32 bit value
1428 lParam
= MAKELPARAM(pt
.x
, pt
.y
);
1431 LRESULT pos
= ::SendMessage(GetHwnd(), EM_CHARFROMPOS
, 0, lParam
);
1435 // this seems to indicate an error...
1436 return wxTE_HT_UNKNOWN
;
1441 #endif // wxUSE_RICHEDIT
1443 // for plain EDIT controls the higher word contains something else
1448 // next determine where it is relatively to our point: EM_CHARFROMPOS
1449 // always returns the closest character but we need to be more precise, so
1450 // double check that we really are where it pretends
1454 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1455 // we don't know how to do it
1458 ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&ptReal
, pos
);
1461 #endif // wxUSE_RICHEDIT
1463 LRESULT lRc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1467 // this is apparently returned when pos corresponds to the last
1474 ptReal
.x
= LOWORD(lRc
);
1475 ptReal
.y
= HIWORD(lRc
);
1479 wxTextCtrlHitTestResult rc
;
1481 if ( pt
.y
> ptReal
.y
+ GetCharHeight() )
1483 else if ( pt
.x
> ptReal
.x
+ GetCharWidth() )
1484 rc
= wxTE_HT_BEYOND
;
1486 rc
= wxTE_HT_ON_TEXT
;
1494 wxPoint
wxTextCtrl::DoPositionToCoords(long pos
) const
1496 // FIXME: This code is broken for rich edit version 2.0 as it uses the same
1497 // API as plain edit i.e. the coordinates are returned directly instead of
1498 // filling the POINT passed as WPARAM with them but we can't distinguish
1499 // between 2.0 and 3.0 unfortunately (see also the use of EM_POSFROMCHAR
1505 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&pt
, pos
);
1507 return wxPoint(pt
.x
, pt
.y
);
1510 #endif // wxUSE_RICHEDIT
1512 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1515 // Finding coordinates for the last position of the control fails
1516 // in plain EDIT control, try to compensate for it by finding it
1517 // ourselves from the position of the previous character.
1518 if ( pos
< GetLastPosition() )
1520 // It's not the expected correctable failure case so just fail.
1521 return wxDefaultPosition
;
1526 // We're being asked the coordinates of the first (and last and
1527 // only) position in an empty control. There is no way to get
1528 // it directly with EM_POSFROMCHAR but EM_GETMARGINS returns
1529 // the correct value for at least the horizontal offset.
1530 rc
= ::SendMessage(GetHwnd(), EM_GETMARGINS
, 0, 0);
1532 // Text control seems to effectively add 1 to margin.
1533 return wxPoint(LOWORD(rc
) + 1, 1);
1536 // We do have a previous character, try to get its coordinates.
1537 rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
- 1, 0);
1540 // If getting coordinates of the previous character failed as
1541 // well, just give up.
1542 return wxDefaultPosition
;
1545 wxString prevChar
= GetRange(pos
- 1, pos
);
1546 wxSize prevCharSize
= GetTextExtent(prevChar
);
1548 if ( prevChar
== wxT("\n" ))
1550 // 'pos' is at the beginning of a new line so its X coordinate
1551 // should be the same as X coordinate of the first character of
1552 // any other line while its Y coordinate will be approximately
1553 // (but we can't compute it exactly...) one character height
1554 // more than that of the previous character.
1555 LRESULT coords0
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, 0, 0);
1556 if ( coords0
== -1 )
1557 return wxDefaultPosition
;
1559 rc
= MAKELPARAM(LOWORD(coords0
), HIWORD(rc
) + prevCharSize
.y
);
1563 // Simple case: previous character is in the same line so this
1564 // one is just after it.
1565 rc
+= MAKELPARAM(prevCharSize
.x
, 0);
1569 // Notice that {LO,HI}WORD macros return WORDs, i.e. unsigned shorts,
1570 // while we want to have signed values here (the y coordinate of any
1571 // position above the first currently visible line is negative, for
1572 // example), hence the need for casts.
1573 return wxPoint(static_cast<short>(LOWORD(rc
)),
1574 static_cast<short>(HIWORD(rc
)));
1577 return wxDefaultPosition
;
1581 // ----------------------------------------------------------------------------
1583 // ----------------------------------------------------------------------------
1585 void wxTextCtrl::ShowPosition(long pos
)
1587 HWND hWnd
= GetHwnd();
1589 // To scroll to a position, we pass the number of lines and characters
1590 // to scroll *by*. This means that we need to:
1591 // (1) Find the line position of the current line.
1592 // (2) Find the line position of pos.
1593 // (3) Scroll by (pos - current).
1594 // For now, ignore the horizontal scrolling.
1596 // Is this where scrolling is relative to - the line containing the caret?
1597 // Or is the first visible line??? Try first visible line.
1598 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, -1, 0L);
1600 int currentLineLineNo
= (int)::SendMessage(hWnd
, EM_GETFIRSTVISIBLELINE
, 0, 0);
1602 int specifiedLineLineNo
= (int)::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1604 int linesToScroll
= specifiedLineLineNo
- currentLineLineNo
;
1606 if (linesToScroll
!= 0)
1607 ::SendMessage(hWnd
, EM_LINESCROLL
, 0, linesToScroll
);
1610 long wxTextCtrl::GetLengthOfLineContainingPos(long pos
) const
1612 return ::SendMessage(GetHwnd(), EM_LINELENGTH
, pos
, 0);
1615 int wxTextCtrl::GetLineLength(long lineNo
) const
1617 long pos
= XYToPosition(0, lineNo
);
1619 return GetLengthOfLineContainingPos(pos
);
1622 wxString
wxTextCtrl::GetLineText(long lineNo
) const
1624 size_t len
= (size_t)GetLineLength(lineNo
) + 1;
1626 // there must be at least enough place for the length WORD in the
1628 len
+= sizeof(WORD
);
1632 wxStringBufferLength
tmp(str
, len
);
1635 *(WORD
*)buf
= (WORD
)len
;
1636 len
= (size_t)::SendMessage(GetHwnd(), EM_GETLINE
, lineNo
, (LPARAM
)buf
);
1641 // remove the '\r' returned by the rich edit control, the user code
1642 // should never see it
1643 if ( buf
[len
- 2] == wxT('\r') && buf
[len
- 1] == wxT('\n') )
1645 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1646 // here and "\n" below
1647 buf
[len
- 2] = wxT('\n');
1650 else if ( buf
[len
- 1] == wxT('\r') )
1652 // richedit 2.0+ uses only "\r", replace it with "\n"
1653 buf
[len
- 1] = wxT('\n');
1656 #endif // wxUSE_RICHEDIT
1658 // remove the '\n' at the end, if any (this is how this function is
1659 // supposed to work according to the docs)
1660 if ( buf
[len
- 1] == wxT('\n') )
1672 void wxTextCtrl::SetMaxLength(unsigned long len
)
1677 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT
, 0, len
? len
: 0x7fffffff);
1680 #endif // wxUSE_RICHEDIT
1682 wxTextEntry::SetMaxLength(len
);
1686 // ----------------------------------------------------------------------------
1688 // ----------------------------------------------------------------------------
1690 void wxTextCtrl::Redo()
1693 if ( GetRichVersion() > 1 )
1695 ::SendMessage(GetHwnd(), EM_REDO
, 0, 0);
1698 #endif // wxUSE_RICHEDIT
1700 wxTextEntry::Redo();
1703 bool wxTextCtrl::CanRedo() const
1706 if ( GetRichVersion() > 1 )
1707 return ::SendMessage(GetHwnd(), EM_CANREDO
, 0, 0) != 0;
1708 #endif // wxUSE_RICHEDIT
1710 return wxTextEntry::CanRedo();
1713 // ----------------------------------------------------------------------------
1714 // caret handling (Windows only)
1715 // ----------------------------------------------------------------------------
1717 bool wxTextCtrl::ShowNativeCaret(bool show
)
1719 if ( show
!= m_isNativeCaretShown
)
1721 if ( !(show
? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1723 // not an error, may simply indicate that it's not shown/hidden
1724 // yet (i.e. it had been hidden/shown 2 times before)
1728 m_isNativeCaretShown
= show
;
1734 // ----------------------------------------------------------------------------
1735 // implementation details
1736 // ----------------------------------------------------------------------------
1738 void wxTextCtrl::Command(wxCommandEvent
& event
)
1740 SetValue(event
.GetString());
1741 ProcessCommand (event
);
1744 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
1746 // By default, load the first file into the text window.
1747 if (event
.GetNumberOfFiles() > 0)
1749 LoadFile(event
.GetFiles()[0]);
1753 // ----------------------------------------------------------------------------
1754 // kbd input processing
1755 // ----------------------------------------------------------------------------
1757 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1759 // check for our special keys here: if we don't do it and the parent frame
1760 // uses them as accelerators, they wouldn't work at all, so we disable
1761 // usual preprocessing for them
1762 if ( msg
->message
== WM_KEYDOWN
)
1764 const WPARAM vkey
= msg
->wParam
;
1765 if ( HIWORD(msg
->lParam
) & KF_ALTDOWN
)
1767 // Alt-Backspace is accelerator for "Undo"
1768 if ( vkey
== VK_BACK
)
1773 // we want to process some Ctrl-foo and Shift-bar but no key
1774 // combinations without either Ctrl or Shift nor with both of them
1776 const int ctrl
= wxIsCtrlDown(),
1777 shift
= wxIsShiftDown();
1778 switch ( ctrl
+ shift
)
1781 wxFAIL_MSG( wxT("how many modifiers have we got?") );
1788 // This one is only special for multi line controls.
1789 if ( !IsMultiLine() )
1803 // either Ctrl or Shift pressed
1818 else // Shift is pressed
1820 if ( vkey
== VK_INSERT
|| vkey
== VK_DELETE
)
1827 return wxControl::MSWShouldPreProcessMessage(msg
);
1830 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
1832 switch ( event
.GetKeyCode() )
1836 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
, m_windowId
);
1837 InitCommandEvent(event
);
1838 event
.SetString(GetValue());
1839 if ( HandleWindowEvent(event
) )
1840 if ( !HasFlag(wxTE_MULTILINE
) )
1842 //else: multiline controls need Enter for themselves
1847 // ok, so this is getting absolutely ridiculous but I don't see
1848 // any other way to fix this bug: when a multiline text control is
1849 // inside a wxFrame, we need to generate the navigation event as
1850 // otherwise nothing happens at all, but when the same control is
1851 // created inside a dialog, IsDialogMessage() *does* switch focus
1852 // all by itself and so if we do it here as well, it is advanced
1853 // twice and goes to the next control... to prevent this from
1854 // happening we're doing this ugly check, the logic being that if
1855 // we don't have focus then it had been already changed to the next
1858 // the right thing to do would, of course, be to understand what
1859 // the hell is IsDialogMessage() doing but this is beyond my feeble
1860 // forces at the moment unfortunately
1861 if ( !(m_windowStyle
& wxTE_PROCESS_TAB
))
1863 if ( FindFocus() == this )
1866 if (!event
.ShiftDown())
1867 flags
|= wxNavigationKeyEvent::IsForward
;
1868 if (event
.ControlDown())
1869 flags
|= wxNavigationKeyEvent::WinChange
;
1870 if (Navigate(flags
))
1876 // Insert tab since calling the default Windows handler
1877 // doesn't seem to do it
1878 WriteText(wxT("\t"));
1884 // no, we didn't process it
1888 void wxTextCtrl::OnKeyDown(wxKeyEvent
& event
)
1890 // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages
1891 // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent
1892 // from working. So we work around it by intercepting these shortcuts
1893 // ourselves and emitting clipboard events (which richedit will handle,
1894 // so everything works as before, including pasting of rich text):
1895 if ( event
.GetModifiers() == wxMOD_CONTROL
&& IsRich() )
1897 switch ( event
.GetKeyCode() )
1913 // Default window procedure of multiline edit controls posts WM_CLOSE to
1914 // the parent window when it gets Escape key press for some reason, prevent
1915 // it from doing this as this resulted in dialog boxes being closed on
1916 // Escape even when they shouldn't be (we do handle Escape ourselves
1917 // correctly in the situations when it should close them).
1918 if ( event
.GetKeyCode() == WXK_ESCAPE
&& IsMultiLine() )
1921 // no, we didn't process it
1925 WXLRESULT
wxTextCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1927 WXLRESULT lRc
= wxTextCtrlBase::MSWWindowProc(nMsg
, wParam
, lParam
);
1933 // we always want the chars and the arrows: the arrows for
1934 // navigation and the chars because we want Ctrl-C to work even
1935 // in a read only control
1936 long lDlgCode
= DLGC_WANTCHARS
| DLGC_WANTARROWS
;
1940 // we may have several different cases:
1941 // 1. normal: both TAB and ENTER are used for navigation
1942 // 2. ctrl wants TAB for itself: ENTER is used to pass to
1943 // the next control in the dialog
1944 // 3. ctrl wants ENTER for itself: TAB is used for dialog
1946 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
1947 // go to the next control (we need some way to do it)
1949 // multiline controls should always get ENTER for themselves
1950 if ( HasFlag(wxTE_PROCESS_ENTER
) || HasFlag(wxTE_MULTILINE
) )
1951 lDlgCode
|= DLGC_WANTMESSAGE
;
1953 if ( HasFlag(wxTE_PROCESS_TAB
) )
1954 lDlgCode
|= DLGC_WANTTAB
;
1960 // NB: use "=", not "|=" as the base class version returns
1961 // the same flags in the disabled state as usual (i.e.
1962 // including DLGC_WANTMESSAGE). This is strange (how
1963 // does it work in the native Win32 apps?) but for now
1968 // Clear the DLGC_HASSETSEL bit from the return value
1969 lRc
&= ~DLGC_HASSETSEL
;
1975 // rich text controls seem to have a bug and don't change the
1976 // cursor to the standard arrow one from the I-beam cursor usually
1977 // used by them even when a popup menu is shown (this works fine
1978 // for plain EDIT controls though), so explicitly work around this
1981 extern wxMenu
*wxCurrentPopupMenu
;
1982 if ( wxCurrentPopupMenu
&&
1983 wxCurrentPopupMenu
->GetInvokingWindow() == this )
1984 ::SetCursor(GetHcursorOf(*wxSTANDARD_CURSOR
));
1986 #endif // wxUSE_MENUS
1992 // ----------------------------------------------------------------------------
1993 // text control event processing
1994 // ----------------------------------------------------------------------------
1996 bool wxTextCtrl::SendUpdateEvent()
1998 switch ( m_updatesCount
)
2001 // remember that we've got an update
2006 // we had already sent one event since the last control modification
2010 wxFAIL_MSG( wxT("unexpected wxTextCtrl::m_updatesCount value") );
2014 // we hadn't updated the control ourselves, this event comes from
2015 // the user, don't need to ignore it nor update the count
2019 // the control was updated programmatically and we do NOT want to
2024 return SendTextUpdatedEvent();
2027 bool wxTextCtrl::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
2036 // the text size limit has been hit -- try to increase it
2037 if ( !AdjustSpaceLimit() )
2039 wxCommandEvent
event(wxEVT_COMMAND_TEXT_MAXLEN
, m_windowId
);
2040 InitCommandEvent(event
);
2041 event
.SetString(GetValue());
2042 ProcessCommand(event
);
2046 // the other edit notification messages are not processed (or, in
2047 // the case of EN_{SET/KILL}FOCUS were already handled at WM_SET/
2057 WXHBRUSH
wxTextCtrl::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
2059 if ( !IsThisEnabled() && !HasFlag(wxTE_MULTILINE
) )
2060 return MSWControlColorDisabled(hDC
);
2062 return wxTextCtrlBase::MSWControlColor(hDC
, hWnd
);
2065 bool wxTextCtrl::HasSpaceLimit(unsigned int *len
) const
2067 // HACK: we try to automatically extend the limit for the amount of text
2068 // to allow (interactively) entering more than 64Kb of text under
2069 // Win9x but we shouldn't reset the text limit which was previously
2070 // set explicitly with SetMaxLength()
2072 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2073 // know the limit we set (if any). We could solve this by storing the
2074 // limit we set in wxTextCtrl but to save space we prefer to simply
2075 // test here the actual limit value: we consider that SetMaxLength()
2076 // can only be called for small values while EN_MAXTEXT is only sent
2077 // for large values (in practice the default limit seems to be 30000
2078 // but make it smaller just to be on the safe side)
2079 *len
= ::SendMessage(GetHwnd(), EM_GETLIMITTEXT
, 0, 0);
2080 return *len
< 10001;
2084 bool wxTextCtrl::AdjustSpaceLimit()
2087 if ( HasSpaceLimit(&limit
) )
2090 unsigned int len
= ::GetWindowTextLength(GetHwnd());
2093 // increment in 32Kb chunks
2094 SetMaxLength(len
+ 0x8000);
2097 // we changed the limit
2101 bool wxTextCtrl::AcceptsFocusFromKeyboard() const
2103 // we don't want focus if we can't be edited unless we're a multiline
2104 // control because then it might be still nice to get focus from keyboard
2105 // to be able to scroll it without mouse
2106 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2109 wxSize
wxTextCtrl::DoGetBestSize() const
2111 return DoGetSizeFromTextSize( DEFAULT_ITEM_WIDTH
);
2114 wxSize
wxTextCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
2117 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
2120 ::SystemParametersInfo(SPI_GETCARETWIDTH
, 0, &wText
, 0);
2124 if ( m_windowStyle
& wxTE_MULTILINE
)
2126 // add space for vertical scrollbar
2127 if ( !(m_windowStyle
& wxTE_NO_VSCROLL
) )
2128 wText
+= ::GetSystemMetrics(SM_CXVSCROLL
);
2132 hText
*= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2133 // add space for horizontal scrollbar
2134 if ( m_windowStyle
& wxHSCROLL
)
2135 hText
+= ::GetSystemMetrics(SM_CYHSCROLL
);
2138 // for single line control cy (height + external leading) is ok
2141 // Add the margins we have previously set
2142 wxPoint
marg( GetMargins() );
2143 wText
+= wxMax(0, marg
.x
);
2144 hText
+= wxMax(0, marg
.y
);
2147 // Text controls without border are special and have the same height as
2148 // static labels (they also have the same appearance when they're disable
2149 // and are often used as a sort of copyable to the clipboard label so it's
2150 // important that they have the same height as the normal labels to not
2152 if ( !HasFlag(wxBORDER_NONE
) )
2154 wText
+= 9; // borders and inner margins
2156 // we have to add the adjustments for the control height only once, not
2157 // once per line, so do it after multiplication above
2158 hText
+= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
) - cy
;
2161 // Perhaps the user wants something different from CharHeight, or ylen
2162 // is used as the height of a multiline text.
2164 hText
+= ylen
- GetCharHeight();
2166 return wxSize(wText
, hText
);
2169 // ----------------------------------------------------------------------------
2170 // standard handlers for standard edit menu events
2171 // ----------------------------------------------------------------------------
2173 void wxTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
2178 void wxTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
2183 void wxTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
2188 void wxTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
2193 void wxTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
2198 void wxTextCtrl::OnDelete(wxCommandEvent
& WXUNUSED(event
))
2203 void wxTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
2208 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
2210 event
.Enable( CanCut() );
2213 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
2215 event
.Enable( CanCopy() );
2218 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
2220 event
.Enable( CanPaste() );
2223 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
2225 event
.Enable( CanUndo() );
2228 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
2230 event
.Enable( CanRedo() );
2233 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent
& event
)
2235 event
.Enable( HasSelection() && IsEditable() );
2238 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
2240 event
.Enable( !IsEmpty() );
2243 void wxTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
2248 if (!m_privateContextMenu
)
2250 m_privateContextMenu
= new wxMenu
;
2251 m_privateContextMenu
->Append(wxID_UNDO
, _("&Undo"));
2252 m_privateContextMenu
->Append(wxID_REDO
, _("&Redo"));
2253 m_privateContextMenu
->AppendSeparator();
2254 m_privateContextMenu
->Append(wxID_CUT
, _("Cu&t"));
2255 m_privateContextMenu
->Append(wxID_COPY
, _("&Copy"));
2256 m_privateContextMenu
->Append(wxID_PASTE
, _("&Paste"));
2257 m_privateContextMenu
->Append(wxID_CLEAR
, _("&Delete"));
2258 m_privateContextMenu
->AppendSeparator();
2259 m_privateContextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
2261 PopupMenu(m_privateContextMenu
);
2269 void wxTextCtrl::OnSetFocus(wxFocusEvent
& event
)
2271 // be sure the caret remains invisible if the user had hidden it
2272 if ( !m_isNativeCaretShown
)
2274 ::HideCaret(GetHwnd());
2280 // the rest of the file only deals with the rich edit controls
2283 // ----------------------------------------------------------------------------
2284 // EN_LINK processing
2285 // ----------------------------------------------------------------------------
2287 bool wxTextCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2289 NMHDR
*hdr
= (NMHDR
* )lParam
;
2290 switch ( hdr
->code
)
2294 const MSGFILTER
*msgf
= (MSGFILTER
*)lParam
;
2295 UINT msg
= msgf
->msg
;
2297 // this is a bit crazy but richedit 1.0 sends us all mouse
2298 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2299 // generate the wxWin events for this message manually
2301 // NB: in fact, this is still not totally correct as it does
2302 // send us WM_LBUTTONUP if the selection was cleared by the
2303 // last click -- so currently we get 2 events in this case,
2304 // but as I don't see any obvious way to check for this I
2305 // leave this code in place because it's still better than
2306 // not getting left up events at all
2307 if ( msg
== WM_LBUTTONUP
)
2309 WXUINT flags
= msgf
->wParam
;
2310 int x
= GET_X_LPARAM(msgf
->lParam
),
2311 y
= GET_Y_LPARAM(msgf
->lParam
);
2313 HandleMouseEvent(msg
, x
, y
, flags
);
2317 // return true to process the event (and false to ignore it)
2322 const ENLINK
*enlink
= (ENLINK
*)hdr
;
2324 switch ( enlink
->msg
)
2327 // ok, so it is hardcoded - do we really nee to
2330 wxCursor
cur(wxCURSOR_HAND
);
2331 ::SetCursor(GetHcursorOf(cur
));
2337 case WM_LBUTTONDOWN
:
2339 case WM_LBUTTONDBLCLK
:
2340 case WM_RBUTTONDOWN
:
2342 case WM_RBUTTONDBLCLK
:
2343 // send a mouse event
2345 static const wxEventType eventsMouse
[] =
2356 // the event ids are consecutive
2358 evtMouse(eventsMouse
[enlink
->msg
- WM_MOUSEMOVE
]);
2360 InitMouseEvent(evtMouse
,
2361 GET_X_LPARAM(enlink
->lParam
),
2362 GET_Y_LPARAM(enlink
->lParam
),
2365 wxTextUrlEvent
event(m_windowId
, evtMouse
,
2367 enlink
->chrg
.cpMax
);
2369 InitCommandEvent(event
);
2371 *result
= ProcessCommand(event
);
2379 // not processed, leave it to the base class
2380 return wxTextCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
2383 #if wxUSE_DRAG_AND_DROP
2385 void wxTextCtrl::SetDropTarget(wxDropTarget
*dropTarget
)
2387 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
2389 // get rid of the built-in drop target
2390 ::RevokeDragDrop(GetHwnd());
2391 m_dropTarget
= NULL
;
2394 wxTextCtrlBase::SetDropTarget(dropTarget
);
2397 #endif // wxUSE_DRAG_AND_DROP
2399 // ----------------------------------------------------------------------------
2400 // colour setting for the rich edit controls
2401 // ----------------------------------------------------------------------------
2403 bool wxTextCtrl::SetBackgroundColour(const wxColour
& colour
)
2405 if ( !wxTextCtrlBase::SetBackgroundColour(colour
) )
2407 // colour didn't really change
2413 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2414 // EM_SETBKGNDCOLOR additionally
2415 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR
, 0, wxColourToRGB(colour
));
2421 bool wxTextCtrl::SetForegroundColour(const wxColour
& colour
)
2423 if ( !wxTextCtrlBase::SetForegroundColour(colour
) )
2425 // colour didn't really change
2431 // change the colour of everything
2432 WinStruct
<CHARFORMAT
> cf
;
2433 cf
.dwMask
= CFM_COLOR
;
2434 cf
.crTextColor
= wxColourToRGB(colour
);
2435 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, SCF_ALL
, (LPARAM
)&cf
);
2441 bool wxTextCtrl::SetFont(const wxFont
& font
)
2443 if ( !wxTextCtrlBase::SetFont(font
) )
2446 if ( GetRichVersion() >= 4 )
2448 // Using WM_SETFONT is not enough with RichEdit 4.1: it does work but
2449 // for ASCII characters only and inserting a non-ASCII one into it
2450 // later reverts to the default font so use EM_SETCHARFORMAT to change
2451 // the default font for it.
2454 SetStyle(-1, -1, attr
);
2460 // ----------------------------------------------------------------------------
2461 // styling support for rich edit controls
2462 // ----------------------------------------------------------------------------
2464 bool wxTextCtrl::MSWSetCharFormat(const wxTextAttr
& style
, long start
, long end
)
2466 // initialize CHARFORMAT struct
2475 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2476 // CHARFORMAT in that case
2478 if ( m_verRichEdit
== 1 )
2480 // this is the only thing the control is going to grok
2481 cf
.cbSize
= sizeof(CHARFORMAT
);
2486 // CHARFORMAT or CHARFORMAT2
2487 cf
.cbSize
= sizeof(cf
);
2490 if ( style
.HasFont() )
2492 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2493 // but using it doesn't seem to hurt neither so leaving it for now
2495 cf
.dwMask
|= CFM_FACE
| CFM_SIZE
| CFM_CHARSET
|
2496 CFM_ITALIC
| CFM_BOLD
| CFM_UNDERLINE
;
2498 // fill in data from LOGFONT but recalculate lfHeight because we need
2499 // the real height in twips and not the negative number which
2500 // wxFillLogFont() returns (this is correct in general and works with
2501 // the Windows font mapper, but not here)
2503 wxFont
font(style
.GetFont());
2506 wxFillLogFont(&lf
, &font
);
2507 cf
.yHeight
= 20*font
.GetPointSize(); // 1 pt = 20 twips
2508 cf
.bCharSet
= lf
.lfCharSet
;
2509 cf
.bPitchAndFamily
= lf
.lfPitchAndFamily
;
2510 wxStrlcpy(cf
.szFaceName
, lf
.lfFaceName
, WXSIZEOF(cf
.szFaceName
));
2512 // also deal with underline/italic/bold attributes: note that we must
2513 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2514 // style to allow clearing it
2517 cf
.dwEffects
|= CFE_ITALIC
;
2520 if ( lf
.lfWeight
== FW_BOLD
)
2522 cf
.dwEffects
|= CFE_BOLD
;
2525 if ( lf
.lfUnderline
)
2527 cf
.dwEffects
|= CFE_UNDERLINE
;
2530 // strikeout fonts are not supported by wxWidgets
2533 if ( style
.HasTextColour() )
2535 cf
.dwMask
|= CFM_COLOR
;
2536 cf
.crTextColor
= wxColourToRGB(style
.GetTextColour());
2540 if ( m_verRichEdit
!= 1 && style
.HasBackgroundColour() )
2542 cf
.dwMask
|= CFM_BACKCOLOR
;
2543 cf
.crBackColor
= wxColourToRGB(style
.GetBackgroundColour());
2545 #endif // wxUSE_RICHEDIT2
2547 // Apply the style either to the selection or to the entire control.
2549 if ( start
!= -1 || end
!= -1 )
2551 DoSetSelection(start
, end
, SetSel_NoScroll
);
2552 selMode
= SCF_SELECTION
;
2559 if ( !::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, selMode
, (LPARAM
)&cf
) )
2561 wxLogLastError(wxT("SendMessage(EM_SETCHARFORMAT)"));
2568 bool wxTextCtrl::MSWSetParaFormat(const wxTextAttr
& style
, long start
, long end
)
2578 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2579 // PARAFORMAT in that case
2581 if ( m_verRichEdit
== 1 )
2583 // this is the only thing the control is going to grok
2584 pf
.cbSize
= sizeof(PARAFORMAT
);
2589 // PARAFORMAT or PARAFORMAT2
2590 pf
.cbSize
= sizeof(pf
);
2593 if (style
.HasAlignment())
2595 pf
.dwMask
|= PFM_ALIGNMENT
;
2596 if (style
.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
2597 pf
.wAlignment
= PFA_RIGHT
;
2598 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
2599 pf
.wAlignment
= PFA_CENTER
;
2600 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED
)
2601 pf
.wAlignment
= PFA_JUSTIFY
;
2603 pf
.wAlignment
= PFA_LEFT
;
2606 if (style
.HasLeftIndent())
2608 pf
.dwMask
|= PFM_STARTINDENT
| PFM_OFFSET
;
2610 // Convert from 1/10 mm to TWIPS
2611 pf
.dxStartIndent
= (int) (((double) style
.GetLeftIndent()) * mm2twips
/ 10.0) ;
2612 pf
.dxOffset
= (int) (((double) style
.GetLeftSubIndent()) * mm2twips
/ 10.0) ;
2615 if (style
.HasRightIndent())
2617 pf
.dwMask
|= PFM_RIGHTINDENT
;
2619 // Convert from 1/10 mm to TWIPS
2620 pf
.dxRightIndent
= (int) (((double) style
.GetRightIndent()) * mm2twips
/ 10.0) ;
2623 if (style
.HasTabs())
2625 pf
.dwMask
|= PFM_TABSTOPS
;
2627 const wxArrayInt
& tabs
= style
.GetTabs();
2629 pf
.cTabCount
= (SHORT
)wxMin(tabs
.GetCount(), MAX_TAB_STOPS
);
2631 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2633 // Convert from 1/10 mm to TWIPS
2634 pf
.rgxTabs
[i
] = (int) (((double) tabs
[i
]) * mm2twips
/ 10.0) ;
2639 if ( m_verRichEdit
> 1 )
2641 if ( wxTheApp
->GetLayoutDirection() == wxLayout_RightToLeft
)
2643 // Use RTL paragraphs in RTL mode to get proper layout
2644 pf
.dwMask
|= PFM_RTLPARA
;
2645 pf
.wEffects
|= PFE_RTLPARA
;
2648 #endif // wxUSE_RICHEDIT2
2652 // Do format the selection.
2653 DoSetSelection(start
, end
, SetSel_NoScroll
);
2655 if ( !::SendMessage(GetHwnd(), EM_SETPARAFORMAT
, 0, (LPARAM
) &pf
) )
2657 wxLogLastError(wxT("SendMessage(EM_SETPARAFORMAT)"));
2666 bool wxTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
2670 // can't do it with normal text control
2674 // the richedit 1.0 doesn't handle setting background colour, so don't
2675 // even try to do anything if it's the only thing we want to change
2676 if ( m_verRichEdit
== 1 && !style
.HasFont() && !style
.HasTextColour() &&
2677 !style
.HasLeftIndent() && !style
.HasRightIndent() && !style
.HasAlignment() &&
2680 // nothing to do: return true if there was really nothing to do and
2681 // false if we failed to set bg colour
2682 return !style
.HasBackgroundColour();
2685 // order the range if needed
2689 // we can only change the format of the selection, so select the range we
2690 // want and restore the old selection later, after MSWSetXXXFormat()
2691 // functions (possibly) change it.
2692 long startOld
, endOld
;
2693 GetSelection(&startOld
, &endOld
);
2695 bool ok
= MSWSetCharFormat(style
, start
, end
);
2696 if ( !MSWSetParaFormat(style
, start
, end
) )
2699 if ( start
!= startOld
|| end
!= endOld
)
2701 // restore the original selection
2702 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2708 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
2710 if ( !wxTextCtrlBase::SetDefaultStyle(style
) )
2715 // we have to do this or the style wouldn't apply for the text typed by
2717 wxTextPos posLast
= GetLastPosition();
2718 SetStyle(posLast
, posLast
, m_defaultStyle
);
2724 bool wxTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
2728 // can't do it with normal text control
2732 // initialize CHARFORMAT struct
2741 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2742 // CHARFORMAT in that case
2744 if ( m_verRichEdit
== 1 )
2746 // this is the only thing the control is going to grok
2747 cf
.cbSize
= sizeof(CHARFORMAT
);
2752 // CHARFORMAT or CHARFORMAT2
2753 cf
.cbSize
= sizeof(cf
);
2755 // we can only change the format of the selection, so select the range we
2756 // want and restore the old selection later
2757 long startOld
, endOld
;
2758 GetSelection(&startOld
, &endOld
);
2760 // but do we really have to change the selection?
2761 bool changeSel
= position
!= startOld
|| position
!= endOld
;
2765 DoSetSelection(position
, position
+ 1, SetSel_NoScroll
);
2768 // get the selection formatting
2769 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT
,
2770 SCF_SELECTION
, (LPARAM
)&cf
) ;
2774 // Convert the height from the units of 1/20th of the point in which
2775 // CHARFORMAT stores it to pixel-based units used by LOGFONT.
2776 const wxCoord ppi
= wxClientDC(this).GetPPI().y
;
2777 lf
.lfHeight
= -MulDiv(cf
.yHeight
/20, ppi
, 72);
2779 lf
.lfCharSet
= ANSI_CHARSET
; // FIXME: how to get correct charset?
2780 lf
.lfClipPrecision
= 0;
2781 lf
.lfEscapement
= 0;
2782 wxStrcpy(lf
.lfFaceName
, cf
.szFaceName
);
2784 //NOTE: we _MUST_ set each of these values to _something_ since we
2785 //do not call wxZeroMemory on the LOGFONT lf
2786 if (cf
.dwEffects
& CFE_ITALIC
)
2789 lf
.lfItalic
= FALSE
;
2791 lf
.lfOrientation
= 0;
2792 lf
.lfPitchAndFamily
= cf
.bPitchAndFamily
;
2795 if (cf
.dwEffects
& CFE_STRIKEOUT
)
2796 lf
.lfStrikeOut
= TRUE
;
2798 lf
.lfStrikeOut
= FALSE
;
2800 if (cf
.dwEffects
& CFE_UNDERLINE
)
2801 lf
.lfUnderline
= TRUE
;
2803 lf
.lfUnderline
= FALSE
;
2805 if (cf
.dwEffects
& CFE_BOLD
)
2806 lf
.lfWeight
= FW_BOLD
;
2808 lf
.lfWeight
= FW_NORMAL
;
2810 wxFont font
= wxCreateFontFromLogFont(& lf
);
2813 style
.SetFont(font
);
2815 style
.SetTextColour(wxColour(cf
.crTextColor
));
2818 if ( m_verRichEdit
!= 1 )
2820 // cf.dwMask |= CFM_BACKCOLOR;
2821 style
.SetBackgroundColour(wxColour(cf
.crBackColor
));
2823 #endif // wxUSE_RICHEDIT2
2825 // now get the paragraph formatting
2828 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2829 // PARAFORMAT in that case
2831 if ( m_verRichEdit
== 1 )
2833 // this is the only thing the control is going to grok
2834 pf
.cbSize
= sizeof(PARAFORMAT
);
2839 // PARAFORMAT or PARAFORMAT2
2840 pf
.cbSize
= sizeof(pf
);
2843 // do format the selection
2844 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT
, 0, (LPARAM
) &pf
) ;
2846 style
.SetLeftIndent( (int) ((double) pf
.dxStartIndent
* twips2mm
* 10.0), (int) ((double) pf
.dxOffset
* twips2mm
* 10.0) );
2847 style
.SetRightIndent( (int) ((double) pf
.dxRightIndent
* twips2mm
* 10.0) );
2849 if (pf
.wAlignment
== PFA_CENTER
)
2850 style
.SetAlignment(wxTEXT_ALIGNMENT_CENTRE
);
2851 else if (pf
.wAlignment
== PFA_RIGHT
)
2852 style
.SetAlignment(wxTEXT_ALIGNMENT_RIGHT
);
2853 else if (pf
.wAlignment
== PFA_JUSTIFY
)
2854 style
.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED
);
2856 style
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
2858 wxArrayInt tabStops
;
2860 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2862 tabStops
.Add( (int) ((double) (pf
.rgxTabs
[i
] & 0xFFFF) * twips2mm
* 10.0) );
2867 // restore the original selection
2868 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2874 // ----------------------------------------------------------------------------
2876 // ----------------------------------------------------------------------------
2878 static const HINSTANCE INVALID_HINSTANCE
= (HINSTANCE
)-1;
2880 bool wxRichEditModule::OnInit()
2882 // don't do anything - we will load it when needed
2886 void wxRichEditModule::OnExit()
2888 for ( size_t i
= 0; i
< WXSIZEOF(ms_hRichEdit
); i
++ )
2890 if ( ms_hRichEdit
[i
] && ms_hRichEdit
[i
] != INVALID_HINSTANCE
)
2892 ::FreeLibrary(ms_hRichEdit
[i
]);
2893 ms_hRichEdit
[i
] = NULL
;
2897 if (ms_inkEditLib
.IsLoaded())
2898 ms_inkEditLib
.Unload();
2903 bool wxRichEditModule::Load(Version version
)
2905 if ( ms_hRichEdit
[version
] == INVALID_HINSTANCE
)
2907 // we had already tried to load it and failed
2911 if ( ms_hRichEdit
[version
] )
2913 // we've already got this one
2917 static const wxChar
*const dllnames
[] =
2924 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames
) == Version_Max
,
2925 RichEditDllNamesVersionsMismatch
);
2927 ms_hRichEdit
[version
] = ::LoadLibrary(dllnames
[version
]);
2929 if ( !ms_hRichEdit
[version
] )
2931 ms_hRichEdit
[version
] = INVALID_HINSTANCE
;
2940 // load the InkEdit library
2941 bool wxRichEditModule::LoadInkEdit()
2943 if (ms_inkEditLibLoadAttemped
)
2944 return ms_inkEditLib
.IsLoaded();
2946 ms_inkEditLibLoadAttemped
= true;
2949 return ms_inkEditLib
.Load(wxT("inked"));
2951 #endif // wxUSE_INKEDIT
2954 #endif // wxUSE_RICHEDIT
2956 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)