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