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