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;
88 rtf_style = new RtfSectionStyle ();
89 rtf_section_stack = null;
91 scrollbars = RichTextBoxScrollBars.Both;
92 alignment = HorizontalAlignment.Left;
93 LostFocus += new EventHandler(RichTextBox_LostFocus);
94 GotFocus += new EventHandler(RichTextBox_GotFocus);
95 BackColor = ThemeEngine.Current.ColorWindow;
97 backcolor_set = false;
98 language_option = RichTextBoxLanguageOptions.AutoFontSizeAdjust;
99 rich_text_shortcuts_enabled = true;
100 selection_back_color = DefaultBackColor;
102 ForeColor = ThemeEngine.Current.ColorWindowText;
104 base.HScrolled += new EventHandler(RichTextBox_HScrolled);
105 base.VScrolled += new EventHandler(RichTextBox_VScrolled);
108 SetStyle (ControlStyles.StandardDoubleClick, false);
111 #endregion // Public Constructors
113 #region Private & Internal Methods
115 internal override void HandleLinkClicked (LinkRectangle link)
117 OnLinkClicked (new LinkClickedEventArgs (link.LinkTag.LinkText));
120 internal override Color ChangeBackColor (Color backColor)
122 if (backColor == Color.Empty) {
124 backcolor_set = false;
126 backColor = SystemColors.Window;
129 backColor = SystemColors.Window;
135 private void RichTextBox_LostFocus(object sender, EventArgs e) {
139 private void RichTextBox_GotFocus(object sender, EventArgs e) {
142 #endregion // Private & Internal Methods
144 #region Public Instance Properties
148 public override bool AllowDrop {
150 return base.AllowDrop;
154 base.AllowDrop = value;
158 [DefaultValue(false)]
160 [DesignerSerializationVisibility (DesignerSerializationVisibility.Visible)]
161 [RefreshProperties (RefreshProperties.Repaint)]
162 [EditorBrowsable (EditorBrowsableState.Never)]
167 public override bool AutoSize {
173 base.AutoSize = value;
177 [MonoTODO ("Value not respected, always true")]
178 [DefaultValue(false)]
179 public bool AutoWordSelection {
180 get { return auto_word_select; }
181 set { auto_word_select = value; }
185 [EditorBrowsable(EditorBrowsableState.Never)]
186 public override System.Drawing.Image BackgroundImage {
187 get { return base.BackgroundImage; }
188 set { base.BackgroundImage = value; }
193 [EditorBrowsable (EditorBrowsableState.Never)]
194 public override ImageLayout BackgroundImageLayout {
195 get { return base.BackgroundImageLayout; }
196 set { base.BackgroundImageLayout = value; }
202 public int BulletIndent {
204 return bullet_indent;
208 bullet_indent = value;
213 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
214 public bool CanRedo {
216 return document.undo.CanRedo;
221 public bool DetectUrls {
222 get { return base.EnableLinks; }
223 set { base.EnableLinks = value; }
228 [DefaultValue (false)]
229 public bool EnableAutoDragDrop {
230 get { return enable_auto_drag_drop; }
231 set { enable_auto_drag_drop = value; }
235 public override Font Font {
246 if (PreferredHeight != Height) {
247 Height = PreferredHeight;
253 // Font changes always set the whole doc to that font
254 start = document.GetLine(1);
255 end = document.GetLine(document.Lines);
256 document.FormatText(start, 1, end, end.text.Length + 1, base.Font, Color.Empty, Color.Empty, FormatSpecified.Font);
261 public override Color ForeColor {
263 return base.ForeColor;
267 base.ForeColor = value;
274 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
275 public RichTextBoxLanguageOptions LanguageOption {
276 get { return language_option; }
277 set { language_option = value; }
281 [DefaultValue(Int32.MaxValue)]
282 public override int MaxLength {
284 return base.max_length;
288 base.max_length = value;
293 public override bool Multiline {
295 return base.Multiline;
299 base.Multiline = value;
304 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
306 public string RedoActionName {
308 return document.undo.RedoActionName;
315 [DefaultValue (true)]
316 [EditorBrowsable (EditorBrowsableState.Never)]
317 public bool RichTextShortcutsEnabled {
318 get { return rich_text_shortcuts_enabled; }
319 set { rich_text_shortcuts_enabled = value; }
325 [MonoTODO("Teach TextControl.RecalculateLine to consider the right margin as well")]
326 public int RightMargin {
332 margin_right = value;
337 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
339 [RefreshProperties (RefreshProperties.All)]
348 start_line = document.GetLine(1);
349 end_line = document.GetLine(document.Lines);
350 return GenerateRTF(start_line, 0, end_line, end_line.text.Length).ToString();
357 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
359 InsertRTFFromStream(data, 0, 1);
367 [DefaultValue(RichTextBoxScrollBars.Both)]
369 public RichTextBoxScrollBars ScrollBars {
375 if (!Enum.IsDefined (typeof (RichTextBoxScrollBars), value))
376 throw new InvalidEnumArgumentException ("value", (int) value,
377 typeof (RichTextBoxScrollBars));
379 if (value != scrollbars) {
381 CalculateDocument ();
388 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
389 public string SelectedRtf {
391 return GenerateRTF(document.selection_start.line, document.selection_start.pos, document.selection_end.line, document.selection_end.pos).ToString();
403 if (document.selection_visible) {
404 document.ReplaceSelection("", false);
407 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
409 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
410 InsertRTFFromStream(data, document.selection_start.pos, document.selection_start.line.line_no, out x, out y, out chars);
413 document.CharIndexToLineTag(sel_start + chars + (y - document.selection_start.line.line_no) * 2, out line, out tag, out sel_start);
414 document.SetSelection(line, sel_start);
415 document.PositionCaret(line, sel_start);
416 document.DisplayCaret();
418 OnTextChanged(EventArgs.Empty);
424 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
425 public override string SelectedText {
427 return base.SelectedText;
431 base.SelectedText = value;
436 [DefaultValue(HorizontalAlignment.Left)]
437 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
438 public HorizontalAlignment SelectionAlignment {
440 HorizontalAlignment align;
445 start = document.ParagraphStart(document.selection_start.line);
446 align = start.alignment;
448 end = document.ParagraphEnd(document.selection_end.line);
453 if (line.alignment != align) {
454 return HorizontalAlignment.Left;
460 line = document.GetLine(line.line_no + 1);
471 start = document.ParagraphStart(document.selection_start.line);
473 end = document.ParagraphEnd(document.selection_end.line);
478 line.alignment = value;
483 line = document.GetLine(line.line_no + 1);
485 this.CalculateDocument();
492 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
493 public Color SelectionBackColor {
494 get { return selection_back_color; }
495 set { selection_back_color = value; }
500 [DefaultValue(false)]
501 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
503 public bool SelectionBullet {
514 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
516 public int SelectionCharOffset {
526 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
527 public Color SelectionColor {
534 if (selection_length > 0) {
535 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
536 end = document.selection_start.line.FindTag (document.selection_end.pos);
538 start = document.selection_start.line.FindTag (document.selection_start.pos);
545 while (tag != null) {
547 if (!color.Equals (tag.Color))
553 tag = document.NextTag (tag);
560 if (value == Color.Empty)
561 value = DefaultForeColor;
566 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
567 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
569 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
570 document.selection_end.line, document.selection_end.pos + 1, null,
571 value, Color.Empty, FormatSpecified.Color);
573 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
574 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
576 document.UpdateView(document.selection_start.line, 0);
578 //Re-Align the caret in case its changed size or position
579 //probably not necessary here
580 document.AlignCaret(false);
585 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
586 public Font SelectionFont {
593 if (selection_length > 0) {
594 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
595 end = document.selection_start.line.FindTag (document.selection_end.pos);
597 start = document.selection_start.line.FindTag (document.selection_start.pos);
603 if (selection_length > 1) {
605 while (tag != null) {
607 if (!font.Equals(tag.Font))
613 tag = document.NextTag (tag);
624 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
625 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
627 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
628 document.selection_end.line, document.selection_end.pos + 1, value,
629 Color.Empty, Color.Empty, FormatSpecified.Font);
631 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
632 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
634 document.UpdateView(document.selection_start.line, 0);
635 //Re-Align the caret in case its changed size or position
636 Document.AlignCaret (false);
643 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
645 public int SelectionHangingIndent {
656 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
658 public int SelectionIndent {
668 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
669 public override int SelectionLength {
671 return base.SelectionLength;
675 base.SelectionLength = value;
680 [DefaultValue(false)]
681 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
683 public bool SelectionProtected {
694 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
696 public int SelectionRightIndent {
706 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
708 public int[] SelectionTabs {
718 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
719 public RichTextBoxSelectionTypes SelectionType {
721 if (document.selection_start == document.selection_end) {
722 return RichTextBoxSelectionTypes.Empty;
726 if (SelectedText.Length > 1) {
727 return RichTextBoxSelectionTypes.MultiChar | RichTextBoxSelectionTypes.Text;
730 return RichTextBoxSelectionTypes.Text;
734 [DefaultValue(false)]
736 public bool ShowSelectionMargin {
747 [RefreshProperties (RefreshProperties.All)]
749 public override string Text {
760 public override int TextLength {
762 return base.TextLength;
767 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
768 public string UndoActionName {
770 return document.undo.UndoActionName;
776 public float ZoomFactor {
785 #endregion // Public Instance Properties
787 #region Protected Instance Properties
788 protected override CreateParams CreateParams {
790 return base.CreateParams;
794 protected override Size DefaultSize {
796 return new Size(100, 96);
799 #endregion // Protected Instance Properties
801 #region Public Instance Methods
802 public bool CanPaste(DataFormats.Format clipFormat) {
803 if ((clipFormat.Name == DataFormats.Rtf) ||
804 (clipFormat.Name == DataFormats.Text) ||
805 (clipFormat.Name == DataFormats.UnicodeText)) {
811 public int Find(char[] characterSet) {
812 return Find(characterSet, -1, -1);
815 public int Find(char[] characterSet, int start) {
816 return Find(characterSet, start, -1);
819 public int Find(char[] characterSet, int start, int end) {
820 Document.Marker start_mark;
821 Document.Marker end_mark;
822 Document.Marker result;
825 document.GetMarker(out start_mark, true);
831 start_mark = new Document.Marker();
833 document.CharIndexToLineTag(start, out line, out tag, out pos);
834 start_mark.line = line;
835 start_mark.tag = tag;
836 start_mark.pos = pos;
840 document.GetMarker(out end_mark, false);
846 end_mark = new Document.Marker();
848 document.CharIndexToLineTag(end, out line, out tag, out pos);
849 end_mark.line = line;
854 if (document.FindChars(characterSet, start_mark, end_mark, out result)) {
855 return document.LineTagToCharIndex(result.line, result.pos);
861 public int Find(string str) {
862 return Find(str, -1, -1, RichTextBoxFinds.None);
865 public int Find(string str, int start, int end, RichTextBoxFinds options) {
866 Document.Marker start_mark;
867 Document.Marker end_mark;
868 Document.Marker result;
871 document.GetMarker(out start_mark, true);
877 start_mark = new Document.Marker();
879 document.CharIndexToLineTag(start, out line, out tag, out pos);
881 start_mark.line = line;
882 start_mark.tag = tag;
883 start_mark.pos = pos;
887 document.GetMarker(out end_mark, false);
893 end_mark = new Document.Marker();
895 document.CharIndexToLineTag(end, out line, out tag, out pos);
897 end_mark.line = line;
902 if (document.Find(str, start_mark, end_mark, out result, options)) {
903 return document.LineTagToCharIndex(result.line, result.pos);
909 public int Find(string str, int start, RichTextBoxFinds options) {
910 return Find(str, start, -1, options);
913 public int Find(string str, RichTextBoxFinds options) {
914 return Find(str, -1, -1, options);
919 public char GetCharFromPosition(Point pt) {
923 PointToTagPos(pt, out tag, out pos);
925 if (pos >= tag.Line.text.Length) {
929 return tag.Line.text[pos];
932 internal override char GetCharFromPositionInternal (Point p)
937 PointToTagPos (p, out tag, out pos);
939 if (pos >= tag.Line.text.Length)
942 return tag.Line.text[pos];
950 int GetCharIndexFromPosition(Point pt) {
954 PointToTagPos(pt, out tag, out pos);
956 return document.LineTagToCharIndex(tag.Line, pos);
963 int GetLineFromCharIndex(int index) {
968 document.CharIndexToLineTag(index, out line, out tag, out pos);
970 return line.LineNo - 1;
977 Point GetPositionFromCharIndex(int index) {
982 document.CharIndexToLineTag(index, out line, out tag, out pos);
984 return new Point((int)line.widths[pos] + 1, line.Y + 1);
987 public void LoadFile(System.IO.Stream data, RichTextBoxStreamType fileType) {
991 // FIXME - ignoring unicode
992 if (fileType == RichTextBoxStreamType.PlainText) {
997 sb = new StringBuilder ((int) data.Length);
998 buffer = new char [1024];
1000 throw new IOException("Not enough memory to load document");
1003 StreamReader sr = new StreamReader (data, Encoding.Default, true);
1004 int charsRead = sr.Read (buffer, 0, buffer.Length);
1005 while (charsRead > 0) {
1006 sb.Append (buffer, 0, charsRead);
1007 charsRead = sr.Read (buffer, 0, buffer.Length);
1009 base.Text = sb.ToString();
1013 InsertRTFFromStream(data, 0, 1);
1015 document.PositionCaret (document.GetLine (1), 0);
1016 document.SetSelectionToCaret (true);
1020 [MonoTODO("Make smarter RTF detection?")]
1021 public void LoadFile(string path) {
1022 if (path.EndsWith(".rtf")) {
1023 LoadFile(path, RichTextBoxStreamType.RichText);
1025 LoadFile(path, RichTextBoxStreamType.PlainText);
1029 public void LoadFile(string path, RichTextBoxStreamType fileType) {
1036 data = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024);
1038 LoadFile(data, fileType);
1041 catch (Exception ex) {
1042 throw new IOException("Could not open file " + path, ex);
1052 public void Paste(DataFormats.Format clipFormat) {
1053 base.Paste(Clipboard.GetDataObject(), clipFormat, false);
1058 document.undo.Redo ();
1061 public void SaveFile(Stream data, RichTextBoxStreamType fileType) {
1067 if (fileType == RichTextBoxStreamType.UnicodePlainText) {
1068 encoding = Encoding.Unicode;
1070 encoding = Encoding.ASCII;
1074 case RichTextBoxStreamType.PlainText:
1075 case RichTextBoxStreamType.TextTextOleObjs:
1076 case RichTextBoxStreamType.UnicodePlainText: {
1078 bytes = encoding.GetBytes(document.Root.text.ToString());
1079 data.Write(bytes, 0, bytes.Length);
1083 for (i = 1; i < document.Lines; i++) {
1084 bytes = encoding.GetBytes(document.GetLine(i).text.ToString() + Environment.NewLine);
1085 data.Write(bytes, 0, bytes.Length);
1087 bytes = encoding.GetBytes(document.GetLine(document.Lines).text.ToString());
1088 data.Write(bytes, 0, bytes.Length);
1093 // If we're here we're saving RTF
1100 start_line = document.GetLine(1);
1101 end_line = document.GetLine(document.Lines);
1102 rtf = GenerateRTF(start_line, 0, end_line, end_line.text.Length);
1104 bytes = new Byte[4096];
1106 // Let's chunk it so we don't use up all memory...
1107 for (i = 0; i < total; i += 1024) {
1108 if ((i + 1024) < total) {
1109 current = encoding.GetBytes(rtf.ToString(i, 1024), 0, 1024, bytes, 0);
1111 current = total - i;
1112 current = encoding.GetBytes(rtf.ToString(i, current), 0, current, bytes, 0);
1114 data.Write(bytes, 0, current);
1118 public void SaveFile(string path) {
1119 if (path.EndsWith(".rtf")) {
1120 SaveFile(path, RichTextBoxStreamType.RichText);
1122 SaveFile(path, RichTextBoxStreamType.PlainText);
1126 public void SaveFile(string path, RichTextBoxStreamType fileType) {
1132 data = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1024, false);
1133 SaveFile(data, fileType);
1137 // throw new IOException("Could not write document to file " + path);
1148 [EditorBrowsable (EditorBrowsableState.Never)]
1149 public new void DrawToBitmap (Bitmap bitmap, Rectangle clip)
1151 Graphics dc = Graphics.FromImage (bitmap);
1153 if (backcolor_set || (Enabled && !read_only)) {
1154 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), clip);
1156 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (ThemeEngine.Current.ColorControl), clip);
1159 // Draw the viewable document
1160 document.Draw (dc, clip);
1164 #endregion // Public Instance Methods
1166 #region Protected Instance Methods
1167 protected virtual object CreateRichEditOleCallback() {
1168 throw new NotImplementedException();
1171 protected override void OnBackColorChanged(EventArgs e) {
1172 base.OnBackColorChanged (e);
1175 protected virtual void OnContentsResized(ContentsResizedEventArgs e) {
1176 ContentsResizedEventHandler eh = (ContentsResizedEventHandler)(Events [ContentsResizedEvent]);
1181 protected override void OnContextMenuChanged(EventArgs e) {
1182 base.OnContextMenuChanged (e);
1185 protected override void OnHandleCreated(EventArgs e) {
1186 base.OnHandleCreated (e);
1189 protected override void OnHandleDestroyed(EventArgs e) {
1190 base.OnHandleDestroyed (e);
1193 protected virtual void OnHScroll(EventArgs e) {
1194 EventHandler eh = (EventHandler)(Events [HScrollEvent]);
1199 [MonoTODO("Determine when to call this")]
1200 protected virtual void OnImeChange(EventArgs e) {
1201 EventHandler eh = (EventHandler)(Events [ImeChangeEvent]);
1206 protected virtual void OnLinkClicked(LinkClickedEventArgs e) {
1207 LinkClickedEventHandler eh = (LinkClickedEventHandler)(Events [LinkClickedEvent]);
1212 protected virtual void OnProtected(EventArgs e) {
1213 EventHandler eh = (EventHandler)(Events [ProtectedEvent]);
1218 protected override void OnRightToLeftChanged(EventArgs e) {
1219 base.OnRightToLeftChanged (e);
1222 protected virtual void OnSelectionChanged(EventArgs e) {
1223 EventHandler eh = (EventHandler)(Events [SelectionChangedEvent]);
1229 protected override void OnSystemColorsChanged(EventArgs e) {
1230 base.OnSystemColorsChanged (e);
1233 protected override void OnTextChanged(EventArgs e) {
1234 base.OnTextChanged (e);
1238 protected virtual void OnVScroll(EventArgs e) {
1239 EventHandler eh = (EventHandler)(Events [VScrollEvent]);
1244 protected override void WndProc(ref Message m) {
1245 base.WndProc (ref m);
1249 protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
1251 return base.ProcessCmdKey (ref msg, keyData);
1254 #endregion // Protected Instance Methods
1257 static object ContentsResizedEvent = new object ();
1258 static object HScrollEvent = new object ();
1259 static object ImeChangeEvent = new object ();
1260 static object LinkClickedEvent = new object ();
1261 static object ProtectedEvent = new object ();
1262 static object SelectionChangedEvent = new object ();
1263 static object VScrollEvent = new object ();
1266 [EditorBrowsable(EditorBrowsableState.Never)]
1267 public new event EventHandler BackgroundImageChanged {
1268 add { base.BackgroundImageChanged += value; }
1269 remove { base.BackgroundImageChanged -= value; }
1274 [EditorBrowsable (EditorBrowsableState.Never)]
1275 public new event EventHandler BackgroundImageLayoutChanged {
1276 add { base.BackgroundImageLayoutChanged += value; }
1277 remove { base.BackgroundImageLayoutChanged -= value; }
1281 public event ContentsResizedEventHandler ContentsResized {
1282 add { Events.AddHandler (ContentsResizedEvent, value); }
1283 remove { Events.RemoveHandler (ContentsResizedEvent, value); }
1288 [EditorBrowsable(EditorBrowsableState.Never)]
1289 public new event EventHandler DoubleClick {
1290 add { base.DoubleClick += value; }
1291 remove { base.DoubleClick -= value; }
1297 [EditorBrowsable(EditorBrowsableState.Never)]
1299 public new event DragEventHandler DragDrop {
1300 add { base.DragDrop += value; }
1301 remove { base.DragDrop -= value; }
1306 [EditorBrowsable(EditorBrowsableState.Never)]
1308 public new event DragEventHandler DragEnter {
1309 add { base.DragEnter += value; }
1310 remove { base.DragEnter -= value; }
1314 [EditorBrowsable(EditorBrowsableState.Never)]
1315 public new event EventHandler DragLeave {
1316 add { base.DragLeave += value; }
1317 remove { base.DragLeave -= value; }
1322 [EditorBrowsable(EditorBrowsableState.Never)]
1323 public new event DragEventHandler DragOver {
1324 add { base.DragOver += value; }
1325 remove { base.DragOver -= value; }
1330 [EditorBrowsable(EditorBrowsableState.Never)]
1331 public new event GiveFeedbackEventHandler GiveFeedback {
1332 add { base.GiveFeedback += value; }
1333 remove { base.GiveFeedback -= value; }
1336 public event EventHandler HScroll {
1337 add { Events.AddHandler (HScrollEvent, value); }
1338 remove { Events.RemoveHandler (HScrollEvent, value); }
1341 public event EventHandler ImeChange {
1342 add { Events.AddHandler (ImeChangeEvent, value); }
1343 remove { Events.RemoveHandler (ImeChangeEvent, value); }
1346 public event LinkClickedEventHandler LinkClicked {
1347 add { Events.AddHandler (LinkClickedEvent, value); }
1348 remove { Events.RemoveHandler (LinkClickedEvent, value); }
1351 public event EventHandler Protected {
1352 add { Events.AddHandler (ProtectedEvent, value); }
1353 remove { Events.RemoveHandler (ProtectedEvent, value); }
1357 [EditorBrowsable(EditorBrowsableState.Never)]
1358 public new event QueryContinueDragEventHandler QueryContinueDrag {
1359 add { base.QueryContinueDrag += value; }
1360 remove { base.QueryContinueDrag -= value; }
1363 [MonoTODO("Currently does not ever fire")]
1364 public event EventHandler SelectionChanged {
1365 add { Events.AddHandler (SelectionChangedEvent, value); }
1366 remove { Events.RemoveHandler (SelectionChangedEvent, value); }
1369 public event EventHandler VScroll {
1370 add { Events.AddHandler (VScrollEvent, value); }
1371 remove { Events.RemoveHandler (VScrollEvent, value); }
1373 #endregion // Events
1375 #region Private Methods
1377 internal override void SelectWord ()
1379 document.ExpandSelection(CaretSelection.Word, false);
1382 private class RtfSectionStyle : ICloneable {
1383 internal Color rtf_color;
1384 internal RTF.Font rtf_rtffont;
1385 internal int rtf_rtffont_size;
1386 internal FontStyle rtf_rtfstyle;
1387 internal HorizontalAlignment rtf_rtfalign;
1388 internal int rtf_par_line_left_indent;
1390 public object Clone ()
1392 RtfSectionStyle new_style = new RtfSectionStyle ();
1394 new_style.rtf_color = rtf_color;
1395 new_style.rtf_par_line_left_indent = rtf_par_line_left_indent;
1396 new_style.rtf_rtfalign = rtf_rtfalign;
1397 new_style.rtf_rtffont = rtf_rtffont;
1398 new_style.rtf_rtffont_size = rtf_rtffont_size;
1399 new_style.rtf_rtfstyle = rtf_rtfstyle;
1405 // To allow us to keep track of the sections and revert formatting
1406 // as we go in and out of sections of the document.
1407 private void HandleGroup (RTF.RTF rtf)
1409 //start group - save the current formatting on to a stack
1410 //end group - go back to the formatting at the current group
1411 if (rtf_section_stack == null) {
1412 rtf_section_stack = new Stack ();
1415 if (rtf.Major == RTF.Major.BeginGroup) {
1416 rtf_section_stack.Push (rtf_style.Clone ());
1417 } else if (rtf.Major == RTF.Major.EndGroup) {
1418 if (rtf_section_stack.Count > 0) {
1419 FlushText (rtf, false);
1421 rtf_style = (RtfSectionStyle) rtf_section_stack.Pop ();
1426 [MonoTODO("Add QuadJust support for justified alignment")]
1427 private void HandleControl(RTF.RTF rtf) {
1429 case RTF.Major.Unicode: {
1431 case RTF.Minor.UnicodeCharBytes: {
1432 rtf_skip_width = rtf.Param;
1436 case RTF.Minor.UnicodeChar: {
1437 rtf_skip_count += rtf_skip_width;
1438 rtf_line.Append((char)rtf.Param);
1445 case RTF.Major.Destination: {
1446 // Console.Write("[Got Destination control {0}]", rtf.Minor);
1451 case RTF.Major.PictAttr:
1452 if (rtf.Picture != null && rtf.Picture.IsValid ()) {
1453 Line line = document.GetLine (rtf_cursor_y);
1454 document.InsertPicture (line, 0, rtf.Picture);
1457 FlushText (rtf, true);
1462 case RTF.Major.CharAttr: {
1464 case RTF.Minor.ForeColor: {
1465 System.Windows.Forms.RTF.Color color;
1467 color = System.Windows.Forms.RTF.Color.GetColor(rtf, rtf.Param);
1469 if (color != null) {
1470 FlushText(rtf, false);
1471 if (color.Red == -1 && color.Green == -1 && color.Blue == -1) {
1472 this.rtf_style.rtf_color = ForeColor;
1474 this.rtf_style.rtf_color = Color.FromArgb(color.Red, color.Green, color.Blue);
1476 FlushText (rtf, false);
1481 case RTF.Minor.FontSize: {
1482 FlushText(rtf, false);
1483 this.rtf_style.rtf_rtffont_size = rtf.Param / 2;
1487 case RTF.Minor.FontNum: {
1488 System.Windows.Forms.RTF.Font font;
1490 font = System.Windows.Forms.RTF.Font.GetFont(rtf, rtf.Param);
1492 FlushText(rtf, false);
1493 this.rtf_style.rtf_rtffont = font;
1498 case RTF.Minor.Plain: {
1499 FlushText(rtf, false);
1500 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1504 case RTF.Minor.Bold: {
1505 FlushText(rtf, false);
1506 if (rtf.Param == RTF.RTF.NoParam) {
1507 rtf_style.rtf_rtfstyle |= FontStyle.Bold;
1509 rtf_style.rtf_rtfstyle &= ~FontStyle.Bold;
1514 case RTF.Minor.Italic: {
1515 FlushText(rtf, false);
1516 if (rtf.Param == RTF.RTF.NoParam) {
1517 rtf_style.rtf_rtfstyle |= FontStyle.Italic;
1519 rtf_style.rtf_rtfstyle &= ~FontStyle.Italic;
1524 case RTF.Minor.StrikeThru: {
1525 FlushText(rtf, false);
1526 if (rtf.Param == RTF.RTF.NoParam) {
1527 rtf_style.rtf_rtfstyle |= FontStyle.Strikeout;
1529 rtf_style.rtf_rtfstyle &= ~FontStyle.Strikeout;
1534 case RTF.Minor.Underline: {
1535 FlushText(rtf, false);
1536 if (rtf.Param == RTF.RTF.NoParam) {
1537 rtf_style.rtf_rtfstyle |= FontStyle.Underline;
1539 rtf_style.rtf_rtfstyle = rtf_style.rtf_rtfstyle & ~FontStyle.Underline;
1544 case RTF.Minor.NoUnderline: {
1545 FlushText(rtf, false);
1546 rtf_style.rtf_rtfstyle &= ~FontStyle.Underline;
1553 case RTF.Major.ParAttr: {
1554 switch (rtf.Minor) {
1556 case RTF.Minor.ParDef:
1557 FlushText (rtf, false);
1558 rtf_style.rtf_par_line_left_indent = 0;
1559 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1562 case RTF.Minor.LeftIndent:
1563 rtf_style.rtf_par_line_left_indent = (int) (((float) rtf.Param / 1440.0F) * CreateGraphics ().DpiX + 0.5F);
1566 case RTF.Minor.QuadCenter:
1567 FlushText (rtf, false);
1568 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1571 case RTF.Minor.QuadJust:
1572 FlushText (rtf, false);
1573 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1576 case RTF.Minor.QuadLeft:
1577 FlushText (rtf, false);
1578 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1581 case RTF.Minor.QuadRight:
1582 FlushText (rtf, false);
1583 rtf_style.rtf_rtfalign = HorizontalAlignment.Right;
1589 case RTF.Major.SpecialChar: {
1590 //Console.Write("[Got SpecialChar control {0}]", rtf.Minor);
1597 private void SpecialChar(RTF.RTF rtf) {
1599 case RTF.Minor.Page:
1600 case RTF.Minor.Sect:
1602 case RTF.Minor.Line:
1603 case RTF.Minor.Par: {
1604 FlushText(rtf, true);
1608 case RTF.Minor.Cell: {
1613 case RTF.Minor.NoBrkSpace: {
1618 case RTF.Minor.Tab: {
1619 rtf_line.Append ("\t");
1620 // FlushText (rtf, false);
1624 case RTF.Minor.NoReqHyphen:
1625 case RTF.Minor.NoBrkHyphen: {
1626 rtf_line.Append ("-");
1627 // FlushText (rtf, false);
1631 case RTF.Minor.Bullet: {
1632 Console.WriteLine("*");
1636 case RTF.Minor.WidowCtrl:
1639 case RTF.Minor.EmDash: {
1640 rtf_line.Append ("\u2014");
1644 case RTF.Minor.EnDash: {
1645 rtf_line.Append ("\u2013");
1649 case RTF.Minor.LQuote: {
1650 Console.Write("\u2018");
1654 case RTF.Minor.RQuote: {
1655 Console.Write("\u2019");
1659 case RTF.Minor.LDblQuote: {
1660 Console.Write("\u201C");
1664 case RTF.Minor.RDblQuote: {
1665 Console.Write("\u201D");
1670 // Console.WriteLine ("skipped special char: {0}", rtf.Minor);
1677 private void HandleText(RTF.RTF rtf) {
1678 if (rtf_skip_count > 0) {
1684 if ((RTF.StandardCharCode)rtf.Minor != RTF.StandardCharCode.nothing) {
1685 rtf_line.Append(rtf_text_map[(RTF.StandardCharCode)rtf.Minor]);
1687 if ((int)rtf.Major > 31 && (int)rtf.Major < 128) {
1688 rtf_line.Append((char)rtf.Major);
1690 //rtf_line.Append((char)rtf.Major);
1691 Console.Write("[Literal:0x{0:X2}]", (int)rtf.Major);
1695 rtf_line.Append (rtf.EncodedText);
1698 private void FlushText(RTF.RTF rtf, bool newline) {
1702 length = rtf_line.Length;
1703 if (!newline && (length == 0)) {
1707 if (rtf_style.rtf_rtffont == null) {
1708 // First font in table is default
1709 rtf_style.rtf_rtffont = System.Windows.Forms.RTF.Font.GetFont (rtf, 0);
1712 font = new Font (rtf_style.rtf_rtffont.Name, rtf_style.rtf_rtffont_size, rtf_style.rtf_rtfstyle);
1714 if (rtf_style.rtf_color == Color.Empty) {
1715 System.Windows.Forms.RTF.Color color;
1717 // First color in table is default
1718 color = System.Windows.Forms.RTF.Color.GetColor (rtf, 0);
1720 if ((color == null) || (color.Red == -1 && color.Green == -1 && color.Blue == -1)) {
1721 rtf_style.rtf_color = ForeColor;
1723 rtf_style.rtf_color = Color.FromArgb (color.Red, color.Green, color.Blue);
1728 rtf_chars += rtf_line.Length;
1732 if (rtf_cursor_x == 0) {
1733 if (newline && rtf_line.ToString ().EndsWith ("\n") == false)
1734 rtf_line.Append ("\n");
1736 document.Add (rtf_cursor_y, rtf_line.ToString (), rtf_style.rtf_rtfalign, font, rtf_style.rtf_color,
1737 newline ? LineEnding.Rich : LineEnding.Wrap);
1738 if (rtf_style.rtf_par_line_left_indent != 0) {
1739 Line line = document.GetLine (rtf_cursor_y);
1740 line.indent = rtf_style.rtf_par_line_left_indent;
1745 line = document.GetLine (rtf_cursor_y);
1746 line.indent = rtf_style.rtf_par_line_left_indent;
1747 if (rtf_line.Length > 0) {
1748 document.InsertString (line, rtf_cursor_x, rtf_line.ToString ());
1749 document.FormatText (line, rtf_cursor_x + 1, line, rtf_cursor_x + 1 + length,
1750 font, rtf_style.rtf_color, Color.Empty,
1751 FormatSpecified.Font | FormatSpecified.Color);
1754 document.Split (line, rtf_cursor_x + length);
1755 line = document.GetLine (rtf_cursor_y);
1756 line.ending = LineEnding.Rich;
1758 if (line.Text.EndsWith ("\n") == false)
1767 rtf_cursor_x += length;
1769 rtf_line.Length = 0; // Empty line
1772 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y) {
1777 InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
1780 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y, out int to_x, out int to_y, out int chars) {
1783 rtf = new RTF.RTF(data);
1786 rtf.ClassCallback[RTF.TokenClass.Text] = new RTF.ClassDelegate(HandleText);
1787 rtf.ClassCallback[RTF.TokenClass.Control] = new RTF.ClassDelegate(HandleControl);
1788 rtf.ClassCallback[RTF.TokenClass.Group] = new RTF.ClassDelegate(HandleGroup);
1792 rtf_line = new StringBuilder();
1793 rtf_style.rtf_color = Color.Empty;
1794 rtf_style.rtf_rtffont_size = (int)this.Font.Size;
1795 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1796 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1797 rtf_style.rtf_rtffont = null;
1798 rtf_cursor_x = cursor_x;
1799 rtf_cursor_y = cursor_y;
1801 rtf.DefaultFont(this.Font.Name);
1803 rtf_text_map = new RTF.TextMap();
1804 RTF.TextMap.SetupStandardTable(rtf_text_map.Table);
1806 document.SuspendRecalc ();
1809 rtf.Read(); // That's it
1810 FlushText(rtf, false);
1815 catch (RTF.RTFException e) {
1819 // Seems to be plain text or broken RTF
1820 Console.WriteLine("RTF Parsing failure: {0}", e.Message);
1823 to_x = rtf_cursor_x;
1824 to_y = rtf_cursor_y;
1827 // clear the section stack if it was used
1828 if (rtf_section_stack != null)
1829 rtf_section_stack.Clear();
1831 document.RecalculateDocument(CreateGraphicsInternal(), cursor_y, document.Lines, false);
1832 document.ResumeRecalc (true);
1834 document.Invalidate (document.GetLine(cursor_y), 0, document.GetLine(document.Lines), -1);
1837 private void RichTextBox_HScrolled(object sender, EventArgs e) {
1841 private void RichTextBox_VScrolled(object sender, EventArgs e) {
1845 private void PointToTagPos(Point pt, out LineTag tag, out int pos) {
1850 if (p.X >= document.ViewPortWidth) {
1851 p.X = document.ViewPortWidth - 1;
1852 } else if (p.X < 0) {
1856 if (p.Y >= document.ViewPortHeight) {
1857 p.Y = document.ViewPortHeight - 1;
1858 } else if (p.Y < 0) {
1862 tag = document.FindCursor(p.X + document.ViewPortX, p.Y + document.ViewPortY, out pos);
1865 private void EmitRTFFontProperties(StringBuilder rtf, int prev_index, int font_index, Font prev_font, Font font) {
1866 if (prev_index != font_index) {
1867 rtf.Append(String.Format("\\f{0}", font_index)); // Font table entry
1870 if ((prev_font == null) || (prev_font.Size != font.Size)) {
1871 rtf.Append(String.Format("\\fs{0}", (int)(font.Size * 2))); // Font size
1874 if ((prev_font == null) || (font.Bold != prev_font.Bold)) {
1878 if (prev_font != null) {
1884 if ((prev_font == null) || (font.Italic != prev_font.Italic)) {
1888 if (prev_font != null) {
1894 if ((prev_font == null) || (font.Strikeout != prev_font.Strikeout)) {
1895 if (font.Strikeout) {
1896 rtf.Append("\\strike");
1898 if (prev_font != null) {
1899 rtf.Append("\\strike0");
1904 if ((prev_font == null) || (font.Underline != prev_font.Underline)) {
1905 if (font.Underline) {
1908 if (prev_font != null) {
1909 rtf.Append("\\ul0");
1915 [MonoTODO("Emit unicode and other special characters properly")]
1916 private void EmitRTFText(StringBuilder rtf, string text) {
1920 // start_pos and end_pos are 0-based
1921 private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
1935 sb = new StringBuilder();
1936 fonts = new ArrayList(10);
1937 colors = new ArrayList(10);
1939 // Two runs, first we parse to determine tables;
1940 // and unlike most of our processing here we work on tags
1943 line_no = start_line.line_no;
1946 // Add default font and color; to optimize document content we don't
1947 // use this.Font and this.ForeColor but the font/color from the first tag
1948 tag = LineTag.FindTag(start_line, pos);
1951 fonts.Add(font.Name);
1954 while (line_no <= end_line.line_no) {
1955 line = document.GetLine(line_no);
1956 tag = LineTag.FindTag(line, pos);
1958 if (line_no != end_line.line_no) {
1959 line_len = line.text.Length;
1964 while (pos < line_len) {
1965 if (tag.Font.Name != font.Name) {
1967 if (!fonts.Contains(font.Name)) {
1968 fonts.Add(font.Name);
1972 if (tag.Color != color) {
1974 if (!colors.Contains(color)) {
1979 pos = tag.Start + tag.Length - 1;
1986 // We have the tables, emit the header
1987 sb.Append("{\\rtf1\\ansi");
1988 sb.Append("\\ansicpg1252"); // FIXME - is this correct?
1991 sb.Append(String.Format("\\deff{0}", fonts.IndexOf(this.Font.Name)));
1994 sb.Append("\\deflang1033\n"); // FIXME - always 1033?
1996 // Emit the font table
1997 sb.Append("{\\fonttbl");
1998 for (i = 0; i < fonts.Count; i++) {
1999 sb.Append(String.Format("{{\\f{0}", i)); // {Font
2000 sb.Append("\\fnil"); // Family
2001 sb.Append("\\fcharset0 "); // Charset ANSI<space>
2002 sb.Append((string)fonts[i]); // Font name
2003 sb.Append(";}"); // }
2007 // Emit the color table (if needed)
2008 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))) {
2009 sb.Append("{\\colortbl "); // Header and NO! default color
2010 for (i = 0; i < colors.Count; i++) {
2011 sb.Append(String.Format("\\red{0}", ((Color)colors[i]).R));
2012 sb.Append(String.Format("\\green{0}", ((Color)colors[i]).G));
2013 sb.Append(String.Format("\\blue{0}", ((Color)colors[i]).B));
2019 sb.Append("{\\*\\generator Mono RichTextBox;}");
2020 // Emit initial paragraph settings
2021 tag = LineTag.FindTag(start_line, start_pos);
2022 sb.Append("\\pard"); // Reset to default paragraph properties
2023 EmitRTFFontProperties(sb, -1, fonts.IndexOf(tag.Font.Name), null, tag.Font); // Font properties
2024 sb.Append(" "); // Space separator
2027 color = (Color)colors[0];
2029 line_no = start_line.line_no;
2032 while (line_no <= end_line.line_no) {
2033 line = document.GetLine(line_no);
2034 tag = LineTag.FindTag(line, pos);
2036 if (line_no != end_line.line_no) {
2037 line_len = line.text.Length;
2042 while (pos < line_len) {
2045 if (tag.Font != font) {
2046 EmitRTFFontProperties(sb, fonts.IndexOf(font.Name), fonts.IndexOf(tag.Font.Name), font, tag.Font);
2050 if (tag.Color != color) {
2052 sb.Append(String.Format("\\cf{0}", colors.IndexOf(color)));
2054 if (length != sb.Length) {
2055 sb.Append(" "); // Emit space to separate keywords from text
2058 // Emit the string itself
2059 if (line_no != end_line.line_no) {
2060 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2062 if (end_pos < (tag.Start + tag.Length - 1)) {
2063 // Emit partial tag only, end_pos is inside this tag
2064 EmitRTFText(sb, tag.Line.text.ToString(pos, end_pos - pos));
2066 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2070 pos = tag.Start + tag.Length - 1;
2073 if (pos >= line.text.Length) {
2074 if (line.ending != LineEnding.Wrap) {
2075 sb.Append("\\par\n");
2086 #endregion // Private Methods