OSDN Git Service

行を生成するメソッドをLineToIndexTableに移動した
[fooeditengine/FooEditEngine.git] / Metro / FooEditEngine / FooTextBox.cs
index 1d28fba..b15ff8e 100644 (file)
@@ -49,7 +49,8 @@ namespace FooEditEngine.Metro
         TextStore2 textStore;
         FooTextBoxAutomationPeer peer;
         bool nowCaretMove = false;
-        DispatcherTimer timer;
+        Document _Document;
+        DispatcherTimer timer = new DispatcherTimer();
 
         /// <summary>
         /// コンストラクター
@@ -77,23 +78,19 @@ namespace FooEditEngine.Metro
             this.Render = new D2DRender(this,this.rectangle,this.textStore);
 
             this.Document = new Document();
-            this.Document.LayoutLines.Render = this.Render;
 
             this.View = new EditView(this.Document, this.Render, new Padding(5, Gripper.HitAreaWidth, Gripper.HitAreaWidth / 2, Gripper.HitAreaWidth));
             this.View.SrcChanged += View_SrcChanged;
             this.View.InsertMode = this.InsertMode;
-            this.View.DrawLineNumber = this.DrawLineNumber;
+            this.Document.DrawLineNumber = this.DrawLineNumber;
             this.View.HideCaret = !this.DrawCaret;
             this.View.HideLineMarker = !this.DrawCaretLine;
-            this.View.HideRuler = !this.DrawRuler;
-            this.View.UrlMark = this.MarkURL;
-            this.View.TabStops = this.TabChars;
+            this.Document.HideRuler = !this.DrawRuler;
+            this.Document.UrlMark = this.MarkURL;
+            this.Document.TabStops = this.TabChars;
 
             this._Controller = new Controller(this.Document, this.View);
-            this._Controller.SelectionChanged += Controller_SelectionChanged;
-
-            this.FirstGripper = new Gripper(this._Controller, this.View, this.Render, GripperPostion.BottomLeft);
-            this.SecondGripper = new Gripper(this._Controller, this.View, this.Render, GripperPostion.BottomRight);
+            this.Document.SelectionChanged += Controller_SelectionChanged;
 
             this.gestureRecongnizer.GestureSettings = GestureSettings.Drag | 
                 GestureSettings.RightTap | 
@@ -107,14 +104,13 @@ namespace FooEditEngine.Metro
             this.gestureRecongnizer.RightTapped += gestureRecongnizer_RightTapped;
             this.gestureRecongnizer.Tapped += gestureRecongnizer_Tapped;
             this.gestureRecongnizer.Dragging += gestureRecongnizer_Dragging;
-            this.gestureRecongnizer.ManipulationInertiaStarting += gestureRecongnizer_ManipulationInertiaStarting;
+            this.gestureRecongnizer.ManipulationInertiaStarting += GestureRecongnizer_ManipulationInertiaStarting; ;
             this.gestureRecongnizer.ManipulationStarted += gestureRecongnizer_ManipulationStarted;
             this.gestureRecongnizer.ManipulationUpdated += gestureRecongnizer_ManipulationUpdated;
             this.gestureRecongnizer.ManipulationCompleted += gestureRecongnizer_ManipulationCompleted;
 
-            this.timer = new DispatcherTimer();
-            this.timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
-            this.timer.Tick += new EventHandler<object>(this.timer_Tick);
+            this.timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
+            this.timer.Tick += this.timer_Tick;
             this.timer.Start();
 
             //Viewの初期化が終わった直後に置かないと例外が発生する
@@ -164,7 +160,7 @@ namespace FooEditEngine.Metro
         /// <param name="length">長さ</param>
         public void Select(int start, int length)
         {
-            this._Controller.Select(start, length);
+            this.Document.Select(start, length);
         }
 
         /// <summary>
@@ -238,7 +234,7 @@ namespace FooEditEngine.Metro
         /// </summary>
         public void SelectAll()
         {
-            this._Controller.Select(0, this.Document.Length);
+            this.Document.Select(0, this.Document.Length);
         }
 
         /// <summary>
