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