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