@@ -345,28 +341,18 @@ namespace FooEditEngine.Metro
         /// <returns>Taskオブジェクト</returns>
         public async Task LoadFileAsync(System.IO.StreamReader sr, System.Threading.CancellationTokenSource token)
         {
-            this.IsEnabled = false;
-            this.View.LayoutLines.IsFrozneDirtyFlag = true;
-            WinFileReader fs = new WinFileReader(sr);
-            await this.Document.LoadAsync(fs, token);
-            this.View.LayoutLines.IsFrozneDirtyFlag = false;
-            TextStoreHelper.NotifyTextChanged(this.textStore, 0, 0, this.Document.Length);
-            if (this.verticalScrollBar != null)
-                this.verticalScrollBar.Maximum = this.View.LayoutLines.Count;
-            this.View.CalculateLineCountOnScreen();
-            this.IsEnabled = true;
+            await this.Document.LoadAsync(sr, token);
         }
 
         /// <summary>
         /// ドキュメントの内容をファイルに保存する
         /// </summary>
         /// <param name="sw">StreamWriter</param>
-        /// <param name="enc">エンコード</param>
+        /// <param name="token">キャンセル用トークン</param>
         /// <returns>Taskオブジェクト</returns>
         public async Task SaveFile(System.IO.StreamWriter sw, System.Threading.CancellationTokenSource token)
         {
-            WinFileWriter fs = new WinFileWriter(sw);
-            await this.Document.SaveAsync(fs, token);
+            await this.Document.SaveAsync(sw, token);
         }
 
         #region command
@@ -491,7 +477,7 @@ namespace FooEditEngine.Metro
                     if (isControlPressed)
                         this._Controller.JumpToHead(isShiftPressed);
                     else
-                        this.Controller.JumpToLineHead(this.View.CaretPostion.row,isShiftPressed);
+                        this.Controller.JumpToLineHead(this.Document.CaretPostion.row,isShiftPressed);
                     this.Refresh();
                     isMovedCaret = true;
                     break;
@@ -499,7 +485,7 @@ namespace FooEditEngine.Metro
                     if (isControlPressed)
                         this._Controller.JumpToEnd(isShiftPressed);
                     else
-                        this.Controller.JumpToLineEnd(this.View.CaretPostion.row,isShiftPressed);
+                        this.Controller.JumpToLineEnd(this.Document.CaretPostion.row,isShiftPressed);
                     this.Refresh();
                     isMovedCaret = true;
                     break;
@@ -637,7 +623,6 @@ namespace FooEditEngine.Metro
         protected override void OnPointerReleased(PointerRoutedEventArgs e)
         {
             this.gestureRecongnizer.ProcessUpEvent(e.GetCurrentPoint(this));
-            this.ReleasePointerCapture(e.Pointer);
             e.Handled = true;
         }
 
@@ -645,15 +630,6 @@ namespace FooEditEngine.Metro
         protected override void OnPointerCanceled(PointerRoutedEventArgs e)
         {
             this.gestureRecongnizer.CompleteGesture();
-            this.ReleasePointerCapture(e.Pointer);
-            e.Handled = true;
-        }
-
-        /// <inheritdoc/>
-        protected override void OnPointerCaptureLost(PointerRoutedEventArgs e)
-        {
-            this.gestureRecongnizer.CompleteGesture();
-            this.ReleasePointerCapture(e.Pointer);
             e.Handled = true;
         }
 
@@ -719,16 +695,13 @@ namespace FooEditEngine.Metro
             Point startPos, endPos;
             TextStoreHelper.GetStringExtent(this.Document, this.View, i_startIndex, i_endIndex, out startPos, out endPos);
 
-            float dpi;
-            this.Render.GetDpi(out dpi, out dpi);
-            double scale = dpi / 96.0;
-
-            var gt = this.TransformToVisual(Window.Current.Content);
-            startPos = gt.TransformPoint(startPos.Scale(scale));
-            endPos = gt.TransformPoint(endPos.Scale(scale));
+            double scale = Util.GetScale();
 
