]> git.saurik.com Git - wxWidgets.git/blob - src/msw/textctrl.cpp
wxXmlNode::GetAttribute's pointer argument must not be NULL, check for it
[wxWidgets.git] / src / msw / textctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/textctrl.cpp
3 // Purpose: wxTextCtrl
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_TEXTCTRL && !(defined(__SMARTPHONE__) && defined(__WXWINCE__))
28
29 #ifndef WX_PRECOMP
30 #include "wx/textctrl.h"
31 #include "wx/settings.h"
32 #include "wx/brush.h"
33 #include "wx/utils.h"
34 #include "wx/intl.h"
35 #include "wx/log.h"
36 #include "wx/app.h"
37 #include "wx/menu.h"
38 #include "wx/math.h"
39 #include "wx/module.h"
40 #include "wx/wxcrtvararg.h"
41 #endif
42
43 #include "wx/sysopt.h"
44
45 #if wxUSE_CLIPBOARD
46 #include "wx/clipbrd.h"
47 #endif
48
49 #include "wx/textfile.h"
50
51 #include <windowsx.h>
52
53 #include "wx/msw/private.h"
54 #include "wx/msw/winundef.h"
55 #include "wx/msw/mslu.h"
56
57 #include <string.h>
58 #include <stdlib.h>
59
60 #ifndef __WXWINCE__
61 #include <sys/types.h>
62 #endif
63
64 #if wxUSE_RICHEDIT
65
66 #if wxUSE_INKEDIT
67 #include "wx/dynlib.h"
68 #endif
69
70 // old mingw32 has richedit stuff directly in windows.h and doesn't have
71 // richedit.h at all
72 #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__)
73 #include <richedit.h>
74 #endif
75
76 #endif // wxUSE_RICHEDIT
77
78 #include "wx/msw/missing.h"
79
80 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
81
82 // dummy value used for m_dropTarget, different from any valid pointer value
83 // (which are all even under Windows) and NULL
84 static wxDropTarget *
85 wxRICHTEXT_DEFAULT_DROPTARGET = wx_reinterpret_cast(wxDropTarget *, 1);
86
87 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
88
89 // ----------------------------------------------------------------------------
90 // private classes
91 // ----------------------------------------------------------------------------
92
93 #if wxUSE_RICHEDIT
94
95 // this module initializes RichEdit DLL(s) if needed
96 class wxRichEditModule : public wxModule
97 {
98 public:
99 enum Version
100 {
101 Version_1, // riched32.dll
102 Version_2or3, // both use riched20.dll
103 Version_41, // msftedit.dll (XP SP1 and Windows 2003)
104 Version_Max
105 };
106
107 virtual bool OnInit();
108 virtual void OnExit();
109
110 // load the richedit DLL for the specified version of rich edit
111 static bool Load(Version version);
112
113 #if wxUSE_INKEDIT
114 // load the InkEdit library
115 static bool LoadInkEdit();
116 #endif
117
118 private:
119 // the handles to richedit 1.0 and 2.0 (or 3.0) DLLs
120 static HINSTANCE ms_hRichEdit[Version_Max];
121
122 #if wxUSE_INKEDIT
123 static wxDynamicLibrary ms_inkEditLib;
124 static bool ms_inkEditLibLoadAttemped;
125 #endif
126
127 DECLARE_DYNAMIC_CLASS(wxRichEditModule)
128 };
129
130 HINSTANCE wxRichEditModule::ms_hRichEdit[Version_Max] = { NULL, NULL, NULL };
131
132 #if wxUSE_INKEDIT
133 wxDynamicLibrary wxRichEditModule::ms_inkEditLib;
134 bool wxRichEditModule::ms_inkEditLibLoadAttemped = false;
135 #endif
136
137 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule, wxModule)
138
139 #endif // wxUSE_RICHEDIT
140
141 // a small class used to set m_updatesCount to 0 (to filter duplicate events if
142 // necessary) and to reset it back to -1 afterwards
143 class UpdatesCountFilter
144 {
145 public:
146 UpdatesCountFilter(int& count)
147 : m_count(count)
148 {
149 wxASSERT_MSG( m_count == -1 || m_count == -2,
150 _T("wrong initial m_updatesCount value") );
151
152 if (m_count != -2)
153 m_count = 0;
154 //else: we don't want to count how many update events we get as we're going
155 // to ignore all of them
156 }
157
158 ~UpdatesCountFilter()
159 {
160 m_count = -1;
161 }
162
163 // return true if an event has been received
164 bool GotUpdate() const
165 {
166 return m_count == 1;
167 }
168
169 private:
170 int& m_count;
171
172 DECLARE_NO_COPY_CLASS(UpdatesCountFilter)
173 };
174
175 // ----------------------------------------------------------------------------
176 // event tables and other macros
177 // ----------------------------------------------------------------------------
178
179 #if wxUSE_EXTENDED_RTTI
180 WX_DEFINE_FLAGS( wxTextCtrlStyle )
181
182 wxBEGIN_FLAGS( wxTextCtrlStyle )
183 // new style border flags, we put them first to
184 // use them for streaming out
185 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
186 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
187 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
188 wxFLAGS_MEMBER(wxBORDER_RAISED)
189 wxFLAGS_MEMBER(wxBORDER_STATIC)
190 wxFLAGS_MEMBER(wxBORDER_NONE)
191
192 // old style border flags
193 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
194 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
195 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
196 wxFLAGS_MEMBER(wxRAISED_BORDER)
197 wxFLAGS_MEMBER(wxSTATIC_BORDER)
198 wxFLAGS_MEMBER(wxBORDER)
199
200 // standard window styles
201 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
202 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
203 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
204 wxFLAGS_MEMBER(wxWANTS_CHARS)
205 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
206 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
207 wxFLAGS_MEMBER(wxVSCROLL)
208 wxFLAGS_MEMBER(wxHSCROLL)
209
210 wxFLAGS_MEMBER(wxTE_PROCESS_ENTER)
211 wxFLAGS_MEMBER(wxTE_PROCESS_TAB)
212 wxFLAGS_MEMBER(wxTE_MULTILINE)
213 wxFLAGS_MEMBER(wxTE_PASSWORD)
214 wxFLAGS_MEMBER(wxTE_READONLY)
215 wxFLAGS_MEMBER(wxHSCROLL)
216 wxFLAGS_MEMBER(wxTE_RICH)
217 wxFLAGS_MEMBER(wxTE_RICH2)
218 wxFLAGS_MEMBER(wxTE_AUTO_URL)
219 wxFLAGS_MEMBER(wxTE_NOHIDESEL)
220 wxFLAGS_MEMBER(wxTE_LEFT)
221 wxFLAGS_MEMBER(wxTE_CENTRE)
222 wxFLAGS_MEMBER(wxTE_RIGHT)
223 wxFLAGS_MEMBER(wxTE_DONTWRAP)
224 wxFLAGS_MEMBER(wxTE_CHARWRAP)
225 wxFLAGS_MEMBER(wxTE_WORDWRAP)
226
227 wxEND_FLAGS( wxTextCtrlStyle )
228
229 IMPLEMENT_DYNAMIC_CLASS_XTI(wxTextCtrl, wxControl,"wx/textctrl.h")
230
231 wxBEGIN_PROPERTIES_TABLE(wxTextCtrl)
232 wxEVENT_PROPERTY( TextUpdated , wxEVT_COMMAND_TEXT_UPDATED , wxCommandEvent )
233 wxEVENT_PROPERTY( TextEnter , wxEVT_COMMAND_TEXT_ENTER , wxCommandEvent )
234
235 wxPROPERTY( Font , wxFont , SetFont , GetFont , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
236 wxPROPERTY( Value , wxString , SetValue, GetValue, wxString() , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
237 wxPROPERTY_FLAGS( WindowStyle , wxTextCtrlStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
238 wxEND_PROPERTIES_TABLE()
239
240 wxBEGIN_HANDLERS_TABLE(wxTextCtrl)
241 wxEND_HANDLERS_TABLE()
242
243 wxCONSTRUCTOR_6( wxTextCtrl , wxWindow* , Parent , wxWindowID , Id , wxString , Value , wxPoint , Position , wxSize , Size , long , WindowStyle)
244 #else
245 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxTextCtrlBase)
246 #endif
247
248
249 BEGIN_EVENT_TABLE(wxTextCtrl, wxTextCtrlBase)
250 EVT_CHAR(wxTextCtrl::OnChar)
251 EVT_DROP_FILES(wxTextCtrl::OnDropFiles)
252
253 #if wxUSE_RICHEDIT
254 EVT_CONTEXT_MENU(wxTextCtrl::OnContextMenu)
255 #endif
256
257 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
258 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
259 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
260 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
261 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
262 EVT_MENU(wxID_CLEAR, wxTextCtrl::OnDelete)
263 EVT_MENU(wxID_SELECTALL, wxTextCtrl::OnSelectAll)
264
265 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
266 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
267 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
268 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
269 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
270 EVT_UPDATE_UI(wxID_CLEAR, wxTextCtrl::OnUpdateDelete)
271 EVT_UPDATE_UI(wxID_SELECTALL, wxTextCtrl::OnUpdateSelectAll)
272
273 EVT_SET_FOCUS(wxTextCtrl::OnSetFocus)
274 END_EVENT_TABLE()
275
276 // ============================================================================
277 // implementation
278 // ============================================================================
279
280 // ----------------------------------------------------------------------------
281 // creation
282 // ----------------------------------------------------------------------------
283
284 void wxTextCtrl::Init()
285 {
286 #if wxUSE_RICHEDIT
287 m_verRichEdit = 0;
288 #endif // wxUSE_RICHEDIT
289
290 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
291 m_isInkEdit = 0;
292 #endif
293
294 m_privateContextMenu = NULL;
295 m_updatesCount = -1;
296 m_isNativeCaretShown = true;
297 }
298
299 wxTextCtrl::~wxTextCtrl()
300 {
301 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
302 if ( m_dropTarget == wxRICHTEXT_DEFAULT_DROPTARGET )
303 {
304 // don't try to destroy this dummy pointer in the base class dtor
305 m_dropTarget = NULL;
306 }
307 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
308
309 delete m_privateContextMenu;
310 }
311
312 bool wxTextCtrl::Create(wxWindow *parent,
313 wxWindowID id,
314 const wxString& value,
315 const wxPoint& pos,
316 const wxSize& size,
317 long style,
318 const wxValidator& validator,
319 const wxString& name)
320 {
321 // base initialization
322 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
323 return false;
324
325 if ( !MSWCreateText(value, pos, size) )
326 return false;
327
328 #if wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
329 if ( IsRich() )
330 {
331 // rich text controls have a default associated drop target which
332 // allows them to receive (rich) text dropped on them, which is nice,
333 // but prevents us from associating a user-defined drop target with
334 // them as we need to unregister the old one first
335 //
336 // to make it work, we set m_dropTarget to this special value initially
337 // and check for it in our SetDropTarget()
338 m_dropTarget = wxRICHTEXT_DEFAULT_DROPTARGET;
339 }
340 #endif // wxUSE_DRAG_AND_DROP && wxUSE_RICHEDIT
341
342 return true;
343 }
344
345 // returns true if the platform should explicitly apply a theme border
346 bool wxTextCtrl::CanApplyThemeBorder() const
347 {
348 #ifdef __WXWINCE__
349 return false;
350 #else
351 // Standard text control already handles theming
352 return ((GetWindowStyle() & (wxTE_RICH|wxTE_RICH2)) != 0);
353 #endif
354 }
355
356 bool wxTextCtrl::MSWCreateText(const wxString& value,
357 const wxPoint& pos,
358 const wxSize& size)
359 {
360 // translate wxWin style flags to MSW ones
361 WXDWORD msStyle = MSWGetCreateWindowFlags();
362
363 // do create the control - either an EDIT or RICHEDIT
364 wxString windowClass = wxT("EDIT");
365
366 #if defined(__POCKETPC__) || defined(__SMARTPHONE__)
367 // A control that capitalizes the first letter
368 if ( HasFlag(wxTE_CAPITALIZE) )
369 windowClass = wxT("CAPEDIT");
370 #endif
371
372 #if wxUSE_RICHEDIT
373 if ( m_windowStyle & wxTE_AUTO_URL )
374 {
375 // automatic URL detection only works in RichEdit 2.0+
376 m_windowStyle |= wxTE_RICH2;
377 }
378
379 if ( m_windowStyle & wxTE_RICH2 )
380 {
381 // using richedit 2.0 implies using wxTE_RICH
382 m_windowStyle |= wxTE_RICH;
383 }
384
385 // we need to load the richedit DLL before creating the rich edit control
386 if ( m_windowStyle & wxTE_RICH )
387 {
388 // versions 2.0, 3.0 and 4.1 of rich edit are mostly compatible with
389 // each other but not with version 1.0, so we have separate flags for
390 // the version 1.0 and the others (and so m_verRichEdit may be 0 (plain
391 // EDIT control), 1 for version 1.0 or 2 for any higher version)
392 //
393 // notice that 1.0 has no Unicode support at all so in Unicode build we
394 // must use another version
395
396 #if wxUSE_UNICODE
397 m_verRichEdit = 2;
398 #else // !wxUSE_UNICODE
399 m_verRichEdit = m_windowStyle & wxTE_RICH2 ? 2 : 1;
400 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
401
402 #if wxUSE_INKEDIT
403 // First test if we can load an ink edit control. Normally, all edit
404 // controls will be made ink edit controls if a tablet environment is
405 // found (or if msw.inkedit != 0 and the InkEd.dll is present).
406 // However, an application can veto ink edit controls by either specifying
407 // msw.inkedit = 0 or by removing wxTE_RICH[2] from the style.
408 //
409 if ((wxSystemSettings::HasFeature(wxSYS_TABLET_PRESENT) || wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) != 0) &&
410 !(wxSystemOptions::HasOption(wxT("msw.inkedit")) && wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) == 0))
411 {
412 if (wxRichEditModule::LoadInkEdit())
413 {
414 windowClass = INKEDIT_CLASS;
415
416 #if wxUSE_INKEDIT && wxUSE_RICHEDIT
417 m_isInkEdit = 1;
418 #endif
419
420 // Fake rich text version for other calls
421 m_verRichEdit = 2;
422 }
423 }
424 #endif
425
426 if (!IsInkEdit())
427 {
428 if ( m_verRichEdit == 2 )
429 {
430 if ( wxRichEditModule::Load(wxRichEditModule::Version_41) )
431 {
432 // yes, class name for version 4.1 really is 5.0
433 windowClass = _T("RICHEDIT50W");
434 }
435 else if ( wxRichEditModule::Load(wxRichEditModule::Version_2or3) )
436 {
437 windowClass = _T("RichEdit20")
438 #if wxUSE_UNICODE
439 _T("W");
440 #else // ANSI
441 _T("A");
442 #endif // Unicode/ANSI
443 }
444 else // failed to load msftedit.dll and riched20.dll
445 {
446 m_verRichEdit = 1;
447 }
448 }
449
450 if ( m_verRichEdit == 1 )
451 {
452 if ( wxRichEditModule::Load(wxRichEditModule::Version_1) )
453 {
454 windowClass = _T("RICHEDIT");
455 }
456 else // failed to load any richedit control DLL
457 {
458 // only give the error msg once if the DLL can't be loaded
459 static bool s_errorGiven = false; // MT ok as only used by GUI
460
461 if ( !s_errorGiven )
462 {
463 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
464
465 s_errorGiven = true;
466 }
467
468 m_verRichEdit = 0;
469 }
470 }
471 } // !useInkEdit
472 }
473 #endif // wxUSE_RICHEDIT
474
475 // we need to turn '\n's into "\r\n"s for the multiline controls
476 wxString valueWin;
477 if ( m_windowStyle & wxTE_MULTILINE )
478 {
479 valueWin = wxTextFile::Translate(value, wxTextFileType_Dos);
480 }
481 else // single line
482 {
483 valueWin = value;
484 }
485
486 if ( !MSWCreateControl(windowClass.wx_str(), msStyle, pos, size, valueWin) )
487 return false;
488
489 #if wxUSE_RICHEDIT
490 if (IsRich())
491 {
492 #if wxUSE_INKEDIT
493 if (IsInkEdit())
494 {
495 // Pass IEM_InsertText (0) as wParam, in order to have the ink always
496 // converted to text.
497 ::SendMessage(GetHwnd(), EM_SETINKINSERTMODE, 0, 0);
498
499 // Make sure the mouse can be used for input
500 ::SendMessage(GetHwnd(), EM_SETUSEMOUSEFORINPUT, 1, 0);
501 }
502 #endif
503
504 // enable the events we're interested in: we want to get EN_CHANGE as
505 // for the normal controls
506 LPARAM mask = ENM_CHANGE;
507
508 if (GetRichVersion() == 1 && !IsInkEdit())
509 {
510 // we also need EN_MSGFILTER for richedit 1.0 for the reasons
511 // explained in its handler
512 mask |= ENM_MOUSEEVENTS;
513
514 // we also need to force the appearance of the vertical scrollbar
515 // initially as otherwise the control doesn't refresh correctly
516 // after resize: but once the vertical scrollbar had been shown
517 // (even if it's subsequently hidden) it does
518 //
519 // this is clearly a bug and for now it has been only noticed under
520 // Windows XP, so if we're sure it works correctly under other
521 // systems we could do this only for XP
522 SetSize(-1, 1); // 1 is small enough to force vert scrollbar
523 SetInitialSize(size);
524 }
525 else if ( m_windowStyle & wxTE_AUTO_URL )
526 {
527 mask |= ENM_LINK;
528
529 ::SendMessage(GetHwnd(), EM_AUTOURLDETECT, TRUE, 0);
530 }
531
532 ::SendMessage(GetHwnd(), EM_SETEVENTMASK, 0, mask);
533 }
534 #endif // wxUSE_RICHEDIT
535
536 #ifndef __WXWINCE__
537 // Without this, if we pass the size in the constructor and then don't change it,
538 // the themed borders will be drawn incorrectly.
539 SetWindowPos(GetHwnd(), NULL, 0, 0, 0, 0,
540 SWP_NOZORDER|SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE|
541 SWP_FRAMECHANGED);
542 #endif
543
544 return true;
545 }
546
547 // Make sure the window style (etc.) reflects the HWND style (roughly)
548 void wxTextCtrl::AdoptAttributesFromHWND()
549 {
550 wxWindow::AdoptAttributesFromHWND();
551
552 HWND hWnd = GetHwnd();
553 long style = ::GetWindowLong(hWnd, GWL_STYLE);
554
555 // retrieve the style to see whether this is an edit or richedit ctrl
556 #if wxUSE_RICHEDIT
557 wxString classname = wxGetWindowClass(GetHWND());
558
559 if ( classname.IsSameAs(_T("EDIT"), false /* no case */) )
560 {
561 m_verRichEdit = 0;
562 }
563 else // rich edit?
564 {
565 wxChar c;
566 if ( wxSscanf(classname, _T("RichEdit%d0%c"), &m_verRichEdit, &c) != 2 )
567 {
568 wxLogDebug(_T("Unknown edit control '%s'."), classname.c_str());
569
570 m_verRichEdit = 0;
571 }
572 }
573 #endif // wxUSE_RICHEDIT
574
575 if (style & ES_MULTILINE)
576 m_windowStyle |= wxTE_MULTILINE;
577 if (style & ES_PASSWORD)
578 m_windowStyle |= wxTE_PASSWORD;
579 if (style & ES_READONLY)
580 m_windowStyle |= wxTE_READONLY;
581 if (style & ES_WANTRETURN)
582 m_windowStyle |= wxTE_PROCESS_ENTER;
583 if (style & ES_CENTER)
584 m_windowStyle |= wxTE_CENTRE;
585 if (style & ES_RIGHT)
586 m_windowStyle |= wxTE_RIGHT;
587 }
588
589 WXDWORD wxTextCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const
590 {
591 long msStyle = wxControl::MSWGetStyle(style, exstyle);
592
593 // styles which we alaways add by default
594 if ( style & wxTE_MULTILINE )
595 {
596 msStyle |= ES_MULTILINE | ES_WANTRETURN;
597 if ( !(style & wxTE_NO_VSCROLL) )
598 {
599 // always adjust the vertical scrollbar automatically if we have it
600 msStyle |= WS_VSCROLL | ES_AUTOVSCROLL;
601
602 #if wxUSE_RICHEDIT
603 // we have to use this style for the rich edit controls because
604 // without it the vertical scrollbar never appears at all in
605 // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it)
606 if ( style & wxTE_RICH2 )
607 {
608 msStyle |= ES_DISABLENOSCROLL;
609 }
610 #endif // wxUSE_RICHEDIT
611 }
612
613 style |= wxTE_PROCESS_ENTER;
614 }
615 else // !multiline
616 {
617 // there is really no reason to not have this style for single line
618 // text controls
619 msStyle |= ES_AUTOHSCROLL;
620 }
621
622 // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz
623 // scrollbar, there is no wrapping -- which makes sense
624 if ( style & wxTE_DONTWRAP )
625 {
626 // automatically scroll the control horizontally as necessary
627 //
628 // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't
629 // show horz scrollbar at all, even in spite of WS_HSCROLL, and as
630 // it doesn't seem to do any harm for plain edit controls, add it
631 // always
632 msStyle |= WS_HSCROLL | ES_AUTOHSCROLL;
633 }
634
635 if ( style & wxTE_READONLY )
636 msStyle |= ES_READONLY;
637
638 if ( style & wxTE_PASSWORD )
639 msStyle |= ES_PASSWORD;
640
641 if ( style & wxTE_NOHIDESEL )
642 msStyle |= ES_NOHIDESEL;
643
644 // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0
645 if ( style & wxTE_CENTRE )
646 msStyle |= ES_CENTER;
647 else if ( style & wxTE_RIGHT )
648 msStyle |= ES_RIGHT;
649 else
650 msStyle |= ES_LEFT; // ES_LEFT is 0 as well but for consistency...
651
652 return msStyle;
653 }
654
655 void wxTextCtrl::SetWindowStyleFlag(long style)
656 {
657 // changing the alignment of the control dynamically works under Win2003
658 // (but not older Windows version: it seems to work under some versions of
659 // XP but not other ones, and we have no way to determine it so be
660 // conservative here) and only for plain EDIT controls (not RICH ones) and
661 // we have to recreate the control to make it always work
662 if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003 )
663 {
664 const long alignMask = wxTE_LEFT | wxTE_CENTRE | wxTE_RIGHT;
665 if ( (style & alignMask) != (GetWindowStyle() & alignMask) )
666 {
667 const wxString value = GetValue();
668 const wxPoint pos = GetPosition();
669 const wxSize size = GetSize();
670
671 // delete the old window
672 HWND hwnd = GetHwnd();
673 DissociateHandle();
674 ::DestroyWindow(hwnd);
675
676 // create the new one with the updated flags
677 m_windowStyle = style;
678 MSWCreateText(value, pos, size);
679
680 // and make sure it has the same attributes as before
681 if ( m_hasFont )
682 {
683 // calling SetFont(m_font) would do nothing as the code would
684 // notice that the font didn't change, so force it to believe
685 // that it did
686 wxFont font = m_font;
687 m_font = wxNullFont;
688 SetFont(font);
689 }
690
691 if ( m_hasFgCol )
692 {
693 wxColour colFg = m_foregroundColour;
694 m_foregroundColour = wxNullColour;
695 SetForegroundColour(colFg);
696 }
697
698 if ( m_hasBgCol )
699 {
700 wxColour colBg = m_backgroundColour;
701 m_backgroundColour = wxNullColour;
702 SetBackgroundColour(colBg);
703 }
704
705 // note that text styles are lost but this is probably not a big
706 // problem: if you use styles, you probably don't use nor change
707 // alignment flags anyhow
708
709 return;
710 }
711 }
712
713 #if wxUSE_RICHEDIT
714 // we have to deal with some styles separately because they can't be
715 // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed
716 // using richedit-specific EM_SETOPTIONS
717 if ( IsRich() &&
718 ((style & wxTE_NOHIDESEL) != (GetWindowStyle() & wxTE_NOHIDESEL)) )
719 {
720 bool set = (style & wxTE_NOHIDESEL) != 0;
721
722 ::SendMessage(GetHwnd(), EM_SETOPTIONS, set ? ECOOP_OR : ECOOP_AND,
723 set ? ECO_NOHIDESEL : ~ECO_NOHIDESEL);
724 }
725 #endif // wxUSE_RICHEDIT
726
727 wxControl::SetWindowStyleFlag(style);
728 }
729
730 // ----------------------------------------------------------------------------
731 // set/get the controls text
732 // ----------------------------------------------------------------------------
733
734 bool wxTextCtrl::IsEmpty() const
735 {
736 // this is an optimization for multiline controls containing a lot of text
737 if ( IsMultiLine() && GetNumberOfLines() != 1 )
738 return false;
739
740 return wxTextCtrlBase::IsEmpty();
741 }
742
743 wxString wxTextCtrl::GetValue() const
744 {
745 // range 0..-1 is special for GetRange() and means to retrieve all text
746 return GetRange(0, -1);
747 }
748
749 wxString wxTextCtrl::GetRange(long from, long to) const
750 {
751 wxString str;
752
753 if ( from >= to && to != -1 )
754 {
755 // nothing to retrieve
756 return str;
757 }
758
759 #if wxUSE_RICHEDIT
760 if ( IsRich() )
761 {
762 int len = GetWindowTextLength(GetHwnd());
763 if ( len > from )
764 {
765 if ( to == -1 )
766 to = len;
767
768 #if !wxUSE_UNICODE
769 // we must use EM_STREAMOUT if we don't want to lose all characters
770 // not representable in the current character set (EM_GETTEXTRANGE
771 // simply replaces them with question marks...)
772 if ( GetRichVersion() > 1 )
773 {
774 // we must have some encoding, otherwise any 8bit chars in the
775 // control are simply *lost* (replaced by '?')
776 wxFontEncoding encoding = wxFONTENCODING_SYSTEM;
777
778 wxFont font = m_defaultStyle.GetFont();
779 if ( !font.Ok() )
780 font = GetFont();
781
782 if ( font.Ok() )
783 {
784 encoding = font.GetEncoding();
785 }
786
787 if ( encoding == wxFONTENCODING_SYSTEM )
788 {
789 encoding = wxLocale::GetSystemEncoding();
790 }
791
792 if ( encoding == wxFONTENCODING_SYSTEM )
793 {
794 encoding = wxFONTENCODING_ISO8859_1;
795 }
796
797 str = StreamOut(encoding);
798
799 if ( !str.empty() )
800 {
801 // we have to manually extract the required part, luckily
802 // this is easy in this case as EOL characters in str are
803 // just LFs because we remove CRs in wxRichEditStreamOut
804 str = str.Mid(from, to - from);
805 }
806 }
807
808 // StreamOut() wasn't used or failed, try to do it in normal way
809 if ( str.empty() )
810 #endif // !wxUSE_UNICODE
811 {
812 // alloc one extra WORD as needed by the control
813 wxStringBuffer tmp(str, ++len);
814 wxChar *p = tmp;
815
816 TEXTRANGE textRange;
817 textRange.chrg.cpMin = from;
818 textRange.chrg.cpMax = to;
819 textRange.lpstrText = p;
820
821 (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE,
822 0, (LPARAM)&textRange);
823
824 if ( m_verRichEdit > 1 )
825 {
826 // RichEdit 2.0 uses just CR ('\r') for the
827 // newlines which is neither Unix nor Windows
828 // style - convert it to something reasonable
829 for ( ; *p; p++ )
830 {
831 if ( *p == _T('\r') )
832 *p = _T('\n');
833 }
834 }
835 }
836
837 if ( m_verRichEdit == 1 )
838 {
839 // convert to the canonical form - see comment below
840 str = wxTextFile::Translate(str, wxTextFileType_Unix);
841 }
842 }
843 //else: no text at all, leave the string empty
844 }
845 else
846 #endif // wxUSE_RICHEDIT
847 {
848 // retrieve all text
849 str = wxGetWindowText(GetHWND());
850
851 // need only a range?
852 if ( from < to )
853 {
854 str = str.Mid(from, to - from);
855 }
856
857 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
858 // canonical one (same one as above) for consistency with the other kinds
859 // of controls and, more importantly, with the other ports
860 str = wxTextFile::Translate(str, wxTextFileType_Unix);
861 }
862
863 return str;
864 }
865
866 void wxTextCtrl::DoSetValue(const wxString& value, int flags)
867 {
868 // if the text is long enough, it's faster to just set it instead of first
869 // comparing it with the old one (chances are that it will be different
870 // anyhow, this comparison is there to avoid flicker for small single-line
871 // edit controls mostly)
872 if ( (value.length() > 0x400) || (value != GetValue()) )
873 {
874 DoWriteText(value, flags /* doesn't include SelectionOnly here */);
875
876 // mark the control as being not dirty - we changed its text, not the
877 // user
878 DiscardEdits();
879
880 // for compatibility, don't move the cursor when doing SetValue()
881 SetInsertionPoint(0);
882 }
883 else // same text
884 {
885 // still reset the modified flag even if the value didn't really change
886 // because now it comes from the program and not the user (and do it
887 // before generating the event so that the event handler could get the
888 // expected value from IsModified())
889 DiscardEdits();
890
891 // still send an event for consistency
892 if (flags & SetValue_SendEvent)
893 SendUpdateEvent();
894 }
895 }
896
897 #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU)
898
899 // TODO: using memcpy() would improve performance a lot for big amounts of text
900
901 DWORD CALLBACK
902 wxRichEditStreamIn(DWORD dwCookie, BYTE *buf, LONG cb, LONG *pcb)
903 {
904 *pcb = 0;
905
906 const wchar_t ** const ppws = (const wchar_t **)dwCookie;
907
908 wchar_t *wbuf = (wchar_t *)buf;
909 const wchar_t *wpc = *ppws;
910 while ( cb && *wpc )
911 {
912 *wbuf++ = *wpc++;
913
914 cb -= sizeof(wchar_t);
915 (*pcb) += sizeof(wchar_t);
916 }
917
918 *ppws = wpc;
919
920 return 0;
921 }
922
923 // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut
924 struct wxStreamOutData
925 {
926 wchar_t *wpc;
927 size_t len;
928 };
929
930 DWORD CALLBACK
931 wxRichEditStreamOut(DWORD_PTR dwCookie, BYTE *buf, LONG cb, LONG *pcb)
932 {
933 *pcb = 0;
934
935 wxStreamOutData *data = (wxStreamOutData *)dwCookie;
936
937 const wchar_t *wbuf = (const wchar_t *)buf;
938 wchar_t *wpc = data->wpc;
939 while ( cb )
940 {
941 wchar_t wch = *wbuf++;
942
943 // turn "\r\n" into "\n" on the fly
944 if ( wch != L'\r' )
945 *wpc++ = wch;
946 else
947 data->len--;
948
949 cb -= sizeof(wchar_t);
950 (*pcb) += sizeof(wchar_t);
951 }
952
953 data->wpc = wpc;
954
955 return 0;
956 }
957
958
959 #if wxUSE_UNICODE_MSLU
960 #define UNUSED_IF_MSLU(param)
961 #else
962 #define UNUSED_IF_MSLU(param) param
963 #endif
964
965 bool
966 wxTextCtrl::StreamIn(const wxString& value,
967 wxFontEncoding UNUSED_IF_MSLU(encoding),
968 bool selectionOnly)
969 {
970 #if wxUSE_UNICODE_MSLU
971 const wchar_t *wpc = value.c_str();
972 #else // !wxUSE_UNICODE_MSLU
973 wxCSConv conv(encoding);
974
975 const size_t len = conv.MB2WC(NULL, value.mb_str(), value.length());
976
977 #if wxUSE_WCHAR_T
978 wxWCharBuffer wchBuf(len);
979 wchar_t *wpc = wchBuf.data();
980 #else
981 wchar_t *wchBuf = (wchar_t *)malloc((len + 1)*sizeof(wchar_t));
982 wchar_t *wpc = wchBuf;
983 #endif
984
985 conv.MB2WC(wpc, value.mb_str(), value.length());
986 #endif // wxUSE_UNICODE_MSLU
987
988 // finally, stream it in the control
989 EDITSTREAM eds;
990 wxZeroMemory(eds);
991 eds.dwCookie = (DWORD)&wpc;
992 // the cast below is needed for broken (very) old mingw32 headers
993 eds.pfnCallback = (EDITSTREAMCALLBACK)wxRichEditStreamIn;
994
995 // same problem as in DoWriteText(): we can get multiple events here
996 UpdatesCountFilter ucf(m_updatesCount);
997
998 ::SendMessage(GetHwnd(), EM_STREAMIN,
999 SF_TEXT |
1000 SF_UNICODE |
1001 (selectionOnly ? SFF_SELECTION : 0),
1002 (LPARAM)&eds);
1003
1004 // It's okay for EN_UPDATE to not be sent if the selection is empty and
1005 // the text is empty, otherwise warn the programmer about it.
1006 wxASSERT_MSG( ucf.GotUpdate() || ( !HasSelection() && value.empty() ),
1007 _T("EM_STREAMIN didn't send EN_UPDATE?") );
1008
1009 if ( eds.dwError )
1010 {
1011 wxLogLastError(_T("EM_STREAMIN"));
1012 }
1013
1014 #if !wxUSE_WCHAR_T
1015 free(wchBuf);
1016 #endif // !wxUSE_WCHAR_T
1017
1018 return true;
1019 }
1020
1021 #if !wxUSE_UNICODE_MSLU
1022
1023 wxString
1024 wxTextCtrl::StreamOut(wxFontEncoding encoding, bool selectionOnly) const
1025 {
1026 wxString out;
1027
1028 const int len = GetWindowTextLength(GetHwnd());
1029
1030 #if wxUSE_WCHAR_T
1031 wxWCharBuffer wchBuf(len);
1032 wchar_t *wpc = wchBuf.data();
1033 #else
1034 wchar_t *wchBuf = (wchar_t *)malloc((len + 1)*sizeof(wchar_t));
1035 wchar_t *wpc = wchBuf;
1036 #endif
1037
1038 wxStreamOutData data;
1039 data.wpc = wpc;
1040 data.len = len;
1041
1042 EDITSTREAM eds;
1043 wxZeroMemory(eds);
1044 eds.dwCookie = (DWORD)&data;
1045 eds.pfnCallback = wxRichEditStreamOut;
1046
1047 ::SendMessage
1048 (
1049 GetHwnd(),
1050 EM_STREAMOUT,
1051 SF_TEXT | SF_UNICODE | (selectionOnly ? SFF_SELECTION : 0),
1052 (LPARAM)&eds
1053 );
1054
1055 if ( eds.dwError )
1056 {
1057 wxLogLastError(_T("EM_STREAMOUT"));
1058 }
1059 else // streamed out ok
1060 {
1061 // NUL-terminate the string because its length could have been
1062 // decreased by wxRichEditStreamOut
1063 *(wchBuf.data() + data.len) = L'\0';
1064
1065 // now convert to the given encoding (this is a possibly lossful
1066 // conversion but what else can we do)
1067 wxCSConv conv(encoding);
1068 size_t lenNeeded = conv.WC2MB(NULL, wchBuf, 0);
1069 if ( lenNeeded++ )
1070 {
1071 conv.WC2MB(wxStringBuffer(out, lenNeeded), wchBuf, lenNeeded);
1072 }
1073 }
1074
1075 #if !wxUSE_WCHAR_T
1076 free(wchBuf);
1077 #endif // !wxUSE_WCHAR_T
1078
1079 return out;
1080 }
1081
1082 #endif // !wxUSE_UNICODE_MSLU
1083
1084 #endif // wxUSE_RICHEDIT
1085
1086 void wxTextCtrl::WriteText(const wxString& value)
1087 {
1088 DoWriteText(value);
1089 }
1090
1091 void wxTextCtrl::DoWriteText(const wxString& value, int flags)
1092 {
1093 bool selectionOnly = (flags & SetValue_SelectionOnly) != 0;
1094 wxString valueDos;
1095 if ( m_windowStyle & wxTE_MULTILINE )
1096 valueDos = wxTextFile::Translate(value, wxTextFileType_Dos);
1097 else
1098 valueDos = value;
1099
1100 #if wxUSE_RICHEDIT
1101 // there are several complications with the rich edit controls here
1102 bool done = false;
1103 if ( IsRich() )
1104 {
1105 // first, ensure that the new text will be in the default style
1106 if ( !m_defaultStyle.IsDefault() )
1107 {
1108 long start, end;
1109 GetSelection(&start, &end);
1110 SetStyle(start, end, m_defaultStyle);
1111 }
1112
1113 #if wxUSE_UNICODE_MSLU
1114 // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x,
1115 // but EM_STREAMIN works
1116 if ( wxUsingUnicowsDll() && GetRichVersion() > 1 )
1117 {
1118 done = StreamIn(valueDos, wxFONTENCODING_SYSTEM, selectionOnly);
1119 }
1120 #endif // wxUSE_UNICODE_MSLU
1121
1122 #if !wxUSE_UNICODE
1123 // next check if the text we're inserting must be shown in a non
1124 // default charset -- this only works for RichEdit > 1.0
1125 if ( GetRichVersion() > 1 )
1126 {
1127 wxFont font = m_defaultStyle.GetFont();
1128 if ( !font.Ok() )
1129 font = GetFont();
1130
1131 if ( font.Ok() )
1132 {
1133 wxFontEncoding encoding = font.GetEncoding();
1134 if ( encoding != wxFONTENCODING_SYSTEM )
1135 {
1136 // we have to use EM_STREAMIN to force richedit control 2.0+
1137 // to show any text in the non default charset -- otherwise
1138 // it thinks it knows better than we do and always shows it
1139 // in the default one
1140 done = StreamIn(valueDos, encoding, selectionOnly);
1141 }
1142 }
1143 }
1144 #endif // !wxUSE_UNICODE
1145 }
1146
1147 if ( !done )
1148 #endif // wxUSE_RICHEDIT
1149 {
1150 // in some cases we get 2 EN_CHANGE notifications after the SendMessage
1151 // call (this happens for plain EDITs with EM_REPLACESEL and under some
1152 // -- undetermined -- conditions with rich edit) and sometimes we don't
1153 // get any events at all (plain EDIT with WM_SETTEXT), so ensure that
1154 // we generate exactly one of them by ignoring all but the first one in
1155 // SendUpdateEvent() and generating one ourselves if we hadn't got any
1156 // notifications from Windows
1157 if ( !(flags & SetValue_SendEvent) )
1158 m_updatesCount = -2; // suppress any update event
1159
1160 UpdatesCountFilter ucf(m_updatesCount);
1161
1162 ::SendMessage(GetHwnd(), selectionOnly ? EM_REPLACESEL : WM_SETTEXT,
1163 // EM_REPLACESEL takes 1 to indicate the operation should be redoable
1164 selectionOnly ? 1 : 0, (LPARAM)valueDos.wx_str());
1165
1166 if ( !ucf.GotUpdate() && (flags & SetValue_SendEvent) )
1167 {
1168 SendUpdateEvent();
1169 }
1170 }
1171 }
1172
1173 void wxTextCtrl::AppendText(const wxString& text)
1174 {
1175 SetInsertionPointEnd();
1176
1177 WriteText(text);
1178
1179 #if wxUSE_RICHEDIT
1180 // don't do this if we're frozen, saves some time
1181 if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 )
1182 {
1183 // setting the caret to the end and showing it simply doesn't work for
1184 // RichEdit 2.0 -- force it to still do what we want
1185 ::SendMessage(GetHwnd(), EM_LINESCROLL, 0, GetNumberOfLines());
1186 }
1187 #endif // wxUSE_RICHEDIT
1188 }
1189
1190 void wxTextCtrl::Clear()
1191 {
1192 ::SetWindowText(GetHwnd(), wxEmptyString);
1193
1194 #if wxUSE_RICHEDIT
1195 if ( !IsRich() )
1196 #endif // wxUSE_RICHEDIT
1197 {
1198 // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves
1199 // but the normal ones don't -- make Clear() behaviour consistent by
1200 // always sending this event
1201
1202 // Windows already sends an update event for single-line
1203 // controls.
1204 if ( m_windowStyle & wxTE_MULTILINE )
1205 SendUpdateEvent();
1206 }
1207 }
1208
1209 #ifdef __WIN32__
1210
1211 bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent& event)
1212 {
1213 SetFocus();
1214
1215 size_t lenOld = GetValue().length();
1216
1217 wxUint32 code = event.GetRawKeyCode();
1218 ::keybd_event((BYTE)code, 0, 0 /* key press */, 0);
1219 ::keybd_event((BYTE)code, 0, KEYEVENTF_KEYUP, 0);
1220
1221 // assume that any alphanumeric key changes the total number of characters
1222 // in the control - this should work in 99% of cases
1223 return GetValue().length() != lenOld;
1224 }
1225
1226 #endif // __WIN32__
1227
1228 // ----------------------------------------------------------------------------
1229 // Clipboard operations
1230 // ----------------------------------------------------------------------------
1231
1232 void wxTextCtrl::Copy()
1233 {
1234 if (CanCopy())
1235 {
1236 ::SendMessage(GetHwnd(), WM_COPY, 0, 0L);
1237 }
1238 }
1239
1240 void wxTextCtrl::Cut()
1241 {
1242 if (CanCut())
1243 {
1244 ::SendMessage(GetHwnd(), WM_CUT, 0, 0L);
1245 }
1246 }
1247
1248 void wxTextCtrl::Paste()
1249 {
1250 if (CanPaste())
1251 {
1252 ::SendMessage(GetHwnd(), WM_PASTE, 0, 0L);
1253 }
1254 }
1255
1256 bool wxTextCtrl::HasSelection() const
1257 {
1258 long from, to;
1259 GetSelection(&from, &to);
1260 return from != to;
1261 }
1262
1263 bool wxTextCtrl::CanCopy() const
1264 {
1265 // Can copy if there's a selection
1266 return HasSelection();
1267 }
1268
1269 bool wxTextCtrl::CanCut() const
1270 {
1271 return CanCopy() && IsEditable();
1272 }
1273
1274 bool wxTextCtrl::CanPaste() const
1275 {
1276 if ( !IsEditable() )
1277 return false;
1278
1279 #if wxUSE_RICHEDIT
1280 if ( IsRich() )
1281 {
1282 UINT cf = 0; // 0 == any format
1283
1284 return ::SendMessage(GetHwnd(), EM_CANPASTE, cf, 0) != 0;
1285 }
1286 #endif // wxUSE_RICHEDIT
1287
1288 // Standard edit control: check for straight text on clipboard
1289 if ( !::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) )
1290 return false;
1291
1292 bool isTextAvailable = ::IsClipboardFormatAvailable(CF_TEXT) != 0;
1293 ::CloseClipboard();
1294
1295 return isTextAvailable;
1296 }
1297
1298 // ----------------------------------------------------------------------------
1299 // Accessors
1300 // ----------------------------------------------------------------------------
1301
1302 void wxTextCtrl::SetEditable(bool editable)
1303 {
1304 HWND hWnd = GetHwnd();
1305 ::SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
1306 }
1307
1308 void wxTextCtrl::SetInsertionPoint(long pos)
1309 {
1310 DoSetSelection(pos, pos);
1311 }
1312
1313 void wxTextCtrl::SetInsertionPointEnd()
1314 {
1315 // we must not do anything if the caret is already there because calling
1316 // SetInsertionPoint() thaws the controls if Freeze() had been called even
1317 // if it doesn't actually move the caret anywhere and so the simple fact of
1318 // doing it results in horrible flicker when appending big amounts of text
1319 // to the control in a few chunks (see DoAddText() test in the text sample)
1320 const wxTextPos lastPosition = GetLastPosition();
1321 if ( GetInsertionPoint() == lastPosition )
1322 {
1323 return;
1324 }
1325
1326 long pos;
1327
1328 #if wxUSE_RICHEDIT
1329 if ( m_verRichEdit == 1 )
1330 {
1331 // we don't have to waste time calling GetLastPosition() in this case
1332 pos = -1;
1333 }
1334 else // !RichEdit 1.0
1335 #endif // wxUSE_RICHEDIT
1336 {
1337 pos = lastPosition;
1338 }
1339
1340 SetInsertionPoint(pos);
1341 }
1342
1343 long wxTextCtrl::GetInsertionPoint() const
1344 {
1345 #if wxUSE_RICHEDIT
1346 if ( IsRich() )
1347 {
1348 CHARRANGE range;
1349 range.cpMin = 0;
1350 range.cpMax = 0;
1351 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range);
1352 return range.cpMin;
1353 }
1354 #endif // wxUSE_RICHEDIT
1355
1356 DWORD Pos = (DWORD)::SendMessage(GetHwnd(), EM_GETSEL, 0, 0L);
1357 return Pos & 0xFFFF;
1358 }
1359
1360 wxTextPos wxTextCtrl::GetLastPosition() const
1361 {
1362 int numLines = GetNumberOfLines();
1363 long posStartLastLine = XYToPosition(0, numLines - 1);
1364
1365 long lenLastLine = GetLengthOfLineContainingPos(posStartLastLine);
1366
1367 return posStartLastLine + lenLastLine;
1368 }
1369
1370 // If the return values from and to are the same, there is no
1371 // selection.
1372 void wxTextCtrl::GetSelection(long* from, long* to) const
1373 {
1374 #if wxUSE_RICHEDIT
1375 if ( IsRich() )
1376 {
1377 CHARRANGE charRange;
1378 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &charRange);
1379
1380 *from = charRange.cpMin;
1381 *to = charRange.cpMax;
1382 }
1383 else
1384 #endif // !wxUSE_RICHEDIT
1385 {
1386 DWORD dwStart, dwEnd;
1387 ::SendMessage(GetHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
1388
1389 *from = dwStart;
1390 *to = dwEnd;
1391 }
1392 }
1393
1394 bool wxTextCtrl::IsEditable() const
1395 {
1396 // strangely enough, we may be called before the control is created: our
1397 // own Create() calls MSWGetStyle() which calls AcceptsFocus() which calls
1398 // us
1399 if ( !m_hWnd )
1400 return true;
1401
1402 long style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
1403
1404 return (style & ES_READONLY) == 0;
1405 }
1406
1407 // ----------------------------------------------------------------------------
1408 // selection
1409 // ----------------------------------------------------------------------------
1410
1411 void wxTextCtrl::SetSelection(long from, long to)
1412 {
1413 // if from and to are both -1, it means (in wxWidgets) that all text should
1414 // be selected - translate into Windows convention
1415 if ( (from == -1) && (to == -1) )
1416 {
1417 from = 0;
1418 to = -1;
1419 }
1420
1421 DoSetSelection(from, to);
1422 }
1423
1424 void wxTextCtrl::DoSetSelection(long from, long to, bool scrollCaret)
1425 {
1426 HWND hWnd = GetHwnd();
1427
1428 #if wxUSE_RICHEDIT
1429 if ( IsRich() )
1430 {
1431 CHARRANGE range;
1432 range.cpMin = from;
1433 range.cpMax = to;
1434 ::SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range);
1435 }
1436 else
1437 #endif // wxUSE_RICHEDIT
1438 {
1439 ::SendMessage(hWnd, EM_SETSEL, (WPARAM)from, (LPARAM)to);
1440 }
1441
1442 if ( scrollCaret && !IsFrozen() )
1443 {
1444 #if wxUSE_RICHEDIT
1445 // richedit 3.0 (i.e. the version living in riched20.dll distributed
1446 // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when
1447 // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL
1448 // option is set (but it does work ok in richedit 1.0 mode...)
1449 //
1450 // so to make it work we either need to give focus to it here which
1451 // will probably create many problems (dummy focus events; window
1452 // containing the text control being brought to foreground
1453 // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may
1454 // create other problems too -- and in fact it does because if we turn
1455 // on/off this style while appending the text to the control, the
1456 // vertical scrollbar never appears in it even if we append tons of
1457 // text and to work around this the only solution I found was to use
1458 // ES_DISABLENOSCROLL
1459 //
1460 // this is very ugly but I don't see any other way to make this work
1461 long style = 0;
1462 if ( GetRichVersion() > 1 )
1463 {
1464 if ( !HasFlag(wxTE_NOHIDESEL) )
1465 {
1466 // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly
1467 // others, remember the style so we can reset it later if needed
1468 style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
1469 ::SendMessage(GetHwnd(), EM_SETOPTIONS,
1470 ECOOP_OR, ECO_NOHIDESEL);
1471 }
1472 //else: everything is already ok
1473 }
1474 #endif // wxUSE_RICHEDIT
1475
1476 ::SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
1477
1478 #if wxUSE_RICHEDIT
1479 // restore ECO_NOHIDESEL if we changed it
1480 if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL) )
1481 {
1482 ::SendMessage(GetHwnd(), EM_SETOPTIONS,
1483 ECOOP_AND, ~ECO_NOHIDESEL);
1484 if ( style != ::GetWindowLong(GetHwnd(), GWL_STYLE) )
1485 ::SetWindowLong(GetHwnd(), GWL_STYLE, style);
1486 }
1487 #endif // wxUSE_RICHEDIT
1488 }
1489 }
1490
1491 // ----------------------------------------------------------------------------
1492 // Working with files
1493 // ----------------------------------------------------------------------------
1494
1495 bool wxTextCtrl::DoLoadFile(const wxString& file, int fileType)
1496 {
1497 if ( wxTextCtrlBase::DoLoadFile(file, fileType) )
1498 {
1499 // update the size limit if needed
1500 AdjustSpaceLimit();
1501
1502 return true;
1503 }
1504
1505 return false;
1506 }
1507
1508 // ----------------------------------------------------------------------------
1509 // Editing
1510 // ----------------------------------------------------------------------------
1511
1512 void wxTextCtrl::Replace(long from, long to, const wxString& value)
1513 {
1514 // Set selection and remove it
1515 DoSetSelection(from, to, false /* don't scroll caret into view */);
1516
1517 DoWriteText(value);
1518 }
1519
1520 void wxTextCtrl::Remove(long from, long to)
1521 {
1522 Replace(from, to, wxEmptyString);
1523 }
1524
1525 bool wxTextCtrl::IsModified() const
1526 {
1527 return ::SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0;
1528 }
1529
1530 void wxTextCtrl::MarkDirty()
1531 {
1532 ::SendMessage(GetHwnd(), EM_SETMODIFY, TRUE, 0L);
1533 }
1534
1535 void wxTextCtrl::DiscardEdits()
1536 {
1537 ::SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
1538 }
1539
1540 int wxTextCtrl::GetNumberOfLines() const
1541 {
1542 return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0);
1543 }
1544
1545 // ----------------------------------------------------------------------------
1546 // Positions <-> coords
1547 // ----------------------------------------------------------------------------
1548
1549 long wxTextCtrl::XYToPosition(long x, long y) const
1550 {
1551 // This gets the char index for the _beginning_ of this line
1552 long charIndex = ::SendMessage(GetHwnd(), EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
1553
1554 return charIndex + x;
1555 }
1556
1557 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
1558 {
1559 HWND hWnd = GetHwnd();
1560
1561 // This gets the line number containing the character
1562 long lineNo;
1563 #if wxUSE_RICHEDIT
1564 if ( IsRich() )
1565 {
1566 lineNo = ::SendMessage(hWnd, EM_EXLINEFROMCHAR, 0, (LPARAM)pos);
1567 }
1568 else
1569 #endif // wxUSE_RICHEDIT
1570 {
1571 lineNo = ::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, 0);
1572 }
1573
1574 if ( lineNo == -1 )
1575 {
1576 // no such line
1577 return false;
1578 }
1579
1580 // This gets the char index for the _beginning_ of this line
1581 long charIndex = ::SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
1582 if ( charIndex == -1 )
1583 {
1584 return false;
1585 }
1586
1587 // The X position must therefore be the different between pos and charIndex
1588 if ( x )
1589 *x = pos - charIndex;
1590 if ( y )
1591 *y = lineNo;
1592
1593 return true;
1594 }
1595
1596 wxTextCtrlHitTestResult
1597 wxTextCtrl::HitTest(const wxPoint& pt, long *posOut) const
1598 {
1599 // first get the position from Windows
1600 LPARAM lParam;
1601
1602 #if wxUSE_RICHEDIT
1603 POINTL ptl;
1604 if ( IsRich() )
1605 {
1606 // for rich edit controls the position is passed iva the struct fields
1607 ptl.x = pt.x;
1608 ptl.y = pt.y;
1609 lParam = (LPARAM)&ptl;
1610 }
1611 else
1612 #endif // wxUSE_RICHEDIT
1613 {
1614 // for the plain ones, we are limited to 16 bit positions which are
1615 // combined in a single 32 bit value
1616 lParam = MAKELPARAM(pt.x, pt.y);
1617 }
1618
1619 LRESULT pos = ::SendMessage(GetHwnd(), EM_CHARFROMPOS, 0, lParam);
1620
1621 if ( pos == -1 )
1622 {
1623 // this seems to indicate an error...
1624 return wxTE_HT_UNKNOWN;
1625 }
1626
1627 #if wxUSE_RICHEDIT
1628 if ( !IsRich() )
1629 #endif // wxUSE_RICHEDIT
1630 {
1631 // for plain EDIT controls the higher word contains something else
1632 pos = LOWORD(pos);
1633 }
1634
1635
1636 // next determine where it is relatively to our point: EM_CHARFROMPOS
1637 // always returns the closest character but we need to be more precise, so
1638 // double check that we really are where it pretends
1639 POINTL ptReal;
1640
1641 #if wxUSE_RICHEDIT
1642 // FIXME: we need to distinguish between richedit 2 and 3 here somehow but
1643 // we don't know how to do it
1644 if ( IsRich() )
1645 {
1646 ::SendMessage(GetHwnd(), EM_POSFROMCHAR, (WPARAM)&ptReal, pos);
1647 }
1648 else
1649 #endif // wxUSE_RICHEDIT
1650 {
1651 LRESULT lRc = ::SendMessage(GetHwnd(), EM_POSFROMCHAR, pos, 0);
1652
1653 if ( lRc == -1 )
1654 {
1655 // this is apparently returned when pos corresponds to the last
1656 // position
1657 ptReal.x =
1658 ptReal.y = 0;
1659 }
1660 else
1661 {
1662 ptReal.x = LOWORD(lRc);
1663 ptReal.y = HIWORD(lRc);
1664 }
1665 }
1666
1667 wxTextCtrlHitTestResult rc;
1668
1669 if ( pt.y > ptReal.y + GetCharHeight() )
1670 rc = wxTE_HT_BELOW;
1671 else if ( pt.x > ptReal.x + GetCharWidth() )
1672 rc = wxTE_HT_BEYOND;
1673 else
1674 rc = wxTE_HT_ON_TEXT;
1675
1676 if ( posOut )
1677 *posOut = pos;
1678
1679 return rc;
1680 }
1681
1682 // ----------------------------------------------------------------------------
1683 //
1684 // ----------------------------------------------------------------------------
1685
1686 void wxTextCtrl::ShowPosition(long pos)
1687 {
1688 HWND hWnd = GetHwnd();
1689
1690 // To scroll to a position, we pass the number of lines and characters
1691 // to scroll *by*. This means that we need to:
1692 // (1) Find the line position of the current line.
1693 // (2) Find the line position of pos.
1694 // (3) Scroll by (pos - current).
1695 // For now, ignore the horizontal scrolling.
1696
1697 // Is this where scrolling is relative to - the line containing the caret?
1698 // Or is the first visible line??? Try first visible line.
1699 // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L);
1700
1701 int currentLineLineNo = (int)::SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L);
1702
1703 int specifiedLineLineNo = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L);
1704
1705 int linesToScroll = specifiedLineLineNo - currentLineLineNo;
1706
1707 if (linesToScroll != 0)
1708 (void)::SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll);
1709 }
1710
1711 long wxTextCtrl::GetLengthOfLineContainingPos(long pos) const
1712 {
1713 return ::SendMessage(GetHwnd(), EM_LINELENGTH, (WPARAM)pos, 0);
1714 }
1715
1716 int wxTextCtrl::GetLineLength(long lineNo) const
1717 {
1718 long pos = XYToPosition(0, lineNo);
1719
1720 return GetLengthOfLineContainingPos(pos);
1721 }
1722
1723 wxString wxTextCtrl::GetLineText(long lineNo) const
1724 {
1725 size_t len = (size_t)GetLineLength(lineNo) + 1;
1726
1727 // there must be at least enough place for the length WORD in the
1728 // buffer
1729 len += sizeof(WORD);
1730
1731 wxString str;
1732 {
1733 wxStringBufferLength tmp(str, len);
1734 wxChar *buf = tmp;
1735
1736 *(WORD *)buf = (WORD)len;
1737 len = (size_t)::SendMessage(GetHwnd(), EM_GETLINE, lineNo, (LPARAM)buf);
1738
1739 #if wxUSE_RICHEDIT
1740 if ( IsRich() )
1741 {
1742 // remove the '\r' returned by the rich edit control, the user code
1743 // should never see it
1744 if ( buf[len - 2] == _T('\r') && buf[len - 1] == _T('\n') )
1745 {
1746 // richedit 1.0 uses "\r\n" as line terminator, so remove "\r"
1747 // here and "\n" below
1748 buf[len - 2] = _T('\n');
1749 len--;
1750 }
1751 else if ( buf[len - 1] == _T('\r') )
1752 {
1753 // richedit 2.0+ uses only "\r", replace it with "\n"
1754 buf[len - 1] = _T('\n');
1755 }
1756 }
1757 #endif // wxUSE_RICHEDIT
1758
1759 // remove the '\n' at the end, if any (this is how this function is
1760 // supposed to work according to the docs)
1761 if ( buf[len - 1] == _T('\n') )
1762 {
1763 len--;
1764 }
1765
1766 buf[len] = 0;
1767 tmp.SetLength(len);
1768 }
1769
1770 return str;
1771 }
1772
1773 void wxTextCtrl::SetMaxLength(unsigned long len)
1774 {
1775 #if wxUSE_RICHEDIT
1776 if ( IsRich() )
1777 {
1778 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT, 0, len ? len : 0x7fffffff);
1779 }
1780 else
1781 #endif // wxUSE_RICHEDIT
1782 {
1783 if ( len >= 0xffff )
1784 {
1785 // this will set it to a platform-dependent maximum (much more
1786 // than 64Kb under NT)
1787 len = 0;
1788 }
1789
1790 ::SendMessage(GetHwnd(), EM_LIMITTEXT, len, 0);
1791 }
1792 }
1793
1794 // ----------------------------------------------------------------------------
1795 // Undo/redo
1796 // ----------------------------------------------------------------------------
1797
1798 void wxTextCtrl::Undo()
1799 {
1800 if (CanUndo())
1801 {
1802 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
1803 }
1804 }
1805
1806 void wxTextCtrl::Redo()
1807 {
1808 if (CanRedo())
1809 {
1810 #if wxUSE_RICHEDIT
1811 if (GetRichVersion() > 1)
1812 ::SendMessage(GetHwnd(), EM_REDO, 0, 0);
1813 else
1814 #endif
1815 // Same as Undo, since Undo undoes the undo, i.e. a redo.
1816 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
1817 }
1818 }
1819
1820 bool wxTextCtrl::CanUndo() const
1821 {
1822 return ::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0;
1823 }
1824
1825 bool wxTextCtrl::CanRedo() const
1826 {
1827 #if wxUSE_RICHEDIT
1828 if (GetRichVersion() > 1)
1829 return ::SendMessage(GetHwnd(), EM_CANREDO, 0, 0) != 0;
1830 else
1831 #endif
1832 return ::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0;
1833 }
1834
1835 // ----------------------------------------------------------------------------
1836 // caret handling (Windows only)
1837 // ----------------------------------------------------------------------------
1838
1839 bool wxTextCtrl::ShowNativeCaret(bool show)
1840 {
1841 if ( show != m_isNativeCaretShown )
1842 {
1843 if ( !(show ? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) )
1844 {
1845 // not an error, may simply indicate that it's not shown/hidden
1846 // yet (i.e. it had been hidden/showh 2 times before)
1847 return false;
1848 }
1849
1850 m_isNativeCaretShown = show;
1851 }
1852
1853 return true;
1854 }
1855
1856 // ----------------------------------------------------------------------------
1857 // implemenation details
1858 // ----------------------------------------------------------------------------
1859
1860 void wxTextCtrl::Command(wxCommandEvent & event)
1861 {
1862 SetValue(event.GetString());
1863 ProcessCommand (event);
1864 }
1865
1866 void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event)
1867 {
1868 // By default, load the first file into the text window.
1869 if (event.GetNumberOfFiles() > 0)
1870 {
1871 LoadFile(event.GetFiles()[0]);
1872 }
1873 }
1874
1875 // ----------------------------------------------------------------------------
1876 // kbd input processing
1877 // ----------------------------------------------------------------------------
1878
1879 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG* msg)
1880 {
1881 // check for our special keys here: if we don't do it and the parent frame
1882 // uses them as accelerators, they wouldn't work at all, so we disable
1883 // usual preprocessing for them
1884 if ( msg->message == WM_KEYDOWN )
1885 {
1886 const WPARAM vkey = msg->wParam;
1887 if ( HIWORD(msg->lParam) & KF_ALTDOWN )
1888 {
1889 // Alt-Backspace is accelerator for "Undo"
1890 if ( vkey == VK_BACK )
1891 return false;
1892 }
1893 else // no Alt
1894 {
1895 // we want to process some Ctrl-foo and Shift-bar but no key
1896 // combinations without either Ctrl or Shift nor with both of them
1897 // pressed
1898 const int ctrl = wxIsCtrlDown(),
1899 shift = wxIsShiftDown();
1900 switch ( ctrl + shift )
1901 {
1902 default:
1903 wxFAIL_MSG( _T("how many modifiers have we got?") );
1904 // fall through
1905
1906 case 0:
1907 if ( IsMultiLine() && vkey == VK_RETURN )
1908 return false;
1909 // fall through
1910 case 2:
1911 break;
1912
1913 case 1:
1914 // either Ctrl or Shift pressed
1915 if ( ctrl )
1916 {
1917 switch ( vkey )
1918 {
1919 case 'C':
1920 case 'V':
1921 case 'X':
1922 case VK_INSERT:
1923 case VK_DELETE:
1924 case VK_HOME:
1925 case VK_END:
1926 return false;
1927 }
1928 }
1929 else // Shift is pressed
1930 {
1931 if ( vkey == VK_INSERT || vkey == VK_DELETE )
1932 return false;
1933 }
1934 }
1935 }
1936 }
1937
1938 return wxControl::MSWShouldPreProcessMessage(msg);
1939 }
1940
1941 void wxTextCtrl::OnChar(wxKeyEvent& event)
1942 {
1943 switch ( event.GetKeyCode() )
1944 {
1945 case WXK_RETURN:
1946 {
1947 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1948 InitCommandEvent(event);
1949 event.SetString(GetValue());
1950 if ( GetEventHandler()->ProcessEvent(event) )
1951 if ( !HasFlag(wxTE_MULTILINE) )
1952 return;
1953 //else: multiline controls need Enter for themselves
1954 }
1955 break;
1956
1957 case WXK_TAB:
1958 // ok, so this is getting absolutely ridiculous but I don't see
1959 // any other way to fix this bug: when a multiline text control is
1960 // inside a wxFrame, we need to generate the navigation event as
1961 // otherwise nothing happens at all, but when the same control is
1962 // created inside a dialog, IsDialogMessage() *does* switch focus
1963 // all by itself and so if we do it here as well, it is advanced
1964 // twice and goes to the next control... to prevent this from
1965 // happening we're doing this ugly check, the logic being that if
1966 // we don't have focus then it had been already changed to the next
1967 // control
1968 //
1969 // the right thing to do would, of course, be to understand what
1970 // the hell is IsDialogMessage() doing but this is beyond my feeble
1971 // forces at the moment unfortunately
1972 if ( !(m_windowStyle & wxTE_PROCESS_TAB))
1973 {
1974 if ( FindFocus() == this )
1975 {
1976 int flags = 0;
1977 if (!event.ShiftDown())
1978 flags |= wxNavigationKeyEvent::IsForward ;
1979 if (event.ControlDown())
1980 flags |= wxNavigationKeyEvent::WinChange ;
1981 if (Navigate(flags))
1982 return;
1983 }
1984 }
1985 else
1986 {
1987 // Insert tab since calling the default Windows handler
1988 // doesn't seem to do it
1989 WriteText(wxT("\t"));
1990 return;
1991 }
1992 break;
1993 }
1994
1995 // no, we didn't process it
1996 event.Skip();
1997 }
1998
1999 WXLRESULT wxTextCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
2000 {
2001 WXLRESULT lRc = wxTextCtrlBase::MSWWindowProc(nMsg, wParam, lParam);
2002
2003 switch ( nMsg )
2004 {
2005 case WM_GETDLGCODE:
2006 {
2007 // we always want the chars and the arrows: the arrows for
2008 // navigation and the chars because we want Ctrl-C to work even
2009 // in a read only control
2010 long lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS;
2011
2012 if ( IsEditable() )
2013 {
2014 // we may have several different cases:
2015 // 1. normal: both TAB and ENTER are used for navigation
2016 // 2. ctrl wants TAB for itself: ENTER is used to pass to
2017 // the next control in the dialog
2018 // 3. ctrl wants ENTER for itself: TAB is used for dialog
2019 // navigation
2020 // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to
2021 // go to the next control (we need some way to do it)
2022
2023 // multiline controls should always get ENTER for themselves
2024 if ( HasFlag(wxTE_PROCESS_ENTER) || HasFlag(wxTE_MULTILINE) )
2025 lDlgCode |= DLGC_WANTMESSAGE;
2026
2027 if ( HasFlag(wxTE_PROCESS_TAB) )
2028 lDlgCode |= DLGC_WANTTAB;
2029
2030 lRc |= lDlgCode;
2031 }
2032 else // !editable
2033 {
2034 // NB: use "=", not "|=" as the base class version returns
2035 // the same flags is this state as usual (i.e.
2036 // including DLGC_WANTMESSAGE). This is strange (how
2037 // does it work in the native Win32 apps?) but for now
2038 // live with it.
2039 lRc = lDlgCode;
2040 }
2041 }
2042 break;
2043
2044 case WM_CUT:
2045 case WM_COPY:
2046 case WM_PASTE:
2047 if ( HandleClipboardEvent(nMsg) )
2048 lRc = 0;
2049 break;
2050 }
2051
2052 return lRc;
2053 }
2054
2055 // ----------------------------------------------------------------------------
2056 // text control event processing
2057 // ----------------------------------------------------------------------------
2058
2059 bool wxTextCtrl::SendUpdateEvent()
2060 {
2061 switch ( m_updatesCount )
2062 {
2063 case 0:
2064 // remember that we've got an update
2065 m_updatesCount++;
2066 break;
2067
2068 case 1:
2069 // we had already sent one event since the last control modification
2070 return false;
2071
2072 default:
2073 wxFAIL_MSG( _T("unexpected wxTextCtrl::m_updatesCount value") );
2074 // fall through
2075
2076 case -1:
2077 // we hadn't updated the control ourselves, this event comes from
2078 // the user, don't need to ignore it nor update the count
2079 break;
2080
2081 case -2:
2082 // the control was updated programmatically and we do NOT want to
2083 // send events
2084 return false;
2085 }
2086
2087 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId());
2088 InitCommandEvent(event);
2089
2090 return ProcessCommand(event);
2091 }
2092
2093 bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
2094 {
2095 switch ( param )
2096 {
2097 case EN_SETFOCUS:
2098 case EN_KILLFOCUS:
2099 {
2100 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
2101 : wxEVT_SET_FOCUS,
2102 m_windowId);
2103 event.SetEventObject(this);
2104 GetEventHandler()->ProcessEvent(event);
2105 }
2106 break;
2107
2108 case EN_CHANGE:
2109 SendUpdateEvent();
2110 break;
2111
2112 case EN_MAXTEXT:
2113 // the text size limit has been hit -- try to increase it
2114 if ( !AdjustSpaceLimit() )
2115 {
2116 wxCommandEvent event(wxEVT_COMMAND_TEXT_MAXLEN, m_windowId);
2117 InitCommandEvent(event);
2118 event.SetString(GetValue());
2119 ProcessCommand(event);
2120 }
2121 break;
2122
2123 // the other edit notification messages are not processed
2124 default:
2125 return false;
2126 }
2127
2128 // processed
2129 return true;
2130 }
2131
2132 WXHBRUSH wxTextCtrl::MSWControlColor(WXHDC hDC, WXHWND hWnd)
2133 {
2134 if ( !IsEnabled() && !HasFlag(wxTE_MULTILINE) )
2135 return MSWControlColorDisabled(hDC);
2136
2137 return wxTextCtrlBase::MSWControlColor(hDC, hWnd);
2138 }
2139
2140 bool wxTextCtrl::HasSpaceLimit(unsigned int *len) const
2141 {
2142 // HACK: we try to automatically extend the limit for the amount of text
2143 // to allow (interactively) entering more than 64Kb of text under
2144 // Win9x but we shouldn't reset the text limit which was previously
2145 // set explicitly with SetMaxLength()
2146 //
2147 // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't
2148 // know the limit we set (if any). We could solve this by storing the
2149 // limit we set in wxTextCtrl but to save space we prefer to simply
2150 // test here the actual limit value: we consider that SetMaxLength()
2151 // can only be called for small values while EN_MAXTEXT is only sent
2152 // for large values (in practice the default limit seems to be 30000
2153 // but make it smaller just to be on the safe side)
2154 *len = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0);
2155 return *len < 10001;
2156
2157 }
2158
2159 bool wxTextCtrl::AdjustSpaceLimit()
2160 {
2161 unsigned int limit;
2162 if ( HasSpaceLimit(&limit) )
2163 return false;
2164
2165 unsigned int len = ::GetWindowTextLength(GetHwnd());
2166 if ( len >= limit )
2167 {
2168 // increment in 32Kb chunks
2169 SetMaxLength(len + 0x8000);
2170 }
2171
2172 // we changed the limit
2173 return true;
2174 }
2175
2176 bool wxTextCtrl::AcceptsFocus() const
2177 {
2178 // we don't want focus if we can't be edited unless we're a multiline
2179 // control because then it might be still nice to get focus from keyboard
2180 // to be able to scroll it without mouse
2181 return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus();
2182 }
2183
2184 wxSize wxTextCtrl::DoGetBestSize() const
2185 {
2186 int cx, cy;
2187 wxGetCharSize(GetHWND(), &cx, &cy, GetFont());
2188
2189 int wText = DEFAULT_ITEM_WIDTH;
2190
2191 int hText = cy;
2192 if ( m_windowStyle & wxTE_MULTILINE )
2193 {
2194 hText *= wxMax(wxMin(GetNumberOfLines(), 10), 2);
2195 }
2196 //else: for single line control everything is ok
2197
2198 // we have to add the adjustments for the control height only once, not
2199 // once per line, so do it after multiplication above
2200 hText += EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy) - cy;
2201
2202 return wxSize(wText, hText);
2203 }
2204
2205 // ----------------------------------------------------------------------------
2206 // standard handlers for standard edit menu events
2207 // ----------------------------------------------------------------------------
2208
2209 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
2210 {
2211 Cut();
2212 }
2213
2214 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
2215 {
2216 Copy();
2217 }
2218
2219 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
2220 {
2221 Paste();
2222 }
2223
2224 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
2225 {
2226 Undo();
2227 }
2228
2229 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
2230 {
2231 Redo();
2232 }
2233
2234 void wxTextCtrl::OnDelete(wxCommandEvent& WXUNUSED(event))
2235 {
2236 long from, to;
2237 GetSelection(& from, & to);
2238 if (from != -1 && to != -1)
2239 Remove(from, to);
2240 }
2241
2242 void wxTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event))
2243 {
2244 SetSelection(-1, -1);
2245 }
2246
2247 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
2248 {
2249 event.Enable( CanCut() );
2250 }
2251
2252 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
2253 {
2254 event.Enable( CanCopy() );
2255 }
2256
2257 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
2258 {
2259 event.Enable( CanPaste() );
2260 }
2261
2262 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
2263 {
2264 event.Enable( CanUndo() );
2265 }
2266
2267 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
2268 {
2269 event.Enable( CanRedo() );
2270 }
2271
2272 void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent& event)
2273 {
2274 long from, to;
2275 GetSelection(& from, & to);
2276 event.Enable(from != -1 && to != -1 && from != to && IsEditable()) ;
2277 }
2278
2279 void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event)
2280 {
2281 event.Enable(GetLastPosition() > 0);
2282 }
2283
2284 void wxTextCtrl::OnContextMenu(wxContextMenuEvent& event)
2285 {
2286 #if wxUSE_RICHEDIT
2287 if (IsRich())
2288 {
2289 if (!m_privateContextMenu)
2290 {
2291 m_privateContextMenu = new wxMenu;
2292 m_privateContextMenu->Append(wxID_UNDO, _("&Undo"));
2293 m_privateContextMenu->Append(wxID_REDO, _("&Redo"));
2294 m_privateContextMenu->AppendSeparator();
2295 m_privateContextMenu->Append(wxID_CUT, _("Cu&t"));
2296 m_privateContextMenu->Append(wxID_COPY, _("&Copy"));
2297 m_privateContextMenu->Append(wxID_PASTE, _("&Paste"));
2298 m_privateContextMenu->Append(wxID_CLEAR, _("&Delete"));
2299 m_privateContextMenu->AppendSeparator();
2300 m_privateContextMenu->Append(wxID_SELECTALL, _("Select &All"));
2301 }
2302 PopupMenu(m_privateContextMenu);
2303 return;
2304 }
2305 else
2306 #endif
2307 event.Skip();
2308 }
2309
2310 void wxTextCtrl::OnSetFocus(wxFocusEvent& WXUNUSED(event))
2311 {
2312 // be sure the caret remains invisible if the user had hidden it
2313 if ( !m_isNativeCaretShown )
2314 {
2315 ::HideCaret(GetHwnd());
2316 }
2317 }
2318
2319 // ----------------------------------------------------------------------------
2320 // Default colors for MSW text control
2321 //
2322 // Set default background color to the native white instead of
2323 // the default wxSYS_COLOUR_BTNFACE (is triggered with wxNullColour).
2324 // ----------------------------------------------------------------------------
2325
2326 wxVisualAttributes wxTextCtrl::GetDefaultAttributes() const
2327 {
2328 wxVisualAttributes attrs;
2329 attrs.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
2330 attrs.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
2331 attrs.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW); //white
2332
2333 return attrs;
2334 }
2335
2336 // the rest of the file only deals with the rich edit controls
2337 #if wxUSE_RICHEDIT
2338
2339 // ----------------------------------------------------------------------------
2340 // EN_LINK processing
2341 // ----------------------------------------------------------------------------
2342
2343 bool wxTextCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
2344 {
2345 NMHDR *hdr = (NMHDR* )lParam;
2346 switch ( hdr->code )
2347 {
2348 case EN_MSGFILTER:
2349 {
2350 const MSGFILTER *msgf = (MSGFILTER *)lParam;
2351 UINT msg = msgf->msg;
2352
2353 // this is a bit crazy but richedit 1.0 sends us all mouse
2354 // events _except_ WM_LBUTTONUP (don't ask me why) so we have
2355 // generate the wxWin events for this message manually
2356 //
2357 // NB: in fact, this is still not totally correct as it does
2358 // send us WM_LBUTTONUP if the selection was cleared by the
2359 // last click -- so currently we get 2 events in this case,
2360 // but as I don't see any obvious way to check for this I
2361 // leave this code in place because it's still better than
2362 // not getting left up events at all
2363 if ( msg == WM_LBUTTONUP )
2364 {
2365 WXUINT flags = msgf->wParam;
2366 int x = GET_X_LPARAM(msgf->lParam),
2367 y = GET_Y_LPARAM(msgf->lParam);
2368
2369 HandleMouseEvent(msg, x, y, flags);
2370 }
2371 }
2372
2373 // return true to process the event (and false to ignore it)
2374 return true;
2375
2376 case EN_LINK:
2377 {
2378 const ENLINK *enlink = (ENLINK *)hdr;
2379
2380 switch ( enlink->msg )
2381 {
2382 case WM_SETCURSOR:
2383 // ok, so it is hardcoded - do we really nee to
2384 // customize it?
2385 {
2386 wxCursor cur(wxCURSOR_HAND);
2387 ::SetCursor(GetHcursorOf(cur));
2388 *result = TRUE;
2389 break;
2390 }
2391
2392 case WM_MOUSEMOVE:
2393 case WM_LBUTTONDOWN:
2394 case WM_LBUTTONUP:
2395 case WM_LBUTTONDBLCLK:
2396 case WM_RBUTTONDOWN:
2397 case WM_RBUTTONUP:
2398 case WM_RBUTTONDBLCLK:
2399 // send a mouse event
2400 {
2401 static const wxEventType eventsMouse[] =
2402 {
2403 wxEVT_MOTION,
2404 wxEVT_LEFT_DOWN,
2405 wxEVT_LEFT_UP,
2406 wxEVT_LEFT_DCLICK,
2407 wxEVT_RIGHT_DOWN,
2408 wxEVT_RIGHT_UP,
2409 wxEVT_RIGHT_DCLICK,
2410 };
2411
2412 // the event ids are consecutive
2413 wxMouseEvent
2414 evtMouse(eventsMouse[enlink->msg - WM_MOUSEMOVE]);
2415
2416 InitMouseEvent(evtMouse,
2417 GET_X_LPARAM(enlink->lParam),
2418 GET_Y_LPARAM(enlink->lParam),
2419 enlink->wParam);
2420
2421 wxTextUrlEvent event(m_windowId, evtMouse,
2422 enlink->chrg.cpMin,
2423 enlink->chrg.cpMax);
2424
2425 InitCommandEvent(event);
2426
2427 *result = ProcessCommand(event);
2428 }
2429 break;
2430 }
2431 }
2432 return true;
2433 }
2434
2435 // not processed, leave it to the base class
2436 return wxTextCtrlBase::MSWOnNotify(idCtrl, lParam, result);
2437 }
2438
2439 #if wxUSE_DRAG_AND_DROP
2440
2441 void wxTextCtrl::SetDropTarget(wxDropTarget *dropTarget)
2442 {
2443 if ( m_dropTarget == wxRICHTEXT_DEFAULT_DROPTARGET )
2444 {
2445 // get rid of the built-in drop target
2446 ::RevokeDragDrop(GetHwnd());
2447 m_dropTarget = NULL;
2448 }
2449
2450 wxTextCtrlBase::SetDropTarget(dropTarget);
2451 }
2452
2453 #endif // wxUSE_DRAG_AND_DROP
2454
2455 // ----------------------------------------------------------------------------
2456 // colour setting for the rich edit controls
2457 // ----------------------------------------------------------------------------
2458
2459 bool wxTextCtrl::SetBackgroundColour(const wxColour& colour)
2460 {
2461 if ( !wxTextCtrlBase::SetBackgroundColour(colour) )
2462 {
2463 // colour didn't really change
2464 return false;
2465 }
2466
2467 if ( IsRich() )
2468 {
2469 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
2470 // EM_SETBKGNDCOLOR additionally
2471 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR, 0, wxColourToRGB(colour));
2472 }
2473
2474 return true;
2475 }
2476
2477 bool wxTextCtrl::SetForegroundColour(const wxColour& colour)
2478 {
2479 if ( !wxTextCtrlBase::SetForegroundColour(colour) )
2480 {
2481 // colour didn't really change
2482 return false;
2483 }
2484
2485 if ( IsRich() )
2486 {
2487 // change the colour of everything
2488 CHARFORMAT cf;
2489 wxZeroMemory(cf);
2490 cf.cbSize = sizeof(cf);
2491 cf.dwMask = CFM_COLOR;
2492 cf.crTextColor = wxColourToRGB(colour);
2493 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf);
2494 }
2495
2496 return true;
2497 }
2498
2499 // ----------------------------------------------------------------------------
2500 // styling support for rich edit controls
2501 // ----------------------------------------------------------------------------
2502
2503 #if wxUSE_RICHEDIT
2504
2505 bool wxTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
2506 {
2507 if ( !IsRich() )
2508 {
2509 // can't do it with normal text control
2510 return false;
2511 }
2512
2513 // the richedit 1.0 doesn't handle setting background colour, so don't
2514 // even try to do anything if it's the only thing we want to change
2515 if ( m_verRichEdit == 1 && !style.HasFont() && !style.HasTextColour() &&
2516 !style.HasLeftIndent() && !style.HasRightIndent() && !style.HasAlignment() &&
2517 !style.HasTabs() )
2518 {
2519 // nothing to do: return true if there was really nothing to do and
2520 // false if we failed to set bg colour
2521 return !style.HasBackgroundColour();
2522 }
2523
2524 // order the range if needed
2525 if ( start > end )
2526 {
2527 long tmp = start;
2528 start = end;
2529 end = tmp;
2530 }
2531
2532 // we can only change the format of the selection, so select the range we
2533 // want and restore the old selection later
2534 long startOld, endOld;
2535 GetSelection(&startOld, &endOld);
2536
2537 // but do we really have to change the selection?
2538 bool changeSel = start != startOld || end != endOld;
2539
2540 if ( changeSel )
2541 {
2542 DoSetSelection(start, end, false /* don't scroll caret into view */);
2543 }
2544
2545 // initialize CHARFORMAT struct
2546 #if wxUSE_RICHEDIT2
2547 CHARFORMAT2 cf;
2548 #else
2549 CHARFORMAT cf;
2550 #endif
2551
2552 wxZeroMemory(cf);
2553
2554 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2555 // CHARFORMAT in that case
2556 #if wxUSE_RICHEDIT2
2557 if ( m_verRichEdit == 1 )
2558 {
2559 // this is the only thing the control is going to grok
2560 cf.cbSize = sizeof(CHARFORMAT);
2561 }
2562 else
2563 #endif
2564 {
2565 // CHARFORMAT or CHARFORMAT2
2566 cf.cbSize = sizeof(cf);
2567 }
2568
2569 if ( style.HasFont() )
2570 {
2571 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
2572 // but using it doesn't seem to hurt neither so leaving it for now
2573
2574 cf.dwMask |= CFM_FACE | CFM_SIZE | CFM_CHARSET |
2575 CFM_ITALIC | CFM_BOLD | CFM_UNDERLINE;
2576
2577 // fill in data from LOGFONT but recalculate lfHeight because we need
2578 // the real height in twips and not the negative number which
2579 // wxFillLogFont() returns (this is correct in general and works with
2580 // the Windows font mapper, but not here)
2581 LOGFONT lf;
2582 wxFillLogFont(&lf, &style.GetFont());
2583 cf.yHeight = 20*style.GetFont().GetPointSize(); // 1 pt = 20 twips
2584 cf.bCharSet = lf.lfCharSet;
2585 cf.bPitchAndFamily = lf.lfPitchAndFamily;
2586 wxStrncpy( cf.szFaceName, lf.lfFaceName, WXSIZEOF(cf.szFaceName) );
2587
2588 // also deal with underline/italic/bold attributes: note that we must
2589 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
2590 // style to allow clearing it
2591 if ( lf.lfItalic )
2592 {
2593 cf.dwEffects |= CFE_ITALIC;
2594 }
2595
2596 if ( lf.lfWeight == FW_BOLD )
2597 {
2598 cf.dwEffects |= CFE_BOLD;
2599 }
2600
2601 if ( lf.lfUnderline )
2602 {
2603 cf.dwEffects |= CFE_UNDERLINE;
2604 }
2605
2606 // strikeout fonts are not supported by wxWidgets
2607 }
2608
2609 if ( style.HasTextColour() )
2610 {
2611 cf.dwMask |= CFM_COLOR;
2612 cf.crTextColor = wxColourToRGB(style.GetTextColour());
2613 }
2614
2615 #if wxUSE_RICHEDIT2
2616 if ( m_verRichEdit != 1 && style.HasBackgroundColour() )
2617 {
2618 cf.dwMask |= CFM_BACKCOLOR;
2619 cf.crBackColor = wxColourToRGB(style.GetBackgroundColour());
2620 }
2621 #endif // wxUSE_RICHEDIT2
2622
2623 // do format the selection
2624 bool ok = ::SendMessage(GetHwnd(), EM_SETCHARFORMAT,
2625 SCF_SELECTION, (LPARAM)&cf) != 0;
2626 if ( !ok )
2627 {
2628 wxLogDebug(_T("SendMessage(EM_SETCHARFORMAT, SCF_SELECTION) failed"));
2629 }
2630
2631 // now do the paragraph formatting
2632 PARAFORMAT2 pf;
2633 wxZeroMemory(pf);
2634 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2635 // PARAFORMAT in that case
2636 #if wxUSE_RICHEDIT2
2637 if ( m_verRichEdit == 1 )
2638 {
2639 // this is the only thing the control is going to grok
2640 pf.cbSize = sizeof(PARAFORMAT);
2641 }
2642 else
2643 #endif
2644 {
2645 // PARAFORMAT or PARAFORMAT2
2646 pf.cbSize = sizeof(pf);
2647 }
2648
2649 if (style.HasAlignment())
2650 {
2651 pf.dwMask |= PFM_ALIGNMENT;
2652 if (style.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT)
2653 pf.wAlignment = PFA_RIGHT;
2654 else if (style.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE)
2655 pf.wAlignment = PFA_CENTER;
2656 else if (style.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED)
2657 pf.wAlignment = PFA_JUSTIFY;
2658 else
2659 pf.wAlignment = PFA_LEFT;
2660 }
2661
2662 if (style.HasLeftIndent())
2663 {
2664 pf.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
2665
2666 // Convert from 1/10 mm to TWIPS
2667 pf.dxStartIndent = (int) (((double) style.GetLeftIndent()) * mm2twips / 10.0) ;
2668 pf.dxOffset = (int) (((double) style.GetLeftSubIndent()) * mm2twips / 10.0) ;
2669 }
2670
2671 if (style.HasRightIndent())
2672 {
2673 pf.dwMask |= PFM_RIGHTINDENT;
2674
2675 // Convert from 1/10 mm to TWIPS
2676 pf.dxRightIndent = (int) (((double) style.GetRightIndent()) * mm2twips / 10.0) ;
2677 }
2678
2679 if (style.HasTabs())
2680 {
2681 pf.dwMask |= PFM_TABSTOPS;
2682
2683 const wxArrayInt& tabs = style.GetTabs();
2684
2685 pf.cTabCount = (SHORT)wxMin(tabs.GetCount(), MAX_TAB_STOPS);
2686 size_t i;
2687 for (i = 0; i < (size_t) pf.cTabCount; i++)
2688 {
2689 // Convert from 1/10 mm to TWIPS
2690 pf.rgxTabs[i] = (int) (((double) tabs[i]) * mm2twips / 10.0) ;
2691 }
2692 }
2693
2694 #if wxUSE_RICHEDIT2
2695 if ( m_verRichEdit > 1 )
2696 {
2697 if ( wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft )
2698 {
2699 // Use RTL paragraphs in RTL mode to get proper layout
2700 pf.dwMask |= PFM_RTLPARA;
2701 pf.wEffects |= PFE_RTLPARA;
2702 }
2703 }
2704 #endif // wxUSE_RICHEDIT2
2705
2706 if ( pf.dwMask )
2707 {
2708 // do format the selection
2709 bool ok = ::SendMessage(GetHwnd(), EM_SETPARAFORMAT,
2710 0, (LPARAM) &pf) != 0;
2711 if ( !ok )
2712 {
2713 wxLogDebug(_T("SendMessage(EM_SETPARAFORMAT, 0) failed"));
2714 }
2715 }
2716
2717 if ( changeSel )
2718 {
2719 // restore the original selection
2720 DoSetSelection(startOld, endOld, false);
2721 }
2722
2723 return ok;
2724 }
2725
2726 bool wxTextCtrl::SetDefaultStyle(const wxTextAttr& style)
2727 {
2728 if ( !wxTextCtrlBase::SetDefaultStyle(style) )
2729 return false;
2730
2731 if ( IsEditable() )
2732 {
2733 // we have to do this or the style wouldn't apply for the text typed by
2734 // the user
2735 wxTextPos posLast = GetLastPosition();
2736 SetStyle(posLast, posLast, m_defaultStyle);
2737 }
2738
2739 return true;
2740 }
2741
2742 bool wxTextCtrl::GetStyle(long position, wxTextAttr& style)
2743 {
2744 if ( !IsRich() )
2745 {
2746 // can't do it with normal text control
2747 return false;
2748 }
2749
2750 // initialize CHARFORMAT struct
2751 #if wxUSE_RICHEDIT2
2752 CHARFORMAT2 cf;
2753 #else
2754 CHARFORMAT cf;
2755 #endif
2756
2757 wxZeroMemory(cf);
2758
2759 // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple
2760 // CHARFORMAT in that case
2761 #if wxUSE_RICHEDIT2
2762 if ( m_verRichEdit == 1 )
2763 {
2764 // this is the only thing the control is going to grok
2765 cf.cbSize = sizeof(CHARFORMAT);
2766 }
2767 else
2768 #endif
2769 {
2770 // CHARFORMAT or CHARFORMAT2
2771 cf.cbSize = sizeof(cf);
2772 }
2773 // we can only change the format of the selection, so select the range we
2774 // want and restore the old selection later
2775 long startOld, endOld;
2776 GetSelection(&startOld, &endOld);
2777
2778 // but do we really have to change the selection?
2779 bool changeSel = position != startOld || position != endOld;
2780
2781 if ( changeSel )
2782 {
2783 DoSetSelection(position, position+1, false /* don't scroll caret into view */);
2784 }
2785
2786 // get the selection formatting
2787 (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT,
2788 SCF_SELECTION, (LPARAM)&cf) ;
2789
2790
2791 LOGFONT lf;
2792 lf.lfHeight = cf.yHeight;
2793 lf.lfWidth = 0;
2794 lf.lfCharSet = ANSI_CHARSET; // FIXME: how to get correct charset?
2795 lf.lfClipPrecision = 0;
2796 lf.lfEscapement = 0;
2797 wxStrcpy(lf.lfFaceName, cf.szFaceName);
2798
2799 //NOTE: we _MUST_ set each of these values to _something_ since we
2800 //do not call wxZeroMemory on the LOGFONT lf
2801 if (cf.dwEffects & CFE_ITALIC)
2802 lf.lfItalic = TRUE;
2803 else
2804 lf.lfItalic = FALSE;
2805
2806 lf.lfOrientation = 0;
2807 lf.lfPitchAndFamily = cf.bPitchAndFamily;
2808 lf.lfQuality = 0;
2809
2810 if (cf.dwEffects & CFE_STRIKEOUT)
2811 lf.lfStrikeOut = TRUE;
2812 else
2813 lf.lfStrikeOut = FALSE;
2814
2815 if (cf.dwEffects & CFE_UNDERLINE)
2816 lf.lfUnderline = TRUE;
2817 else
2818 lf.lfUnderline = FALSE;
2819
2820 if (cf.dwEffects & CFE_BOLD)
2821 lf.lfWeight = FW_BOLD;
2822 else
2823 lf.lfWeight = FW_NORMAL;
2824
2825 wxFont font = wxCreateFontFromLogFont(& lf);
2826 if (font.Ok())
2827 {
2828 style.SetFont(font);
2829 }
2830 style.SetTextColour(wxColour(cf.crTextColor));
2831
2832 #if wxUSE_RICHEDIT2
2833 if ( m_verRichEdit != 1 )
2834 {
2835 // cf.dwMask |= CFM_BACKCOLOR;
2836 style.SetBackgroundColour(wxColour(cf.crBackColor));
2837 }
2838 #endif // wxUSE_RICHEDIT2
2839
2840 // now get the paragraph formatting
2841 PARAFORMAT2 pf;
2842 wxZeroMemory(pf);
2843 // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple
2844 // PARAFORMAT in that case
2845 #if wxUSE_RICHEDIT2
2846 if ( m_verRichEdit == 1 )
2847 {
2848 // this is the only thing the control is going to grok
2849 pf.cbSize = sizeof(PARAFORMAT);
2850 }
2851 else
2852 #endif
2853 {
2854 // PARAFORMAT or PARAFORMAT2
2855 pf.cbSize = sizeof(pf);
2856 }
2857
2858 // do format the selection
2859 (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT, 0, (LPARAM) &pf) ;
2860
2861 style.SetLeftIndent( (int) ((double) pf.dxStartIndent * twips2mm * 10.0), (int) ((double) pf.dxOffset * twips2mm * 10.0) );
2862 style.SetRightIndent( (int) ((double) pf.dxRightIndent * twips2mm * 10.0) );
2863
2864 if (pf.wAlignment == PFA_CENTER)
2865 style.SetAlignment(wxTEXT_ALIGNMENT_CENTRE);
2866 else if (pf.wAlignment == PFA_RIGHT)
2867 style.SetAlignment(wxTEXT_ALIGNMENT_RIGHT);
2868 else if (pf.wAlignment == PFA_JUSTIFY)
2869 style.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED);
2870 else
2871 style.SetAlignment(wxTEXT_ALIGNMENT_LEFT);
2872
2873 wxArrayInt tabStops;
2874 size_t i;
2875 for (i = 0; i < (size_t) pf.cTabCount; i++)
2876 {
2877 tabStops.Add( (int) ((double) (pf.rgxTabs[i] & 0xFFFF) * twips2mm * 10.0) );
2878 }
2879
2880 if ( changeSel )
2881 {
2882 // restore the original selection
2883 DoSetSelection(startOld, endOld, false);
2884 }
2885
2886 return true;
2887 }
2888
2889 #endif
2890
2891 // ----------------------------------------------------------------------------
2892 // wxRichEditModule
2893 // ----------------------------------------------------------------------------
2894
2895 static const HINSTANCE INVALID_HINSTANCE = (HINSTANCE)-1;
2896
2897 bool wxRichEditModule::OnInit()
2898 {
2899 // don't do anything - we will load it when needed
2900 return true;
2901 }
2902
2903 void wxRichEditModule::OnExit()
2904 {
2905 for ( size_t i = 0; i < WXSIZEOF(ms_hRichEdit); i++ )
2906 {
2907 if ( ms_hRichEdit[i] && ms_hRichEdit[i] != INVALID_HINSTANCE )
2908 {
2909 ::FreeLibrary(ms_hRichEdit[i]);
2910 ms_hRichEdit[i] = NULL;
2911 }
2912 }
2913 #if wxUSE_INKEDIT
2914 if (ms_inkEditLib.IsLoaded())
2915 ms_inkEditLib.Unload();
2916 #endif
2917 }
2918
2919 /* static */
2920 bool wxRichEditModule::Load(Version version)
2921 {
2922 if ( ms_hRichEdit[version] == INVALID_HINSTANCE )
2923 {
2924 // we had already tried to load it and failed
2925 return false;
2926 }
2927
2928 if ( ms_hRichEdit[version] )
2929 {
2930 // we've already got this one
2931 return true;
2932 }
2933
2934 static const wxChar *dllnames[] =
2935 {
2936 _T("riched32"),
2937 _T("riched20"),
2938 _T("msftedit"),
2939 };
2940
2941 wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames) == Version_Max,
2942 RichEditDllNamesVersionsMismatch );
2943
2944 ms_hRichEdit[version] = ::LoadLibrary(dllnames[version]);
2945
2946 if ( !ms_hRichEdit[version] )
2947 {
2948 ms_hRichEdit[version] = INVALID_HINSTANCE;
2949
2950 return false;
2951 }
2952
2953 return true;
2954 }
2955
2956 #if wxUSE_INKEDIT
2957 // load the InkEdit library
2958 bool wxRichEditModule::LoadInkEdit()
2959 {
2960 static wxDynamicLibrary ms_inkEditLib;
2961 static bool ms_inkEditLibLoadAttemped;
2962 if (ms_inkEditLibLoadAttemped)
2963 ms_inkEditLib.IsLoaded();
2964
2965 ms_inkEditLibLoadAttemped = true;
2966
2967 wxLogNull logNull;
2968 return ms_inkEditLib.Load(wxT("inked"));
2969 }
2970 #endif
2971
2972
2973 #endif // wxUSE_RICHEDIT
2974
2975 #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)