OSDN Git Service

22384105178fbfe462e2de7b442c4d7f01225711
[fooeditengine/FooEditEngine.git] / Core / Direct2D / D2DRenderCommon.cs
1 /*
2  * Copyright (C) 2013 FooProject
3  * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
5
6  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
7  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
8
9 You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
10  */
11 using System;
12 using System.Collections.Generic;
13 using System.Linq;
14 using System.Text;
15 using FooEditEngine;
16 using SharpDX;
17 using D2D = SharpDX.Direct2D1;
18 using DW = SharpDX.DirectWrite;
19 using DXGI = SharpDX.DXGI;
20 using System.Runtime.InteropServices;
21
22 namespace FooEditEngine
23 {
24     delegate void PreDrawOneLineHandler(MyTextLayout layout);
25
26     delegate void GetDpiHandler(out float dpix,out float dpiy);
27
28     /// <summary>
29     /// 文字列のアンチエイリアシングモードを指定する
30     /// </summary>
31     public enum TextAntialiasMode
32     {
33         /// <summary>
34         /// 最適なものが選択されます
35         /// </summary>
36         Default = D2D.TextAntialiasMode.Default,
37         /// <summary>
38         /// ClearTypeでアンチエイリアシングを行います
39         /// </summary>
40         ClearType = D2D.TextAntialiasMode.Cleartype,
41         /// <summary>
42         /// グレイスケールモードでアンチエイリアシングを行います
43         /// </summary>
44         GrayScale = D2D.TextAntialiasMode.Grayscale,
45         /// <summary>
46         /// アンチエイリアシングを行いません
47         /// </summary>
48         Aliased = D2D.TextAntialiasMode.Aliased,
49     }
50
51     sealed class ColorBrushCollection
52     {
53         ResourceManager<Color4, D2D.SolidColorBrush> cache = new ResourceManager<Color4, D2D.SolidColorBrush>();
54         D2D.RenderTarget _render;
55
56         public event EventHandler RenderChanged;
57
58         public D2D.RenderTarget Render
59         {
60             get
61             {
62                 return this._render;
63             }
64             set
65             {
66                 this._render = value;
67                 if (this.RenderChanged != null)
68                     this.RenderChanged(this, null);
69             }
70         }
71
72         public D2D.SolidColorBrush Get(Color4 key)
73         {
74             if (this.Render == null || this.Render.IsDisposed)
75                 throw new InvalidOperationException();
76             D2D.SolidColorBrush brush;
77             bool result = cache.TryGetValue(key, out brush);
78             if (!result)
79             {
80                 brush = new D2D.SolidColorBrush(this.Render, key);
81                 cache.Add(key, brush);
82             }
83             
84             return brush;
85         }
86
87         public void Clear()
88         {
89             cache.Clear();
90         }
91     }
92
93     sealed class StrokeCollection
94     {
95         ResourceManager<HilightType, D2D.StrokeStyle> cache = new ResourceManager<HilightType, D2D.StrokeStyle>();
96
97         public D2D.Factory Factory;
98
99         public D2D.StrokeStyle Get(HilightType type)
100         {
101             if(this.Factory == null || this.Factory.IsDisposed)
102                 throw new InvalidOperationException();
103             D2D.StrokeStyle stroke;
104             if (this.cache.TryGetValue(type, out stroke))
105                 return stroke;
106
107             D2D.StrokeStyleProperties prop = new D2D.StrokeStyleProperties();
108             prop.DashCap = D2D.CapStyle.Flat;
109             prop.DashOffset = 0;
110             prop.DashStyle = D2D.DashStyle.Solid;
111             prop.EndCap = D2D.CapStyle.Flat;
112             prop.LineJoin = D2D.LineJoin.Miter;
113             prop.MiterLimit = 0;
114             prop.StartCap = D2D.CapStyle.Flat;
115             switch (type)
116             {
117                 case HilightType.Sold:
118                 case HilightType.Url:
119                 case HilightType.Squiggle:
120                     prop.DashStyle = D2D.DashStyle.Solid;
121                     break;
122                 case HilightType.Dash:
123                     prop.DashStyle = D2D.DashStyle.Dash;
124                     break;
125                 case HilightType.DashDot:
126                     prop.DashStyle = D2D.DashStyle.DashDot;
127                     break;
128                 case HilightType.DashDotDot:
129                     prop.DashStyle = D2D.DashStyle.DashDotDot;
130                     break;
131                 case HilightType.Dot:
132                     prop.DashStyle = D2D.DashStyle.Dot;
133                     break;
134             }
135             stroke = new D2D.StrokeStyle(this.Factory, prop);
136             this.cache.Add(type, stroke);
137             return stroke;
138         }
139         public void Clear()
140         {
141             cache.Clear();
142         }
143     }
144
145     sealed class EffectCollection
146     {
147         ResourceManager<Color4, ResourceManager<HilightType, DrawingEffect>> cache = new ResourceManager<Color4, ResourceManager<HilightType, DrawingEffect>>();
148         public DrawingEffect Get(Color4 color, HilightType type)
149         {
150             ResourceManager<HilightType, DrawingEffect> hilights;
151             DrawingEffect effect;
152             if (this.cache.TryGetValue(color, out hilights))
153             {
154                 if (hilights.TryGetValue(type, out effect))
155                     return effect;
156                 effect = new DrawingEffect(type, color);
157                 hilights.Add(type, effect);
158                 return effect;
159             }
160             effect = new DrawingEffect(type, color);
161             hilights = new ResourceManager<HilightType, DrawingEffect>();
162             hilights.Add(type, effect);
163             this.cache.Add(color, hilights);
164             return effect;
165         }
166         public void Clear()
167         {
168             foreach (ResourceManager<HilightType, DrawingEffect> hilights in this.cache.Values)
169                 hilights.Clear();
170             cache.Clear();
171         }
172     }
173
174     class D2DRenderCommon : IDisposable
175     {
176         ColorBrushCollection Brushes = new ColorBrushCollection();
177         StrokeCollection Strokes = new StrokeCollection();
178         EffectCollection Effects = new EffectCollection();
179         InlineManager HiddenChars;
180         TextAntialiasMode _TextAntialiasMode;
181         Color4 _ControlChar,_Forground,_URL,_Hilight;
182         DW.Factory DWFactory;
183 #if METRO
184         D2D.Factory1 D2DFactory;
185 #else
186         D2D.Factory D2DFactory;
187 #endif
188         DW.TextFormat format;
189         D2D.Bitmap bitmap;
190         D2D.RenderTarget render;
191         CustomTextRenderer textRender;
192         int tabLength = 8;
193         bool hasCache, _ShowLineBreak;
194         Size renderSize = new Size();
195         Color4 _Comment, _Literal, _Keyword1, _Keyword2;
196
197         public D2DRenderCommon()
198         {
199             this.DWFactory = new DW.Factory(DW.FactoryType.Shared);
200 #if METRO
201             this.D2DFactory = new D2D.Factory1(D2D.FactoryType.MultiThreaded);
202 #else
203             this.D2DFactory = new D2D.Factory(D2D.FactoryType.MultiThreaded);
204 #endif
205             this.Strokes.Factory = this.D2DFactory;
206             this.ChangedRenderResource += (s, e) => { };
207             this.ChangedRightToLeft += (s, e) => { };
208         }
209
210         public event ChangedRenderResourceEventHandler ChangedRenderResource;
211
212         public event EventHandler ChangedRightToLeft;
213
214         public const int MiniumeWidth = 40;    //これ以上ないと誤操作が起こる
215
216         public void InitTextFormat(string fontName, float fontSize, DW.FontWeight fontWeigth = DW.FontWeight.Normal,DW.FontStyle fontStyle = DW.FontStyle.Normal)
217         {
218             if(this.format != null)
219                 this.format.Dispose();
220
221             float dpix, dpiy;
222             this.GetDpi(out dpix, out dpiy);
223
224             this.format = new DW.TextFormat(this.DWFactory, fontName, fontWeigth, fontStyle, fontSize);
225             this.format.WordWrapping = DW.WordWrapping.NoWrap;
226
227             if (this.HiddenChars == null)
228                 this.HiddenChars = new InlineManager(this.DWFactory, this.format, this.ControlChar, this.Brushes);
229             else
230                 this.HiddenChars.Format = this.format;
231
232             this.TabWidthChar = this.TabWidthChar;
233
234             this.hasCache = false;
235
236             MyTextLayout layout = new MyTextLayout(this.DWFactory, "0", this.format, float.MaxValue, float.MaxValue, dpix, false);
237             layout.RightToLeft = false;
238             this.emSize = new Size(layout.Width, layout.Height);
239             layout.Dispose();
240
241             layout = new MyTextLayout(this.DWFactory, "+", this.format, float.MaxValue, float.MaxValue, dpix, false);
242             layout.RightToLeft = false;
243 #if METRO
244             this.FoldingWidth = Math.Max(D2DRenderCommon.MiniumeWidth, layout.Width);
245 #else
246             this.FoldingWidth = layout.Width;
247 #endif
248             layout.Dispose();
249
250             this.ChangedRenderResource(this,new ChangedRenderRsourceEventArgs(ResourceType.Font));
251         }
252
253         public bool RightToLeft
254         {
255             get
256             {
257                 return this.format.ReadingDirection == DW.ReadingDirection.RightToLeft;
258             }
259             set
260             {
261                 this.format.ReadingDirection = value ? DW.ReadingDirection.RightToLeft : DW.ReadingDirection.LeftToRight;
262                 this.ChangedRightToLeft(this, null);                
263             }
264         }
265
266         public TextAntialiasMode TextAntialiasMode
267         {
268             get
269             {
270                 return this._TextAntialiasMode;
271             }
272             set
273             {
274                 if (this.render == null)
275                     throw new InvalidOperationException();
276                 this._TextAntialiasMode = value;
277                 this.render.TextAntialiasMode = (D2D.TextAntialiasMode)value;
278                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Antialias));
279             }
280         }
281
282         public bool ShowFullSpace
283         {
284             get
285             {
286                 if (this.HiddenChars == null)
287                     return false;
288                 else
289                     return this.HiddenChars.ContainsSymbol(' ');
290             }
291             set
292             {
293                 if (this.HiddenChars == null)
294                     throw new InvalidOperationException();
295                 if (value)
296                     this.HiddenChars.AddSymbol(' ', '□');
297                 else
298                     this.HiddenChars.RemoveSymbol(' ');
299             }
300         }
301
302         public bool ShowHalfSpace
303         {
304             get
305             {
306                 if (this.HiddenChars == null)
307                     return false;
308                 else
309                     return this.HiddenChars.ContainsSymbol(' ');
310             }
311             set
312             {
313                 if (this.HiddenChars == null)
314                     throw new InvalidOperationException();
315                 if (value)
316                     this.HiddenChars.AddSymbol(' ', 'ロ');
317                 else
318                     this.HiddenChars.RemoveSymbol(' ');
319             }
320         }
321
322         public bool ShowTab
323         {
324             get
325             {
326                 if (this.HiddenChars == null)
327                     return false;
328                 else
329                     return this.HiddenChars.ContainsSymbol('\t');
330             }
331             set
332             {
333                 if (this.HiddenChars == null)
334                     throw new InvalidOperationException();
335                 if (value)
336                     this.HiddenChars.AddSymbol('\t', '>');
337                 else
338                     this.HiddenChars.RemoveSymbol('\t');
339             }
340         }
341
342         public bool ShowLineBreak
343         {
344             get
345             {
346                 return this._ShowLineBreak;
347             }
348             set
349             {
350                 this._ShowLineBreak = value;
351             }
352         }
353
354         public Color4 Foreground
355         {
356             get
357             {
358                 return this._Forground;
359             }
360             set
361             {
362                 if (this.render == null)
363                     return;
364                 this._Forground = value;
365                 if (this.textRender != null)
366                     this.textRender.DefaultFore = value;
367                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
368             }
369         }
370
371         public Color4 Background
372         {
373             get;
374             set;
375         }
376
377         public Color4 InsertCaret
378         {
379             get;
380             set;
381         }
382
383         public Color4 OverwriteCaret
384         {
385             get;
386             set;
387         }
388
389         public Color4 LineMarker
390         {
391             get;
392             set;
393         }
394
395         public Color4 UpdateArea
396         {
397             get;
398             set;
399         }
400
401         public Color4 LineNumber
402         {
403             get;
404             set;
405         }
406
407         public Color4 ControlChar
408         {
409             get
410             {
411                 return this._ControlChar;
412             }
413             set
414             {
415                 this._ControlChar = value;
416                 if (this.HiddenChars != null)
417                     this.HiddenChars.Fore = value;
418                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
419             }
420         }
421
422         public Color4 Url
423         {
424             get
425             {
426                 return this._URL;
427             }
428             set
429             {
430                 this._URL = value;
431                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
432             }
433         }
434
435         public Color4 Hilight
436         {
437             get
438             {
439                 return this._Hilight;
440             }
441             set
442             {
443                 this._Hilight = value;
444             }
445         }
446
447         public Color4 Comment
448         {
449             get
450             {
451                 return this._Comment;
452             }
453             set
454             {
455                 this._Comment = value;
456                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
457             }
458         }
459
460         public Color4 Literal
461         {
462             get
463             {
464                 return this._Literal;
465             }
466             set
467             {
468                 this._Literal = value;
469                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
470             }
471         }
472
473         public Color4 Keyword1
474         {
475             get
476             {
477                 return this._Keyword1;
478             }
479             set
480             {
481                 this._Keyword1 = value;
482                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
483             }
484         }
485
486         public Color4 Keyword2
487         {
488             get
489             {
490                 return this._Keyword2;
491             }
492             set
493             {
494                 this._Keyword2 = value;
495                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
496             }
497         }
498
499         public Rectangle TextArea
500         {
501             get;
502             set;
503         }
504
505         public double LineNemberWidth
506         {
507             get
508             {
509                 return this.emSize.Width * EditView.LineNumberLength;
510             }
511         }
512
513         public double FoldingWidth
514         {
515             get;
516             private set;
517         }
518
519         public int TabWidthChar
520         {
521             get { return this.tabLength; }
522             set
523             {
524                 if (value == 0)
525                     return;
526                 this.tabLength = value;
527                 DW.TextLayout layout = new DW.TextLayout(this.DWFactory, "0", this.format, float.MaxValue, float.MaxValue);
528                 float width = (float)(layout.Metrics.Width * value);
529                 this.HiddenChars.TabWidth = width;
530                 this.format.IncrementalTabStop = width;
531             }
532         }
533
534         public Size emSize
535         {
536             get;
537             private set;
538         }
539
540         public void DrawGripper(Point p, double radius)
541         {
542             D2D.Ellipse ellipse = new D2D.Ellipse();
543             ellipse.Point = p;
544             ellipse.RadiusX = (float)radius;
545             ellipse.RadiusY = (float)radius;
546             this.render.FillEllipse(ellipse, this.Brushes.Get(this.Background));
547             this.render.DrawEllipse(ellipse, this.Brushes.Get(this.Foreground));
548         }
549
550         public void ReConstructDeviceResource()
551         {
552             this.ReConstructDeviceResource(this.renderSize.Width, this.renderSize.Height);
553         }
554
555         public void ReConstructDeviceResource(double width, double height)
556         {
557             this.DestructDeviceResource();
558             this.ConstructDeviceResource(width, height);
559         }
560
561         public virtual void DrawCachedBitmap(Rectangle rect)
562         {
563             if (this.render == null || this.render.IsDisposed)
564                 return;
565             render.DrawBitmap(this.bitmap, rect, 1.0f, D2D.BitmapInterpolationMode.Linear, rect);
566         }
567
568         public virtual void CacheContent()
569         {
570             if (this.render == null || this.bitmap == null || this.bitmap.IsDisposed || this.render.IsDisposed)
571                 return;
572             render.Flush();
573             this.bitmap.CopyFromRenderTarget(this.render, new SharpDX.Point(), new SharpDX.Rectangle(0, 0, (int)this.renderSize.Width, (int)this.renderSize.Height));
574             this.hasCache = true;
575         }
576
577         public virtual bool IsVaildCache()
578         {
579             return this.hasCache;
580         }
581
582         public virtual void BegineDraw()
583         {
584             if (this.render == null || this.render.IsDisposed)
585                 return;
586             this.render.BeginDraw();
587             this.render.AntialiasMode = D2D.AntialiasMode.Aliased;
588         }
589
590         public virtual void EndDraw()
591         {
592             if (this.render == null || this.render.IsDisposed)
593                 return;
594             this.render.AntialiasMode = D2D.AntialiasMode.PerPrimitive;
595             this.render.EndDraw();
596         }
597
598         public void DrawString(string str, double x, double y, StringAlignment align, Size layoutRect, StringColorType colorType = StringColorType.Forground)
599         {
600             if (this.render == null || this.render.IsDisposed)
601                 return;
602             float dpix, dpiy;
603             D2D.SolidColorBrush brush;
604             switch (colorType)
605             {
606                 case StringColorType.Forground:
607                     brush = this.Brushes.Get(this.Foreground);
608                     break;
609                 case StringColorType.LineNumber:
610                     brush = this.Brushes.Get(this.LineNumber);
611                     break;
612                 default:
613                     throw new ArgumentOutOfRangeException();
614             }
615             this.GetDpi(out dpix, out dpiy);
616             MyTextLayout layout = new MyTextLayout(this.DWFactory, str, this.format, (float)layoutRect.Width, (float)layoutRect.Height,dpix,false);
617             layout.StringAlignment = align;
618             layout.Draw(this.render, (float)x, (float)y, brush);
619             layout.Dispose();
620         }
621
622         public void DrawFoldingMark(bool expand, double x, double y)
623         {
624             string mark = expand ? "-" : "+";
625             this.DrawString(mark, x, y,StringAlignment.Left, new Size(this.FoldingWidth, this.emSize.Height));
626         }
627
628         public void FillRectangle(Rectangle rect,FillRectType type)
629         {
630             if (this.render == null || this.render.IsDisposed)
631                 return;
632             D2D.SolidColorBrush brush = null;
633             switch(type)
634             {
635                 case FillRectType.OverwriteCaret:
636                     brush = this.Brushes.Get(this.OverwriteCaret);
637                     this.render.FillRectangle(rect, brush);
638                     break;
639                 case FillRectType.InsertCaret:
640                     brush = this.Brushes.Get(this.InsertCaret);
641                     this.render.FillRectangle(rect, brush);
642                     break;
643                 case FillRectType.InsertPoint:
644                     brush = this.Brushes.Get(this.Hilight);
645                     this.render.FillRectangle(rect, brush);
646                     break;
647                 case FillRectType.LineMarker:
648                     brush = this.Brushes.Get(this.LineMarker);
649                     this.render.DrawRectangle(rect, brush, EditView.LineMarkerThickness);
650                     break;
651                 case FillRectType.UpdateArea:
652                     brush = this.Brushes.Get(this.UpdateArea);
653                     this.render.FillRectangle(rect, brush);
654                     break;
655             }
656         }
657
658         public void FillBackground(Rectangle rect)
659         {
660             if (this.render == null || this.render.IsDisposed)
661                 return;
662             this.render.Clear(this.Background);
663         }
664
665         public void DrawOneLine(LineToIndexTable lti, int row, double x, double y, IEnumerable<Selection> SelectRanges,PreDrawOneLineHandler PreDrawOneLine)
666         {
667             int lineLength = lti.GetLengthFromLineNumber(row);
668
669             if (lineLength == 0 || this.render == null || this.render.IsDisposed)
670                 return;
671
672             MyTextLayout layout = (MyTextLayout)lti.GetLayout(row);
673
674             this.render.PushAxisAlignedClip(this.TextArea, D2D.AntialiasMode.Aliased);
675
676             if(PreDrawOneLine != null)
677                 PreDrawOneLine(layout);
678
679             if (SelectRanges != null)
680             {
681                 foreach (Selection sel in SelectRanges)
682                 {
683                     if (sel.length == 0 || sel.start == -1)
684                         continue;
685
686                     this.DrawMarkerEffect(layout, HilightType.Select, sel.start, sel.length, x, y, false);
687                 }
688             }
689
690             layout.Draw(textRender, (float)x, (float)y);
691
692             this.render.PopAxisAlignedClip();
693         }
694
695         public void SetTextColor(MyTextLayout layout,int start, int length, Color4? color)
696         {
697             if (color == null)
698                 return;
699             layout.SetDrawingEffect(this.Brushes.Get((Color4)color), new DW.TextRange(start, length));
700         }
701
702         public void DrawLine(Point from, Point to)
703         {
704             D2D.Brush brush = this.Brushes.Get(this.Foreground);
705             D2D.StrokeStyle stroke = this.Strokes.Get(HilightType.Sold);
706             this.render.DrawLine(from, to, brush, 1.0f, stroke);
707         }
708
709         public void DrawMarkerEffect(MyTextLayout layout, HilightType type, int start, int length, double x, double y, bool isBold, Color4? effectColor = null)
710         {
711             if (type == HilightType.None)
712                 return;
713
714             float thickness = isBold ? 2 : 1;
715
716             Color4 color;
717             if (effectColor != null)
718                 color = (Color4)effectColor;
719             else if (type == HilightType.Select)
720                 color = this.Hilight;
721             else
722                 color = this.Foreground;
723
724             IMarkerEffecter effecter = null;
725             D2D.SolidColorBrush brush = this.Brushes.Get(color);
726
727             if (type == HilightType.Squiggle)
728                 effecter = new D2DSquilleLineMarker(this.render, brush, this.Strokes.Get(HilightType.Squiggle), thickness);
729             else if (type == HilightType.Select)
730                 effecter = new HilightMarker(this.render, brush);
731             else if (type == HilightType.None)
732                 effecter = null;
733             else
734                 effecter = new LineMarker(this.render, brush, this.Strokes.Get(type), thickness);
735
736             if (effecter != null)
737             {
738                 bool isUnderline = type != HilightType.Select;
739
740                 DW.HitTestMetrics[] metrics = layout.HitTestTextRange(start, length, (float)x, (float)y);
741                 foreach (DW.HitTestMetrics metric in metrics)
742                 {
743                     float offset = isUnderline ? metric.Height : 0;
744                     effecter.Draw(metric.Left, metric.Top + offset, metric.Width, metric.Height);
745                 }
746             }
747         }
748
749         public ITextLayout CreateLaytout(string str, SyntaxInfo[] syntaxCollection, IEnumerable<Marker> MarkerRanges)
750         {
751             float dpix,dpiy;
752             this.GetDpi(out dpix,out dpiy);
753
754             bool hasNewLine = str.Length > 0 && str[str.Length - 1] == Document.NewLine;
755             MyTextLayout newLayout = new MyTextLayout(this.DWFactory,
756                 str,
757                 this.format,
758                 this.TextArea.Width,
759                 this.TextArea.Height,
760                 dpiy,
761                 hasNewLine && this._ShowLineBreak);
762             ParseLayout(newLayout, str);
763             if (syntaxCollection != null)
764             {
765                 foreach (SyntaxInfo s in syntaxCollection)
766                 {
767                     D2D.SolidColorBrush brush = this.Brushes.Get(this.Foreground);
768                     switch (s.type)
769                     {
770                         case TokenType.Comment:
771                             brush = this.Brushes.Get(this.Comment);
772                             break;
773                         case TokenType.Keyword1:
774                             brush = this.Brushes.Get(this.Keyword1);
775                             break;
776                         case TokenType.Keyword2:
777                             brush = this.Brushes.Get(this.Keyword2);
778                             break;
779                         case TokenType.Literal:
780                             brush = this.Brushes.Get(this.Literal);
781                             break;
782                     }
783                     newLayout.SetDrawingEffect(brush, new DW.TextRange(s.index, s.length));
784                 }
785             }
786
787             if (MarkerRanges != null)
788             {
789                 foreach (Marker m in MarkerRanges)
790                 {
791                     if (m.start == -1 || m.length == 0)
792                         continue;
793                     Color4 color = new Color4(m.color.R / 255.0f, m.color.G / 255.0f, m.color.B / 255.0f, m.color.A / 255.0f);
794                     if (m.hilight == HilightType.Url)
795                         color = this.Url;
796                     newLayout.SetDrawingEffect(this.Effects.Get(color, m.hilight), new DW.TextRange(m.start, m.length));
797                 }
798             }
799
800             return newLayout;
801        }
802
803         public List<LineToIndexTableData> BreakLine(Document doc, LineToIndexTable layoutLineCollection, int startIndex, int endIndex, double wrapwidth)
804         {
805             List<LineToIndexTableData> output = new List<LineToIndexTableData>();
806
807             this.format.WordWrapping = DW.WordWrapping.Wrap;
808
809             foreach (string str in doc.GetLines(startIndex, endIndex))
810             {
811                 DW.TextLayout layout = new DW.TextLayout(this.DWFactory, str, this.format, (float)wrapwidth, float.MaxValue);
812
813                 int i = startIndex;
814                 foreach (DW.LineMetrics metrics in layout.GetLineMetrics())
815                 {
816                     if (metrics.Length == 0 && metrics.NewlineLength == 0)
817                         continue;
818
819                     bool lineend = false;
820                     if (metrics.NewlineLength > 0)
821                         lineend = true;
822
823                     output.Add(layoutLineCollection.CreateLineToIndexTableData(i, (int)metrics.Length, lineend, null));
824                     i += Util.RoundUp(metrics.Length);
825                 }
826
827                 layout.Dispose();
828
829                 startIndex += str.Length;
830             }
831
832             this.format.WordWrapping = DW.WordWrapping.NoWrap;
833
834             if (output.Count > 0)
835                 output.Last().LineEnd = true;
836
837             return output;
838         }
839
840         public virtual void Dispose()
841         {
842             this.DestructDeviceResource();
843             this.HiddenChars.Clear();
844             if (this.format != null)
845                 this.format.Dispose();
846             if(this.DWFactory != null)
847                 this.DWFactory.Dispose();
848             if(this.D2DFactory != null)
849                 this.D2DFactory.Dispose();
850         }
851
852         public void ConstructDeviceResource(double width, double height)
853         {
854             float dpiX, dpiY;
855             this.GetDpi(out dpiX, out dpiY);
856             D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties(
857                 D2D.RenderTargetType.Default,
858                 new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
859                 dpiX,
860                 dpiY,
861                 D2D.RenderTargetUsage.None,
862                 D2D.FeatureLevel.Level_DEFAULT);
863
864             this.render = this.ConstructRender(this.D2DFactory,prop,width,height);
865
866             this.Brushes.Render = this.render;
867
868             D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
869             bmpProp.DpiX = dpiX;
870             bmpProp.DpiY = dpiY;
871             bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore);
872             this.bitmap = new D2D.Bitmap(this.render, new SharpDX.Size2((int)width, (int)height), bmpProp);
873             this.hasCache = false;
874
875             this.ConstrctedResource();
876
877             this.textRender = new CustomTextRenderer(this.render, this.Brushes,this.Strokes, this.Foreground);
878
879             this.renderSize.Width = width;
880             this.renderSize.Height = height;
881
882             this.TextAntialiasMode = this._TextAntialiasMode;
883         }
884
885 #if METRO
886         protected virtual D2D.RenderTarget ConstructRender(D2D.Factory1 factory, D2D.RenderTargetProperties prop, double width, double height)
887 #else
888         protected virtual D2D.RenderTarget ConstructRender(D2D.Factory factory, D2D.RenderTargetProperties prop, double width, double height)
889 #endif
890         {
891             throw new NotImplementedException();
892         }
893
894         protected virtual void ConstrctedResource()
895         {
896             throw new NotImplementedException();
897         }
898
899         public virtual void GetDpi(out float dpix,out float dpiy)
900         {
901             throw new NotImplementedException();
902         }
903
904         protected virtual void DestructRender()
905         {
906             throw new NotImplementedException();
907
908         }
909
910         protected virtual void ReCreateTarget()
911         {
912             throw new NotImplementedException();
913         }
914
915         public void DestructDeviceResource()
916         {
917             this.hasCache = false;
918             if (this.bitmap != null)
919                 this.bitmap.Dispose();
920             this.Brushes.Clear();
921             this.Strokes.Clear();
922             this.Effects.Clear();
923             if (this.textRender != null)
924                 this.textRender.Dispose();
925             this.DestructRender();
926         }
927
928         void ParseLayout(MyTextLayout layout, string str)
929         {
930             for (int i = 0; i < str.Length; i++)
931             {
932                 DW.InlineObject inlineObject = this.HiddenChars.Get(layout,i, str);
933                 if (inlineObject != null)
934                 {
935                     layout.SetInlineObject(inlineObject, new DW.TextRange(i, 1));
936                     layout.SetDrawingEffect(this.Brushes.Get(this.ControlChar), new DW.TextRange(i, 1));
937                 }
938             }
939             layout.SetLineBreakBrush(this.Brushes.Get(this.ControlChar));
940         }
941     }
942 }