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