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 [MonoTODO ("Value not respected, always true")]
177 [DefaultValue(false)]
178 public bool AutoWordSelection {
179 get { return auto_word_select; }
180 set { auto_word_select = value; }
184 [EditorBrowsable(EditorBrowsableState.Never)]
185 public override System.Drawing.Image BackgroundImage {
186 get { return base.BackgroundImage; }
187 set { base.BackgroundImage = value; }
192 [EditorBrowsable (EditorBrowsableState.Never)]
193 public override ImageLayout BackgroundImageLayout {
194 get { return base.BackgroundImageLayout; }
195 set { base.BackgroundImageLayout = value; }
201 public int BulletIndent {
203 return bullet_indent;
207 bullet_indent = value;
212 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
213 public bool CanRedo {
215 return document.undo.CanRedo;
220 public bool DetectUrls {
221 get { return base.EnableLinks; }
222 set { base.EnableLinks = value; }
227 [DefaultValue (false)]
228 public bool EnableAutoDragDrop {
229 get { return enable_auto_drag_drop; }
230 set { enable_auto_drag_drop = value; }
234 public override Font Font {
245 if (PreferredHeight != Height) {
246 Height = PreferredHeight;
252 // Font changes always set the whole doc to that font
253 start = document.GetLine(1);
254 end = document.GetLine(document.Lines);
255 document.FormatText(start, 1, end, end.text.Length + 1, base.Font, Color.Empty, Color.Empty, FormatSpecified.Font);
260 public override Color ForeColor {
262 return base.ForeColor;
266 base.ForeColor = value;
273 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
274 public RichTextBoxLanguageOptions LanguageOption {
275 get { return language_option; }
276 set { language_option = value; }
280 [DefaultValue(Int32.MaxValue)]
281 public override int MaxLength {
283 return base.max_length;
287 base.max_length = value;
292 public override bool Multiline {
294 return base.Multiline;
298 base.Multiline = value;
303 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
305 public string RedoActionName {
307 return document.undo.RedoActionName;
314 [DefaultValue (true)]
315 [EditorBrowsable (EditorBrowsableState.Never)]
316 public bool RichTextShortcutsEnabled {
317 get { return rich_text_shortcuts_enabled; }
318 set { rich_text_shortcuts_enabled = value; }
324 [MonoTODO("Teach TextControl.RecalculateLine to consider the right margin as well")]
325 public int RightMargin {
331 margin_right = value;
336 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
338 [RefreshProperties (RefreshProperties.All)]
347 start_line = document.GetLine(1);
348 end_line = document.GetLine(document.Lines);
349 return GenerateRTF(start_line, 0, end_line, end_line.text.Length).ToString();
356 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
358 InsertRTFFromStream(data, 0, 1);
366 [DefaultValue(RichTextBoxScrollBars.Both)]
368 public RichTextBoxScrollBars ScrollBars {
374 if (!Enum.IsDefined (typeof (RichTextBoxScrollBars), value))
375 throw new InvalidEnumArgumentException ("value", (int) value,
376 typeof (RichTextBoxScrollBars));
378 if (value != scrollbars) {
380 CalculateDocument ();
387 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
388 public string SelectedRtf {
390 return GenerateRTF(document.selection_start.line, document.selection_start.pos, document.selection_end.line, document.selection_end.pos).ToString();
402 if (document.selection_visible) {
403 document.ReplaceSelection("", false);
406 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
408 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
409 InsertRTFFromStream(data, document.selection_start.pos, document.selection_start.line.line_no, out x, out y, out chars);
412 document.CharIndexToLineTag(sel_start + chars + (y - document.selection_start.line.line_no) * 2, out line, out tag, out sel_start);
413 document.SetSelection(line, sel_start);
414 document.PositionCaret(line, sel_start);
415 document.DisplayCaret();
417 OnTextChanged(EventArgs.Empty);
423 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
424 public override string SelectedText {
426 return base.SelectedText;
430 base.SelectedText = value;
435 [DefaultValue(HorizontalAlignment.Left)]
436 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
437 public HorizontalAlignment SelectionAlignment {
439 HorizontalAlignment align;
444 start = document.ParagraphStart(document.selection_start.line);
445 align = start.alignment;
447 end = document.ParagraphEnd(document.selection_end.line);
452 if (line.alignment != align) {
453 return HorizontalAlignment.Left;
459 line = document.GetLine(line.line_no + 1);
470 start = document.ParagraphStart(document.selection_start.line);
472 end = document.ParagraphEnd(document.selection_end.line);
477 line.alignment = value;
482 line = document.GetLine(line.line_no + 1);
484 this.CalculateDocument();
491 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
492 public Color SelectionBackColor {
493 get { return selection_back_color; }
494 set { selection_back_color = value; }
499 [DefaultValue(false)]
500 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
502 public bool SelectionBullet {
513 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
515 public int SelectionCharOffset {
525 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
526 public Color SelectionColor {
533 if (selection_length > 0) {
534 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
535 end = document.selection_start.line.FindTag (document.selection_end.pos);
537 start = document.selection_start.line.FindTag (document.selection_start.pos);
544 while (tag != null) {
546 if (!color.Equals (tag.Color))
552 tag = document.NextTag (tag);
559 if (value == Color.Empty)
560 value = DefaultForeColor;
565 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
566 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
568 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
569 document.selection_end.line, document.selection_end.pos + 1, null,
570 value, Color.Empty, FormatSpecified.Color);
572 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
573 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
575 document.UpdateView(document.selection_start.line, 0);
577 //Re-Align the caret in case its changed size or position
578 //probably not necessary here
579 document.AlignCaret(false);
584 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
585 public Font SelectionFont {
592 if (selection_length > 0) {
593 start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
594 end = document.selection_start.line.FindTag (document.selection_end.pos);
596 start = document.selection_start.line.FindTag (document.selection_start.pos);
602 if (selection_length > 1) {
604 while (tag != null) {
606 if (!font.Equals(tag.Font))
612 tag = document.NextTag (tag);
623 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
624 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
626 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
627 document.selection_end.line, document.selection_end.pos + 1, value,
628 Color.Empty, Color.Empty, FormatSpecified.Font);
630 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
631 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
633 document.UpdateView(document.selection_start.line, 0);
634 //Re-Align the caret in case its changed size or position
635 Document.AlignCaret (false);
642 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
644 public int SelectionHangingIndent {
655 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
657 public int SelectionIndent {
667 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
668 public override int SelectionLength {
670 return base.SelectionLength;
674 base.SelectionLength = value;
679 [DefaultValue(false)]
680 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
682 public bool SelectionProtected {
693 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
695 public int SelectionRightIndent {
705 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
707 public int[] SelectionTabs {
717 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
718 public RichTextBoxSelectionTypes SelectionType {
720 if (document.selection_start == document.selection_end) {
721 return RichTextBoxSelectionTypes.Empty;
725 if (SelectedText.Length > 1) {
726 return RichTextBoxSelectionTypes.MultiChar | RichTextBoxSelectionTypes.Text;
729 return RichTextBoxSelectionTypes.Text;
733 [DefaultValue(false)]
735 public bool ShowSelectionMargin {
746 [RefreshProperties (RefreshProperties.All)]
748 public override string Text {
759 public override int TextLength {
761 return base.TextLength;
766 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
767 public string UndoActionName {
769 return document.undo.UndoActionName;
775 public float ZoomFactor {
784 #endregion // Public Instance Properties
786 #region Protected Instance Properties
787 protected override CreateParams CreateParams {
789 return base.CreateParams;
793 protected override Size DefaultSize {
795 return new Size(100, 96);
798 #endregion // Protected Instance Properties
800 #region Public Instance Methods
801 public bool CanPaste(DataFormats.Format clipFormat) {
802 if ((clipFormat.Name == DataFormats.Rtf) ||
803 (clipFormat.Name == DataFormats.Text) ||
804 (clipFormat.Name == DataFormats.UnicodeText)) {
810 public int Find(char[] characterSet) {
811 return Find(characterSet, -1, -1);
814 public int Find(char[] characterSet, int start) {
815 return Find(characterSet, start, -1);
818 public int Find(char[] characterSet, int start, int end) {
819 Document.Marker start_mark;
820 Document.Marker end_mark;
821 Document.Marker result;
824 document.GetMarker(out start_mark, true);
830 start_mark = new Document.Marker();
832 document.CharIndexToLineTag(start, out line, out tag, out pos);
833 start_mark.line = line;
834 start_mark.tag = tag;
835 start_mark.pos = pos;
839 document.GetMarker(out end_mark, false);
845 end_mark = new Document.Marker();
847 document.CharIndexToLineTag(end, out line, out tag, out pos);
848 end_mark.line = line;
853 if (document.FindChars(characterSet, start_mark, end_mark, out result)) {
854 return document.LineTagToCharIndex(result.line, result.pos);
860 public int Find(string str) {
861 return Find(str, -1, -1, RichTextBoxFinds.None);
864 public int Find(string str, int start, int end, RichTextBoxFinds options) {
865 Document.Marker start_mark;
866 Document.Marker end_mark;
867 Document.Marker result;
870 document.GetMarker(out start_mark, true);
876 start_mark = new Document.Marker();
878 document.CharIndexToLineTag(start, out line, out tag, out pos);
880 start_mark.line = line;
881 start_mark.tag = tag;
882 start_mark.pos = pos;
886 document.GetMarker(out end_mark, false);
892 end_mark = new Document.Marker();
894 document.CharIndexToLineTag(end, out line, out tag, out pos);
896 end_mark.line = line;
901 if (document.Find(str, start_mark, end_mark, out result, options)) {
902 return document.LineTagToCharIndex(result.line, result.pos);
908 public int Find(string str, int start, RichTextBoxFinds options) {
909 return Find(str, start, -1, options);
912 public int Find(string str, RichTextBoxFinds options) {
913 return Find(str, -1, -1, options);
918 public char GetCharFromPosition(Point pt) {
922 PointToTagPos(pt, out tag, out pos);
924 if (pos >= tag.Line.text.Length) {
928 return tag.Line.text[pos];
931 internal override char GetCharFromPositionInternal (Point p)
936 PointToTagPos (p, out tag, out pos);
938 if (pos >= tag.Line.text.Length)
941 return tag.Line.text[pos];
949 int GetCharIndexFromPosition(Point pt) {
953 PointToTagPos(pt, out tag, out pos);
955 return document.LineTagToCharIndex(tag.Line, pos);
962 int GetLineFromCharIndex(int index) {
967 document.CharIndexToLineTag(index, out line, out tag, out pos);
969 return line.LineNo - 1;
976 Point GetPositionFromCharIndex(int index) {
981 document.CharIndexToLineTag(index, out line, out tag, out pos);
983 return new Point((int)line.widths[pos] + 1, line.Y + 1);
986 public void LoadFile(System.IO.Stream data, RichTextBoxStreamType fileType) {
990 // FIXME - ignoring unicode
991 if (fileType == RichTextBoxStreamType.PlainText) {
996 sb = new StringBuilder ((int) data.Length);
997 buffer = new char [1024];
999 throw new IOException("Not enough memory to load document");
1002 StreamReader sr = new StreamReader (data, Encoding.Default, true);
1003 int charsRead = sr.Read (buffer, 0, buffer.Length);
1004 while (charsRead > 0) {
1005 sb.Append (buffer, 0, charsRead);
1006 charsRead = sr.Read (buffer, 0, buffer.Length);
1008 base.Text = sb.ToString();
1012 InsertRTFFromStream(data, 0, 1);
1014 document.PositionCaret (document.GetLine (1), 0);
1015 document.SetSelectionToCaret (true);
1019 [MonoTODO("Make smarter RTF detection?")]
1020 public void LoadFile(string path) {
1021 if (path.EndsWith(".rtf")) {
1022 LoadFile(path, RichTextBoxStreamType.RichText);
1024 LoadFile(path, RichTextBoxStreamType.PlainText);
1028 public void LoadFile(string path, RichTextBoxStreamType fileType) {
1035 data = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024);
1037 LoadFile(data, fileType);
1040 catch (Exception ex) {
1041 throw new IOException("Could not open file " + path, ex);
1051 public void Paste(DataFormats.Format clipFormat) {
1052 base.Paste(Clipboard.GetDataObject(), clipFormat, false);
1057 document.undo.Redo ();
1060 public void SaveFile(Stream data, RichTextBoxStreamType fileType) {
1066 if (fileType == RichTextBoxStreamType.UnicodePlainText) {
1067 encoding = Encoding.Unicode;
1069 encoding = Encoding.ASCII;
1073 case RichTextBoxStreamType.PlainText:
1074 case RichTextBoxStreamType.TextTextOleObjs:
1075 case RichTextBoxStreamType.UnicodePlainText: {
1077 bytes = encoding.GetBytes(document.Root.text.ToString());
1078 data.Write(bytes, 0, bytes.Length);
1082 for (i = 1; i < document.Lines; i++) {
1083 bytes = encoding.GetBytes(document.GetLine(i).text.ToString() + Environment.NewLine);
1084 data.Write(bytes, 0, bytes.Length);
1086 bytes = encoding.GetBytes(document.GetLine(document.Lines).text.ToString());
1087 data.Write(bytes, 0, bytes.Length);
1092 // If we're here we're saving RTF
1099 start_line = document.GetLine(1);
1100 end_line = document.GetLine(document.Lines);
1101 rtf = GenerateRTF(start_line, 0, end_line, end_line.text.Length);
1103 bytes = new Byte[4096];
1105 // Let's chunk it so we don't use up all memory...
1106 for (i = 0; i < total; i += 1024) {
1107 if ((i + 1024) < total) {
1108 current = encoding.GetBytes(rtf.ToString(i, 1024), 0, 1024, bytes, 0);
1110 current = total - i;
1111 current = encoding.GetBytes(rtf.ToString(i, current), 0, current, bytes, 0);
1113 data.Write(bytes, 0, current);
1117 public void SaveFile(string path) {
1118 if (path.EndsWith(".rtf")) {
1119 SaveFile(path, RichTextBoxStreamType.RichText);
1121 SaveFile(path, RichTextBoxStreamType.PlainText);
1125 public void SaveFile(string path, RichTextBoxStreamType fileType) {
1131 data = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1024, false);
1132 SaveFile(data, fileType);
1136 // throw new IOException("Could not write document to file " + path);
1147 [EditorBrowsable (EditorBrowsableState.Never)]
1148 public new void DrawToBitmap (Bitmap bitmap, Rectangle clip)
1150 Graphics dc = Graphics.FromImage (bitmap);
1152 if (backcolor_set || (Enabled && !read_only)) {
1153 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), clip);
1155 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (ThemeEngine.Current.ColorControl), clip);
1158 // Draw the viewable document
1159 document.Draw (dc, clip);
1163 #endregion // Public Instance Methods
1165 #region Protected Instance Methods
1166 protected virtual object CreateRichEditOleCallback() {
1167 throw new NotImplementedException();
1170 protected override void OnBackColorChanged(EventArgs e) {
1171 base.OnBackColorChanged (e);
1174 protected virtual void OnContentsResized(ContentsResizedEventArgs e) {
1175 ContentsResizedEventHandler eh = (ContentsResizedEventHandler)(Events [ContentsResizedEvent]);
1180 protected override void OnContextMenuChanged(EventArgs e) {
1181 base.OnContextMenuChanged (e);
1184 protected override void OnHandleCreated(EventArgs e) {
1185 base.OnHandleCreated (e);
1188 protected override void OnHandleDestroyed(EventArgs e) {
1189 base.OnHandleDestroyed (e);
1192 protected virtual void OnHScroll(EventArgs e) {
1193 EventHandler eh = (EventHandler)(Events [HScrollEvent]);
1198 [MonoTODO("Determine when to call this")]
1199 protected virtual void OnImeChange(EventArgs e) {
1200 EventHandler eh = (EventHandler)(Events [ImeChangeEvent]);
1205 protected virtual void OnLinkClicked(LinkClickedEventArgs e) {
1206 LinkClickedEventHandler eh = (LinkClickedEventHandler)(Events [LinkClickedEvent]);
1211 protected virtual void OnProtected(EventArgs e) {
1212 EventHandler eh = (EventHandler)(Events [ProtectedEvent]);
1217 protected override void OnRightToLeftChanged(EventArgs e) {
1218 base.OnRightToLeftChanged (e);
1221 protected virtual void OnSelectionChanged(EventArgs e) {
1222 EventHandler eh = (EventHandler)(Events [SelectionChangedEvent]);
1228 protected override void OnSystemColorsChanged(EventArgs e) {
1229 base.OnSystemColorsChanged (e);
1232 protected override void OnTextChanged(EventArgs e) {
1233 base.OnTextChanged (e);
1237 protected virtual void OnVScroll(EventArgs e) {
1238 EventHandler eh = (EventHandler)(Events [VScrollEvent]);
1243 protected override void WndProc(ref Message m) {
1244 base.WndProc (ref m);
1248 protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
1250 return base.ProcessCmdKey (ref msg, keyData);
1253 #endregion // Protected Instance Methods
1256 static object ContentsResizedEvent = new object ();
1257 static object HScrollEvent = new object ();
1258 static object ImeChangeEvent = new object ();
1259 static object LinkClickedEvent = new object ();
1260 static object ProtectedEvent = new object ();
1261 static object SelectionChangedEvent = new object ();
1262 static object VScrollEvent = new object ();
1265 [EditorBrowsable(EditorBrowsableState.Never)]
1266 public new event EventHandler BackgroundImageChanged {
1267 add { base.BackgroundImageChanged += value; }
1268 remove { base.BackgroundImageChanged -= value; }
1273 [EditorBrowsable (EditorBrowsableState.Never)]
1274 public new event EventHandler BackgroundImageLayoutChanged {
1275 add { base.BackgroundImageLayoutChanged += value; }
1276 remove { base.BackgroundImageLayoutChanged -= value; }
1280 public event ContentsResizedEventHandler ContentsResized {
1281 add { Events.AddHandler (ContentsResizedEvent, value); }
1282 remove { Events.RemoveHandler (ContentsResizedEvent, value); }
1287 [EditorBrowsable(EditorBrowsableState.Never)]
1288 public new event EventHandler DoubleClick {
1289 add { base.DoubleClick += value; }
1290 remove { base.DoubleClick -= value; }
1296 [EditorBrowsable(EditorBrowsableState.Never)]
1298 public new event DragEventHandler DragDrop {
1299 add { base.DragDrop += value; }
1300 remove { base.DragDrop -= value; }
1305 [EditorBrowsable(EditorBrowsableState.Never)]
1307 public new event DragEventHandler DragEnter {
1308 add { base.DragEnter += value; }
1309 remove { base.DragEnter -= value; }
1313 [EditorBrowsable(EditorBrowsableState.Never)]
1314 public new event EventHandler DragLeave {
1315 add { base.DragLeave += value; }
1316 remove { base.DragLeave -= value; }
1321 [EditorBrowsable(EditorBrowsableState.Never)]
1322 public new event DragEventHandler DragOver {
1323 add { base.DragOver += value; }
1324 remove { base.DragOver -= value; }
1329 [EditorBrowsable(EditorBrowsableState.Never)]
1330 public new event GiveFeedbackEventHandler GiveFeedback {
1331 add { base.GiveFeedback += value; }
1332 remove { base.GiveFeedback -= value; }
1335 public event EventHandler HScroll {
1336 add { Events.AddHandler (HScrollEvent, value); }
1337 remove { Events.RemoveHandler (HScrollEvent, value); }
1340 public event EventHandler ImeChange {
1341 add { Events.AddHandler (ImeChangeEvent, value); }
1342 remove { Events.RemoveHandler (ImeChangeEvent, value); }
1345 public event LinkClickedEventHandler LinkClicked {
1346 add { Events.AddHandler (LinkClickedEvent, value); }
1347 remove { Events.RemoveHandler (LinkClickedEvent, value); }
1350 public event EventHandler Protected {
1351 add { Events.AddHandler (ProtectedEvent, value); }
1352 remove { Events.RemoveHandler (ProtectedEvent, value); }
1356 [EditorBrowsable(EditorBrowsableState.Never)]
1357 public new event QueryContinueDragEventHandler QueryContinueDrag {
1358 add { base.QueryContinueDrag += value; }
1359 remove { base.QueryContinueDrag -= value; }
1362 [MonoTODO("Currently does not ever fire")]
1363 public event EventHandler SelectionChanged {
1364 add { Events.AddHandler (SelectionChangedEvent, value); }
1365 remove { Events.RemoveHandler (SelectionChangedEvent, value); }
1368 public event EventHandler VScroll {
1369 add { Events.AddHandler (VScrollEvent, value); }
1370 remove { Events.RemoveHandler (VScrollEvent, value); }
1372 #endregion // Events
1374 #region Private Methods
1376 internal override void SelectWord ()
1378 document.ExpandSelection(CaretSelection.Word, false);
1381 private class RtfSectionStyle : ICloneable {
1382 internal Color rtf_color;
1383 internal RTF.Font rtf_rtffont;
1384 internal int rtf_rtffont_size;
1385 internal FontStyle rtf_rtfstyle;
1386 internal HorizontalAlignment rtf_rtfalign;
1387 internal int rtf_par_line_left_indent;
1389 public object Clone ()
1391 RtfSectionStyle new_style = new RtfSectionStyle ();
1393 new_style.rtf_color = rtf_color;
1394 new_style.rtf_par_line_left_indent = rtf_par_line_left_indent;
1395 new_style.rtf_rtfalign = rtf_rtfalign;
1396 new_style.rtf_rtffont = rtf_rtffont;
1397 new_style.rtf_rtffont_size = rtf_rtffont_size;
1398 new_style.rtf_rtfstyle = rtf_rtfstyle;
1404 // To allow us to keep track of the sections and revert formatting
1405 // as we go in and out of sections of the document.
1406 private void HandleGroup (RTF.RTF rtf)
1408 //start group - save the current formatting on to a stack
1409 //end group - go back to the formatting at the current group
1410 if (rtf_section_stack == null) {
1411 rtf_section_stack = new Stack ();
1414 if (rtf.Major == RTF.Major.BeginGroup) {
1415 rtf_section_stack.Push (rtf_style.Clone ());
1416 } else if (rtf.Major == RTF.Major.EndGroup) {
1417 if (rtf_section_stack.Count > 0) {
1418 FlushText (rtf, false);
1420 rtf_style = (RtfSectionStyle) rtf_section_stack.Pop ();
1425 [MonoTODO("Add QuadJust support for justified alignment")]
1426 private void HandleControl(RTF.RTF rtf) {
1428 case RTF.Major.Unicode: {
1430 case RTF.Minor.UnicodeCharBytes: {
1431 rtf_skip_width = rtf.Param;
1435 case RTF.Minor.UnicodeChar: {
1436 rtf_skip_count += rtf_skip_width;
1437 rtf_line.Append((char)rtf.Param);
1444 case RTF.Major.Destination: {
1445 // Console.Write("[Got Destination control {0}]", rtf.Minor);
1450 case RTF.Major.PictAttr:
1451 if (rtf.Picture != null && rtf.Picture.IsValid ()) {
1452 Line line = document.GetLine (rtf_cursor_y);
1453 document.InsertPicture (line, 0, rtf.Picture);
1456 FlushText (rtf, true);
1461 case RTF.Major.CharAttr: {
1463 case RTF.Minor.ForeColor: {
1464 System.Windows.Forms.RTF.Color color;
1466 color = System.Windows.Forms.RTF.Color.GetColor(rtf, rtf.Param);
1468 if (color != null) {
1469 FlushText(rtf, false);
1470 if (color.Red == -1 && color.Green == -1 && color.Blue == -1) {
1471 this.rtf_style.rtf_color = ForeColor;
1473 this.rtf_style.rtf_color = Color.FromArgb(color.Red, color.Green, color.Blue);
1475 FlushText (rtf, false);
1480 case RTF.Minor.FontSize: {
1481 FlushText(rtf, false);
1482 this.rtf_style.rtf_rtffont_size = rtf.Param / 2;
1486 case RTF.Minor.FontNum: {
1487 System.Windows.Forms.RTF.Font font;
1489 font = System.Windows.Forms.RTF.Font.GetFont(rtf, rtf.Param);
1491 FlushText(rtf, false);
1492 this.rtf_style.rtf_rtffont = font;
1497 case RTF.Minor.Plain: {
1498 FlushText(rtf, false);
1499 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1503 case RTF.Minor.Bold: {
1504 FlushText(rtf, false);
1505 if (rtf.Param == RTF.RTF.NoParam) {
1506 rtf_style.rtf_rtfstyle |= FontStyle.Bold;
1508 rtf_style.rtf_rtfstyle &= ~FontStyle.Bold;
1513 case RTF.Minor.Italic: {
1514 FlushText(rtf, false);
1515 if (rtf.Param == RTF.RTF.NoParam) {
1516 rtf_style.rtf_rtfstyle |= FontStyle.Italic;
1518 rtf_style.rtf_rtfstyle &= ~FontStyle.Italic;
1523 case RTF.Minor.StrikeThru: {
1524 FlushText(rtf, false);
1525 if (rtf.Param == RTF.RTF.NoParam) {
1526 rtf_style.rtf_rtfstyle |= FontStyle.Strikeout;
1528 rtf_style.rtf_rtfstyle &= ~FontStyle.Strikeout;
1533 case RTF.Minor.Underline: {
1534 FlushText(rtf, false);
1535 if (rtf.Param == RTF.RTF.NoParam) {
1536 rtf_style.rtf_rtfstyle |= FontStyle.Underline;
1538 rtf_style.rtf_rtfstyle = rtf_style.rtf_rtfstyle & ~FontStyle.Underline;
1543 case RTF.Minor.NoUnderline: {
1544 FlushText(rtf, false);
1545 rtf_style.rtf_rtfstyle &= ~FontStyle.Underline;
1552 case RTF.Major.ParAttr: {
1553 switch (rtf.Minor) {
1555 case RTF.Minor.ParDef:
1556 FlushText (rtf, false);
1557 rtf_style.rtf_par_line_left_indent = 0;
1558 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1561 case RTF.Minor.LeftIndent:
1562 rtf_style.rtf_par_line_left_indent = (int) (((float) rtf.Param / 1440.0F) * CreateGraphics ().DpiX + 0.5F);
1565 case RTF.Minor.QuadCenter:
1566 FlushText (rtf, false);
1567 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1570 case RTF.Minor.QuadJust:
1571 FlushText (rtf, false);
1572 rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1575 case RTF.Minor.QuadLeft:
1576 FlushText (rtf, false);
1577 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1580 case RTF.Minor.QuadRight:
1581 FlushText (rtf, false);
1582 rtf_style.rtf_rtfalign = HorizontalAlignment.Right;
1588 case RTF.Major.SpecialChar: {
1589 //Console.Write("[Got SpecialChar control {0}]", rtf.Minor);
1596 private void SpecialChar(RTF.RTF rtf) {
1598 case RTF.Minor.Page:
1599 case RTF.Minor.Sect:
1601 case RTF.Minor.Line:
1602 case RTF.Minor.Par: {
1603 FlushText(rtf, true);
1607 case RTF.Minor.Cell: {
1612 case RTF.Minor.NoBrkSpace: {
1617 case RTF.Minor.Tab: {
1618 rtf_line.Append ("\t");
1619 // FlushText (rtf, false);
1623 case RTF.Minor.NoReqHyphen:
1624 case RTF.Minor.NoBrkHyphen: {
1625 rtf_line.Append ("-");
1626 // FlushText (rtf, false);
1630 case RTF.Minor.Bullet: {
1631 Console.WriteLine("*");
1635 case RTF.Minor.WidowCtrl:
1638 case RTF.Minor.EmDash: {
1639 rtf_line.Append ("\u2014");
1643 case RTF.Minor.EnDash: {
1644 rtf_line.Append ("\u2013");
1648 case RTF.Minor.LQuote: {
1649 Console.Write("\u2018");
1653 case RTF.Minor.RQuote: {
1654 Console.Write("\u2019");
1658 case RTF.Minor.LDblQuote: {
1659 Console.Write("\u201C");
1663 case RTF.Minor.RDblQuote: {
1664 Console.Write("\u201D");
1669 // Console.WriteLine ("skipped special char: {0}", rtf.Minor);
1676 private void HandleText(RTF.RTF rtf) {
1677 if (rtf_skip_count > 0) {
1683 if ((RTF.StandardCharCode)rtf.Minor != RTF.StandardCharCode.nothing) {
1684 rtf_line.Append(rtf_text_map[(RTF.StandardCharCode)rtf.Minor]);
1686 if ((int)rtf.Major > 31 && (int)rtf.Major < 128) {
1687 rtf_line.Append((char)rtf.Major);
1689 //rtf_line.Append((char)rtf.Major);
1690 Console.Write("[Literal:0x{0:X2}]", (int)rtf.Major);
1694 rtf_line.Append (rtf.EncodedText);
1697 private void FlushText(RTF.RTF rtf, bool newline) {
1701 length = rtf_line.Length;
1702 if (!newline && (length == 0)) {
1706 if (rtf_style.rtf_rtffont == null) {
1707 // First font in table is default
1708 rtf_style.rtf_rtffont = System.Windows.Forms.RTF.Font.GetFont (rtf, 0);
1711 font = new Font (rtf_style.rtf_rtffont.Name, rtf_style.rtf_rtffont_size, rtf_style.rtf_rtfstyle);
1713 if (rtf_style.rtf_color == Color.Empty) {
1714 System.Windows.Forms.RTF.Color color;
1716 // First color in table is default
1717 color = System.Windows.Forms.RTF.Color.GetColor (rtf, 0);
1719 if ((color == null) || (color.Red == -1 && color.Green == -1 && color.Blue == -1)) {
1720 rtf_style.rtf_color = ForeColor;
1722 rtf_style.rtf_color = Color.FromArgb (color.Red, color.Green, color.Blue);
1727 rtf_chars += rtf_line.Length;
1731 if (rtf_cursor_x == 0) {
1732 if (newline && rtf_line.ToString ().EndsWith ("\n") == false)
1733 rtf_line.Append ("\n");
1735 document.Add (rtf_cursor_y, rtf_line.ToString (), rtf_style.rtf_rtfalign, font, rtf_style.rtf_color,
1736 newline ? LineEnding.Rich : LineEnding.Wrap);
1737 if (rtf_style.rtf_par_line_left_indent != 0) {
1738 Line line = document.GetLine (rtf_cursor_y);
1739 line.indent = rtf_style.rtf_par_line_left_indent;
1744 line = document.GetLine (rtf_cursor_y);
1745 line.indent = rtf_style.rtf_par_line_left_indent;
1746 if (rtf_line.Length > 0) {
1747 document.InsertString (line, rtf_cursor_x, rtf_line.ToString ());
1748 document.FormatText (line, rtf_cursor_x + 1, line, rtf_cursor_x + 1 + length,
1749 font, rtf_style.rtf_color, Color.Empty,
1750 FormatSpecified.Font | FormatSpecified.Color);
1753 document.Split (line, rtf_cursor_x + length);
1754 line = document.GetLine (rtf_cursor_y);
1755 line.ending = LineEnding.Rich;
1757 if (line.Text.EndsWith ("\n") == false)
1766 rtf_cursor_x += length;
1768 rtf_line.Length = 0; // Empty line
1771 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y) {
1776 InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
1779 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y, out int to_x, out int to_y, out int chars) {
1782 rtf = new RTF.RTF(data);
1785 rtf.ClassCallback[RTF.TokenClass.Text] = new RTF.ClassDelegate(HandleText);
1786 rtf.ClassCallback[RTF.TokenClass.Control] = new RTF.ClassDelegate(HandleControl);
1787 rtf.ClassCallback[RTF.TokenClass.Group] = new RTF.ClassDelegate(HandleGroup);
1791 rtf_line = new StringBuilder();
1792 rtf_style.rtf_color = Color.Empty;
1793 rtf_style.rtf_rtffont_size = (int)this.Font.Size;
1794 rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1795 rtf_style.rtf_rtfstyle = FontStyle.Regular;
1796 rtf_style.rtf_rtffont = null;
1797 rtf_cursor_x = cursor_x;
1798 rtf_cursor_y = cursor_y;
1800 rtf.DefaultFont(this.Font.Name);
1802 rtf_text_map = new RTF.TextMap();
1803 RTF.TextMap.SetupStandardTable(rtf_text_map.Table);
1805 document.SuspendRecalc ();
1808 rtf.Read(); // That's it
1809 FlushText(rtf, false);
1814 catch (RTF.RTFException e) {
1818 // Seems to be plain text or broken RTF
1819 Console.WriteLine("RTF Parsing failure: {0}", e.Message);
1822 to_x = rtf_cursor_x;
1823 to_y = rtf_cursor_y;
1826 // clear the section stack if it was used
1827 if (rtf_section_stack != null)
1828 rtf_section_stack.Clear();
1830 document.RecalculateDocument(CreateGraphicsInternal(), cursor_y, document.Lines, false);
1831 document.ResumeRecalc (true);
1833 document.Invalidate (document.GetLine(cursor_y), 0, document.GetLine(document.Lines), -1);
1836 private void RichTextBox_HScrolled(object sender, EventArgs e) {
1840 private void RichTextBox_VScrolled(object sender, EventArgs e) {
1844 private void PointToTagPos(Point pt, out LineTag tag, out int pos) {
1849 if (p.X >= document.ViewPortWidth) {
1850 p.X = document.ViewPortWidth - 1;
1851 } else if (p.X < 0) {
1855 if (p.Y >= document.ViewPortHeight) {
1856 p.Y = document.ViewPortHeight - 1;
1857 } else if (p.Y < 0) {
1861 tag = document.FindCursor(p.X + document.ViewPortX, p.Y + document.ViewPortY, out pos);
1864 private void EmitRTFFontProperties(StringBuilder rtf, int prev_index, int font_index, Font prev_font, Font font) {
1865 if (prev_index != font_index) {
1866 rtf.Append(String.Format("\\f{0}", font_index)); // Font table entry
1869 if ((prev_font == null) || (prev_font.Size != font.Size)) {
1870 rtf.Append(String.Format("\\fs{0}", (int)(font.Size * 2))); // Font size
1873 if ((prev_font == null) || (font.Bold != prev_font.Bold)) {
1877 if (prev_font != null) {
1883 if ((prev_font == null) || (font.Italic != prev_font.Italic)) {
1887 if (prev_font != null) {
1893 if ((prev_font == null) || (font.Strikeout != prev_font.Strikeout)) {
1894 if (font.Strikeout) {
1895 rtf.Append("\\strike");
1897 if (prev_font != null) {
1898 rtf.Append("\\strike0");
1903 if ((prev_font == null) || (font.Underline != prev_font.Underline)) {
1904 if (font.Underline) {
1907 if (prev_font != null) {
1908 rtf.Append("\\ul0");
1914 [MonoTODO("Emit unicode and other special characters properly")]
1915 private void EmitRTFText(StringBuilder rtf, string text) {
1919 // start_pos and end_pos are 0-based
1920 private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
1934 sb = new StringBuilder();
1935 fonts = new ArrayList(10);
1936 colors = new ArrayList(10);
1938 // Two runs, first we parse to determine tables;
1939 // and unlike most of our processing here we work on tags
1942 line_no = start_line.line_no;
1945 // Add default font and color; to optimize document content we don't
1946 // use this.Font and this.ForeColor but the font/color from the first tag
1947 tag = LineTag.FindTag(start_line, pos);
1950 fonts.Add(font.Name);
1953 while (line_no <= end_line.line_no) {
1954 line = document.GetLine(line_no);
1955 tag = LineTag.FindTag(line, pos);
1957 if (line_no != end_line.line_no) {
1958 line_len = line.text.Length;
1963 while (pos < line_len) {
1964 if (tag.Font.Name != font.Name) {
1966 if (!fonts.Contains(font.Name)) {
1967 fonts.Add(font.Name);
1971 if (tag.Color != color) {
1973 if (!colors.Contains(color)) {
1978 pos = tag.Start + tag.Length - 1;
1985 // We have the tables, emit the header
1986 sb.Append("{\\rtf1\\ansi");
1987 sb.Append("\\ansicpg1252"); // FIXME - is this correct?
1990 sb.Append(String.Format("\\deff{0}", fonts.IndexOf(this.Font.Name)));
1993 sb.Append("\\deflang1033\n"); // FIXME - always 1033?
1995 // Emit the font table
1996 sb.Append("{\\fonttbl");
1997 for (i = 0; i < fonts.Count; i++) {
1998 sb.Append(String.Format("{{\\f{0}", i)); // {Font
1999 sb.Append("\\fnil"); // Family
2000 sb.Append("\\fcharset0 "); // Charset ANSI<space>
2001 sb.Append((string)fonts[i]); // Font name
2002 sb.Append(";}"); // }
2006 // Emit the color table (if needed)
2007 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))) {
2008 sb.Append("{\\colortbl "); // Header and NO! default color
2009 for (i = 0; i < colors.Count; i++) {
2010 sb.Append(String.Format("\\red{0}", ((Color)colors[i]).R));
2011 sb.Append(String.Format("\\green{0}", ((Color)colors[i]).G));
2012 sb.Append(String.Format("\\blue{0}", ((Color)colors[i]).B));
2018 sb.Append("{\\*\\generator Mono RichTextBox;}");
2019 // Emit initial paragraph settings
2020 tag = LineTag.FindTag(start_line, start_pos);
2021 sb.Append("\\pard"); // Reset to default paragraph properties
2022 EmitRTFFontProperties(sb, -1, fonts.IndexOf(tag.Font.Name), null, tag.Font); // Font properties
2023 sb.Append(" "); // Space separator
2026 color = (Color)colors[0];
2028 line_no = start_line.line_no;
2031 while (line_no <= end_line.line_no) {
2032 line = document.GetLine(line_no);
2033 tag = LineTag.FindTag(line, pos);
2035 if (line_no != end_line.line_no) {
2036 line_len = line.text.Length;
2041 while (pos < line_len) {
2044 if (tag.Font != font) {
2045 EmitRTFFontProperties(sb, fonts.IndexOf(font.Name), fonts.IndexOf(tag.Font.Name), font, tag.Font);
2049 if (tag.Color != color) {
2051 sb.Append(String.Format("\\cf{0}", colors.IndexOf(color)));
2053 if (length != sb.Length) {
2054 sb.Append(" "); // Emit space to separate keywords from text
2057 // Emit the string itself
2058 if (line_no != end_line.line_no) {
2059 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2061 if (end_pos < (tag.Start + tag.Length - 1)) {
2062 // Emit partial tag only, end_pos is inside this tag
2063 EmitRTFText(sb, tag.Line.text.ToString(pos, end_pos - pos));
2065 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2069 pos = tag.Start + tag.Length - 1;
2072 if (pos >= line.text.Length) {
2073 if (line.ending != LineEnding.Wrap) {
2074 sb.Append("\\par\n");
2085 #endregion // Private Methods