]> git.saurik.com Git - wxWidgets.git/blob - src/msw/textctrl.cpp
b8b44e6c6d3a4b2c8bb006c39fac51681136386b
[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 and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 #ifdef __GNUG__
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 #endif
42
43 #include "wx/module.h"
44
45 #if wxUSE_CLIPBOARD
46 #include "wx/clipbrd.h"
47 #endif
48
49 #include "wx/textfile.h"
50
51 #include <windowsx.h>
52
53 #include "wx/msw/private.h"
54
55 #include <string.h>
56 #include <stdlib.h>
57 #include <sys/types.h>
58
59 #if wxUSE_RICHEDIT && (!defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__))
60 #include <richedit.h>
61 #endif
62
63 // old mingw32 doesn't define this
64 #ifndef CFM_CHARSET
65 #define CFM_CHARSET 0x08000000
66 #endif // CFM_CHARSET
67
68 #ifndef CFM_BACKCOLOR
69 #define CFM_BACKCOLOR 0x04000000
70 #endif
71
72 // cygwin does not have these defined for richedit
73 #ifndef ENM_LINK
74 #define ENM_LINK 0x04000000
75 #endif
76
77 #ifndef EM_AUTOURLDETECT
78 #define EM_AUTOURLDETECT (WM_USER + 91)
79 #endif
80
81 #ifndef EN_LINK
82 #define EN_LINK 0x070b
83
84 typedef struct _enlink
85 {
86 NMHDR nmhdr;
87 UINT msg;
88 WPARAM wParam;
89 LPARAM lParam;
90 CHARRANGE chrg;
91 } ENLINK;
92 #endif // ENLINK
93
94 // ----------------------------------------------------------------------------
95 // private functions
96 // ----------------------------------------------------------------------------
97
98 #if wxUSE_RICHEDIT
99
100 DWORD CALLBACK wxRichEditStreamIn(DWORD dwCookie, BYTE *buf, LONG cb, LONG *pcb);
101
102 #endif // wxUSE_RICHEDIT
103
104 // ----------------------------------------------------------------------------
105 // private classes
106 // ----------------------------------------------------------------------------
107
108 #if wxUSE_RICHEDIT
109
110 // this module initializes RichEdit DLL if needed
111 class wxRichEditModule : public wxModule
112 {
113 public:
114 virtual bool OnInit();
115 virtual void OnExit();
116
117 // get the version currently loaded, -1 if none
118 static int GetLoadedVersion() { return ms_verRichEdit; }
119
120 // load the richedit DLL of at least of required version
121 static bool Load(int version = 1);
122
123 private:
124 // the handle to richedit DLL and the version of the DLL loaded
125 static HINSTANCE ms_hRichEdit;
126
127 // the DLL version loaded or -1 if none
128 static int ms_verRichEdit;
129
130 DECLARE_DYNAMIC_CLASS(wxRichEditModule)
131 };
132
133 HINSTANCE wxRichEditModule::ms_hRichEdit = (HINSTANCE)NULL;
134 int wxRichEditModule::ms_verRichEdit = -1;
135
136 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule, wxModule)
137
138 #endif // wxUSE_RICHEDIT
139
140 // ----------------------------------------------------------------------------
141 // event tables and other macros
142 // ----------------------------------------------------------------------------
143
144 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxControl)
145
146 BEGIN_EVENT_TABLE(wxTextCtrl, wxControl)
147 EVT_CHAR(wxTextCtrl::OnChar)
148 EVT_DROP_FILES(wxTextCtrl::OnDropFiles)
149
150 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
151 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
152 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
153 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
154 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
155
156 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
157 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
158 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
159 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
160 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
161 #ifdef __WIN16__
162 EVT_ERASE_BACKGROUND(wxTextCtrl::OnEraseBackground)
163 #endif
164 END_EVENT_TABLE()
165
166 // ============================================================================
167 // implementation
168 // ============================================================================
169
170 // ----------------------------------------------------------------------------
171 // creation
172 // ----------------------------------------------------------------------------
173
174 void wxTextCtrl::Init()
175 {
176 #if wxUSE_RICHEDIT
177 m_verRichEdit = 0;
178 #endif
179 }
180
181 bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id,
182 const wxString& value,
183 const wxPoint& pos,
184 const wxSize& size,
185 long style,
186 const wxValidator& validator,
187 const wxString& name)
188 {
189 // base initialization
190 if ( !CreateBase(parent, id, pos, size, style, validator, name) )
191 return FALSE;
192
193 if ( parent )
194 parent->AddChild(this);
195
196 // translate wxWin style flags to MSW ones, checking for consistency while
197 // doing it
198 long msStyle = ES_LEFT | WS_TABSTOP;
199
200 if ( m_windowStyle & wxCLIP_SIBLINGS )
201 msStyle |= WS_CLIPSIBLINGS;
202
203 if ( m_windowStyle & wxTE_MULTILINE )
204 {
205 wxASSERT_MSG( !(m_windowStyle & wxTE_PROCESS_ENTER),
206 wxT("wxTE_PROCESS_ENTER style is ignored for multiline text controls (they always process it)") );
207
208 msStyle |= ES_MULTILINE | ES_WANTRETURN;
209 if ((m_windowStyle & wxTE_NO_VSCROLL) == 0)
210 msStyle |= WS_VSCROLL;
211 m_windowStyle |= wxTE_PROCESS_ENTER;
212 }
213 else // !multiline
214 {
215 // there is really no reason to not have this style for single line
216 // text controls
217 msStyle |= ES_AUTOHSCROLL;
218 }
219
220 if ( m_windowStyle & wxHSCROLL )
221 msStyle |= WS_HSCROLL | ES_AUTOHSCROLL;
222
223 if ( m_windowStyle & wxTE_READONLY )
224 msStyle |= ES_READONLY;
225
226 if ( m_windowStyle & wxTE_PASSWORD )
227 msStyle |= ES_PASSWORD;
228
229 if ( m_windowStyle & wxTE_AUTO_SCROLL )
230 msStyle |= ES_AUTOHSCROLL;
231
232 if ( m_windowStyle & wxTE_NOHIDESEL )
233 msStyle |= ES_NOHIDESEL;
234
235 // we always want the characters and the arrows
236 m_lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS;
237
238 // we may have several different cases:
239 // 1. normal case: both TAB and ENTER are used for dialog navigation
240 // 2. ctrl which wants TAB for itself: ENTER is used to pass to the next
241 // control in the dialog
242 // 3. ctrl which wants ENTER for itself: TAB is used for dialog navigation
243 // 4. ctrl which wants both TAB and ENTER: Ctrl-ENTER is used to pass to
244 // the next control
245 if ( m_windowStyle & wxTE_PROCESS_ENTER )
246 m_lDlgCode |= DLGC_WANTMESSAGE;
247 if ( m_windowStyle & wxTE_PROCESS_TAB )
248 m_lDlgCode |= DLGC_WANTTAB;
249
250 // do create the control - either an EDIT or RICHEDIT
251 wxString windowClass = wxT("EDIT");
252
253 #if wxUSE_RICHEDIT
254 if ( m_windowStyle & wxTE_RICH )
255 {
256 static bool s_errorGiven = FALSE; // MT-FIXME
257
258 // only give the error msg once if the DLL can't be loaded
259 if ( !s_errorGiven )
260 {
261 // first try to load the RichEdit DLL (will do nothing if already
262 // done)
263 if ( !wxRichEditModule::Load() )
264 {
265 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
266
267 s_errorGiven = TRUE;
268 }
269 }
270
271 if ( !s_errorGiven )
272 {
273 msStyle |= ES_AUTOVSCROLL;
274
275 m_verRichEdit = wxRichEditModule::GetLoadedVersion();
276 if ( m_verRichEdit == 1 )
277 {
278 windowClass = wxT("RICHEDIT");
279 }
280 else
281 {
282 #ifndef RICHEDIT_CLASS
283 wxString RICHEDIT_CLASS;
284 RICHEDIT_CLASS.Printf(_T("RichEdit%d0"), m_verRichEdit);
285 #if wxUSE_UNICODE
286 RICHEDIT_CLASS += _T('W');
287 #else // ANSI
288 RICHEDIT_CLASS += _T('A');
289 #endif // Unicode/ANSI
290 #endif // !RICHEDIT_CLASS
291
292 windowClass = RICHEDIT_CLASS;
293 }
294 }
295 }
296 #endif // wxUSE_RICHEDIT
297
298 // we need to turn '\n's into "\r\n"s for the multiline controls
299 wxString valueWin;
300 if ( m_windowStyle & wxTE_MULTILINE )
301 {
302 valueWin = wxTextFile::Translate(value, wxTextFileType_Dos);
303 }
304 else // single line
305 {
306 valueWin = value;
307 }
308
309 if ( !MSWCreateControl(windowClass, msStyle, pos, size, valueWin) )
310 return FALSE;
311
312 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW));
313
314 #if wxUSE_RICHEDIT
315 if ( IsRich() )
316 {
317 // have to enable events manually
318 LPARAM mask = ENM_CHANGE | ENM_DROPFILES | ENM_SELCHANGE | ENM_UPDATE;
319
320 if ( m_windowStyle & wxTE_AUTO_URL )
321 {
322 mask |= ENM_LINK;
323
324 ::SendMessage(GetHwnd(), EM_AUTOURLDETECT, TRUE, 0);
325 }
326
327 ::SendMessage(GetHwnd(), EM_SETEVENTMASK, 0, mask);
328 }
329 #endif // wxUSE_RICHEDIT
330
331 return TRUE;
332 }
333
334 // Make sure the window style (etc.) reflects the HWND style (roughly)
335 void wxTextCtrl::AdoptAttributesFromHWND()
336 {
337 wxWindow::AdoptAttributesFromHWND();
338
339 HWND hWnd = GetHwnd();
340 long style = ::GetWindowLong(hWnd, GWL_STYLE);
341
342 // retrieve the style to see whether this is an edit or richedit ctrl
343 #if wxUSE_RICHEDIT
344 wxString classname = wxGetWindowClass(GetHWND());
345
346 if ( classname.IsSameAs(_T("EDIT"), FALSE /* no case */) )
347 {
348 m_verRichEdit = 0;
349 }
350 else // rich edit?
351 {
352 wxChar c;
353 if ( wxSscanf(classname, _T("RichEdit%d0%c"), &m_verRichEdit, &c) != 2 )
354 {
355 wxLogDebug(_T("Unknown edit control '%s'."), classname.c_str());
356
357 m_verRichEdit = 0;
358 }
359 }
360 #endif // wxUSE_RICHEDIT
361
362 if (style & ES_MULTILINE)
363 m_windowStyle |= wxTE_MULTILINE;
364 if (style & ES_PASSWORD)
365 m_windowStyle |= wxTE_PASSWORD;
366 if (style & ES_READONLY)
367 m_windowStyle |= wxTE_READONLY;
368 if (style & ES_WANTRETURN)
369 m_windowStyle |= wxTE_PROCESS_ENTER;
370 }
371
372 // ----------------------------------------------------------------------------
373 // set/get the controls text
374 // ----------------------------------------------------------------------------
375
376 wxString wxTextCtrl::GetValue() const
377 {
378 // we can't use wxGetWindowText() (i.e. WM_GETTEXT internally) for
379 // retrieving more than 64Kb under Win9x
380 #if wxUSE_RICHEDIT
381 if ( IsRich() )
382 {
383 wxString str;
384
385 int len = GetWindowTextLength(GetHwnd());
386 if ( len )
387 {
388 // alloc one extra WORD as needed by the control
389 wxChar *p = str.GetWriteBuf(++len);
390
391 TEXTRANGE textRange;
392 textRange.chrg.cpMin = 0;
393 textRange.chrg.cpMax = -1;
394 textRange.lpstrText = p;
395
396 (void)SendMessage(GetHwnd(), EM_GETTEXTRANGE, 0, (LPARAM)&textRange);
397
398 // believe it or not, but EM_GETTEXTRANGE uses just CR ('\r') for
399 // the newlines which is neither Unix nor Windows style (Win95 with
400 // riched20.dll shows this behaviour) - convert it to something
401 // reasonable
402 for ( ; *p; p++ )
403 {
404 if ( *p == _T('\r') )
405 *p = _T('\n');
406 }
407
408 str.UngetWriteBuf();
409 }
410 //else: no text at all, leave the string empty
411
412 return str;
413 }
414 #endif // wxUSE_RICHEDIT
415
416 // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the
417 // same one as above for consitency
418 wxString str = wxGetWindowText(GetHWND());
419
420 return wxTextFile::Translate(str, wxTextFileType_Unix);
421 }
422
423 void wxTextCtrl::SetValue(const wxString& value)
424 {
425 // if the text is long enough, it's faster to just set it instead of first
426 // comparing it with the old one (chances are that it will be different
427 // anyhow, this comparison is there to avoid flicker for small single-line
428 // edit controls mostly)
429 if ( (value.length() > 0x400) || (value != GetValue()) )
430 {
431 // it is simpler to do this but it could be more efficient to reproduce
432 // WriteText() logic here
433 Clear();
434
435 WriteText(value);
436 }
437 }
438
439 #if wxUSE_RICHEDIT
440
441 DWORD CALLBACK wxRichEditStreamIn(DWORD dwCookie, BYTE *buf, LONG cb, LONG *pcb)
442 {
443 *pcb = 0;
444
445 wchar_t *wbuf = (wchar_t *)buf;
446 const wchar_t *wpc = *(const wchar_t **)dwCookie;
447 while ( cb && *wpc )
448 {
449 *wbuf++ = *wpc++;
450
451 cb -= sizeof(wchar_t);
452 (*pcb) += sizeof(wchar_t);
453 }
454
455 *(const wchar_t **)dwCookie = wpc;
456
457 return 0;
458 }
459
460 extern long wxEncodingToCodepage(wxFontEncoding encoding); // from strconv.cpp
461
462 bool wxTextCtrl::StreamIn(const wxString& value, wxFontEncoding encoding)
463 {
464 // we have to use EM_STREAMIN to force richedit control 2.0+ to show any
465 // text in the non default charset - otherwise it thinks it knows better
466 // than we do and always shows it in the default one
467
468 // first get the Windows code page for this encoding
469 long codepage = wxEncodingToCodepage(encoding);
470 if ( codepage == -1 )
471 {
472 // unknown encoding
473 return FALSE;
474 }
475
476 // next translate to Unicode using this code page
477 int len = ::MultiByteToWideChar(codepage, 0, value, -1, NULL, 0);
478 wxWCharBuffer wchBuf(len);
479 if ( !::MultiByteToWideChar(codepage, 0, value, -1,
480 (wchar_t *)wchBuf.data(), len) )
481 {
482 wxLogLastError(_T("MultiByteToWideChar"));
483 }
484
485 // finally, stream it in the control
486 const wchar_t *wpc = wchBuf;
487
488 EDITSTREAM eds;
489 wxZeroMemory(eds);
490 eds.dwCookie = (DWORD)&wpc;
491 eds.pfnCallback = wxRichEditStreamIn;
492
493 if ( !::SendMessage(GetHwnd(), EM_STREAMIN,
494 SF_TEXT | SF_UNICODE | SFF_SELECTION,
495 (LPARAM)&eds) || eds.dwError )
496 {
497 wxLogLastError(_T("EM_STREAMIN"));
498
499 return FALSE;
500 }
501
502 return TRUE;
503 }
504
505 #endif // wxUSE_RICHEDIT
506
507 void wxTextCtrl::WriteText(const wxString& value)
508 {
509 wxString valueDos = wxTextFile::Translate(value, wxTextFileType_Dos);
510
511 #if wxUSE_RICHEDIT
512 // there are several complications with the rich edit controls here
513 bool done = FALSE;
514 if ( IsRich() )
515 {
516 // first, ensure that the new text will be in the default style
517 if ( !m_defaultStyle.IsDefault() )
518 {
519 long start, end;
520 GetSelection(&start, &end);
521 SetStyle(start, end, m_defaultStyle );
522 }
523
524 // next check if the text we're inserting must be shown in a non
525 // default charset -- this only works for RichEdit > 1.0
526 if ( GetRichVersion() > 1 )
527 {
528 wxFont font = m_defaultStyle.GetFont();
529 if ( !font.Ok() )
530 font = GetFont();
531
532 if ( font.Ok() )
533 {
534 wxFontEncoding encoding = font.GetEncoding();
535 if ( encoding != wxFONTENCODING_SYSTEM )
536 {
537 done = StreamIn(valueDos, encoding);
538 }
539 }
540 }
541 }
542
543 if ( !done )
544 #endif // wxUSE_RICHEDIT
545 {
546 ::SendMessage(GetHwnd(), EM_REPLACESEL, 0, (LPARAM)valueDos.c_str());
547 }
548
549 AdjustSpaceLimit();
550 }
551
552 void wxTextCtrl::AppendText(const wxString& text)
553 {
554 SetInsertionPointEnd();
555
556 WriteText(text);
557 }
558
559 void wxTextCtrl::Clear()
560 {
561 ::SetWindowText(GetHwnd(), wxT(""));
562 }
563
564 // ----------------------------------------------------------------------------
565 // Clipboard operations
566 // ----------------------------------------------------------------------------
567
568 void wxTextCtrl::Copy()
569 {
570 if (CanCopy())
571 {
572 HWND hWnd = GetHwnd();
573 SendMessage(hWnd, WM_COPY, 0, 0L);
574 }
575 }
576
577 void wxTextCtrl::Cut()
578 {
579 if (CanCut())
580 {
581 HWND hWnd = GetHwnd();
582 SendMessage(hWnd, WM_CUT, 0, 0L);
583 }
584 }
585
586 void wxTextCtrl::Paste()
587 {
588 if (CanPaste())
589 {
590 HWND hWnd = GetHwnd();
591 SendMessage(hWnd, WM_PASTE, 0, 0L);
592 }
593 }
594
595 bool wxTextCtrl::CanCopy() const
596 {
597 // Can copy if there's a selection
598 long from, to;
599 GetSelection(& from, & to);
600 return (from != to) ;
601 }
602
603 bool wxTextCtrl::CanCut() const
604 {
605 // Can cut if there's a selection
606 long from, to;
607 GetSelection(& from, & to);
608 return (from != to) && (IsEditable());
609 }
610
611 bool wxTextCtrl::CanPaste() const
612 {
613 if ( !IsEditable() )
614 return FALSE;
615
616 #if wxUSE_RICHEDIT
617 if ( IsRich() )
618 {
619 UINT cf = 0; // 0 == any format
620
621 return ::SendMessage(GetHwnd(), EM_CANPASTE, cf, 0) != 0;
622 }
623 #endif // wxUSE_RICHEDIT
624
625 // Standard edit control: check for straight text on clipboard
626 if ( !::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) )
627 return FALSE;
628
629 bool isTextAvailable = ::IsClipboardFormatAvailable(CF_TEXT) != 0;
630 ::CloseClipboard();
631
632 return isTextAvailable;
633 }
634
635 // ----------------------------------------------------------------------------
636 // Accessors
637 // ----------------------------------------------------------------------------
638
639 void wxTextCtrl::SetEditable(bool editable)
640 {
641 HWND hWnd = GetHwnd();
642 SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
643 }
644
645 void wxTextCtrl::SetInsertionPoint(long pos)
646 {
647 SetSelection(pos, pos);
648
649 #if wxUSE_RICHEDIT
650 if ( !IsRich() )
651 #endif
652 {
653 static const wxChar *nothing = _T("");
654 SendMessage(GetHwnd(), EM_REPLACESEL, 0, (LPARAM)nothing);
655 }
656 }
657
658 void wxTextCtrl::SetInsertionPointEnd()
659 {
660 long pos = GetLastPosition();
661 SetInsertionPoint(pos);
662 }
663
664 long wxTextCtrl::GetInsertionPoint() const
665 {
666 #if wxUSE_RICHEDIT
667 if ( IsRich() )
668 {
669 CHARRANGE range;
670 range.cpMin = 0;
671 range.cpMax = 0;
672 SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range);
673 return range.cpMin;
674 }
675 #endif // wxUSE_RICHEDIT
676
677 DWORD Pos = (DWORD)SendMessage(GetHwnd(), EM_GETSEL, 0, 0L);
678 return Pos & 0xFFFF;
679 }
680
681 long wxTextCtrl::GetLastPosition() const
682 {
683 HWND hWnd = GetHwnd();
684
685 // Will always return a number > 0 (according to docs)
686 int noLines = (int)SendMessage(hWnd, EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0L);
687
688 // This gets the char index for the _beginning_ of the last line
689 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)(noLines-1), (LPARAM)0L);
690
691 // Get number of characters in the last line. We'll add this to the character
692 // index for the last line, 1st position.
693 int lineLength = (int)SendMessage(hWnd, EM_LINELENGTH, (WPARAM)charIndex, (LPARAM)0L);
694
695 return (long)(charIndex + lineLength);
696 }
697
698 // If the return values from and to are the same, there is no
699 // selection.
700 void wxTextCtrl::GetSelection(long* from, long* to) const
701 {
702 #if wxUSE_RICHEDIT
703 if ( IsRich() )
704 {
705 CHARRANGE charRange;
706 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &charRange);
707
708 *from = charRange.cpMin;
709 *to = charRange.cpMax;
710 }
711 else
712 #endif // !wxUSE_RICHEDIT
713 {
714 DWORD dwStart, dwEnd;
715 ::SendMessage(GetHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd);
716
717 *from = dwStart;
718 *to = dwEnd;
719 }
720 }
721
722 wxString wxTextCtrl::GetStringSelection() const
723 {
724 // the base class version works correctly for the rich text controls
725 // because there the lines are terminated with just '\r' which means that
726 // the string length is not changed in the result of the translations doen
727 // in GetValue() but for the normal ones when we replace "\r\n" with '\n'
728 // we break the indices
729 #if wxUSE_RICHEDIT
730 if ( IsRich() )
731 return wxTextCtrlBase::GetStringSelection();
732 #endif // wxUSE_RICHEDIT
733
734 long from, to;
735 GetSelection(&from, &to);
736
737 wxString str;
738 if ( from < to )
739 {
740 str = wxGetWindowText(GetHWND()).Mid(from, to - from);
741
742 // and now that we have the correct selection, convert it to the
743 // correct format
744 str = wxTextFile::Translate(str, wxTextFileType_Unix);
745 }
746
747 return str;
748 }
749
750 bool wxTextCtrl::IsEditable() const
751 {
752 long style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
753
754 return ((style & ES_READONLY) == 0);
755 }
756
757 // ----------------------------------------------------------------------------
758 // selection
759 // ----------------------------------------------------------------------------
760
761 void wxTextCtrl::SetSelection(long from, long to)
762 {
763 DoSetSelection(from, to);
764 }
765
766 void wxTextCtrl::DoSetSelection(long from, long to, bool scrollCaret)
767 {
768 // if from and to are both -1, it means (in wxWindows) that all text should
769 // be selected - translate into Windows convention
770 if ( (from == -1) && (to == -1) )
771 {
772 from = 0;
773 to = -1;
774 }
775
776 HWND hWnd = GetHwnd();
777
778 #ifdef __WIN32__
779 #if wxUSE_RICHEDIT
780 if ( IsRich() )
781 {
782 CHARRANGE range;
783 range.cpMin = from;
784 range.cpMax = to;
785 SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range);
786 }
787 else
788 #endif // wxUSE_RICHEDIT
789 {
790 SendMessage(hWnd, EM_SETSEL, (WPARAM)from, (LPARAM)to);
791 }
792
793 if ( scrollCaret )
794 {
795 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
796 }
797 #else // Win16
798 // WPARAM is 0: selection is scrolled into view
799 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(from, to));
800 #endif // Win32/16
801 }
802
803 // ----------------------------------------------------------------------------
804 // Editing
805 // ----------------------------------------------------------------------------
806
807 void wxTextCtrl::Replace(long from, long to, const wxString& value)
808 {
809 // Set selection and remove it
810 DoSetSelection(from, to, FALSE);
811
812 SendMessage(GetHwnd(), EM_REPLACESEL,
813 #ifdef __WIN32__
814 TRUE,
815 #else
816 FALSE,
817 #endif
818 (LPARAM)value.c_str());
819 }
820
821 void wxTextCtrl::Remove(long from, long to)
822 {
823 Replace(from, to, _T(""));
824 }
825
826 bool wxTextCtrl::LoadFile(const wxString& file)
827 {
828 if ( wxTextCtrlBase::LoadFile(file) )
829 {
830 // update the size limit if needed
831 AdjustSpaceLimit();
832
833 return TRUE;
834 }
835
836 return FALSE;
837 }
838
839 bool wxTextCtrl::IsModified() const
840 {
841 return (SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0);
842 }
843
844 // Makes 'unmodified'
845 void wxTextCtrl::DiscardEdits()
846 {
847 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
848 }
849
850 int wxTextCtrl::GetNumberOfLines() const
851 {
852 return (int)SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0);
853 }
854
855 long wxTextCtrl::XYToPosition(long x, long y) const
856 {
857 HWND hWnd = GetHwnd();
858
859 // This gets the char index for the _beginning_ of this line
860 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
861 return (long)(x + charIndex);
862 }
863
864 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
865 {
866 HWND hWnd = GetHwnd();
867
868 // This gets the line number containing the character
869 int lineNo;
870 #if wxUSE_RICHEDIT
871 if ( IsRich() )
872 {
873 lineNo = (int)SendMessage(hWnd, EM_EXLINEFROMCHAR, 0, (LPARAM)pos);
874 }
875 else
876 #endif // wxUSE_RICHEDIT
877 lineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, 0);
878
879 if ( lineNo == -1 )
880 {
881 // no such line
882 return FALSE;
883 }
884
885 // This gets the char index for the _beginning_ of this line
886 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
887 if ( charIndex == -1 )
888 {
889 return FALSE;
890 }
891
892 // The X position must therefore be the different between pos and charIndex
893 if ( x )
894 *x = (long)(pos - charIndex);
895 if ( y )
896 *y = (long)lineNo;
897
898 return TRUE;
899 }
900
901 void wxTextCtrl::ShowPosition(long pos)
902 {
903 HWND hWnd = GetHwnd();
904
905 // To scroll to a position, we pass the number of lines and characters
906 // to scroll *by*. This means that we need to:
907 // (1) Find the line position of the current line.
908 // (2) Find the line position of pos.
909 // (3) Scroll by (pos - current).
910 // For now, ignore the horizontal scrolling.
911
912 // Is this where scrolling is relative to - the line containing the caret?
913 // Or is the first visible line??? Try first visible line.
914 // int currentLineLineNo1 = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L);
915
916 int currentLineLineNo = (int)SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L);
917
918 int specifiedLineLineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L);
919
920 int linesToScroll = specifiedLineLineNo - currentLineLineNo;
921
922 if (linesToScroll != 0)
923 (void)SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll);
924 }
925
926 int wxTextCtrl::GetLineLength(long lineNo) const
927 {
928 long charIndex = XYToPosition(0, lineNo);
929 int len = (int)SendMessage(GetHwnd(), EM_LINELENGTH, charIndex, 0);
930 return len;
931 }
932
933 wxString wxTextCtrl::GetLineText(long lineNo) const
934 {
935 size_t len = (size_t)GetLineLength(lineNo) + 1;
936
937 // there must be at least enough place for the length WORD in the
938 // buffer
939 len += sizeof(WORD);
940
941 wxString str;
942 wxChar *buf = str.GetWriteBuf(len);
943
944 *(WORD *)buf = (WORD)len;
945 len = (size_t)::SendMessage(GetHwnd(), EM_GETLINE, lineNo, (LPARAM)buf);
946 buf[len] = 0;
947
948 str.UngetWriteBuf(len);
949
950 return str;
951 }
952
953 void wxTextCtrl::SetMaxLength(unsigned long len)
954 {
955 ::SendMessage(GetHwnd(), EM_LIMITTEXT, len, 0);
956 }
957
958 // ----------------------------------------------------------------------------
959 // Undo/redo
960 // ----------------------------------------------------------------------------
961
962 void wxTextCtrl::Undo()
963 {
964 if (CanUndo())
965 {
966 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
967 }
968 }
969
970 void wxTextCtrl::Redo()
971 {
972 if (CanRedo())
973 {
974 // Same as Undo, since Undo undoes the undo, i.e. a redo.
975 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
976 }
977 }
978
979 bool wxTextCtrl::CanUndo() const
980 {
981 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
982 }
983
984 bool wxTextCtrl::CanRedo() const
985 {
986 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
987 }
988
989 // ----------------------------------------------------------------------------
990 // implemenation details
991 // ----------------------------------------------------------------------------
992
993 void wxTextCtrl::Command(wxCommandEvent & event)
994 {
995 SetValue(event.GetString());
996 ProcessCommand (event);
997 }
998
999 void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event)
1000 {
1001 // By default, load the first file into the text window.
1002 if (event.GetNumberOfFiles() > 0)
1003 {
1004 LoadFile(event.GetFiles()[0]);
1005 }
1006 }
1007
1008 // ----------------------------------------------------------------------------
1009 // kbd input processing
1010 // ----------------------------------------------------------------------------
1011
1012 bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG* pMsg)
1013 {
1014 MSG *msg = (MSG *)pMsg;
1015
1016 // check for our special keys here: if we don't do it and the parent frame
1017 // uses them as accelerators, they wouldn't work at all, so we disable
1018 // usual preprocessing for them
1019 if ( msg->message == WM_KEYDOWN )
1020 {
1021 WORD vkey = msg->wParam;
1022 if ( (HIWORD(msg->lParam) & KF_ALTDOWN) == KF_ALTDOWN )
1023 {
1024 if ( vkey == VK_BACK )
1025 return FALSE;
1026 }
1027 else // no Alt
1028 {
1029 if ( wxIsCtrlDown() )
1030 {
1031 switch ( vkey )
1032 {
1033 case 'C':
1034 case 'V':
1035 case 'X':
1036 case VK_INSERT:
1037 case VK_DELETE:
1038 case VK_HOME:
1039 case VK_END:
1040 return FALSE;
1041 }
1042 }
1043 else if ( wxIsShiftDown() )
1044 {
1045 if ( vkey == VK_INSERT || vkey == VK_DELETE )
1046 return FALSE;
1047 }
1048 }
1049 }
1050
1051 return wxControl::MSWShouldPreProcessMessage(pMsg);
1052 }
1053
1054 void wxTextCtrl::OnChar(wxKeyEvent& event)
1055 {
1056 switch ( event.KeyCode() )
1057 {
1058 case WXK_RETURN:
1059 if ( !(m_windowStyle & wxTE_MULTILINE) )
1060 {
1061 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1062 InitCommandEvent(event);
1063 event.SetString(GetValue());
1064 if ( GetEventHandler()->ProcessEvent(event) )
1065 return;
1066 }
1067 //else: multiline controls need Enter for themselves
1068
1069 break;
1070
1071 case WXK_TAB:
1072 // always produce navigation event - even if we process TAB
1073 // ourselves the fact that we got here means that the user code
1074 // decided to skip processing of this TAB - probably to let it
1075 // do its default job.
1076 {
1077 wxNavigationKeyEvent eventNav;
1078 eventNav.SetDirection(!event.ShiftDown());
1079 eventNav.SetWindowChange(event.ControlDown());
1080 eventNav.SetEventObject(this);
1081
1082 if ( GetParent()->GetEventHandler()->ProcessEvent(eventNav) )
1083 return;
1084 }
1085 break;
1086 }
1087
1088 // no, we didn't process it
1089 event.Skip();
1090 }
1091
1092 bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
1093 {
1094 switch (param)
1095 {
1096 case EN_SETFOCUS:
1097 case EN_KILLFOCUS:
1098 {
1099 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
1100 : wxEVT_SET_FOCUS,
1101 m_windowId);
1102 event.SetEventObject( this );
1103 GetEventHandler()->ProcessEvent(event);
1104 }
1105 break;
1106
1107 case EN_CHANGE:
1108 {
1109 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, m_windowId);
1110 InitCommandEvent(event);
1111 event.SetString(GetValue());
1112 ProcessCommand(event);
1113 }
1114 break;
1115
1116 case EN_MAXTEXT:
1117 // the text size limit has been hit - increase it
1118 if ( !AdjustSpaceLimit() )
1119 {
1120 wxCommandEvent event(wxEVT_COMMAND_TEXT_MAXLEN, m_windowId);
1121 InitCommandEvent(event);
1122 event.SetString(GetValue());
1123 ProcessCommand(event);
1124 }
1125 break;
1126
1127 // the other notification messages are not processed
1128 case EN_UPDATE:
1129 case EN_ERRSPACE:
1130 case EN_HSCROLL:
1131 case EN_VSCROLL:
1132 return FALSE;
1133 default:
1134 return FALSE;
1135 }
1136
1137 // processed
1138 return TRUE;
1139 }
1140
1141 WXHBRUSH wxTextCtrl::OnCtlColor(WXHDC pDC, WXHWND WXUNUSED(pWnd), WXUINT WXUNUSED(nCtlColor),
1142 #if wxUSE_CTL3D
1143 WXUINT message,
1144 WXWPARAM wParam,
1145 WXLPARAM lParam
1146 #else
1147 WXUINT WXUNUSED(message),
1148 WXWPARAM WXUNUSED(wParam),
1149 WXLPARAM WXUNUSED(lParam)
1150 #endif
1151 )
1152 {
1153 #if wxUSE_CTL3D
1154 if ( m_useCtl3D )
1155 {
1156 HBRUSH hbrush = Ctl3dCtlColorEx(message, wParam, lParam);
1157 return (WXHBRUSH) hbrush;
1158 }
1159 #endif // wxUSE_CTL3D
1160
1161 HDC hdc = (HDC)pDC;
1162 if (GetParent()->GetTransparentBackground())
1163 SetBkMode(hdc, TRANSPARENT);
1164 else
1165 SetBkMode(hdc, OPAQUE);
1166
1167 wxColour colBack = GetBackgroundColour();
1168
1169 if (!IsEnabled() && (GetWindowStyle() & wxTE_MULTILINE) == 0)
1170 colBack = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DFACE);
1171
1172 ::SetBkColor(hdc, wxColourToRGB(colBack));
1173 ::SetTextColor(hdc, wxColourToRGB(GetForegroundColour()));
1174
1175 wxBrush *brush = wxTheBrushList->FindOrCreateBrush(colBack, wxSOLID);
1176
1177 return (WXHBRUSH)brush->GetResourceHandle();
1178 }
1179
1180 // In WIN16, need to override normal erasing because
1181 // Ctl3D doesn't use the wxWindows background colour.
1182 #ifdef __WIN16__
1183 void wxTextCtrl::OnEraseBackground(wxEraseEvent& event)
1184 {
1185 wxColour col(m_backgroundColour);
1186
1187 #if wxUSE_CTL3D
1188 if (m_useCtl3D)
1189 col = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW);
1190 #endif
1191
1192 RECT rect;
1193 ::GetClientRect(GetHwnd(), &rect);
1194
1195 COLORREF ref = PALETTERGB(col.Red(),
1196 col.Green(),
1197 col.Blue());
1198 HBRUSH hBrush = ::CreateSolidBrush(ref);
1199 if ( !hBrush )
1200 wxLogLastError(wxT("CreateSolidBrush"));
1201
1202 HDC hdc = (HDC)event.GetDC()->GetHDC();
1203
1204 int mode = ::SetMapMode(hdc, MM_TEXT);
1205
1206 ::FillRect(hdc, &rect, hBrush);
1207 ::DeleteObject(hBrush);
1208 ::SetMapMode(hdc, mode);
1209
1210 }
1211 #endif // Win16
1212
1213 bool wxTextCtrl::AdjustSpaceLimit()
1214 {
1215 #ifndef __WIN16__
1216 unsigned int limit = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0);
1217
1218 // HACK: we try to automatically extend the limit for the amount of text
1219 // to allow (interactively) entering more than 64Kb of text under
1220 // Win9x but we shouldn't reset the text limit which was previously
1221 // set explicitly with SetMaxLength()
1222 //
1223 // we could solve this by storing the limit we set in wxTextCtrl but
1224 // to save space we prefer to simply test here the actual limit
1225 // value: we consider that SetMaxLength() can only be called for
1226 // values < 32Kb
1227 if ( limit < 0x8000 )
1228 {
1229 // we've got more text than limit set by SetMaxLength()
1230 return FALSE;
1231 }
1232
1233 unsigned int len = ::GetWindowTextLength(GetHwnd());
1234 if ( len >= limit )
1235 {
1236 limit = len + 0x8000; // 32Kb
1237
1238 #if wxUSE_RICHEDIT
1239 if ( IsRich() )
1240 {
1241 // as a nice side effect, this also allows passing limit > 64Kb
1242 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT, 0, limit);
1243 }
1244 else
1245 #endif // wxUSE_RICHEDIT
1246 {
1247 if ( limit > 0xffff )
1248 {
1249 // this will set it to a platform-dependent maximum (much more
1250 // than 64Kb under NT)
1251 limit = 0;
1252 }
1253
1254 ::SendMessage(GetHwnd(), EM_LIMITTEXT, limit, 0);
1255 }
1256 }
1257 #endif // !Win16
1258
1259 // we changed the limit
1260 return TRUE;
1261 }
1262
1263 bool wxTextCtrl::AcceptsFocus() const
1264 {
1265 // we don't want focus if we can't be edited
1266 return IsEditable() && wxControl::AcceptsFocus();
1267 }
1268
1269 wxSize wxTextCtrl::DoGetBestSize() const
1270 {
1271 int cx, cy;
1272 wxGetCharSize(GetHWND(), &cx, &cy, &GetFont());
1273
1274 int wText = DEFAULT_ITEM_WIDTH;
1275
1276 int hText = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
1277 if ( m_windowStyle & wxTE_MULTILINE )
1278 {
1279 hText *= wxMax(GetNumberOfLines(), 5);
1280 }
1281 //else: for single line control everything is ok
1282
1283 return wxSize(wText, hText);
1284 }
1285
1286 // ----------------------------------------------------------------------------
1287 // standard handlers for standard edit menu events
1288 // ----------------------------------------------------------------------------
1289
1290 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
1291 {
1292 Cut();
1293 }
1294
1295 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
1296 {
1297 Copy();
1298 }
1299
1300 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
1301 {
1302 Paste();
1303 }
1304
1305 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
1306 {
1307 Undo();
1308 }
1309
1310 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
1311 {
1312 Redo();
1313 }
1314
1315 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1316 {
1317 event.Enable( CanCut() );
1318 }
1319
1320 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1321 {
1322 event.Enable( CanCopy() );
1323 }
1324
1325 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1326 {
1327 event.Enable( CanPaste() );
1328 }
1329
1330 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1331 {
1332 event.Enable( CanUndo() );
1333 }
1334
1335 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1336 {
1337 event.Enable( CanRedo() );
1338 }
1339
1340 // the rest of the file only deals with the rich edit controls
1341 #if wxUSE_RICHEDIT
1342
1343 // ----------------------------------------------------------------------------
1344 // EN_LINK processing
1345 // ----------------------------------------------------------------------------
1346
1347 bool wxTextCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
1348 {
1349 NMHDR *hdr = (NMHDR* )lParam;
1350 if ( hdr->code == EN_LINK )
1351 {
1352 ENLINK *enlink = (ENLINK *)hdr;
1353
1354 switch ( enlink->msg )
1355 {
1356 case WM_SETCURSOR:
1357 // ok, so it is hardcoded - do we really nee to customize it?
1358 ::SetCursor(GetHcursorOf(wxCursor(wxCURSOR_HAND)));
1359 *result = TRUE;
1360 break;
1361
1362 case WM_MOUSEMOVE:
1363 case WM_LBUTTONDOWN:
1364 case WM_LBUTTONUP:
1365 case WM_LBUTTONDBLCLK:
1366 case WM_RBUTTONDOWN:
1367 case WM_RBUTTONUP:
1368 case WM_RBUTTONDBLCLK:
1369 // send a mouse event
1370 {
1371 static const wxEventType eventsMouse[] =
1372 {
1373 wxEVT_MOTION,
1374 wxEVT_LEFT_DOWN,
1375 wxEVT_LEFT_UP,
1376 wxEVT_LEFT_DCLICK,
1377 wxEVT_RIGHT_DOWN,
1378 wxEVT_RIGHT_UP,
1379 wxEVT_RIGHT_DCLICK,
1380 };
1381
1382 // the event ids are consecutive
1383 wxMouseEvent
1384 evtMouse(eventsMouse[enlink->msg - WM_MOUSEMOVE]);
1385
1386 InitMouseEvent(evtMouse,
1387 GET_X_LPARAM(enlink->lParam),
1388 GET_Y_LPARAM(enlink->lParam),
1389 enlink->wParam);
1390
1391 wxTextUrlEvent event(m_windowId, evtMouse,
1392 enlink->chrg.cpMin,
1393 enlink->chrg.cpMax);
1394
1395 InitCommandEvent(event);
1396
1397 *result = ProcessCommand(event);
1398 }
1399 break;
1400 }
1401
1402 return TRUE;
1403 }
1404
1405 // not processed
1406 return FALSE;
1407 }
1408
1409 // ----------------------------------------------------------------------------
1410 // colour setting for the rich edit controls
1411 // ----------------------------------------------------------------------------
1412
1413 // Watcom C++ doesn't define this
1414 #ifndef SCF_ALL
1415 #define SCF_ALL 0x0004
1416 #endif
1417
1418 bool wxTextCtrl::SetBackgroundColour(const wxColour& colour)
1419 {
1420 if ( !wxTextCtrlBase::SetBackgroundColour(colour) )
1421 {
1422 // colour didn't really change
1423 return FALSE;
1424 }
1425
1426 if ( IsRich() )
1427 {
1428 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
1429 // EM_SETBKGNDCOLOR additionally
1430 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR, 0, wxColourToRGB(colour));
1431 }
1432
1433 return TRUE;
1434 }
1435
1436 bool wxTextCtrl::SetForegroundColour(const wxColour& colour)
1437 {
1438 if ( !wxTextCtrlBase::SetForegroundColour(colour) )
1439 {
1440 // colour didn't really change
1441 return FALSE;
1442 }
1443
1444 if ( IsRich() )
1445 {
1446 // change the colour of everything
1447 CHARFORMAT cf;
1448 wxZeroMemory(cf);
1449 cf.cbSize = sizeof(cf);
1450 cf.dwMask = CFM_COLOR;
1451 cf.crTextColor = wxColourToRGB(colour);
1452 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf);
1453 }
1454
1455 return TRUE;
1456 }
1457
1458 // ----------------------------------------------------------------------------
1459 // styling support for rich edit controls
1460 // ----------------------------------------------------------------------------
1461
1462 bool wxTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
1463 {
1464 if ( !IsRich() )
1465 {
1466 // can't do it with normal text control
1467 return FALSE;
1468 }
1469
1470 // the rich text control doesn't handle setting background colour, so don't
1471 // even try if it's the only thing we want to change
1472 if ( wxRichEditModule::GetLoadedVersion() < 2 &&
1473 !style.HasFont() && !style.HasTextColour() )
1474 {
1475 // nothing to do: return TRUE if there was really nothing to do and
1476 // FALSE if we failed to set bg colour
1477 return !style.HasBackgroundColour();
1478 }
1479
1480 // order the range if needed
1481 if ( start > end )
1482 {
1483 long tmp = start;
1484 start = end;
1485 end = tmp;
1486 }
1487
1488 // we can only change the format of the selection, so select the range we
1489 // want and restore the old selection later
1490 long startOld, endOld;
1491 GetSelection(&startOld, &endOld);
1492
1493 // but do we really have to change the selection?
1494 bool changeSel = start != startOld || end != endOld;
1495
1496 if ( changeSel )
1497 {
1498 DoSetSelection(start, end, FALSE);
1499 }
1500
1501 // initialize CHARFORMAT struct
1502 #if wxUSE_RICHEDIT2
1503 CHARFORMAT2 cf;
1504 #else
1505 CHARFORMAT cf;
1506 #endif
1507 wxZeroMemory(cf);
1508 cf.cbSize = sizeof(cf);
1509
1510 if ( style.HasFont() )
1511 {
1512 // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0
1513 // but using it doesn't seem to hurt neither so leaving it for now
1514
1515 cf.dwMask |= CFM_FACE | CFM_SIZE | CFM_CHARSET |
1516 CFM_ITALIC | CFM_BOLD | CFM_UNDERLINE;
1517
1518 // fill in data from LOGFONT but recalculate lfHeight because we need
1519 // the real height in twips and not the negative number which
1520 // wxFillLogFont() returns (this is correct in general and works with
1521 // the Windows font mapper, but not here)
1522 LOGFONT lf;
1523 wxFillLogFont(&lf, &style.GetFont());
1524 cf.yHeight = 20*style.GetFont().GetPointSize(); // 1 pt = 20 twips
1525 cf.bCharSet = lf.lfCharSet;
1526 cf.bPitchAndFamily = lf.lfPitchAndFamily;
1527 wxStrncpy( cf.szFaceName, lf.lfFaceName, WXSIZEOF(cf.szFaceName) );
1528
1529 // also deal with underline/italic/bold attributes: note that we must
1530 // always set CFM_ITALIC &c bits in dwMask, even if we don't set the
1531 // style to allow clearing it
1532 if ( lf.lfItalic )
1533 {
1534 cf.dwEffects |= CFE_ITALIC;
1535 }
1536
1537 if ( lf.lfWeight == FW_BOLD )
1538 {
1539 cf.dwEffects |= CFE_BOLD;
1540 }
1541
1542 if ( lf.lfUnderline )
1543 {
1544 cf.dwEffects |= CFE_UNDERLINE;
1545 }
1546
1547 // strikeout fonts are not supported by wxWindows
1548 }
1549
1550 if ( style.HasTextColour() )
1551 {
1552 cf.dwMask |= CFM_COLOR;
1553 cf.crTextColor = wxColourToRGB(style.GetTextColour());
1554 }
1555
1556 #if wxUSE_RICHEDIT2
1557 if ( wxRichEditModule::GetLoadedVersion() > 1 && style.HasBackgroundColour() )
1558 {
1559 cf.dwMask |= CFM_BACKCOLOR;
1560 cf.crBackColor = wxColourToRGB(style.GetBackgroundColour());
1561 }
1562 #endif // wxUSE_RICHEDIT2
1563
1564 // do format the selection
1565 bool ok = ::SendMessage(GetHwnd(), EM_SETCHARFORMAT,
1566 SCF_SELECTION, (LPARAM)&cf) != 0;
1567 if ( !ok )
1568 {
1569 wxLogDebug(_T("SendMessage(EM_SETCHARFORMAT, SCF_SELECTION) failed"));
1570 }
1571
1572 if ( changeSel )
1573 {
1574 // restore the original selection
1575 DoSetSelection(startOld, endOld, FALSE);
1576 }
1577
1578 return ok;
1579 }
1580
1581 // ----------------------------------------------------------------------------
1582 // wxRichEditModule
1583 // ----------------------------------------------------------------------------
1584
1585 bool wxRichEditModule::OnInit()
1586 {
1587 // don't do anything - we will load it when needed
1588 return TRUE;
1589 }
1590
1591 void wxRichEditModule::OnExit()
1592 {
1593 if ( ms_hRichEdit )
1594 {
1595 FreeLibrary(ms_hRichEdit);
1596 }
1597 }
1598
1599 /* static */
1600 bool wxRichEditModule::Load(int version)
1601 {
1602 wxCHECK_MSG( version >= 1 && version <= 3, FALSE,
1603 _T("incorrect richedit control version requested") );
1604
1605 if ( version <= ms_verRichEdit )
1606 {
1607 // we've already got this or better
1608 return TRUE;
1609 }
1610
1611 if ( ms_hRichEdit )
1612 {
1613 ::FreeLibrary(ms_hRichEdit);
1614 }
1615
1616 // always try load riched20.dll first - like this we won't have to reload
1617 // it later if we're first asked for RE 1 and then for RE 2 or 3
1618 wxString dllname = _T("riched20.dll");
1619 ms_hRichEdit = ::LoadLibrary(dllname);
1620 ms_verRichEdit = 2; // no way to tell if it's 2 or 3, assume 2
1621
1622 if ( !ms_hRichEdit && (version == 1) )
1623 {
1624 // fall back to RE 1
1625 dllname = _T("riched32.dll");
1626 ms_hRichEdit = ::LoadLibrary(dllname);
1627 ms_verRichEdit = 1;
1628 }
1629
1630 if ( !ms_hRichEdit )
1631 {
1632 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname.c_str());
1633
1634 ms_verRichEdit = -1;
1635
1636 return FALSE;
1637 }
1638
1639 return TRUE;
1640 }
1641
1642 #endif // wxUSE_RICHEDIT
1643
1644 #endif // wxUSE_TEXTCTRL