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