1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "textctrl.h"
16 #include <sys/types.h>
20 #include "wx/textctrl.h"
21 #include "wx/settings.h"
22 #include "wx/filefn.h"
25 #if defined(__BORLANDC__) && !defined(__WIN32__)
34 #include <sys/types.h>
38 #include "wx/motif/private.h"
41 wxTextWindowChangedProc (Widget w
, XtPointer clientData
, XtPointer ptr
);
43 wxTextWindowModifyProc (Widget w
, XtPointer clientData
, XmTextVerifyCallbackStruct
*cbs
);
45 wxTextWindowGainFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
);
47 wxTextWindowLoseFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
);
48 static void wxTextWindowActivateProc(Widget w
, XtPointer clientData
,
49 XmAnyCallbackStruct
*ptr
);
51 #if !USE_SHARED_LIBRARY
52 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl
, wxControl
)
54 BEGIN_EVENT_TABLE(wxTextCtrl
, wxControl
)
55 EVT_DROP_FILES(wxTextCtrl::OnDropFiles
)
56 EVT_CHAR(wxTextCtrl::OnChar
)
61 wxTextCtrl::wxTextCtrl()
62 #ifndef NO_TEXT_WINDOW_STREAM
67 m_tempCallbackStruct
= (void*) NULL
;
69 m_processedDefault
= FALSE
;
72 bool wxTextCtrl::Create(wxWindow
*parent
, wxWindowID id
,
73 const wxString
& value
,
75 const wxSize
& size
, long style
,
76 const wxValidator
& validator
,
79 m_tempCallbackStruct
= (void*) NULL
;
81 m_processedDefault
= FALSE
;
83 // m_backgroundColour = parent->GetBackgroundColour();
84 m_backgroundColour
= * wxWHITE
;
85 m_foregroundColour
= parent
->GetForegroundColour();
88 SetValidator(validator
);
89 if (parent
) parent
->AddChild(this);
91 m_windowStyle
= style
;
94 m_windowId
= (int)NewControlId();
98 Widget parentWidget
= (Widget
) parent
->GetClientWidget();
100 bool wantHorizScrolling
= ((m_windowStyle
& wxHSCROLL
) != 0);
102 // If we don't have horizontal scrollbars, we want word wrap.
103 bool wantWordWrap
= !wantHorizScrolling
;
105 if (m_windowStyle
& wxTE_MULTILINE
)
108 XtSetArg (args
[0], XmNscrollHorizontal
, wantHorizScrolling
? True
: False
);
109 XtSetArg (args
[1], XmNwordWrap
, wantWordWrap
? True
: False
);
111 m_mainWidget
= (WXWidget
) XmCreateScrolledText (parentWidget
, (char*) (const char*) name
, args
, 2);
113 XtVaSetValues ((Widget
) m_mainWidget
,
114 XmNeditable
, ((style
& wxTE_READONLY
) ? False
: True
),
115 XmNeditMode
, XmMULTI_LINE_EDIT
,
117 XtManageChild ((Widget
) m_mainWidget
);
121 m_mainWidget
= (WXWidget
) XtVaCreateManagedWidget ((char*) (const char*) name
,
122 xmTextWidgetClass
, parentWidget
,
125 // TODO: Is this relevant? What does it do?
127 if (!value
.IsNull() && (value
.Length() > (unsigned int) noCols
))
128 noCols
= value
.Length();
129 XtVaSetValues ((Widget
) m_mainWidget
,
135 XmTextSetString ((Widget
) m_mainWidget
, (char*) (const char*) value
);
137 XtAddCallback((Widget
) m_mainWidget
, XmNvalueChangedCallback
, (XtCallbackProc
)wxTextWindowChangedProc
, (XtPointer
)this);
139 XtAddCallback((Widget
) m_mainWidget
, XmNmodifyVerifyCallback
, (XtCallbackProc
)wxTextWindowModifyProc
, (XtPointer
)this);
141 XtAddCallback((Widget
) m_mainWidget
, XmNactivateCallback
, (XtCallbackProc
)wxTextWindowActivateProc
, (XtPointer
)this);
143 XtAddCallback((Widget
) m_mainWidget
, XmNfocusCallback
, (XtCallbackProc
)wxTextWindowGainFocusProc
, (XtPointer
)this);
145 XtAddCallback((Widget
) m_mainWidget
, XmNlosingFocusCallback
, (XtCallbackProc
)wxTextWindowLoseFocusProc
, (XtPointer
)this);
147 m_windowFont
= parent
->GetFont();
150 SetCanAddEventHandler(TRUE
);
151 AttachWidget (parent
, m_mainWidget
, (WXWidget
) NULL
, pos
.x
, pos
.y
, size
.x
, size
.y
);
153 ChangeBackgroundColour();
158 WXWidget
wxTextCtrl::GetTopWidget() const
160 return ((m_windowStyle
& wxTE_MULTILINE
) ? (WXWidget
) XtParent((Widget
) m_mainWidget
) : m_mainWidget
);
163 wxString
wxTextCtrl::GetValue() const
165 if (m_windowStyle
& wxTE_PASSWORD
)
169 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
178 return wxEmptyString
;
183 void wxTextCtrl::SetValue(const wxString
& value
)
185 // This assert is wrong -- means that you can't set an empty
186 // string (IsNull == IsEmpty).
187 // wxASSERT_MSG( (!value.IsNull()), "Must not pass a null string to wxTextCtrl::SetValue." ) ;
190 XmTextSetString ((Widget
) m_mainWidget
, (char*) (const char*) value
);
192 m_inSetValue
= FALSE
;
195 // Clipboard operations
196 void wxTextCtrl::Copy()
198 XmTextCopy((Widget
) m_mainWidget
, CurrentTime
);
201 void wxTextCtrl::Cut()
203 XmTextCut((Widget
) m_mainWidget
, CurrentTime
);
206 void wxTextCtrl::Paste()
208 XmTextPaste((Widget
) m_mainWidget
);
211 void wxTextCtrl::SetEditable(bool editable
)
213 XmTextSetEditable((Widget
) m_mainWidget
, (Boolean
) editable
);
216 void wxTextCtrl::SetInsertionPoint(long pos
)
218 XmTextSetInsertionPosition ((Widget
) m_mainWidget
, (XmTextPosition
) pos
);
221 void wxTextCtrl::SetInsertionPointEnd()
223 long pos
= GetLastPosition();
224 SetInsertionPoint(pos
);
227 long wxTextCtrl::GetInsertionPoint() const
229 return (long) XmTextGetInsertionPosition ((Widget
) m_mainWidget
);
232 long wxTextCtrl::GetLastPosition() const
234 return (long) XmTextGetLastPosition ((Widget
) m_mainWidget
);
237 void wxTextCtrl::Replace(long from
, long to
, const wxString
& value
)
239 XmTextReplace ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
240 (char*) (const char*) value
);
243 void wxTextCtrl::Remove(long from
, long to
)
245 XmTextSetSelection ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
247 XmTextRemove ((Widget
) m_mainWidget
);
250 void wxTextCtrl::SetSelection(long from
, long to
)
252 XmTextSetSelection ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
256 bool wxTextCtrl::LoadFile(const wxString
& file
)
258 if (!wxFileExists(file
))
265 Widget textWidget
= (Widget
) m_mainWidget
;
269 if ((stat ((char*) (const char*) file
, &statb
) == -1) || (statb
.st_mode
& S_IFMT
) != S_IFREG
||
270 !(fp
= fopen ((char*) (const char*) file
, "r")))
276 long len
= statb
.st_size
;
278 if (!(text
= XtMalloc ((unsigned) (len
+ 1))))
283 if (fread (text
, sizeof (char), len
, fp
) != (size_t) len
)
289 XmTextSetString (textWidget
, text
);
290 // m_textPosition = len;
297 // If file is null, try saved file name first
298 // Returns TRUE if succeeds.
299 bool wxTextCtrl::SaveFile(const wxString
& file
)
301 wxString
theFile(file
);
303 theFile
= m_fileName
;
306 m_fileName
= theFile
;
308 Widget textWidget
= (Widget
) m_mainWidget
;
311 if (!(fp
= fopen ((char*) (const char*) theFile
, "w")))
317 char *text
= XmTextGetString (textWidget
);
318 long len
= XmTextGetLastPosition (textWidget
);
320 if (fwrite (text
, sizeof (char), len
, fp
) != (size_t) len
)
322 // Did not write whole file
324 // Make sure newline terminates the file
325 if (text
[len
- 1] != '\n')
335 void wxTextCtrl::WriteText(const wxString
& text
)
337 long textPosition
= GetInsertionPoint() + strlen (text
);
338 XmTextInsert ((Widget
) m_mainWidget
, GetInsertionPoint(), (char*) (const char*) text
);
339 XtVaSetValues ((Widget
) m_mainWidget
, XmNcursorPosition
, textPosition
, NULL
);
340 SetInsertionPoint(textPosition
);
341 XmTextShowPosition ((Widget
) m_mainWidget
, textPosition
);
345 void wxTextCtrl::AppendText(const wxString
& text
)
347 long textPosition
= GetLastPosition() + strlen(text
);
348 XmTextInsert ((Widget
) m_mainWidget
, GetLastPosition(), (char*) (const char*) text
);
349 XtVaSetValues ((Widget
) m_mainWidget
, XmNcursorPosition
, textPosition
, NULL
);
350 SetInsertionPoint(textPosition
);
351 XmTextShowPosition ((Widget
) m_mainWidget
, textPosition
);
355 void wxTextCtrl::Clear()
357 XmTextSetString ((Widget
) m_mainWidget
, "");
361 bool wxTextCtrl::IsModified() const
366 // Makes 'unmodified'
367 void wxTextCtrl::DiscardEdits()
369 XmTextSetString ((Widget
) m_mainWidget
, "");
373 int wxTextCtrl::GetNumberOfLines() const
375 // HIDEOUSLY inefficient, but we have no choice.
376 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
381 bool finished
= FALSE
;
404 long wxTextCtrl::XYToPosition(long x
, long y
) const
406 /* It seems, that there is a bug in some versions of the Motif library,
407 so the original wxWin-Code doesn't work. */
409 Widget textWidget = (Widget) handle;
410 return (long) XmTextXYToPos (textWidget, (Position) x, (Position) y);
412 /* Now a little workaround: */
414 for (int i
=0; i
<y
; i
++) r
+=(GetLineLength(i
)+1);
418 void wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
421 XmTextPosToXY((Widget
) m_mainWidget
, pos
, &xx
, &yy
);
425 void wxTextCtrl::ShowPosition(long pos
)
427 XmTextShowPosition ((Widget
) m_mainWidget
, (XmTextPosition
) pos
);
430 int wxTextCtrl::GetLineLength(long lineNo
) const
432 wxString str
= GetLineText (lineNo
);
433 return (int) str
.Length();
436 wxString
wxTextCtrl::GetLineText(long lineNo
) const
438 // HIDEOUSLY inefficient, but we have no choice.
439 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
446 for (i
= 0; currentLine
!= lineNo
&& s
[i
]; i
++ )
451 for (j
= 0; s
[i
] && s
[i
] != '\n'; i
++, j
++ )
458 return wxEmptyString
;
465 void wxTextCtrl::Command(wxCommandEvent
& event
)
467 SetValue (event
.GetString());
468 ProcessCommand (event
);
471 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
473 // By default, load the first file into the text window.
474 if (event
.GetNumberOfFiles() > 0)
476 LoadFile(event
.GetFiles()[0]);
480 // The streambuf code was partly taken from chapter 3 by Jerry Schwarz of
481 // AT&T's "C++ Lanuage System Release 3.0 Library Manual" - Stein Somers
483 //=========================================================================
484 // Called then the buffer is full (gcc 2.6.3)
485 // or when "endl" is output (Borland 4.5)
486 //=========================================================================
487 // Class declaration using multiple inheritance doesn't work properly for
488 // Borland. See note in wb_text.h.
489 #ifndef NO_TEXT_WINDOW_STREAM
490 int wxTextCtrl::overflow(int c
)
492 // Make sure there is a holding area
493 if ( allocate()==EOF
)
495 wxError("Streambuf allocation failed","Internal error");
499 // Verify that there are no characters in get area
500 if ( gptr() && gptr() < egptr() )
502 wxError("wxTextCtrl::overflow: Who's trespassing my get area?","Internal error");
509 // Make sure there is a put area
512 /* This doesn't seem to be fatal so comment out error message */
513 // wxError("Put area not opened","Internal error");
514 setp( base(), base() );
517 // Determine how many characters have been inserted but no consumed
518 int plen
= pptr() - pbase();
520 // Now Jerry relies on the fact that the buffer is at least 2 chars
521 // long, but the holding area "may be as small as 1" ???
522 // And we need an additional \0, so let's keep this inefficient but
525 // If c!=EOF, it is a character that must also be comsumed
526 int xtra
= c
==EOF
? 0 : 1;
528 // Write temporary C-string to wxTextWindow
530 char *txt
= new char[plen
+xtra
+1];
531 memcpy(txt
, pbase(), plen
);
532 txt
[plen
] = (char)c
; // append c
533 txt
[plen
+xtra
] = '\0'; // append '\0' or overwrite c
534 // If the put area already contained \0, output will be truncated there
540 setp(pbase(), epptr());
542 #if defined(__WATCOMC__)
544 #elif defined(zapeof) // HP-UX (all cfront based?)
547 return c
!=EOF
? c
: 0; // this should make everybody happy
551 //=========================================================================
552 // called then "endl" is output (gcc) or then explicit sync is done (Borland)
553 //=========================================================================
554 int wxTextCtrl::sync()
556 // Verify that there are no characters in get area
557 if ( gptr() && gptr() < egptr() )
559 wxError("Who's trespassing my get area?","Internal error");
563 if ( pptr() && pptr() > pbase() ) return overflow(EOF
);
567 int len = pptr() - pbase();
568 char *txt = new char[len+1];
569 strncpy(txt, pbase(), len);
572 setp(pbase(), epptr());
578 //=========================================================================
579 // Should not be called by a "ostream". Used by a "istream"
580 //=========================================================================
581 int wxTextCtrl::underflow()
587 wxTextCtrl
& wxTextCtrl::operator<<(const wxString
& s
)
593 wxTextCtrl
& wxTextCtrl::operator<<(float f
)
596 str
.Printf("%.2f", f
);
601 wxTextCtrl
& wxTextCtrl::operator<<(double d
)
604 str
.Printf("%.2f", d
);
609 wxTextCtrl
& wxTextCtrl::operator<<(int i
)
617 wxTextCtrl
& wxTextCtrl::operator<<(long i
)
620 str
.Printf("%ld", i
);
625 wxTextCtrl
& wxTextCtrl::operator<<(const char c
)
635 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
637 // Indicates that we should generate a normal command, because
638 // we're letting default behaviour happen (otherwise it's vetoed
639 // by virtue of overriding OnChar)
640 m_processedDefault
= TRUE
;
642 if (m_tempCallbackStruct
)
644 XmTextVerifyCallbackStruct
*textStruct
=
645 (XmTextVerifyCallbackStruct
*) m_tempCallbackStruct
;
646 textStruct
->doit
= True
;
647 if (isascii(event
.m_keyCode
) && (textStruct
->text
->length
== 1))
649 textStruct
->text
->ptr
[0] = ((event
.m_keyCode
== WXK_RETURN
) ? 10 : event
.m_keyCode
);
654 void wxTextCtrl::ChangeFont(bool keepOriginalSize
)
656 wxWindow::ChangeFont(keepOriginalSize
);
659 void wxTextCtrl::ChangeBackgroundColour()
661 wxWindow::ChangeBackgroundColour();
663 /* TODO: should scrollbars be affected? Should probably have separate
664 * function to change them (by default, taken from wxSystemSettings)
666 if (m_windowStyle
& wxTE_MULTILINE
)
668 Widget parent
= XtParent ((Widget
) m_mainWidget
);
671 XtVaGetValues (parent
,
672 XmNhorizontalScrollBar
, &hsb
,
673 XmNverticalScrollBar
, &vsb
,
675 wxColour backgroundColour
= wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DFACE
);
677 DoChangeBackgroundColour((WXWidget
) hsb
, backgroundColour
, TRUE
);
679 DoChangeBackgroundColour((WXWidget
) vsb
, backgroundColour
, TRUE
);
681 DoChangeBackgroundColour((WXWidget
) parent
, m_backgroundColour
, TRUE
);
685 void wxTextCtrl::ChangeForegroundColour()
687 wxWindow::ChangeForegroundColour();
689 if (m_windowStyle
& wxTE_MULTILINE
)
691 Widget parent
= XtParent ((Widget
) m_mainWidget
);
694 XtVaGetValues (parent
,
695 XmNhorizontalScrollBar
, &hsb
,
696 XmNverticalScrollBar
, &vsb
,
699 /* TODO: should scrollbars be affected? Should probably have separate
700 * function to change them (by default, taken from wxSystemSettings)
702 DoChangeForegroundColour((WXWidget) hsb, m_foregroundColour);
704 DoChangeForegroundColour((WXWidget) vsb, m_foregroundColour);
706 DoChangeForegroundColour((WXWidget
) parent
, m_foregroundColour
);
710 static void wxTextWindowChangedProc (Widget w
, XtPointer clientData
, XtPointer ptr
)
712 if (!wxGetWindowFromTable(w
))
713 // Widget has been deleted!
716 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
717 tw
->SetModified(TRUE
);
721 wxTextWindowModifyProc (Widget w
, XtPointer clientData
, XmTextVerifyCallbackStruct
*cbs
)
723 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
724 tw
->m_processedDefault
= FALSE
;
726 // First, do some stuff if it's a password control.
727 // (What does this do exactly?)
729 if (tw
->GetWindowStyleFlag() & wxTE_PASSWORD
)
732 * At least on my system (SunOS 4.1.3 + Motif 1.2), you need to think of
733 * every event as a replace event. cbs->text->ptr gives the replacement
734 * text, cbs->startPos gives the index of the first char affected by the
735 * replace, and cbs->endPos gives the index one more than the last char
736 * affected by the replace (startPos == endPos implies an empty range).
737 * Hence, a deletion is represented by replacing all input text with a
738 * blank string ("", *not* NULL!). A simple insertion that does not
739 * overwrite any text has startPos == endPos.
742 if (tw
->m_value
.IsNull())
744 tw
->m_value
= cbs
->text
->ptr
;
748 char * passwd
= (char*) (const char*) tw
->m_value
; // Set up a more convenient alias.
750 int len
= passwd
? strlen(passwd
) : 0; // Enough room for old text
751 len
+= strlen(cbs
->text
->ptr
) + 1; // + new text (if any) + NUL
752 len
-= cbs
->endPos
- cbs
->startPos
; // - text from affected region.
754 char * newS
= new char [len
];
755 char * p
= passwd
, * dest
= newS
, * insert
= cbs
->text
->ptr
;
757 // Copy (old) text from passwd, up to the start posn of the change.
759 for (i
= 0; i
< cbs
->startPos
; ++i
)
762 // Copy the text to be inserted).
766 // Finally, copy into newS any remaining text from passwd[endPos] on.
767 for (p
= passwd
+ cbs
->endPos
; *p
; )
776 if (cbs
->text
->length
>0)
779 for (i
= 0; i
< cbs
->text
->length
; ++i
)
780 cbs
->text
->ptr
[i
] = '*';
781 cbs
->text
->ptr
[i
] = 0;
785 // If we're already within an OnChar, return: probably
786 // a programmatic insertion.
787 if (tw
->m_tempCallbackStruct
)
790 // Check for a backspace
791 if (cbs
->startPos
== (cbs
->currInsert
- 1))
793 tw
->m_tempCallbackStruct
= (void*) cbs
;
795 wxKeyEvent
event (wxEVT_CHAR
);
796 event
.SetId(tw
->GetId());
797 event
.m_keyCode
= WXK_DELETE
;
798 event
.SetEventObject(tw
);
800 // Only if wxTextCtrl::OnChar is called
801 // will this be set to True (and the character
805 tw
->GetEventHandler()->ProcessEvent(event
);
807 tw
->m_tempCallbackStruct
= NULL
;
809 if (tw
->InSetValue())
812 if (tw
->m_processedDefault
)
814 // Can generate a command
815 wxCommandEvent
commandEvent(wxEVT_COMMAND_TEXT_UPDATED
, tw
->GetId());
816 commandEvent
.SetEventObject(tw
);
817 tw
->ProcessCommand(commandEvent
);
823 // Pasting operation: let it through without
825 if (cbs
->text
->length
> 1)
828 // Something other than text
829 if (cbs
->text
->ptr
== NULL
)
832 tw
->m_tempCallbackStruct
= (void*) cbs
;
834 wxKeyEvent
event (wxEVT_CHAR
);
835 event
.SetId(tw
->GetId());
836 event
.SetEventObject(tw
);
837 event
.m_keyCode
= (cbs
->text
->ptr
[0] == 10 ? 13 : cbs
->text
->ptr
[0]);
839 // Only if wxTextCtrl::OnChar is called
840 // will this be set to True (and the character
844 tw
->GetEventHandler()->ProcessEvent(event
);
846 tw
->m_tempCallbackStruct
= NULL
;
848 if (tw
->InSetValue())
851 if (tw
->m_processedDefault
)
853 // Can generate a command
854 wxCommandEvent
commandEvent(wxEVT_COMMAND_TEXT_UPDATED
, tw
->GetId());
855 commandEvent
.SetEventObject(tw
);
856 tw
->ProcessCommand(commandEvent
);
861 wxTextWindowGainFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
)
863 if (!wxGetWindowFromTable(w
))
866 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
867 wxFocusEvent
event(wxEVT_SET_FOCUS
, tw
->GetId());
868 event
.SetEventObject(tw
);
869 tw
->GetEventHandler()->ProcessEvent(event
);
873 wxTextWindowLoseFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
)
875 if (!wxGetWindowFromTable(w
))
878 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
879 wxFocusEvent
event(wxEVT_KILL_FOCUS
, tw
->GetId());
880 event
.SetEventObject(tw
);
881 tw
->GetEventHandler()->ProcessEvent(event
);
884 static void wxTextWindowActivateProc(Widget w
, XtPointer clientData
,
885 XmAnyCallbackStruct
*ptr
)
887 if (!wxGetWindowFromTable(w
))
890 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
893 type_event = wxEVENT_TYPE_TEXT_ENTER_COMMAND ;
896 type_event = wxEVENT_TYPE_TEXT_COMMAND ;
901 if (tw
->InSetValue())
904 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
);
905 event
.SetId(tw
->GetId());
906 event
.SetEventObject(tw
);
907 tw
->ProcessCommand(event
);