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