-            o_topLeft = new POINT((int)startPos.X, (int)startPos.Y);
-            o_bottomRight = new POINT((int)endPos.X, (int)endPos.Y);
+            //DIPを渡すと予測候補の位置がおかしくなるので、デバイス依存の座標に変換する
+            var screenStartPos = Util.GetScreentPoint(startPos, this).Scale(scale);
+            var screenEndPos = Util.GetScreentPoint(endPos, this).Scale(scale);
+            o_topLeft = new POINT((int)(screenStartPos.X), (int)(screenStartPos.Y));
+            o_bottomRight = new POINT((int)(screenEndPos.X), (int)(screenEndPos.Y));
         }
 
         void _textStore_GetScreenExtent(out POINT o_topLeft, out POINT o_bottomRight)
@@ -744,14 +717,20 @@ namespace FooEditEngine.Metro
             o_bottomRight = new POINT((int)pointBottomRight.X, (int)pointBottomRight.Y);
         }
 
-        void _textStore_GetSelectionIndex(out int o_startIndex, out int o_endIndex)
+        void _textStore_GetSelectionIndex(int start_index, int max_count, out DotNetTextStore.TextSelection[] sels)
         {
-            TextStoreHelper.GetSelection(this._Controller, this.View.Selections, out o_startIndex, out o_endIndex);
+            TextRange selRange;
+            TextStoreHelper.GetSelection(this._Controller, this.View.Selections, out selRange);
+
+            sels = new DotNetTextStore.TextSelection[1];
+            sels[0] = new DotNetTextStore.TextSelection();
+            sels[0].start = selRange.Index;
+            sels[0].end = selRange.Index + selRange.Length;
         }
 
-        void _textStore_SetSelectionIndex(int i_startIndex, int i_endIndex)
+        void _textStore_SetSelectionIndex(DotNetTextStore.TextSelection[] sels)
         {
-            TextStoreHelper.SetSelectionIndex(this._Controller, this.View, i_startIndex, i_endIndex);
+            TextStoreHelper.SetSelectionIndex(this._Controller, this.View, sels[0].start, sels[0].end);
             this.Refresh();
         }
 
@@ -765,92 +744,34 @@ namespace FooEditEngine.Metro
         {
             //こうしないと選択できなくなってしまう
             this.nowCaretMove = true;
-            SetValue(SelectionProperty, new TextRange(this._Controller.SelectionStart, this._Controller.SelectionLength));
-            SetValue(CaretPostionPropertyKey, this.View.CaretPostion);
+            SetValue(SelectedTextProperty, this._Controller.SelectedText);
+            SetValue(CaretPostionPropertyKey, this.Document.CaretPostion);
             this.nowCaretMove = false;
             if (this.textStore.IsLocked() == false)
                 this.textStore.NotifySelectionChanged();
         }
 
-        Gripper FirstGripper, SecondGripper;
-        bool HittedCaret;
         Gripper hittedGripper;
-        private void gestureRecongnizer_ManipulationInertiaStarting(GestureRecognizer sender, ManipulationInertiaStartingEventArgs e)
+        void gestureRecongnizer_ManipulationStarted(GestureRecognizer sender, ManipulationStartedEventArgs e)
         {
-            //sender.InertiaTranslationDeceleration = 0.001f;
-            //sender.InertiaExpansionDeceleration = 100.0f * 96.0f / 1000.0f;
-            //sender.InertiaRotationDeceleration = 720.0f / (1000.0f * 1000.0f);
+            //Updateedの段階でヒットテストしてしまうとグリッパーを触ってもヒットしないことがある
+            this.hittedGripper = this.View.HitGripperFromPoint(e.Position);
         }
 
