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