2008-01-03 Jonathan Pobst <monkey@jpobst.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / RichTextBox.cs
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:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
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.
19 //
20 // Copyright (c) 2005-2006 Novell, Inc. (http://www.novell.com)
21 //
22 // Authors:
23 //      Peter Bartok    <pbartok@novell.com>
24 //
25 //
26
27 // #define DEBUG
28
29 using System;
30 using System.Collections;
31 using System.ComponentModel;
32 using System.Drawing;
33 using System.Drawing.Imaging;
34 using System.IO;
35 using System.Text;
36 using System.Runtime.InteropServices;
37 using RTF=System.Windows.Forms.RTF;
38
39 namespace System.Windows.Forms {
40 #if NET_2_0
41         [ClassInterface (ClassInterfaceType.AutoDispatch)]
42         [Docking (DockingBehavior.Ask)]
43         [ComVisible (true)]
44         [Designer ("System.Windows.Forms.Design.RichTextBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
45 #endif
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;
52                 internal float          zoom;
53                 private StringBuilder   rtf_line;
54
55                 private RtfSectionStyle rtf_style;      // Replaces individual style
56                                                         // properties so we can revert
57                 private Stack           rtf_section_stack;
58
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;
65
66 #if NET_2_0
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;
71 #endif
72                 #endregion      // Local Variables
73
74                 #region Public Constructors
75                 public RichTextBox() {
76                         accepts_return = true;
77                         auto_word_select = false;
78                         bullet_indent = 0;
79                         max_length = Int32.MaxValue;
80                         margin_right = 0;
81                         zoom = 1;
82                         base.Multiline = true;
83                         document.CRLFSize = 1;
84                         shortcuts_enabled = true;
85                         disabled_foreground_grey = false;
86                         base.EnableLinks = true;
87                         
88                         rtf_style = new RtfSectionStyle ();
89                         rtf_section_stack = null;
90
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;
96 #if NET_2_0
97                         backcolor_set = false;
98                         language_option = RichTextBoxLanguageOptions.AutoFontSizeAdjust;
99                         rich_text_shortcuts_enabled = true;
100                         selection_back_color = DefaultBackColor;
101 #endif
102                         ForeColor = ThemeEngine.Current.ColorWindowText;
103
104                         base.HScrolled += new EventHandler(RichTextBox_HScrolled);
105                         base.VScrolled += new EventHandler(RichTextBox_VScrolled);
106
107 #if NET_2_0
108                         SetStyle (ControlStyles.StandardDoubleClick, false);
109 #endif
110                 }
111                 #endregion      // Public Constructors
112
113                 #region Private & Internal Methods
114
115                 internal override void HandleLinkClicked (LinkRectangle link)
116                 {
117                         OnLinkClicked (new LinkClickedEventArgs (link.LinkTag.LinkText));
118                 }
119
120                 internal override Color ChangeBackColor (Color backColor)
121                 {
122                         if (backColor == Color.Empty) {
123 #if NET_2_0
124                                 backcolor_set = false;
125                                 if (!ReadOnly) {
126                                         backColor = SystemColors.Window;
127                                 }
128 #else
129                                 backColor = SystemColors.Window;
130 #endif
131                         }
132                         return backColor;
133                 }
134
135                 private void RichTextBox_LostFocus(object sender, EventArgs e) {
136                         Invalidate();
137                 }
138
139                 private void RichTextBox_GotFocus(object sender, EventArgs e) {
140                         Invalidate();
141                 }
142                 #endregion      // Private & Internal Methods
143
144                 #region Public Instance Properties
145 #if NET_2_0
146                 [Browsable (false)]
147 #endif
148                 public override bool AllowDrop {
149                         get {
150                                 return base.AllowDrop;
151                         }
152
153                         set {
154                                 base.AllowDrop = value;
155                         }
156                 }
157
158                 [DefaultValue(false)]
159 #if NET_2_0
160                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Visible)]
161                 [RefreshProperties (RefreshProperties.Repaint)]
162                 [EditorBrowsable (EditorBrowsableState.Never)]
163                 [Browsable (false)]
164 #else
165                 [Localizable(true)]
166 #endif
167                 public override bool AutoSize {
168                         get {
169                                 return auto_size;
170                         }
171
172                         set {
173                                 base.AutoSize = value;
174                         }
175                 }
176
177                 [DefaultValue(false)]
178                 public bool AutoWordSelection {
179                         get {
180                                 return auto_word_select;
181                         }
182
183                         set {
184                                 auto_word_select = true;
185                         }
186                 }
187
188                 [Browsable(false)]
189                 [EditorBrowsable(EditorBrowsableState.Never)]
190                 public override System.Drawing.Image BackgroundImage {
191                         get { return base.BackgroundImage; }
192                         set { base.BackgroundImage = value; }
193                 }
194
195 #if NET_2_0
196                 [Browsable (false)]
197                 [EditorBrowsable (EditorBrowsableState.Never)]
198                 public override ImageLayout BackgroundImageLayout {
199                         get { return base.BackgroundImageLayout; }
200                         set { base.BackgroundImageLayout = value; }
201                 }
202 #endif
203
204                 [DefaultValue(0)]
205                 [Localizable(true)]
206                 public int BulletIndent {
207                         get {
208                                 return bullet_indent;
209                         }
210
211                         set {
212                                 bullet_indent = value;
213                         }
214                 }
215
216                 [Browsable(false)]
217                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
218                 public bool CanRedo {
219                         get {
220                                 return document.undo.CanRedo;
221                         }
222                 }
223
224                 [DefaultValue(true)]
225                 public bool DetectUrls {
226                         get { return base.EnableLinks; }
227                         set { base.EnableLinks = value; }
228                 }
229
230 #if NET_2_0
231                 [MonoTODO ("Stub")]
232                 [DefaultValue (false)]
233                 public bool EnableAutoDragDrop {
234                         get { return enable_auto_drag_drop; }
235                         set { enable_auto_drag_drop = value; }
236                 }
237 #endif
238
239                 public override Font Font {
240                         get {
241                                 return base.Font;
242                         }
243
244                         set {
245                                 if (font != value) {
246                                         Line    start;
247                                         Line    end;
248
249                                         if (auto_size) {
250                                                 if (PreferredHeight != Height) {
251                                                         Height = PreferredHeight;
252                                                 }
253                                         }
254
255                                         base.Font = value;
256
257                                         // Font changes always set the whole doc to that font
258                                         start = document.GetLine(1);
259                                         end = document.GetLine(document.Lines);
260                                         document.FormatText(start, 1, end, end.text.Length + 1, base.Font, Color.Empty, Color.Empty, FormatSpecified.Font);
261                                 }
262                         }
263                 }
264
265                 public override Color ForeColor {
266                         get {
267                                 return base.ForeColor;
268                         }
269
270                         set {
271                                 base.ForeColor = value;
272                         }
273                 }
274
275 #if NET_2_0
276                 [MonoTODO ("Stub")]
277                 [Browsable (false)]
278                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
279                 public RichTextBoxLanguageOptions LanguageOption {
280                         get { return language_option; }
281                         set { language_option = value; }
282                 }
283 #endif
284
285                 [DefaultValue(Int32.MaxValue)]
286                 public override int MaxLength {
287                         get {
288                                 return base.max_length;
289                         }
290
291                         set {
292                                 base.max_length = value;
293                         }
294                 }
295
296                 [DefaultValue(true)]
297                 public override bool Multiline {
298                         get {
299                                 return base.Multiline;
300                         }
301
302                         set {
303                                 base.Multiline = value;
304                         }
305                 }
306
307                 [Browsable(false)]
308                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
309                 [MonoTODO]
310                 public string RedoActionName {
311                         get {
312                                 return document.undo.RedoActionName;
313                         }
314                 }
315
316 #if NET_2_0
317                 [MonoTODO ("Stub")]
318                 [Browsable (false)]
319                 [DefaultValue (true)]
320                 [EditorBrowsable (EditorBrowsableState.Never)]
321                 public bool RichTextShortcutsEnabled {
322                         get { return rich_text_shortcuts_enabled; }
323                         set { rich_text_shortcuts_enabled = value; }
324                 }
325 #endif
326
327                 [DefaultValue(0)]
328                 [Localizable(true)]
329                 [MonoTODO("Teach TextControl.RecalculateLine to consider the right margin as well")]
330                 public int RightMargin {
331                         get {
332                                 return margin_right;
333                         }
334
335                         set {
336                                 margin_right = value;
337                         }
338                 }
339
340                 [Browsable(false)]
341                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
342 #if NET_2_0
343                 [RefreshProperties (RefreshProperties.All)]
344 #else
345                 [DefaultValue("")]
346 #endif
347                 public string Rtf {
348                         get {
349                                 Line            start_line;
350                                 Line            end_line;
351
352                                 start_line = document.GetLine(1);
353                                 end_line = document.GetLine(document.Lines);
354                                 return GenerateRTF(start_line, 0, end_line, end_line.text.Length).ToString();
355                         }
356
357                         set {
358                                 MemoryStream    data;
359
360                                 document.Empty();
361                                 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
362
363                                 InsertRTFFromStream(data, 0, 1);
364
365                                 data.Close();
366
367                                 Invalidate();
368                         }
369                 }
370
371                 [DefaultValue(RichTextBoxScrollBars.Both)]
372                 [Localizable(true)]
373                 public RichTextBoxScrollBars ScrollBars {
374                         get {
375                                 return scrollbars;
376                         }
377
378                         set {
379                                 if (!Enum.IsDefined (typeof (RichTextBoxScrollBars), value))
380                                         throw new InvalidEnumArgumentException ("value", (int) value,
381                                                 typeof (RichTextBoxScrollBars));
382
383                                 if (value != scrollbars) {
384                                         scrollbars = value;
385                                         CalculateDocument ();
386                                 }
387                         }
388                 }
389
390                 [Browsable(false)]
391                 [DefaultValue("")]
392                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
393                 public string SelectedRtf {
394                         get {
395                                 return GenerateRTF(document.selection_start.line, document.selection_start.pos, document.selection_end.line, document.selection_end.pos).ToString();
396                         }
397
398                         set {                           
399                                 MemoryStream    data;
400                                 int             x;
401                                 int             y;
402                                 int             sel_start;
403                                 int             chars;
404                                 Line            line;
405                                 LineTag         tag;
406
407                                 if (document.selection_visible) {
408                                         document.ReplaceSelection("", false);
409                                 }
410
411                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
412
413                                 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
414                                 InsertRTFFromStream(data, document.selection_start.pos, document.selection_start.line.line_no, out x, out y, out chars);
415                                 data.Close();
416
417                                 document.CharIndexToLineTag(sel_start + chars + (y - document.selection_start.line.line_no) * 2, out line, out tag, out sel_start);
418                                 document.SetSelection(line, sel_start);
419                                 document.PositionCaret(line, sel_start);
420                                 document.DisplayCaret();
421                                 ScrollToCaret();
422                                 OnTextChanged(EventArgs.Empty);
423                         }
424                 }
425
426                 [Browsable(false)]
427                 [DefaultValue("")]
428                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
429                 public override string SelectedText {
430                         get {
431                                 return base.SelectedText;
432                         }
433
434                         set {
435                                 base.SelectedText = value;
436                         }
437                 }
438
439                 [Browsable(false)]
440                 [DefaultValue(HorizontalAlignment.Left)]
441                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
442                 public HorizontalAlignment SelectionAlignment {
443                         get {
444                                 HorizontalAlignment     align;
445                                 Line                    start;
446                                 Line                    end;
447                                 Line                    line;
448
449                                 start = document.ParagraphStart(document.selection_start.line);
450                                 align = start.alignment;
451
452                                 end = document.ParagraphEnd(document.selection_end.line);
453
454                                 line = start;
455
456                                 while (true) {
457                                         if (line.alignment != align) {
458                                                 return HorizontalAlignment.Left;
459                                         }
460
461                                         if (line == end) {
462                                                 break;
463                                         }
464                                         line = document.GetLine(line.line_no + 1);
465                                 }
466
467                                 return align;
468                         }
469
470                         set {
471                                 Line                    start;
472                                 Line                    end;
473                                 Line                    line;
474
475                                 start = document.ParagraphStart(document.selection_start.line);
476
477                                 end = document.ParagraphEnd(document.selection_end.line);
478
479                                 line = start;
480
481                                 while (true) {
482                                         line.alignment = value;
483
484                                         if (line == end) {
485                                                 break;
486                                         }
487                                         line = document.GetLine(line.line_no + 1);
488                                 }
489                                 this.CalculateDocument();
490                         }
491                 }
492
493 #if NET_2_0
494                 [MonoTODO ("Stub")]
495                 [Browsable (false)]
496                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
497                 public Color SelectionBackColor {
498                         get { return selection_back_color; }
499                         set { selection_back_color = value; }
500                 }
501 #endif
502
503                 [Browsable(false)]
504                 [DefaultValue(false)]
505                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
506                 [MonoTODO]
507                 public bool SelectionBullet {
508                         get {
509                                 return false;
510                         }
511
512                         set {
513                         }
514                 }
515
516                 [Browsable(false)]
517                 [DefaultValue(0)]
518                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
519                 [MonoTODO]
520                 public int SelectionCharOffset {
521                         get {
522                                 return 0;
523                         }
524
525                         set {
526                         }
527                 }
528
529                 [Browsable(false)]
530                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
531                 public Color SelectionColor {
532                         get {
533                                 Color   color;
534                                 LineTag start;
535                                 LineTag end;
536                                 LineTag tag;
537
538                                 if (selection_length > 0) {
539                                         start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
540                                         end = document.selection_start.line.FindTag (document.selection_end.pos);
541                                 } else {
542                                         start = document.selection_start.line.FindTag (document.selection_start.pos);
543                                         end = start;
544                                 }
545
546                                 color = start.Color;
547
548                                 tag = start;
549                                 while (tag != null) {
550
551                                         if (!color.Equals (tag.Color))
552                                                 return Color.Empty;
553
554                                         if (tag == end)
555                                                 break;
556
557                                         tag = document.NextTag (tag);
558                                 }
559
560                                 return color;
561                         }
562
563                         set {
564                                 if (value == Color.Empty)
565                                         value = DefaultForeColor;
566                                         
567                                 int sel_start;
568                                 int sel_end;
569
570                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
571                                 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
572
573                                 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
574                                                 document.selection_end.line, document.selection_end.pos + 1, null,
575                                                 value, Color.Empty, FormatSpecified.Color);
576
577                                 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
578                                 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
579
580                                 document.UpdateView(document.selection_start.line, 0);
581                                 document.AlignCaret();
582                         }
583                 }
584
585                 [Browsable(false)]
586                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
587                 public Font SelectionFont {
588                         get {
589                                 Font    font;
590                                 LineTag start;
591                                 LineTag end;
592                                 LineTag tag;
593
594                                 if (selection_length > 0) {
595                                         start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
596                                         end = document.selection_start.line.FindTag (document.selection_end.pos);
597                                 } else {
598                                         start = document.selection_start.line.FindTag (document.selection_start.pos);
599                                         end = start;
600                                 }
601
602                                 font = start.Font;
603
604                                 if (selection_length > 1) {
605                                         tag = start;
606                                         while (tag != null) {
607
608                                                 if (!font.Equals(tag.Font))
609                                                         return null;
610
611                                                 if (tag == end)
612                                                         break;
613
614                                                 tag = document.NextTag (tag);
615                                         }
616                                 }
617
618                                 return font;
619                         }
620
621                         set {
622                                 int             sel_start;
623                                 int             sel_end;
624
625                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
626                                 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
627
628                                 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
629                                                 document.selection_end.line, document.selection_end.pos + 1, value,
630                                                 Color.Empty, Color.Empty, FormatSpecified.Font);
631
632                                 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
633                                 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
634
635                                 document.UpdateView(document.selection_start.line, 0);
636                                 document.AlignCaret();
637
638                         }
639                 }
640
641                 [Browsable(false)]
642                 [DefaultValue(0)]
643                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
644                 [MonoTODO]
645                 public int SelectionHangingIndent {
646                         get {
647                                 return 0;
648                         }
649
650                         set {
651                         }
652                 }
653
654                 [Browsable(false)]
655                 [DefaultValue(0)]
656                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
657                 [MonoTODO]
658                 public int SelectionIndent {
659                         get {
660                                 return 0;
661                         }
662
663                         set {
664                         }
665                 }
666
667                 [Browsable(false)]
668                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
669                 public override int SelectionLength {
670                         get {
671                                 return base.SelectionLength;
672                         }
673
674                         set {
675                                 base.SelectionLength = value;
676                         }
677                 }
678
679                 [Browsable(false)]
680                 [DefaultValue(false)]
681                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
682                 [MonoTODO]
683                 public bool SelectionProtected {
684                         get {
685                                 return false;
686                         }
687
688                         set {
689                         }
690                 }
691
692                 [Browsable(false)]
693                 [DefaultValue(0)]
694                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
695                 [MonoTODO]
696                 public int SelectionRightIndent {
697                         get {
698                                 return 0;
699                         }
700
701                         set {
702                         }
703                 }
704
705                 [Browsable(false)]
706                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
707                 [MonoTODO]
708                 public int[] SelectionTabs {
709                         get {
710                                 return new int[0];
711                         }
712
713                         set {
714                         }
715                 }
716
717                 [Browsable(false)]
718                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
719                 public RichTextBoxSelectionTypes SelectionType {
720                         get {
721                                 if (document.selection_start == document.selection_end) {
722                                         return RichTextBoxSelectionTypes.Empty;
723                                 }
724
725                                 // Lazy, but works
726                                 if (SelectedText.Length > 1) {
727                                         return RichTextBoxSelectionTypes.MultiChar | RichTextBoxSelectionTypes.Text;
728                                 }
729
730                                 return RichTextBoxSelectionTypes.Text;
731                         }
732                 }
733
734                 [DefaultValue(false)]
735                 [MonoTODO]
736                 public bool ShowSelectionMargin {
737                         get {
738                                 return false;
739                         }
740
741                         set {
742                         }
743                 }
744
745                 [Localizable(true)]
746 #if NET_2_0
747                 [RefreshProperties (RefreshProperties.All)]
748 #endif
749                 public override string Text {
750                         get {
751                                 return base.Text;
752                         }
753
754                         set {
755                                 base.Text = value;
756                         }
757                 }
758
759                 [Browsable(false)]
760                 public override int TextLength {
761                         get {
762                                 return base.TextLength;
763                         }
764                 }
765
766                 [Browsable(false)]
767                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
768                 public string UndoActionName {
769                         get {
770                                 return document.undo.UndoActionName;
771                         }
772                 }
773
774                 [Localizable(true)]
775                 [DefaultValue(1)]
776                 public float ZoomFactor {
777                         get {
778                                 return zoom;
779                         }
780
781                         set {
782                                 zoom = value;
783                         }
784                 }
785                 #endregion      // Public Instance Properties
786
787                 #region Protected Instance Properties
788                 protected override CreateParams CreateParams {
789                         get {
790                                 return base.CreateParams;
791                         }
792                 }
793
794                 protected override Size DefaultSize {
795                         get {
796                                 return new Size(100, 96);
797                         }
798                 }
799                 #endregion      // Protected Instance Properties
800
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)) {
806                                         return true;
807                         }
808                         return false;
809                 }
810
811                 public int Find(char[] characterSet) {
812                         return Find(characterSet, -1, -1);
813                 }
814
815                 public int Find(char[] characterSet, int start) {
816                         return Find(characterSet, start, -1);
817                 }
818
819                 public int Find(char[] characterSet, int start, int end) {
820                         Document.Marker start_mark;
821                         Document.Marker end_mark;
822                         Document.Marker result;
823
824                         if (start == -1) {
825                                 document.GetMarker(out start_mark, true);
826                         } else {
827                                 Line line;
828                                 LineTag tag;
829                                 int pos;
830
831                                 start_mark = new Document.Marker();
832
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;
837                         }
838
839                         if (end == -1) {
840                                 document.GetMarker(out end_mark, false);
841                         } else {
842                                 Line line;
843                                 LineTag tag;
844                                 int pos;
845
846                                 end_mark = new Document.Marker();
847
848                                 document.CharIndexToLineTag(end, out line, out tag, out pos);
849                                 end_mark.line = line;
850                                 end_mark.tag = tag;
851                                 end_mark.pos = pos;
852                         }
853
854                         if (document.FindChars(characterSet, start_mark, end_mark, out result)) {
855                                 return document.LineTagToCharIndex(result.line, result.pos);
856                         }
857
858                         return -1;
859                 }
860
861                 public int Find(string str) {
862                         return Find(str, -1, -1, RichTextBoxFinds.None);
863                 }
864
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;
869
870                         if (start == -1) {
871                                 document.GetMarker(out start_mark, true);
872                         } else {
873                                 Line line;
874                                 LineTag tag;
875                                 int pos;
876
877                                 start_mark = new Document.Marker();
878
879                                 document.CharIndexToLineTag(start, out line, out tag, out pos);
880
881                                 start_mark.line = line;
882                                 start_mark.tag = tag;
883                                 start_mark.pos = pos;
884                         }
885
886                         if (end == -1) {
887                                 document.GetMarker(out end_mark, false);
888                         } else {
889                                 Line line;
890                                 LineTag tag;
891                                 int pos;
892
893                                 end_mark = new Document.Marker();
894
895                                 document.CharIndexToLineTag(end, out line, out tag, out pos);
896
897                                 end_mark.line = line;
898                                 end_mark.tag = tag;
899                                 end_mark.pos = pos;
900                         }
901
902                         if (document.Find(str, start_mark, end_mark, out result, options)) {
903                                 return document.LineTagToCharIndex(result.line, result.pos);
904                         }
905
906                         return -1;
907                 }
908
909                 public int Find(string str, int start, RichTextBoxFinds options) {
910                         return Find(str, start, -1, options);
911                 }
912
913                 public int Find(string str, RichTextBoxFinds options) {
914                         return Find(str, -1, -1, options);
915                 }
916
917                 
918 #if !NET_2_0
919                 public char GetCharFromPosition(Point pt) {
920                         LineTag tag;
921                         int     pos;
922
923                         PointToTagPos(pt, out tag, out pos);
924
925                         if (pos >= tag.Line.text.Length) {
926                                 return '\n';
927                         }
928
929                         return tag.Line.text[pos];
930                 }
931 #else
932                 internal override char GetCharFromPositionInternal (Point p)
933                 {
934                         LineTag tag;
935                         int pos;
936
937                         PointToTagPos (p, out tag, out pos);
938
939                         if (pos >= tag.Line.text.Length)
940                                 return '\n';
941
942                         return tag.Line.text[pos];
943                 }
944 #endif
945
946                 public
947 #if NET_2_0
948                 override
949 #endif  
950                 int GetCharIndexFromPosition(Point pt) {
951                         LineTag tag;
952                         int     pos;
953
954                         PointToTagPos(pt, out tag, out pos);
955
956                         return document.LineTagToCharIndex(tag.Line, pos);
957                 }
958
959                 public
960 #if NET_2_0
961                 override
962 #endif
963                 int GetLineFromCharIndex(int index) {
964                         Line    line;
965                         LineTag tag;
966                         int     pos;
967
968                         document.CharIndexToLineTag(index, out line, out tag, out pos);
969
970                         return line.LineNo - 1;
971                 }
972
973                 public
974 #if NET_2_0
975                 override
976 #endif
977                 Point GetPositionFromCharIndex(int index) {
978                         Line    line;
979                         LineTag tag;
980                         int     pos;
981
982                         document.CharIndexToLineTag(index, out line, out tag, out pos);
983
984                         return new Point((int)line.widths[pos] + 1, line.Y + 1);
985                 }
986
987                 public void LoadFile(System.IO.Stream data, RichTextBoxStreamType fileType) {
988                         document.Empty();
989
990                         
991                         // FIXME - ignoring unicode
992                         if (fileType == RichTextBoxStreamType.PlainText) {
993                                 StringBuilder sb;
994                                 char[] buffer;
995
996                                 try {
997                                         sb = new StringBuilder ((int) data.Length);
998                                         buffer = new char [1024];
999                                 } catch {
1000                                         throw new IOException("Not enough memory to load document");
1001                                 }
1002
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);
1008                                 }
1009                                 base.Text = sb.ToString();
1010                                 return;
1011                         }
1012
1013                         InsertRTFFromStream(data, 0, 1);
1014
1015                         document.PositionCaret (document.GetLine (1), 0);
1016                         document.SetSelectionToCaret (true);
1017                         ScrollToCaret ();
1018                 }
1019
1020                 [MonoTODO("Make smarter RTF detection?")]
1021                 public void LoadFile(string path) {
1022                         if (path.EndsWith(".rtf")) {
1023                                 LoadFile(path, RichTextBoxStreamType.RichText);
1024                         } else {
1025                                 LoadFile(path, RichTextBoxStreamType.PlainText);
1026                         }
1027                 }
1028
1029                 public void LoadFile(string path, RichTextBoxStreamType fileType) {
1030                         FileStream      data;
1031
1032                         data = null;
1033
1034
1035                         try {
1036                                 data = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024);
1037
1038                                 LoadFile(data, fileType);
1039                         }
1040 #if !DEBUG
1041                         catch (Exception ex) {
1042                                 throw new IOException("Could not open file " + path, ex);
1043                         }
1044 #endif
1045                         finally {
1046                                 if (data != null) {
1047                                         data.Close();
1048                                 }
1049                         }
1050                 }
1051
1052                 public void Paste(DataFormats.Format clipFormat) {
1053                         base.Paste(Clipboard.GetDataObject(), clipFormat, false);
1054                 }
1055
1056                 public void Redo()
1057                 {
1058                         document.undo.Redo ();
1059                 }
1060
1061                 public void SaveFile(Stream data, RichTextBoxStreamType fileType) {
1062                         Encoding        encoding;
1063                         int             i;
1064                         Byte[]          bytes;
1065
1066
1067                         if (fileType == RichTextBoxStreamType.UnicodePlainText) {
1068                                 encoding = Encoding.Unicode;
1069                         } else {
1070                                 encoding = Encoding.ASCII;
1071                         }
1072
1073                         switch(fileType) {
1074                                 case RichTextBoxStreamType.PlainText: 
1075                                 case RichTextBoxStreamType.TextTextOleObjs: 
1076                                 case RichTextBoxStreamType.UnicodePlainText: {
1077                                         if (!Multiline) {
1078                                                 bytes = encoding.GetBytes(document.Root.text.ToString());
1079                                                 data.Write(bytes, 0, bytes.Length);
1080                                                 return;
1081                                         }
1082
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);
1086                                         }
1087                                         bytes = encoding.GetBytes(document.GetLine(document.Lines).text.ToString());
1088                                         data.Write(bytes, 0, bytes.Length);
1089                                         return;
1090                                 }
1091                         }
1092
1093                         // If we're here we're saving RTF
1094                         Line            start_line;
1095                         Line            end_line;
1096                         StringBuilder   rtf;
1097                         int             current;
1098                         int             total;
1099
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);
1103                         total = rtf.Length;
1104                         bytes = new Byte[4096];
1105
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);
1110                                 } else {
1111                                         current = total - i;
1112                                         current = encoding.GetBytes(rtf.ToString(i, current), 0, current, bytes, 0);
1113                                 }
1114                                 data.Write(bytes, 0, current);
1115                         }
1116                 }
1117
1118                 public void SaveFile(string path) {
1119                         if (path.EndsWith(".rtf")) {
1120                                 SaveFile(path, RichTextBoxStreamType.RichText);
1121                         } else {
1122                                 SaveFile(path, RichTextBoxStreamType.PlainText);
1123                         }
1124                 }
1125
1126                 public void SaveFile(string path, RichTextBoxStreamType fileType) {
1127                         FileStream      data;
1128
1129                         data = null;
1130
1131 //                      try {
1132                                 data = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1024, false);
1133                                 SaveFile(data, fileType);
1134 //                      }
1135
1136 //                      catch {
1137 //                              throw new IOException("Could not write document to file " + path);
1138 //                      }
1139
1140 //                      finally {
1141                                 if (data != null) {
1142                                         data.Close();
1143                                 }
1144 //                      }
1145                 }
1146
1147 #if NET_2_0
1148                 [EditorBrowsable (EditorBrowsableState.Never)]
1149                 public new void DrawToBitmap (Bitmap bitmap, Rectangle clip)
1150                 {
1151                         Graphics dc = Graphics.FromImage (bitmap);
1152
1153                         if (backcolor_set || (Enabled && !read_only)) {
1154                                 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), clip);
1155                         } else {
1156                                 dc.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (ThemeEngine.Current.ColorControl), clip);
1157                         }
1158                         
1159                         // Draw the viewable document
1160                         document.Draw (dc, clip);
1161                 }
1162 #endif
1163
1164                 #endregion      // Public Instance Methods
1165
1166                 #region Protected Instance Methods
1167                 protected virtual object CreateRichEditOleCallback() {
1168                         throw new NotImplementedException();
1169                 }
1170
1171                 protected override void OnBackColorChanged(EventArgs e) {
1172                         base.OnBackColorChanged (e);
1173                 }
1174
1175                 protected virtual void OnContentsResized(ContentsResizedEventArgs e) {
1176                         ContentsResizedEventHandler eh = (ContentsResizedEventHandler)(Events [ContentsResizedEvent]);
1177                         if (eh != null)
1178                                 eh (this, e);
1179                 }
1180
1181                 protected override void OnContextMenuChanged(EventArgs e) {
1182                         base.OnContextMenuChanged (e);
1183                 }
1184
1185                 protected override void OnHandleCreated(EventArgs e) {
1186                         base.OnHandleCreated (e);
1187                 }
1188
1189                 protected override void OnHandleDestroyed(EventArgs e) {
1190                         base.OnHandleDestroyed (e);
1191                 }
1192
1193                 protected virtual void OnHScroll(EventArgs e) {
1194                         EventHandler eh = (EventHandler)(Events [HScrollEvent]);
1195                         if (eh != null)
1196                                 eh (this, e);
1197                 }
1198
1199                 [MonoTODO("Determine when to call this")]
1200                 protected virtual void OnImeChange(EventArgs e) {
1201                         EventHandler eh = (EventHandler)(Events [ImeChangeEvent]);
1202                         if (eh != null)
1203                                 eh (this, e);
1204                 }
1205
1206                 protected virtual void OnLinkClicked(LinkClickedEventArgs e) {
1207                         LinkClickedEventHandler eh = (LinkClickedEventHandler)(Events [LinkClickedEvent]);
1208                         if (eh != null)
1209                                 eh (this, e);
1210                 }
1211
1212                 protected virtual void OnProtected(EventArgs e) {
1213                         EventHandler eh = (EventHandler)(Events [ProtectedEvent]);
1214                         if (eh != null)
1215                                 eh (this, e);
1216                 }
1217
1218                 protected override void OnRightToLeftChanged(EventArgs e) {
1219                         base.OnRightToLeftChanged (e);
1220                 }
1221
1222                 protected virtual void OnSelectionChanged(EventArgs e) {
1223                         EventHandler eh = (EventHandler)(Events [SelectionChangedEvent]);
1224                         if (eh != null)
1225                                 eh (this, e);
1226                 }
1227
1228 #if !NET_2_0
1229                 protected override void OnSystemColorsChanged(EventArgs e) {
1230                         base.OnSystemColorsChanged (e);
1231                 }
1232
1233                 protected override void OnTextChanged(EventArgs e) {
1234                         base.OnTextChanged (e);
1235                 }
1236 #endif
1237
1238                 protected virtual void OnVScroll(EventArgs e) {
1239                         EventHandler eh = (EventHandler)(Events [VScrollEvent]);
1240                         if (eh != null)
1241                                 eh (this, e);
1242                 }
1243
1244                 protected override void WndProc(ref Message m) {
1245                         base.WndProc (ref m);
1246                 }
1247
1248 #if NET_2_0
1249                 protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
1250                 {
1251                         return base.ProcessCmdKey (ref msg, keyData);
1252                 }
1253 #endif
1254                 #endregion      // Protected Instance Methods
1255
1256                 #region Events
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 ();
1264
1265                 [Browsable(false)]
1266                 [EditorBrowsable(EditorBrowsableState.Never)]
1267                 public new event EventHandler BackgroundImageChanged {
1268                         add { base.BackgroundImageChanged += value; }
1269                         remove { base.BackgroundImageChanged -= value; }
1270                 }
1271
1272 #if NET_2_0
1273                 [Browsable (false)]
1274                 [EditorBrowsable (EditorBrowsableState.Never)]
1275                 public new event EventHandler BackgroundImageLayoutChanged {
1276                         add { base.BackgroundImageLayoutChanged += value; }
1277                         remove { base.BackgroundImageLayoutChanged -= value; }
1278                 }
1279 #endif
1280
1281                 public event ContentsResizedEventHandler ContentsResized {
1282                         add { Events.AddHandler (ContentsResizedEvent, value); }
1283                         remove { Events.RemoveHandler (ContentsResizedEvent, value); }
1284                 }
1285
1286 #if !NET_2_0
1287                 [Browsable(false)]
1288                 [EditorBrowsable(EditorBrowsableState.Never)]
1289                 public new event EventHandler DoubleClick {
1290                         add { base.DoubleClick += value; }
1291                         remove { base.DoubleClick -= value; }
1292                 }
1293 #endif
1294
1295                 [Browsable(false)]
1296 #if !NET_2_0
1297                 [EditorBrowsable(EditorBrowsableState.Never)]
1298 #endif
1299                 public new event DragEventHandler DragDrop {
1300                         add { base.DragDrop += value; }
1301                         remove { base.DragDrop -= value; }
1302                 }
1303
1304                 [Browsable(false)]
1305 #if !NET_2_0
1306                 [EditorBrowsable(EditorBrowsableState.Never)]
1307 #endif
1308                 public new event DragEventHandler DragEnter {
1309                         add { base.DragEnter += value; }
1310                         remove { base.DragEnter -= value; }
1311                 }
1312
1313                 [Browsable(false)]
1314                 [EditorBrowsable(EditorBrowsableState.Never)]
1315                 public new event EventHandler DragLeave {
1316                         add { base.DragLeave += value; }
1317                         remove { base.DragLeave -= value; }
1318                 }
1319
1320
1321                 [Browsable(false)]
1322                 [EditorBrowsable(EditorBrowsableState.Never)]
1323                 public new event DragEventHandler DragOver {
1324                         add { base.DragOver += value; }
1325                         remove { base.DragOver -= value; }
1326                 }
1327
1328
1329                 [Browsable(false)]
1330                 [EditorBrowsable(EditorBrowsableState.Never)]
1331                 public new event GiveFeedbackEventHandler GiveFeedback {
1332                         add { base.GiveFeedback += value; }
1333                         remove { base.GiveFeedback -= value; }
1334                 }
1335
1336                 public event EventHandler HScroll {
1337                         add { Events.AddHandler (HScrollEvent, value); }
1338                         remove { Events.RemoveHandler (HScrollEvent, value); }
1339                 }
1340
1341                 public event EventHandler ImeChange {
1342                         add { Events.AddHandler (ImeChangeEvent, value); }
1343                         remove { Events.RemoveHandler (ImeChangeEvent, value); }
1344                 }
1345
1346                 public event LinkClickedEventHandler LinkClicked {
1347                         add { Events.AddHandler (LinkClickedEvent, value); }
1348                         remove { Events.RemoveHandler (LinkClickedEvent, value); }
1349                 }
1350
1351                 public event EventHandler Protected {
1352                         add { Events.AddHandler (ProtectedEvent, value); }
1353                         remove { Events.RemoveHandler (ProtectedEvent, value); }
1354                 }
1355
1356                 [Browsable(false)]
1357                 [EditorBrowsable(EditorBrowsableState.Never)]
1358                 public new event QueryContinueDragEventHandler QueryContinueDrag {
1359                         add { base.QueryContinueDrag += value; }
1360                         remove { base.QueryContinueDrag -= value; }
1361                 }
1362
1363                 public event EventHandler SelectionChanged {
1364                         add { Events.AddHandler (SelectionChangedEvent, value); }
1365                         remove { Events.RemoveHandler (SelectionChangedEvent, value); }
1366                 }
1367
1368                 public event EventHandler VScroll {
1369                         add { Events.AddHandler (VScrollEvent, value); }
1370                         remove { Events.RemoveHandler (VScrollEvent, value); }
1371                 }
1372                 #endregion      // Events
1373
1374                 #region Private Methods
1375
1376                 internal override void SelectWord ()
1377                 {
1378                         document.ExpandSelection(CaretSelection.Word, false);
1379                 }
1380
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;
1388
1389                         public object Clone ()
1390                         {
1391                                 RtfSectionStyle new_style = new RtfSectionStyle ();
1392
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;
1399
1400                                 return new_style;
1401                         }
1402                 }
1403
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)
1407                 {
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 ();
1412                         }
1413
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);
1419
1420                                         rtf_style = (RtfSectionStyle) rtf_section_stack.Pop ();
1421                                 }
1422                         }
1423                 }
1424
1425                 [MonoTODO("Add QuadJust support for justified alignment")]
1426                 private void HandleControl(RTF.RTF rtf) {
1427                         switch(rtf.Major) {
1428                                 case RTF.Major.Unicode: {
1429                                         switch(rtf.Minor) {
1430                                                 case RTF.Minor.UnicodeCharBytes: {
1431                                                         rtf_skip_width = rtf.Param;
1432                                                         break;
1433                                                 }
1434
1435                                                 case RTF.Minor.UnicodeChar: {
1436                                                         rtf_skip_count += rtf_skip_width;
1437                                                         rtf_line.Append((char)rtf.Param);
1438                                                         break;
1439                                                 }
1440                                         }
1441                                         break;
1442                                 }
1443
1444                                 case RTF.Major.Destination: {
1445 //                                      Console.Write("[Got Destination control {0}]", rtf.Minor);
1446                                         rtf.SkipGroup();
1447                                         break;
1448                                 }
1449
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);
1454                                                 rtf_cursor_x++;
1455
1456                                                 FlushText (rtf, true);
1457                                                 rtf.Picture = null;
1458                                         }
1459                                         break;
1460
1461                                 case RTF.Major.CharAttr: {
1462                                         switch(rtf.Minor) {
1463                                                 case RTF.Minor.ForeColor: {
1464                                                         System.Windows.Forms.RTF.Color  color;
1465
1466                                                         color = System.Windows.Forms.RTF.Color.GetColor(rtf, rtf.Param);
1467                                                         
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;
1472                                                                 } else {
1473                                                                         this.rtf_style.rtf_color = Color.FromArgb(color.Red, color.Green, color.Blue);
1474                                                                 }
1475                                                                 FlushText (rtf, false);
1476                                                         }
1477                                                         break;
1478                                                 }
1479
1480                                                 case RTF.Minor.FontSize: {
1481                                                         FlushText(rtf, false);
1482                                                         this.rtf_style.rtf_rtffont_size = rtf.Param / 2;
1483                                                         break;
1484                                                 }
1485
1486                                                 case RTF.Minor.FontNum: {
1487                                                         System.Windows.Forms.RTF.Font   font;
1488
1489                                                         font = System.Windows.Forms.RTF.Font.GetFont(rtf, rtf.Param);
1490                                                         if (font != null) {
1491                                                                 FlushText(rtf, false);
1492                                                                 this.rtf_style.rtf_rtffont = font;
1493                                                         }
1494                                                         break;
1495                                                 }
1496
1497                                                 case RTF.Minor.Plain: {
1498                                                         FlushText(rtf, false);
1499                                                         rtf_style.rtf_rtfstyle = FontStyle.Regular;
1500                                                         break;
1501                                                 }
1502
1503                                                 case RTF.Minor.Bold: {
1504                                                         FlushText(rtf, false);
1505                                                         if (rtf.Param == RTF.RTF.NoParam) {
1506                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Bold;
1507                                                         } else {
1508                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Bold;
1509                                                         }
1510                                                         break;
1511                                                 }
1512
1513                                                 case RTF.Minor.Italic: {
1514                                                         FlushText(rtf, false);
1515                                                         if (rtf.Param == RTF.RTF.NoParam) {
1516                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Italic;
1517                                                         } else {
1518                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Italic;
1519                                                         }
1520                                                         break;
1521                                                 }
1522
1523                                                 case RTF.Minor.StrikeThru: {
1524                                                         FlushText(rtf, false);
1525                                                         if (rtf.Param == RTF.RTF.NoParam) {
1526                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Strikeout;
1527                                                         } else {
1528                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Strikeout;
1529                                                         }
1530                                                         break;
1531                                                 }
1532
1533                                                 case RTF.Minor.Underline: {
1534                                                         FlushText(rtf, false);
1535                                                         if (rtf.Param == RTF.RTF.NoParam) {
1536                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Underline;
1537                                                         } else {
1538                                                                 rtf_style.rtf_rtfstyle = rtf_style.rtf_rtfstyle & ~FontStyle.Underline;
1539                                                         }
1540                                                         break;
1541                                                 }
1542
1543                                                 case RTF.Minor.NoUnderline: {
1544                                                         FlushText(rtf, false);
1545                                                         rtf_style.rtf_rtfstyle &= ~FontStyle.Underline;
1546                                                         break;
1547                                                 }
1548                                         }
1549                                         break;
1550                                 }
1551
1552                         case RTF.Major.ParAttr: {
1553                                 switch (rtf.Minor) {
1554
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;
1559                                         break;
1560
1561                                 case RTF.Minor.LeftIndent:
1562                                         rtf_style.rtf_par_line_left_indent = (int) (((float) rtf.Param / 1440.0F) * CreateGraphics ().DpiX + 0.5F);
1563                                         break;
1564
1565                                 case RTF.Minor.QuadCenter:
1566                                         FlushText (rtf, false);
1567                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1568                                         break;
1569
1570                                 case RTF.Minor.QuadJust:
1571                                         FlushText (rtf, false);
1572                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1573                                         break;
1574
1575                                 case RTF.Minor.QuadLeft:
1576                                         FlushText (rtf, false);
1577                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1578                                         break;
1579
1580                                 case RTF.Minor.QuadRight:
1581                                         FlushText (rtf, false);
1582                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Right;
1583                                         break;
1584                                 }
1585                                 break;
1586                         }
1587
1588                         case RTF.Major.SpecialChar: {
1589                                         //Console.Write("[Got SpecialChar control {0}]", rtf.Minor);
1590                                         SpecialChar (rtf);
1591                                         break;
1592                                 }
1593                         }
1594                 }
1595
1596                 private void SpecialChar(RTF.RTF rtf) {
1597                         switch(rtf.Minor) {
1598                                 case RTF.Minor.Page:
1599                                 case RTF.Minor.Sect:
1600                                 case RTF.Minor.Row:
1601                                 case RTF.Minor.Line:
1602                                 case RTF.Minor.Par: {
1603                                         FlushText(rtf, true);
1604                                         break;
1605                                 }
1606
1607                                 case RTF.Minor.Cell: {
1608                                         Console.Write(" ");
1609                                         break;
1610                                 }
1611
1612                                 case RTF.Minor.NoBrkSpace: {
1613                                         Console.Write(" ");
1614                                         break;
1615                                 }
1616
1617                                 case RTF.Minor.Tab: {
1618                                         rtf_line.Append ("\t");
1619 //                                      FlushText (rtf, false);
1620                                         break;
1621                                 }
1622
1623                                 case RTF.Minor.NoReqHyphen:
1624                                 case RTF.Minor.NoBrkHyphen: {
1625                                         rtf_line.Append ("-");
1626 //                                      FlushText (rtf, false);
1627                                         break;
1628                                 }
1629
1630                                 case RTF.Minor.Bullet: {
1631                                         Console.WriteLine("*");
1632                                         break;
1633                                 }
1634
1635                         case RTF.Minor.WidowCtrl:
1636                                 break;
1637
1638                                 case RTF.Minor.EmDash: {
1639                                 rtf_line.Append ("\u2014");
1640                                         break;
1641                                 }
1642
1643                                 case RTF.Minor.EnDash: {
1644                                         rtf_line.Append ("\u2013");
1645                                         break;
1646                                 }
1647 /*
1648                                 case RTF.Minor.LQuote: {
1649                                         Console.Write("\u2018");
1650                                         break;
1651                                 }
1652
1653                                 case RTF.Minor.RQuote: {
1654                                         Console.Write("\u2019");
1655                                         break;
1656                                 }
1657
1658                                 case RTF.Minor.LDblQuote: {
1659                                         Console.Write("\u201C");
1660                                         break;
1661                                 }
1662
1663                                 case RTF.Minor.RDblQuote: {
1664                                         Console.Write("\u201D");
1665                                         break;
1666                                 }
1667 */
1668                                 default: {
1669 //                                      Console.WriteLine ("skipped special char:   {0}", rtf.Minor);
1670 //                                      rtf.SkipGroup();
1671                                         break;
1672                                 }
1673                         }
1674                 }
1675
1676                 private void HandleText(RTF.RTF rtf) {
1677                         if (rtf_skip_count > 0) {
1678                                 rtf_skip_count--;
1679                                 return;
1680                         }
1681
1682                         /*
1683                         if ((RTF.StandardCharCode)rtf.Minor != RTF.StandardCharCode.nothing) {
1684                                 rtf_line.Append(rtf_text_map[(RTF.StandardCharCode)rtf.Minor]);
1685                         } else {
1686                                 if ((int)rtf.Major > 31 && (int)rtf.Major < 128) {
1687                                         rtf_line.Append((char)rtf.Major);
1688                                 } else {
1689                                         //rtf_line.Append((char)rtf.Major);
1690                                         Console.Write("[Literal:0x{0:X2}]", (int)rtf.Major);
1691                                 }
1692                         }
1693                         */
1694                         rtf_line.Append (rtf.EncodedText);
1695                 }
1696
1697                 private void FlushText(RTF.RTF rtf, bool newline) {
1698                         int             length;
1699                         Font            font;
1700
1701                         length = rtf_line.Length;
1702                         if (!newline && (length == 0)) {
1703                                 return;
1704                         }
1705
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);
1709                         }
1710
1711                         font = new Font (rtf_style.rtf_rtffont.Name, rtf_style.rtf_rtffont_size, rtf_style.rtf_rtfstyle);
1712
1713                         if (rtf_style.rtf_color == Color.Empty) {
1714                                 System.Windows.Forms.RTF.Color color;
1715
1716                                 // First color in table is default
1717                                 color = System.Windows.Forms.RTF.Color.GetColor (rtf, 0);
1718
1719                                 if ((color == null) || (color.Red == -1 && color.Green == -1 && color.Blue == -1)) {
1720                                         rtf_style.rtf_color = ForeColor;
1721                                 } else {
1722                                         rtf_style.rtf_color = Color.FromArgb (color.Red, color.Green, color.Blue);
1723                                 }
1724
1725                         }
1726
1727                         rtf_chars += rtf_line.Length;
1728
1729
1730
1731                         if (rtf_cursor_x == 0) {
1732                                 document.Add (rtf_cursor_y, rtf_line.ToString (), rtf_style.rtf_rtfalign, font, rtf_style.rtf_color,
1733                                                                 newline ? LineEnding.Rich : LineEnding.Wrap);
1734                                 if (rtf_style.rtf_par_line_left_indent != 0) {
1735                                         Line line = document.GetLine (rtf_cursor_y);
1736                                         line.indent = rtf_style.rtf_par_line_left_indent;
1737                                 }
1738                         } else {
1739                                 Line line;
1740
1741                                 line = document.GetLine (rtf_cursor_y);
1742                                 line.indent = rtf_style.rtf_par_line_left_indent;
1743                                 if (rtf_line.Length > 0) {
1744                                         document.InsertString (line, rtf_cursor_x, rtf_line.ToString ());
1745                                         document.FormatText (line, rtf_cursor_x + 1, line, rtf_cursor_x + 1 + length,
1746                             font, rtf_style.rtf_color, Color.Empty,
1747                                                         FormatSpecified.Font | FormatSpecified.Color);
1748                                 }
1749                                 if (newline) {
1750                                         document.Split (line, rtf_cursor_x + length);
1751                                         line = document.GetLine (rtf_cursor_y);
1752                                         line.ending = LineEnding.Rich;
1753                                 }
1754                         }
1755
1756                         if (newline) {
1757                                 rtf_cursor_x = 0;
1758                                 rtf_cursor_y++;
1759                         } else {
1760                                 rtf_cursor_x += length;
1761                         }
1762                         rtf_line.Length = 0;    // Empty line
1763                 }
1764
1765                 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y) {
1766                         int     x;
1767                         int     y;
1768                         int     chars;
1769
1770                         InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
1771                 }
1772
1773                 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y, out int to_x, out int to_y, out int chars) {
1774                         RTF.RTF         rtf;
1775
1776                         rtf = new RTF.RTF(data);
1777
1778                         // Prepare
1779                         rtf.ClassCallback[RTF.TokenClass.Text] = new RTF.ClassDelegate(HandleText);
1780                         rtf.ClassCallback[RTF.TokenClass.Control] = new RTF.ClassDelegate(HandleControl);
1781                         rtf.ClassCallback[RTF.TokenClass.Group] = new RTF.ClassDelegate(HandleGroup);
1782
1783                         rtf_skip_width = 0;
1784                         rtf_skip_count = 0;
1785                         rtf_line = new StringBuilder();
1786                         rtf_style.rtf_color = Color.Empty;
1787                         rtf_style.rtf_rtffont_size = (int)this.Font.Size;
1788                         rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1789                         rtf_style.rtf_rtfstyle = FontStyle.Regular;
1790                         rtf_style.rtf_rtffont = null;
1791                         rtf_cursor_x = cursor_x;
1792                         rtf_cursor_y = cursor_y;
1793                         rtf_chars = 0;
1794                         rtf.DefaultFont(this.Font.Name);
1795
1796                         rtf_text_map = new RTF.TextMap();
1797                         RTF.TextMap.SetupStandardTable(rtf_text_map.Table);
1798
1799                         document.SuspendRecalc ();
1800
1801                         try {
1802                                 rtf.Read();     // That's it
1803                                 FlushText(rtf, false);
1804
1805                         }
1806
1807
1808                         catch (RTF.RTFException e) {
1809 #if DEBUG
1810                                 throw e;
1811 #endif
1812                                 // Seems to be plain text or broken RTF
1813                                 Console.WriteLine("RTF Parsing failure: {0}", e.Message);
1814                         }                     
1815
1816                         to_x = rtf_cursor_x;
1817                         to_y = rtf_cursor_y;
1818                         chars = rtf_chars;
1819
1820                         // clear the section stack if it was used
1821                         if (rtf_section_stack != null)
1822                                 rtf_section_stack.Clear();
1823
1824                         document.RecalculateDocument(CreateGraphicsInternal(), cursor_y, document.Lines, false);
1825                         document.ResumeRecalc (true);
1826
1827                         document.Invalidate (document.GetLine(cursor_y), 0, document.GetLine(document.Lines), -1);
1828                 }
1829
1830                 private void RichTextBox_HScrolled(object sender, EventArgs e) {
1831                         OnHScroll(e);
1832                 }
1833
1834                 private void RichTextBox_VScrolled(object sender, EventArgs e) {
1835                         OnVScroll(e);
1836                 }
1837
1838                 private void PointToTagPos(Point pt, out LineTag tag, out int pos) {
1839                         Point p;
1840
1841                         p = pt;
1842
1843                         if (p.X >= document.ViewPortWidth) {
1844                                 p.X = document.ViewPortWidth - 1;
1845                         } else if (p.X < 0) {
1846                                 p.X = 0;
1847                         }
1848
1849                         if (p.Y >= document.ViewPortHeight) {
1850                                 p.Y = document.ViewPortHeight - 1;
1851                         } else if (p.Y < 0) {
1852                                 p.Y = 0;
1853                         }
1854
1855                         tag = document.FindCursor(p.X + document.ViewPortX, p.Y + document.ViewPortY, out pos);
1856                 }
1857
1858                 private void EmitRTFFontProperties(StringBuilder rtf, int prev_index, int font_index, Font prev_font, Font font) {
1859                         if (prev_index != font_index) {
1860                                 rtf.Append(String.Format("\\f{0}", font_index));        // Font table entry
1861                         }
1862
1863                         if ((prev_font == null) || (prev_font.Size != font.Size)) {
1864                                 rtf.Append(String.Format("\\fs{0}", (int)(font.Size * 2)));             // Font size
1865                         }
1866
1867                         if ((prev_font == null) || (font.Bold != prev_font.Bold)) {
1868                                 if (font.Bold) {
1869                                         rtf.Append("\\b");
1870                                 } else {
1871                                         if (prev_font != null) {
1872                                                 rtf.Append("\\b0");
1873                                         }
1874                                 }
1875                         }
1876
1877                         if ((prev_font == null) || (font.Italic != prev_font.Italic)) {
1878                                 if (font.Italic) {
1879                                         rtf.Append("\\i");
1880                                 } else {
1881                                         if (prev_font != null) {
1882                                                 rtf.Append("\\i0");
1883                                         }
1884                                 }
1885                         }
1886
1887                         if ((prev_font == null) || (font.Strikeout != prev_font.Strikeout)) {
1888                                 if (font.Strikeout) {
1889                                         rtf.Append("\\strike");
1890                                 } else {
1891                                         if (prev_font != null) {
1892                                                 rtf.Append("\\strike0");
1893                                         }
1894                                 }
1895                         }
1896
1897                         if ((prev_font == null) || (font.Underline != prev_font.Underline)) {
1898                                 if (font.Underline) {
1899                                         rtf.Append("\\ul");
1900                                 } else {
1901                                         if (prev_font != null) {
1902                                                 rtf.Append("\\ul0");
1903                                         }
1904                                 }
1905                         }
1906                 }
1907
1908                 [MonoTODO("Emit unicode and other special characters properly")]
1909                 private void EmitRTFText(StringBuilder rtf, string text) {
1910                         rtf.Append(text);
1911                 }
1912
1913                 // start_pos and end_pos are 0-based
1914                 private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
1915                         StringBuilder   sb;
1916                         ArrayList       fonts;
1917                         ArrayList       colors;
1918                         Color           color;
1919                         Font            font;
1920                         Line            line;
1921                         LineTag         tag;
1922                         int             pos;
1923                         int             line_no;
1924                         int             line_len;
1925                         int             i;
1926                         int             length;
1927
1928                         sb = new StringBuilder();
1929                         fonts = new ArrayList(10);
1930                         colors = new ArrayList(10);
1931
1932                         // Two runs, first we parse to determine tables;
1933                         // and unlike most of our processing here we work on tags
1934
1935                         line = start_line;
1936                         line_no = start_line.line_no;
1937                         pos = start_pos;
1938
1939                         // Add default font and color; to optimize document content we don't
1940                         // use this.Font and this.ForeColor but the font/color from the first tag
1941                         tag = LineTag.FindTag(start_line, pos);
1942                         font = tag.Font;
1943                         color = tag.Color;
1944                         fonts.Add(font.Name);
1945                         colors.Add(color);
1946
1947                         while (line_no <= end_line.line_no) {
1948                                 line = document.GetLine(line_no);
1949                                 tag = LineTag.FindTag(line, pos);
1950
1951                                 if (line_no != end_line.line_no) {
1952                                         line_len = line.text.Length;
1953                                 } else {
1954                                         line_len = end_pos;
1955                                 }
1956
1957                                 while (pos < line_len) {
1958                                         if (tag.Font.Name != font.Name) {
1959                                                 font = tag.Font;
1960                                                 if (!fonts.Contains(font.Name)) {
1961                                                         fonts.Add(font.Name);
1962                                                 }
1963                                         }
1964
1965                                         if (tag.Color != color) {
1966                                                 color = tag.Color;
1967                                                 if (!colors.Contains(color)) {
1968                                                         colors.Add(color);
1969                                                 }
1970                                         }
1971
1972                                         pos = tag.Start + tag.Length - 1;
1973                                         tag = tag.Next;
1974                                 }
1975                                 pos = 0;
1976                                 line_no++;
1977                         }
1978
1979                         // We have the tables, emit the header
1980                         sb.Append("{\\rtf1\\ansi");
1981                         sb.Append("\\ansicpg1252");     // FIXME - is this correct?
1982
1983                         // Default Font
1984                         sb.Append(String.Format("\\deff{0}", fonts.IndexOf(this.Font.Name)));
1985
1986                         // Default Language 
1987                         sb.Append("\\deflang1033\n");   // FIXME - always 1033?
1988
1989                         // Emit the font table
1990                         sb.Append("{\\fonttbl");
1991                         for (i = 0; i < fonts.Count; i++) {
1992                                 sb.Append(String.Format("{{\\f{0}", i));        // {Font 
1993                                 sb.Append("\\fnil");                    // Family
1994                                 sb.Append("\\fcharset0 ");              // Charset ANSI<space>
1995                                 sb.Append((string)fonts[i]);            // Font name
1996                                 sb.Append(";}");                        // }
1997                         }
1998                         sb.Append("}\n");
1999
2000                         // Emit the color table (if needed)
2001                         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))) {
2002                                 sb.Append("{\\colortbl ");                      // Header and NO! default color
2003                                 for (i = 0; i < colors.Count; i++) {
2004                                         sb.Append(String.Format("\\red{0}", ((Color)colors[i]).R));
2005                                         sb.Append(String.Format("\\green{0}", ((Color)colors[i]).G));
2006                                         sb.Append(String.Format("\\blue{0}", ((Color)colors[i]).B));
2007                                         sb.Append(";");
2008                                 }
2009                                 sb.Append("}\n");
2010                         }
2011
2012                         sb.Append("{\\*\\generator Mono RichTextBox;}");
2013                         // Emit initial paragraph settings
2014                         tag = LineTag.FindTag(start_line, start_pos);
2015                         sb.Append("\\pard");    // Reset to default paragraph properties
2016                         EmitRTFFontProperties(sb, -1, fonts.IndexOf(tag.Font.Name), null, tag.Font);    // Font properties
2017                         sb.Append(" ");         // Space separator
2018
2019                         font = tag.Font;
2020                         color = (Color)colors[0];
2021                         line = start_line;
2022                         line_no = start_line.line_no;
2023                         pos = start_pos;
2024
2025                         while (line_no <= end_line.line_no) {
2026                                 line = document.GetLine(line_no);
2027                                 tag = LineTag.FindTag(line, pos);
2028
2029                                 if (line_no != end_line.line_no) {
2030                                         line_len = line.text.Length;
2031                                 } else {
2032                                         line_len = end_pos;
2033                                 }
2034
2035                                 while (pos < line_len) {
2036                                         length = sb.Length;
2037
2038                                         if (tag.Font != font) {
2039                                                 EmitRTFFontProperties(sb, fonts.IndexOf(font.Name), fonts.IndexOf(tag.Font.Name), font, tag.Font);
2040                                                 font = tag.Font;
2041                                         }
2042
2043                                         if (tag.Color != color) {
2044                                                 color = tag.Color;
2045                                                 sb.Append(String.Format("\\cf{0}", colors.IndexOf(color)));
2046                                         }
2047                                         if (length != sb.Length) {
2048                                                 sb.Append(" "); // Emit space to separate keywords from text
2049                                         }
2050
2051                                         // Emit the string itself
2052                                         if (line_no != end_line.line_no) {
2053                                                 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2054                                         } else {
2055                                                 if (end_pos < (tag.Start + tag.Length - 1)) {
2056                                                         // Emit partial tag only, end_pos is inside this tag
2057                                                         EmitRTFText(sb, tag.Line.text.ToString(pos, end_pos - pos));
2058                                                 } else {
2059                                                         EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2060                                                 }
2061                                         }
2062
2063                                         pos = tag.Start + tag.Length - 1;
2064                                         tag = tag.Next;
2065                                 }
2066                                 if (pos >= line.text.Length) {
2067                                         if (line.ending != LineEnding.Wrap) {
2068                                                 sb.Append("\\par\n");
2069                                         }
2070                                 }
2071                                 pos = 0;
2072                                 line_no++;
2073                         }
2074
2075                         sb.Append("}\n");
2076
2077                         return sb;
2078                 }
2079                 #endregion      // Private Methods
2080         }
2081 }