-        void gestureRecongnizer_ManipulationStarted(GestureRecognizer sender, ManipulationStartedEventArgs e)
+        private void GestureRecongnizer_ManipulationInertiaStarting(GestureRecognizer sender, ManipulationInertiaStartingEventArgs args)
         {
-            this.HittedCaret = false;
-            this.hittedGripper = null;
-
-            Point p = e.Position;
-            TextPoint tp = this.View.GetTextPointFromPostion(p);
-            if (tp == this.View.CaretPostion)
-            {
-                HittedCaret = true;
-            }
-            
-            if (this.FirstGripper.IsHit(p))
-            {
-                hittedGripper = this.FirstGripper;
-                HittedCaret = true;
-                System.Diagnostics.Debug.WriteLine("first gripper hitted");
-            }
-            
-            else if (this.SecondGripper.IsHit(p))
-            {
-                hittedGripper = this.SecondGripper;
-                HittedCaret = true;
-                System.Diagnostics.Debug.WriteLine("second gripper hitted");
-            }
+            //sender.InertiaTranslationDeceleration = 0.001f;
+            //sender.InertiaExpansionDeceleration = 100.0f * 96.0f / 1000.0f;
+            //sender.InertiaRotationDeceleration = 720.0f / (1000.0f * 1000.0f);
         }
 
         void gestureRecongnizer_ManipulationUpdated(GestureRecognizer sender, ManipulationUpdatedEventArgs e)
         {
-            if (HittedCaret)
+            if (this._Controller.MoveCaretAndGripper(e.Position, this.hittedGripper))
             {
-                Point p;
-                if (this.hittedGripper == null)
-                     p = e.Position;
-                else
-                    p = this.hittedGripper.AdjustPoint(e.Position);
-
-                if (hittedGripper != null)
-                {
-                    TextPoint tp = this.View.GetTextPointFromPostion(p);
-                    if (this._Controller.IsReverseSelect())
-                    {
-                        if (Object.ReferenceEquals(hittedGripper,this.SecondGripper))
-                            this._Controller.MoveSelectBefore(tp);
-                        else
-                            this._Controller.MoveCaretAndSelect(tp);
-                    }
-                    else
-                    {
-                        if (Object.ReferenceEquals(hittedGripper,this.FirstGripper))
-                            this._Controller.MoveSelectBefore(tp);
-                        else
-                            this._Controller.MoveCaretAndSelect(tp);
-                    }
-                }
-                else
-                {
-                    TextPoint tp = this.View.GetTextPointFromPostion(p);
-                    this._Controller.MoveCaretAndSelect(tp);
-                }
                 if (this.peer != null)
                     this.peer.OnNotifyCaretChanged();
-                if (this._Controller.SelectionLength != 0)
-                    this.FirstGripper.Enabled = true;
-                else
-                    this.FirstGripper.Enabled = false;
-
-                this.Refresh();
-                
+                this.Refresh();                
                 return;
             }
 
@@ -881,18 +802,11 @@ namespace FooEditEngine.Metro
             //Xの絶対値が大きければ横方向のスクロールで、そうでなければ縦方向らしい
             if (Math.Abs(e.Cumulative.Translation.X) < Math.Abs(e.Cumulative.Translation.Y))
             {
-                int scrollCount = 0;
-                if (e.PointerDeviceType == PointerDeviceType.Mouse)  //ホイールを使っているので、スクロール行数を計算する
-                    scrollCount = (int)Math.Abs(translation.Y / sender.MouseWheelParameters.CharTranslation.Y);
+                int deltay = (int)Math.Abs(Math.Ceiling(translation.Y));
+                if (translation.Y < 0)
+                    this._Controller.ScrollByPixel(ScrollDirection.Down, deltay, false, false);
                 else
-                    scrollCount = (int)Math.Abs(translation.Y + 0.5);
-
-                if (translation.Y > 0)
-                    this._Controller.Scroll(ScrollDirection.Up, scrollCount, false, false);
-                else
-                    this._Controller.Scroll(ScrollDirection.Down, scrollCount, false, false);
-                this.FirstGripper.Enabled = false;
-                this.SecondGripper.Enabled = false;
+                    this._Controller.ScrollByPixel(ScrollDirection.Up, deltay, false, false);
                 this.Refresh();
                 return;
             }
@@ -904,8 +818,6 @@ namespace FooEditEngine.Metro
                     this._Controller.Scroll(ScrollDirection.Left, deltax, false, false);
                 else
                     this._Controller.Scroll(ScrollDirection.Right, deltax, false, false);
-                this.FirstGripper.Enabled = false;
-                this.SecondGripper.Enabled = false;
                 this.Refresh();
             }
         }
