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
|
503 if ( IsSingleLine() )
505 // If we don't set the margins explicitly, their size depends on the
506 // control initial size, see #2438. So explicitly set them to something
507 // consistent. And for this we have 2 candidates: EC_USEFONTINFO (which
508 // sets the left margin to 3 pixels, at least under Windows 7) or 0. We
509 // use the former because it looks like it was meant to be used as the
510 // default (what else would it be there for?) and 0 looks bad in
511 // classic mode, i.e. without themes. Also, the margin can be reset to
512 // 0 easily by calling SetMargins() explicitly but setting it to the
513 // default value is not currently supported.
515 // Finally, notice that EC_USEFONTINFO is used differently for plain
516 // and rich text controls.
521 wParam
= EC_USEFONTINFO
;
524 else // plain EDIT, EC_USEFONTINFO is used in lParam with them.
526 wParam
= EC_LEFTMARGIN
| EC_RIGHTMARGIN
;
527 lParam
= MAKELPARAM(EC_USEFONTINFO
, EC_USEFONTINFO
);
530 ::SendMessage(GetHwnd(), EM_SETMARGINS
, wParam
, lParam
);
532 #endif // !__WXWINCE__
537 // Make sure the window style (etc.) reflects the HWND style (roughly)
538 void wxTextCtrl::AdoptAttributesFromHWND()
540 wxWindow::AdoptAttributesFromHWND();
542 HWND hWnd
= GetHwnd();
543 long style
= ::GetWindowLong(hWnd
, GWL_STYLE
);
545 // retrieve the style to see whether this is an edit or richedit ctrl
547 wxString classname
= wxGetWindowClass(GetHWND());
549 if ( classname
.IsSameAs(wxT("EDIT"), false /* no case */) )
556 if ( wxSscanf(classname
, wxT("RichEdit%d0%c"), &m_verRichEdit
, &c
) != 2 )
558 wxLogDebug(wxT("Unknown edit control '%s'."), classname
.c_str());
563 #endif // wxUSE_RICHEDIT
565 if (style
& ES_MULTILINE
)
566 m_windowStyle
|= wxTE_MULTILINE
;
567 if (style
& ES_PASSWORD
)
568 m_windowStyle
|= wxTE_PASSWORD
;
569 if (style
& ES_READONLY
)
570 m_windowStyle
|= wxTE_READONLY
;
571 if (style
& ES_WANTRETURN
)
572 m_windowStyle
|= wxTE_PROCESS_ENTER
;
573 if (style
& ES_CENTER
)
574 m_windowStyle
|= wxTE_CENTRE
;
575 if (style
& ES_RIGHT
)
576 m_windowStyle
|= wxTE_RIGHT
;
579 WXDWORD
wxTextCtrl::MSWGetStyle(long style
, WXDWORD
*exstyle
) const
581 long msStyle
= wxControl::MSWGetStyle(style
, exstyle
);
583 // styles which we always add by default
584 if ( style
& wxTE_MULTILINE
)
586 msStyle
|= ES_MULTILINE
| ES_WANTRETURN
;
587 if ( !(style
& wxTE_NO_VSCROLL
) )
589 // always adjust the vertical scrollbar automatically if we have it
590 msStyle
|= WS_VSCROLL
| ES_AUTOVSCROLL
;
593 // we have to use this style for the rich edit controls because
594 // without it the vertical scrollbar never appears at all in
595 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
596 if ( style
& wxTE_RICH2
)
598 msStyle
|= ES_DISABLENOSCROLL
;
600 #endif // wxUSE_RICHEDIT
603 style
|= wxTE_PROCESS_ENTER
;
607 // there is really no reason to not have this style for single line
609 msStyle
|= ES_AUTOHSCROLL
;
612 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
613 // scrollbar, there is no wrapping -- which makes sense
614 if ( style
& wxTE_DONTWRAP
)
616 // automatically scroll the control horizontally as necessary
618 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
619 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
620 // it doesn't seem to do any harm for plain edit controls, add it
622 msStyle
|= WS_HSCROLL
| ES_AUTOHSCROLL
;
625 if ( style
& wxTE_READONLY
)
626 msStyle
|= ES_READONLY
;
628 if ( style
& wxTE_PASSWORD
)
629 msStyle
|= ES_PASSWORD
;
631 if ( style
& wxTE_NOHIDESEL
)
632 msStyle
|= ES_NOHIDESEL
;
634 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
635 if ( style
& wxTE_CENTRE
)
636 msStyle
|= ES_CENTER
;
637 else if ( style
& wxTE_RIGHT
)
640 msStyle
|= ES_LEFT
; // ES_LEFT is 0 as well but for consistency...
645 void wxTextCtrl::SetWindowStyleFlag(long style
)
647 // changing the alignment of the control dynamically works under Win2003
648 // (but not older Windows version: it seems to work under some versions of
649 // XP but not other ones, and we have no way to determine it so be
650 // conservative here) and only for plain EDIT controls (not RICH ones) and
651 // we have to recreate the control to make it always work
652 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003
)
654 const long alignMask
= wxTE_LEFT
| wxTE_CENTRE
| wxTE_RIGHT
;
655 if ( (style
& alignMask
) != (GetWindowStyle() & alignMask
) )
657 const wxString value
= GetValue();
658 const wxPoint pos
= GetPosition();
659 const wxSize size
= GetSize();
661 // delete the old window
662 HWND hwnd
= GetHwnd();
664 ::DestroyWindow(hwnd
);
666 // create the new one with the updated flags
667 m_windowStyle
= style
;
668 MSWCreateText(value
, pos
, size
);
670 // and make sure it has the same attributes as before
673 // calling SetFont(m_font) would do nothing as the code would
674 // notice that the font didn't change, so force it to believe
676 wxFont font
= m_font
;
683 wxColour colFg
= m_foregroundColour
;
684 m_foregroundColour
= wxNullColour
;
685 SetForegroundColour(colFg
);
690 wxColour colBg
= m_backgroundColour
;
691 m_backgroundColour
= wxNullColour
;
692 SetBackgroundColour(colBg
);
695 // note that text styles are lost but this is probably not a big
696 // problem: if you use styles, you probably don't use nor change
697 // alignment flags anyhow
704 // we have to deal with some styles separately because they can't be
705 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
706 // using richedit-specific EM_SETOPTIONS
708 ((style
& wxTE_NOHIDESEL
) != (GetWindowStyle() & wxTE_NOHIDESEL
)) )
710 bool set
= (style
& wxTE_NOHIDESEL
) != 0;
712 ::SendMessage(GetHwnd(), EM_SETOPTIONS
, set
? ECOOP_OR
: ECOOP_AND
,
713 set
? ECO_NOHIDESEL
: ~ECO_NOHIDESEL
);
715 #endif // wxUSE_RICHEDIT
717 wxControl::SetWindowStyleFlag(style
);
720 // ----------------------------------------------------------------------------
721 // set/get the controls text
722 // ----------------------------------------------------------------------------
724 bool wxTextCtrl::IsEmpty() const
726 // this is an optimization for multiline controls containing a lot of text
727 if ( IsMultiLine() && GetNumberOfLines() != 1 )
730 return wxTextCtrlBase::IsEmpty();
733 wxString
wxTextCtrl::GetValue() const
735 // range 0..-1 is special for GetRange() and means to retrieve all text
736 return GetRange(0, -1);
739 wxString
wxTextCtrl::GetRange(long from
, long to
) const
743 if ( from
>= to
&& to
!= -1 )
745 // nothing to retrieve
752 int len
= GetWindowTextLength(GetHwnd());
759 // we must use EM_STREAMOUT if we don't want to lose all characters
760 // not representable in the current character set (EM_GETTEXTRANGE
761 // simply replaces them with question marks...)
762 if ( GetRichVersion() > 1 )
764 // we must have some encoding, otherwise any 8bit chars in the
765 // control are simply *lost* (replaced by '?')
766 wxFontEncoding encoding
= wxFONTENCODING_SYSTEM
;
768 wxFont font
= m_defaultStyle
.GetFont();
774 encoding
= font
.GetEncoding();
778 if ( encoding
== wxFONTENCODING_SYSTEM
)
780 encoding
= wxLocale::GetSystemEncoding();
784 if ( encoding
== wxFONTENCODING_SYSTEM
)
786 encoding
= wxFONTENCODING_ISO8859_1
;
789 str
= StreamOut(encoding
);
793 // we have to manually extract the required part, luckily
794 // this is easy in this case as EOL characters in str are
795 // just LFs because we remove CRs in wxRichEditStreamOut
796 str
= str
.Mid(from
, to
- from
);
800 // StreamOut() wasn't used or failed, try to do it in normal way
802 #endif // !wxUSE_UNICODE
804 // alloc one extra WORD as needed by the control
805 wxStringBuffer
tmp(str
, ++len
);
809 textRange
.chrg
.cpMin
= from
;
810 textRange
.chrg
.cpMax
= to
;
811 textRange
.lpstrText
= p
;
813 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE
,
814 0, (LPARAM
)&textRange
);
816 if ( m_verRichEdit
> 1 )
818 // RichEdit 2.0 uses just CR ('\r') for the
819 // newlines which is neither Unix nor Windows
820 // style - convert it to something reasonable
823 if ( *p
== wxT('\r') )
829 if ( m_verRichEdit
== 1 )
831 // convert to the canonical form - see comment below
832 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
835 //else: no text at all, leave the string empty
838 #endif // wxUSE_RICHEDIT
840 // retrieve all text: wxTextEntry method works even for multiline
841 // controls and must be used for single line ones to account for hints
842 str
= wxTextEntry::GetValue();
844 // need only a range?
847 str
= str
.Mid(from
, to
- from
);
850 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
851 // canonical one (same one as above) for consistency with the other kinds
852 // of controls and, more importantly, with the other ports
853 str
= wxTextFile::Translate(str
, wxTextFileType_Unix
);
859 void wxTextCtrl::DoSetValue(const wxString
& value
, int flags
)
861 // if the text is long enough, it's faster to just set it instead of first
862 // comparing it with the old one (chances are that it will be different
863 // anyhow, this comparison is there to avoid flicker for small single-line
864 // edit controls mostly)
865 if ( (value
.length() > 0x400) || (value
!= DoGetValue()) )
867 DoWriteText(value
, flags
/* doesn't include SelectionOnly here */);
869 // mark the control as being not dirty - we changed its text, not the
873 // for compatibility, don't move the cursor when doing SetValue()
874 SetInsertionPoint(0);
878 // still reset the modified flag even if the value didn't really change
879 // because now it comes from the program and not the user (and do it
880 // before generating the event so that the event handler could get the
881 // expected value from IsModified())
884 // still send an event for consistency
885 if (flags
& SetValue_SendEvent
)
890 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
892 // TODO: using memcpy() would improve performance a lot for big amounts of text
895 wxRichEditStreamIn(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
899 const wchar_t ** const ppws
= (const wchar_t **)dwCookie
;
901 wchar_t *wbuf
= (wchar_t *)buf
;
902 const wchar_t *wpc
= *ppws
;
907 cb
-= sizeof(wchar_t);
908 (*pcb
) += sizeof(wchar_t);
916 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
917 struct wxStreamOutData
924 wxRichEditStreamOut(DWORD_PTR dwCookie
, BYTE
*buf
, LONG cb
, LONG
*pcb
)
928 wxStreamOutData
*data
= (wxStreamOutData
*)dwCookie
;
930 const wchar_t *wbuf
= (const wchar_t *)buf
;
931 wchar_t *wpc
= data
->wpc
;
934 wchar_t wch
= *wbuf
++;
936 // turn "\r\n" into "\n" on the fly
942 cb
-= sizeof(wchar_t);
943 (*pcb
) += sizeof(wchar_t);
952 #if wxUSE_UNICODE_MSLU
953 #define UNUSED_IF_MSLU(param)
955 #define UNUSED_IF_MSLU(param) param
959 wxTextCtrl::StreamIn(const wxString
& value
,
960 wxFontEncoding
UNUSED_IF_MSLU(encoding
),
963 #if wxUSE_UNICODE_MSLU
964 const wchar_t *wpc
= value
.c_str();
965 #else // !wxUSE_UNICODE_MSLU
966 wxCSConv
conv(encoding
);
968 const size_t len
= conv
.MB2WC(NULL
, value
.mb_str(), value
.length());
970 if (len
== wxCONV_FAILED
)
973 wxWCharBuffer
wchBuf(len
); // allocates one extra character
974 wchar_t *wpc
= wchBuf
.data();
976 conv
.MB2WC(wpc
, value
.mb_str(), len
+ 1);
977 #endif // wxUSE_UNICODE_MSLU
979 // finally, stream it in the control
982 eds
.dwCookie
= (DWORD_PTR
)&wpc
;
983 // the cast below is needed for broken (very) old mingw32 headers
984 eds
.pfnCallback
= (EDITSTREAMCALLBACK
)wxRichEditStreamIn
;
986 // same problem as in DoWriteText(): we can get multiple events here
987 UpdatesCountFilter
ucf(m_updatesCount
);
989 ::SendMessage(GetHwnd(), EM_STREAMIN
,
992 (selectionOnly
? SFF_SELECTION
: 0),
995 // It's okay for EN_UPDATE to not be sent if the selection is empty and
996 // the text is empty, otherwise warn the programmer about it.
997 wxASSERT_MSG( ucf
.GotUpdate() || ( !HasSelection() && value
.empty() ),
998 wxT("EM_STREAMIN didn't send EN_UPDATE?") );
1002 wxLogLastError(wxT("EM_STREAMIN"));
1008 #if !wxUSE_UNICODE_MSLU
1011 wxTextCtrl::StreamOut(wxFontEncoding encoding
, bool selectionOnly
) const
1015 const int len
= GetWindowTextLength(GetHwnd());
1017 wxWCharBuffer
wchBuf(len
);
1018 wchar_t *wpc
= wchBuf
.data();
1020 wxStreamOutData data
;
1026 eds
.dwCookie
= (DWORD
)&data
;
1027 eds
.pfnCallback
= wxRichEditStreamOut
;
1033 SF_TEXT
| SF_UNICODE
| (selectionOnly
? SFF_SELECTION
: 0),
1039 wxLogLastError(wxT("EM_STREAMOUT"));
1041 else // streamed out ok
1043 // NUL-terminate the string because its length could have been
1044 // decreased by wxRichEditStreamOut
1045 *(wchBuf
.data() + data
.len
) = L
'\0';
1047 // now convert to the given encoding (this is a possibly lossful
1048 // conversion but what else can we do)
1049 wxCSConv
conv(encoding
);
1050 size_t lenNeeded
= conv
.WC2MB(NULL
, wchBuf
, 0);
1052 if ( lenNeeded
!= wxCONV_FAILED
&& lenNeeded
++ )
1054 conv
.WC2MB(wxStringBuffer(out
, lenNeeded
), wchBuf
, lenNeeded
);
1061 #endif // !wxUSE_UNICODE_MSLU
1063 #endif // wxUSE_RICHEDIT
1065 void wxTextCtrl::WriteText(const wxString
& value
)
1070 void wxTextCtrl::DoWriteText(const wxString
& value
, int flags
)
1072 bool selectionOnly
= (flags
& SetValue_SelectionOnly
) != 0;
1074 if ( m_windowStyle
& wxTE_MULTILINE
)
1075 valueDos
= wxTextFile::Translate(value
, wxTextFileType_Dos
);
1080 // there are several complications with the rich edit controls here
1084 // first, ensure that the new text will be in the default style
1085 if ( !m_defaultStyle
.IsDefault() )
1088 GetSelection(&start
, &end
);
1089 SetStyle(start
, end
, m_defaultStyle
);
1092 #if wxUSE_UNICODE_MSLU
1093 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1094 // but EM_STREAMIN works
1095 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1097 done
= StreamIn(valueDos
, wxFONTENCODING_SYSTEM
, selectionOnly
);
1099 #endif // wxUSE_UNICODE_MSLU
1102 // next check if the text we're inserting must be shown in a non
1103 // default charset -- this only works for RichEdit > 1.0
1104 if ( GetRichVersion() > 1 )
1106 wxFont font
= m_defaultStyle
.GetFont();
1112 wxFontEncoding encoding
= font
.GetEncoding();
1113 if ( encoding
!= wxFONTENCODING_SYSTEM
)
1115 // we have to use EM_STREAMIN to force richedit control 2.0+
1116 // to show any text in the non default charset -- otherwise
1117 // it thinks it knows better than we do and always shows it
1118 // in the default one
1119 done
= StreamIn(valueDos
, encoding
, selectionOnly
);
1123 #endif // !wxUSE_UNICODE
1127 #endif // wxUSE_RICHEDIT
1129 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1130 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1131 // -- undetermined -- conditions with rich edit) and sometimes we don't
1132 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1133 // we generate exactly one of them by ignoring all but the first one in
1134 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1135 // notifications from Windows
1136 if ( !(flags
& SetValue_SendEvent
) )
1137 m_updatesCount
= -2; // suppress any update event
1139 UpdatesCountFilter
ucf(m_updatesCount
);
1141 ::SendMessage(GetHwnd(), selectionOnly
? EM_REPLACESEL
: WM_SETTEXT
,
1142 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1143 selectionOnly
? 1 : 0, wxMSW_CONV_LPARAM(valueDos
));
1145 if ( !ucf
.GotUpdate() && (flags
& SetValue_SendEvent
) )
1152 void wxTextCtrl::AppendText(const wxString
& text
)
1154 wxTextEntry::AppendText(text
);
1157 // don't do this if we're frozen, saves some time
1158 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1160 ::SendMessage(GetHwnd(), WM_VSCROLL
, SB_BOTTOM
, (LPARAM
)NULL
);
1162 #endif // wxUSE_RICHEDIT
1165 void wxTextCtrl::Clear()
1167 ::SetWindowText(GetHwnd(), wxEmptyString
);
1169 if ( IsMultiLine() && !IsRich() )
1171 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1172 // but the normal ones don't -- make Clear() behaviour consistent by
1173 // always sending this event
1180 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent
& event
)
1184 size_t lenOld
= GetValue().length();
1186 wxUint32 code
= event
.GetRawKeyCode();
1187 ::keybd_event((BYTE
)code
, 0, 0 /* key press */, 0);
1188 ::keybd_event((BYTE
)code
, 0, KEYEVENTF_KEYUP
, 0);
1190 // assume that any alphanumeric key changes the total number of characters
1191 // in the control - this should work in 99% of cases
1192 return GetValue().length() != lenOld
;
1197 // ----------------------------------------------------------------------------
1199 // ----------------------------------------------------------------------------
1201 void wxTextCtrl::SetInsertionPointEnd()
1203 // we must not do anything if the caret is already there because calling
1204 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1205 // if it doesn't actually move the caret anywhere and so the simple fact of
1206 // doing it results in horrible flicker when appending big amounts of text
1207 // to the control in a few chunks (see DoAddText() test in the text sample)
1208 const wxTextPos lastPosition
= GetLastPosition();
1209 if ( GetInsertionPoint() == lastPosition
)
1214 SetInsertionPoint(lastPosition
);
1217 long wxTextCtrl::GetInsertionPoint() const
1225 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &range
);
1228 #endif // wxUSE_RICHEDIT
1230 return wxTextEntry::GetInsertionPoint();
1233 wxTextPos
wxTextCtrl::GetLastPosition() const
1235 if ( IsMultiLine() )
1237 int numLines
= GetNumberOfLines();
1238 long posStartLastLine
= XYToPosition(0, numLines
- 1);
1240 long lenLastLine
= GetLengthOfLineContainingPos(posStartLastLine
);
1242 return posStartLastLine
+ lenLastLine
;
1245 return wxTextEntry::GetLastPosition();
1248 // If the return values from and to are the same, there is no
1250 void wxTextCtrl::GetSelection(long *from
, long *to
) const
1255 CHARRANGE charRange
;
1256 ::SendMessage(GetHwnd(), EM_EXGETSEL
, 0, (LPARAM
) &charRange
);
1258 *from
= charRange
.cpMin
;
1259 *to
= charRange
.cpMax
;
1262 #endif // !wxUSE_RICHEDIT
1264 wxTextEntry::GetSelection(from
, to
);
1268 // ----------------------------------------------------------------------------
1270 // ----------------------------------------------------------------------------
1272 void wxTextCtrl::DoSetSelection(long from
, long to
, int flags
)
1274 HWND hWnd
= GetHwnd();
1279 // if from and to are both -1, it means (in wxWidgets) that all text
1280 // should be selected, translate this into Windows convention
1281 if ( (from
== -1) && (to
== -1) )
1289 ::SendMessage(hWnd
, EM_EXSETSEL
, 0, (LPARAM
)&range
);
1292 #endif // wxUSE_RICHEDIT
1294 wxTextEntry::DoSetSelection(from
, to
, flags
);
1297 if ( (flags
& SetSel_Scroll
) && !IsFrozen() )
1300 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1301 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1302 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1303 // option is set (but it does work ok in richedit 1.0 mode...)
1305 // so to make it work we either need to give focus to it here which
1306 // will probably create many problems (dummy focus events; window
1307 // containing the text control being brought to foreground
1308 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1309 // create other problems too -- and in fact it does because if we turn
1310 // on/off this style while appending the text to the control, the
1311 // vertical scrollbar never appears in it even if we append tons of
1312 // text and to work around this the only solution I found was to use
1313 // ES_DISABLENOSCROLL
1315 // this is very ugly but I don't see any other way to make this work
1317 if ( GetRichVersion() > 1 )
1319 if ( !HasFlag(wxTE_NOHIDESEL
) )
1321 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1322 // others, remember the style so we can reset it later if needed
1323 style
= ::GetWindowLong(GetHwnd(), GWL_STYLE
);
1324 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1325 ECOOP_OR
, ECO_NOHIDESEL
);
1327 //else: everything is already ok
1329 #endif // wxUSE_RICHEDIT
1331 ::SendMessage(hWnd
, EM_SCROLLCARET
, 0, (LPARAM
)0);
1334 // restore ECO_NOHIDESEL if we changed it
1335 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL
) )
1337 ::SendMessage(GetHwnd(), EM_SETOPTIONS
,
1338 ECOOP_AND
, ~ECO_NOHIDESEL
);
1339 if ( style
!= ::GetWindowLong(GetHwnd(), GWL_STYLE
) )
1340 ::SetWindowLong(GetHwnd(), GWL_STYLE
, style
);
1342 #endif // wxUSE_RICHEDIT
1346 // ----------------------------------------------------------------------------
1347 // Working with files
1348 // ----------------------------------------------------------------------------
1350 bool wxTextCtrl::DoLoadFile(const wxString
& file
, int fileType
)
1352 if ( wxTextCtrlBase::DoLoadFile(file
, fileType
) )
1354 // update the size limit if needed
1363 // ----------------------------------------------------------------------------
1365 // ----------------------------------------------------------------------------
1367 bool wxTextCtrl::IsModified() const
1369 return ::SendMessage(GetHwnd(), EM_GETMODIFY
, 0, 0) != 0;
1372 void wxTextCtrl::MarkDirty()
1374 ::SendMessage(GetHwnd(), EM_SETMODIFY
, TRUE
, 0);
1377 void wxTextCtrl::DiscardEdits()
1379 ::SendMessage(GetHwnd(), EM_SETMODIFY
, FALSE
, 0);
1382 // ----------------------------------------------------------------------------
1383 // Positions <-> coords
1384 // ----------------------------------------------------------------------------
1386 int wxTextCtrl::GetNumberOfLines() const
1388 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT
, 0, 0);
1391 long wxTextCtrl::XYToPosition(long x
, long y
) const
1393 // This gets the char index for the _beginning_ of this line
1394 long charIndex
= ::SendMessage(GetHwnd(), EM_LINEINDEX
, y
, 0);
1396 return charIndex
+ x
;
1399 bool wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
1401 HWND hWnd
= GetHwnd();
1403 // This gets the line number containing the character
1408 lineNo
= ::SendMessage(hWnd
, EM_EXLINEFROMCHAR
, 0, pos
);
1411 #endif // wxUSE_RICHEDIT
1413 lineNo
= ::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1422 // This gets the char index for the _beginning_ of this line
1423 long charIndex
= ::SendMessage(hWnd
, EM_LINEINDEX
, lineNo
, 0);
1424 if ( charIndex
== -1 )
1429 // The X position must therefore be the different between pos and charIndex
1431 *x
= pos
- charIndex
;
1438 wxTextCtrlHitTestResult
1439 wxTextCtrl::HitTest(const wxPoint
& pt
, long *posOut
) const
1441 // first get the position from Windows
1448 // for rich edit controls the position is passed iva the struct fields
1451 lParam
= (LPARAM
)&ptl
;
1454 #endif // wxUSE_RICHEDIT
1456 // for the plain ones, we are limited to 16 bit positions which are
1457 // combined in a single 32 bit value
1458 lParam
= MAKELPARAM(pt
.x
, pt
.y
);
1461 LRESULT pos
= ::SendMessage(GetHwnd(), EM_CHARFROMPOS
, 0, lParam
);
1465 // this seems to indicate an error...
1466 return wxTE_HT_UNKNOWN
;
1471 #endif // wxUSE_RICHEDIT
1473 // for plain EDIT controls the higher word contains something else
1478 // next determine where it is relatively to our point: EM_CHARFROMPOS
1479 // always returns the closest character but we need to be more precise, so
1480 // double check that we really are where it pretends
1484 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1485 // we don't know how to do it
1488 ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&ptReal
, pos
);
1491 #endif // wxUSE_RICHEDIT
1493 LRESULT lRc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1497 // this is apparently returned when pos corresponds to the last
1504 ptReal
.x
= LOWORD(lRc
);
1505 ptReal
.y
= HIWORD(lRc
);
1509 wxTextCtrlHitTestResult rc
;
1511 if ( pt
.y
> ptReal
.y
+ GetCharHeight() )
1513 else if ( pt
.x
> ptReal
.x
+ GetCharWidth() )
1514 rc
= wxTE_HT_BEYOND
;
1516 rc
= wxTE_HT_ON_TEXT
;
1524 wxPoint
wxTextCtrl::DoPositionToCoords(long pos
) const
1526 // FIXME: This code is broken for rich edit version 2.0 as it uses the same
1527 // API as plain edit i.e. the coordinates are returned directly instead of
1528 // filling the POINT passed as WPARAM with them but we can't distinguish
1529 // between 2.0 and 3.0 unfortunately (see also the use of EM_POSFROMCHAR
1535 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, (WPARAM
)&pt
, pos
);
1537 return wxPoint(pt
.x
, pt
.y
);
1540 #endif // wxUSE_RICHEDIT
1542 LRESULT rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
, 0);
1545 // Finding coordinates for the last position of the control fails
1546 // in plain EDIT control, try to compensate for it by finding it
1547 // ourselves from the position of the previous character.
1548 if ( pos
< GetLastPosition() )
1550 // It's not the expected correctable failure case so just fail.
1551 return wxDefaultPosition
;
1556 // We're being asked the coordinates of the first (and last and
1557 // only) position in an empty control. There is no way to get
1558 // it directly with EM_POSFROMCHAR but EM_GETMARGINS returns
1559 // the correct value for at least the horizontal offset.
1560 rc
= ::SendMessage(GetHwnd(), EM_GETMARGINS
, 0, 0);
1562 // Text control seems to effectively add 1 to margin.
1563 return wxPoint(LOWORD(rc
) + 1, 1);
1566 // We do have a previous character, try to get its coordinates.
1567 rc
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, pos
- 1, 0);
1570 // If getting coordinates of the previous character failed as
1571 // well, just give up.
1572 return wxDefaultPosition
;
1575 wxString prevChar
= GetRange(pos
- 1, pos
);
1576 wxSize prevCharSize
= GetTextExtent(prevChar
);
1578 if ( prevChar
== wxT("\n" ))
1580 // 'pos' is at the beginning of a new line so its X coordinate
1581 // should be the same as X coordinate of the first character of
1582 // any other line while its Y coordinate will be approximately
1583 // (but we can't compute it exactly...) one character height
1584 // more than that of the previous character.
1585 LRESULT coords0
= ::SendMessage(GetHwnd(), EM_POSFROMCHAR
, 0, 0);
1586 if ( coords0
== -1 )
1587 return wxDefaultPosition
;
1589 rc
= MAKELPARAM(LOWORD(coords0
), HIWORD(rc
) + prevCharSize
.y
);
1593 // Simple case: previous character is in the same line so this
1594 // one is just after it.
1595 rc
+= MAKELPARAM(prevCharSize
.x
, 0);
1599 // Notice that {LO,HI}WORD macros return WORDs, i.e. unsigned shorts,
1600 // while we want to have signed values here (the y coordinate of any
1601 // position above the first currently visible line is negative, for
1602 // example), hence the need for casts.
1603 return wxPoint(static_cast<short>(LOWORD(rc
)),
1604 static_cast<short>(HIWORD(rc
)));
1607 return wxDefaultPosition
;
1611 // ----------------------------------------------------------------------------
1613 // ----------------------------------------------------------------------------
1615 void wxTextCtrl::ShowPosition(long pos
)
1617 HWND hWnd
= GetHwnd();
1619 // To scroll to a position, we pass the number of lines and characters
1620 // to scroll *by*. This means that we need to:
1621 // (1) Find the line position of the current line.
1622 // (2) Find the line position of pos.
1623 // (3) Scroll by (pos - current).
1624 // For now, ignore the horizontal scrolling.
1626 // Is this where scrolling is relative to - the line containing the caret?
1627 // Or is the first visible line??? Try first visible line.
1628 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, -1, 0L);
1630 int currentLineLineNo
= (int)::SendMessage(hWnd
, EM_GETFIRSTVISIBLELINE
, 0, 0);
1632 int specifiedLineLineNo
= (int)::SendMessage(hWnd
, EM_LINEFROMCHAR
, pos
, 0);
1634 int linesToScroll
= specifiedLineLineNo
- currentLineLineNo
;
1636 if (linesToScroll
!= 0)
1637 ::SendMessage(hWnd
, EM_LINESCROLL
, 0, linesToScroll
);
1640 long wxTextCtrl::GetLengthOfLineContainingPos(long pos
) const
1642 return ::SendMessage(GetHwnd(), EM_LINELENGTH
, pos
, 0);
1645 int wxTextCtrl::GetLineLength(long lineNo
) const
1647 long pos
= XYToPosition(0, lineNo
);
1649 return GetLengthOfLineContainingPos(pos
);
1652 wxString
wxTextCtrl::GetLineText(long lineNo
) const
1654 size_t len
= (size_t)GetLineLength(lineNo
) + 1;
1656 // there must be at least enough place for the length WORD in the
1658 len
+= sizeof(WORD
);
1662 wxStringBufferLength
tmp(str
, len
);
1665 *(WORD
*)buf
= (WORD
)len
;
1666 len
= (size_t)::SendMessage(GetHwnd(), EM_GETLINE
, lineNo
, (LPARAM
)buf
);
1671 // remove the '\r' returned by the rich edit control, the user code
1672 // should never see it
1673 if ( buf
[len
- 2] == wxT('\r') && buf
[len
- 1] == wxT('\n') )
1675 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1676 // here and "\n" below
1677 buf
[len
- 2] = wxT('\n');
1680 else if ( buf
[len
- 1] == wxT('\r') )
1682 // richedit 2.0+ uses only "\r", replace it with "\n"
1683 buf
[len
- 1] = wxT('\n');
1686 #endif // wxUSE_RICHEDIT
1688 // remove the '\n' at the end, if any (this is how this function is
1689 // supposed to work according to the docs)
1690 if ( buf
[len
- 1] == wxT('\n') )
1702 void wxTextCtrl::SetMaxLength(unsigned long len
)
1707 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT
, 0, len
? len
: 0x7fffffff);
1710 #endif // wxUSE_RICHEDIT
1712 wxTextEntry::SetMaxLength(len
);
1716 // ----------------------------------------------------------------------------
1718 // ----------------------------------------------------------------------------
1720 void wxTextCtrl::Redo()
1723 if ( GetRichVersion() > 1 )
1725 ::SendMessage(GetHwnd(), EM_REDO
, 0, 0);
1728 #endif // wxUSE_RICHEDIT
1730 wxTextEntry::Redo();
1733 bool wxTextCtrl::CanRedo() const
1736 if ( GetRichVersion() > 1 )
1737 return ::SendMessage(GetHwnd(), EM_CANREDO
, 0, 0) != 0;
1738 #endif // wxUSE_RICHEDIT
1740 return wxTextEntry::CanRedo();
1743 // ----------------------------------------------------------------------------
1744 // caret handling (Windows only)
1745 // ----------------------------------------------------------------------------
1747 bool wxTextCtrl::ShowNativeCaret(bool show
)
1749 if ( show
!= m_isNativeCaretShown
)
1751 if ( !(show
? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1753 // not an error, may simply indicate that it's not shown/hidden
1754 // yet (i.e. it had been hidden/shown 2 times before)
1758 m_isNativeCaretShown
= show
;
1764 // ----------------------------------------------------------------------------
1765 // implementation details
1766 // ----------------------------------------------------------------------------
1768 void wxTextCtrl::Command(wxCommandEvent
& event
)
1770 SetValue(event
.GetString());
1771 ProcessCommand (event
);
1774 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
1776 // By default, load the first file into the text window.
1777 if (event
.GetNumberOfFiles() > 0)
1779 LoadFile(event
.GetFiles()[0]);
1783 // ----------------------------------------------------------------------------
1784 // kbd input processing
1785 // ----------------------------------------------------------------------------
1787 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG
* msg
)
1789 // check for our special keys here: if we don't do it and the parent frame
1790 // uses them as accelerators, they wouldn't work at all, so we disable
1791 // usual preprocessing for them
1792 if ( msg
->message
== WM_KEYDOWN
)
1794 const WPARAM vkey
= msg
->wParam
;
1795 if ( HIWORD(msg
->lParam
) & KF_ALTDOWN
)
1797 // Alt-Backspace is accelerator for "Undo"
1798 if ( vkey
== VK_BACK
)
1803 // we want to process some Ctrl-foo and Shift-bar but no key
1804 // combinations without either Ctrl or Shift nor with both of them
1806 const int ctrl
= wxIsCtrlDown(),
1807 shift
= wxIsShiftDown();
1808 switch ( ctrl
+ shift
)
1811 wxFAIL_MSG( wxT("how many modifiers have we got?") );
1818 // This one is only special for multi line controls.
1819 if ( !IsMultiLine() )
1833 // either Ctrl or Shift pressed
1848 else // Shift is pressed
1850 if ( vkey
== VK_INSERT
|| vkey
== VK_DELETE
)
1857 return wxControl::MSWShouldPreProcessMessage(msg
);
1860 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
1862 switch ( event
.GetKeyCode() )
1866 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
, m_windowId
);
1867 InitCommandEvent(event
);
1868 event
.SetString(GetValue());
1869 if ( HandleWindowEvent(event
) )
1870 if ( !HasFlag(wxTE_MULTILINE
) )
1872 //else: multiline controls need Enter for themselves
1877 // ok, so this is getting absolutely ridiculous but I don't see
1878 // any other way to fix this bug: when a multiline text control is
1879 // inside a wxFrame, we need to generate the navigation event as
1880 // otherwise nothing happens at all, but when the same control is
1881 // created inside a dialog, IsDialogMessage() *does* switch focus
1882 // all by itself and so if we do it here as well, it is advanced
1883 // twice and goes to the next control... to prevent this from
1884 // happening we're doing this ugly check, the logic being that if
1885 // we don't have focus then it had been already changed to the next
1888 // the right thing to do would, of course, be to understand what
1889 // the hell is IsDialogMessage() doing but this is beyond my feeble
1890 // forces at the moment unfortunately
1891 if ( !(m_windowStyle
& wxTE_PROCESS_TAB
))
1893 if ( FindFocus() == this )
1896 if (!event
.ShiftDown())
1897 flags
|= wxNavigationKeyEvent::IsForward
;
1898 if (event
.ControlDown())
1899 flags
|= wxNavigationKeyEvent::WinChange
;
1900 if (Navigate(flags
))
1906 // Insert tab since calling the default Windows handler
1907 // doesn't seem to do it
1908 WriteText(wxT("\t"));
1914 // no, we didn't process it
1918 void wxTextCtrl::OnKeyDown(wxKeyEvent
& event
)
1920 // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages
1921 // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent
1922 // from working. So we work around it by intercepting these shortcuts
1923 // ourselves and emitting clipboard events (which richedit will handle,
1924 // so everything works as before, including pasting of rich text):
1925 if ( event
.GetModifiers() == wxMOD_CONTROL
&& IsRich() )
1927 switch ( event
.GetKeyCode() )
1943 // Default window procedure of multiline edit controls posts WM_CLOSE to
1944 // the parent window when it gets Escape key press for some reason, prevent
1945 // it from doing this as this resulted in dialog boxes being closed on
1946 // Escape even when they shouldn't be (we do handle Escape ourselves
1947 // correctly in the situations when it should close them).
1948 if ( event
.GetKeyCode() == WXK_ESCAPE
&& IsMultiLine() )
1951 // no, we didn't process it
1955 WXLRESULT
wxTextCtrl::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
1957 WXLRESULT lRc
= wxTextCtrlBase::MSWWindowProc(nMsg
, wParam
, lParam
);
1963 // we always want the chars and the arrows: the arrows for
1964 // navigation and the chars because we want Ctrl-C to work even
1965 // in a read only control
1966 long lDlgCode
= DLGC_WANTCHARS
| DLGC_WANTARROWS
;
1970 // we may have several different cases:
1971 // 1. normal: both TAB and ENTER are used for navigation
1972 // 2. ctrl wants TAB for itself: ENTER is used to pass to
1973 // the next control in the dialog
1974 // 3. ctrl wants ENTER for itself: TAB is used for dialog
1976 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
1977 // go to the next control (we need some way to do it)
1979 // multiline controls should always get ENTER for themselves
1980 if ( HasFlag(wxTE_PROCESS_ENTER
) || HasFlag(wxTE_MULTILINE
) )
1981 lDlgCode
|= DLGC_WANTMESSAGE
;
1983 if ( HasFlag(wxTE_PROCESS_TAB
) )
1984 lDlgCode
|= DLGC_WANTTAB
;
1990 // NB: use "=", not "|=" as the base class version returns
1991 // the same flags in the disabled state as usual (i.e.
1992 // including DLGC_WANTMESSAGE). This is strange (how
1993 // does it work in the native Win32 apps?) but for now
1998 // Clear the DLGC_HASSETSEL bit from the return value
1999 lRc
&= ~DLGC_HASSETSEL
;
2005 // rich text controls seem to have a bug and don't change the
2006 // cursor to the standard arrow one from the I-beam cursor usually
2007 // used by them even when a popup menu is shown (this works fine
2008 // for plain EDIT controls though), so explicitly work around this
2011 extern wxMenu
*wxCurrentPopupMenu
;
2012 if ( wxCurrentPopupMenu
&&
2013 wxCurrentPopupMenu
->GetInvokingWindow() == this )
2014 ::SetCursor(GetHcursorOf(*wxSTANDARD_CURSOR
));
2016 #endif // wxUSE_MENUS
2022 // ----------------------------------------------------------------------------
2023 // text control event processing
2024 // ----------------------------------------------------------------------------
2026 bool wxTextCtrl::SendUpdateEvent()
2028 switch ( m_updatesCount
)
2031 // remember that we've got an update
2036 // we had already sent one event since the last control modification
2040 wxFAIL_MSG( wxT("unexpected wxTextCtrl::m_updatesCount value") );
2044 // we hadn't updated the control ourselves, this event comes from
2045 // the user, don't need to ignore it nor update the count
2049 // the control was updated programmatically and we do NOT want to
2054 return SendTextUpdatedEvent();
2057 bool wxTextCtrl::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
2066 // the text size limit has been hit -- try to increase it
2067 if ( !AdjustSpaceLimit() )
2069 wxCommandEvent
event(wxEVT_COMMAND_TEXT_MAXLEN
, m_windowId
);
2070 InitCommandEvent(event
);
2071 event
.SetString(GetValue());
2072 ProcessCommand(event
);
2076 // the other edit notification messages are not processed (or, in
2077 // the case of EN_{SET/KILL}FOCUS were already handled at WM_SET/
2087 WXHBRUSH
wxTextCtrl::MSWControlColor(WXHDC hDC
, WXHWND hWnd
)
2089 if ( !IsThisEnabled() && !HasFlag(wxTE_MULTILINE
) )
2090 return MSWControlColorDisabled(hDC
);
2092 return wxTextCtrlBase::MSWControlColor(hDC
, hWnd
);
2095 bool wxTextCtrl::HasSpaceLimit(unsigned int *len
) const
2097 // HACK: we try to automatically extend the limit for the amount of text
2098 // to allow (interactively) entering more than 64Kb of text under
2099 // Win9x but we shouldn't reset the text limit which was previously
2100 // set explicitly with SetMaxLength()
2102 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2103 // know the limit we set (if any). We could solve this by storing the
2104 // limit we set in wxTextCtrl but to save space we prefer to simply
2105 // test here the actual limit value: we consider that SetMaxLength()
2106 // can only be called for small values while EN_MAXTEXT is only sent
2107 // for large values (in practice the default limit seems to be 30000
2108 // but make it smaller just to be on the safe side)
2109 *len
= ::SendMessage(GetHwnd(), EM_GETLIMITTEXT
, 0, 0);
2110 return *len
< 10001;
2114 bool wxTextCtrl::AdjustSpaceLimit()
2117 if ( HasSpaceLimit(&limit
) )
2120 unsigned int len
= ::GetWindowTextLength(GetHwnd());
2123 // increment in 32Kb chunks
2124 SetMaxLength(len
+ 0x8000);
2127 // we changed the limit
2131 bool wxTextCtrl::AcceptsFocusFromKeyboard() const
2133 // we don't want focus if we can't be edited unless we're a multiline
2134 // control because then it might be still nice to get focus from keyboard
2135 // to be able to scroll it without mouse
2136 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2139 wxSize
wxTextCtrl::DoGetBestSize() const
2141 return DoGetSizeFromTextSize( DEFAULT_ITEM_WIDTH
);
2144 wxSize
wxTextCtrl::DoGetSizeFromTextSize(int xlen
, int ylen
) const
2147 wxGetCharSize(GetHWND(), &cx
, &cy
, GetFont());
2150 ::SystemParametersInfo(SPI_GETCARETWIDTH
, 0, &wText
, 0);
2154 if ( m_windowStyle
& wxTE_MULTILINE
)
2156 // add space for vertical scrollbar
2157 if ( !(m_windowStyle
& wxTE_NO_VSCROLL
) )
2158 wText
+= ::GetSystemMetrics(SM_CXVSCROLL
);
2162 hText
*= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2163 // add space for horizontal scrollbar
2164 if ( m_windowStyle
& wxHSCROLL
)
2165 hText
+= ::GetSystemMetrics(SM_CYHSCROLL
);
2168 // for single line control cy (height + external leading) is ok
2171 // Add the margins we have previously set
2172 wxPoint
marg( GetMargins() );
2173 wText
+= wxMax(0, marg
.x
);
2174 hText
+= wxMax(0, marg
.y
);
2177 // Text controls without border are special and have the same height as
2178 // static labels (they also have the same appearance when they're disable
2179 // and are often used as a sort of copyable to the clipboard label so it's
2180 // important that they have the same height as the normal labels to not
2182 if ( !HasFlag(wxBORDER_NONE
) )
2184 wText
+= 9; // borders and inner margins
2186 // we have to add the adjustments for the control height only once, not
2187 // once per line, so do it after multiplication above
2188 hText
+= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
) - cy
;
2191 // Perhaps the user wants something different from CharHeight, or ylen
2192 // is used as the height of a multiline text.
2194 hText
+= ylen
- GetCharHeight();
2196 return wxSize(wText
, hText
);
2199 // ----------------------------------------------------------------------------
2200 // standard handlers for standard edit menu events
2201 // ----------------------------------------------------------------------------
2203 void wxTextCtrl::OnCut(wxCommandEvent
& WXUNUSED(event
))
2208 void wxTextCtrl::OnCopy(wxCommandEvent
& WXUNUSED(event
))
2213 void wxTextCtrl::OnPaste(wxCommandEvent
& WXUNUSED(event
))
2218 void wxTextCtrl::OnUndo(wxCommandEvent
& WXUNUSED(event
))
2223 void wxTextCtrl::OnRedo(wxCommandEvent
& WXUNUSED(event
))
2228 void wxTextCtrl::OnDelete(wxCommandEvent
& WXUNUSED(event
))
2233 void wxTextCtrl::OnSelectAll(wxCommandEvent
& WXUNUSED(event
))
2238 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent
& event
)
2240 event
.Enable( CanCut() );
2243 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent
& event
)
2245 event
.Enable( CanCopy() );
2248 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent
& event
)
2250 event
.Enable( CanPaste() );
2253 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent
& event
)
2255 event
.Enable( CanUndo() );
2258 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent
& event
)
2260 event
.Enable( CanRedo() );
2263 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent
& event
)
2265 event
.Enable( HasSelection() && IsEditable() );
2268 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent
& event
)
2270 event
.Enable( !IsEmpty() );
2273 void wxTextCtrl::OnContextMenu(wxContextMenuEvent
& event
)
2278 if (!m_privateContextMenu
)
2280 m_privateContextMenu
= new wxMenu
;
2281 m_privateContextMenu
->Append(wxID_UNDO
, _("&Undo"));
2282 m_privateContextMenu
->Append(wxID_REDO
, _("&Redo"));
2283 m_privateContextMenu
->AppendSeparator();
2284 m_privateContextMenu
->Append(wxID_CUT
, _("Cu&t"));
2285 m_privateContextMenu
->Append(wxID_COPY
, _("&Copy"));
2286 m_privateContextMenu
->Append(wxID_PASTE
, _("&Paste"));
2287 m_privateContextMenu
->Append(wxID_CLEAR
, _("&Delete"));
2288 m_privateContextMenu
->AppendSeparator();
2289 m_privateContextMenu
->Append(wxID_SELECTALL
, _("Select &All"));
2291 PopupMenu(m_privateContextMenu
);
2299 void wxTextCtrl::OnSetFocus(wxFocusEvent
& event
)
2301 // be sure the caret remains invisible if the user had hidden it
2302 if ( !m_isNativeCaretShown
)
2304 ::HideCaret(GetHwnd());
2310 // the rest of the file only deals with the rich edit controls
2313 // ----------------------------------------------------------------------------
2314 // EN_LINK processing
2315 // ----------------------------------------------------------------------------
2317 bool wxTextCtrl::MSWOnNotify(int idCtrl
, WXLPARAM lParam
, WXLPARAM
*result
)
2319 NMHDR
*hdr
= (NMHDR
* )lParam
;
2320 switch ( hdr
->code
)
2324 const MSGFILTER
*msgf
= (MSGFILTER
*)lParam
;
2325 UINT msg
= msgf
->msg
;
2327 // this is a bit crazy but richedit 1.0 sends us all mouse
2328 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2329 // generate the wxWin events for this message manually
2331 // NB: in fact, this is still not totally correct as it does
2332 // send us WM_LBUTTONUP if the selection was cleared by the
2333 // last click -- so currently we get 2 events in this case,
2334 // but as I don't see any obvious way to check for this I
2335 // leave this code in place because it's still better than
2336 // not getting left up events at all
2337 if ( msg
== WM_LBUTTONUP
)
2339 WXUINT flags
= msgf
->wParam
;
2340 int x
= GET_X_LPARAM(msgf
->lParam
),
2341 y
= GET_Y_LPARAM(msgf
->lParam
);
2343 HandleMouseEvent(msg
, x
, y
, flags
);
2347 // return true to process the event (and false to ignore it)
2352 const ENLINK
*enlink
= (ENLINK
*)hdr
;
2354 switch ( enlink
->msg
)
2357 // ok, so it is hardcoded - do we really nee to
2360 wxCursor
cur(wxCURSOR_HAND
);
2361 ::SetCursor(GetHcursorOf(cur
));
2367 case WM_LBUTTONDOWN
:
2369 case WM_LBUTTONDBLCLK
:
2370 case WM_RBUTTONDOWN
:
2372 case WM_RBUTTONDBLCLK
:
2373 // send a mouse event
2375 static const wxEventType eventsMouse
[] =
2386 // the event ids are consecutive
2388 evtMouse(eventsMouse
[enlink
->msg
- WM_MOUSEMOVE
]);
2390 InitMouseEvent(evtMouse
,
2391 GET_X_LPARAM(enlink
->lParam
),
2392 GET_Y_LPARAM(enlink
->lParam
),
2395 wxTextUrlEvent
event(m_windowId
, evtMouse
,
2397 enlink
->chrg
.cpMax
);
2399 InitCommandEvent(event
);
2401 *result
= ProcessCommand(event
);
2409 // not processed, leave it to the base class
2410 return wxTextCtrlBase::MSWOnNotify(idCtrl
, lParam
, result
);
2413 #if wxUSE_DRAG_AND_DROP
2415 void wxTextCtrl::SetDropTarget(wxDropTarget
*dropTarget
)
2417 if ( m_dropTarget
== wxRICHTEXT_DEFAULT_DROPTARGET
)
2419 // get rid of the built-in drop target
2420 ::RevokeDragDrop(GetHwnd());
2421 m_dropTarget
= NULL
;
2424 wxTextCtrlBase::SetDropTarget(dropTarget
);
2427 #endif // wxUSE_DRAG_AND_DROP
2429 // ----------------------------------------------------------------------------
2430 // colour setting for the rich edit controls
2431 // ----------------------------------------------------------------------------
2433 bool wxTextCtrl::SetBackgroundColour(const wxColour
& colour
)
2435 if ( !wxTextCtrlBase::SetBackgroundColour(colour
) )
2437 // colour didn't really change
2443 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2444 // EM_SETBKGNDCOLOR additionally
2445 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR
, 0, wxColourToRGB(colour
));
2451 bool wxTextCtrl::SetForegroundColour(const wxColour
& colour
)
2453 if ( !wxTextCtrlBase::SetForegroundColour(colour
) )
2455 // colour didn't really change
2461 // change the colour of everything
2462 WinStruct
<CHARFORMAT
> cf
;
2463 cf
.dwMask
= CFM_COLOR
;
2464 cf
.crTextColor
= wxColourToRGB(colour
);
2465 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, SCF_ALL
, (LPARAM
)&cf
);
2471 bool wxTextCtrl::SetFont(const wxFont
& font
)
2473 if ( !wxTextCtrlBase::SetFont(font
) )
2476 if ( GetRichVersion() >= 4 )
2478 // Using WM_SETFONT is not enough with RichEdit 4.1: it does work but
2479 // for ASCII characters only and inserting a non-ASCII one into it
2480 // later reverts to the default font so use EM_SETCHARFORMAT to change
2481 // the default font for it.
2484 SetStyle(-1, -1, attr
);
2490 // ----------------------------------------------------------------------------
2491 // styling support for rich edit controls
2492 // ----------------------------------------------------------------------------
2494 bool wxTextCtrl::MSWSetCharFormat(const wxTextAttr
& style
, long start
, long end
)
2496 // initialize CHARFORMAT struct
2505 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2506 // CHARFORMAT in that case
2508 if ( m_verRichEdit
== 1 )
2510 // this is the only thing the control is going to grok
2511 cf
.cbSize
= sizeof(CHARFORMAT
);
2516 // CHARFORMAT or CHARFORMAT2
2517 cf
.cbSize
= sizeof(cf
);
2520 if ( style
.HasFont() )
2522 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2523 // but using it doesn't seem to hurt neither so leaving it for now
2525 cf
.dwMask
|= CFM_FACE
| CFM_SIZE
| CFM_CHARSET
|
2526 CFM_ITALIC
| CFM_BOLD
| CFM_UNDERLINE
;
2528 // fill in data from LOGFONT but recalculate lfHeight because we need
2529 // the real height in twips and not the negative number which
2530 // wxFillLogFont() returns (this is correct in general and works with
2531 // the Windows font mapper, but not here)
2533 wxFont
font(style
.GetFont());
2536 wxFillLogFont(&lf
, &font
);
2537 cf
.yHeight
= 20*font
.GetPointSize(); // 1 pt = 20 twips
2538 cf
.bCharSet
= lf
.lfCharSet
;
2539 cf
.bPitchAndFamily
= lf
.lfPitchAndFamily
;
2540 wxStrlcpy(cf
.szFaceName
, lf
.lfFaceName
, WXSIZEOF(cf
.szFaceName
));
2542 // also deal with underline/italic/bold attributes: note that we must
2543 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2544 // style to allow clearing it
2547 cf
.dwEffects
|= CFE_ITALIC
;
2550 if ( lf
.lfWeight
== FW_BOLD
)
2552 cf
.dwEffects
|= CFE_BOLD
;
2555 if ( lf
.lfUnderline
)
2557 cf
.dwEffects
|= CFE_UNDERLINE
;
2560 // strikeout fonts are not supported by wxWidgets
2563 if ( style
.HasTextColour() )
2565 cf
.dwMask
|= CFM_COLOR
;
2566 cf
.crTextColor
= wxColourToRGB(style
.GetTextColour());
2570 if ( m_verRichEdit
!= 1 && style
.HasBackgroundColour() )
2572 cf
.dwMask
|= CFM_BACKCOLOR
;
2573 cf
.crBackColor
= wxColourToRGB(style
.GetBackgroundColour());
2575 #endif // wxUSE_RICHEDIT2
2577 // Apply the style either to the selection or to the entire control.
2579 if ( start
!= -1 || end
!= -1 )
2581 DoSetSelection(start
, end
, SetSel_NoScroll
);
2582 selMode
= SCF_SELECTION
;
2589 if ( !::SendMessage(GetHwnd(), EM_SETCHARFORMAT
, selMode
, (LPARAM
)&cf
) )
2591 wxLogLastError(wxT("SendMessage(EM_SETCHARFORMAT)"));
2598 bool wxTextCtrl::MSWSetParaFormat(const wxTextAttr
& style
, long start
, long end
)
2608 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2609 // PARAFORMAT in that case
2611 if ( m_verRichEdit
== 1 )
2613 // this is the only thing the control is going to grok
2614 pf
.cbSize
= sizeof(PARAFORMAT
);
2619 // PARAFORMAT or PARAFORMAT2
2620 pf
.cbSize
= sizeof(pf
);
2623 if (style
.HasAlignment())
2625 pf
.dwMask
|= PFM_ALIGNMENT
;
2626 if (style
.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT
)
2627 pf
.wAlignment
= PFA_RIGHT
;
2628 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE
)
2629 pf
.wAlignment
= PFA_CENTER
;
2630 else if (style
.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED
)
2631 pf
.wAlignment
= PFA_JUSTIFY
;
2633 pf
.wAlignment
= PFA_LEFT
;
2636 if (style
.HasLeftIndent())
2638 pf
.dwMask
|= PFM_STARTINDENT
| PFM_OFFSET
;
2640 // Convert from 1/10 mm to TWIPS
2641 pf
.dxStartIndent
= (int) (((double) style
.GetLeftIndent()) * mm2twips
/ 10.0) ;
2642 pf
.dxOffset
= (int) (((double) style
.GetLeftSubIndent()) * mm2twips
/ 10.0) ;
2645 if (style
.HasRightIndent())
2647 pf
.dwMask
|= PFM_RIGHTINDENT
;
2649 // Convert from 1/10 mm to TWIPS
2650 pf
.dxRightIndent
= (int) (((double) style
.GetRightIndent()) * mm2twips
/ 10.0) ;
2653 if (style
.HasTabs())
2655 pf
.dwMask
|= PFM_TABSTOPS
;
2657 const wxArrayInt
& tabs
= style
.GetTabs();
2659 pf
.cTabCount
= (SHORT
)wxMin(tabs
.GetCount(), MAX_TAB_STOPS
);
2661 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2663 // Convert from 1/10 mm to TWIPS
2664 pf
.rgxTabs
[i
] = (int) (((double) tabs
[i
]) * mm2twips
/ 10.0) ;
2669 if ( m_verRichEdit
> 1 )
2671 if ( wxTheApp
->GetLayoutDirection() == wxLayout_RightToLeft
)
2673 // Use RTL paragraphs in RTL mode to get proper layout
2674 pf
.dwMask
|= PFM_RTLPARA
;
2675 pf
.wEffects
|= PFE_RTLPARA
;
2678 #endif // wxUSE_RICHEDIT2
2682 // Do format the selection.
2683 DoSetSelection(start
, end
, SetSel_NoScroll
);
2685 if ( !::SendMessage(GetHwnd(), EM_SETPARAFORMAT
, 0, (LPARAM
) &pf
) )
2687 wxLogLastError(wxT("SendMessage(EM_SETPARAFORMAT)"));
2696 bool wxTextCtrl::SetStyle(long start
, long end
, const wxTextAttr
& style
)
2700 // can't do it with normal text control
2704 // the richedit 1.0 doesn't handle setting background colour, so don't
2705 // even try to do anything if it's the only thing we want to change
2706 if ( m_verRichEdit
== 1 && !style
.HasFont() && !style
.HasTextColour() &&
2707 !style
.HasLeftIndent() && !style
.HasRightIndent() && !style
.HasAlignment() &&
2710 // nothing to do: return true if there was really nothing to do and
2711 // false if we failed to set bg colour
2712 return !style
.HasBackgroundColour();
2715 // order the range if needed
2719 // we can only change the format of the selection, so select the range we
2720 // want and restore the old selection later, after MSWSetXXXFormat()
2721 // functions (possibly) change it.
2722 long startOld
, endOld
;
2723 GetSelection(&startOld
, &endOld
);
2725 bool ok
= MSWSetCharFormat(style
, start
, end
);
2726 if ( !MSWSetParaFormat(style
, start
, end
) )
2729 if ( start
!= startOld
|| end
!= endOld
)
2731 // restore the original selection
2732 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2738 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr
& style
)
2740 if ( !wxTextCtrlBase::SetDefaultStyle(style
) )
2745 // we have to do this or the style wouldn't apply for the text typed by
2747 wxTextPos posLast
= GetLastPosition();
2748 SetStyle(posLast
, posLast
, m_defaultStyle
);
2754 bool wxTextCtrl::GetStyle(long position
, wxTextAttr
& style
)
2758 // can't do it with normal text control
2762 // initialize CHARFORMAT struct
2771 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2772 // CHARFORMAT in that case
2774 if ( m_verRichEdit
== 1 )
2776 // this is the only thing the control is going to grok
2777 cf
.cbSize
= sizeof(CHARFORMAT
);
2782 // CHARFORMAT or CHARFORMAT2
2783 cf
.cbSize
= sizeof(cf
);
2785 // we can only change the format of the selection, so select the range we
2786 // want and restore the old selection later
2787 long startOld
, endOld
;
2788 GetSelection(&startOld
, &endOld
);
2790 // but do we really have to change the selection?
2791 bool changeSel
= position
!= startOld
|| position
!= endOld
;
2795 DoSetSelection(position
, position
+ 1, SetSel_NoScroll
);
2798 // get the selection formatting
2799 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT
,
2800 SCF_SELECTION
, (LPARAM
)&cf
) ;
2804 // Convert the height from the units of 1/20th of the point in which
2805 // CHARFORMAT stores it to pixel-based units used by LOGFONT.
2806 const wxCoord ppi
= wxClientDC(this).GetPPI().y
;
2807 lf
.lfHeight
= -MulDiv(cf
.yHeight
/20, ppi
, 72);
2809 lf
.lfCharSet
= ANSI_CHARSET
; // FIXME: how to get correct charset?
2810 lf
.lfClipPrecision
= 0;
2811 lf
.lfEscapement
= 0;
2812 wxStrcpy(lf
.lfFaceName
, cf
.szFaceName
);
2814 //NOTE: we _MUST_ set each of these values to _something_ since we
2815 //do not call wxZeroMemory on the LOGFONT lf
2816 if (cf
.dwEffects
& CFE_ITALIC
)
2819 lf
.lfItalic
= FALSE
;
2821 lf
.lfOrientation
= 0;
2822 lf
.lfPitchAndFamily
= cf
.bPitchAndFamily
;
2825 if (cf
.dwEffects
& CFE_STRIKEOUT
)
2826 lf
.lfStrikeOut
= TRUE
;
2828 lf
.lfStrikeOut
= FALSE
;
2830 if (cf
.dwEffects
& CFE_UNDERLINE
)
2831 lf
.lfUnderline
= TRUE
;
2833 lf
.lfUnderline
= FALSE
;
2835 if (cf
.dwEffects
& CFE_BOLD
)
2836 lf
.lfWeight
= FW_BOLD
;
2838 lf
.lfWeight
= FW_NORMAL
;
2840 wxFont font
= wxCreateFontFromLogFont(& lf
);
2843 style
.SetFont(font
);
2845 style
.SetTextColour(wxColour(cf
.crTextColor
));
2848 if ( m_verRichEdit
!= 1 )
2850 // cf.dwMask |= CFM_BACKCOLOR;
2851 style
.SetBackgroundColour(wxColour(cf
.crBackColor
));
2853 #endif // wxUSE_RICHEDIT2
2855 // now get the paragraph formatting
2858 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2859 // PARAFORMAT in that case
2861 if ( m_verRichEdit
== 1 )
2863 // this is the only thing the control is going to grok
2864 pf
.cbSize
= sizeof(PARAFORMAT
);
2869 // PARAFORMAT or PARAFORMAT2
2870 pf
.cbSize
= sizeof(pf
);
2873 // do format the selection
2874 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT
, 0, (LPARAM
) &pf
) ;
2876 style
.SetLeftIndent( (int) ((double) pf
.dxStartIndent
* twips2mm
* 10.0), (int) ((double) pf
.dxOffset
* twips2mm
* 10.0) );
2877 style
.SetRightIndent( (int) ((double) pf
.dxRightIndent
* twips2mm
* 10.0) );
2879 if (pf
.wAlignment
== PFA_CENTER
)
2880 style
.SetAlignment(wxTEXT_ALIGNMENT_CENTRE
);
2881 else if (pf
.wAlignment
== PFA_RIGHT
)
2882 style
.SetAlignment(wxTEXT_ALIGNMENT_RIGHT
);
2883 else if (pf
.wAlignment
== PFA_JUSTIFY
)
2884 style
.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED
);
2886 style
.SetAlignment(wxTEXT_ALIGNMENT_LEFT
);
2888 wxArrayInt tabStops
;
2890 for (i
= 0; i
< (size_t) pf
.cTabCount
; i
++)
2892 tabStops
.Add( (int) ((double) (pf
.rgxTabs
[i
] & 0xFFFF) * twips2mm
* 10.0) );
2897 // restore the original selection
2898 DoSetSelection(startOld
, endOld
, SetSel_NoScroll
);
2904 // ----------------------------------------------------------------------------
2906 // ----------------------------------------------------------------------------
2908 static const HINSTANCE INVALID_HINSTANCE
= (HINSTANCE
)-1;
2910 bool wxRichEditModule::OnInit()
2912 // don't do anything - we will load it when needed
2916 void wxRichEditModule::OnExit()
2918 for ( size_t i
= 0; i
< WXSIZEOF(ms_hRichEdit
); i
++ )
2920 if ( ms_hRichEdit
[i
] && ms_hRichEdit
[i
] != INVALID_HINSTANCE
)
2922 ::FreeLibrary(ms_hRichEdit
[i
]);
2923 ms_hRichEdit
[i
] = NULL
;
2927 if (ms_inkEditLib
.IsLoaded())
2928 ms_inkEditLib
.Unload();
2933 bool wxRichEditModule::Load(Version version
)
2935 if ( ms_hRichEdit
[version
] == INVALID_HINSTANCE
)
2937 // we had already tried to load it and failed
2941 if ( ms_hRichEdit
[version
] )
2943 // we've already got this one
2947 static const wxChar
*const dllnames
[] =
2954 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames
) == Version_Max
,
2955 RichEditDllNamesVersionsMismatch
);
2957 ms_hRichEdit
[version
] = ::LoadLibrary(dllnames
[version
]);
2959 if ( !ms_hRichEdit
[version
] )
2961 ms_hRichEdit
[version
] = INVALID_HINSTANCE
;
2970 // load the InkEdit library
2971 bool wxRichEditModule::LoadInkEdit()
2973 if (ms_inkEditLibLoadAttemped
)
2974 return ms_inkEditLib
.IsLoaded();
2976 ms_inkEditLibLoadAttemped
= true;
2979 return ms_inkEditLib
.Load(wxT("inked"));
2981 #endif // wxUSE_INKEDIT
2984 #endif // wxUSE_RICHEDIT
2986 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)