]> git.saurik.com Git - wxWidgets.git/blob - src/msw/textctrl.cpp
1. DoSetSize() simplified, DoGetBestSize() introduced
[wxWidgets.git] / src / msw / textctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #ifdef __GNUG__
13 #pragma implementation "textctrl.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef WX_PRECOMP
24 #include "wx/textctrl.h"
25 #include "wx/settings.h"
26 #include "wx/brush.h"
27 #include "wx/utils.h"
28 #include "wx/log.h"
29 #endif
30
31 #if wxUSE_CLIPBOARD
32 #include "wx/app.h"
33 #include "wx/clipbrd.h"
34 #endif
35
36 #include "wx/msw/private.h"
37
38 #include <windows.h>
39 #include <stdlib.h>
40
41 #if wxUSE_IOSTREAMH
42 # include <fstream.h>
43 #else
44 # include <fstream>
45 #endif
46
47 #include <sys/types.h>
48 #ifndef __MWERKS__
49 #include <sys/stat.h>
50 #else
51 #include <stat.h>
52 #endif
53 #if defined(__BORLANDC__) && !defined(__WIN32__)
54 #include <alloc.h>
55 #else
56 #if !defined(__GNUWIN32__) && !defined(__SALFORDC__)
57 #include <malloc.h>
58 #endif
59 #define farmalloc malloc
60 #define farfree free
61 #endif
62 #include <windowsx.h>
63
64 #include <string.h>
65
66 #if wxUSE_RICHEDIT && !defined(__GNUWIN32__)
67 #include <richedit.h>
68 #endif
69
70 #if !USE_SHARED_LIBRARY
71
72 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxControl)
73
74 BEGIN_EVENT_TABLE(wxTextCtrl, wxControl)
75 EVT_CHAR(wxTextCtrl::OnChar)
76 EVT_DROP_FILES(wxTextCtrl::OnDropFiles)
77
78 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
79 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
80 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
81 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
82 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
83
84 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
85 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
86 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
87 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
88 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
89 END_EVENT_TABLE()
90
91 #endif // USE_SHARED_LIBRARY
92
93 // Text item
94 wxTextCtrl::wxTextCtrl()
95 #ifndef NO_TEXT_WINDOW_STREAM
96 : streambuf()
97 #endif
98 {
99 #if wxUSE_RICHEDIT
100 m_isRich = FALSE;
101 #endif
102 }
103
104 bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id,
105 const wxString& value,
106 const wxPoint& pos,
107 const wxSize& size, long style,
108 const wxValidator& validator,
109 const wxString& name)
110 {
111 SetName(name);
112 SetValidator(validator);
113 if (parent) parent->AddChild(this);
114
115 m_windowStyle = style;
116
117 // Should this be taken from the system colours?
118 // SetBackgroundColour(wxColour(255, 255, 255));
119
120 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW));
121
122 SetForegroundColour(parent->GetForegroundColour()) ;
123
124 if ( id == -1 )
125 m_windowId = (int)NewControlId();
126 else
127 m_windowId = id;
128
129 int x = pos.x;
130 int y = pos.y;
131 int width = size.x;
132 int height = size.y;
133
134 long msStyle = ES_LEFT | WS_VISIBLE | WS_CHILD | WS_TABSTOP;
135 if (m_windowStyle & wxTE_MULTILINE)
136 {
137 wxASSERT_MSG( !(m_windowStyle & wxTE_PROCESS_ENTER),
138 _T("wxTE_PROCESS_ENTER style is ignored for multiline controls") );
139
140 msStyle |= ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL ; // WS_BORDER
141 m_windowStyle |= wxTE_PROCESS_ENTER;
142 }
143 else
144 msStyle |= ES_AUTOHSCROLL ;
145
146 if (m_windowStyle & wxTE_READONLY)
147 msStyle |= ES_READONLY;
148
149 if (m_windowStyle & wxHSCROLL)
150 msStyle |= (WS_HSCROLL | ES_AUTOHSCROLL) ;
151 if (m_windowStyle & wxTE_PASSWORD) // hidden input
152 msStyle |= ES_PASSWORD;
153
154 // we always want the characters and the arrows
155 m_lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS;
156
157 // we may have several different cases:
158 // 1. normal case: both TAB and ENTER are used for dialog navigation
159 // 2. ctrl which wants TAB for itself: ENTER is used to pass to the next
160 // control in the dialog
161 // 3. ctrl which wants ENTER for itself: TAB is used for dialog navigation
162 // 4. ctrl which wants both TAB and ENTER: Ctrl-ENTER is used to pass to
163 // the next control
164 if ( m_windowStyle & wxTE_PROCESS_ENTER )
165 m_lDlgCode |= DLGC_WANTMESSAGE;
166 if ( m_windowStyle & wxTE_PROCESS_TAB )
167 m_lDlgCode |= DLGC_WANTTAB;
168
169 const wxChar *windowClass = _T("EDIT");
170
171 #if wxUSE_RICHEDIT
172 if ( m_windowStyle & wxTE_MULTILINE )
173 {
174 msStyle |= ES_AUTOVSCROLL;
175 m_isRich = TRUE;
176 windowClass = _T("RichEdit") ;
177 }
178 else
179 m_isRich = FALSE;
180 #endif
181
182 bool want3D;
183 WXDWORD exStyle = Determine3DEffects(WS_EX_CLIENTEDGE, &want3D) ;
184
185 // If we're in Win95, and we want a simple 2D border,
186 // then make it an EDIT control instead.
187 #if wxUSE_RICHEDIT
188 if (m_windowStyle & wxSIMPLE_BORDER)
189 {
190 windowClass = _T("EDIT");
191 m_isRich = FALSE;
192 }
193 #endif
194
195 // Even with extended styles, need to combine with WS_BORDER
196 // for them to look right.
197 if ( want3D || wxStyleHasBorder(m_windowStyle) )
198 msStyle |= WS_BORDER;
199
200 m_hWnd = (WXHWND)::CreateWindowEx(exStyle, windowClass, NULL,
201 msStyle,
202 0, 0, 0, 0, (HWND) ((wxWindow*)parent)->GetHWND(), (HMENU)m_windowId,
203 wxGetInstance(), NULL);
204
205 wxCHECK_MSG( m_hWnd, FALSE, _T("Failed to create text ctrl") );
206
207 #if wxUSE_CTL3D
208 if ( want3D )
209 {
210 Ctl3dSubclassCtl((HWND)m_hWnd);
211 m_useCtl3D = TRUE;
212 }
213 #endif
214
215 #if wxUSE_RICHEDIT
216 if (m_isRich)
217 {
218 // Have to enable events
219 ::SendMessage((HWND)m_hWnd, EM_SETEVENTMASK, 0,
220 ENM_CHANGE | ENM_DROPFILES | ENM_SELCHANGE | ENM_UPDATE);
221 }
222 #endif
223
224 SubclassWin(GetHWND());
225
226 if ( parent->GetFont().Ok() && parent->GetFont().Ok() )
227 {
228 SetFont(parent->GetFont());
229 }
230 else
231 {
232 SetFont(wxSystemSettings::GetSystemFont(wxSYS_SYSTEM_FONT));
233 }
234
235 SetSize(x, y, width, height);
236
237 // Causes a crash for Symantec C++ and WIN32 for some reason
238 #if !(defined(__SC__) && defined(__WIN32__))
239 if ( !value.IsEmpty() )
240 {
241 SetValue(value);
242 }
243 #endif
244
245 return TRUE;
246 }
247
248 // Make sure the window style (etc.) reflects the HWND style (roughly)
249 void wxTextCtrl::AdoptAttributesFromHWND()
250 {
251 wxWindow::AdoptAttributesFromHWND();
252
253 HWND hWnd = GetHwnd();
254 long style = GetWindowLong((HWND) hWnd, GWL_STYLE);
255
256 // retrieve the style to see whether this is an edit or richedit ctrl
257 #if wxUSE_RICHEDIT
258 wxChar buf[256];
259
260 #ifndef __WIN32__
261 GetClassName((HWND) hWnd, buf, 256);
262 #else
263 #ifdef UNICODE
264 GetClassNameW((HWND) hWnd, buf, 256);
265 #else
266 #ifdef __TWIN32__
267 GetClassName((HWND) hWnd, buf, 256);
268 #else
269 GetClassNameA((HWND) hWnd, buf, 256);
270 #endif
271 #endif
272 #endif
273
274 wxString str(buf);
275 str.UpperCase();
276
277 if (str == _T("EDIT"))
278 m_isRich = FALSE;
279 else
280 m_isRich = TRUE;
281 #endif
282
283 if (style & ES_MULTILINE)
284 m_windowStyle |= wxTE_MULTILINE;
285 if (style & ES_PASSWORD)
286 m_windowStyle |= wxTE_PASSWORD;
287 if (style & ES_READONLY)
288 m_windowStyle |= wxTE_READONLY;
289 if (style & ES_WANTRETURN)
290 m_windowStyle |= wxTE_PROCESS_ENTER;
291 }
292
293 void wxTextCtrl::SetupColours()
294 {
295 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW));
296 SetForegroundColour(GetParent()->GetForegroundColour());
297 }
298
299 wxString wxTextCtrl::GetValue() const
300 {
301 return wxGetWindowText(GetHWND());
302 }
303
304 void wxTextCtrl::SetValue(const wxString& value)
305 {
306 // If newlines are denoted by just 10, must stick 13 in front.
307 int singletons = 0;
308 int len = value.Length();
309 int i;
310 for (i = 0; i < len; i ++)
311 {
312 if ((i > 0) && (value[i] == 10) && (value[i-1] != 13))
313 singletons ++;
314 }
315 if (singletons > 0)
316 {
317 wxChar *tmp = new wxChar[len + singletons + 1];
318 int j = 0;
319 for (i = 0; i < len; i ++)
320 {
321 if ((i > 0) && (value[i] == 10) && (value[i-1] != 13))
322 {
323 tmp[j] = 13;
324 j ++;
325 }
326 tmp[j] = value[i];
327 j ++;
328 }
329 tmp[j] = 0;
330 SetWindowText(GetHwnd(), tmp);
331 delete[] tmp;
332 }
333 else
334 SetWindowText(GetHwnd(), (const wxChar *)value);
335
336 AdjustSpaceLimit();
337 }
338
339 wxSize wxTextCtrl::DoGetBestSize()
340 {
341 int cx, cy;
342 wxGetCharSize(GetHWND(), &cx, &cy, &GetFont());
343
344 int wText = DEFAULT_ITEM_WIDTH;
345 int hText = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
346
347 return wxSize(wText, hText);
348 }
349
350 // Clipboard operations
351 void wxTextCtrl::Copy()
352 {
353 if (CanCopy())
354 {
355 HWND hWnd = GetHwnd();
356 SendMessage(hWnd, WM_COPY, 0, 0L);
357 }
358 }
359
360 void wxTextCtrl::Cut()
361 {
362 if (CanCut())
363 {
364 HWND hWnd = GetHwnd();
365 SendMessage(hWnd, WM_CUT, 0, 0L);
366 }
367 }
368
369 void wxTextCtrl::Paste()
370 {
371 if (CanPaste())
372 {
373 HWND hWnd = GetHwnd();
374 SendMessage(hWnd, WM_PASTE, 0, 0L);
375 }
376 }
377
378 void wxTextCtrl::SetEditable(bool editable)
379 {
380 HWND hWnd = GetHwnd();
381 SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
382 }
383
384 void wxTextCtrl::SetInsertionPoint(long pos)
385 {
386 HWND hWnd = GetHwnd();
387 #ifdef __WIN32__
388 #if wxUSE_RICHEDIT
389 if ( m_isRich)
390 {
391 CHARRANGE range;
392 range.cpMin = pos;
393 range.cpMax = pos;
394 SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range);
395 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
396 }
397 else
398 #endif
399 {
400 SendMessage(hWnd, EM_SETSEL, pos, pos);
401 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
402 }
403 #else
404 SendMessage(hWnd, EM_SETSEL, 0, MAKELPARAM(pos, pos));
405 #endif
406 char *nothing = "";
407 SendMessage(hWnd, EM_REPLACESEL, 0, (LPARAM)nothing);
408 }
409
410 void wxTextCtrl::SetInsertionPointEnd()
411 {
412 long pos = GetLastPosition();
413 SetInsertionPoint(pos);
414 }
415
416 long wxTextCtrl::GetInsertionPoint() const
417 {
418 #if wxUSE_RICHEDIT
419 if (m_isRich)
420 {
421 CHARRANGE range;
422 range.cpMin = 0;
423 range.cpMax = 0;
424 SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range);
425 return range.cpMin;
426 }
427 #endif
428
429 DWORD Pos=(DWORD)SendMessage(GetHwnd(), EM_GETSEL, 0, 0L);
430 return Pos&0xFFFF;
431 }
432
433 long wxTextCtrl::GetLastPosition() const
434 {
435 HWND hWnd = GetHwnd();
436
437 // Will always return a number > 0 (according to docs)
438 int noLines = (int)SendMessage(hWnd, EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0L);
439
440 // This gets the char index for the _beginning_ of the last line
441 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)(noLines-1), (LPARAM)0L);
442
443 // Get number of characters in the last line. We'll add this to the character
444 // index for the last line, 1st position.
445 int lineLength = (int)SendMessage(hWnd, EM_LINELENGTH, (WPARAM)charIndex, (LPARAM)0L);
446
447 return (long)(charIndex + lineLength);
448 }
449
450 void wxTextCtrl::Replace(long from, long to, const wxString& value)
451 {
452 #if wxUSE_CLIPBOARD
453 HWND hWnd = GetHwnd();
454 long fromChar = from;
455 long toChar = to;
456
457 // Set selection and remove it
458 #ifdef __WIN32__
459 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
460 #else
461 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
462 #endif
463 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
464
465 // Now replace with 'value', by pasting.
466 wxSetClipboardData(wxDF_TEXT, (wxObject *) (const wxChar *)value, 0, 0);
467
468 // Paste into edit control
469 SendMessage(hWnd, WM_PASTE, (WPARAM)0, (LPARAM)0L);
470 #else
471 wxFAIL_MSG("wxTextCtrl::Replace not implemented if wxUSE_CLIPBOARD is 0.");
472 #endif
473 }
474
475 void wxTextCtrl::Remove(long from, long to)
476 {
477 HWND hWnd = GetHwnd();
478 long fromChar = from;
479 long toChar = to;
480
481 // Cut all selected text
482 #ifdef __WIN32__
483 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
484 #else
485 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
486 #endif
487 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
488 }
489
490 void wxTextCtrl::SetSelection(long from, long to)
491 {
492 HWND hWnd = GetHwnd();
493 long fromChar = from;
494 long toChar = to;
495 // if from and to are both -1, it means
496 // (in wxWindows) that all text should be selected.
497 // This translates into Windows convention
498 if ((from == -1) && (to == -1))
499 {
500 fromChar = 0;
501 toChar = -1;
502 }
503
504 #ifdef __WIN32__
505 SendMessage(hWnd, EM_SETSEL, (WPARAM)fromChar, (LPARAM)toChar);
506 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
507 #else
508 // WPARAM is 0: selection is scrolled into view
509 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
510 #endif
511 }
512
513 bool wxTextCtrl::LoadFile(const wxString& file)
514 {
515 if (!wxFileExists(WXSTRINGCAST file))
516 return FALSE;
517
518 m_fileName = file;
519
520 Clear();
521
522 // ifstream input(WXSTRINGCAST file, ios::nocreate | ios::in);
523 ifstream input(MBSTRINGCAST file.mb_str(wxConvFile), ios::in);
524
525 if (!input.bad())
526 {
527 // Previously a SETSEL/REPLACESEL call-pair were done to insert
528 // line by line into the control. Apart from being very slow this
529 // was limited to 32K of text by the external interface presenting
530 // positions as signed shorts. Now load in one chunk...
531 // Note use of 'farmalloc' as in Borland 3.1 'size_t' is 16-bits...
532
533 #ifdef __SALFORDC__
534 struct _stat stat_buf;
535 if (stat(MBSTRINGCAST file.mb_str(wxConvFile), &stat_buf) < 0)
536 return FALSE;
537 #else
538 struct stat stat_buf;
539 if (stat(file.mb_str(wxConvFile), &stat_buf) < 0)
540 return FALSE;
541 #endif
542
543 // wxChar *tmp_buffer = (wxChar*)farmalloc(stat_buf.st_size+1);
544 // This may need to be a bigger buffer than the file size suggests,
545 // if it's a UNIX file. Give it an extra 1000 just in case.
546 wxChar *tmp_buffer = (wxChar*)farmalloc((size_t)(stat_buf.st_size+1+1000));
547 char *read_buffer = new char[512];
548 long no_lines = 0;
549 long pos = 0;
550 while (!input.eof() && input.peek() != EOF)
551 {
552 input.getline(read_buffer, 500);
553 int len = strlen(read_buffer);
554 wxBuffer[len] = 13;
555 wxBuffer[len+1] = 10;
556 wxBuffer[len+2] = 0;
557 #if wxUSE_UNICODE
558 pos += wxConvCurrent->MB2WC(tmp_buffer+pos, read_buffer, (size_t)-1);
559 #else
560 strcpy(tmp_buffer+pos, read_buffer);
561 pos += strlen(read_buffer);
562 #endif
563 no_lines++;
564 }
565 delete[] read_buffer;
566
567 SetWindowText(GetHwnd(), tmp_buffer);
568 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
569 farfree(tmp_buffer);
570
571 // update the size limit if needed
572 AdjustSpaceLimit();
573
574 return TRUE;
575 }
576 return FALSE;
577 }
578
579 // If file is null, try saved file name first
580 // Returns TRUE if succeeds.
581 bool wxTextCtrl::SaveFile(const wxString& file)
582 {
583 wxString theFile(file);
584
585 if (theFile == _T(""))
586 theFile = m_fileName;
587
588 if (theFile == _T(""))
589 return FALSE;
590
591 m_fileName = theFile;
592
593 ofstream output(MBSTRINGCAST theFile.mb_str(wxConvFile));
594 if (output.bad())
595 return FALSE;
596
597 // This will only save 64K max
598 unsigned long nbytes = SendMessage(GetHwnd(), WM_GETTEXTLENGTH, 0, 0);
599 char *tmp_buffer = (char*)farmalloc((size_t)(nbytes+1));
600 SendMessage(GetHwnd(), WM_GETTEXT, (WPARAM)(nbytes+1), (LPARAM)tmp_buffer);
601 char *pstr = tmp_buffer;
602
603 // Convert \r\n to just \n
604 while (*pstr)
605 {
606 if (*pstr != '\r')
607 output << *pstr;
608 pstr++;
609 }
610
611 farfree(tmp_buffer);
612 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
613
614 return TRUE;
615 }
616
617 void wxTextCtrl::WriteText(const wxString& text)
618 {
619 // Covert \n to \r\n
620 int len = text.Length();
621 char *newtext = new char[(len*2)+1];
622 int i = 0;
623 int j = 0;
624 while (i < len)
625 {
626 if (text[i] == '\n')
627 {
628 newtext[j] = '\r';
629 j ++;
630 }
631 newtext[j] = text[i];
632 i ++;
633 j ++;
634 }
635 newtext[j] = 0;
636 SendMessage(GetHwnd(), EM_REPLACESEL, 0, (LPARAM)newtext);
637 delete[] newtext;
638
639 AdjustSpaceLimit();
640 }
641
642 void wxTextCtrl::AppendText(const wxString& text)
643 {
644 SetInsertionPointEnd();
645 WriteText(text);
646 }
647
648 void wxTextCtrl::Clear()
649 {
650 SetWindowText(GetHwnd(), _T(""));
651 }
652
653 bool wxTextCtrl::IsModified() const
654 {
655 return (SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0);
656 }
657
658 // Makes 'unmodified'
659 void wxTextCtrl::DiscardEdits()
660 {
661 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
662 }
663
664 /*
665 * Some of the following functions are yet to be implemented
666 *
667 */
668
669 int wxTextCtrl::GetNumberOfLines() const
670 {
671 return (int)SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0);
672 }
673
674 long wxTextCtrl::XYToPosition(long x, long y) const
675 {
676 HWND hWnd = GetHwnd();
677
678 // This gets the char index for the _beginning_ of this line
679 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
680 return (long)(x + charIndex);
681 }
682
683 void wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
684 {
685 HWND hWnd = GetHwnd();
686
687 // This gets the line number containing the character
688 int lineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0);
689 // This gets the char index for the _beginning_ of this line
690 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
691 // The X position must therefore be the different between pos and charIndex
692 *x = (long)(pos - charIndex);
693 *y = (long)lineNo;
694 }
695
696 void wxTextCtrl::ShowPosition(long pos)
697 {
698 HWND hWnd = GetHwnd();
699
700 // To scroll to a position, we pass the number of lines and characters
701 // to scroll *by*. This means that we need to:
702 // (1) Find the line position of the current line.
703 // (2) Find the line position of pos.
704 // (3) Scroll by (pos - current).
705 // For now, ignore the horizontal scrolling.
706
707 // Is this where scrolling is relative to - the line containing the caret?
708 // Or is the first visible line??? Try first visible line.
709 // int currentLineLineNo1 = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L);
710
711 int currentLineLineNo = (int)SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L);
712
713 int specifiedLineLineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L);
714
715 int linesToScroll = specifiedLineLineNo - currentLineLineNo;
716
717 if (linesToScroll != 0)
718 (void)SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll);
719 }
720
721 int wxTextCtrl::GetLineLength(long lineNo) const
722 {
723 long charIndex = XYToPosition(0, lineNo);
724 int len = (int)SendMessage(GetHwnd(), EM_LINELENGTH, charIndex, 0);
725 return len;
726 }
727
728 wxString wxTextCtrl::GetLineText(long lineNo) const
729 {
730 size_t len = (size_t)GetLineLength(lineNo);
731 char *buf = (char *)malloc(len);
732 *(WORD *)buf = len;
733 int noChars = (int)SendMessage(GetHwnd(), EM_GETLINE, lineNo, (LPARAM)buf);
734 buf[noChars] = 0;
735
736 wxString str(buf);
737
738 free(buf);
739
740 return str;
741 }
742
743 bool wxTextCtrl::CanCopy() const
744 {
745 // Can copy if there's a selection
746 long from, to;
747 GetSelection(& from, & to);
748 return (from != to) ;
749 }
750
751 bool wxTextCtrl::CanCut() const
752 {
753 // Can cut if there's a selection
754 long from, to;
755 GetSelection(& from, & to);
756 return (from != to) ;
757 }
758
759 bool wxTextCtrl::CanPaste() const
760 {
761 #if wxUSE_RICHEDIT
762 if (m_isRich)
763 {
764 int dataFormat = 0; // 0 == any format
765 return (::SendMessage( GetHwnd(), EM_CANPASTE, (WPARAM) (UINT) dataFormat, 0) != 0);
766 }
767 #endif
768 if (!IsEditable())
769 return FALSE;
770
771 // Standard edit control: check for straight text on clipboard
772 bool isTextAvailable = FALSE;
773 if (::OpenClipboard((HWND) wxTheApp->GetTopWindow()->GetHWND()))
774 {
775 isTextAvailable = (::IsClipboardFormatAvailable(CF_TEXT) != 0);
776 ::CloseClipboard();
777 }
778 return isTextAvailable;
779 }
780
781 // Undo/redo
782 void wxTextCtrl::Undo()
783 {
784 if (CanUndo())
785 {
786 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
787 }
788 }
789
790 void wxTextCtrl::Redo()
791 {
792 if (CanRedo())
793 {
794 // Same as Undo, since Undo undoes the undo, i.e. a redo.
795 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
796 }
797 }
798
799 bool wxTextCtrl::CanUndo() const
800 {
801 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
802 }
803
804 bool wxTextCtrl::CanRedo() const
805 {
806 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
807 }
808
809 // If the return values from and to are the same, there is no
810 // selection.
811 void wxTextCtrl::GetSelection(long* from, long* to) const
812 {
813 #if wxUSE_RICHEDIT
814 if (m_isRich)
815 {
816 CHARRANGE charRange;
817 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) (CHARRANGE*) & charRange);
818
819 *from = charRange.cpMin;
820 *to = charRange.cpMax;
821
822 return;
823 }
824 #endif
825 DWORD dwStart, dwEnd;
826 WPARAM wParam = (WPARAM) (DWORD*) & dwStart; // receives starting position
827 LPARAM lParam = (LPARAM) (DWORD*) & dwEnd; // receives ending position
828
829 ::SendMessage(GetHwnd(), EM_GETSEL, wParam, lParam);
830
831 *from = dwStart;
832 *to = dwEnd;
833 }
834
835 bool wxTextCtrl::IsEditable() const
836 {
837 long style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
838
839 return ((style & ES_READONLY) == 0);
840 }
841
842 void wxTextCtrl::Command(wxCommandEvent & event)
843 {
844 SetValue (event.GetString());
845 ProcessCommand (event);
846 }
847
848 void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event)
849 {
850 // By default, load the first file into the text window.
851 if (event.GetNumberOfFiles() > 0)
852 {
853 LoadFile(event.GetFiles()[0]);
854 }
855 }
856
857 // The streambuf code was partly taken from chapter 3 by Jerry Schwarz of
858 // AT&T's "C++ Lanuage System Release 3.0 Library Manual" - Stein Somers
859
860 //=========================================================================
861 // Called then the buffer is full (gcc 2.6.3)
862 // or when "endl" is output (Borland 4.5)
863 //=========================================================================
864 // Class declaration using multiple inheritance doesn't work properly for
865 // Borland. See note in textctrl.h.
866 #ifndef NO_TEXT_WINDOW_STREAM
867 int wxTextCtrl::overflow(int c)
868 {
869 // Make sure there is a holding area
870 // this is not needed in <iostream> usage as it automagically allocates
871 // it, but does someone want to emulate it for safety's sake?
872 #if wxUSE_IOSTREAMH
873 if ( allocate()==EOF )
874 {
875 wxLogError("Streambuf allocation failed");
876 return EOF;
877 }
878 #endif
879
880 // Verify that there are no characters in get area
881 if ( gptr() && gptr() < egptr() )
882 {
883 wxError("Who's trespassing my get area?","Internal error");
884 return EOF;
885 }
886
887 // Reset get area
888 setg(0,0,0);
889
890 // Make sure there is a put area
891 if ( ! pptr() )
892 {
893 /* This doesn't seem to be fatal so comment out error message */
894 // wxError("Put area not opened","Internal error");
895
896 #if wxUSE_IOSTREAMH
897 setp( base(), base() );
898 #else
899 setp( pbase(), pbase() );
900 #endif
901 }
902
903 // Determine how many characters have been inserted but no consumed
904 int plen = pptr() - pbase();
905
906 // Now Jerry relies on the fact that the buffer is at least 2 chars
907 // long, but the holding area "may be as small as 1" ???
908 // And we need an additional \0, so let's keep this inefficient but
909 // safe copy.
910
911 // If c!=EOF, it is a character that must also be comsumed
912 int xtra = c==EOF? 0 : 1;
913
914 // Write temporary C-string to wxTextWindow
915 {
916 char *txt = new char[plen+xtra+1];
917 memcpy(txt, pbase(), plen);
918 txt[plen] = (char)c; // append c
919 txt[plen+xtra] = '\0'; // append '\0' or overwrite c
920 // If the put area already contained \0, output will be truncated there
921 AppendText(txt);
922 delete[] txt;
923 }
924
925 // Reset put area
926 setp(pbase(), epptr());
927
928 #if defined(__WATCOMC__)
929 return __NOT_EOF;
930 #elif defined(zapeof) // HP-UX (all cfront based?)
931 return zapeof(c);
932 #else
933 return c!=EOF ? c : 0; // this should make everybody happy
934 #endif
935
936 /* OLD CODE
937 int len = pptr() - pbase();
938 char *txt = new char[len+1];
939 strncpy(txt, pbase(), len);
940 txt[len] = '\0';
941 (*this) << txt;
942 setp(pbase(), epptr());
943 delete[] txt;
944 return EOF;
945 */
946 }
947
948 //=========================================================================
949 // called then "endl" is output (gcc) or then explicit sync is done (Borland)
950 //=========================================================================
951 int wxTextCtrl::sync()
952 {
953 // Verify that there are no characters in get area
954 if ( gptr() && gptr() < egptr() )
955 {
956 wxError("Who's trespassing my get area?","Internal error");
957 return EOF;
958 }
959
960 if ( pptr() && pptr() > pbase() ) return overflow(EOF);
961
962 return 0;
963 /* OLD CODE
964 int len = pptr() - pbase();
965 char *txt = new char[len+1];
966 strncpy(txt, pbase(), len);
967 txt[len] = '\0';
968 (*this) << txt;
969 setp(pbase(), epptr());
970 delete[] txt;
971 return 0;
972 */
973 }
974
975 //=========================================================================
976 // Should not be called by a "ostream". Used by a "istream"
977 //=========================================================================
978 int wxTextCtrl::underflow()
979 {
980 return EOF;
981 }
982 #endif
983
984 wxTextCtrl& wxTextCtrl::operator<<(const wxString& s)
985 {
986 AppendText(s);
987 return *this;
988 }
989
990 wxTextCtrl& wxTextCtrl::operator<<(float f)
991 {
992 wxString str;
993 str.Printf(_T("%.2f"), f);
994 AppendText(str);
995 return *this;
996 }
997
998 wxTextCtrl& wxTextCtrl::operator<<(double d)
999 {
1000 wxString str;
1001 str.Printf(_T("%.2f"), d);
1002 AppendText(str);
1003 return *this;
1004 }
1005
1006 wxTextCtrl& wxTextCtrl::operator<<(int i)
1007 {
1008 wxString str;
1009 str.Printf(_T("%d"), i);
1010 AppendText(str);
1011 return *this;
1012 }
1013
1014 wxTextCtrl& wxTextCtrl::operator<<(long i)
1015 {
1016 wxString str;
1017 str.Printf(_T("%ld"), i);
1018 AppendText(str);
1019 return *this;
1020 }
1021
1022 wxTextCtrl& wxTextCtrl::operator<<(const char c)
1023 {
1024 char buf[2];
1025
1026 buf[0] = c;
1027 buf[1] = 0;
1028 AppendText(buf);
1029 return *this;
1030 }
1031
1032 WXHBRUSH wxTextCtrl::OnCtlColor(WXHDC pDC, WXHWND pWnd, WXUINT nCtlColor,
1033 WXUINT message, WXWPARAM wParam, WXLPARAM lParam)
1034 {
1035 #if wxUSE_CTL3D
1036 if ( m_useCtl3D )
1037 {
1038 HBRUSH hbrush = Ctl3dCtlColorEx(message, wParam, lParam);
1039 return (WXHBRUSH) hbrush;
1040 }
1041 #endif
1042
1043 if (GetParent()->GetTransparentBackground())
1044 SetBkMode((HDC) pDC, TRANSPARENT);
1045 else
1046 SetBkMode((HDC) pDC, OPAQUE);
1047
1048 ::SetBkColor((HDC) pDC, RGB(GetBackgroundColour().Red(), GetBackgroundColour().Green(), GetBackgroundColour().Blue()));
1049 ::SetTextColor((HDC) pDC, RGB(GetForegroundColour().Red(), GetForegroundColour().Green(), GetForegroundColour().Blue()));
1050
1051 wxBrush *backgroundBrush = wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(), wxSOLID);
1052
1053 // Note that this will be cleaned up in wxApp::OnIdle, if backgroundBrush
1054 // has a zero usage count.
1055 // NOT NOW - will be cleaned up at end of app.
1056 // backgroundBrush->RealizeResource();
1057 return (WXHBRUSH) backgroundBrush->GetResourceHandle();
1058 }
1059
1060 void wxTextCtrl::OnChar(wxKeyEvent& event)
1061 {
1062 switch ( event.KeyCode() )
1063 {
1064 case WXK_RETURN:
1065 if ( !(m_windowStyle & wxTE_MULTILINE) )
1066 {
1067 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1068 event.SetEventObject( this );
1069 if ( GetEventHandler()->ProcessEvent(event) )
1070 return;
1071 }
1072 //else: multiline controls need Enter for themselves
1073
1074 break;
1075
1076 case WXK_TAB:
1077 // always produce navigation event - even if we process TAB
1078 // ourselves the fact that we got here means that the user code
1079 // decided to skip processing of this TAB - probably to let it
1080 // do its default job.
1081 //
1082 // NB: Notice that Ctrl-Tab is handled elsewhere and Alt-Tab is
1083 // handled by Windows
1084 {
1085 wxNavigationKeyEvent eventNav;
1086 eventNav.SetDirection(!event.ShiftDown());
1087 eventNav.SetWindowChange(FALSE);
1088 eventNav.SetEventObject(this);
1089
1090 if ( GetEventHandler()->ProcessEvent(eventNav) )
1091 return;
1092 }
1093 break;
1094
1095 default:
1096 event.Skip();
1097 return;
1098 }
1099
1100 // don't just call event.Skip() because this will cause TABs and ENTERs
1101 // be passed upwards and we don't always want this - instead process it
1102 // right here
1103
1104 // FIXME
1105 event.Skip();
1106 }
1107
1108 bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
1109 {
1110 switch (param)
1111 {
1112 case EN_SETFOCUS:
1113 case EN_KILLFOCUS:
1114 {
1115 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
1116 : wxEVT_SET_FOCUS,
1117 m_windowId);
1118 event.SetEventObject( this );
1119 GetEventHandler()->ProcessEvent(event);
1120 }
1121 break;
1122
1123 case EN_CHANGE:
1124 {
1125 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, m_windowId);
1126 wxString val(GetValue());
1127 if ( !val.IsNull() )
1128 event.m_commandString = WXSTRINGCAST val;
1129 event.SetEventObject( this );
1130 ProcessCommand(event);
1131 }
1132 break;
1133
1134 case EN_ERRSPACE:
1135 // the text size limit has been hit - increase it
1136 AdjustSpaceLimit();
1137 break;
1138
1139 // the other notification messages are not processed
1140 case EN_UPDATE:
1141 case EN_MAXTEXT:
1142 case EN_HSCROLL:
1143 case EN_VSCROLL:
1144 default:
1145 return FALSE;
1146 }
1147
1148 // processed
1149 return TRUE;
1150 }
1151
1152 void wxTextCtrl::AdjustSpaceLimit()
1153 {
1154 #ifndef __WIN16__
1155 unsigned int len = ::GetWindowTextLength(GetHwnd()),
1156 limit = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0);
1157 if ( len > limit )
1158 {
1159 limit = len + 0x8000; // 32Kb
1160
1161 #if wxUSE_RICHEDIT
1162 if ( m_isRich || limit > 0xffff )
1163 #else
1164 if ( limit > 0xffff )
1165 #endif
1166 ::SendMessage(GetHwnd(), EM_LIMITTEXT, 0, limit);
1167 else
1168 ::SendMessage(GetHwnd(), EM_LIMITTEXT, limit, 0);
1169 }
1170 #endif
1171 }
1172
1173 // For Rich Edit controls. Do we need it?
1174 #if 0
1175 #if wxUSE_RICHEDIT
1176 bool wxTextCtrl::MSWOnNotify(WXWPARAM wParam, WXLPARAM lParam)
1177 {
1178 wxCommandEvent event(0, m_windowId);
1179 int eventType = 0;
1180 NMHDR *hdr1 = (NMHDR *) lParam;
1181 switch ( hdr1->code )
1182 {
1183 // Insert case code here
1184 default :
1185 return wxControl::MSWOnNotify(wParam, lParam);
1186 break;
1187 }
1188
1189 event.SetEventObject( this );
1190 event.SetEventType(eventType);
1191
1192 if ( !GetEventHandler()->ProcessEvent(event) )
1193 return FALSE;
1194
1195 return TRUE;
1196 }
1197 #endif
1198 #endif
1199
1200 void wxTextCtrl::OnCut(wxCommandEvent& event)
1201 {
1202 Cut();
1203 }
1204
1205 void wxTextCtrl::OnCopy(wxCommandEvent& event)
1206 {
1207 Copy();
1208 }
1209
1210 void wxTextCtrl::OnPaste(wxCommandEvent& event)
1211 {
1212 Paste();
1213 }
1214
1215 void wxTextCtrl::OnUndo(wxCommandEvent& event)
1216 {
1217 Undo();
1218 }
1219
1220 void wxTextCtrl::OnRedo(wxCommandEvent& event)
1221 {
1222 Redo();
1223 }
1224
1225 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1226 {
1227 event.Enable( CanCut() );
1228 }
1229
1230 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1231 {
1232 event.Enable( CanCopy() );
1233 }
1234
1235 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1236 {
1237 event.Enable( CanPaste() );
1238 }
1239
1240 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1241 {
1242 event.Enable( CanUndo() );
1243 }
1244
1245 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1246 {
1247 event.Enable( CanRedo() );
1248 }
1249
1250 bool wxTextCtrl::AcceptsFocus() const
1251 {
1252 // we don't want focus if we can't be edited
1253 return IsEditable() && wxControl::AcceptsFocus();
1254 }