@@ -960,15 +872,16 @@ namespace FooEditEngine.Metro
         void gestureRecongnizer_Tapped(GestureRecognizer sender, TappedEventArgs e)
         {
             bool touched = e.PointerDeviceType == PointerDeviceType.Touch;
-            this.FirstGripper.Enabled = false;
-            this.SecondGripper.Enabled = touched;
+            this.Document.SelectGrippers.BottomLeft.Enabled = false;
+            this.Document.SelectGrippers.BottomRight.Enabled = touched;
             this.JumpCaret(e.Position);
             System.Diagnostics.Debug.WriteLine(e.TapCount);
             if (e.TapCount == 2)
             {
-                this.FirstGripper.Enabled = touched;
+                this.Document.SelectGrippers.BottomLeft.Enabled = touched;
                 //タッチスクリーンでダブルタップした場合、アンカーインデックスを単語の先頭にしないとバグる
-                this.Controller.SelectWord(this.Controller.SelectionStart, touched);
+                this.Document.SelectWord(this.Controller.SelectionStart, touched);
+                this.Refresh();
             }
         }
 
@@ -1003,14 +916,18 @@ namespace FooEditEngine.Metro
         void gestureRecongnizer_Dragging(GestureRecognizer sender, DraggingEventArgs e)
         {
             Point p = e.Position;
+            TextPointSearchRange searchRange;
             if (this.View.HitTextArea(p.X, p.Y))
-            {
-                TextPoint tp = this.View.GetTextPointFromPostion(p);
-                this._Controller.MoveCaretAndSelect(tp);
-                if (this.peer != null)
-                    this.peer.OnNotifyCaretChanged();
-                this.Refresh();
-            }
+                searchRange = TextPointSearchRange.TextAreaOnly;
+            else if (this._Controller.SelectionLength > 0)
+                searchRange = TextPointSearchRange.Full;
+            else
+                return;
+            TextPoint tp = this.View.GetTextPointFromPostion(p, searchRange);
+            this._Controller.MoveCaretAndSelect(tp);
+            if (this.peer != null)
+                this.peer.OnNotifyCaretChanged();
+            this.Refresh();
         }
 
         bool IsModiferKeyPressed(VirtualKey key)
@@ -1023,14 +940,7 @@ namespace FooEditEngine.Metro
             if (this.rectangle.ActualWidth == 0 || this.rectangle.ActualHeight == 0 || this.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
                 return;
 
-            this.Render.BegineDraw();
-            if (this.IsEnabled)
-                this.View.Draw(updateRect);
-            else
-                this.Render.FillBackground(updateRect);
-            this.FirstGripper.Draw();
-            this.SecondGripper.Draw();
-            this.Render.EndDraw();
+            this.Render.DrawContent(this.View, this.IsEnabled, updateRect);
         }
 
 
@@ -1092,8 +1002,6 @@ namespace FooEditEngine.Metro
             else
                 toX = -this.horizontalScrollBar.Value;
             this._Controller.Scroll(toX, this.View.Src.Row, false, false);
-            this.FirstGripper.Enabled = false;
-            this.SecondGripper.Enabled = false;
             this.Refresh();
         }
 
@@ -1105,8 +1013,6 @@ namespace FooEditEngine.Metro
             if (newRow >= this.View.LayoutLines.Count)
                 return;
             this._Controller.Scroll(this.View.Src.X, newRow, false, false);
-            this.FirstGripper.Enabled = false;
-            this.SecondGripper.Enabled = false;
             this.Refresh();
         }
 
@@ -1116,6 +1022,8 @@ namespace FooEditEngine.Metro
                 return;
             if (e.type == UpdateType.Replace)
                 TextStoreHelper.NotifyTextChanged(this.textStore, e.startIndex, e.removeLength, e.insertLength);
+            if(this.peer != null)
+                this.peer.OnNotifyTextChanged();
         }
 
         void FooTextBox_Loaded(object sender, RoutedEventArgs e)
