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