]> git.saurik.com Git - wxWidgets.git/blob - src/msw/textctrl.cpp
Canvas lib precompiled header fix; doc typos fixes; makefile.vc dbtable.cpp addition
[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 #ifndef WX_PRECOMP
32 #include "wx/textctrl.h"
33 #include "wx/settings.h"
34 #include "wx/brush.h"
35 #include "wx/utils.h"
36 #include "wx/intl.h"
37 #include "wx/log.h"
38 #include "wx/app.h"
39 #endif
40
41 #include "wx/module.h"
42
43 #if wxUSE_CLIPBOARD
44 #include "wx/clipbrd.h"
45 #endif
46
47 #include "wx/textfile.h"
48
49 #include <windowsx.h>
50
51 #include "wx/msw/private.h"
52
53 #include <string.h>
54 #include <stdlib.h>
55 #include <sys/types.h>
56
57 #if wxUSE_RICHEDIT && (!defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__))
58 #include <richedit.h>
59 #endif
60
61 // old mingw32 doesn't define this
62 #ifndef CFM_CHARSET
63 #define CFM_CHARSET 0x08000000
64 #endif // CFM_CHARSET
65
66 // ----------------------------------------------------------------------------
67 // private classes
68 // ----------------------------------------------------------------------------
69
70 #if wxUSE_RICHEDIT
71
72 // this module initializes RichEdit DLL if needed
73 class wxRichEditModule : public wxModule
74 {
75 public:
76 virtual bool OnInit();
77 virtual void OnExit();
78
79 // get the version currently loaded, -1 if none
80 static int GetLoadedVersion() { return ms_verRichEdit; }
81
82 // load the richedit DLL of at least of required version
83 static bool Load(int version = 1);
84
85 private:
86 // the handle to richedit DLL and the version of the DLL loaded
87 static HINSTANCE ms_hRichEdit;
88
89 // the DLL version loaded or -1 if none
90 static int ms_verRichEdit;
91
92 DECLARE_DYNAMIC_CLASS(wxRichEditModule)
93 };
94
95 HINSTANCE wxRichEditModule::ms_hRichEdit = (HINSTANCE)NULL;
96 int wxRichEditModule::ms_verRichEdit = -1;
97
98 IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule, wxModule)
99
100 #endif // wxUSE_RICHEDIT
101
102 // ----------------------------------------------------------------------------
103 // event tables and other macros
104 // ----------------------------------------------------------------------------
105
106 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxControl)
107
108 BEGIN_EVENT_TABLE(wxTextCtrl, wxControl)
109 EVT_CHAR(wxTextCtrl::OnChar)
110 EVT_DROP_FILES(wxTextCtrl::OnDropFiles)
111
112 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
113 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
114 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
115 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
116 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
117
118 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
119 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
120 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
121 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
122 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
123 #ifdef __WIN16__
124 EVT_ERASE_BACKGROUND(wxTextCtrl::OnEraseBackground)
125 #endif
126 END_EVENT_TABLE()
127
128 // ============================================================================
129 // implementation
130 // ============================================================================
131
132 // ----------------------------------------------------------------------------
133 // creation
134 // ----------------------------------------------------------------------------
135
136 wxTextCtrl::wxTextCtrl()
137 {
138 #if wxUSE_RICHEDIT
139 m_isRich = FALSE;
140 #endif
141 }
142
143 bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id,
144 const wxString& value,
145 const wxPoint& pos,
146 const wxSize& size,
147 long style,
148 const wxValidator& validator,
149 const wxString& name)
150 {
151 // base initialization
152 if ( !CreateBase(parent, id, pos, size, style, validator, name) )
153 return FALSE;
154
155 if ( parent )
156 parent->AddChild(this);
157
158 // translate wxWin style flags to MSW ones, checking for consistency while
159 // doing it
160 long msStyle = ES_LEFT | WS_VISIBLE | WS_CHILD | WS_TABSTOP;
161
162 if ( m_windowStyle & wxCLIP_SIBLINGS )
163 msStyle |= WS_CLIPSIBLINGS;
164
165 if ( m_windowStyle & wxTE_MULTILINE )
166 {
167 wxASSERT_MSG( !(m_windowStyle & wxTE_PROCESS_ENTER),
168 wxT("wxTE_PROCESS_ENTER style is ignored for multiline text controls (they always process it)") );
169
170 msStyle |= ES_MULTILINE | ES_WANTRETURN;
171 if ((m_windowStyle & wxTE_NO_VSCROLL) == 0)
172 msStyle |= WS_VSCROLL;
173 m_windowStyle |= wxTE_PROCESS_ENTER;
174 }
175 else
176 msStyle |= ES_AUTOHSCROLL;
177
178 if (m_windowStyle & wxHSCROLL)
179 msStyle |= (WS_HSCROLL | ES_AUTOHSCROLL);
180
181 if (m_windowStyle & wxTE_READONLY)
182 msStyle |= ES_READONLY;
183
184 if (m_windowStyle & wxTE_PASSWORD) // hidden input
185 msStyle |= ES_PASSWORD;
186
187 if (m_windowStyle & wxTE_AUTO_SCROLL)
188 msStyle |= ES_AUTOHSCROLL;
189
190
191 // we always want the characters and the arrows
192 m_lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS;
193
194 // we may have several different cases:
195 // 1. normal case: both TAB and ENTER are used for dialog navigation
196 // 2. ctrl which wants TAB for itself: ENTER is used to pass to the next
197 // control in the dialog
198 // 3. ctrl which wants ENTER for itself: TAB is used for dialog navigation
199 // 4. ctrl which wants both TAB and ENTER: Ctrl-ENTER is used to pass to
200 // the next control
201 if ( m_windowStyle & wxTE_PROCESS_ENTER )
202 m_lDlgCode |= DLGC_WANTMESSAGE;
203 if ( m_windowStyle & wxTE_PROCESS_TAB )
204 m_lDlgCode |= DLGC_WANTTAB;
205
206 // do create the control - either an EDIT or RICHEDIT
207 wxString windowClass = wxT("EDIT");
208
209 #if wxUSE_RICHEDIT
210 if ( m_windowStyle & wxTE_RICH )
211 {
212 static bool s_errorGiven = FALSE; // MT-FIXME
213
214 // only give the error msg once if the DLL can't be loaded
215 if ( !s_errorGiven )
216 {
217 // first try to load the RichEdit DLL (will do nothing if already
218 // done)
219 if ( !wxRichEditModule::Load() )
220 {
221 wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll"));
222
223 s_errorGiven = TRUE;
224 }
225 }
226
227 if ( s_errorGiven )
228 {
229 m_isRich = FALSE;
230 }
231 else
232 {
233 msStyle |= ES_AUTOVSCROLL;
234 m_isRich = TRUE;
235
236 int ver = wxRichEditModule::GetLoadedVersion();
237 if ( ver == 1 )
238 {
239 windowClass = wxT("RICHEDIT");
240 }
241 else
242 {
243 #ifndef RICHEDIT_CLASS
244 wxString RICHEDIT_CLASS;
245 RICHEDIT_CLASS.Printf(_T("RichEdit%d0"), ver);
246 #if wxUSE_UNICODE
247 RICHEDIT_CLASS += _T('W');
248 #else // ANSI
249 RICHEDIT_CLASS += _T('A');
250 #endif // Unicode/ANSI
251 #endif // !RICHEDIT_CLASS
252
253 windowClass = RICHEDIT_CLASS;
254 }
255 }
256 }
257 else
258 m_isRich = FALSE;
259 #endif // wxUSE_RICHEDIT
260
261 bool want3D;
262 WXDWORD exStyle = Determine3DEffects(WS_EX_CLIENTEDGE, &want3D);
263
264 // Even with extended styles, need to combine with WS_BORDER for them to
265 // look right.
266 if ( want3D || wxStyleHasBorder(m_windowStyle) )
267 msStyle |= WS_BORDER;
268
269 // NB: don't use pos and size as CreateWindowEx arguments because they
270 // might be -1 in which case we should use the default values (and
271 // SetSize called below takes care of it)
272 m_hWnd = (WXHWND)::CreateWindowEx(exStyle,
273 windowClass.c_str(),
274 NULL,
275 msStyle,
276 0, 0, 0, 0,
277 GetHwndOf(parent),
278 (HMENU)m_windowId,
279 wxGetInstance(),
280 NULL);
281
282 wxCHECK_MSG( m_hWnd, FALSE, wxT("Failed to create text ctrl") );
283
284 #if wxUSE_CTL3D
285 if ( want3D )
286 {
287 Ctl3dSubclassCtl(GetHwnd());
288 m_useCtl3D = TRUE;
289 }
290 #endif
291
292 #if wxUSE_RICHEDIT
293 if (m_isRich)
294 {
295 // Have to enable events
296 ::SendMessage(GetHwnd(), EM_SETEVENTMASK, 0,
297 ENM_CHANGE | ENM_DROPFILES | ENM_SELCHANGE | ENM_UPDATE);
298 }
299 #endif
300
301 SubclassWin(GetHWND());
302
303 // set font, position, size and initial value
304 wxFont& fontParent = parent->GetFont();
305 if ( fontParent.Ok() )
306 {
307 SetFont(fontParent);
308 }
309 else
310 {
311 SetFont(wxSystemSettings::GetSystemFont(wxSYS_SYSTEM_FONT));
312 }
313
314 // Causes a crash for Symantec C++ and WIN32 for some reason
315 #if !(defined(__SC__) && defined(__WIN32__))
316 if ( !value.IsEmpty() )
317 {
318 SetValue(value);
319 }
320 #endif
321
322 // set colours
323 SetupColours();
324
325 SetSize(pos.x, pos.y, size.x, size.y);
326
327 return TRUE;
328 }
329
330 // Make sure the window style (etc.) reflects the HWND style (roughly)
331 void wxTextCtrl::AdoptAttributesFromHWND()
332 {
333 wxWindow::AdoptAttributesFromHWND();
334
335 HWND hWnd = GetHwnd();
336 long style = GetWindowLong(hWnd, GWL_STYLE);
337
338 // retrieve the style to see whether this is an edit or richedit ctrl
339 #if wxUSE_RICHEDIT
340 wxChar buf[256];
341
342 GetClassName(hWnd, buf, WXSIZEOF(buf));
343
344 if ( wxStricmp(buf, wxT("EDIT")) == 0 )
345 m_isRich = FALSE;
346 else
347 m_isRich = TRUE;
348 #endif // wxUSE_RICHEDIT
349
350 if (style & ES_MULTILINE)
351 m_windowStyle |= wxTE_MULTILINE;
352 if (style & ES_PASSWORD)
353 m_windowStyle |= wxTE_PASSWORD;
354 if (style & ES_READONLY)
355 m_windowStyle |= wxTE_READONLY;
356 if (style & ES_WANTRETURN)
357 m_windowStyle |= wxTE_PROCESS_ENTER;
358 }
359
360 void wxTextCtrl::SetupColours()
361 {
362 wxColour bkgndColour;
363 // if (IsEditable() || (m_windowStyle & wxTE_MULTILINE))
364 bkgndColour = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW);
365 // else
366 // bkgndColour = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DFACE);
367
368 SetBackgroundColour(bkgndColour);
369 SetForegroundColour(GetParent()->GetForegroundColour());
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 ( m_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 wxString valueDos = wxTextFile::Translate(value, wxTextFileType_Dos);
432
433 SetWindowText(GetHwnd(), valueDos.c_str());
434
435 // for compatibility with the GTK and because it is more logical, we
436 // move the cursor to the end of the text after SetValue()
437
438 // GRG, Jun/2000: Changed this back after a lot of discussion
439 // in the lists. wxWindows 2.2 will have a set of flags to
440 // customize this behaviour.
441 //SetInsertionPointEnd();
442
443 AdjustSpaceLimit();
444 }
445 }
446
447 void wxTextCtrl::WriteText(const wxString& value)
448 {
449 wxString valueDos = wxTextFile::Translate(value, wxTextFileType_Dos);
450
451 #if wxUSE_RICHEDIT
452 // ensure that the new text will be in the default style
453 if ( IsRich() &&
454 (m_defaultStyle.HasFont() || m_defaultStyle.HasTextColour()) )
455 {
456 long start, end;
457 GetSelection(&start, &end);
458 SetStyle(start, end, m_defaultStyle );
459 }
460 #endif // wxUSE_RICHEDIT
461
462 SendMessage(GetHwnd(), EM_REPLACESEL, 0, (LPARAM)valueDos.c_str());
463
464 AdjustSpaceLimit();
465 }
466
467 void wxTextCtrl::AppendText(const wxString& text)
468 {
469 SetInsertionPointEnd();
470 WriteText(text);
471 }
472
473 void wxTextCtrl::Clear()
474 {
475 SetWindowText(GetHwnd(), wxT(""));
476 }
477
478 // ----------------------------------------------------------------------------
479 // Clipboard operations
480 // ----------------------------------------------------------------------------
481
482 void wxTextCtrl::Copy()
483 {
484 if (CanCopy())
485 {
486 HWND hWnd = GetHwnd();
487 SendMessage(hWnd, WM_COPY, 0, 0L);
488 }
489 }
490
491 void wxTextCtrl::Cut()
492 {
493 if (CanCut())
494 {
495 HWND hWnd = GetHwnd();
496 SendMessage(hWnd, WM_CUT, 0, 0L);
497 }
498 }
499
500 void wxTextCtrl::Paste()
501 {
502 if (CanPaste())
503 {
504 HWND hWnd = GetHwnd();
505 SendMessage(hWnd, WM_PASTE, 0, 0L);
506 }
507 }
508
509 bool wxTextCtrl::CanCopy() const
510 {
511 // Can copy if there's a selection
512 long from, to;
513 GetSelection(& from, & to);
514 return (from != to) ;
515 }
516
517 bool wxTextCtrl::CanCut() const
518 {
519 // Can cut if there's a selection
520 long from, to;
521 GetSelection(& from, & to);
522 return (from != to) && (IsEditable());
523 }
524
525 bool wxTextCtrl::CanPaste() const
526 {
527 #if wxUSE_RICHEDIT
528 if (m_isRich)
529 {
530 int dataFormat = 0; // 0 == any format
531 return (::SendMessage( GetHwnd(), EM_CANPASTE, (WPARAM) (UINT) dataFormat, 0) != 0);
532 }
533 #endif
534 if (!IsEditable())
535 return FALSE;
536
537 // Standard edit control: check for straight text on clipboard
538 bool isTextAvailable = FALSE;
539 if ( ::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) )
540 {
541 isTextAvailable = (::IsClipboardFormatAvailable(CF_TEXT) != 0);
542 ::CloseClipboard();
543 }
544
545 return isTextAvailable;
546 }
547
548 // ----------------------------------------------------------------------------
549 // Accessors
550 // ----------------------------------------------------------------------------
551
552 void wxTextCtrl::SetEditable(bool editable)
553 {
554 HWND hWnd = GetHwnd();
555 SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
556 }
557
558 void wxTextCtrl::SetInsertionPoint(long pos)
559 {
560 HWND hWnd = GetHwnd();
561 #ifdef __WIN32__
562 #if wxUSE_RICHEDIT
563 if ( m_isRich)
564 {
565 CHARRANGE range;
566 range.cpMin = pos;
567 range.cpMax = pos;
568 SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range);
569 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
570 }
571 else
572 #endif // wxUSE_RICHEDIT
573 {
574 SendMessage(hWnd, EM_SETSEL, pos, pos);
575 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
576 }
577 #else // Win16
578 SendMessage(hWnd, EM_SETSEL, 0, MAKELPARAM(pos, pos));
579 #endif // Win32/16
580
581 static const wxChar *nothing = _T("");
582 SendMessage(hWnd, EM_REPLACESEL, 0, (LPARAM)nothing);
583 }
584
585 void wxTextCtrl::SetInsertionPointEnd()
586 {
587 long pos = GetLastPosition();
588 SetInsertionPoint(pos);
589 }
590
591 long wxTextCtrl::GetInsertionPoint() const
592 {
593 #if wxUSE_RICHEDIT
594 if (m_isRich)
595 {
596 CHARRANGE range;
597 range.cpMin = 0;
598 range.cpMax = 0;
599 SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range);
600 return range.cpMin;
601 }
602 #endif
603
604 DWORD Pos = (DWORD)SendMessage(GetHwnd(), EM_GETSEL, 0, 0L);
605 return Pos & 0xFFFF;
606 }
607
608 long wxTextCtrl::GetLastPosition() const
609 {
610 HWND hWnd = GetHwnd();
611
612 // Will always return a number > 0 (according to docs)
613 int noLines = (int)SendMessage(hWnd, EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0L);
614
615 // This gets the char index for the _beginning_ of the last line
616 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)(noLines-1), (LPARAM)0L);
617
618 // Get number of characters in the last line. We'll add this to the character
619 // index for the last line, 1st position.
620 int lineLength = (int)SendMessage(hWnd, EM_LINELENGTH, (WPARAM)charIndex, (LPARAM)0L);
621
622 return (long)(charIndex + lineLength);
623 }
624
625 // If the return values from and to are the same, there is no
626 // selection.
627 void wxTextCtrl::GetSelection(long* from, long* to) const
628 {
629 #if wxUSE_RICHEDIT
630 if (m_isRich)
631 {
632 CHARRANGE charRange;
633 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) (CHARRANGE*) & charRange);
634
635 *from = charRange.cpMin;
636 *to = charRange.cpMax;
637 }
638 else
639 #endif // rich/!rich
640 {
641 DWORD dwStart, dwEnd;
642 WPARAM wParam = (WPARAM) &dwStart; // receives starting position
643 LPARAM lParam = (LPARAM) &dwEnd; // receives ending position
644
645 ::SendMessage(GetHwnd(), EM_GETSEL, wParam, lParam);
646
647 *from = dwStart;
648 *to = dwEnd;
649 }
650 }
651
652 bool wxTextCtrl::IsEditable() const
653 {
654 long style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
655
656 return ((style & ES_READONLY) == 0);
657 }
658
659 // ----------------------------------------------------------------------------
660 // Editing
661 // ----------------------------------------------------------------------------
662
663 void wxTextCtrl::Replace(long from, long to, const wxString& value)
664 {
665 #if wxUSE_CLIPBOARD
666 HWND hWnd = GetHwnd();
667 long fromChar = from;
668 long toChar = to;
669
670 // Set selection and remove it
671 #ifdef __WIN32__
672 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
673 #else
674 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
675 #endif
676 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
677
678 // Now replace with 'value', by pasting.
679 wxSetClipboardData(wxDF_TEXT, (wxObject *) (const wxChar *)value, 0, 0);
680
681 // Paste into edit control
682 SendMessage(hWnd, WM_PASTE, (WPARAM)0, (LPARAM)0L);
683 #else
684 wxFAIL_MSG("wxTextCtrl::Replace not implemented if wxUSE_CLIPBOARD is 0.");
685 #endif
686 }
687
688 void wxTextCtrl::Remove(long from, long to)
689 {
690 HWND hWnd = GetHwnd();
691 long fromChar = from;
692 long toChar = to;
693
694 // Cut all selected text
695 #ifdef __WIN32__
696 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
697 #else
698 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
699 #endif
700 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
701 }
702
703 void wxTextCtrl::SetSelection(long from, long to)
704 {
705 HWND hWnd = GetHwnd();
706 long fromChar = from;
707 long toChar = to;
708
709 // if from and to are both -1, it means (in wxWindows) that all text should
710 // be selected. Translate into Windows convention
711 if ((from == -1) && (to == -1))
712 {
713 fromChar = 0;
714 toChar = -1;
715 }
716
717 #ifdef __WIN32__
718 SendMessage(hWnd, EM_SETSEL, (WPARAM)fromChar, (LPARAM)toChar);
719 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
720 #else
721 // WPARAM is 0: selection is scrolled into view
722 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
723 #endif
724 }
725
726 bool wxTextCtrl::LoadFile(const wxString& file)
727 {
728 if ( wxTextCtrlBase::LoadFile(file) )
729 {
730 // update the size limit if needed
731 AdjustSpaceLimit();
732
733 return TRUE;
734 }
735
736 return FALSE;
737 }
738
739 bool wxTextCtrl::IsModified() const
740 {
741 return (SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0);
742 }
743
744 // Makes 'unmodified'
745 void wxTextCtrl::DiscardEdits()
746 {
747 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
748 }
749
750 int wxTextCtrl::GetNumberOfLines() const
751 {
752 return (int)SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0);
753 }
754
755 long wxTextCtrl::XYToPosition(long x, long y) const
756 {
757 HWND hWnd = GetHwnd();
758
759 // This gets the char index for the _beginning_ of this line
760 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
761 return (long)(x + charIndex);
762 }
763
764 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
765 {
766 HWND hWnd = GetHwnd();
767
768 // This gets the line number containing the character
769 int lineNo;
770 #if wxUSE_RICHEDIT
771 if ( m_isRich )
772 {
773 lineNo = (int)SendMessage(hWnd, EM_EXLINEFROMCHAR, 0, (LPARAM)pos);
774 }
775 else
776 #endif // wxUSE_RICHEDIT
777 lineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, 0);
778
779 if ( lineNo == -1 )
780 {
781 // no such line
782 return FALSE;
783 }
784
785 // This gets the char index for the _beginning_ of this line
786 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
787 if ( charIndex == -1 )
788 {
789 return FALSE;
790 }
791
792 // The X position must therefore be the different between pos and charIndex
793 if ( x )
794 *x = (long)(pos - charIndex);
795 if ( y )
796 *y = (long)lineNo;
797
798 return TRUE;
799 }
800
801 void wxTextCtrl::ShowPosition(long pos)
802 {
803 HWND hWnd = GetHwnd();
804
805 // To scroll to a position, we pass the number of lines and characters
806 // to scroll *by*. This means that we need to:
807 // (1) Find the line position of the current line.
808 // (2) Find the line position of pos.
809 // (3) Scroll by (pos - current).
810 // For now, ignore the horizontal scrolling.
811
812 // Is this where scrolling is relative to - the line containing the caret?
813 // Or is the first visible line??? Try first visible line.
814 // int currentLineLineNo1 = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L);
815
816 int currentLineLineNo = (int)SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L);
817
818 int specifiedLineLineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L);
819
820 int linesToScroll = specifiedLineLineNo - currentLineLineNo;
821
822 if (linesToScroll != 0)
823 (void)SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll);
824 }
825
826 int wxTextCtrl::GetLineLength(long lineNo) const
827 {
828 long charIndex = XYToPosition(0, lineNo);
829 int len = (int)SendMessage(GetHwnd(), EM_LINELENGTH, charIndex, 0);
830 return len;
831 }
832
833 wxString wxTextCtrl::GetLineText(long lineNo) const
834 {
835 size_t len = (size_t)GetLineLength(lineNo) + 1;
836
837 // there must be at least enough place for the length WORD in the
838 // buffer
839 len += sizeof(WORD);
840
841 wxString str;
842 wxChar *buf = str.GetWriteBuf(len);
843
844 *(WORD *)buf = (WORD)len;
845 len = (size_t)::SendMessage(GetHwnd(), EM_GETLINE, lineNo, (LPARAM)buf);
846 buf[len] = 0;
847
848 str.UngetWriteBuf(len);
849
850 return str;
851 }
852
853 // ----------------------------------------------------------------------------
854 // Undo/redo
855 // ----------------------------------------------------------------------------
856
857 void wxTextCtrl::Undo()
858 {
859 if (CanUndo())
860 {
861 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
862 }
863 }
864
865 void wxTextCtrl::Redo()
866 {
867 if (CanRedo())
868 {
869 // Same as Undo, since Undo undoes the undo, i.e. a redo.
870 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
871 }
872 }
873
874 bool wxTextCtrl::CanUndo() const
875 {
876 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
877 }
878
879 bool wxTextCtrl::CanRedo() const
880 {
881 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
882 }
883
884 // ----------------------------------------------------------------------------
885 // implemenation details
886 // ----------------------------------------------------------------------------
887
888 void wxTextCtrl::Command(wxCommandEvent & event)
889 {
890 SetValue(event.GetString());
891 ProcessCommand (event);
892 }
893
894 void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event)
895 {
896 // By default, load the first file into the text window.
897 if (event.GetNumberOfFiles() > 0)
898 {
899 LoadFile(event.GetFiles()[0]);
900 }
901 }
902
903 void wxTextCtrl::OnChar(wxKeyEvent& event)
904 {
905 switch ( event.KeyCode() )
906 {
907 case WXK_RETURN:
908 if ( !(m_windowStyle & wxTE_MULTILINE) )
909 {
910 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
911 InitCommandEvent(event);
912 event.SetString(GetValue());
913 if ( GetEventHandler()->ProcessEvent(event) )
914 return;
915 }
916 //else: multiline controls need Enter for themselves
917
918 break;
919
920 case WXK_TAB:
921 // always produce navigation event - even if we process TAB
922 // ourselves the fact that we got here means that the user code
923 // decided to skip processing of this TAB - probably to let it
924 // do its default job.
925 {
926 wxNavigationKeyEvent eventNav;
927 eventNav.SetDirection(!event.ShiftDown());
928 eventNav.SetWindowChange(event.ControlDown());
929 eventNav.SetEventObject(this);
930
931 if ( GetParent()->GetEventHandler()->ProcessEvent(eventNav) )
932 return;
933 }
934 break;
935 }
936
937 // no, we didn't process it
938 event.Skip();
939 }
940
941 bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
942 {
943 switch (param)
944 {
945 case EN_SETFOCUS:
946 case EN_KILLFOCUS:
947 {
948 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
949 : wxEVT_SET_FOCUS,
950 m_windowId);
951 event.SetEventObject( this );
952 GetEventHandler()->ProcessEvent(event);
953 }
954 break;
955
956 case EN_CHANGE:
957 {
958 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, m_windowId);
959 InitCommandEvent(event);
960 event.SetString(GetValue());
961 ProcessCommand(event);
962 }
963 break;
964
965 case EN_MAXTEXT:
966 // the text size limit has been hit - increase it
967 AdjustSpaceLimit();
968 break;
969
970 // the other notification messages are not processed
971 case EN_UPDATE:
972 case EN_ERRSPACE:
973 case EN_HSCROLL:
974 case EN_VSCROLL:
975 return FALSE;
976 default:
977 return FALSE;
978 }
979
980 // processed
981 return TRUE;
982 }
983
984 WXHBRUSH wxTextCtrl::OnCtlColor(WXHDC pDC, WXHWND WXUNUSED(pWnd), WXUINT WXUNUSED(nCtlColor),
985 #if wxUSE_CTL3D
986 WXUINT message,
987 WXWPARAM wParam,
988 WXLPARAM lParam
989 #else
990 WXUINT WXUNUSED(message),
991 WXWPARAM WXUNUSED(wParam),
992 WXLPARAM WXUNUSED(lParam)
993 #endif
994 )
995 {
996 #if wxUSE_CTL3D
997 if ( m_useCtl3D )
998 {
999 HBRUSH hbrush = Ctl3dCtlColorEx(message, wParam, lParam);
1000 return (WXHBRUSH) hbrush;
1001 }
1002 #endif // wxUSE_CTL3D
1003
1004 HDC hdc = (HDC)pDC;
1005 if (GetParent()->GetTransparentBackground())
1006 SetBkMode(hdc, TRANSPARENT);
1007 else
1008 SetBkMode(hdc, OPAQUE);
1009
1010 wxColour colBack = GetBackgroundColour();
1011
1012 if (!IsEnabled() && (GetWindowStyle() & wxTE_MULTILINE) == 0)
1013 colBack = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DFACE);
1014
1015 ::SetBkColor(hdc, wxColourToRGB(colBack));
1016 ::SetTextColor(hdc, wxColourToRGB(GetForegroundColour()));
1017
1018 wxBrush *brush = wxTheBrushList->FindOrCreateBrush(colBack, wxSOLID);
1019
1020 return (WXHBRUSH)brush->GetResourceHandle();
1021 }
1022
1023 // In WIN16, need to override normal erasing because
1024 // Ctl3D doesn't use the wxWindows background colour.
1025 #ifdef __WIN16__
1026 void wxTextCtrl::OnEraseBackground(wxEraseEvent& event)
1027 {
1028 wxColour col(m_backgroundColour);
1029
1030 #if wxUSE_CTL3D
1031 if (m_useCtl3D)
1032 col = wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW);
1033 #endif
1034
1035 RECT rect;
1036 ::GetClientRect(GetHwnd(), &rect);
1037
1038 COLORREF ref = PALETTERGB(col.Red(),
1039 col.Green(),
1040 col.Blue());
1041 HBRUSH hBrush = ::CreateSolidBrush(ref);
1042 if ( !hBrush )
1043 wxLogLastError(wxT("CreateSolidBrush"));
1044
1045 HDC hdc = (HDC)event.GetDC()->GetHDC();
1046
1047 int mode = ::SetMapMode(hdc, MM_TEXT);
1048
1049 ::FillRect(hdc, &rect, hBrush);
1050 ::DeleteObject(hBrush);
1051 ::SetMapMode(hdc, mode);
1052
1053 }
1054 #endif
1055
1056 void wxTextCtrl::AdjustSpaceLimit()
1057 {
1058 #ifndef __WIN16__
1059 unsigned int len = ::GetWindowTextLength(GetHwnd()),
1060 limit = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0);
1061 if ( len >= limit )
1062 {
1063 limit = len + 0x8000; // 32Kb
1064
1065 #if wxUSE_RICHEDIT
1066 if ( m_isRich )
1067 {
1068 // as a nice side effect, this also allows passing limit > 64Kb
1069 ::SendMessage(GetHwnd(), EM_EXLIMITTEXT, 0, limit);
1070 }
1071 else
1072 #endif // wxUSE_RICHEDIT
1073 {
1074 if ( limit > 0xffff )
1075 {
1076 // this will set it to a platform-dependent maximum (much more
1077 // than 64Kb under NT)
1078 limit = 0;
1079 }
1080
1081 ::SendMessage(GetHwnd(), EM_LIMITTEXT, limit, 0);
1082 }
1083 }
1084 #endif // !Win16
1085 }
1086
1087 bool wxTextCtrl::AcceptsFocus() const
1088 {
1089 // we don't want focus if we can't be edited
1090 return IsEditable() && wxControl::AcceptsFocus();
1091 }
1092
1093 wxSize wxTextCtrl::DoGetBestSize() const
1094 {
1095 int cx, cy;
1096 wxGetCharSize(GetHWND(), &cx, &cy, &GetFont());
1097
1098 int wText = DEFAULT_ITEM_WIDTH;
1099
1100 int hText = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
1101 if ( m_windowStyle & wxTE_MULTILINE )
1102 {
1103 hText *= wxMax(GetNumberOfLines(), 5);
1104 }
1105 //else: for single line control everything is ok
1106
1107 return wxSize(wText, hText);
1108 }
1109
1110 // ----------------------------------------------------------------------------
1111 // standard handlers for standard edit menu events
1112 // ----------------------------------------------------------------------------
1113
1114 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
1115 {
1116 Cut();
1117 }
1118
1119 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
1120 {
1121 Copy();
1122 }
1123
1124 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
1125 {
1126 Paste();
1127 }
1128
1129 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
1130 {
1131 Undo();
1132 }
1133
1134 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
1135 {
1136 Redo();
1137 }
1138
1139 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1140 {
1141 event.Enable( CanCut() );
1142 }
1143
1144 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1145 {
1146 event.Enable( CanCopy() );
1147 }
1148
1149 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1150 {
1151 event.Enable( CanPaste() );
1152 }
1153
1154 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1155 {
1156 event.Enable( CanUndo() );
1157 }
1158
1159 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1160 {
1161 event.Enable( CanRedo() );
1162 }
1163
1164 // the rest of the file only deals with the rich edit controls
1165 #if wxUSE_RICHEDIT
1166
1167 // ----------------------------------------------------------------------------
1168 // colour setting for the rich edit controls
1169 // ----------------------------------------------------------------------------
1170
1171 // Watcom C++ doesn't define this
1172 #ifndef SCF_ALL
1173 #define SCF_ALL 0x0004
1174 #endif
1175
1176 bool wxTextCtrl::SetBackgroundColour(const wxColour& colour)
1177 {
1178 if ( !wxTextCtrlBase::SetBackgroundColour(colour) )
1179 {
1180 // colour didn't really change
1181 return FALSE;
1182 }
1183
1184 if ( IsRich() )
1185 {
1186 // rich edit doesn't use WM_CTLCOLOR, hence we need to send
1187 // EM_SETBKGNDCOLOR additionally
1188 ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR, 0, wxColourToRGB(colour));
1189 }
1190
1191 return TRUE;
1192 }
1193
1194 bool wxTextCtrl::SetForegroundColour(const wxColour& colour)
1195 {
1196 if ( !wxTextCtrlBase::SetForegroundColour(colour) )
1197 {
1198 // colour didn't really change
1199 return FALSE;
1200 }
1201
1202 if ( IsRich() )
1203 {
1204 // change the colour of everything
1205 CHARFORMAT cf;
1206 wxZeroMemory(cf);
1207 cf.cbSize = sizeof(cf);
1208 cf.dwMask = CFM_COLOR;
1209 cf.crTextColor = wxColourToRGB(colour);
1210 ::SendMessage(GetHwnd(), EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf);
1211 }
1212
1213 return TRUE;
1214 }
1215
1216 // ----------------------------------------------------------------------------
1217 // styling support for rich edit controls
1218 // ----------------------------------------------------------------------------
1219
1220 bool wxTextCtrl::SetStyle(long start, long end, const wxTextAttr& style)
1221 {
1222 if ( !IsRich() )
1223 {
1224 // can't do it with normal text control
1225 return FALSE;
1226 }
1227
1228 // the rich text control doesn't handle setting background colour, so don't
1229 // even try if it's the only thing we want to change
1230 if ( wxRichEditModule::GetLoadedVersion() < 2 &&
1231 !style.HasFont() && !style.HasTextColour() )
1232 {
1233 // nothing to do: return TRUE if there was really nothing to do and
1234 // FALSE if we failed to set bg colour
1235 return !style.HasBackgroundColour();
1236 }
1237
1238 // order the range if needed
1239 if ( start > end )
1240 {
1241 long tmp = start;
1242 start = end;
1243 end = tmp;
1244 }
1245
1246 // we can only change the format of the selection, so select the range we
1247 // want and restore the old selection later
1248 long startOld, endOld;
1249 GetSelection(&startOld, &endOld);
1250
1251 // but do we really have to change the selection?
1252 bool changeSel = start != startOld || end != endOld;
1253
1254 if ( changeSel )
1255 SendMessage(GetHwnd(), EM_SETSEL, (WPARAM) start, (LPARAM) end);
1256
1257 // initialize CHARFORMAT struct
1258 #if wxUSE_RICHEDIT2
1259 CHARFORMAT2 cf;
1260 #else
1261 CHARFORMAT cf;
1262 #endif
1263 wxZeroMemory(cf);
1264 cf.cbSize = sizeof(cf);
1265
1266 if ( style.HasFont() )
1267 {
1268 cf.dwMask |= CFM_FACE | CFM_SIZE | CFM_CHARSET;
1269
1270 // fill in data from LOGFONT but recalculate lfHeight because we need
1271 // the real height in twips and not the negative number which
1272 // wxFillLogFont() returns (this is correct in general and works with
1273 // the Windows font mapper, but not here)
1274 LOGFONT lf;
1275 wxFillLogFont(&lf, &style.GetFont());
1276 cf.yHeight = 20*style.GetFont().GetPointSize(); // 1 pt = 20 twips
1277 cf.bCharSet = lf.lfCharSet;
1278 cf.bPitchAndFamily = lf.lfPitchAndFamily;
1279 wxStrncpy( cf.szFaceName, lf.lfFaceName, WXSIZEOF(cf.szFaceName) );
1280
1281 // also deal with underline/italic/bold attributes
1282 if ( lf.lfItalic )
1283 {
1284 cf.dwMask |= CFM_ITALIC;
1285 cf.dwEffects |= CFE_ITALIC;
1286 }
1287
1288 if ( lf.lfWeight == FW_BOLD )
1289 {
1290 cf.dwMask |= CFM_BOLD;
1291 cf.dwEffects |= CFE_BOLD;
1292 }
1293
1294 if ( lf.lfUnderline )
1295 {
1296 cf.dwMask |= CFM_UNDERLINE;
1297 cf.dwEffects |= CFE_UNDERLINE;
1298 }
1299
1300 // strikeout fonts are not supported by wxWindows
1301 }
1302
1303 if ( style.HasTextColour() )
1304 {
1305 cf.dwMask |= CFM_COLOR;
1306 cf.crTextColor = wxColourToRGB(style.GetTextColour());
1307 }
1308
1309 #if wxUSE_RICHEDIT2
1310 #ifndef CFM_BACKCOLOR
1311 #define CFM_BACKCOLOR 0x04000000
1312 #endif
1313
1314 if ( wxRichEditModule::GetLoadedVersion() > 1 && style.HasBackgroundColour() )
1315 {
1316 cf.dwMask |= CFM_BACKCOLOR;
1317 cf.crBackColor = wxColourToRGB(style.GetBackgroundColour());
1318 }
1319 #endif
1320 // do format the selection
1321 bool ok = ::SendMessage(GetHwnd(), EM_SETCHARFORMAT,
1322 SCF_SELECTION, (LPARAM)&cf) != 0;
1323 if ( !ok )
1324 {
1325 wxLogDebug(_T("SendMessage(EM_SETCHARFORMAT, SCF_SELECTION) failed"));
1326 }
1327
1328 if ( changeSel )
1329 {
1330 // restore the original selection
1331 SendMessage(GetHwnd(), EM_SETSEL, (WPARAM)startOld, (LPARAM)endOld);
1332 }
1333
1334 return ok;
1335 }
1336
1337 // ----------------------------------------------------------------------------
1338 // wxRichEditModule
1339 // ----------------------------------------------------------------------------
1340
1341 bool wxRichEditModule::OnInit()
1342 {
1343 // don't do anything - we will load it when needed
1344 return TRUE;
1345 }
1346
1347 void wxRichEditModule::OnExit()
1348 {
1349 if ( ms_hRichEdit )
1350 {
1351 FreeLibrary(ms_hRichEdit);
1352 }
1353 }
1354
1355 /* static */
1356 bool wxRichEditModule::Load(int version)
1357 {
1358 wxCHECK_MSG( version >= 1 && version <= 3, FALSE,
1359 _T("incorrect richedit control version requested") );
1360
1361 if ( version <= ms_verRichEdit )
1362 {
1363 // we've already got this or better
1364 return TRUE;
1365 }
1366
1367 if ( ms_hRichEdit )
1368 {
1369 ::FreeLibrary(ms_hRichEdit);
1370 }
1371
1372 // always try load riched20.dll first - like this we won't have to reload
1373 // it later if we're first asked for RE 1 and then for RE 2 or 3
1374 wxString dllname = _T("riched20.dll");
1375 ms_hRichEdit = ::LoadLibrary(dllname);
1376 ms_verRichEdit = 2; // no way to tell if it's 2 or 3, assume 2
1377
1378 if ( !ms_hRichEdit && (version == 1) )
1379 {
1380 // fall back to RE 1
1381 dllname = _T("riched32.dll");
1382 ms_hRichEdit = ::LoadLibrary(dllname);
1383 ms_verRichEdit = 1;
1384 }
1385
1386 if ( !ms_hRichEdit )
1387 {
1388 wxLogSysError(_("Could not load Rich Edit DLL '%s'"), dllname.c_str());
1389
1390 ms_verRichEdit = -1;
1391
1392 return FALSE;
1393 }
1394
1395 return TRUE;
1396 }
1397
1398 #endif // wxUSE_RICHEDIT
1399