1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:c
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 // Copyright (c) 2004-2006 Novell, Inc. (http://www.novell.com)
23 // Peter Bartok pbartok@novell.com
31 using System.ComponentModel;
32 using System.ComponentModel.Design;
34 using System.Drawing.Text;
36 using System.Runtime.InteropServices;
37 using System.Collections;
39 namespace System.Windows.Forms
43 [DefaultBindingProperty ("Text")]
44 [ClassInterface (ClassInterfaceType.AutoDispatch)]
46 [DefaultEvent("TextChanged")]
47 [Designer("System.Windows.Forms.Design.TextBoxBaseDesigner, " + Consts.AssemblySystem_Design)]
48 public abstract class TextBoxBase : Control
50 #region Local Variables
51 internal HorizontalAlignment alignment;
52 internal bool accepts_tab;
53 internal bool accepts_return;
54 internal bool auto_size;
55 internal bool backcolor_set;
56 internal CharacterCasing character_casing;
57 internal bool hide_selection;
59 internal bool modified;
60 internal char password_char;
61 internal bool read_only;
62 internal bool word_wrap;
63 internal Document document;
64 internal LineTag caret_tag; // tag our cursor is in
65 internal int caret_pos; // position on the line our cursor is in (can be 0 = beginning of line)
66 internal ImplicitHScrollBar hscroll;
67 internal ImplicitVScrollBar vscroll;
68 internal RichTextBoxScrollBars scrollbars;
69 internal Timer scroll_timer;
70 internal bool richtext;
71 internal bool show_selection; // set to true to always show selection, even if no focus is set
72 internal ArrayList list_links; // currently showing links
73 private LinkRectangle current_link; // currently hovering link
74 private bool enable_links; // whether links are enabled
76 internal bool has_been_focused;
78 internal int selection_length = -1; // set to the user-specified selection length, or -1 if none
79 internal bool show_caret_w_selection; // TextBox shows the caret when the selection is visible
80 internal int canvas_width;
81 internal int canvas_height;
82 static internal int track_width = 2; //
83 static internal int track_border = 5; //
84 internal DateTime click_last;
85 internal int click_point_x;
86 internal int click_point_y;
87 internal CaretSelection click_mode;
88 internal BorderStyle actual_border_style;
89 internal bool shortcuts_enabled = true;
91 internal static bool draw_lines = false;
94 #endregion // Local Variables
96 #region Internal Constructor
97 // Constructor will go when complete, only for testing - pdb
98 internal TextBoxBase ()
100 alignment = HorizontalAlignment.Left;
101 accepts_return = false;
104 InternalBorderStyle = BorderStyle.Fixed3D;
105 actual_border_style = BorderStyle.Fixed3D;
106 character_casing = CharacterCasing.Normal;
107 hide_selection = true;
108 max_length = short.MaxValue;
109 password_char = '\0';
113 show_selection = false;
114 enable_links = false;
115 list_links = new ArrayList ();
117 show_caret_w_selection = (this is TextBox);
118 document = new Document(this);
119 document.WidthChanged += new EventHandler(document_WidthChanged);
120 document.HeightChanged += new EventHandler(document_HeightChanged);
121 //document.CaretMoved += new EventHandler(CaretMoved);
122 document.Wrap = false;
123 click_last = DateTime.Now;
124 click_mode = CaretSelection.Position;
126 MouseDown += new MouseEventHandler(TextBoxBase_MouseDown);
127 MouseUp += new MouseEventHandler(TextBoxBase_MouseUp);
128 MouseMove += new MouseEventHandler(TextBoxBase_MouseMove);
129 SizeChanged += new EventHandler(TextBoxBase_SizeChanged);
130 FontChanged += new EventHandler(TextBoxBase_FontOrColorChanged);
131 ForeColorChanged += new EventHandler(TextBoxBase_FontOrColorChanged);
132 MouseWheel += new MouseEventHandler(TextBoxBase_MouseWheel);
133 RightToLeftChanged += new EventHandler (TextBoxBase_RightToLeftChanged);
135 scrollbars = RichTextBoxScrollBars.None;
137 hscroll = new ImplicitHScrollBar();
138 hscroll.ValueChanged += new EventHandler(hscroll_ValueChanged);
139 hscroll.SetStyle (ControlStyles.Selectable, false);
140 hscroll.Enabled = false;
141 hscroll.Visible = false;
142 hscroll.Maximum = Int32.MaxValue;
144 vscroll = new ImplicitVScrollBar();
145 vscroll.ValueChanged += new EventHandler(vscroll_ValueChanged);
146 vscroll.SetStyle (ControlStyles.Selectable, false);
147 vscroll.Enabled = false;
148 vscroll.Visible = false;
149 vscroll.Maximum = Int32.MaxValue;
152 this.Controls.AddImplicit (hscroll);
153 this.Controls.AddImplicit (vscroll);
156 SetStyle(ControlStyles.UserPaint | ControlStyles.StandardClick, false);
158 SetStyle(ControlStyles.UseTextForAccessibility, false);
160 base.SetAutoSizeMode (AutoSizeMode.GrowAndShrink);
163 canvas_width = ClientSize.Width;
164 canvas_height = ClientSize.Height;
165 document.ViewPortWidth = canvas_width;
166 document.ViewPortHeight = canvas_height;
168 Cursor = Cursors.IBeam;
170 #endregion // Internal Constructor
172 #region Private and Internal Methods
173 internal string CaseAdjust (string s)
175 if (character_casing == CharacterCasing.Normal)
177 if (character_casing == CharacterCasing.Lower)
183 internal override Size GetPreferredSizeCore (Size proposedSize)
185 return new Size (Width, Height);
189 internal override void HandleClick (int clicks, MouseEventArgs me)
191 // MS seems to fire the click event in spite of the styles they set
192 bool click_set = GetStyle (ControlStyles.StandardClick);
193 bool doubleclick_set = GetStyle (ControlStyles.StandardDoubleClick);
195 // so explicitly set them to true first
196 SetStyle (ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true);
198 base.HandleClick (clicks, me);
200 // then revert to our previous state
202 SetStyle (ControlStyles.StandardClick, false);
203 if (!doubleclick_set)
204 SetStyle (ControlStyles.StandardDoubleClick, false);
207 internal override void PaintControlBackground (PaintEventArgs pevent)
209 if (!ThemeEngine.Current.TextBoxBaseShouldPaintBackground (this))
211 base.PaintControlBackground (pevent);
213 #endregion // Private and Internal Methods
215 #region Public Instance Properties
216 [DefaultValue(false)]
217 [MWFCategory("Behavior")]
218 public bool AcceptsTab {
224 if (value != accepts_tab) {
226 OnAcceptsTabChanged(EventArgs.Empty);
233 [EditorBrowsable (EditorBrowsableState.Never)]
237 [RefreshProperties(RefreshProperties.Repaint)]
238 [MWFCategory("Behavior")]
251 if (value != auto_size) {
254 if (PreferredHeight != ClientSize.Height) {
255 ClientSize = new Size(ClientSize.Width, PreferredHeight);
259 OnAutoSizeChanged(EventArgs.Empty);
266 public override System.Drawing.Color BackColor {
268 return base.BackColor;
271 backcolor_set = true;
272 base.BackColor = ChangeBackColor (value);
277 [EditorBrowsable(EditorBrowsableState.Never)]
278 public override System.Drawing.Image BackgroundImage {
280 return base.BackgroundImage;
283 base.BackgroundImage = value;
287 [DefaultValue(BorderStyle.Fixed3D)]
289 [MWFCategory("Appearance")]
290 public BorderStyle BorderStyle {
291 get { return actual_border_style; }
293 if (value == actual_border_style)
296 if (actual_border_style != BorderStyle.Fixed3D || value != BorderStyle.Fixed3D)
299 actual_border_style = value;
300 document.UpdateMargins ();
302 if (value != BorderStyle.Fixed3D)
303 value = BorderStyle.None;
305 InternalBorderStyle = value;
306 OnBorderStyleChanged(EventArgs.Empty);
311 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
312 public bool CanUndo {
314 return document.undo.CanUndo;
319 public override System.Drawing.Color ForeColor {
321 return base.ForeColor;
324 base.ForeColor = value;
329 [MWFCategory("Behavior")]
330 public bool HideSelection {
332 return hide_selection;
336 if (value != hide_selection) {
337 hide_selection = value;
338 OnHideSelectionChanged(EventArgs.Empty);
340 document.selection_visible = !hide_selection;
341 document.InvalidateSelectionArea();
346 [MergableProperty (false)]
348 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
349 [Editor("System.Windows.Forms.Design.StringArrayEditor, " + Consts.AssemblySystem_Design, typeof(System.Drawing.Design.UITypeEditor))]
351 [MWFCategory("Appearance")]
352 public string[] Lines {
357 count = document.Lines;
359 // Handle empty document
360 if ((count == 1) && (document.GetLine (1).text.Length == 0)) {
361 return new string [0];
364 lines = new ArrayList ();
369 StringBuilder lt = new StringBuilder ();
372 line = document.GetLine (i++);
373 lt.Append (line.TextWithoutEnding ());
374 } while (line.ending == LineEnding.Wrap && i <= count);
376 lines.Add (lt.ToString ());
379 return (string []) lines.ToArray (typeof (string));
383 StringBuilder sb = new StringBuilder ();
385 for (int i = 0; i < value.Length; i++) {
386 // Don't add the last line if it is just an empty line feed
387 // the line feed is reflected in the previous line's ending
388 if (i == value.Length - 1 && value[i].Length == 0)
391 sb.Append (value[i] + Environment.NewLine);
394 int newline_length = Environment.NewLine.Length;
396 // We want to remove the final new line character
397 if (sb.Length >= newline_length)
398 sb.Remove (sb.Length - newline_length, newline_length);
400 Text = sb.ToString ();
404 [DefaultValue(32767)]
406 [MWFCategory("Behavior")]
407 public virtual int MaxLength {
409 if (max_length == (int.MaxValue - 1)) { // We don't distinguish between single and multi-line limits
416 if (value != max_length) {
418 value = int.MaxValue - 1;
426 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
427 public bool Modified {
433 if (value != modified) {
435 OnModifiedChanged(EventArgs.Empty);
440 [DefaultValue(false)]
442 [RefreshProperties(RefreshProperties.All)]
443 [MWFCategory("Behavior")]
444 public virtual bool Multiline {
446 return document.multiline;
450 if (value != document.multiline) {
451 document.multiline = value;
454 SetStyle (ControlStyles.FixedHeight, !value);
456 // SetBoundsCore overrides the Height for multiline if it needs to,
457 // so we don't need to worry about it here.
458 SetBoundsCore (Left, Top, Width, ExplicitBounds.Height, BoundsSpecified.None);
461 Parent.PerformLayout ();
463 OnMultilineChanged(EventArgs.Empty);
466 if (document.multiline) {
467 document.Wrap = word_wrap;
468 document.PasswordChar = "";
471 document.Wrap = false;
472 if (this.password_char != '\0') {
474 document.PasswordChar = (this as TextBox).PasswordChar.ToString ();
476 document.PasswordChar = "";
481 CalculateDocument ();
486 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
487 [EditorBrowsable(EditorBrowsableState.Advanced)]
488 public int PreferredHeight {
490 if (BorderStyle != BorderStyle.None)
491 return Font.Height + 7;
493 // usually in borderless mode the top margin is 0, but
494 // try to access it, in case it was set manually, as ToolStrip* controls do
495 return Font.Height + TopMargin;
500 [RefreshProperties (RefreshProperties.Repaint)]
502 [DefaultValue(false)]
503 [MWFCategory("Behavior")]
504 public bool ReadOnly {
510 if (value != read_only) {
513 if (!backcolor_set) {
515 background_color = SystemColors.Control;
517 background_color = SystemColors.Window;
520 OnReadOnlyChanged(EventArgs.Empty);
527 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
528 public virtual string SelectedText {
530 string retval = document.GetSelection ();
533 if (!IsHandleCreated && retval == string.Empty)
540 document.ReplaceSelection(CaseAdjust(value), false);
543 OnTextChanged(EventArgs.Empty);
548 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
549 public virtual int SelectionLength {
551 int res = document.SelectionLength ();
554 if (res == 0 && !IsHandleCreated)
563 string msg = String.Format ("'{0}' is not a valid value for 'SelectionLength'", value);
565 throw new ArgumentOutOfRangeException ("SelectionLength", msg);
567 throw new ArgumentException (msg);
571 document.InvalidateSelectionArea ();
578 selection_length = value;
579 start = document.LineTagToCharIndex (document.selection_start.line, document.selection_start.pos);
580 document.CharIndexToLineTag (start + value, out line, out tag, out pos);
581 document.SetSelectionEnd (line, pos, true);
582 document.PositionCaret (line, pos);
584 selection_length = -1;
585 document.SetSelectionEnd (document.selection_start.line, document.selection_start.pos, true);
586 document.PositionCaret (document.selection_start.line, document.selection_start.pos);
592 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
593 public int SelectionStart {
595 return document.LineTagToCharIndex(document.selection_start.line,
596 document.selection_start.pos);
601 string msg = String.Format ("'{0}' is not a valid value for 'SelectionStart'", value);
603 throw new ArgumentOutOfRangeException ("SelectionStart", msg);
605 throw new ArgumentException (msg);
609 // If SelectionStart has been used, we don't highlight on focus
610 has_been_focused = true;
612 document.InvalidateSelectionArea ();
613 document.SetSelectionStart (value, false);
614 if (selection_length > -1)
615 document.SetSelectionEnd (value + selection_length, true);
617 document.SetSelectionEnd (value, true);
618 document.PositionCaret (document.selection_start.line, document.selection_start.pos);
624 [DefaultValue (true)]
625 public virtual bool ShortcutsEnabled {
626 get { return shortcuts_enabled; }
627 set { shortcuts_enabled = value; }
630 [Editor ("System.ComponentModel.Design.MultilineStringEditor, " + Consts.AssemblySystem_Design,
631 "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
634 public override string Text {
636 if (document == null || document.Root == null || document.Root.text == null)
639 StringBuilder sb = new StringBuilder();
642 for (int i = 1; i <= document.Lines; i++) {
643 line = document.GetLine (i);
644 sb.Append(line.text.ToString ());
647 return sb.ToString();
651 // reset to force a select all next time the box gets focus
652 has_been_focused = false;
657 if ((value != null) && (value != "")) {
661 document.Insert (document.GetLine (1), 0, false, value);
663 document.PositionCaret (document.GetLine (1), 0);
664 document.SetSelectionToCaret (true);
670 document.SetSelectionToCaret (true);
672 CalculateDocument ();
675 OnTextChanged(EventArgs.Empty);
680 public virtual int TextLength {
682 if (document == null || document.Root == null || document.Root.text == null)
690 [MWFCategory("Behavior")]
691 public bool WordWrap {
697 if (value != word_wrap) {
698 if (document.multiline) {
700 document.Wrap = value;
702 CalculateDocument ();
709 [EditorBrowsable (EditorBrowsableState.Never)]
710 public override ImageLayout BackgroundImageLayout {
711 get { return base.BackgroundImageLayout; }
712 set { base.BackgroundImageLayout = value; }
716 [EditorBrowsable (EditorBrowsableState.Never)]
717 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
718 public new Padding Padding {
719 get { return base.Padding; }
720 set { base.Padding = value; }
723 protected override Cursor DefaultCursor {
724 get { return Cursors.IBeam; }
727 #endregion // Public Instance Properties
729 #region Protected Instance Properties
731 protected override bool CanEnableIme {
733 if (ReadOnly || password_char != '\0')
741 protected override CreateParams CreateParams {
743 return base.CreateParams;
747 protected override System.Drawing.Size DefaultSize {
749 return new Size(100, 20);
754 // Currently our double buffering breaks our scrolling, so don't let people enable this
755 [EditorBrowsable (EditorBrowsableState.Never)]
756 protected override bool DoubleBuffered {
757 get { return false; }
762 #endregion // Protected Instance Properties
764 #region Public Instance Methods
765 public void AppendText (string text)
767 // Save some cycles and only check the Text if we are one line
768 bool is_empty = document.Lines == 1 && Text == String.Empty;
770 // make sure the caret begins at the end
771 if (document.caret.line.line_no != document.Lines ||
772 (document.caret.pos) != document.caret.line.TextLengthWithoutEnding ()) {
773 document.MoveCaret (CaretDirection.CtrlEnd);
775 document.Insert (document.caret.line, document.caret.pos, false, text, document.CaretTag);
776 document.MoveCaret (CaretDirection.CtrlEnd);
777 document.SetSelectionToCaret (true);
783 // Avoid the initial focus selecting all when append text is used
785 has_been_focused = true;
788 OnTextChanged(EventArgs.Empty);
797 public void ClearUndo ()
799 document.undo.Clear();
806 o = new DataObject(DataFormats.Text, SelectedText);
807 if (this is RichTextBox)
808 o.SetData(DataFormats.Rtf, ((RichTextBox)this).SelectedRtf);
809 Clipboard.SetDataObject(o);
816 o = new DataObject(DataFormats.Text, SelectedText);
817 if (this is RichTextBox)
818 o.SetData(DataFormats.Rtf, ((RichTextBox)this).SelectedRtf);
819 Clipboard.SetDataObject (o);
821 document.undo.BeginUserAction (Locale.GetText ("Cut"));
822 document.ReplaceSelection (String.Empty, false);
823 document.undo.EndUserAction ();
826 OnTextChanged (EventArgs.Empty);
831 Paste (Clipboard.GetDataObject(), null, false);
834 public void ScrollToCaret ()
837 CaretMoved (this, EventArgs.Empty);
840 public void Select(int start, int length)
842 SelectionStart = start;
843 SelectionLength = length;
846 public void SelectAll ()
850 last = document.GetLine(document.Lines);
851 document.SetSelectionStart(document.GetLine(1), 0, false);
852 document.SetSelectionEnd(last, last.text.Length, true);
853 document.PositionCaret (document.selection_end.line, document.selection_end.pos);
854 selection_length = -1;
856 CaretMoved (this, null);
858 document.DisplayCaret ();
861 internal void SelectAllNoScroll ()
865 last = document.GetLine(document.Lines);
866 document.SetSelectionStart(document.GetLine(1), 0, false);
867 document.SetSelectionEnd(last, last.text.Length, false);
868 document.PositionCaret (document.selection_end.line, document.selection_end.pos);
869 selection_length = -1;
871 document.DisplayCaret ();
874 public override string ToString ()
876 return String.Concat (base.ToString (), ", Text: ", Text);
879 [MonoInternalNote ("Deleting is classed as Typing, instead of its own Undo event")]
882 if (document.undo.Undo ()) {
884 OnTextChanged (EventArgs.Empty);
889 public void DeselectAll ()
894 public virtual char GetCharFromPosition (Point pt)
896 return GetCharFromPositionInternal (pt);
899 internal virtual char GetCharFromPositionInternal (Point p)
902 LineTag tag = document.FindCursor (p.X, p.Y, out index);
904 return (char) 0; // Shouldn't happen
906 if (index >= tag.Line.text.Length) {
908 if (tag.Line.ending == LineEnding.Wrap) {
909 // If we have wrapped text, we return the first char of the next line
910 Line line = document.GetLine (tag.Line.line_no + 1);
912 return line.text [0];
916 if (tag.Line.line_no == document.Lines) {
917 // Last line returns the last char
918 return tag.Line.text [tag.Line.text.Length - 1];
921 // This really shouldn't happen
924 return tag.Line.text [index];
927 public virtual int GetCharIndexFromPosition (Point pt)
930 LineTag tag = document.FindCursor (pt.X, pt.Y, out line_index);
934 if (line_index >= tag.Line.text.Length) {
936 if (tag.Line.ending == LineEnding.Wrap) {
937 // If we have wrapped text, we return the first char of the next line
938 Line line = document.GetLine (tag.Line.line_no + 1);
940 return document.LineTagToCharIndex (line, 0);
943 if (tag.Line.line_no == document.Lines) {
944 // Last line returns the last char
945 return document.LineTagToCharIndex (tag.Line, tag.Line.text.Length - 1);
951 return document.LineTagToCharIndex (tag.Line, line_index);
954 public virtual Point GetPositionFromCharIndex (int index)
960 document.CharIndexToLineTag (index, out line, out tag, out pos);
962 return new Point ((int) (line.widths [pos] +
963 line.X + document.viewport_x),
964 line.Y + document.viewport_y + tag.Shift);
967 public int GetFirstCharIndexFromLine (int lineNumber)
969 Line line = document.GetLine (lineNumber + 1);
973 return document.LineTagToCharIndex (line, 0);
976 public int GetFirstCharIndexOfCurrentLine ()
978 return document.LineTagToCharIndex (document.caret.line, 0);
981 #endregion // Public Instance Methods
983 #region Protected Instance Methods
984 protected override void CreateHandle ()
986 CalculateDocument ();
987 base.CreateHandle ();
988 document.AlignCaret();
992 internal virtual void HandleLinkClicked (LinkRectangle link_clicked)
996 protected override bool IsInputKey (Keys keyData)
998 if ((keyData & Keys.Alt) != 0)
999 return base.IsInputKey(keyData);
1001 switch (keyData & Keys.KeyCode) {
1003 return (accepts_return && document.multiline);
1007 if (accepts_tab && document.multiline)
1008 if ((keyData & Keys.Control) == 0)
1027 protected virtual void OnAcceptsTabChanged(EventArgs e)
1029 EventHandler eh = (EventHandler)(Events [AcceptsTabChangedEvent]);
1035 protected virtual void OnAutoSizeChanged (EventArgs e)
1037 EventHandler eh = (EventHandler)(Events [AutoSizeChangedEvent]);
1043 protected virtual void OnBorderStyleChanged (EventArgs e)
1045 EventHandler eh = (EventHandler)(Events [BorderStyleChangedEvent]);
1050 protected override void OnFontChanged (EventArgs e)
1052 base.OnFontChanged (e);
1054 if (auto_size && !document.multiline) {
1055 if (PreferredHeight != ClientSize.Height) {
1056 Height = PreferredHeight;
1061 protected override void OnHandleCreated (EventArgs e)
1063 base.OnHandleCreated (e);
1067 protected override void OnHandleDestroyed (EventArgs e)
1069 base.OnHandleDestroyed (e);
1072 protected virtual void OnHideSelectionChanged (EventArgs e)
1074 EventHandler eh = (EventHandler)(Events [HideSelectionChangedEvent]);
1079 protected virtual void OnModifiedChanged (EventArgs e)
1081 EventHandler eh = (EventHandler)(Events [ModifiedChangedEvent]);
1086 protected virtual void OnMultilineChanged (EventArgs e)
1088 EventHandler eh = (EventHandler)(Events [MultilineChangedEvent]);
1094 protected override void OnPaddingChanged (EventArgs e)
1096 base.OnPaddingChanged (e);
1100 protected virtual void OnReadOnlyChanged (EventArgs e)
1102 EventHandler eh = (EventHandler)(Events [ReadOnlyChangedEvent]);
1108 protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
1110 return base.ProcessCmdKey (ref msg, keyData);
1113 protected override bool ProcessDialogKey (Keys keyData)
1115 // The user can use Ctrl-Tab or Ctrl-Shift-Tab to move control focus
1116 // instead of inserting a Tab. However, the focus-moving-tab-stuffs
1117 // doesn't work if Ctrl is pushed, so we remove it before sending it.
1118 if (accepts_tab && (keyData & (Keys.Control | Keys.Tab)) == (Keys.Control | Keys.Tab))
1119 keyData ^= Keys.Control;
1121 return base.ProcessDialogKey(keyData);
1124 private bool ProcessKey (Keys keyData)
1129 control = (Control.ModifierKeys & Keys.Control) != 0;
1130 shift = (Control.ModifierKeys & Keys.Shift) != 0;
1132 if (shortcuts_enabled) {
1133 switch (keyData & Keys.KeyCode) {
1135 if (control && read_only == false) {
1149 if (control && read_only == false) {
1150 return Paste(Clipboard.GetDataObject(), null, true);
1155 if (control && read_only == false) {
1170 if (read_only == false) {
1172 Paste (Clipboard.GetDataObject (), null, true);
1189 if (shift && read_only == false) {
1194 if (document.selection_visible) {
1195 document.ReplaceSelection("", false);
1197 // DeleteChar only deletes on the line, doesn't do the combine
1198 if (document.CaretPosition >= document.CaretLine.TextLengthWithoutEnding ()) {
1199 if (document.CaretLine.LineNo < document.Lines) {
1202 line = document.GetLine(document.CaretLine.LineNo + 1);
1204 // this line needs to be invalidated before it is combined
1205 // because once it is combined, all it's coordinates will
1207 document.Invalidate (line, 0, line, line.text.Length);
1208 document.Combine(document.CaretLine, line);
1210 document.UpdateView(document.CaretLine,
1216 document.DeleteChar(document.CaretTag.Line, document.CaretPosition, true);
1220 end_pos = document.CaretPosition;
1222 while ((end_pos < document.CaretLine.Text.Length) && !Document.IsWordSeparator(document.CaretLine.Text[end_pos])) {
1226 if (end_pos < document.CaretLine.Text.Length) {
1229 document.DeleteChars(document.CaretTag.Line, document.CaretPosition, end_pos - document.CaretPosition);
1234 document.AlignCaret();
1235 document.UpdateCaret();
1236 CaretMoved(this, null);
1239 OnTextChanged (EventArgs.Empty);
1245 switch (keyData & Keys.KeyCode) {
1248 document.MoveCaret(CaretDirection.WordBack);
1250 if (!document.selection_visible || shift) {
1251 document.MoveCaret(CaretDirection.CharBack);
1253 document.MoveCaret(CaretDirection.SelectionStart);
1258 document.SetSelectionToCaret(true);
1260 document.SetSelectionToCaret(false);
1263 CaretMoved(this, null);
1269 document.MoveCaret(CaretDirection.WordForward);
1271 if (!document.selection_visible || shift) {
1272 document.MoveCaret(CaretDirection.CharForward);
1274 document.MoveCaret(CaretDirection.SelectionEnd);
1278 document.SetSelectionToCaret(true);
1280 document.SetSelectionToCaret(false);
1283 CaretMoved(this, null);
1289 if (document.CaretPosition == 0) {
1290 document.MoveCaret(CaretDirection.LineUp);
1292 document.MoveCaret(CaretDirection.Home);
1295 document.MoveCaret(CaretDirection.LineUp);
1298 if ((Control.ModifierKeys & Keys.Shift) == 0) {
1299 document.SetSelectionToCaret(true);
1301 document.SetSelectionToCaret(false);
1304 CaretMoved(this, null);
1310 if (document.CaretPosition == document.CaretLine.Text.Length) {
1311 document.MoveCaret(CaretDirection.LineDown);
1313 document.MoveCaret(CaretDirection.End);
1316 document.MoveCaret(CaretDirection.LineDown);
1319 if ((Control.ModifierKeys & Keys.Shift) == 0) {
1320 document.SetSelectionToCaret(true);
1322 document.SetSelectionToCaret(false);
1325 CaretMoved(this, null);
1330 if ((Control.ModifierKeys & Keys.Control) != 0) {
1331 document.MoveCaret(CaretDirection.CtrlHome);
1333 document.MoveCaret(CaretDirection.Home);
1336 if ((Control.ModifierKeys & Keys.Shift) == 0) {
1337 document.SetSelectionToCaret(true);
1339 document.SetSelectionToCaret(false);
1342 CaretMoved(this, null);
1347 if ((Control.ModifierKeys & Keys.Control) != 0) {
1348 document.MoveCaret(CaretDirection.CtrlEnd);
1350 document.MoveCaret(CaretDirection.End);
1353 if ((Control.ModifierKeys & Keys.Shift) == 0) {
1354 document.SetSelectionToCaret(true);
1356 document.SetSelectionToCaret(false);
1359 CaretMoved(this, null);
1363 //case Keys.Enter: {
1364 // // ignoring accepts_return, fixes bug #76355
1365 // if (!read_only && document.multiline && (accepts_return || (FindForm() != null && FindForm().AcceptButton == null) || ((Control.ModifierKeys & Keys.Control) != 0))) {
1368 // if (document.selection_visible) {
1369 // document.ReplaceSelection("\n", false);
1372 // line = document.CaretLine;
1374 // document.Split (document.CaretLine, document.CaretTag, document.CaretPosition);
1375 // line.ending = LineEnding.Rich;
1376 // document.InsertString (line, line.text.Length,
1377 // document.LineEndingToString (line.ending));
1378 // OnTextChanged(EventArgs.Empty);
1380 // document.UpdateView (line, document.Lines - line.line_no, 0);
1381 // CaretMoved(this, null);
1388 if (!read_only && accepts_tab && document.multiline) {
1389 document.InsertCharAtCaret ('\t', true);
1391 CaretMoved(this, null);
1393 OnTextChanged (EventArgs.Empty);
1401 if ((Control.ModifierKeys & Keys.Control) != 0) {
1402 document.MoveCaret(CaretDirection.CtrlPgUp);
1404 document.MoveCaret(CaretDirection.PgUp);
1406 document.DisplayCaret ();
1410 case Keys.PageDown: {
1411 if ((Control.ModifierKeys & Keys.Control) != 0) {
1412 document.MoveCaret(CaretDirection.CtrlPgDn);
1414 document.MoveCaret(CaretDirection.PgDn);
1416 document.DisplayCaret ();
1424 internal virtual void RaiseSelectionChanged ()
1426 // Do nothing, overridden in RTB
1429 private void HandleBackspace (bool control)
1433 fire_changed = false;
1435 // delete only deletes on the line, doesn't do the combine
1436 if (document.selection_visible) {
1437 document.undo.BeginUserAction (Locale.GetText ("Delete"));
1438 document.ReplaceSelection("", false);
1439 document.undo.EndUserAction ();
1440 fire_changed = true;
1441 document.SetSelectionToCaret (true);
1443 document.SetSelectionToCaret (true);
1445 if (document.CaretPosition == 0) {
1446 if (document.CaretLine.LineNo > 1) {
1450 line = document.GetLine(document.CaretLine.LineNo - 1);
1451 new_caret_pos = line.TextLengthWithoutEnding ();
1453 // Invalidate the old line position before we do the combine
1454 document.Invalidate (line, 0, line, line.text.Length);
1455 document.Combine(line, document.CaretLine);
1457 document.UpdateView(line, document.Lines - line.LineNo, 0);
1458 document.PositionCaret(line, new_caret_pos);
1459 document.SetSelectionToCaret (true);
1460 document.UpdateCaret();
1461 fire_changed = true;
1464 if (!control || document.CaretPosition == 0) {
1466 // Move before we delete because the delete will change positions around
1467 // if we cross a wrap border
1468 LineTag tag = document.CaretTag;
1469 int pos = document.CaretPosition;
1470 document.MoveCaret (CaretDirection.CharBack);
1471 document.DeleteChar (tag.Line, pos, false);
1472 document.SetSelectionToCaret (true);
1477 start_pos = document.CaretPosition - 1;
1478 while ((start_pos > 0) && !Document.IsWordSeparator(document.CaretLine.Text[start_pos - 1])) {
1482 document.undo.BeginUserAction (Locale.GetText ("Delete"));
1483 document.DeleteChars(document.CaretTag.Line, start_pos, document.CaretPosition - start_pos);
1484 document.undo.EndUserAction ();
1485 document.PositionCaret(document.CaretLine, start_pos);
1486 document.SetSelectionToCaret (true);
1488 document.UpdateCaret();
1489 fire_changed = true;
1493 CaretMoved (this, null);
1497 OnTextChanged(EventArgs.Empty);
1501 private void HandleEnter ()
1503 // ignoring accepts_return, fixes bug #76355
1504 if (!read_only && document.multiline && (accepts_return || (FindForm() != null && FindForm().AcceptButton == null) || ((Control.ModifierKeys & Keys.Control) != 0))) {
1507 if (document.selection_visible)
1508 document.ReplaceSelection ("", false);
1510 line = document.CaretLine;
1512 document.Split (document.CaretLine, document.CaretTag, document.CaretPosition);
1513 line.ending = document.StringToLineEnding (Environment.NewLine);
1514 document.InsertString (line, line.text.Length, document.LineEndingToString (line.ending));
1516 document.UpdateView (line, document.Lines - line.line_no, 0);
1517 CaretMoved (this, null);
1519 OnTextChanged (EventArgs.Empty);
1523 protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified)
1525 // Make sure we don't get sized bigger than we want to be
1528 if (!document.multiline) {
1529 if (height != PreferredHeight) {
1530 // If the specified has Height, we need to store that in the
1531 // ExplicitBounds because we are going to override it
1532 if ((specified & BoundsSpecified.Height) != 0) {
1533 Rectangle r = ExplicitBounds;
1536 specified &= ~BoundsSpecified.Height;
1539 height = PreferredHeight;
1544 base.SetBoundsCore (x, y, width, height, specified);
1547 protected override void WndProc (ref Message m)
1549 switch ((Msg)m.Msg) {
1550 case Msg.WM_KEYDOWN: {
1551 if (ProcessKeyMessage(ref m) || ProcessKey((Keys)m.WParam.ToInt32() | XplatUI.State.ModifierKeys)) {
1552 m.Result = IntPtr.Zero;
1562 if (ProcessKeyMessage(ref m)) {
1563 m.Result = IntPtr.Zero;
1571 m.Result = IntPtr.Zero;
1573 ch = m.WParam.ToInt32();
1576 HandleBackspace(true);
1577 } else if (ch >= 32) {
1578 if (document.selection_visible) {
1579 document.ReplaceSelection("", false);
1582 char c = (char)m.WParam;
1583 switch (character_casing) {
1584 case CharacterCasing.Upper:
1585 c = Char.ToUpper((char) m.WParam);
1587 case CharacterCasing.Lower:
1588 c = Char.ToLower((char) m.WParam);
1592 if (document.Length < max_length) {
1593 document.InsertCharAtCaret(c, true);
1597 CaretMoved (this, null);
1599 OnTextChanged(EventArgs.Empty);
1602 XplatUI.AudibleAlert(AlertType.Default);
1605 } else if (ch == 8) {
1606 HandleBackspace(false);
1607 } else if (ch == 13)
1613 case Msg.WM_SETFOCUS:
1614 base.WndProc(ref m);
1615 document.CaretHasFocus ();
1618 case Msg.WM_KILLFOCUS:
1619 base.WndProc(ref m);
1620 document.CaretLostFocus ();
1623 case Msg.WM_NCPAINT:
1624 if (!ThemeEngine.Current.TextBoxBaseHandleWmNcPaint (this, ref m))
1625 base.WndProc(ref m);
1629 base.WndProc(ref m);
1634 #endregion // Protected Instance Methods
1637 static object AcceptsTabChangedEvent = new object ();
1638 static object AutoSizeChangedEvent = new object ();
1639 static object BorderStyleChangedEvent = new object ();
1640 static object HideSelectionChangedEvent = new object ();
1641 static object ModifiedChangedEvent = new object ();
1642 static object MultilineChangedEvent = new object ();
1643 static object ReadOnlyChangedEvent = new object ();
1644 static object HScrolledEvent = new object ();
1645 static object VScrolledEvent = new object ();
1647 public event EventHandler AcceptsTabChanged {
1648 add { Events.AddHandler (AcceptsTabChangedEvent, value); }
1649 remove { Events.RemoveHandler (AcceptsTabChangedEvent, value); }
1654 [EditorBrowsable (EditorBrowsableState.Never)]
1660 event EventHandler AutoSizeChanged {
1661 add { Events.AddHandler (AutoSizeChangedEvent, value); }
1662 remove { Events.RemoveHandler (AutoSizeChangedEvent, value); }
1665 public event EventHandler BorderStyleChanged {
1666 add { Events.AddHandler (BorderStyleChangedEvent, value); }
1667 remove { Events.RemoveHandler (BorderStyleChangedEvent, value); }
1670 public event EventHandler HideSelectionChanged {
1671 add { Events.AddHandler (HideSelectionChangedEvent, value); }
1672 remove { Events.RemoveHandler (HideSelectionChangedEvent, value); }
1675 public event EventHandler ModifiedChanged {
1676 add { Events.AddHandler (ModifiedChangedEvent, value); }
1677 remove { Events.RemoveHandler (ModifiedChangedEvent, value); }
1680 public event EventHandler MultilineChanged {
1681 add { Events.AddHandler (MultilineChangedEvent, value); }
1682 remove { Events.RemoveHandler (MultilineChangedEvent, value); }
1685 public event EventHandler ReadOnlyChanged {
1686 add { Events.AddHandler (ReadOnlyChangedEvent, value); }
1687 remove { Events.RemoveHandler (ReadOnlyChangedEvent, value); }
1690 internal event EventHandler HScrolled {
1691 add { Events.AddHandler (HScrolledEvent, value); }
1692 remove { Events.RemoveHandler (HScrolledEvent, value); }
1695 internal event EventHandler VScrolled {
1696 add { Events.AddHandler (VScrolledEvent, value); }
1697 remove { Events.RemoveHandler (VScrolledEvent, value); }
1701 [EditorBrowsable(EditorBrowsableState.Never)]
1702 public new event EventHandler BackgroundImageChanged {
1703 add { base.BackgroundImageChanged += value; }
1704 remove { base.BackgroundImageChanged -= value; }
1709 [EditorBrowsable (EditorBrowsableState.Never)]
1710 public new event EventHandler BackgroundImageLayoutChanged {
1711 add { base.BackgroundImageLayoutChanged += value; }
1712 remove { base.BackgroundImageLayoutChanged -= value; }
1716 [EditorBrowsable (EditorBrowsableState.Always)]
1717 public new event MouseEventHandler MouseClick {
1718 add { base.MouseClick += value; }
1719 remove { base.MouseClick -= value; }
1723 [EditorBrowsable (EditorBrowsableState.Never)]
1724 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1725 public new event EventHandler PaddingChanged {
1726 add { base.PaddingChanged += value; }
1727 remove { base.PaddingChanged -= value; }
1731 [EditorBrowsable (EditorBrowsableState.Always)]
1734 [EditorBrowsable(EditorBrowsableState.Advanced)]
1736 public new event EventHandler Click {
1737 add { base.Click += value; }
1738 remove { base.Click -= value; }
1741 // XXX should this not manipulate base.Paint?
1743 [EditorBrowsable(EditorBrowsableState.Never)]
1744 public new event PaintEventHandler Paint;
1745 #endregion // Events
1747 #region Private Methods
1748 internal Document Document {
1758 internal bool EnableLinks {
1759 get { return enable_links; }
1761 enable_links = value;
1763 document.EnableLinks = value;
1767 internal override bool ScaleChildrenInternal {
1768 get { return false; }
1771 internal bool ShowSelection {
1773 if (show_selection || !hide_selection) {
1781 if (show_selection == value)
1784 show_selection = value;
1785 // Currently InvalidateSelectionArea is commented out so do a full invalidate
1786 document.InvalidateSelectionArea();
1790 internal int TopMargin {
1792 return document.top_margin;
1795 document.top_margin = value;
1799 #region UIA Framework Properties
1801 internal ScrollBar UIAHScrollBar {
1802 get { return hscroll; }
1805 internal ScrollBar UIAVScrollBar {
1806 get { return vscroll; }
1809 #endregion UIA Framework Properties
1811 internal Graphics CreateGraphicsInternal ()
1813 if (IsHandleCreated)
1814 return base.CreateGraphics();
1816 return DeviceContext;
1819 internal override void OnPaintInternal (PaintEventArgs pevent)
1821 Draw (pevent.Graphics, pevent.ClipRectangle);
1824 // OnPaint does not get raised on MS (see bug #80639)
1826 pevent.Handled = true;
1829 internal void Draw (Graphics g, Rectangle clippingArea)
1831 ThemeEngine.Current.TextBoxBaseFillBackground (this, g, clippingArea);
1833 // Draw the viewable document
1834 document.Draw(g, clippingArea);
1837 private void FixupHeight ()
1840 if (!document.multiline) {
1841 if (PreferredHeight != ClientSize.Height) {
1842 ClientSize = new Size (ClientSize.Width, PreferredHeight);
1848 private bool IsDoubleClick (MouseEventArgs e)
1850 TimeSpan interval = DateTime.Now - click_last;
1851 if (interval.TotalMilliseconds > SystemInformation.DoubleClickTime)
1853 Size dcs = SystemInformation.DoubleClickSize;
1854 if (e.X < click_point_x - dcs.Width / 2 || e.X > click_point_x + dcs.Width / 2)
1856 if (e.Y < click_point_y - dcs.Height / 2 || e.Y > click_point_y + dcs.Height / 2)
1861 private void TextBoxBase_MouseDown (object sender, MouseEventArgs e)
1863 bool dbliclick = false;
1865 if (e.Button == MouseButtons.Left) {
1867 // Special case when shift key is pressed and
1868 // left mouse is clicked.. set selection from
1869 // current cursor to mouse
1870 if ((Control.ModifierKeys & Keys.Shift) > 0) {
1871 document.PositionCaret (e.X + document.ViewPortX, e.Y + document.ViewPortY);
1872 document.SetSelectionToCaret (false);
1873 document.DisplayCaret ();
1877 dbliclick = IsDoubleClick (e);
1879 if (current_link != null) {
1880 HandleLinkClicked (current_link);
1884 //ensure nothing is selected anymore BEFORE we
1885 //position the caret, so the caret is recreated
1886 //(caret is only visible when nothing is selected)
1887 if (document.selection_visible && dbliclick == false) {
1888 document.SetSelectionToCaret (true);
1889 click_mode = CaretSelection.Position;
1892 document.PositionCaret(e.X + document.ViewPortX, e.Y + document.ViewPortY);
1895 switch (click_mode) {
1896 case CaretSelection.Position:
1898 click_mode = CaretSelection.Word;
1900 case CaretSelection.Word:
1902 if (this is TextBox) {
1903 document.SetSelectionToCaret (true);
1904 click_mode = CaretSelection.Position;
1908 document.ExpandSelection (CaretSelection.Line, false);
1909 click_mode = CaretSelection.Line;
1911 case CaretSelection.Line:
1913 // Gotta do this first because Exanding to a word
1914 // from a line doesn't really work
1915 document.SetSelectionToCaret (true);
1918 click_mode = CaretSelection.Word;
1922 document.SetSelectionToCaret (true);
1923 click_mode = CaretSelection.Position;
1926 click_point_x = e.X;
1927 click_point_y = e.Y;
1928 click_last = DateTime.Now;
1931 if ((e.Button == MouseButtons.Middle) && XplatUI.RunningOnUnix) {
1932 Document.Marker marker;
1934 marker.tag = document.FindCursor(e.X + document.ViewPortX, e.Y + document.ViewPortY, out marker.pos);
1935 marker.line = marker.tag.Line;
1936 marker.height = marker.tag.Height;
1938 document.SetSelection(marker.line, marker.pos, marker.line, marker.pos);
1939 Paste (Clipboard.GetDataObject (true), null, true);
1943 private void TextBoxBase_MouseUp (object sender, MouseEventArgs e)
1945 if (e.Button == MouseButtons.Left) {
1946 if (click_mode == CaretSelection.Position) {
1947 document.SetSelectionToCaret(false);
1948 document.DisplayCaret();
1950 // Only raise if there is text.
1951 if (Text.Length > 0)
1952 RaiseSelectionChanged ();
1955 if (scroll_timer != null) {
1956 scroll_timer.Enabled = false;
1962 private void SizeControls ()
1964 if (hscroll.Visible) {
1965 //vscroll.Maximum += hscroll.Height;
1966 canvas_height = ClientSize.Height - hscroll.Height;
1968 canvas_height = ClientSize.Height;
1971 if (vscroll.Visible) {
1972 //hscroll.Maximum += vscroll.Width;
1973 canvas_width = ClientSize.Width - vscroll.Width;
1975 if (GetInheritedRtoL () == RightToLeft.Yes) {
1976 document.OffsetX = vscroll.Width;
1978 document.OffsetX = 0;
1982 canvas_width = ClientSize.Width;
1983 document.OffsetX = 0;
1986 document.ViewPortWidth = canvas_width;
1987 document.ViewPortHeight = canvas_height;
1990 private void PositionControls ()
1992 if (canvas_height < 1 || canvas_width < 1)
1995 int hmod = vscroll.Visible ? vscroll.Width : 0;
1996 int vmod = hscroll.Visible ? hscroll.Height : 0;
1998 if (GetInheritedRtoL () == RightToLeft.Yes) {
1999 hscroll.Bounds = new Rectangle (ClientRectangle.Left + hmod,
2000 Math.Max(0, ClientRectangle.Height - hscroll.Height),
2004 vscroll.Bounds = new Rectangle (ClientRectangle.Left,
2005 ClientRectangle.Top,
2007 Math.Max(0, ClientSize.Height - (vmod)));
2009 hscroll.Bounds = new Rectangle (ClientRectangle.Left,
2010 Math.Max(0, ClientRectangle.Height - hscroll.Height),
2011 Math.Max(0, ClientSize.Width - hmod),
2014 vscroll.Bounds = new Rectangle (
2015 Math.Max(0, ClientRectangle.Right - vscroll.Width),
2016 ClientRectangle.Top,
2018 Math.Max(0, ClientSize.Height - vmod));
2022 internal RightToLeft GetInheritedRtoL ()
2024 for (Control c = this; c != null; c = c.Parent)
2025 if (c.RightToLeft != RightToLeft.Inherit)
2026 return c.RightToLeft;
2027 return RightToLeft.No;
2030 private void TextBoxBase_SizeChanged (object sender, EventArgs e)
2032 if (IsHandleCreated)
2033 CalculateDocument ();
2036 private void TextBoxBase_RightToLeftChanged (object o, EventArgs e)
2038 if (IsHandleCreated)
2039 CalculateDocument ();
2042 private void TextBoxBase_MouseWheel (object sender, MouseEventArgs e)
2044 if (!vscroll.Enabled)
2048 vscroll.Value = Math.Min (vscroll.Value + SystemInformation.MouseWheelScrollLines * 5,
2049 Math.Max (0, vscroll.Maximum - document.ViewPortHeight + 1));
2051 vscroll.Value = Math.Max (0, vscroll.Value - SystemInformation.MouseWheelScrollLines * 5);
2054 internal virtual void SelectWord ()
2056 StringBuilder s = document.caret.line.text;
2057 int start = document.caret.pos;
2058 int end = document.caret.pos;
2061 if (document.caret.line.line_no >= document.Lines)
2063 Line line = document.GetLine (document.caret.line.line_no + 1);
2064 document.PositionCaret (line, 0);
2073 // skip whitespace until we hit a word
2074 while (start > 0 && s [start] == ' ')
2077 while (start > 0 && (s [start] != ' '))
2079 if (s [start] == ' ')
2083 if (s [end] == ' ') {
2084 while (end < s.Length && s [end] == ' ')
2087 while (end < s.Length && s [end] != ' ')
2089 while (end < s.Length && s [end] == ' ')
2093 document.SetSelection (document.caret.line, start, document.caret.line, end);
2094 document.PositionCaret (document.selection_end.line, document.selection_end.pos);
2095 document.DisplayCaret();
2098 internal void CalculateDocument()
2100 CalculateScrollBars ();
2101 document.RecalculateDocument (CreateGraphicsInternal ());
2104 if (document.caret.line != null && document.caret.line.Y < document.ViewPortHeight) {
2105 // The window has probably been resized, making the entire thing visible, so
2106 // we need to set the scroll position back to zero.
2113 internal void CalculateScrollBars ()
2115 // FIXME - need separate calculations for center and right alignment
2118 if (document.Width >= document.ViewPortWidth) {
2119 hscroll.SetValues (0, Math.Max (1, document.Width), -1,
2120 document.ViewPortWidth < 0 ? 0 : document.ViewPortWidth);
2121 if (document.multiline)
2122 hscroll.Enabled = true;
2124 hscroll.Enabled = false;
2125 hscroll.Maximum = document.ViewPortWidth;
2128 if (document.Height >= document.ViewPortHeight) {
2129 vscroll.SetValues (0, Math.Max (1, document.Height), -1,
2130 document.ViewPortHeight < 0 ? 0 : document.ViewPortHeight);
2131 if (document.multiline)
2132 vscroll.Enabled = true;
2134 vscroll.Enabled = false;
2135 vscroll.Maximum = document.ViewPortHeight;
2139 switch (scrollbars) {
2140 case RichTextBoxScrollBars.Both:
2141 case RichTextBoxScrollBars.Horizontal:
2143 hscroll.Visible = hscroll.Enabled;
2145 hscroll.Visible = this.Multiline;
2147 case RichTextBoxScrollBars.ForcedBoth:
2148 case RichTextBoxScrollBars.ForcedHorizontal:
2149 hscroll.Visible = true;
2152 hscroll.Visible = false;
2156 hscroll.Visible = false;
2159 switch (scrollbars) {
2160 case RichTextBoxScrollBars.Both:
2161 case RichTextBoxScrollBars.Vertical:
2163 vscroll.Visible = vscroll.Enabled;
2165 vscroll.Visible = this.Multiline;
2167 case RichTextBoxScrollBars.ForcedBoth:
2168 case RichTextBoxScrollBars.ForcedVertical:
2169 vscroll.Visible = true;
2172 vscroll.Visible = false;
2176 PositionControls ();
2178 SizeControls (); //Update sizings now we've decided whats visible
2181 private void document_WidthChanged (object sender, EventArgs e)
2183 CalculateScrollBars();
2186 private void document_HeightChanged (object sender, EventArgs e)
2188 CalculateScrollBars();
2191 private void ScrollLinks (int xChange, int yChange)
2193 foreach (LinkRectangle link in list_links)
2194 link.Scroll (xChange, yChange);
2197 private void hscroll_ValueChanged (object sender, EventArgs e)
2201 old_viewport_x = document.ViewPortX;
2202 document.ViewPortX = this.hscroll.Value;
2205 // Before scrolling we want to destroy the caret, then draw a new one after the scroll
2206 // the reason for this is that scrolling changes the coordinates of the caret, and we
2207 // will get tracers if we don't
2210 document.CaretLostFocus ();
2212 if (vscroll.Visible) {
2213 if (GetInheritedRtoL () == RightToLeft.Yes) {
2214 XplatUI.ScrollWindow (this.Handle, new Rectangle (vscroll.Width, 0, ClientSize.Width - vscroll.Width, ClientSize.Height), old_viewport_x - this.hscroll.Value, 0, false);
2216 XplatUI.ScrollWindow (this.Handle, new Rectangle (0, 0, ClientSize.Width - vscroll.Width, ClientSize.Height), old_viewport_x - this.hscroll.Value, 0, false);
2219 XplatUI.ScrollWindow(this.Handle, ClientRectangle, old_viewport_x - this.hscroll.Value, 0, false);
2222 ScrollLinks (old_viewport_x - this.hscroll.Value, 0);
2225 document.CaretHasFocus ();
2227 EventHandler eh = (EventHandler)(Events [HScrolledEvent]);
2229 eh (this, EventArgs.Empty);
2232 private void vscroll_ValueChanged (object sender, EventArgs e)
2236 old_viewport_y = document.ViewPortY;
2237 document.ViewPortY = this.vscroll.Value;
2240 // Before scrolling we want to destroy the caret, then draw a new one after the scroll
2241 // the reason for this is that scrolling changes the coordinates of the caret, and we
2242 // will get tracers if we don't
2245 document.CaretLostFocus ();
2247 if (hscroll.Visible) {
2248 XplatUI.ScrollWindow(this.Handle, new Rectangle(0, 0, ClientSize.Width, ClientSize.Height - hscroll.Height), 0, old_viewport_y - this.vscroll.Value, false);
2250 XplatUI.ScrollWindow(this.Handle, ClientRectangle, 0, old_viewport_y - this.vscroll.Value, false);
2253 ScrollLinks (0, old_viewport_y - this.vscroll.Value);
2256 document.CaretHasFocus ();
2258 EventHandler eh = (EventHandler)(Events [VScrolledEvent]);
2260 eh (this, EventArgs.Empty);
2263 private void TextBoxBase_MouseMove (object sender, MouseEventArgs e)
2265 // FIXME - handle auto-scrolling if mouse is to the right/left of the window
2266 if (e.Button == MouseButtons.Left && Capture) {
2267 if (!ClientRectangle.Contains (e.X, e.Y)) {
2268 if (scroll_timer == null) {
2269 scroll_timer = new Timer ();
2270 scroll_timer.Interval = 100;
2271 scroll_timer.Tick += new EventHandler (ScrollTimerTickHandler);
2274 if (!scroll_timer.Enabled) {
2275 scroll_timer.Start ();
2277 // Force the first tick
2278 ScrollTimerTickHandler (null, EventArgs.Empty);
2282 document.PositionCaret(e.X + document.ViewPortX, e.Y + document.ViewPortY);
2283 if (click_mode == CaretSelection.Position) {
2284 document.SetSelectionToCaret(false);
2285 document.DisplayCaret();
2289 //search through link boxes to see if the mouse is over one of them
2291 bool found_link = false;
2292 foreach (LinkRectangle link in list_links) {
2293 if (link.LinkAreaRectangle.Contains (e.X, e.Y)) {
2294 XplatUI.SetCursor (window.Handle, Cursors.Hand.handle);
2297 current_link = link;
2302 if (found_link == false) {
2304 XplatUI.SetCursor (window.Handle, DefaultCursor.handle);
2306 XplatUI.SetCursor(window.Handle, Cursors.IBeam.handle);
2308 current_link = null;
2312 private void TextBoxBase_FontOrColorChanged (object sender, EventArgs e)
2316 document.SuspendRecalc ();
2317 // Font changes apply to the whole document
2318 for (int i = 1; i <= document.Lines; i++) {
2319 line = document.GetLine(i);
2320 if (LineTag.FormatText(line, 1, line.text.Length, Font, ForeColor,
2321 Color.Empty, FormatSpecified.Font | FormatSpecified.Color))
2322 document.RecalculateDocument (CreateGraphicsInternal (), line.LineNo, line.LineNo, false);
2324 document.ResumeRecalc (false);
2326 // Make sure the caret height is matching the new font height
2327 document.AlignCaret();
2330 private void ScrollTimerTickHandler (object sender, EventArgs e)
2332 Point pt = Cursor.Position;
2334 pt = PointToClient (pt);
2336 if (pt.X < ClientRectangle.Left) {
2337 document.MoveCaret(CaretDirection.CharBackNoWrap);
2338 document.SetSelectionToCaret(false);
2340 CaretMoved(this, null);
2341 } else if (pt.X > ClientRectangle.Right) {
2342 document.MoveCaret(CaretDirection.CharForwardNoWrap);
2343 document.SetSelectionToCaret(false);
2345 CaretMoved(this, null);
2346 } else if (pt.Y > ClientRectangle.Bottom) {
2347 document.MoveCaret(CaretDirection.LineDown);
2348 document.SetSelectionToCaret(false);
2350 CaretMoved(this, null);
2351 } else if (pt.Y < ClientRectangle.Top) {
2352 document.MoveCaret(CaretDirection.LineUp);
2353 document.SetSelectionToCaret(false);
2355 CaretMoved(this, null);
2359 /// <summary>Ensure the caret is always visible</summary>
2360 internal void CaretMoved (object sender, EventArgs e)
2365 if (!IsHandleCreated || canvas_width < 1 || canvas_height < 1)
2368 document.MoveCaretToTextTag ();
2369 pos = document.Caret;
2371 //Console.WriteLine("Caret now at {0} (Thumb: {1}x{2}, Canvas: {3}x{4}, Document {5}x{6})", pos, hscroll.Value, vscroll.Value, canvas_width, canvas_height, document.Width, document.Height);
2374 // Horizontal scrolling:
2375 // If the caret moves to the left outside the visible area, we jump the document into view, not just one
2376 // character, but 1/3 of the width of the document
2377 // If the caret moves to the right outside the visible area, we scroll just enough to keep the caret visible
2379 // Handle horizontal scrolling
2380 if (document.CaretLine.alignment == HorizontalAlignment.Left) {
2381 // Check if we moved out of view to the left
2382 if (pos.X < (document.ViewPortX)) {
2384 if ((hscroll.Value - document.ViewPortWidth / 3) >= hscroll.Minimum) {
2385 hscroll.SafeValueSet (hscroll.Value - document.ViewPortWidth / 3);
2387 hscroll.Value = hscroll.Minimum;
2389 } while (hscroll.Value > pos.X);
2392 // Check if we moved out of view to the right
2393 if ((pos.X >= (document.ViewPortWidth + document.ViewPortX)) && (hscroll.Value != hscroll.Maximum)) {
2394 if ((pos.X - document.ViewPortWidth + 1) <= hscroll.Maximum) {
2395 if (pos.X - document.ViewPortWidth >= 0) {
2396 hscroll.SafeValueSet (pos.X - document.ViewPortWidth + 1);
2401 hscroll.Value = hscroll.Maximum;
2404 } else if (document.CaretLine.alignment == HorizontalAlignment.Right) {
2405 // hscroll.Value = pos.X;
2407 // if ((pos.X > (this.canvas_width + document.ViewPortX)) && (hscroll.Enabled && (hscroll.Value != hscroll.Maximum))) {
2408 // hscroll.Value = hscroll.Maximum;
2411 // FIXME - implement center cursor alignment
2414 if (Text.Length > 0)
2415 RaiseSelectionChanged ();
2417 if (!document.multiline)
2420 // Handle vertical scrolling
2421 height = document.CaretLine.Height + 1;
2423 if (pos.Y < document.ViewPortY)
2424 vscroll.SafeValueSet (pos.Y);
2425 if ((pos.Y + height) > (document.ViewPortY + canvas_height))
2426 vscroll.Value = Math.Min (vscroll.Maximum, pos.Y - canvas_height + height);
2429 internal bool Paste (IDataObject clip, DataFormats.Format format, bool obey_length)
2436 if (format == null) {
2437 if ((this is RichTextBox) && clip.GetDataPresent(DataFormats.Rtf)) {
2438 format = DataFormats.GetFormat(DataFormats.Rtf);
2439 } else if ((this is RichTextBox) && clip.GetDataPresent (DataFormats.Bitmap)) {
2440 format = DataFormats.GetFormat (DataFormats.Bitmap);
2441 } else if (clip.GetDataPresent(DataFormats.UnicodeText)) {
2442 format = DataFormats.GetFormat(DataFormats.UnicodeText);
2443 } else if (clip.GetDataPresent(DataFormats.Text)) {
2444 format = DataFormats.GetFormat(DataFormats.Text);
2449 if ((format.Name == DataFormats.Rtf) && !(this is RichTextBox)) {
2453 if (!clip.GetDataPresent(format.Name)) {
2458 if (format.Name == DataFormats.Rtf) {
2459 document.undo.BeginUserAction (Locale.GetText ("Paste"));
2460 ((RichTextBox)this).SelectedRtf = (string)clip.GetData(DataFormats.Rtf);
2461 document.undo.EndUserAction ();
2464 } else if (format.Name == DataFormats.Bitmap) {
2465 document.undo.BeginUserAction (Locale.GetText ("Paste"));
2466 // document.InsertImage (document.caret.line, document.caret.pos, (Image) clip.GetData (DataFormats.Bitmap));
2467 document.MoveCaret (CaretDirection.CharForward);
2468 document.undo.EndUserAction ();
2470 } else if (format.Name == DataFormats.UnicodeText) {
2471 s = (string)clip.GetData(DataFormats.UnicodeText);
2472 } else if (format.Name == DataFormats.Text) {
2473 s = (string)clip.GetData(DataFormats.Text);
2479 document.undo.BeginUserAction (Locale.GetText ("Paste"));
2480 this.SelectedText = s;
2481 document.undo.EndUserAction ();
2483 if ((s.Length + (document.Length - SelectedText.Length)) < max_length) {
2484 document.undo.BeginUserAction (Locale.GetText ("Paste"));
2485 this.SelectedText = s;
2486 document.undo.EndUserAction ();
2487 } else if ((document.Length - SelectedText.Length) < max_length) {
2488 document.undo.BeginUserAction (Locale.GetText ("Paste"));
2489 this.SelectedText = s.Substring (0, max_length - (document.Length - SelectedText.Length));
2490 document.undo.EndUserAction ();
2498 internal virtual Color ChangeBackColor (Color backColor)
2503 internal override bool IsInputCharInternal (char charCode)
2507 #endregion // Private Methods
2509 #region Private Classes
2510 internal class LinkRectangle {
2511 private Rectangle link_area_rectangle;
2512 private LineTag link_tag;
2514 public LinkRectangle (Rectangle rect)
2517 link_area_rectangle = rect;
2520 public Rectangle LinkAreaRectangle {
2521 get { return link_area_rectangle; }
2522 set { link_area_rectangle = value; }
2525 public LineTag LinkTag {
2526 get { return link_tag; }
2527 set { link_tag = value; }
2530 public void Scroll (int x_change, int y_change)
2532 link_area_rectangle.X += x_change;
2533 link_area_rectangle.Y += y_change;
2539 // This is called just before OnTextChanged is called.
2540 internal virtual void OnTextUpdate ()
2544 protected override void OnTextChanged (EventArgs e)
2546 base.OnTextChanged (e);
2549 public virtual int GetLineFromCharIndex (int index)
2555 document.CharIndexToLineTag (index, out line_out, out tag_out, out pos);
2557 return line_out.LineNo;
2560 protected override void OnMouseUp (MouseEventArgs mevent)
2562 base.OnMouseUp (mevent);