@@ -1125,25 +1033,32 @@ namespace FooEditEngine.Metro
 
         void timer_Tick(object sender, object e)
         {
-            bool updateAll = this.View.LayoutLines.HilightAll() || this.View.LayoutLines.GenerateFolding();
-            if (updateAll)
-                this.Refresh();
+            if (this.View.LayoutLines.HilightAll() || this.View.LayoutLines.GenerateFolding())
+                this.Refresh(this.View.PageBound);
         }
 
         /// <inheritdoc/>
         public static void OnPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
         {
             FooTextBox source = (FooTextBox)sender;
+            if(e.Property.Equals(SelectedTextProperty) && !source.nowCaretMove)
+                source._Controller.SelectedText = source.SelectedText;
+            if(e.Property.Equals(HilighterProperty))
+                source.View.Hilighter = source.Hilighter;
+            if (e.Property.Equals(TextAntialiasModeProperty))
+                source.Render.TextAntialiasMode = source.TextAntialiasMode;
+            if (e.Property.Equals(FoldingStrategyProperty))
+                source.View.LayoutLines.FoldingStrategy = source.FoldingStrategy;
             if (e.Property.Equals(IndentModeProperty))
                 source.Controller.IndentMode = source.IndentMode;
             if (e.Property.Equals(SelectionProperty) && !source.nowCaretMove)
-                source._Controller.Select(source.Selection.Index,source.Selection.Length);
+                source.Document.Select(source.Selection.Index,source.Selection.Length);
             if (e.Property.Equals(CaretPostionPropertyKey) && !source.nowCaretMove)
                 source.JumpCaret(source.CaretPostion.row, source.CaretPostion.col);
             if (e.Property.Equals(InsertModeProperty))
                 source.View.InsertMode = source.InsertMode;
             if (e.Property.Equals(TabCharsProperty))
-                source.View.TabStops = source.TabChars;
+                source.Document.TabStops = source.TabChars;
             if (e.Property.Equals(RectSelectModeProperty))
                 source._Controller.RectSelection = source.RectSelectMode;
             if (e.Property.Equals(DrawCaretProperty))
@@ -1151,10 +1066,7 @@ namespace FooEditEngine.Metro
             if (e.Property.Equals(DrawCaretLineProperty))
                 source.View.HideLineMarker = !source.DrawCaretLine;
             if (e.Property.Equals(DrawLineNumberProperty))
-            {
-                source.View.DrawLineNumber = source.DrawLineNumber;
-                source._Controller.JumpCaret(source.View.CaretPostion.row, source.View.CaretPostion.col);
-            }
+                source.Document.DrawLineNumber = source.DrawLineNumber;
             if(e.Property.Equals(MagnificationPowerPropertyKey))
                 source.Render.FontSize = source.FontSize * source.MagnificationPower;
             if (e.Property.Equals(FontFamilyProperty))
@@ -1192,7 +1104,7 @@ namespace FooEditEngine.Metro
             if (e.Property.Equals(LineMarkerProperty))
                 source.Render.LineMarker = D2DRenderBase.ToColor4(source.LineMarker);
             if (e.Property.Equals(MarkURLProperty))
-                source.View.UrlMark = source.MarkURL;
+                source.Document.UrlMark = source.MarkURL;
             if (e.Property.Equals(ShowFullSpaceProperty))
                 source.Render.ShowFullSpace = source.ShowFullSpace;
             if (e.Property.Equals(ShowHalfSpaceProperty))
@@ -1202,23 +1114,23 @@ namespace FooEditEngine.Metro
             if (e.Property.Equals(ShowLineBreakProperty))
                 source.Render.ShowLineBreak = source.ShowLineBreak;
             if (e.Property.Equals(LineBreakProperty))
-                source.View.LineBreak = source.LineBreakMethod;
+                source.Document.LineBreak = source.LineBreakMethod;
             if (e.Property.Equals(LineBreakCharCountProperty))
-                source.View.LineBreakCharCount = source.LineBreakCharCount;
+                source.Document.LineBreakCharCount = source.LineBreakCharCount;
             if (e.Property.Equals(UpdateAreaProperty))
                 source.Render.UpdateArea = D2DRenderBase.ToColor4(source.UpdateArea);
             if (e.Property.Equals(LineNumberProperty))
                 source.Render.LineNumber = D2DRenderBase.ToColor4(source.LineNumber);
             if (e.Property.Equals(FlowDirectionProperty))
             {
-                source.Render.RightToLeft = source.FlowDirection == Windows.UI.Xaml.FlowDirection.RightToLeft;
+                source.Document.RightToLeft = source.FlowDirection == Windows.UI.Xaml.FlowDirection.RightToLeft;
                 if(source.horizontalScrollBar != null)
                     source.horizontalScrollBar.FlowDirection = source.FlowDirection;
             }
             if (e.Property.Equals(DrawRulerProperty))
             {
-                source.View.HideRuler = !source.DrawRuler;
-                source._Controller.JumpCaret(source.View.CaretPostion.row, source.View.CaretPostion.col);
+                source.Document.HideRuler = !source.DrawRuler;
+                source._Controller.JumpCaret(source.Document.CaretPostion.row, source.Document.CaretPostion.col);
             }
         }
         #endregion
