1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "textctrl.h"
24 #include <sys/types.h>
29 #include "wx/textctrl.h"
30 #include "wx/settings.h"
31 #include "wx/filefn.h"
36 #include "wx/motif/private.h"
38 // ----------------------------------------------------------------------------
40 // ----------------------------------------------------------------------------
42 // helper: inserts the new text in the value of the text ctrl and returns the
44 static void MergeChangesIntoString(wxString
& value
,
45 XmTextVerifyCallbackStruct
*textStruct
);
48 static void wxTextWindowChangedProc(Widget w
, XtPointer clientData
, XtPointer ptr
);
49 static void wxTextWindowModifyProc(Widget w
, XtPointer clientData
, XmTextVerifyCallbackStruct
*cbs
);
50 static void wxTextWindowGainFocusProc(Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
);
51 static void wxTextWindowLoseFocusProc(Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
);
52 static void wxTextWindowActivateProc(Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*ptr
);
54 #if !USE_SHARED_LIBRARY
55 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl
, wxControl
)
57 BEGIN_EVENT_TABLE(wxTextCtrl
, wxControl
)
58 EVT_DROP_FILES(wxTextCtrl::OnDropFiles
)
59 EVT_CHAR(wxTextCtrl::OnChar
)
63 // ============================================================================
65 // ============================================================================
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
72 wxTextCtrl::wxTextCtrl()
73 #ifndef NO_TEXT_WINDOW_STREAM
77 m_tempCallbackStruct
= (void*) NULL
;
79 m_processedDefault
= FALSE
;
82 bool wxTextCtrl::Create(wxWindow
*parent
,
84 const wxString
& value
,
88 const wxValidator
& validator
,
91 m_tempCallbackStruct
= (void*) NULL
;
93 m_processedDefault
= FALSE
;
94 // m_backgroundColour = parent->GetBackgroundColour();
95 m_backgroundColour
= * wxWHITE
;
96 m_foregroundColour
= parent
->GetForegroundColour();
99 SetValidator(validator
);
101 parent
->AddChild(this);
103 m_windowStyle
= style
;
106 m_windowId
= (int)NewControlId();
110 Widget parentWidget
= (Widget
) parent
->GetClientWidget();
112 bool wantHorizScrolling
= ((m_windowStyle
& wxHSCROLL
) != 0);
114 // If we don't have horizontal scrollbars, we want word wrap.
115 bool wantWordWrap
= !wantHorizScrolling
;
117 if (m_windowStyle
& wxTE_MULTILINE
)
120 XtSetArg (args
[0], XmNscrollHorizontal
, wantHorizScrolling
? True
: False
);
121 XtSetArg (args
[1], XmNwordWrap
, wantWordWrap
? True
: False
);
123 m_mainWidget
= (WXWidget
) XmCreateScrolledText(parentWidget
,
127 XtVaSetValues ((Widget
) m_mainWidget
,
128 XmNeditable
, ((style
& wxTE_READONLY
) ? False
: True
),
129 XmNeditMode
, XmMULTI_LINE_EDIT
,
131 XtManageChild ((Widget
) m_mainWidget
);
135 m_mainWidget
= (WXWidget
)XtVaCreateManagedWidget
143 // TODO: Is this relevant? What does it do?
145 if (!value
.IsNull() && (value
.Length() > (unsigned int) noCols
))
146 noCols
= value
.Length();
147 XtVaSetValues((Widget
) m_mainWidget
,
152 // remove border if asked for
153 if ( style
& wxNO_BORDER
)
155 XtVaSetValues((Widget
)m_mainWidget
,
156 XmNshadowThickness
, 0,
161 XmTextSetString ((Widget
) m_mainWidget
, (char*)value
.c_str());
164 XtAddCallback((Widget
) m_mainWidget
, XmNvalueChangedCallback
, (XtCallbackProc
)wxTextWindowChangedProc
, (XtPointer
)this);
166 XtAddCallback((Widget
) m_mainWidget
, XmNmodifyVerifyCallback
, (XtCallbackProc
)wxTextWindowModifyProc
, (XtPointer
)this);
168 XtAddCallback((Widget
) m_mainWidget
, XmNactivateCallback
, (XtCallbackProc
)wxTextWindowActivateProc
, (XtPointer
)this);
170 XtAddCallback((Widget
) m_mainWidget
, XmNfocusCallback
, (XtCallbackProc
)wxTextWindowGainFocusProc
, (XtPointer
)this);
172 XtAddCallback((Widget
) m_mainWidget
, XmNlosingFocusCallback
, (XtCallbackProc
)wxTextWindowLoseFocusProc
, (XtPointer
)this);
175 m_windowFont
= parent
->GetFont();
178 SetCanAddEventHandler(TRUE
);
179 AttachWidget (parent
, m_mainWidget
, (WXWidget
) NULL
, pos
.x
, pos
.y
, size
.x
, size
.y
);
181 ChangeBackgroundColour();
186 WXWidget
wxTextCtrl::GetTopWidget() const
188 return ((m_windowStyle
& wxTE_MULTILINE
) ? (WXWidget
) XtParent((Widget
) m_mainWidget
) : m_mainWidget
);
191 wxString
wxTextCtrl::GetValue() const
193 wxString str
; // result
195 if (m_windowStyle
& wxTE_PASSWORD
)
197 // the value is stored always in m_value because it can't be retrieved
198 // from the text control
203 // just get the string from Motif
204 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
210 //else: return empty string
212 if ( m_tempCallbackStruct
)
214 // the string in the control isn't yet updated, can't use it as is
215 MergeChangesIntoString(str
, (XmTextVerifyCallbackStruct
*)
216 m_tempCallbackStruct
);
223 void wxTextCtrl::SetValue(const wxString
& value
)
227 XmTextSetString ((Widget
) m_mainWidget
, (char*)value
.c_str());
229 m_inSetValue
= FALSE
;
232 // Clipboard operations
233 void wxTextCtrl::Copy()
235 XmTextCopy((Widget
) m_mainWidget
, CurrentTime
);
238 void wxTextCtrl::Cut()
240 XmTextCut((Widget
) m_mainWidget
, CurrentTime
);
243 void wxTextCtrl::Paste()
245 XmTextPaste((Widget
) m_mainWidget
);
248 void wxTextCtrl::SetEditable(bool editable
)
250 XmTextSetEditable((Widget
) m_mainWidget
, (Boolean
) editable
);
253 void wxTextCtrl::SetInsertionPoint(long pos
)
255 XmTextSetInsertionPosition ((Widget
) m_mainWidget
, (XmTextPosition
) pos
);
258 void wxTextCtrl::SetInsertionPointEnd()
260 long pos
= GetLastPosition();
261 SetInsertionPoint(pos
);
264 long wxTextCtrl::GetInsertionPoint() const
266 return (long) XmTextGetInsertionPosition ((Widget
) m_mainWidget
);
269 long wxTextCtrl::GetLastPosition() const
271 return (long) XmTextGetLastPosition ((Widget
) m_mainWidget
);
274 void wxTextCtrl::Replace(long from
, long to
, const wxString
& value
)
276 XmTextReplace ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
277 (char*) (const char*) value
);
280 void wxTextCtrl::Remove(long from
, long to
)
282 XmTextSetSelection ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
284 XmTextRemove ((Widget
) m_mainWidget
);
287 void wxTextCtrl::SetSelection(long from
, long to
)
289 XmTextSetSelection ((Widget
) m_mainWidget
, (XmTextPosition
) from
, (XmTextPosition
) to
,
293 bool wxTextCtrl::LoadFile(const wxString
& file
)
295 if (!wxFileExists(file
))
302 Widget textWidget
= (Widget
) m_mainWidget
;
306 if ((stat ((char*) (const char*) file
, &statb
) == -1) || (statb
.st_mode
& S_IFMT
) != S_IFREG
||
307 !(fp
= fopen ((char*) (const char*) file
, "r")))
313 long len
= statb
.st_size
;
315 if (!(text
= XtMalloc ((unsigned) (len
+ 1))))
320 if (fread (text
, sizeof (char), len
, fp
) != (size_t) len
)
326 XmTextSetString (textWidget
, text
);
327 // m_textPosition = len;
334 // If file is null, try saved file name first
335 // Returns TRUE if succeeds.
336 bool wxTextCtrl::SaveFile(const wxString
& file
)
338 wxString
theFile(file
);
340 theFile
= m_fileName
;
343 m_fileName
= theFile
;
345 Widget textWidget
= (Widget
) m_mainWidget
;
348 if (!(fp
= fopen ((char*) (const char*) theFile
, "w")))
354 char *text
= XmTextGetString (textWidget
);
355 long len
= XmTextGetLastPosition (textWidget
);
357 if (fwrite (text
, sizeof (char), len
, fp
) != (size_t) len
)
359 // Did not write whole file
361 // Make sure newline terminates the file
362 if (text
[len
- 1] != '\n')
372 void wxTextCtrl::WriteText(const wxString
& text
)
374 long textPosition
= GetInsertionPoint() + strlen (text
);
375 XmTextInsert ((Widget
) m_mainWidget
, GetInsertionPoint(), (char*) (const char*) text
);
376 XtVaSetValues ((Widget
) m_mainWidget
, XmNcursorPosition
, textPosition
, NULL
);
377 SetInsertionPoint(textPosition
);
378 XmTextShowPosition ((Widget
) m_mainWidget
, textPosition
);
382 void wxTextCtrl::AppendText(const wxString
& text
)
384 long textPosition
= GetLastPosition() + strlen(text
);
385 XmTextInsert ((Widget
) m_mainWidget
, GetLastPosition(), (char*) (const char*) text
);
386 XtVaSetValues ((Widget
) m_mainWidget
, XmNcursorPosition
, textPosition
, NULL
);
387 SetInsertionPoint(textPosition
);
388 XmTextShowPosition ((Widget
) m_mainWidget
, textPosition
);
392 void wxTextCtrl::Clear()
394 XmTextSetString ((Widget
) m_mainWidget
, "");
398 bool wxTextCtrl::IsModified() const
403 // Makes 'unmodified'
404 void wxTextCtrl::DiscardEdits()
406 XmTextSetString ((Widget
) m_mainWidget
, "");
410 int wxTextCtrl::GetNumberOfLines() const
412 // HIDEOUSLY inefficient, but we have no choice.
413 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
418 bool finished
= FALSE
;
441 long wxTextCtrl::XYToPosition(long x
, long y
) const
443 /* It seems, that there is a bug in some versions of the Motif library,
444 so the original wxWin-Code doesn't work. */
446 Widget textWidget = (Widget) handle;
447 return (long) XmTextXYToPos (textWidget, (Position) x, (Position) y);
449 /* Now a little workaround: */
451 for (int i
=0; i
<y
; i
++) r
+=(GetLineLength(i
)+1);
455 void wxTextCtrl::PositionToXY(long pos
, long *x
, long *y
) const
458 XmTextPosToXY((Widget
) m_mainWidget
, pos
, &xx
, &yy
);
462 void wxTextCtrl::ShowPosition(long pos
)
464 XmTextShowPosition ((Widget
) m_mainWidget
, (XmTextPosition
) pos
);
467 int wxTextCtrl::GetLineLength(long lineNo
) const
469 wxString str
= GetLineText (lineNo
);
470 return (int) str
.Length();
473 wxString
wxTextCtrl::GetLineText(long lineNo
) const
475 // HIDEOUSLY inefficient, but we have no choice.
476 char *s
= XmTextGetString ((Widget
) m_mainWidget
);
483 for (i
= 0; currentLine
!= lineNo
&& s
[i
]; i
++ )
488 for (j
= 0; s
[i
] && s
[i
] != '\n'; i
++, j
++ )
495 return wxEmptyString
;
502 void wxTextCtrl::Command(wxCommandEvent
& event
)
504 SetValue (event
.GetString());
505 ProcessCommand (event
);
508 void wxTextCtrl::OnDropFiles(wxDropFilesEvent
& event
)
510 // By default, load the first file into the text window.
511 if (event
.GetNumberOfFiles() > 0)
513 LoadFile(event
.GetFiles()[0]);
517 // The streambuf code was partly taken from chapter 3 by Jerry Schwarz of
518 // AT&T's "C++ Lanuage System Release 3.0 Library Manual" - Stein Somers
520 //=========================================================================
521 // Called then the buffer is full (gcc 2.6.3)
522 // or when "endl" is output (Borland 4.5)
523 //=========================================================================
524 // Class declaration using multiple inheritance doesn't work properly for
525 // Borland. See note in wb_text.h.
526 #ifndef NO_TEXT_WINDOW_STREAM
527 int wxTextCtrl::overflow(int c
)
529 // Make sure there is a holding area
530 if ( allocate()==EOF
)
532 wxError("Streambuf allocation failed","Internal error");
536 // Verify that there are no characters in get area
537 if ( gptr() && gptr() < egptr() )
539 wxError("wxTextCtrl::overflow: Who's trespassing my get area?","Internal error");
546 // Make sure there is a put area
549 /* This doesn't seem to be fatal so comment out error message */
550 // wxError("Put area not opened","Internal error");
551 setp( base(), base() );
554 // Determine how many characters have been inserted but no consumed
555 int plen
= pptr() - pbase();
557 // Now Jerry relies on the fact that the buffer is at least 2 chars
558 // long, but the holding area "may be as small as 1" ???
559 // And we need an additional \0, so let's keep this inefficient but
562 // If c!=EOF, it is a character that must also be comsumed
563 int xtra
= c
==EOF
? 0 : 1;
565 // Write temporary C-string to wxTextWindow
567 char *txt
= new char[plen
+xtra
+1];
568 memcpy(txt
, pbase(), plen
);
569 txt
[plen
] = (char)c
; // append c
570 txt
[plen
+xtra
] = '\0'; // append '\0' or overwrite c
571 // If the put area already contained \0, output will be truncated there
577 setp(pbase(), epptr());
579 #if defined(__WATCOMC__)
581 #elif defined(zapeof) // HP-UX (all cfront based?)
584 return c
!=EOF
? c
: 0; // this should make everybody happy
588 //=========================================================================
589 // called then "endl" is output (gcc) or then explicit sync is done (Borland)
590 //=========================================================================
591 int wxTextCtrl::sync()
593 // Verify that there are no characters in get area
594 if ( gptr() && gptr() < egptr() )
596 wxError("Who's trespassing my get area?","Internal error");
600 if ( pptr() && pptr() > pbase() ) return overflow(EOF
);
604 int len = pptr() - pbase();
605 char *txt = new char[len+1];
606 strncpy(txt, pbase(), len);
609 setp(pbase(), epptr());
615 //=========================================================================
616 // Should not be called by a "ostream". Used by a "istream"
617 //=========================================================================
618 int wxTextCtrl::underflow()
624 wxTextCtrl
& wxTextCtrl::operator<<(const wxString
& s
)
630 wxTextCtrl
& wxTextCtrl::operator<<(float f
)
633 str
.Printf("%.2f", f
);
638 wxTextCtrl
& wxTextCtrl::operator<<(double d
)
641 str
.Printf("%.2f", d
);
646 wxTextCtrl
& wxTextCtrl::operator<<(int i
)
654 wxTextCtrl
& wxTextCtrl::operator<<(long i
)
657 str
.Printf("%ld", i
);
662 wxTextCtrl
& wxTextCtrl::operator<<(const char c
)
672 void wxTextCtrl::OnChar(wxKeyEvent
& event
)
674 // Indicates that we should generate a normal command, because
675 // we're letting default behaviour happen (otherwise it's vetoed
676 // by virtue of overriding OnChar)
677 m_processedDefault
= TRUE
;
679 if (m_tempCallbackStruct
)
681 XmTextVerifyCallbackStruct
*textStruct
=
682 (XmTextVerifyCallbackStruct
*) m_tempCallbackStruct
;
683 textStruct
->doit
= True
;
684 if (isascii(event
.m_keyCode
) && (textStruct
->text
->length
== 1))
686 textStruct
->text
->ptr
[0] = ((event
.m_keyCode
== WXK_RETURN
) ? 10 : event
.m_keyCode
);
691 void wxTextCtrl::ChangeFont(bool keepOriginalSize
)
693 wxWindow::ChangeFont(keepOriginalSize
);
696 void wxTextCtrl::ChangeBackgroundColour()
698 wxWindow::ChangeBackgroundColour();
700 /* TODO: should scrollbars be affected? Should probably have separate
701 * function to change them (by default, taken from wxSystemSettings)
703 if (m_windowStyle
& wxTE_MULTILINE
)
705 Widget parent
= XtParent ((Widget
) m_mainWidget
);
708 XtVaGetValues (parent
,
709 XmNhorizontalScrollBar
, &hsb
,
710 XmNverticalScrollBar
, &vsb
,
712 wxColour backgroundColour
= wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DFACE
);
714 DoChangeBackgroundColour((WXWidget
) hsb
, backgroundColour
, TRUE
);
716 DoChangeBackgroundColour((WXWidget
) vsb
, backgroundColour
, TRUE
);
718 DoChangeBackgroundColour((WXWidget
) parent
, m_backgroundColour
, TRUE
);
722 void wxTextCtrl::ChangeForegroundColour()
724 wxWindow::ChangeForegroundColour();
726 if (m_windowStyle
& wxTE_MULTILINE
)
728 Widget parent
= XtParent ((Widget
) m_mainWidget
);
731 XtVaGetValues (parent
,
732 XmNhorizontalScrollBar
, &hsb
,
733 XmNverticalScrollBar
, &vsb
,
736 /* TODO: should scrollbars be affected? Should probably have separate
737 * function to change them (by default, taken from wxSystemSettings)
739 DoChangeForegroundColour((WXWidget) hsb, m_foregroundColour);
741 DoChangeForegroundColour((WXWidget) vsb, m_foregroundColour);
743 DoChangeForegroundColour((WXWidget
) parent
, m_foregroundColour
);
747 void wxTextCtrl::DoSendEvents(void *wxcbs
, long keycode
)
749 // we're in process of updating the text control
750 m_tempCallbackStruct
= wxcbs
;
752 XmTextVerifyCallbackStruct
*cbs
= (XmTextVerifyCallbackStruct
*)wxcbs
;
754 wxKeyEvent
event (wxEVT_CHAR
);
755 event
.SetId(GetId());
756 event
.m_keyCode
= keycode
;
757 event
.SetEventObject(this);
759 // Only if wxTextCtrl::OnChar is called will this be set to True (and
760 // the character passed through)
763 GetEventHandler()->ProcessEvent(event
);
765 if ( !InSetValue() && m_processedDefault
)
767 // Can generate a command
768 wxCommandEvent
commandEvent(wxEVT_COMMAND_TEXT_UPDATED
, GetId());
769 commandEvent
.SetEventObject(this);
770 ProcessCommand(commandEvent
);
773 // do it after the (user) event handlers processed the events because
774 // otherwise GetValue() would return incorrect (not yet updated value)
775 m_tempCallbackStruct
= NULL
;
778 // ----------------------------------------------------------------------------
779 // helpers and Motif callbacks
780 // ----------------------------------------------------------------------------
782 static void MergeChangesIntoString(wxString
& value
,
783 XmTextVerifyCallbackStruct
*cbs
)
786 * At least on my system (SunOS 4.1.3 + Motif 1.2), you need to think of
787 * every event as a replace event. cbs->text->ptr gives the replacement
788 * text, cbs->startPos gives the index of the first char affected by the
789 * replace, and cbs->endPos gives the index one more than the last char
790 * affected by the replace (startPos == endPos implies an empty range).
791 * Hence, a deletion is represented by replacing all input text with a
792 * blank string ("", *not* NULL!). A simple insertion that does not
793 * overwrite any text has startPos == endPos.
798 // easy case: the ol value was empty
799 value
= cbs
->text
->ptr
;
803 // merge the changes into the value
804 const char * const passwd
= value
;
805 int len
= value
.length();
807 len
+= strlen(cbs
->text
->ptr
) + 1; // + new text (if any) + NUL
808 len
-= cbs
->endPos
- cbs
->startPos
; // - text from affected region.
810 char * newS
= new char [len
];
812 * insert
= cbs
->text
->ptr
;
814 // Copy (old) text from passwd, up to the start posn of the change.
816 const char * p
= passwd
;
817 for (i
= 0; i
< cbs
->startPos
; ++i
)
820 // Copy the text to be inserted).
824 // Finally, copy into newS any remaining text from passwd[endPos] on.
825 for (p
= passwd
+ cbs
->endPos
; *p
; )
836 wxTextWindowChangedProc (Widget w
, XtPointer clientData
, XtPointer ptr
)
838 if (!wxGetWindowFromTable(w
))
839 // Widget has been deleted!
842 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
843 tw
->SetModified(TRUE
);
847 wxTextWindowModifyProc (Widget w
, XtPointer clientData
, XmTextVerifyCallbackStruct
*cbs
)
849 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
850 tw
->m_processedDefault
= FALSE
;
852 // First, do some stuff if it's a password control: in this case, we need
853 // to store the string inside the class because GetValue() can't retrieve
854 // it from the text ctrl. We do *not* do it in other circumstances because
855 // it would double the amount of memory needed.
857 if ( tw
->GetWindowStyleFlag() & wxTE_PASSWORD
)
859 MergeChangesIntoString(tw
->m_value
, cbs
);
861 if ( cbs
->text
->length
> 0 )
864 for (i
= 0; i
< cbs
->text
->length
; ++i
)
865 cbs
->text
->ptr
[i
] = '*';
866 cbs
->text
->ptr
[i
] = '\0';
870 // If we're already within an OnChar, return: probably a programmatic
872 if (tw
->m_tempCallbackStruct
)
875 // Check for a backspace
876 if (cbs
->startPos
== (cbs
->currInsert
- 1))
878 tw
->DoSendEvents((void *)cbs
, WXK_DELETE
);
883 // Pasting operation: let it through without calling OnChar
884 if (cbs
->text
->length
> 1)
887 // Something other than text
888 if (cbs
->text
->ptr
== NULL
)
892 char ch
= cbs
->text
->ptr
[0];
893 tw
->DoSendEvents((void *)cbs
, ch
== '\n' ? '\r' : ch
);
897 wxTextWindowGainFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
)
899 if (!wxGetWindowFromTable(w
))
902 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
903 wxFocusEvent
event(wxEVT_SET_FOCUS
, tw
->GetId());
904 event
.SetEventObject(tw
);
905 tw
->GetEventHandler()->ProcessEvent(event
);
909 wxTextWindowLoseFocusProc (Widget w
, XtPointer clientData
, XmAnyCallbackStruct
*cbs
)
911 if (!wxGetWindowFromTable(w
))
914 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
915 wxFocusEvent
event(wxEVT_KILL_FOCUS
, tw
->GetId());
916 event
.SetEventObject(tw
);
917 tw
->GetEventHandler()->ProcessEvent(event
);
920 static void wxTextWindowActivateProc(Widget w
, XtPointer clientData
,
921 XmAnyCallbackStruct
*ptr
)
923 if (!wxGetWindowFromTable(w
))
926 wxTextCtrl
*tw
= (wxTextCtrl
*) clientData
;
928 if (tw
->InSetValue())
931 wxCommandEvent
event(wxEVT_COMMAND_TEXT_ENTER
);
932 event
.SetId(tw
->GetId());
933 event
.SetEventObject(tw
);
934 tw
->ProcessCommand(event
);