OSDN Git Service

文字の表示がにじむ問題を修正した
[fooeditengine/FooEditEngine.git] / Common / 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     sealed 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 void InitTextFormat(string fontName, float fontSize, DW.FontWeight fontWeigth = DW.FontWeight.Normal,DW.FontStyle fontStyle = DW.FontStyle.Normal)
215         {
216             if(this.format != null)
217                 this.format.Dispose();
218             
219             this.format = new DW.TextFormat(this.DWFactory, fontName,fontWeigth,fontStyle, fontSize / 72.0f * 96.0f);
220             this.format.WordWrapping = DW.WordWrapping.NoWrap;
221
222             if (this.HiddenChars == null)
223             {
224                 this.HiddenChars = new InlineManager(this.DWFactory, this.format, this.ControlChar, this.Brushes);
225                 this.HiddenChars.TabWidth = this.HiddenChars.TabWidth;
226             }
227             else
228                 this.HiddenChars.Format = this.format;
229
230             this.hasCache = false;
231
232             DW.TextLayout layout = new DW.TextLayout(this.DWFactory, "0", this.format, float.MaxValue, float.MaxValue);
233             layout.ReadingDirection = DW.ReadingDirection.LeftToRight;
234             this.emSize = new Size(layout.Metrics.WidthIncludingTrailingWhitespace, layout.Metrics.Height);
235
236             layout = new DW.TextLayout(this.DWFactory, "+", this.format, float.MaxValue, float.MaxValue);
237             layout.ReadingDirection = DW.ReadingDirection.LeftToRight;
238             this.FoldingWidth = layout.Metrics.Width;
239
240             this.ChangedRenderResource(this,new ChangedRenderRsourceEventArgs(ResourceType.Font));
241         }
242
243         public bool RightToLeft
244         {
245             get
246             {
247                 return this.format.ReadingDirection == DW.ReadingDirection.RightToLeft;
248             }
249             set
250             {
251                 this.format.ReadingDirection = value ? DW.ReadingDirection.RightToLeft : DW.ReadingDirection.LeftToRight;
252                 this.ChangedRightToLeft(this, null);                
253             }
254         }
255
256         public TextAntialiasMode TextAntialiasMode
257         {
258             get
259             {
260                 return this._TextAntialiasMode;
261             }
262             set
263             {
264                 if (this.render == null)
265                     throw new InvalidOperationException();
266                 this._TextAntialiasMode = value;
267                 this.render.TextAntialiasMode = (D2D.TextAntialiasMode)value;
268                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Antialias));
269             }
270         }
271
272         public bool ShowFullSpace
273         {
274             get
275             {
276                 if (this.HiddenChars == null)
277                     return false;
278                 else
279                     return this.HiddenChars.ContainsSymbol(' ');
280             }
281             set
282             {
283                 if (this.HiddenChars == null)
284                     throw new InvalidOperationException();
285                 if (value)
286                     this.HiddenChars.AddSymbol(' ', '□');
287                 else
288                     this.HiddenChars.RemoveSymbol(' ');
289                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.InlineChar));
290             }
291         }
292
293         public bool ShowHalfSpace
294         {
295             get
296             {
297                 if (this.HiddenChars == null)
298                     return false;
299                 else
300                     return this.HiddenChars.ContainsSymbol(' ');
301             }
302             set
303             {
304                 if (this.HiddenChars == null)
305                     throw new InvalidOperationException();
306                 if (value)
307                     this.HiddenChars.AddSymbol(' ', 'ロ');
308                 else
309                     this.HiddenChars.RemoveSymbol(' ');
310                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.InlineChar));
311             }
312         }
313
314         public bool ShowTab
315         {
316             get
317             {
318                 if (this.HiddenChars == null)
319                     return false;
320                 else
321                     return this.HiddenChars.ContainsSymbol('\t');
322             }
323             set
324             {
325                 if (this.HiddenChars == null)
326                     throw new InvalidOperationException();
327                 if (value)
328                     this.HiddenChars.AddSymbol('\t', '>');
329                 else
330                     this.HiddenChars.RemoveSymbol('\t');
331                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.InlineChar));
332             }
333         }
334
335         public bool ShowLineBreak
336         {
337             get
338             {
339                 return this._ShowLineBreak;
340             }
341             set
342             {
343                 this._ShowLineBreak = value;
344                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.InlineChar));
345             }
346         }
347
348         public Color4 Foreground
349         {
350             get
351             {
352                 return this._Forground;
353             }
354             set
355             {
356                 if (this.render == null)
357                     return;
358                 this._Forground = value;
359                 if (this.textRender != null)
360                     this.textRender.DefaultFore = value;
361                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
362             }
363         }
364
365         public Color4 Background
366         {
367             get;
368             set;
369         }
370
371         public Color4 InsertCaret
372         {
373             get;
374             set;
375         }
376
377         public Color4 OverwriteCaret
378         {
379             get;
380             set;
381         }
382
383         public Color4 LineMarker
384         {
385             get;
386             set;
387         }
388
389         public Color4 ControlChar
390         {
391             get
392             {
393                 return this._ControlChar;
394             }
395             set
396             {
397                 if (this.render == null)
398                     return;
399                 this._ControlChar = value;
400                 if (this.HiddenChars != null)
401                     this.HiddenChars.Fore = value;
402                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
403             }
404         }
405
406         public Color4 Url
407         {
408             get
409             {
410                 return this._URL;
411             }
412             set
413             {
414                 if (this.render == null)
415                     return;
416
417                 this._URL = value;
418                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
419             }
420         }
421
422         public Color4 Hilight
423         {
424             get
425             {
426                 return this._Hilight;
427             }
428             set
429             {
430                 this._Hilight = value;
431             }
432         }
433
434         public Color4 Comment
435         {
436             get
437             {
438                 return this._Comment;
439             }
440             set
441             {
442                 this._Comment = value;
443                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
444             }
445         }
446
447         public Color4 Literal
448         {
449             get
450             {
451                 return this._Literal;
452             }
453             set
454             {
455                 this._Literal = value;
456                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
457             }
458         }
459
460         public Color4 Keyword1
461         {
462             get
463             {
464                 return this._Keyword1;
465             }
466             set
467             {
468                 this._Keyword1 = value;
469                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
470             }
471         }
472
473         public Color4 Keyword2
474         {
475             get
476             {
477                 return this._Keyword2;
478             }
479             set
480             {
481                 this._Keyword2 = value;
482                 this.ChangedRenderResource(this, new ChangedRenderRsourceEventArgs(ResourceType.Brush));
483             }
484         }
485
486         public Rectangle ClipRect
487         {
488             get;
489             set;
490         }
491
492         public double LineNemberWidth
493         {
494             get
495             {
496                 return this.emSize.Width * (EditView.LineNumberLength + 1);
497             }
498         }
499
500         public double FoldingWidth
501         {
502             get;
503             private set;
504         }
505
506         public int TabWidthChar
507         {
508             get { return this.tabLength; }
509             set
510             {
511                 this.tabLength = value;
512                 DW.TextLayout layout = new DW.TextLayout(this.DWFactory, "0", this.format, float.MaxValue, float.MaxValue);
513                 float width = (float)(layout.Metrics.Width * value);
514                 this.HiddenChars.TabWidth = width;
515                 this.format.IncrementalTabStop = width;
516             }
517         }
518
519         public Size emSize
520         {
521             get;
522             private set;
523         }
524
525         public void DrawGripper(Point p, double radius)
526         {
527             D2D.Ellipse ellipse = new D2D.Ellipse();
528             ellipse.Point = p;
529             ellipse.RadiusX = (float)radius;
530             ellipse.RadiusY = (float)radius;
531             this.render.FillEllipse(ellipse, this.Brushes.Get(this.Background));
532             this.render.DrawEllipse(ellipse, this.Brushes.Get(this.Foreground));
533         }
534
535         public void ReConstructDeviceResource()
536         {
537             this.ReConstructDeviceResource(this.renderSize.Width, this.renderSize.Height);
538         }
539
540         public void ReConstructDeviceResource(double width, double height)
541         {
542             this.DestructDeviceResource();
543             this.ConstructDeviceResource(width, height);
544         }
545
546         public void DrawCachedBitmap(Rectangle rect)
547         {
548             if (this.render == null || this.render.IsDisposed)
549                 return;
550             render.DrawBitmap(this.bitmap, rect, 1.0f, D2D.BitmapInterpolationMode.Linear, rect);
551         }
552
553         public void CacheContent()
554         {
555             if (this.render == null || this.bitmap == null || this.bitmap.IsDisposed || this.render.IsDisposed)
556                 return;
557             render.Flush();
558             this.bitmap.CopyFromRenderTarget(this.render, new SharpDX.Point(), new SharpDX.Rectangle(0, 0, (int)this.renderSize.Width, (int)this.renderSize.Height));
559             this.hasCache = true;
560         }
561
562         public bool IsVaildCache()
563         {
564             return this.hasCache;
565         }
566
567         public void BegineDraw()
568         {
569             if (this.render == null || this.render.IsDisposed)
570                 return;
571             this.render.BeginDraw();
572             this.render.AntialiasMode = D2D.AntialiasMode.Aliased;
573         }
574
575         public void EndDraw()
576         {
577             if (this.render == null || this.render.IsDisposed)
578                 return;
579             this.render.AntialiasMode = D2D.AntialiasMode.PerPrimitive;
580             this.render.EndDraw();
581         }
582
583         public void DrawString(string str, double x, double y, StringAlignment align, Size layoutRect)
584         {
585             if (this.render == null || this.render.IsDisposed)
586                 return;
587             float dpix, dpiy;
588             this.GetDpi(out dpix,out dpiy);
589             MyTextLayout layout = new MyTextLayout(this.DWFactory, str, this.format, (float)layoutRect.Width, (float)layoutRect.Height,dpix,false);
590             layout.StringAlignment = align;
591             D2D.SolidColorBrush brush = this.Brushes.Get(this.Foreground);
592             layout.Draw(this.render, (float)x, (float)y, brush);
593             layout.Dispose();
594         }
595
596         public void DrawFoldingMark(bool expand, double x, double y)
597         {
598             string mark = expand ? "-" : "+";
599             this.DrawString(mark, x, y,StringAlignment.Left, new Size(this.FoldingWidth, this.emSize.Height));
600         }
601
602         public void FillRectangle(Rectangle rect,FillRectType type)
603         {
604             const float lineMarkerThickness = 2;
605             if (this.render == null || this.render.IsDisposed)
606                 return;
607             D2D.SolidColorBrush brush = null;
608             switch(type)
609             {
610                 case FillRectType.OverwriteCaret:
611                     brush = this.Brushes.Get(this.OverwriteCaret);
612                     this.render.FillRectangle(rect, brush);
613                     break;
614                 case FillRectType.InsertCaret:
615                     brush = this.Brushes.Get(this.InsertCaret);
616                     this.render.FillRectangle(rect, brush);
617                     break;
618                 case FillRectType.InsertPoint:
619                     brush = this.Brushes.Get(this.Hilight);
620                     this.render.FillRectangle(rect, brush);
621                     break;
622                 case FillRectType.LineMarker:
623                     brush = this.Brushes.Get(this.LineMarker);
624                     this.render.DrawRectangle(rect, brush, lineMarkerThickness);
625                     break;
626             }
627         }
628
629         public void FillBackground(Rectangle rect)
630         {
631             if (this.render == null || this.render.IsDisposed)
632                 return;
633             this.render.Clear(this.Background);
634         }
635
636         public void DrawOneLine(LineToIndexTable lti, int row, double x, double y, IEnumerable<Selection> SelectRanges,PreDrawOneLineHandler PreDrawOneLine)
637         {
638             int lineLength = lti.GetLengthFromLineNumber(row);
639
640             if (lineLength == 0 || this.render == null || this.render.IsDisposed)
641                 return;
642
643             MyTextLayout layout = (MyTextLayout)lti.GetLayout(row);
644
645             this.render.PushAxisAlignedClip(this.ClipRect, D2D.AntialiasMode.Aliased);
646
647             if(PreDrawOneLine != null)
648                 PreDrawOneLine(layout);
649
650             if (SelectRanges != null)
651             {
652                 foreach (Selection sel in SelectRanges)
653                 {
654                     if (sel.length == 0 || sel.start == -1)
655                         continue;
656
657                     this.DrawMarkerEffect(layout, HilightType.Select, sel.start, sel.length, x, y, false);
658                 }
659             }
660
661             layout.Draw(textRender, (float)x, (float)y);
662
663             this.render.PopAxisAlignedClip();
664         }
665
666         public void SetTextColor(MyTextLayout layout,int start, int length, Color4? color)
667         {
668             if (color == null)
669                 return;
670             layout.SetDrawingEffect(this.Brushes.Get((Color4)color), new DW.TextRange(start, length));
671         }
672
673         public void DrawLine(Point from, Point to)
674         {
675             D2D.Brush brush = this.Brushes.Get(this.Foreground);
676             D2D.StrokeStyle stroke = this.Strokes.Get(HilightType.Sold);
677             this.render.DrawLine(from, to, brush, 1.0f, stroke);
678         }
679
680         public void DrawMarkerEffect(MyTextLayout layout, HilightType type, int start, int length, double x, double y, bool isBold, Color4? effectColor = null)
681         {
682             if (type == HilightType.None)
683                 return;
684
685             float thickness = isBold ? 2 : 1;
686
687             Color4 color;
688             if (effectColor != null)
689                 color = (Color4)effectColor;
690             else if (type == HilightType.Select)
691                 color = this.Hilight;
692             else
693                 color = this.Foreground;
694
695             IMarkerEffecter effecter = null;
696             D2D.SolidColorBrush brush = this.Brushes.Get(color);
697
698             if (type == HilightType.Squiggle)
699                 effecter = new D2DSquilleLineMarker(this.render, brush, this.Strokes.Get(HilightType.Squiggle), thickness);
700             else if (type == HilightType.Select)
701                 effecter = new HilightMarker(this.render, brush);
702             else if (type == HilightType.None)
703                 effecter = null;
704             else
705                 effecter = new LineMarker(this.render, brush, this.Strokes.Get(type), thickness);
706
707             if (effecter != null)
708             {
709                 bool isUnderline = type != HilightType.Select;
710
711                 DW.HitTestMetrics[] metrics = layout.HitTestTextRange(start, length, (float)x, (float)y);
712                 foreach (DW.HitTestMetrics metric in metrics)
713                 {
714                     float offset = isUnderline ? metric.Height : 0;
715                     effecter.Draw(metric.Left, metric.Top + offset, metric.Width, metric.Height);
716                 }
717             }
718         }
719
720         public ITextLayout CreateLaytout(string str, SyntaxInfo[] syntaxCollection, IEnumerable<Marker> MarkerRanges)
721         {
722             float dpix,dpiy;
723             this.GetDpi(out dpix,out dpiy);
724
725             bool hasNewLine = str.Length > 0 && str[str.Length - 1] == Document.NewLine;
726             MyTextLayout newLayout = new MyTextLayout(this.DWFactory,
727                 str,
728                 this.format,
729                 this.ClipRect.Width,
730                 this.ClipRect.Height,
731                 dpiy,
732                 hasNewLine && this._ShowLineBreak);
733             ParseLayout(newLayout, str);
734             if (syntaxCollection != null)
735             {
736                 foreach (SyntaxInfo s in syntaxCollection)
737                 {
738                     D2D.SolidColorBrush brush = this.Brushes.Get(this.Foreground);
739                     switch (s.type)
740                     {
741                         case TokenType.Comment:
742                             brush = this.Brushes.Get(this.Comment);
743                             break;
744                         case TokenType.Keyword1:
745                             brush = this.Brushes.Get(this.Keyword1);
746                             break;
747                         case TokenType.Keyword2:
748                             brush = this.Brushes.Get(this.Keyword2);
749                             break;
750                         case TokenType.Literal:
751                             brush = this.Brushes.Get(this.Literal);
752                             break;
753                     }
754                     newLayout.SetDrawingEffect(brush, new DW.TextRange(s.index, s.length));
755                 }
756             }
757
758             if (MarkerRanges != null)
759             {
760                 foreach (Marker m in MarkerRanges)
761                 {
762                     if (m.start == -1 || m.length == 0)
763                         continue;
764                     Color4 color = new Color4(m.R / 255.0f, m.G / 255.0f, m.B / 255.0f, m.A / 255.0f);
765                     if (m.hilight == HilightType.Url)
766                         color = this.Url;
767                     newLayout.SetDrawingEffect(this.Effects.Get(color, m.hilight), new DW.TextRange(m.start, m.length));
768                 }
769             }
770
771             return newLayout;
772        }
773
774         public List<LineToIndexTableData> BreakLine(Document doc, LineToIndexTable layoutLineCollection, int startIndex, int endIndex, double wrapwidth)
775         {
776             List<LineToIndexTableData> output = new List<LineToIndexTableData>();
777
778             this.format.WordWrapping = DW.WordWrapping.Wrap;
779
780             foreach (string str in doc.GetLines(startIndex, endIndex))
781             {
782                 DW.TextLayout layout = new DW.TextLayout(this.DWFactory, str, this.format, (float)wrapwidth, float.MaxValue);
783
784                 int i = startIndex;
785                 foreach (DW.LineMetrics metrics in layout.GetLineMetrics())
786                 {
787                     if (metrics.Length == 0 && metrics.NewlineLength == 0)
788                         continue;
789
790                     bool lineend = false;
791                     if (metrics.NewlineLength > 0)
792                         lineend = true;
793
794                     output.Add(layoutLineCollection.CreateLineToIndexTableData(i, (int)metrics.Length, lineend, null));
795                     i += Util.RoundUp(metrics.Length);
796                 }
797
798                 layout.Dispose();
799
800                 startIndex += str.Length;
801             }
802
803             this.format.WordWrapping = DW.WordWrapping.NoWrap;
804
805             if (output.Count > 0)
806                 output.Last().LineEnd = true;
807
808             return output;
809         }
810
811         public void Dispose()
812         {
813             this.DestructDeviceResource();
814             this.HiddenChars.Clear();
815             if (this.format != null)
816                 this.format.Dispose();
817             if(this.DWFactory != null)
818                 this.DWFactory.Dispose();
819             if(this.D2DFactory != null)
820                 this.D2DFactory.Dispose();
821         }
822
823         public void ConstructDeviceResource(double width, double height)
824         {
825             float dpiX, dpiY;
826             this.GetDpi(out dpiX, out dpiY);
827             D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties(
828                 D2D.RenderTargetType.Default,
829                 new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
830                 dpiX,
831                 dpiY,
832                 D2D.RenderTargetUsage.None,
833                 D2D.FeatureLevel.Level_DEFAULT);
834
835             this.render = this.ConstructRender(this.D2DFactory,prop,width,height);
836
837             this.Brushes.Render = this.render;
838
839             D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
840             bmpProp.DpiX = dpiX;
841             bmpProp.DpiY = dpiY;
842             bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore);
843             this.bitmap = new D2D.Bitmap(this.render, new SharpDX.Size2((int)width, (int)height), bmpProp);
844             this.hasCache = false;
845
846             this.ConstrctedResource();
847
848             this.textRender = new CustomTextRenderer(this.render, this.Brushes,this.Strokes, this.Foreground);
849
850             this.renderSize.Width = width;
851             this.renderSize.Height = height;
852
853             this.TextAntialiasMode = this._TextAntialiasMode;
854         }
855
856 #if METRO
857         public System.Func<D2D.Factory1,D2D.RenderTargetProperties,double,double,D2D.RenderTarget> ConstructRender;
858 #else
859         public System.Func<D2D.Factory,D2D.RenderTargetProperties,double,double,D2D.RenderTarget> ConstructRender;
860 #endif
861         public System.Action ConstrctedResource;
862
863         public GetDpiHandler GetDpi;
864
865         public System.Action DestructRender;
866
867         public System.Action ReCreateTarget;
868
869         public void DestructDeviceResource()
870         {
871             this.hasCache = false;
872             if (this.bitmap != null)
873                 this.bitmap.Dispose();
874             this.Brushes.Clear();
875             this.Strokes.Clear();
876             this.Effects.Clear();
877             if (this.textRender != null)
878                 this.textRender.Dispose();
879             this.DestructRender();
880         }
881
882         void ParseLayout(MyTextLayout layout, string str)
883         {
884             for (int i = 0; i < str.Length; i++)
885             {
886                 DW.InlineObject inlineObject = this.HiddenChars.Get(layout,i, str);
887                 if (inlineObject != null)
888                 {
889                     layout.SetInlineObject(inlineObject, new DW.TextRange(i, 1));
890                     layout.SetDrawingEffect(this.Brushes.Get(this.ControlChar), new DW.TextRange(i, 1));
891                 }
892             }
893             layout.SetLineBreakBrush(this.Brushes.Get(this.ControlChar));
894         }
895     }
896 }