@@ -1247,57 +1159,54 @@ namespace FooEditEngine.Metro
         /// </summary>
         public TextAntialiasMode TextAntialiasMode
         {
-            get
-            {
-                return this.Render.TextAntialiasMode;
-            }
-            set
-            {
-                this.Render.TextAntialiasMode = value;
-            }
+            get { return (TextAntialiasMode)GetValue(TextAntialiasModeProperty); }
+            set { SetValue(TextAntialiasModeProperty, value); }
         }
 
         /// <summary>
+        /// TextAntialiasModeの依存プロパティを表す
+        /// </summary>
+        public static readonly DependencyProperty TextAntialiasModeProperty =
+            DependencyProperty.Register("TextAntialiasMode", typeof(TextAntialiasMode), typeof(FooTextBox), new PropertyMetadata(TextAntialiasMode.Default, OnPropertyChanged));
+
+        /// <summary>
         /// シンタックスハイライターを表す
         /// </summary>
         public IHilighter Hilighter
         {
-            get
-            {
-                return this.View.Hilighter;
-            }
-            set
-            {
-                this.View.Hilighter = value;
-                this.View.LayoutLines.ClearLayoutCache();
-            }
+            get { return (IHilighter)GetValue(HilighterProperty); }
+            set { SetValue(HilighterProperty, value); }
         }
 
         /// <summary>
+        /// Hilighterの依存プロパティを表す
+        /// </summary>
+        public static readonly DependencyProperty HilighterProperty =
+            DependencyProperty.Register("Hilighter", typeof(IHilighter), typeof(FooTextBox), new PropertyMetadata(null, OnPropertyChanged));
+
+        /// <summary>
         /// フォールティングを作成するインターフェイスを表す
         /// </summary>
         public IFoldingStrategy FoldingStrategy
         {
-            get
-            {
-                return this.View.LayoutLines.FoldingStrategy;
-            }
-            set
-            {
-                this.View.LayoutLines.FoldingStrategy = value;
-                if (value == null)
-                    this.View.LayoutLines.FoldingCollection.Clear();
-            }
+            get { return (IFoldingStrategy)GetValue(FoldingStrategyProperty); }
+            set { SetValue(FoldingStrategyProperty, value); }
         }
 
         /// <summary>
+        /// FoldingStrategyの依存プロパティ
+        /// </summary>
+        public static readonly DependencyProperty FoldingStrategyProperty =
+            DependencyProperty.Register("FoldingStrategy", typeof(IFoldingStrategy), typeof(FooTextBox), new PropertyMetadata(null,OnPropertyChanged));
+
+        /// <summary>
         /// マーカーパターンセットを表す
         /// </summary>
         public MarkerPatternSet MarkerPatternSet
         {
             get
             {
-                return this.View.MarkerPatternSet;
+                return this.Document.MarkerPatternSet;
             }
         }
 
