]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/textctrl.cpp
wxSpinButton::GetValue() returns correct result now
[wxWidgets.git] / src / msw / textctrl.cpp
... / ...
CommitLineData
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
72IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxControl)
73
74BEGIN_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)
89END_EVENT_TABLE()
90
91#endif // USE_SHARED_LIBRARY
92
93// Text item
94wxTextCtrl::wxTextCtrl()
95#ifndef NO_TEXT_WINDOW_STREAM
96 : streambuf()
97#endif
98{
99#if wxUSE_RICHEDIT
100 m_isRich = FALSE;
101#endif
102}
103
104bool 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)
249void 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
293void wxTextCtrl::SetupColours()
294{
295 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW));
296 SetForegroundColour(GetParent()->GetForegroundColour());
297}
298
299wxString wxTextCtrl::GetValue() const
300{
301 return wxGetWindowText(GetHWND());
302}
303
304void 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
339void wxTextCtrl::DoSetSize(int x, int y, int width, int height, int sizeFlags)
340{
341 int currentX, currentY;
342 GetPosition(&currentX, &currentY);
343 int x1 = x;
344 int y1 = y;
345 int w1 = width;
346 int h1 = height;
347
348 if (x == -1 || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE))
349 x1 = currentX;
350 if (y == -1 || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE))
351 y1 = currentY;
352
353 AdjustForParentClientOrigin(x1, y1, sizeFlags);
354
355 int cx; // button font dimensions
356 int cy;
357
358 wxGetCharSize(GetHWND(), &cx, &cy, & this->GetFont());
359
360 int control_width, control_height, control_x, control_y;
361
362 // If we're prepared to use the existing size, then...
363 if (width == -1 && height == -1 && ((sizeFlags & wxSIZE_AUTO) != wxSIZE_AUTO))
364 {
365 GetSize(&w1, &h1);
366 }
367
368 // Deal with default size (using -1 values)
369 if (w1<=0)
370 w1 = DEFAULT_ITEM_WIDTH;
371
372 control_x = x1;
373 control_y = y1;
374 control_width = w1;
375 control_height = h1;
376
377 // Calculations may have made text size too small
378 if (control_height <= 0)
379 control_height = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
380
381 if (control_width <= 0)
382 control_width = DEFAULT_ITEM_WIDTH;
383
384 MoveWindow(GetHwnd(), (int)control_x, (int)control_y,
385 (int)control_width, (int)control_height, TRUE);
386}
387
388// Clipboard operations
389void wxTextCtrl::Copy()
390{
391 if (CanCopy())
392 {
393 HWND hWnd = GetHwnd();
394 SendMessage(hWnd, WM_COPY, 0, 0L);
395 }
396}
397
398void wxTextCtrl::Cut()
399{
400 if (CanCut())
401 {
402 HWND hWnd = GetHwnd();
403 SendMessage(hWnd, WM_CUT, 0, 0L);
404 }
405}
406
407void wxTextCtrl::Paste()
408{
409 if (CanPaste())
410 {
411 HWND hWnd = GetHwnd();
412 SendMessage(hWnd, WM_PASTE, 0, 0L);
413 }
414}
415
416void wxTextCtrl::SetEditable(bool editable)
417{
418 HWND hWnd = GetHwnd();
419 SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L);
420}
421
422void wxTextCtrl::SetInsertionPoint(long pos)
423{
424 HWND hWnd = GetHwnd();
425#ifdef __WIN32__
426#if wxUSE_RICHEDIT
427 if ( m_isRich)
428 {
429 CHARRANGE range;
430 range.cpMin = pos;
431 range.cpMax = pos;
432 SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range);
433 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
434 }
435 else
436#endif
437 {
438 SendMessage(hWnd, EM_SETSEL, pos, pos);
439 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
440 }
441#else
442 SendMessage(hWnd, EM_SETSEL, 0, MAKELPARAM(pos, pos));
443#endif
444 char *nothing = "";
445 SendMessage(hWnd, EM_REPLACESEL, 0, (LPARAM)nothing);
446}
447
448void wxTextCtrl::SetInsertionPointEnd()
449{
450 long pos = GetLastPosition();
451 SetInsertionPoint(pos);
452}
453
454long wxTextCtrl::GetInsertionPoint() const
455{
456#if wxUSE_RICHEDIT
457 if (m_isRich)
458 {
459 CHARRANGE range;
460 range.cpMin = 0;
461 range.cpMax = 0;
462 SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range);
463 return range.cpMin;
464 }
465#endif
466
467 DWORD Pos=(DWORD)SendMessage(GetHwnd(), EM_GETSEL, 0, 0L);
468 return Pos&0xFFFF;
469}
470
471long wxTextCtrl::GetLastPosition() const
472{
473 HWND hWnd = GetHwnd();
474
475 // Will always return a number > 0 (according to docs)
476 int noLines = (int)SendMessage(hWnd, EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0L);
477
478 // This gets the char index for the _beginning_ of the last line
479 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)(noLines-1), (LPARAM)0L);
480
481 // Get number of characters in the last line. We'll add this to the character
482 // index for the last line, 1st position.
483 int lineLength = (int)SendMessage(hWnd, EM_LINELENGTH, (WPARAM)charIndex, (LPARAM)0L);
484
485 return (long)(charIndex + lineLength);
486}
487
488void wxTextCtrl::Replace(long from, long to, const wxString& value)
489{
490#if wxUSE_CLIPBOARD
491 HWND hWnd = GetHwnd();
492 long fromChar = from;
493 long toChar = to;
494
495 // Set selection and remove it
496#ifdef __WIN32__
497 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
498#else
499 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
500#endif
501 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
502
503 // Now replace with 'value', by pasting.
504 wxSetClipboardData(wxDF_TEXT, (wxObject *) (const wxChar *)value, 0, 0);
505
506 // Paste into edit control
507 SendMessage(hWnd, WM_PASTE, (WPARAM)0, (LPARAM)0L);
508#else
509 wxFAIL_MSG("wxTextCtrl::Replace not implemented if wxUSE_CLIPBOARD is 0.");
510#endif
511}
512
513void wxTextCtrl::Remove(long from, long to)
514{
515 HWND hWnd = GetHwnd();
516 long fromChar = from;
517 long toChar = to;
518
519 // Cut all selected text
520#ifdef __WIN32__
521 SendMessage(hWnd, EM_SETSEL, fromChar, toChar);
522#else
523 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
524#endif
525 SendMessage(hWnd, WM_CUT, (WPARAM)0, (LPARAM)0);
526}
527
528void wxTextCtrl::SetSelection(long from, long to)
529{
530 HWND hWnd = GetHwnd();
531 long fromChar = from;
532 long toChar = to;
533 // if from and to are both -1, it means
534 // (in wxWindows) that all text should be selected.
535 // This translates into Windows convention
536 if ((from == -1) && (to == -1))
537 {
538 fromChar = 0;
539 toChar = -1;
540 }
541
542#ifdef __WIN32__
543 SendMessage(hWnd, EM_SETSEL, (WPARAM)fromChar, (LPARAM)toChar);
544 SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0);
545#else
546 // WPARAM is 0: selection is scrolled into view
547 SendMessage(hWnd, EM_SETSEL, (WPARAM)0, (LPARAM)MAKELONG(fromChar, toChar));
548#endif
549}
550
551bool wxTextCtrl::LoadFile(const wxString& file)
552{
553 if (!wxFileExists(WXSTRINGCAST file))
554 return FALSE;
555
556 m_fileName = file;
557
558 Clear();
559
560// ifstream input(WXSTRINGCAST file, ios::nocreate | ios::in);
561 ifstream input(MBSTRINGCAST file.mb_str(wxConvFile), ios::in);
562
563 if (!input.bad())
564 {
565 // Previously a SETSEL/REPLACESEL call-pair were done to insert
566 // line by line into the control. Apart from being very slow this
567 // was limited to 32K of text by the external interface presenting
568 // positions as signed shorts. Now load in one chunk...
569 // Note use of 'farmalloc' as in Borland 3.1 'size_t' is 16-bits...
570
571#ifdef __SALFORDC__
572 struct _stat stat_buf;
573 if (stat(MBSTRINGCAST file.mb_str(wxConvFile), &stat_buf) < 0)
574 return FALSE;
575#else
576 struct stat stat_buf;
577 if (stat(file.mb_str(wxConvFile), &stat_buf) < 0)
578 return FALSE;
579#endif
580
581// wxChar *tmp_buffer = (wxChar*)farmalloc(stat_buf.st_size+1);
582 // This may need to be a bigger buffer than the file size suggests,
583 // if it's a UNIX file. Give it an extra 1000 just in case.
584 wxChar *tmp_buffer = (wxChar*)farmalloc((size_t)(stat_buf.st_size+1+1000));
585 char *read_buffer = new char[512];
586 long no_lines = 0;
587 long pos = 0;
588 while (!input.eof() && input.peek() != EOF)
589 {
590 input.getline(read_buffer, 500);
591 int len = strlen(read_buffer);
592 wxBuffer[len] = 13;
593 wxBuffer[len+1] = 10;
594 wxBuffer[len+2] = 0;
595#if wxUSE_UNICODE
596 pos += wxConvCurrent->MB2WC(tmp_buffer+pos, read_buffer, (size_t)-1);
597#else
598 strcpy(tmp_buffer+pos, read_buffer);
599 pos += strlen(read_buffer);
600#endif
601 no_lines++;
602 }
603 delete[] read_buffer;
604
605 SetWindowText(GetHwnd(), tmp_buffer);
606 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
607 farfree(tmp_buffer);
608
609 // update the size limit if needed
610 AdjustSpaceLimit();
611
612 return TRUE;
613 }
614 return FALSE;
615}
616
617// If file is null, try saved file name first
618// Returns TRUE if succeeds.
619bool wxTextCtrl::SaveFile(const wxString& file)
620{
621 wxString theFile(file);
622
623 if (theFile == _T(""))
624 theFile = m_fileName;
625
626 if (theFile == _T(""))
627 return FALSE;
628
629 m_fileName = theFile;
630
631 ofstream output(MBSTRINGCAST theFile.mb_str(wxConvFile));
632 if (output.bad())
633 return FALSE;
634
635 // This will only save 64K max
636 unsigned long nbytes = SendMessage(GetHwnd(), WM_GETTEXTLENGTH, 0, 0);
637 char *tmp_buffer = (char*)farmalloc((size_t)(nbytes+1));
638 SendMessage(GetHwnd(), WM_GETTEXT, (WPARAM)(nbytes+1), (LPARAM)tmp_buffer);
639 char *pstr = tmp_buffer;
640
641 // Convert \r\n to just \n
642 while (*pstr)
643 {
644 if (*pstr != '\r')
645 output << *pstr;
646 pstr++;
647 }
648
649 farfree(tmp_buffer);
650 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
651
652 return TRUE;
653}
654
655void wxTextCtrl::WriteText(const wxString& text)
656{
657 // Covert \n to \r\n
658 int len = text.Length();
659 char *newtext = new char[(len*2)+1];
660 int i = 0;
661 int j = 0;
662 while (i < len)
663 {
664 if (text[i] == '\n')
665 {
666 newtext[j] = '\r';
667 j ++;
668 }
669 newtext[j] = text[i];
670 i ++;
671 j ++;
672 }
673 newtext[j] = 0;
674 SendMessage(GetHwnd(), EM_REPLACESEL, 0, (LPARAM)newtext);
675 delete[] newtext;
676
677 AdjustSpaceLimit();
678}
679
680void wxTextCtrl::AppendText(const wxString& text)
681{
682 SetInsertionPointEnd();
683 WriteText(text);
684}
685
686void wxTextCtrl::Clear()
687{
688 SetWindowText(GetHwnd(), _T(""));
689}
690
691bool wxTextCtrl::IsModified() const
692{
693 return (SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0);
694}
695
696// Makes 'unmodified'
697void wxTextCtrl::DiscardEdits()
698{
699 SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L);
700}
701
702/*
703 * Some of the following functions are yet to be implemented
704 *
705 */
706
707int wxTextCtrl::GetNumberOfLines() const
708{
709 return (int)SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0);
710}
711
712long wxTextCtrl::XYToPosition(long x, long y) const
713{
714 HWND hWnd = GetHwnd();
715
716 // This gets the char index for the _beginning_ of this line
717 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)y, (LPARAM)0);
718 return (long)(x + charIndex);
719}
720
721void wxTextCtrl::PositionToXY(long pos, long *x, long *y) const
722{
723 HWND hWnd = GetHwnd();
724
725 // This gets the line number containing the character
726 int lineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0);
727 // This gets the char index for the _beginning_ of this line
728 int charIndex = (int)SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0);
729 // The X position must therefore be the different between pos and charIndex
730 *x = (long)(pos - charIndex);
731 *y = (long)lineNo;
732}
733
734void wxTextCtrl::ShowPosition(long pos)
735{
736 HWND hWnd = GetHwnd();
737
738 // To scroll to a position, we pass the number of lines and characters
739 // to scroll *by*. This means that we need to:
740 // (1) Find the line position of the current line.
741 // (2) Find the line position of pos.
742 // (3) Scroll by (pos - current).
743 // For now, ignore the horizontal scrolling.
744
745 // Is this where scrolling is relative to - the line containing the caret?
746 // Or is the first visible line??? Try first visible line.
747// int currentLineLineNo1 = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L);
748
749 int currentLineLineNo = (int)SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L);
750
751 int specifiedLineLineNo = (int)SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L);
752
753 int linesToScroll = specifiedLineLineNo - currentLineLineNo;
754
755 if (linesToScroll != 0)
756 (void)SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll);
757}
758
759int wxTextCtrl::GetLineLength(long lineNo) const
760{
761 long charIndex = XYToPosition(0, lineNo);
762 HWND hWnd = GetHwnd();
763 int len = (int)SendMessage(hWnd, EM_LINELENGTH, (WPARAM)charIndex, (LPARAM)0);
764 return len;
765}
766
767wxString wxTextCtrl::GetLineText(long lineNo) const
768{
769 HWND hWnd = GetHwnd();
770 *(WORD *)wxBuffer = 512;
771 int noChars = (int)SendMessage(hWnd, EM_GETLINE, (WPARAM)lineNo, (LPARAM)wxBuffer);
772 wxBuffer[noChars] = 0;
773 return wxString(wxBuffer);
774}
775
776bool wxTextCtrl::CanCopy() const
777{
778 // Can copy if there's a selection
779 long from, to;
780 GetSelection(& from, & to);
781 return (from != to) ;
782}
783
784bool wxTextCtrl::CanCut() const
785{
786 // Can cut if there's a selection
787 long from, to;
788 GetSelection(& from, & to);
789 return (from != to) ;
790}
791
792bool wxTextCtrl::CanPaste() const
793{
794#if wxUSE_RICHEDIT
795 if (m_isRich)
796 {
797 int dataFormat = 0; // 0 == any format
798 return (::SendMessage( GetHwnd(), EM_CANPASTE, (WPARAM) (UINT) dataFormat, 0) != 0);
799 }
800#endif
801 if (!IsEditable())
802 return FALSE;
803
804 // Standard edit control: check for straight text on clipboard
805 bool isTextAvailable = FALSE;
806 if (::OpenClipboard((HWND) wxTheApp->GetTopWindow()->GetHWND()))
807 {
808 isTextAvailable = (::IsClipboardFormatAvailable(CF_TEXT) != 0);
809 ::CloseClipboard();
810 }
811 return isTextAvailable;
812}
813
814// Undo/redo
815void wxTextCtrl::Undo()
816{
817 if (CanUndo())
818 {
819 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
820 }
821}
822
823void wxTextCtrl::Redo()
824{
825 if (CanRedo())
826 {
827 // Same as Undo, since Undo undoes the undo, i.e. a redo.
828 ::SendMessage(GetHwnd(), EM_UNDO, 0, 0);
829 }
830}
831
832bool wxTextCtrl::CanUndo() const
833{
834 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
835}
836
837bool wxTextCtrl::CanRedo() const
838{
839 return (::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0);
840}
841
842// If the return values from and to are the same, there is no
843// selection.
844void wxTextCtrl::GetSelection(long* from, long* to) const
845{
846#if wxUSE_RICHEDIT
847 if (m_isRich)
848 {
849 CHARRANGE charRange;
850 ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) (CHARRANGE*) & charRange);
851
852 *from = charRange.cpMin;
853 *to = charRange.cpMax;
854
855 return;
856 }
857#endif
858 DWORD dwStart, dwEnd;
859 WPARAM wParam = (WPARAM) (DWORD*) & dwStart; // receives starting position
860 LPARAM lParam = (LPARAM) (DWORD*) & dwEnd; // receives ending position
861
862 ::SendMessage(GetHwnd(), EM_GETSEL, wParam, lParam);
863
864 *from = dwStart;
865 *to = dwEnd;
866}
867
868bool wxTextCtrl::IsEditable() const
869{
870 long style = ::GetWindowLong(GetHwnd(), GWL_STYLE);
871
872 return ((style & ES_READONLY) == 0);
873}
874
875void wxTextCtrl::Command(wxCommandEvent & event)
876{
877 SetValue (event.GetString());
878 ProcessCommand (event);
879}
880
881void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event)
882{
883 // By default, load the first file into the text window.
884 if (event.GetNumberOfFiles() > 0)
885 {
886 LoadFile(event.GetFiles()[0]);
887 }
888}
889
890// The streambuf code was partly taken from chapter 3 by Jerry Schwarz of
891// AT&T's "C++ Lanuage System Release 3.0 Library Manual" - Stein Somers
892
893//=========================================================================
894// Called then the buffer is full (gcc 2.6.3)
895// or when "endl" is output (Borland 4.5)
896//=========================================================================
897// Class declaration using multiple inheritance doesn't work properly for
898// Borland. See note in textctrl.h.
899#ifndef NO_TEXT_WINDOW_STREAM
900int wxTextCtrl::overflow(int c)
901{
902 // Make sure there is a holding area
903 // this is not needed in <iostream> usage as it automagically allocates
904 // it, but does someone want to emulate it for safety's sake?
905#if wxUSE_IOSTREAMH
906 if ( allocate()==EOF )
907 {
908 wxLogError("Streambuf allocation failed");
909 return EOF;
910 }
911#endif
912
913 // Verify that there are no characters in get area
914 if ( gptr() && gptr() < egptr() )
915 {
916 wxError("Who's trespassing my get area?","Internal error");
917 return EOF;
918 }
919
920 // Reset get area
921 setg(0,0,0);
922
923 // Make sure there is a put area
924 if ( ! pptr() )
925 {
926/* This doesn't seem to be fatal so comment out error message */
927// wxError("Put area not opened","Internal error");
928
929#if wxUSE_IOSTREAMH
930 setp( base(), base() );
931#else
932 setp( pbase(), pbase() );
933#endif
934 }
935
936 // Determine how many characters have been inserted but no consumed
937 int plen = pptr() - pbase();
938
939 // Now Jerry relies on the fact that the buffer is at least 2 chars
940 // long, but the holding area "may be as small as 1" ???
941 // And we need an additional \0, so let's keep this inefficient but
942 // safe copy.
943
944 // If c!=EOF, it is a character that must also be comsumed
945 int xtra = c==EOF? 0 : 1;
946
947 // Write temporary C-string to wxTextWindow
948 {
949 char *txt = new char[plen+xtra+1];
950 memcpy(txt, pbase(), plen);
951 txt[plen] = (char)c; // append c
952 txt[plen+xtra] = '\0'; // append '\0' or overwrite c
953 // If the put area already contained \0, output will be truncated there
954 AppendText(txt);
955 delete[] txt;
956 }
957
958 // Reset put area
959 setp(pbase(), epptr());
960
961#if defined(__WATCOMC__)
962 return __NOT_EOF;
963#elif defined(zapeof) // HP-UX (all cfront based?)
964 return zapeof(c);
965#else
966 return c!=EOF ? c : 0; // this should make everybody happy
967#endif
968
969/* OLD CODE
970 int len = pptr() - pbase();
971 char *txt = new char[len+1];
972 strncpy(txt, pbase(), len);
973 txt[len] = '\0';
974 (*this) << txt;
975 setp(pbase(), epptr());
976 delete[] txt;
977 return EOF;
978*/
979}
980
981//=========================================================================
982// called then "endl" is output (gcc) or then explicit sync is done (Borland)
983//=========================================================================
984int wxTextCtrl::sync()
985{
986 // Verify that there are no characters in get area
987 if ( gptr() && gptr() < egptr() )
988 {
989 wxError("Who's trespassing my get area?","Internal error");
990 return EOF;
991 }
992
993 if ( pptr() && pptr() > pbase() ) return overflow(EOF);
994
995 return 0;
996/* OLD CODE
997 int len = pptr() - pbase();
998 char *txt = new char[len+1];
999 strncpy(txt, pbase(), len);
1000 txt[len] = '\0';
1001 (*this) << txt;
1002 setp(pbase(), epptr());
1003 delete[] txt;
1004 return 0;
1005*/
1006}
1007
1008//=========================================================================
1009// Should not be called by a "ostream". Used by a "istream"
1010//=========================================================================
1011int wxTextCtrl::underflow()
1012{
1013 return EOF;
1014}
1015#endif
1016
1017wxTextCtrl& wxTextCtrl::operator<<(const wxString& s)
1018{
1019 AppendText(s);
1020 return *this;
1021}
1022
1023wxTextCtrl& wxTextCtrl::operator<<(float f)
1024{
1025 wxString str;
1026 str.Printf(_T("%.2f"), f);
1027 AppendText(str);
1028 return *this;
1029}
1030
1031wxTextCtrl& wxTextCtrl::operator<<(double d)
1032{
1033 wxString str;
1034 str.Printf(_T("%.2f"), d);
1035 AppendText(str);
1036 return *this;
1037}
1038
1039wxTextCtrl& wxTextCtrl::operator<<(int i)
1040{
1041 wxString str;
1042 str.Printf(_T("%d"), i);
1043 AppendText(str);
1044 return *this;
1045}
1046
1047wxTextCtrl& wxTextCtrl::operator<<(long i)
1048{
1049 wxString str;
1050 str.Printf(_T("%ld"), i);
1051 AppendText(str);
1052 return *this;
1053}
1054
1055wxTextCtrl& wxTextCtrl::operator<<(const char c)
1056{
1057 char buf[2];
1058
1059 buf[0] = c;
1060 buf[1] = 0;
1061 AppendText(buf);
1062 return *this;
1063}
1064
1065WXHBRUSH wxTextCtrl::OnCtlColor(WXHDC pDC, WXHWND pWnd, WXUINT nCtlColor,
1066 WXUINT message, WXWPARAM wParam, WXLPARAM lParam)
1067{
1068#if wxUSE_CTL3D
1069 if ( m_useCtl3D )
1070 {
1071 HBRUSH hbrush = Ctl3dCtlColorEx(message, wParam, lParam);
1072 return (WXHBRUSH) hbrush;
1073 }
1074#endif
1075
1076 if (GetParent()->GetTransparentBackground())
1077 SetBkMode((HDC) pDC, TRANSPARENT);
1078 else
1079 SetBkMode((HDC) pDC, OPAQUE);
1080
1081 ::SetBkColor((HDC) pDC, RGB(GetBackgroundColour().Red(), GetBackgroundColour().Green(), GetBackgroundColour().Blue()));
1082 ::SetTextColor((HDC) pDC, RGB(GetForegroundColour().Red(), GetForegroundColour().Green(), GetForegroundColour().Blue()));
1083
1084 wxBrush *backgroundBrush = wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(), wxSOLID);
1085
1086 // Note that this will be cleaned up in wxApp::OnIdle, if backgroundBrush
1087 // has a zero usage count.
1088 // NOT NOW - will be cleaned up at end of app.
1089// backgroundBrush->RealizeResource();
1090 return (WXHBRUSH) backgroundBrush->GetResourceHandle();
1091}
1092
1093void wxTextCtrl::OnChar(wxKeyEvent& event)
1094{
1095 switch ( event.KeyCode() )
1096 {
1097 case WXK_RETURN:
1098 if ( !(m_windowStyle & wxTE_MULTILINE) )
1099 {
1100 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1101 event.SetEventObject( this );
1102 if ( GetEventHandler()->ProcessEvent(event) )
1103 return;
1104 }
1105 //else: multiline controls need Enter for themselves
1106
1107 break;
1108
1109 case WXK_TAB:
1110 // always produce navigation event - even if we process TAB
1111 // ourselves the fact that we got here means that the user code
1112 // decided to skip processing of this TAB - probably to let it
1113 // do its default job.
1114 //
1115 // NB: Notice that Ctrl-Tab is handled elsewhere and Alt-Tab is
1116 // handled by Windows
1117 {
1118 wxNavigationKeyEvent eventNav;
1119 eventNav.SetDirection(!event.ShiftDown());
1120 eventNav.SetWindowChange(FALSE);
1121 eventNav.SetEventObject(this);
1122
1123 if ( GetEventHandler()->ProcessEvent(eventNav) )
1124 return;
1125 }
1126 break;
1127
1128 default:
1129 event.Skip();
1130 return;
1131 }
1132
1133 // don't just call event.Skip() because this will cause TABs and ENTERs
1134 // be passed upwards and we don't always want this - instead process it
1135 // right here
1136
1137 // FIXME
1138 event.Skip();
1139}
1140
1141bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
1142{
1143 switch (param)
1144 {
1145 case EN_SETFOCUS:
1146 case EN_KILLFOCUS:
1147 {
1148 wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS
1149 : wxEVT_SET_FOCUS,
1150 m_windowId);
1151 event.SetEventObject( this );
1152 GetEventHandler()->ProcessEvent(event);
1153 }
1154 break;
1155
1156 case EN_CHANGE:
1157 {
1158 wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, m_windowId);
1159 wxString val(GetValue());
1160 if ( !val.IsNull() )
1161 event.m_commandString = WXSTRINGCAST val;
1162 event.SetEventObject( this );
1163 ProcessCommand(event);
1164 }
1165 break;
1166
1167 case EN_ERRSPACE:
1168 // the text size limit has been hit - increase it
1169 AdjustSpaceLimit();
1170 break;
1171
1172 // the other notification messages are not processed
1173 case EN_UPDATE:
1174 case EN_MAXTEXT:
1175 case EN_HSCROLL:
1176 case EN_VSCROLL:
1177 default:
1178 return FALSE;
1179 }
1180
1181 // processed
1182 return TRUE;
1183}
1184
1185void wxTextCtrl::AdjustSpaceLimit()
1186{
1187#ifndef __WIN16__
1188 unsigned int len = ::GetWindowTextLength(GetHwnd()),
1189 limit = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0);
1190 if ( len > limit )
1191 {
1192 limit = len + 0x8000; // 32Kb
1193
1194#if wxUSE_RICHEDIT
1195 if ( m_isRich || limit > 0xffff )
1196#else
1197 if ( limit > 0xffff )
1198#endif
1199 ::SendMessage(GetHwnd(), EM_LIMITTEXT, 0, limit);
1200 else
1201 ::SendMessage(GetHwnd(), EM_LIMITTEXT, limit, 0);
1202 }
1203#endif
1204}
1205
1206// For Rich Edit controls. Do we need it?
1207#if 0
1208#if wxUSE_RICHEDIT
1209bool wxTextCtrl::MSWOnNotify(WXWPARAM wParam, WXLPARAM lParam)
1210{
1211 wxCommandEvent event(0, m_windowId);
1212 int eventType = 0;
1213 NMHDR *hdr1 = (NMHDR *) lParam;
1214 switch ( hdr1->code )
1215 {
1216 // Insert case code here
1217 default :
1218 return wxControl::MSWOnNotify(wParam, lParam);
1219 break;
1220 }
1221
1222 event.SetEventObject( this );
1223 event.SetEventType(eventType);
1224
1225 if ( !GetEventHandler()->ProcessEvent(event) )
1226 return FALSE;
1227
1228 return TRUE;
1229}
1230#endif
1231#endif
1232
1233void wxTextCtrl::OnCut(wxCommandEvent& event)
1234{
1235 Cut();
1236}
1237
1238void wxTextCtrl::OnCopy(wxCommandEvent& event)
1239{
1240 Copy();
1241}
1242
1243void wxTextCtrl::OnPaste(wxCommandEvent& event)
1244{
1245 Paste();
1246}
1247
1248void wxTextCtrl::OnUndo(wxCommandEvent& event)
1249{
1250 Undo();
1251}
1252
1253void wxTextCtrl::OnRedo(wxCommandEvent& event)
1254{
1255 Redo();
1256}
1257
1258void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1259{
1260 event.Enable( CanCut() );
1261}
1262
1263void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1264{
1265 event.Enable( CanCopy() );
1266}
1267
1268void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1269{
1270 event.Enable( CanPaste() );
1271}
1272
1273void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1274{
1275 event.Enable( CanUndo() );
1276}
1277
1278void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1279{
1280 event.Enable( CanRedo() );
1281}
1282