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:
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) 2005-2006 Novell, Inc. (http://www.novell.com)
23 // Peter Bartok <pbartok@novell.com>
30 using System.Collections;
31 using System.ComponentModel;
33 using System.Drawing.Imaging;
36 using System.Runtime.InteropServices;
37 using RTF=System.Windows.Forms.RTF;
39 namespace System.Windows.Forms {
41 [ClassInterface (ClassInterfaceType.AutoDispatch)]
42 [Docking (DockingBehavior.Ask)]
44 [Designer ("System.Windows.Forms.Design.RichTextBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
46 public class RichTextBox : TextBoxBase {
47 #region Local Variables
48 internal bool auto_word_select;
49 internal int bullet_indent;
50 internal bool detect_urls;
51 internal int margin_right;
53 private StringBuilder rtf_line;
55 private RtfSectionStyle rtf_style; // Replaces individual style
56 // properties so we can revert
57 private Stack rtf_section_stack;
59 private RTF.TextMap rtf_text_map;
60 private int rtf_skip_width;
61 private int rtf_skip_count;
62 private int rtf_cursor_x;
63 private int rtf_cursor_y;
64 private int rtf_chars;
67 private bool enable_auto_drag_drop;
68 private RichTextBoxLanguageOptions language_option;
69 private bool rich_text_shortcuts_enabled;
70 private Color selection_back_color;
72 #endregion // Local Variables
74 #region Public Constructors
75 public RichTextBox() {
76 accepts_return = true;
77 auto_word_select = false;
79 max_length = Int32.MaxValue;
82 base.Multiline = true;
83 document.CRLFSize = 1;
84 shortcuts_enabled = true;
85 base.EnableLinks = true;
87 rtf_style = new RtfSectionStyle ();
88 rtf_section_stack = null;
90 scrollbars = RichTextBoxScrollBars.Both;
91 alignment = HorizontalAlignment.Left;
92 LostFocus += new EventHandler(RichTextBox_LostFocus);
93 GotFocus += new EventHandler(RichTextBox_GotFocus);
94 BackColor = ThemeEngine.Current.ColorWindow;
96 backcolor_set = false;
97 language_option = RichTextBoxLanguageOptions.AutoFontSizeAdjust;
98 rich_text_shortcuts_enabled = true;
99 selection_back_color = DefaultBackColor;
101 ForeColor = ThemeEngine.Current.ColorWindowText;
103 base.HScrolled += new EventHandler(RichTextBox_HScrolled);
104 base.VScrolled += new EventHandler(RichTextBox_VScrolled);
107 SetStyle (ControlStyles.StandardDoubleClick, false);
110 #endregion // Public Constructors
112 #region Private & Internal Methods
114 internal override void HandleLinkClicked (LinkRectangle link)
116 OnLinkClicked (new LinkClickedEventArgs (link.LinkTag.LinkText));
119 internal override Color ChangeBackColor (Color backColor)
121 if (backColor == Color.Empty) {
123 backcolor_set = false;
125 backColor = SystemColors.Window;
128 backColor = SystemColors.Window;
134 private void RichTextBox_LostFocus(object sender, EventArgs e) {
138 private void RichTextBox_GotFocus(object sender, EventArgs e) {
141 #endregion // Private & Internal Methods
143 #region Public Instance Properties
147 public override bool AllowDrop {
149 return base.AllowDrop;
153 base.AllowDrop = value;
157 [DefaultValue(false)]
159 [DesignerSerializationVisibility (DesignerSerializationVisibility.Visible)]
160 [RefreshProperties (RefreshProperties.Repaint)]
161 [EditorBrowsable (EditorBrowsableState.Never)]
166 public override bool AutoSize {
172 base.AutoSize = value;
176 [DefaultValue(false)]
177 public bool AutoWordSelection {
179 return auto_word_select;
183 auto_word_select = true;
188 [EditorBrowsable(EditorBrowsableState.Never)]
189 public override System.Drawing.Image BackgroundImage {
190 get { return base.BackgroundImage; }
191 set { base.BackgroundImage = value; }
196 [EditorBrowsable (EditorBrowsableState.Never)]
197 public override ImageLayout BackgroundImageLayout {
198 get { return base.BackgroundImageLayout; }
199 set { base.BackgroundImageLayout = value; }
205 public int BulletIndent {
207 return bullet_indent;
211 bullet_indent = value;
216 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
217 public bool CanRedo {
219 return document.undo.CanRedo;
224 public bool DetectUrls {
225 get { return base.EnableLinks; }
226 set { base.EnableLinks = value; }
231 [DefaultValue (false)]
232 public bool EnableAutoDragDrop {
233 get { return enable_auto_drag_drop; }
234 set { enable_auto_drag_drop = value; }
238 public override Font Font {
249 if (PreferredHeight != Height) {
250 Height = PreferredHeight;
256 // Font changes always set the whole doc to that font
257 start = document.GetLine(1);
258 end = document.GetLine(document.Lines);
259 document.FormatText(start, 1, end, end.text.Length + 1, base.Font, Color.Empty, Color.Empty, FormatSpecified.Font);
264 public override Color ForeColor {
266 return base.ForeColor;
270 base.ForeColor = value;
277 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
278 public RichTextBoxLanguageOptions LanguageOption {
279 get { return language_option; }
280 set { language_option = value; }
284 [DefaultValue(Int32.MaxValue)]
285 public override int MaxLength {
287 return base.max_length;
291 base.max_length = value;
296 public override bool Multiline {
298 return base.Multiline;
302 base.Multiline = value;
307 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
309 public string RedoActionName {
311 return document.undo.RedoActionName;
318 [DefaultValue (true)]
319 [EditorBrowsable (EditorBrowsableState.Never)]
320 public bool RichTextShortcutsEnabled {
321 get { return rich_text_shortcuts_enabled; }
322 set { rich_text_shortcuts_enabled = value; }
328 [MonoTODO("Teach TextControl.RecalculateLine to consider the right margin as well")]
329 public int RightMargin {
335 margin_right = value;
340 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
342 [RefreshProperties (RefreshProperties.All)]
351 start_line = document.GetLine(1);
352 end_line = document.GetLine(document.Lines);
353 return GenerateRTF(start_line, 0, end_line, end_line.text.Length).ToString();
360 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
362 InsertRTFFromStream(data, 0, 1);
370 [DefaultValue(RichTextBoxScrollBars.Both)]
372 public RichTextBoxScrollBars ScrollBars {
378 if (!Enum.IsDefined (typeof (RichTextBoxScrollBars), value))
379 throw new InvalidEnumArgumentException ("value", (int) value,
380 typeof (RichTextBoxScrollBars));
382 if (value != scrollbars) {
384 CalculateDocument ();
391 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
392 public string SelectedRtf {
394 return GenerateRTF(document.selection_start.line, document.selection_start.pos, document.selection_end.line, document.selection_end.pos).ToString();
406 if (document.selection_visible) {
407 document.ReplaceSelection("", false);
410 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
412 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
413 InsertRTFFromStream(data, document.selection_start.pos, document.selection_start.line.line_no, out x, out y, out chars);
416 document.CharIndexToLineTag(sel_start + chars + (y - document.selection_start.line.line_no) * 2, out line, out tag, out sel_start);
417 document.SetSelection(line, sel_start);
418 document.PositionCaret(line, sel_start);
419 document.DisplayCaret();
421 OnTextChanged(EventArgs.Empty);
427 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
428 public override string SelectedText {
430 return base.SelectedText;
434 base.SelectedText = value;
439 [DefaultValue(HorizontalAlignment.Left)]
440 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
441 public HorizontalAlignment SelectionAlignment {
443 HorizontalAlignment align;
448 start = document.ParagraphStart(document.selection_start.line);
449 align = start.alignment;
451 end = document.ParagraphEnd(document.selection_end.line);
456 if (line.alignment != align) {
457 return HorizontalAlignment.Left;
463 line = document.GetLine(line.line_no + 1);
474 start = document.ParagraphStart(document.selection_start.line);
476 end = document.ParagraphEnd(document.selection_end.line);
481 line.alignment = value;
486 line = document.GetLine(line.line_no + 1);
488 this.CalculateDocument();
495 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
496 public Color SelectionBackColor {
497 get { return selection_back_color; }
498 set { selection_back_color = value; }
503 [DefaultValue(false)]
504 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
506 public bool SelectionBullet {
517 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
519 public int SelectionCharOffset {
529 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
530 public Color SelectionColor {
537 if (selection_length > 0) {
538 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
539 end = document.selection_start.line.FindTag (document.selection_end.pos);
541 start = document.selection_start.line.FindTag (document.selection_start.pos);
548 while (tag != null) {
550 if (!color.Equals (tag.Color))
556 tag = document.NextTag (tag);
563 if (value == Color.Empty)
564 value = DefaultForeColor;
569 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
570 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
572 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
573 document.selection_end.line, document.selection_end.pos + 1, null,
574 value, Color.Empty, FormatSpecified.Color);
576 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
577 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
579 document.UpdateView(document.selection_start.line, 0);
581 //Re-Align the caret in case its changed size or position
582 //probably not necessary here
583 document.AlignCaret(false);
588 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
589 public Font SelectionFont {
596 if (selection_length > 0) {
597 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
598 end = document.selection_start.line.FindTag (document.selection_end.pos);
600 start = document.selection_start.line.FindTag (document.selection_start.pos);
606 if (selection_length > 1) {
608 while (tag != null) {
610 if (!font.Equals(tag.Font))
616 tag = document.NextTag (tag);
627 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
628 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
630 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
631 document.selection_end.line, document.selection_end.pos + 1, value,
632 Color.Empty, Color.Empty, FormatSpecified.Font);
634 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
635 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
637 document.UpdateView(document.selection_start.line, 0);
638 //Re-Align the caret in case its changed size or position
639 Document.AlignCaret (false);
646 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
648 public int SelectionHangingIndent {
659 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
661 public int SelectionIndent {
671 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
672 public override int SelectionLength {
674 return base.SelectionLength;
678 base.SelectionLength = value;
683 [DefaultValue(false)]
684 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
686 public bool SelectionProtected {
697 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
699 public int SelectionRightIndent {
709 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
711 public int[] SelectionTabs {
721 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
722 public RichTextBoxSelectionTypes SelectionType {
724 if (document.selection_start == document.selection_end) {
725 return RichTextBoxSelectionTypes.Empty;
729 if (SelectedText.Length > 1) {
730 return RichTextBoxSelectionTypes.MultiChar | RichTextBoxSelectionTypes.Text;
733 return RichTextBoxSelectionTypes.Text;
737 [DefaultValue(false)]
739 public bool ShowSelectionMargin {
750 [RefreshProperties (RefreshProperties.All)]
752 public override string Text {
763 public override int TextLength {
765 return base.TextLength;
770 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
771 public string UndoActionName {
773 return document.undo.UndoActionName;
779 public float ZoomFactor {
788 #endregion // Public Instance Properties
790 #region Protected Instance Properties
791 protected override CreateParams CreateParams {
793 return base.CreateParams;
797 protected override Size DefaultSize {
799 return new Size(100, 96);
802 #endregion // Protected Instance Properties
804 #region Public Instance Methods
805 public bool CanPaste(DataFormats.Format clipFormat) {
806 if ((clipFormat.Name == DataFormats.Rtf) ||
807 (clipFormat.Name == DataFormats.Text) ||
808 (clipFormat.Name == DataFormats.UnicodeText)) {
814 public int Find(char[] characterSet) {
815 return Find(characterSet, -1, -1);
818 public int Find(char[] characterSet, int start) {
819 return Find(characterSet, start, -1);
822 public int Find(char[] characterSet, int start, int end) {
823 Document.Marker start_mark;
824 Document.Marker end_mark;
825 Document.Marker result;
828 document.GetMarker(out start_mark, true);
834 start_mark = new Document.Marker();
836 document.CharIndexToLineTag(start, out line, out tag, out pos);
837 start_mark.line = line;
838 start_mark.tag = tag;
839 start_mark.pos = pos;
843 document.GetMarker(out end_mark, false);
849 end_mark = new Document.Marker();
851 document.CharIndexToLineTag(end, out line, out tag, out pos);
852 end_mark.line = line;
857 if (document.FindChars(characterSet, start_mark, end_mark, out result)) {
858 return document.LineTagToCharIndex(result.line, result.pos);
864 public int Find(string str) {
865 return Find(str, -1, -1, RichTextBoxFinds.None);
868 public int Find(string str, int start, int end, RichTextBoxFinds options) {
869 Document.Marker start_mark;
870 Document.Marker end_mark;
871 Document.Marker result;
874 document.GetMarker(out start_mark, true);
880 start_mark = new Document.Marker();
882 document.CharIndexToLineTag(start, out line, out tag, out pos);
884 start_mark.line = line;
885 start_mark.tag = tag;
886 start_mark.pos = pos;
890 document.GetMarker(out end_mark, false);
896 end_mark = new Document.Marker();
898 document.CharIndexToLineTag(end, out line, out tag, out pos);
900 end_mark.line = line;
905 if (document.Find(str, start_mark, end_mark, out result, options)) {
906 return document.LineTagToCharIndex(result.line, result.pos);
912 public int Find(string str, int start, RichTextBoxFinds options) {
913 return Find(str, start, -1, options);
916 public int Find(string str, RichTextBoxFinds options) {
917 return Find(str, -1, -1, options);
922 public char GetCharFromPosition(Point pt) {
926 PointToTagPos(pt, out tag, out pos);
928 if (pos >= tag.Line.text.Length) {
932 return tag.Line.text[pos];
935 internal override char GetCharFromPositionInternal (Point p)
940 PointToTagPos (p, out tag, out pos);
942 if (pos >= tag.Line.text.Length)
945 return tag.Line.text[pos];
953 int GetCharIndexFromPosition(Point pt) {
957 PointToTagPos(pt, out tag, out pos);
959 return document.LineTagToCharIndex(tag.Line, pos);
966 int GetLineFromCharIndex(int index) {
971 document.CharIndexToLineTag(index, out line, out tag, out pos);
973 return line.LineNo - 1;
980 Point GetPositionFromCharIndex(int index) {
985 document.CharIndexToLineTag(index, out line, out tag, out pos);
987 return new Point((int)line.widths[pos] + 1, line.Y + 1);
990 public void LoadFile(System.IO.Stream data, RichTextBoxStreamType fileType) {
994 // FIXME - ignoring unicode
995 if (fileType == RichTextBoxStreamType.PlainText) {
1000 sb = new StringBuilder ((int) data.Length);
1001 buffer = new char [1024];
1003 throw new IOException("Not enough memory to load document");
1006 StreamReader sr = new StreamReader (data, Encoding.Default, true);
1007 int charsRead = sr.Read (buffer, 0, buffer.Length);
1008 while (charsRead > 0) {
1009 sb.Append (buffer, 0, charsRead);
1010 charsRead = sr.Read (buffer, 0, buffer.Length);
1012 base.Text = sb.ToString();
1016 InsertRTFFromStream(data, 0, 1);
1018 document.PositionCaret (document.GetLine (1), 0);
1019 document.SetSelectionToCaret (true);
1023 [MonoTODO("Make smarter RTF detection?")]
1024 public void LoadFile(string path) {
1025 if (path.EndsWith(".rtf")) {
1026 LoadFile(path, RichTextBoxStreamType.RichText);
1028 LoadFile(path, RichTextBoxStreamType.PlainText);
1032 public void LoadFile(string path, RichTextBoxStreamType fileType) {
1039 data = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024);
1041 LoadFile(data, fileType);
1044 catch (Exception ex) {
1045 throw new IOException("Could not open file " + path, ex);
1055 public void Paste(DataFormats.Format clipFormat) {
1056 base.Paste(Clipboard.GetDataObject(), clipFormat, false);
1061 document.undo.Redo ();
1064 public void SaveFile(Stream data, RichTextBoxStreamType fileType) {
1070 if (fileType == RichTextBoxStreamType.UnicodePlainText) {
1071 encoding = Encoding.Unicode;
1073 encoding = Encoding.ASCII;
1077 case RichTextBoxStreamType.PlainText:
1078 case RichTextBoxStreamType.TextTextOleObjs:
1079 case RichTextBoxStreamType.UnicodePlainText: {
1081 bytes = encoding.GetBytes(document.Root.text.ToString());
1082 data.Write(bytes, 0, bytes.Length);
1086 for (i = 1; i < document.Lines; i++) {
1087 bytes = encoding.GetBytes(document.GetLine(i).text.ToString() + Environment.NewLine);
1088 data.Write(bytes, 0, bytes.Length);
1090 bytes = encoding.GetBytes(document.GetLine(document.Lines).text.ToString());
1091 data.Write(bytes, 0, bytes.Length);
1096 // If we're here we're saving RTF
1103 start_line = document.GetLine(1);
1104 end_line = document.GetLine(document.Lines);
1105 rtf = GenerateRTF(start_line, 0, end_line, end_line.text.Length);
1107 bytes = new Byte[4096];
1109 // Let's chunk it so we don't use up all memory...
1110 for (i = 0; i < total; i += 1024) {
1111 if ((i + 1024) < total) {
1112 current = encoding.GetBytes(rtf.ToString(i, 1024), 0, 1024, bytes, 0);
1114 current = total - i;
1115 current = encoding.GetBytes(rtf.ToString(i, current), 0, current, bytes, 0);
1117 data.Write(bytes, 0, current);
1121 public void SaveFile(string path) {
1122 if (path.EndsWith(".rtf")) {
1123 SaveFile(path, RichTextBoxStreamType.RichText);
1125 SaveFile(path, RichTextBoxStreamType.PlainText);
1129 public void SaveFile(string path, RichTextBoxStreamType fileType) {
1135 data = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1024, false);
1136 SaveFile(data, fileType);
1140 // throw new IOException("Could not write document to file " + path);
1151 [EditorBrowsable (EditorBrowsableState.Never)]
1152 public new void DrawToBitmap (Bitmap bitmap, Rectangle clip)
1154 Graphics dc = Graphics.FromImage (bitmap);
1156 if (backcolor_set || (Enabled && !read_only)) {
1157 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), clip);
1159 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (ThemeEngine.Current.ColorControl), clip);
1162 // Draw the viewable document
1163 document.Draw (dc, clip);
1167 #endregion // Public Instance Methods
1169 #region Protected Instance Methods
1170 protected virtual object CreateRichEditOleCallback() {
1171 throw new NotImplementedException();
1174 protected override void OnBackColorChanged(EventArgs e) {
1175 base.OnBackColorChanged (e);
1178 protected virtual void OnContentsResized(ContentsResizedEventArgs e) {
1179 ContentsResizedEventHandler eh = (ContentsResizedEventHandler)(Events [ContentsResizedEvent]);
1184 protected override void OnContextMenuChanged(EventArgs e) {
1185 base.OnContextMenuChanged (e);
1188 protected override void OnHandleCreated(EventArgs e) {
1189 base.OnHandleCreated (e);
1192 protected override void OnHandleDestroyed(EventArgs e) {
1193 base.OnHandleDestroyed (e);
1196 protected virtual void OnHScroll(EventArgs e) {
1197 EventHandler eh = (EventHandler)(Events [HScrollEvent]);
1202 [MonoTODO("Determine when to call this")]
1203 protected virtual void OnImeChange(EventArgs e) {
1204 EventHandler eh = (EventHandler)(Events [ImeChangeEvent]);
1209 protected virtual void OnLinkClicked(LinkClickedEventArgs e) {
1210 LinkClickedEventHandler eh = (LinkClickedEventHandler)(Events [LinkClickedEvent]);
1215 protected virtual void OnProtected(EventArgs e) {
1216 EventHandler eh = (EventHandler)(Events [ProtectedEvent]);
1221 protected override void OnRightToLeftChanged(EventArgs e) {
1222 base.OnRightToLeftChanged (e);
1225 protected virtual void OnSelectionChanged(EventArgs e) {
1226 EventHandler eh = (EventHandler)(Events [SelectionChangedEvent]);
1232 protected override void OnSystemColorsChanged(EventArgs e) {
1233 base.OnSystemColorsChanged (e);
1236 protected override void OnTextChanged(EventArgs e) {
1237 base.OnTextChanged (e);
1241 protected virtual void OnVScroll(EventArgs e) {
1242 EventHandler eh = (EventHandler)(Events [VScrollEvent]);
1247 protected override void WndProc(ref Message m) {
1248 base.WndProc (ref m);
1252 protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
1254 return base.ProcessCmdKey (ref msg, keyData);
1257 #endregion // Protected Instance Methods
1260 static object ContentsResizedEvent = new object ();
1261 static object HScrollEvent = new object ();
1262 static object ImeChangeEvent = new object ();
1263 static object LinkClickedEvent = new object ();
1264 static object ProtectedEvent = new object ();
1265 static object SelectionChangedEvent = new object ();
1266 static object VScrollEvent = new object ();
1269 [EditorBrowsable(EditorBrowsableState.Never)]
1270 public new event EventHandler BackgroundImageChanged {
1271 add { base.BackgroundImageChanged += value; }
1272 remove { base.BackgroundImageChanged -= value; }
1277 [EditorBrowsable (EditorBrowsableState.Never)]
1278 public new event EventHandler BackgroundImageLayoutChanged {
1279 add { base.BackgroundImageLayoutChanged += value; }
1280 remove { base.BackgroundImageLayoutChanged -= value; }
1284 public event ContentsResizedEventHandler ContentsResized {
1285 add { Events.AddHandler (ContentsResizedEvent, value); }
1286 remove { Events.RemoveHandler (ContentsResizedEvent, value); }
1291 [EditorBrowsable(EditorBrowsableState.Never)]
1292 public new event EventHandler DoubleClick {
1293 add { base.DoubleClick += value; }
1294 remove { base.DoubleClick -= value; }
1300 [EditorBrowsable(EditorBrowsableState.Never)]
1302 public new event DragEventHandler DragDrop {
1303 add { base.DragDrop += value; }
1304 remove { base.DragDrop -= value; }
1309 [EditorBrowsable(EditorBrowsableState.Never)]
1311 public new event DragEventHandler DragEnter {
1312 add { base.DragEnter += value; }
1313 remove { base.DragEnter -= value; }
1317 [EditorBrowsable(EditorBrowsableState.Never)]
1318 public new event EventHandler DragLeave {
1319 add { base.DragLeave += value; }
1320 remove { base.DragLeave -= value; }
1325 [EditorBrowsable(EditorBrowsableState.Never)]
1326 public new event DragEventHandler DragOver {
1327 add { base.DragOver += value; }
1328 remove { base.DragOver -= value; }
1333 [EditorBrowsable(EditorBrowsableState.Never)]
1334 public new event GiveFeedbackEventHandler GiveFeedback {
1335 add { base.GiveFeedback += value; }
1336 remove { base.GiveFeedback -= value; }
1339 public event EventHandler HScroll {
1340 add { Events.AddHandler (HScrollEvent, value); }
1341 remove { Events.RemoveHandler (HScrollEvent, value); }
1344 public event EventHandler ImeChange {
1345 add { Events.AddHandler (ImeChangeEvent, value); }
1346 remove { Events.RemoveHandler (ImeChangeEvent, value); }
1349 public event LinkClickedEventHandler LinkClicked {
1350 add { Events.AddHandler (LinkClickedEvent, value); }
1351 remove { Events.RemoveHandler (LinkClickedEvent, value); }
1354 public event EventHandler Protected {
1355 add { Events.AddHandler (ProtectedEvent, value); }
1356 remove { Events.RemoveHandler (ProtectedEvent, value); }
1360 [EditorBrowsable(EditorBrowsableState.Never)]
1361 public new event QueryContinueDragEventHandler QueryContinueDrag {
1362 add { base.QueryContinueDrag += value; }
1363 remove { base.QueryContinueDrag -= value; }
1366 public event EventHandler SelectionChanged {
1367 add { Events.AddHandler (SelectionChangedEvent, value); }
1368 remove { Events.RemoveHandler (SelectionChangedEvent, value); }
1371 public event EventHandler VScroll {
1372 add { Events.AddHandler (VScrollEvent, value); }
1373 remove { Events.RemoveHandler (VScrollEvent, value); }
1375 #endregion // Events
1377 #region Private Methods
1379 internal override void SelectWord ()
1381 document.ExpandSelection(CaretSelection.Word, false);
1384 private class RtfSectionStyle : ICloneable {
1385 internal Color rtf_color;
1386 internal RTF.Font rtf_rtffont;
1387 internal int rtf_rtffont_size;
1388 internal FontStyle rtf_rtfstyle;
1389 internal HorizontalAlignment rtf_rtfalign;
1390 internal int rtf_par_line_left_indent;
1392 public object Clone ()
1394 RtfSectionStyle new_style = new RtfSectionStyle ();
1396 new_style.rtf_color = rtf_color;
1397 new_style.rtf_par_line_left_indent = rtf_par_line_left_indent;
1398 new_style.rtf_rtfalign = rtf_rtfalign;
1399 new_style.rtf_rtffont = rtf_rtffont;
1400 new_style.rtf_rtffont_size = rtf_rtffont_size;
1401 new_style.rtf_rtfstyle = rtf_rtfstyle;
1407 // To allow us to keep track of the sections and revert formatting
1408 // as we go in and out of sections of the document.
1409 private void HandleGroup (RTF.RTF rtf)
1411 //start group - save the current formatting on to a stack
1412 //end group - go back to the formatting at the current group
1413 if (rtf_section_stack == null) {
1414 rtf_section_stack = new Stack ();
1417 if (rtf.Major == RTF.Major.BeginGroup) {
1418 rtf_section_stack.Push (rtf_style.Clone ());
1419 } else if (rtf.Major == RTF.Major.EndGroup) {
1420 if (rtf_section_stack.Count > 0) {
1421 FlushText (rtf, false);
1423 rtf_style = (RtfSectionStyle) rtf_section_stack.Pop ();
1428 [MonoTODO("Add QuadJust support for justified alignment")]
1429 private void HandleControl(RTF.RTF rtf) {
1431 case RTF.Major.Unicode: {
1433 case RTF.Minor.UnicodeCharBytes: {
1434 rtf_skip_width = rtf.Param;
1438 case RTF.Minor.UnicodeChar: {
1439 rtf_skip_count += rtf_skip_width;
1440 rtf_line.Append((char)rtf.Param);
1447 case RTF.Major.Destination: {
1448 // Console.Write("[Got Destination control {0}]", rtf.Minor);
1453 case RTF.Major.PictAttr:
1454 if (rtf.Picture != null && rtf.Picture.IsValid ()) {
1455 Line line = document.GetLine (rtf_cursor_y);
1456 document.InsertPicture (line, 0, rtf.Picture);
1459 FlushText (rtf, true);
1464 case RTF.Major.CharAttr: {
1466 case RTF.Minor.ForeColor: {
1467 System.Windows.Forms.RTF.Color color;
1469 color = System.Windows.Forms.RTF.Color.GetColor(rtf, rtf.Param);
1471 if (color != null) {
1472 FlushText(rtf, false);
1473 if (color.Red == -1 && color.Green == -1 && color.Blue == -1) {
1474 this.rtf_style.rtf_color = ForeColor;
1476 this.rtf_style.rtf_color = Color.FromArgb(color.Red, color.Green, color.Blue);
1478 FlushText (rtf, false);
1483 case RTF.Minor.FontSize: {
1484 FlushText(rtf, false);
1485 this.rtf_style.rtf_rtffont_size = rtf.Param / 2;
1489 case RTF.Minor.FontNum: {
1490 System.Windows.Forms.RTF.Font font;
1492 font = System.Windows.Forms.RTF.Font.GetFont(rtf, rtf.Param);
1494 FlushText(rtf, false);
1495 this.rtf_style.rtf_rtffont = font;
1500 case RTF.Minor.Plain: {
1501 FlushText(rtf, false);
1502 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1506 case RTF.Minor.Bold: {
1507 FlushText(rtf, false);
1508 if (rtf.Param == RTF.RTF.NoParam) {
1509 rtf_style.rtf_rtfstyle |= FontStyle.Bold;
1511 rtf_style.rtf_rtfstyle &= ~FontStyle.Bold;
1516 case RTF.Minor.Italic: {
1517 FlushText(rtf, false);
1518 if (rtf.Param == RTF.RTF.NoParam) {
1519 rtf_style.rtf_rtfstyle |= FontStyle.Italic;
1521 rtf_style.rtf_rtfstyle &= ~FontStyle.Italic;
1526 case RTF.Minor.StrikeThru: {
1527 FlushText(rtf, false);
1528 if (rtf.Param == RTF.RTF.NoParam) {
1529 rtf_style.rtf_rtfstyle |= FontStyle.Strikeout;
1531 rtf_style.rtf_rtfstyle &= ~FontStyle.Strikeout;
1536 case RTF.Minor.Underline: {
1537 FlushText(rtf, false);
1538 if (rtf.Param == RTF.RTF.NoParam) {
1539 rtf_style.rtf_rtfstyle |= FontStyle.Underline;
1541 rtf_style.rtf_rtfstyle = rtf_style.rtf_rtfstyle & ~FontStyle.Underline;
1546 case RTF.Minor.NoUnderline: {
1547 FlushText(rtf, false);
1548 rtf_style.rtf_rtfstyle &= ~FontStyle.Underline;
1555 case RTF.Major.ParAttr: {
1556 switch (rtf.Minor) {
1558 case RTF.Minor.ParDef:
1559 FlushText (rtf, false);
1560 rtf_style.rtf_par_line_left_indent = 0;
1561 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1564 case RTF.Minor.LeftIndent:
1565 rtf_style.rtf_par_line_left_indent = (int) (((float) rtf.Param / 1440.0F) * CreateGraphics ().DpiX + 0.5F);
1568 case RTF.Minor.QuadCenter:
1569 FlushText (rtf, false);
1570 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1573 case RTF.Minor.QuadJust:
1574 FlushText (rtf, false);
1575 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1578 case RTF.Minor.QuadLeft:
1579 FlushText (rtf, false);
1580 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1583 case RTF.Minor.QuadRight:
1584 FlushText (rtf, false);
1585 rtf_style.rtf_rtfalign = HorizontalAlignment.Right;
1591 case RTF.Major.SpecialChar: {
1592 //Console.Write("[Got SpecialChar control {0}]", rtf.Minor);
1599 private void SpecialChar(RTF.RTF rtf) {
1601 case RTF.Minor.Page:
1602 case RTF.Minor.Sect:
1604 case RTF.Minor.Line:
1605 case RTF.Minor.Par: {
1606 FlushText(rtf, true);
1610 case RTF.Minor.Cell: {
1615 case RTF.Minor.NoBrkSpace: {
1620 case RTF.Minor.Tab: {
1621 rtf_line.Append ("\t");
1622 // FlushText (rtf, false);
1626 case RTF.Minor.NoReqHyphen:
1627 case RTF.Minor.NoBrkHyphen: {
1628 rtf_line.Append ("-");
1629 // FlushText (rtf, false);
1633 case RTF.Minor.Bullet: {
1634 Console.WriteLine("*");
1638 case RTF.Minor.WidowCtrl:
1641 case RTF.Minor.EmDash: {
1642 rtf_line.Append ("\u2014");
1646 case RTF.Minor.EnDash: {
1647 rtf_line.Append ("\u2013");
1651 case RTF.Minor.LQuote: {
1652 Console.Write("\u2018");
1656 case RTF.Minor.RQuote: {
1657 Console.Write("\u2019");
1661 case RTF.Minor.LDblQuote: {
1662 Console.Write("\u201C");
1666 case RTF.Minor.RDblQuote: {
1667 Console.Write("\u201D");
1672 // Console.WriteLine ("skipped special char: {0}", rtf.Minor);
1679 private void HandleText(RTF.RTF rtf) {
1680 if (rtf_skip_count > 0) {
1686 if ((RTF.StandardCharCode)rtf.Minor != RTF.StandardCharCode.nothing) {
1687 rtf_line.Append(rtf_text_map[(RTF.StandardCharCode)rtf.Minor]);
1689 if ((int)rtf.Major > 31 && (int)rtf.Major < 128) {
1690 rtf_line.Append((char)rtf.Major);
1692 //rtf_line.Append((char)rtf.Major);
1693 Console.Write("[Literal:0x{0:X2}]", (int)rtf.Major);
1697 rtf_line.Append (rtf.EncodedText);
1700 private void FlushText(RTF.RTF rtf, bool newline) {
1704 length = rtf_line.Length;
1705 if (!newline && (length == 0)) {
1709 if (rtf_style.rtf_rtffont == null) {
1710 // First font in table is default
1711 rtf_style.rtf_rtffont = System.Windows.Forms.RTF.Font.GetFont (rtf, 0);
1714 font = new Font (rtf_style.rtf_rtffont.Name, rtf_style.rtf_rtffont_size, rtf_style.rtf_rtfstyle);
1716 if (rtf_style.rtf_color == Color.Empty) {
1717 System.Windows.Forms.RTF.Color color;
1719 // First color in table is default
1720 color = System.Windows.Forms.RTF.Color.GetColor (rtf, 0);
1722 if ((color == null) || (color.Red == -1 && color.Green == -1 && color.Blue == -1)) {
1723 rtf_style.rtf_color = ForeColor;
1725 rtf_style.rtf_color = Color.FromArgb (color.Red, color.Green, color.Blue);
1730 rtf_chars += rtf_line.Length;
1734 if (rtf_cursor_x == 0) {
1735 if (newline && rtf_line.ToString ().EndsWith ("\n") == false)
1736 rtf_line.Append ("\n");
1738 document.Add (rtf_cursor_y, rtf_line.ToString (), rtf_style.rtf_rtfalign, font, rtf_style.rtf_color,
1739 newline ? LineEnding.Rich : LineEnding.Wrap);
1740 if (rtf_style.rtf_par_line_left_indent != 0) {
1741 Line line = document.GetLine (rtf_cursor_y);
1742 line.indent = rtf_style.rtf_par_line_left_indent;
1747 line = document.GetLine (rtf_cursor_y);
1748 line.indent = rtf_style.rtf_par_line_left_indent;
1749 if (rtf_line.Length > 0) {
1750 document.InsertString (line, rtf_cursor_x, rtf_line.ToString ());
1751 document.FormatText (line, rtf_cursor_x + 1, line, rtf_cursor_x + 1 + length,
1752 font, rtf_style.rtf_color, Color.Empty,
1753 FormatSpecified.Font | FormatSpecified.Color);
1756 document.Split (line, rtf_cursor_x + length);
1757 line = document.GetLine (rtf_cursor_y);
1758 line.ending = LineEnding.Rich;
1760 if (line.Text.EndsWith ("\n") == false)
1769 rtf_cursor_x += length;
1771 rtf_line.Length = 0; // Empty line
1774 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y) {
1779 InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
1782 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y, out int to_x, out int to_y, out int chars) {
1785 rtf = new RTF.RTF(data);
1788 rtf.ClassCallback[RTF.TokenClass.Text] = new RTF.ClassDelegate(HandleText);
1789 rtf.ClassCallback[RTF.TokenClass.Control] = new RTF.ClassDelegate(HandleControl);
1790 rtf.ClassCallback[RTF.TokenClass.Group] = new RTF.ClassDelegate(HandleGroup);
1794 rtf_line = new StringBuilder();
1795 rtf_style.rtf_color = Color.Empty;
1796 rtf_style.rtf_rtffont_size = (int)this.Font.Size;
1797 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1798 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1799 rtf_style.rtf_rtffont = null;
1800 rtf_cursor_x = cursor_x;
1801 rtf_cursor_y = cursor_y;
1803 rtf.DefaultFont(this.Font.Name);
1805 rtf_text_map = new RTF.TextMap();
1806 RTF.TextMap.SetupStandardTable(rtf_text_map.Table);
1808 document.SuspendRecalc ();
1811 rtf.Read(); // That's it
1812 FlushText(rtf, false);
1817 catch (RTF.RTFException e) {
1821 // Seems to be plain text or broken RTF
1822 Console.WriteLine("RTF Parsing failure: {0}", e.Message);
1825 to_x = rtf_cursor_x;
1826 to_y = rtf_cursor_y;
1829 // clear the section stack if it was used
1830 if (rtf_section_stack != null)
1831 rtf_section_stack.Clear();
1833 document.RecalculateDocument(CreateGraphicsInternal(), cursor_y, document.Lines, false);
1834 document.ResumeRecalc (true);
1836 document.Invalidate (document.GetLine(cursor_y), 0, document.GetLine(document.Lines), -1);
1839 private void RichTextBox_HScrolled(object sender, EventArgs e) {
1843 private void RichTextBox_VScrolled(object sender, EventArgs e) {
1847 private void PointToTagPos(Point pt, out LineTag tag, out int pos) {
1852 if (p.X >= document.ViewPortWidth) {
1853 p.X = document.ViewPortWidth - 1;
1854 } else if (p.X < 0) {
1858 if (p.Y >= document.ViewPortHeight) {
1859 p.Y = document.ViewPortHeight - 1;
1860 } else if (p.Y < 0) {
1864 tag = document.FindCursor(p.X + document.ViewPortX, p.Y + document.ViewPortY, out pos);
1867 private void EmitRTFFontProperties(StringBuilder rtf, int prev_index, int font_index, Font prev_font, Font font) {
1868 if (prev_index != font_index) {
1869 rtf.Append(String.Format("\\f{0}", font_index)); // Font table entry
1872 if ((prev_font == null) || (prev_font.Size != font.Size)) {
1873 rtf.Append(String.Format("\\fs{0}", (int)(font.Size * 2))); // Font size
1876 if ((prev_font == null) || (font.Bold != prev_font.Bold)) {
1880 if (prev_font != null) {
1886 if ((prev_font == null) || (font.Italic != prev_font.Italic)) {
1890 if (prev_font != null) {
1896 if ((prev_font == null) || (font.Strikeout != prev_font.Strikeout)) {
1897 if (font.Strikeout) {
1898 rtf.Append("\\strike");
1900 if (prev_font != null) {
1901 rtf.Append("\\strike0");
1906 if ((prev_font == null) || (font.Underline != prev_font.Underline)) {
1907 if (font.Underline) {
1910 if (prev_font != null) {
1911 rtf.Append("\\ul0");
1917 [MonoTODO("Emit unicode and other special characters properly")]
1918 private void EmitRTFText(StringBuilder rtf, string text) {
1922 // start_pos and end_pos are 0-based
1923 private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
1937 sb = new StringBuilder();
1938 fonts = new ArrayList(10);
1939 colors = new ArrayList(10);
1941 // Two runs, first we parse to determine tables;
1942 // and unlike most of our processing here we work on tags
1945 line_no = start_line.line_no;
1948 // Add default font and color; to optimize document content we don't
1949 // use this.Font and this.ForeColor but the font/color from the first tag
1950 tag = LineTag.FindTag(start_line, pos);
1953 fonts.Add(font.Name);
1956 while (line_no <= end_line.line_no) {
1957 line = document.GetLine(line_no);
1958 tag = LineTag.FindTag(line, pos);
1960 if (line_no != end_line.line_no) {
1961 line_len = line.text.Length;
1966 while (pos < line_len) {
1967 if (tag.Font.Name != font.Name) {
1969 if (!fonts.Contains(font.Name)) {
1970 fonts.Add(font.Name);
1974 if (tag.Color != color) {
1976 if (!colors.Contains(color)) {
1981 pos = tag.Start + tag.Length - 1;
1988 // We have the tables, emit the header
1989 sb.Append("{\\rtf1\\ansi");
1990 sb.Append("\\ansicpg1252"); // FIXME - is this correct?
1993 sb.Append(String.Format("\\deff{0}", fonts.IndexOf(this.Font.Name)));
1996 sb.Append("\\deflang1033\n"); // FIXME - always 1033?
1998 // Emit the font table
1999 sb.Append("{\\fonttbl");
2000 for (i = 0; i < fonts.Count; i++) {
2001 sb.Append(String.Format("{{\\f{0}", i)); // {Font
2002 sb.Append("\\fnil"); // Family
2003 sb.Append("\\fcharset0 "); // Charset ANSI<space>
2004 sb.Append((string)fonts[i]); // Font name
2005 sb.Append(";}"); // }
2009 // Emit the color table (if needed)
2010 if ((colors.Count > 1) || ((((Color)colors[0]).R != this.ForeColor.R) || (((Color)colors[0]).G != this.ForeColor.G) || (((Color)colors[0]).B != this.ForeColor.B))) {
2011 sb.Append("{\\colortbl "); // Header and NO! default color
2012 for (i = 0; i < colors.Count; i++) {
2013 sb.Append(String.Format("\\red{0}", ((Color)colors[i]).R));
2014 sb.Append(String.Format("\\green{0}", ((Color)colors[i]).G));
2015 sb.Append(String.Format("\\blue{0}", ((Color)colors[i]).B));
2021 sb.Append("{\\*\\generator Mono RichTextBox;}");
2022 // Emit initial paragraph settings
2023 tag = LineTag.FindTag(start_line, start_pos);
2024 sb.Append("\\pard"); // Reset to default paragraph properties
2025 EmitRTFFontProperties(sb, -1, fonts.IndexOf(tag.Font.Name), null, tag.Font); // Font properties
2026 sb.Append(" "); // Space separator
2029 color = (Color)colors[0];
2031 line_no = start_line.line_no;
2034 while (line_no <= end_line.line_no) {
2035 line = document.GetLine(line_no);
2036 tag = LineTag.FindTag(line, pos);
2038 if (line_no != end_line.line_no) {
2039 line_len = line.text.Length;
2044 while (pos < line_len) {
2047 if (tag.Font != font) {
2048 EmitRTFFontProperties(sb, fonts.IndexOf(font.Name), fonts.IndexOf(tag.Font.Name), font, tag.Font);
2052 if (tag.Color != color) {
2054 sb.Append(String.Format("\\cf{0}", colors.IndexOf(color)));
2056 if (length != sb.Length) {
2057 sb.Append(" "); // Emit space to separate keywords from text
2060 // Emit the string itself
2061 if (line_no != end_line.line_no) {
2062 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2064 if (end_pos < (tag.Start + tag.Length - 1)) {
2065 // Emit partial tag only, end_pos is inside this tag
2066 EmitRTFText(sb, tag.Line.text.ToString(pos, end_pos - pos));
2068 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2072 pos = tag.Start + tag.Length - 1;
2075 if (pos >= line.text.Length) {
2076 if (line.ending != LineEnding.Wrap) {
2077 sb.Append("\\par\n");
2088 #endregion // Private Methods