@@ -1306,8 +1215,66 @@ namespace FooEditEngine.Metro
         /// </summary>
         public Document Document
         {
-            get;
-            private set;
+            get
+            {
+                return this._Document;
+            }
+            set
+            {
+                Document old_doc = this._Document;
+                int oldLength = 0;
+                if (this._Document != null)
+                {
+                    old_doc.Update -= new DocumentUpdateEventHandler(Document_Update);
+                    old_doc.LoadProgress -= _Document_LoadProgress;
+                    oldLength = old_doc.Length;
+                }
+
+                this._Document = value;
+                this._Document.LayoutLines.Render = this.Render;
+                this._Document.Update += new DocumentUpdateEventHandler(Document_Update);
+                this._Document.LoadProgress += _Document_LoadProgress;
+                //初期化が終わっていればすべて存在する
+                if (this.Controller != null && this.View != null && this.textStore != null)
+                {
+                    this.Controller.Document = value;
+                    this.View.Document = value;
+                    this.Controller.AdjustCaret();
+                    this.textStore.NotifyTextChanged(oldLength, value.Length);
+
+                    //依存プロパティとドキュメント内容が食い違っているので再設定する
+                    this.ShowFullSpace = value.ShowFullSpace;
+                    this.ShowHalfSpace = value.ShowHalfSpace;
+                    this.ShowLineBreak = value.ShowLineBreak;
+                    this.ShowTab = value.ShowTab;
+                    this.FlowDirection = value.RightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
+                    this.IndentMode = value.IndentMode;
+                    this.DrawCaretLine = !value.HideLineMarker;
+                    this.InsertMode = value.InsertMode;
+                    this.DrawRuler = !value.HideRuler;
+                    this.DrawLineNumber = value.DrawLineNumber;
+                    this.MarkURL = value.UrlMark;
+                    this.LineBreakMethod = value.LineBreak;
+                    this.LineBreakCharCount = value.LineBreakCharCount;
+                    this.TabChars = value.TabStops;
+
+                    this.Refresh();
+                }
+            }
+        }
+
+        private void _Document_LoadProgress(object sender, ProgressEventArgs e)
+        {
+            if(e.state == ProgressState.Start)
+                this.IsEnabled = false;
+            else if(e.state == ProgressState.Complete)
+            {
+                TextStoreHelper.NotifyTextChanged(this.textStore, 0, 0, this.Document.Length);
+                if (this.verticalScrollBar != null)
+                    this.verticalScrollBar.Maximum = this.View.LayoutLines.Count;
+                this.View.CalculateLineCountOnScreen();
+                this.IsEnabled = true;
+            }
         }
 
         /// <summary>
@@ -1323,18 +1290,17 @@ namespace FooEditEngine.Metro
         /// </summary>
         public string SelectedText
         {
-            get
-            {
-                return this._Controller.SelectedText;
-            }
-            set
-            {
-                int oldLength = this.Document.Length;
-                this._Controller.SelectedText = value;
-            }
+            get { return (string)GetValue(SelectedTextProperty); }
+            set { SetValue(SelectedTextProperty, value); }
         }
 
         /// <summary>
+        /// SelectedTextの依存プロパティを表す
+        /// </summary>
+        public static readonly DependencyProperty SelectedTextProperty =
+            DependencyProperty.Register("SelectedText", typeof(string), typeof(FooTextBox), new PropertyMetadata(null, OnPropertyChanged));
+
+        /// <summary>
         /// インデントの方法を表す
         /// </summary>
         public IndentMode IndentMode
@@ -1366,7 +1332,7 @@ namespace FooEditEngine.Metro
         /// Selectionの依存プロパティを表す
         /// </summary>
         public static readonly DependencyProperty SelectionProperty =
-            DependencyProperty.Register("Selection", typeof(TextRange), typeof(FooTextBox), new PropertyMetadata(0));
+            DependencyProperty.Register("Selection", typeof(TextRange), typeof(FooTextBox), new PropertyMetadata(TextRange.Null, OnPropertyChanged));
 
         /// <summary>
         /// 拡大率を表す
@@ -1618,7 +1584,7 @@ namespace FooEditEngine.Metro
         /// UpdateAreaの依存プロパティを表す
         /// </summary>
         public static readonly DependencyProperty UpdateAreaProperty =
-            DependencyProperty.Register("UpdateArea", typeof(Windows.UI.Color), typeof(FooTextBox), new PropertyMetadata(Colors.MediumSeaGreen));
+            DependencyProperty.Register("UpdateArea", typeof(Windows.UI.Color), typeof(FooTextBox), new PropertyMetadata(Colors.MediumSeaGreen, OnPropertyChanged));
 
         /// <summary>
         /// ラインマーカーの色を表す
@@ -1781,7 +1747,7 @@ namespace FooEditEngine.Metro
         /// LineBreakCharCountの依存プロパティを表す
         /// </summary>
         public static readonly DependencyProperty LineBreakCharCountProperty =
-            DependencyProperty.Register("LineBreakCharCount", typeof(int), typeof(FooTextBox), new PropertyMetadata(80));        
+            DependencyProperty.Register("LineBreakCharCount", typeof(int), typeof(FooTextBox), new PropertyMetadata(80, OnPropertyChanged));        
 
         /// <summary>
         /// キャレットを描くなら真。そうでないなら偽を返す。これは依存プロパティです