OSDN Git Service

ドラッグしながらの選択ができなくなるので元に戻した
[fooeditengine/FooEditEngine.git] / WPF / FooEditEngine / FooTextBox.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.Text;
13 using System.Threading.Tasks;
14 using System.Runtime.InteropServices;
15 using System.Windows;
16 using System.Windows.Input;
17 using System.Windows.Media;
18 using System.Windows.Controls;
19 using System.Windows.Controls.Primitives;
20 using System.Windows.Documents;
21 using System.Windows.Interop;
22 using System.Windows.Threading;
23 using DotNetTextStore;
24 using DotNetTextStore.UnmanagedAPI.TSF;
25 using DotNetTextStore.UnmanagedAPI.WinDef;
26 using Microsoft.Win32;
27
28 namespace FooEditEngine.WPF
29 {
30     /// <summary>
31     /// WPFでのFooTextBoxの実装
32     /// </summary>
33     public sealed class FooTextBox : Control, IDisposable
34     {
35         const double MaxFontSize = 72.0f;
36         const double MinFontSize = 1;
37
38         EditView View;
39         Controller _Controller;
40         D2DRender Render;
41         Image image;
42         ScrollBar verticalScrollBar, horizontalScrollBar;
43         TextStore textStore;
44         DispatcherTimer timer;
45         bool disposed = false;
46         FooTextBoxAutomationPeer peer;
47         bool isNotifyChanged = false;
48         Document _Document;
49         Popup popup;
50
51         const int Interval = 96;
52         const int IntervalWhenLostFocuse = 160;
53
54         static FooTextBox()
55         {
56             DefaultStyleKeyProperty.OverrideMetadata(typeof(FooTextBox), new FrameworkPropertyMetadata(typeof(FooTextBox)));
57             KeyboardNavigation.IsTabStopProperty.OverrideMetadata(typeof(FooTextBox), new FrameworkPropertyMetadata(true));
58             KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(FooTextBox), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
59         }
60
61         /// <summary>
62         /// コンストラクター
63         /// </summary>
64         public FooTextBox()
65         {
66             this.popup = new Popup();
67
68             this.image = new Image();
69             this.image.Stretch = Stretch.Fill;
70             this.image.HorizontalAlignment = HorizontalAlignment.Left;
71             this.image.VerticalAlignment = VerticalAlignment.Top;
72
73             this.textStore = new TextStore();
74             this.textStore.IsLoading += textStore_IsLoading;
75             this.textStore.IsReadOnly += textStore_IsReadOnly;
76             this.textStore.GetStringLength += () => this.Document.Length;
77             this.textStore.GetString += _textStore_GetString;
78             this.textStore.GetSelectionIndex += _textStore_GetSelectionIndex;
79             this.textStore.SetSelectionIndex += _textStore_SetSelectionIndex;
80             this.textStore.InsertAtSelection += _textStore_InsertAtSelection;
81             this.textStore.GetHWnd += _textStore_GetHWnd;
82             this.textStore.GetScreenExtent += _textStore_GetScreenExtent;
83             this.textStore.GetStringExtent += _textStore_GetStringExtent;
84             this.textStore.CompositionStarted += textStore_CompositionStarted;
85             this.textStore.CompositionUpdated += textStore_CompositionUpdated;
86             this.textStore.CompositionEnded += textStore_CompositionEnded;
87
88             this.Render = new D2DRender(this, 200, 200,this.image);
89
90             this.Document = new Document();
91
92             this.View = new EditView(this.Document, this.Render, new Padding(5, 5, 5, 5));
93             this.View.SrcChanged += View_SrcChanged;
94             this.View.InsertMode = this.InsertMode;
95             this.Document.DrawLineNumber = this.DrawLineNumber;
96             this.View.HideCaret = !this.DrawCaret;
97             this.View.HideLineMarker = !this.DrawCaretLine;
98             this.Document.HideRuler = !this.DrawRuler;
99             this.Document.UrlMark = this.MarkURL;
100             this.Document.TabStops = this.TabChars;
101             this.Document.ShowFullSpace = this.ShowFullSpace;
102             this.Document.ShowHalfSpace = this.ShowHalfSpace;
103             this.Document.ShowTab = this.ShowTab;
104
105             this._Controller = new Controller(this.Document, this.View);
106             this._Document.SelectionChanged += new EventHandler(Controller_SelectionChanged);
107
108             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, CopyCommand, CanExecute));
109             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, CutCommand, CanExecute));
110             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, PasteCommand, CanExecute));
111             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, DeleteCommand, CanExecute));
112             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, SelectAllCommand, CanExecute));
113             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, UndoCommand, CanExecute));
114             this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, RedoCommand, CanExecute));
115             this.CommandBindings.Add(new CommandBinding(EditingCommands.ToggleInsert, ToggleInsertCommand, CanExecute));
116             this.CommandBindings.Add(new CommandBinding(FooTextBoxCommands.ToggleRectSelectMode, ToggleRectSelectCommand, CanExecute));
117             this.CommandBindings.Add(new CommandBinding(FooTextBoxCommands.ToggleFlowDirection, ToggleFlowDirectionCommand, CanExecute));
118             this.CommandBindings.Add(new CommandBinding(FooTextBoxCommands.ToggleCodePoint, ToggleCodePointCommand, CanExecute));
119
120             this.InputBindings.Add(new InputBinding(ApplicationCommands.Copy, new KeyGesture(Key.C, ModifierKeys.Control)));
121             this.InputBindings.Add(new InputBinding(ApplicationCommands.Cut, new KeyGesture(Key.X, ModifierKeys.Control)));
122             this.InputBindings.Add(new InputBinding(ApplicationCommands.Paste, new KeyGesture(Key.V, ModifierKeys.Control)));
123             this.InputBindings.Add(new InputBinding(ApplicationCommands.Delete, new KeyGesture(Key.Delete, ModifierKeys.None)));
124             this.InputBindings.Add(new InputBinding(ApplicationCommands.SelectAll, new KeyGesture(Key.A, ModifierKeys.Control)));
125             this.InputBindings.Add(new InputBinding(ApplicationCommands.Undo, new KeyGesture(Key.Z, ModifierKeys.Control)));
126             this.InputBindings.Add(new InputBinding(ApplicationCommands.Redo, new KeyGesture(Key.Y, ModifierKeys.Control)));
127             this.InputBindings.Add(new InputBinding(EditingCommands.ToggleInsert, new KeyGesture(Key.Insert, ModifierKeys.None)));
128             this.InputBindings.Add(new InputBinding(FooTextBoxCommands.ToggleCodePoint, new KeyGesture(Key.X, ModifierKeys.Alt)));
129
130             this.timer = new DispatcherTimer();
131             this.timer.Interval = new TimeSpan(0, 0, 0, 0, Interval);
132             this.timer.Tick += new EventHandler(timer_Tick);
133
134             this.Loaded += new RoutedEventHandler(FooTextBox_Loaded);
135
136             this.AutoIndentHooker = (s,e)=>{};
137
138             SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
139
140             this.SystemEvents_UserPreferenceChanged(null, new UserPreferenceChangedEventArgs(UserPreferenceCategory.Keyboard));
141
142             this.CaretMoved += (s, e) => { };
143
144             this.IsManipulationEnabled = true;
145         }
146
147         /// <summary>
148         /// ファイナライザー
149         /// </summary>
150         ~FooTextBox()
151         {
152             //Dispose(false)を呼び出すと落ちる
153             this.Dispose(false);
154         }
155
156         /// <summary>
157         /// オートインデントを行うためのイベント
158         /// </summary>
159         [Obsolete]
160         public AutoIndentHookerHandler AutoIndentHooker;
161
162         /// <summary>
163         /// テンプレートを適用します
164         /// </summary>
165         public override void OnApplyTemplate()
166         {
167             base.OnApplyTemplate();
168
169             Grid grid = this.GetTemplateChild("PART_Grid") as Grid;
170             if (grid != null)
171             {
172                 Grid.SetRow(this.image, 0);
173                 Grid.SetColumn(this.image, 0);
174                 grid.Children.Add(this.image);
175
176                 Grid.SetRow(this.popup, 0);
177                 Grid.SetColumn(this.popup, 0);
178                 grid.Children.Add(this.popup);
179                 //this.popup.PlacementTarget = this;
180                 this.popup.Placement = PlacementMode.Absolute;
181             }
182
183             this.horizontalScrollBar = this.GetTemplateChild("PART_HorizontalScrollBar") as ScrollBar;
184             if (this.horizontalScrollBar != null)
185             {
186                 this.horizontalScrollBar.SmallChange = 10;
187                 this.horizontalScrollBar.LargeChange = 100;
188                 this.horizontalScrollBar.Maximum = this.horizontalScrollBar.LargeChange + 1;
189                 this.horizontalScrollBar.Scroll += new ScrollEventHandler(horizontalScrollBar_Scroll);
190             }
191             this.verticalScrollBar = this.GetTemplateChild("PART_VerticalScrollBar") as ScrollBar;
192             if (this.verticalScrollBar != null)
193             {
194                 this.verticalScrollBar.SmallChange = 1;
195                 this.verticalScrollBar.LargeChange = 10;
196                 this.verticalScrollBar.Maximum = this.Document.LayoutLines.Count - 1;
197                 this.verticalScrollBar.Scroll += new ScrollEventHandler(verticalScrollBar_Scroll);
198             }
199         }
200
201         /// <summary>
202         /// ドキュメントを選択する
203         /// </summary>
204         /// <param name="start">開始インデックス</param>
205         /// <param name="length">長さ</param>
206         public void Select(int start, int length)
207         {
208             this.Document.Select(start, length);
209             this.textStore.NotifySelectionChanged();
210         }
211
212         /// <summary>
213         /// キャレットを指定した行に移動させます
214         /// </summary>
215         /// <param name="index">インデックス</param>
216         /// <remarks>このメソッドを呼び出すと選択状態は解除されます</remarks>
217         public void JumpCaret(int index)
218         {
219             this._Controller.JumpCaret(index);
220         }
221         /// <summary>
222         /// キャレットを指定した行と桁に移動させます
223         /// </summary>
224         /// <param name="row">行番号</param>
225         /// <param name="col">桁</param>
226         /// <remarks>このメソッドを呼び出すと選択状態は解除されます</remarks>
227         public void JumpCaret(int row, int col)
228         {
229             this._Controller.JumpCaret(row, col);
230         }
231
232         /// <summary>
233         /// 選択中のテキストをクリップボードにコピーします
234         /// </summary>
235         public void Copy()
236         {
237             string text = this._Controller.SelectedText;
238             if (text != null && text != string.Empty)
239                 Clipboard.SetText(text);
240         }
241
242         /// <summary>
243         /// 選択中のテキストをクリップボードに切り取ります
244         /// </summary>
245         public void Cut()
246         {
247             string text = this._Controller.SelectedText;
248             if (text != null && text != string.Empty)
249             {
250                 Clipboard.SetText(text);
251                 this._Controller.SelectedText = "";
252             }
253         }
254
255         /// <summary>
256         /// 選択中のテキストを貼り付けます
257         /// </summary>
258         public void Paste()
259         {
260             if (Clipboard.ContainsText() == false)
261                 return;
262             string text = Clipboard.GetText();
263             this._Controller.SelectedText = text;
264         }
265
266         /// <summary>
267         /// 選択を解除する
268         /// </summary>
269         public void DeSelectAll()
270         {
271             this._Controller.DeSelectAll();
272             this.textStore.NotifySelectionChanged();
273         }
274
275         /// <summary>
276         /// 対応する座標を返します
277         /// </summary>
278         /// <param name="tp">テキストポイント</param>
279         /// <returns>座標</returns>
280         /// <remarks>テキストポイントがクライアント領域の原点より外にある場合、返される値は原点に丸められます</remarks>
281         public System.Windows.Point GetPostionFromTextPoint(TextPoint tp)
282         {
283             if (this.Document.FireUpdateEvent == false)
284                 throw new InvalidOperationException("");
285             return this.View.GetPostionFromTextPoint(tp);
286         }
287
288         /// <summary>
289         /// 対応するテキストポイントを返します
290         /// </summary>
291         /// <param name="p">クライアント領域の原点を左上とする座標</param>
292         /// <returns>テキストポイント</returns>
293         public TextPoint GetTextPointFromPostion(System.Windows.Point p)
294         {
295             if (this.Document.FireUpdateEvent == false)
296                 throw new InvalidOperationException("");
297             return this.View.GetTextPointFromPostion(p);
298         }
299
300         /// <summary>
301         /// 行の高さを取得します
302         /// </summary>
303         /// <param name="row">レイアウト行</param>
304         /// <returns>行の高さ</returns>
305         public double GetLineHeight(int row)
306         {
307             if (this.Document.FireUpdateEvent == false)
308                 throw new InvalidOperationException("");
309             return this.View.LayoutLines.GetLayout(row).Height;;
310         }
311
312         /// <summary>
313         /// インデックスに対応する座標を得ます
314         /// </summary>
315         /// <param name="index">インデックス</param>
316         /// <returns>座標を返す</returns>
317         public System.Windows.Point GetPostionFromIndex(int index)
318         {
319             if (this.Document.FireUpdateEvent == false)
320                 throw new InvalidOperationException("");
321             TextPoint tp = this.View.GetLayoutLineFromIndex(index);
322             return this.View.GetPostionFromTextPoint(tp);
323         }
324
325         /// <summary>
326         /// 座標からインデックスに変換します
327         /// </summary>
328         /// <param name="p">座標</param>
329         /// <returns>インデックスを返す</returns>
330         public int GetIndexFromPostion(System.Windows.Point p)
331         {
332             if (this.Document.FireUpdateEvent == false)
333                 throw new InvalidOperationException("");
334             TextPoint tp = this.View.GetTextPointFromPostion(p);
335             return this.View.GetIndexFromLayoutLine(tp);
336         }
337
338         /// <summary>
339         /// 再描写する
340         /// </summary>
341         public void Refresh()
342         {
343             this.Refresh(this.View.PageBound);
344         }
345
346         /// <summary>
347         /// レイアウト行をすべて破棄し、再度レイアウトを行う
348         /// </summary>
349         public void PerfomLayouts()
350         {
351             this.View.PerfomLayouts();
352         }
353
354         /// <summary>
355         /// 指定行までスクロールする
356         /// </summary>
357         /// <param name="row">行</param>
358         /// <param name="alignTop">指定行を画面上に置くなら真。そうでないなら偽</param>
359         public void ScrollIntoView(int row, bool alignTop)
360         {
361             this.View.ScrollIntoView(row, alignTop);
362         }
363
364         /// <summary>
365         /// ストリームからドキュメントを構築する
366         /// </summary>
367         /// <param name="tr">TextReader</param>
368         /// <param name="token">キャンセル用トークン</param>
369         /// <returns>Taskオブジェクト</returns>
370         public async Task LoadAsync(System.IO.TextReader tr, System.Threading.CancellationTokenSource token)
371         {
372             await this.Document.LoadAsync(tr, token);
373         }
374
375         /// <summary>
376         /// ファイルからドキュメントを構築する
377         /// </summary>
378         /// <param name="filepath">ファイルパス</param>
379         /// <param name="enc">エンコード</param>
380         /// <param name="token">キャンセル用トークン</param>
381         /// <returns>Taskオブジェクト</returns>
382         public async Task LoadFileAsync(string filepath, Encoding enc,System.Threading.CancellationTokenSource token)
383         {
384             var fs = new System.IO.StreamReader(filepath, enc);
385             await this.Document.LoadAsync(fs, token);
386             fs.Close();
387         }
388
389         private void Document_LoadProgress(object sender, ProgressEventArgs e)
390         {
391             if (e.state == ProgressState.Start)
392             {
393                 this.IsEnabled = false;
394             }
395             else if (e.state == ProgressState.Complete)
396             {
397                 TextStoreHelper.NotifyTextChanged(this.textStore, 0, 0, this.Document.Length);
398                 if (this.verticalScrollBar != null)
399                     this.verticalScrollBar.Maximum = this.View.LayoutLines.Count;
400                 this.View.CalculateWhloeViewPort();
401                 this.View.CalculateLineCountOnScreen();
402                 this.IsEnabled = true;
403                 this.Refresh(this.View.PageBound);
404             }
405         }
406
407         /// <summary>
408         /// ドキュメントの内容をファイルに保存する
409         /// </summary>
410         /// <param name="filepath">ファイルパス</param>
411         /// <param name="newLine">改行コード</param>
412         /// <param name="enc">エンコード</param>
413         /// <param name="token">キャンセル用トークン</param>
414         /// <returns>Taskオブジェクト</returns>
415         public async Task SaveFile(string filepath, Encoding enc,string newLine, System.Threading.CancellationTokenSource token)
416         {
417             var fs = new System.IO.StreamWriter(filepath, false , enc);
418             fs.NewLine = newLine;
419             await this.Document.SaveAsync(fs, token);
420             fs.Close();
421         }
422
423         /// <summary>
424         /// アンマネージドリソースを開放する
425         /// </summary>
426         public void Dispose()
427         {
428             if (this.disposed)
429                 return;
430             this.Dispose(true);
431             GC.SuppressFinalize(this);
432             this.disposed = true;
433         }
434
435         /// <summary>
436         /// リソースを開放する
437         /// </summary>
438         /// <param name="disposing">真ならマネージドリソースも開放し、そうでないならアンマネージドリソースのみを開放する</param>
439         void Dispose(bool disposing)
440         {
441             if (disposing)
442             {
443                 this.textStore.Dispose();
444                 this.timer.Stop();
445                 this.View.Dispose();
446                 this.Render.Dispose();
447             }
448             SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
449         }
450         
451         void Refresh(Rectangle updateRect)
452         {
453             if (this.disposed || this.Visibility == Visibility.Collapsed)
454                 return;
455
456             this.Render.DrawContent(this.View, this.IsEnabled, updateRect);
457             this.Document.IsRequestRedraw = false;
458         }
459
460         #region Commands
461         void CanExecute(object sender, CanExecuteRoutedEventArgs e)
462         {
463             e.CanExecute = this.IsEnabled;
464         }
465
466         void ToggleCodePointCommand(object sender, RoutedEventArgs e)
467         {
468             if (!this._Controller.ConvertToChar())
469                 this._Controller.ConvertToCodePoint();
470             this.Refresh();
471         }
472
473         void CopyCommand(object sender, RoutedEventArgs e)
474         {
475             this.Copy();
476         }
477
478         void CutCommand(object sender, RoutedEventArgs e)
479         {
480             this.Cut();
481             this.Refresh();
482         }
483
484         void PasteCommand(object sender, RoutedEventArgs e)
485         {
486             this.Paste();
487             this.Refresh();
488         }
489
490         void DeleteCommand(object sender, RoutedEventArgs e)
491         {
492             int oldLength = this.Document.Length;
493             this._Controller.DoDeleteAction();
494             this.Refresh();
495         }
496
497         void SelectAllCommand(object sender, RoutedEventArgs e)
498         {
499             this.Select(0, this.Document.Length);
500             this.Refresh();
501         }
502
503         void UndoCommand(object sender, RoutedEventArgs e)
504         {
505             int oldLength = this.Document.Length;
506             this.Document.UndoManager.undo();
507             this.Refresh();
508         }
509
510         void RedoCommand(object sender, RoutedEventArgs e)
511         {
512             int oldLength = this.Document.Length;
513             this.Document.UndoManager.redo();
514             this.Refresh();
515         }
516
517         void ToggleInsertCommand(object sender, RoutedEventArgs e)
518         {
519             if (this.InsertMode)
520                 this.InsertMode = false;
521             else
522                 this.InsertMode = true;
523             this.Refresh();
524         }
525
526         void ToggleRectSelectCommand(object sender, RoutedEventArgs e)
527         {
528             if (this.RectSelectMode)
529                 this.RectSelectMode = false;
530             else
531                 this.RectSelectMode = true;
532             this.Refresh();
533         }
534         void ToggleFlowDirectionCommand(object sender, RoutedEventArgs e)
535         {
536             if (this.FlowDirection == System.Windows.FlowDirection.LeftToRight)
537                 this.FlowDirection = System.Windows.FlowDirection.RightToLeft;
538             else
539                 this.FlowDirection = System.Windows.FlowDirection.LeftToRight;
540             this.Refresh();
541         }
542         #endregion
543         #region TSF
544         internal TextStore TextStore
545         {
546             get { return this.textStore; }
547         }
548
549         bool textStore_IsReadOnly()
550         {
551             return false;
552         }
553
554         bool textStore_IsLoading()
555         {
556             return false;
557         }
558
559         void textStore_CompositionEnded()
560         {
561             TextStoreHelper.EndCompostion(this.Document);
562             this.Refresh();
563         }
564
565         void textStore_CompositionUpdated(int start, int end)
566         {
567             if (TextStoreHelper.ScrollToCompstionUpdated(this.textStore, this.View, start, end))
568                 this.Refresh();
569         }
570         bool textStore_CompositionStarted()
571         {
572             bool result = TextStoreHelper.StartCompstion(this.Document);
573             if (!result)
574                 System.Media.SystemSounds.Beep.Play();
575             return result;
576         }
577
578         string _textStore_GetString(int start, int length)
579         {
580             return this.Document.ToString(start, length);
581         }
582
583         IntPtr _textStore_GetHWnd()
584         {
585             var hwndSource = HwndSource.FromVisual(this) as HwndSource;
586             if (hwndSource != null)
587                 return hwndSource.Handle;
588             else
589                 return IntPtr.Zero;
590         }
591
592         void _textStore_GetStringExtent(
593             int i_startIndex,
594             int i_endIndex,
595             out POINT o_topLeft,
596             out POINT o_bottomRight
597         )
598         {
599             Point startPos, endPos;
600             TextStoreHelper.GetStringExtent(this.Document, this.View, i_startIndex, i_endIndex, out startPos, out endPos);
601
602             double scale = this.Render.GetScale();
603             
604             startPos = PointToScreen(this.TranslatePoint(startPos.Scale(scale), this));
605             endPos = PointToScreen(this.TranslatePoint(endPos.Scale(scale), this));
606             
607             o_topLeft = new POINT((int)startPos.X, (int)startPos.Y);
608             o_bottomRight = new POINT((int)endPos.X, (int)endPos.Y);
609         }
610
611         void _textStore_GetScreenExtent(out POINT o_topLeft, out POINT o_bottomRight)
612         {
613             var pointTopLeft = new Point(0, 0);
614             var pointBottomRight = new Point(this.RenderSize.Width, this.RenderSize.Height);
615
616             pointTopLeft = PointToScreen(pointTopLeft);
617             pointBottomRight = PointToScreen(pointBottomRight);
618
619             o_topLeft = new POINT((int)pointTopLeft.X, (int)pointTopLeft.Y);
620             o_bottomRight = new POINT((int)pointBottomRight.X, (int)pointBottomRight.Y);
621         }
622
623         void _textStore_GetSelectionIndex(int start_index, int max_count, out DotNetTextStore.TextSelection[] sels)
624         {
625             TextRange selRange;
626             TextStoreHelper.GetSelection(this._Controller, this.View.Selections, out selRange);
627
628             sels = new DotNetTextStore.TextSelection[1];
629             sels[0] = new DotNetTextStore.TextSelection();
630             sels[0].start = selRange.Index;
631             sels[0].end = selRange.Index + selRange.Length;
632         }
633
634         void _textStore_SetSelectionIndex(DotNetTextStore.TextSelection[] sels)
635         {
636             TextStoreHelper.SetSelectionIndex(this._Controller, this.View, sels[0].start, sels[0].end);
637             this.Refresh();
638         }
639
640         void _textStore_InsertAtSelection(string i_value, ref int o_startIndex, ref int o_endIndex)
641         {
642             TextStoreHelper.InsertTextAtSelection(this._Controller, i_value);
643             this.Refresh();
644         }
645
646         /// <summary>
647         /// キーボードフォーカスが取得されたときに呼ばれます
648         /// </summary>
649         /// <param name="e">イベントデーター</param>
650         protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
651         {
652             base.OnGotKeyboardFocus(e);
653             this.textStore.SetFocus();
654             this.View.IsFocused = true;
655             this.timer.Interval = new TimeSpan(0,0,0,0,Interval);
656             this.Refresh();
657         }
658
659         /// <summary>
660         /// キーボードフォーカスが失われたときに呼ばれます
661         /// </summary>
662         /// <param name="e">イベントデーター</param>
663         protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
664         {
665             base.OnLostKeyboardFocus(e);
666             this.View.IsFocused = false;
667             this.timer.Interval = new TimeSpan(0, 0, 0, 0, IntervalWhenLostFocuse);
668             this.Refresh();
669         }
670         #endregion
671         #region Event
672         /// <summary>
673         /// キャレットが移動したときに通知されるイベント
674         /// </summary>
675         public event EventHandler CaretMoved;
676
677         /// <inheritdoc/>
678         protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
679         {
680             this.peer = new FooTextBoxAutomationPeer(this);
681             return this.peer;
682         }
683
684
685         /// <inheritdoc/>
686         protected override void OnTextInput(TextCompositionEventArgs e)
687         {
688             if (e.Text == "\r")
689             {
690                 this._Controller.DoEnterAction();
691                 this.AutoIndentHooker(this, null);
692             }
693             else if (e.Text == "\b")
694             {
695                 this._Controller.DoBackSpaceAction();
696             }
697             else
698             {
699                 if(this.IsInputString(e.Text))
700                     this._Controller.DoInputString(e.Text);
701             }
702             this.Refresh();
703             base.OnTextInput(e);
704             e.Handled = true;
705         }
706
707         bool IsInputString(string s)
708         {
709             foreach (char charCode in s)
710             {
711                 if ((0x20 <= charCode && charCode <= 0x7e)
712                     || 0x7f < charCode)
713                     return true;
714             }
715             return false;
716         }
717
718         /// <inheritdoc/>
719         protected override void OnKeyDown(KeyEventArgs e)
720         {
721             if (this.textStore.IsLocked())
722                 return;
723
724             ModifierKeys modiferKeys = e.KeyboardDevice.Modifiers;
725
726             var autocomplete = this.Document.AutoComplete as AutoCompleteBox;
727             if (autocomplete != null &&
728                 autocomplete.ProcessKeyDown(this,e, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Control), this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift)))
729             {
730                 e.Handled = true;
731                 return;
732             }
733
734             bool movedCaret = false;
735             switch (e.Key)
736             {
737                 case Key.Up:
738                     this._Controller.MoveCaretVertical(-1, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
739                     this.Refresh();
740                     e.Handled = true;
741                     movedCaret = true;
742                     break;
743                 case Key.Down:
744                     this._Controller.MoveCaretVertical(+1, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
745                     this.Refresh();
746                     e.Handled = true;
747                     movedCaret = true;
748                     break;
749                 case Key.Left:
750                     this._Controller.MoveCaretHorizontical(-1, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift), this.IsPressedModifierKey(modiferKeys, ModifierKeys.Control));
751                     this.Refresh();
752                     e.Handled = true;
753                     movedCaret = true;
754                     break;
755                 case Key.Right:
756                     this._Controller.MoveCaretHorizontical(1, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift), this.IsPressedModifierKey(modiferKeys, ModifierKeys.Control));
757                     this.Refresh();
758                     e.Handled = true;
759                     movedCaret = true;
760                     break;
761                 case Key.PageUp:
762                     this._Controller.Scroll(ScrollDirection.Up,this.View.LineCountOnScreen, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift),true);
763                     this.Refresh();
764                     movedCaret = true;
765                     break;
766                 case Key.PageDown:
767                     this._Controller.Scroll(ScrollDirection.Down,this.View.LineCountOnScreen, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift),true);
768                     this.Refresh();
769                     movedCaret = true;
770                     break;
771                 case Key.Home:
772                     if (this.IsPressedModifierKey(modiferKeys, ModifierKeys.Control))
773                         this._Controller.JumpToHead(this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
774                     else
775                         this._Controller.JumpToLineHead(this.Document.CaretPostion.row, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
776                     this.Refresh();
777                     movedCaret = true;
778                     break;
779                 case Key.End:
780                     if (this.IsPressedModifierKey(modiferKeys, ModifierKeys.Control))
781                         this._Controller.JumpToEnd(this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
782                     else
783                         this._Controller.JumpToLineEnd(this.Document.CaretPostion.row, this.IsPressedModifierKey(modiferKeys, ModifierKeys.Shift));
784                     this.Refresh();
785                     movedCaret = true;
786                     break;
787                 case Key.Tab:
788                     int oldLength = this.Document.Length;
789                     if (this.Selection.Length == 0)
790                         this._Controller.DoInputChar('\t');
791                     else if(this.IsPressedModifierKey(modiferKeys,ModifierKeys.Shift))
792                         this._Controller.DownIndent();
793                     else
794                         this._Controller.UpIndent();
795                     this.Refresh();
796                     e.Handled = true;
797                     break;
798             }
799             if (movedCaret && this.peer != null)
800                 this.peer.OnNotifyCaretChanged();
801             base.OnKeyDown(e);
802         }
803
804         bool IsPressedModifierKey(ModifierKeys keys, ModifierKeys pressed)
805         {
806             if (keys == pressed)
807                 return true;
808             if ((keys & pressed) == pressed)
809                 return true;
810             return false;
811         }
812
813         /// <summary>
814         /// ダブルクリックされたときに呼ばれます
815         /// </summary>
816         /// <param name="e">イベントパラメーター</param>
817         /// <remarks>
818         /// イベントパラメーターはFooMouseEventArgsにキャスト可能です。
819         /// e.Handledを真にした場合、単語単位の選択が行われなくなります
820         /// </remarks>
821         protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
822         {
823             var p = this.GetDipFromPoint(e.GetPosition(this));
824             TextPoint tp = this.View.GetTextPointFromPostion(p);
825             if (tp == TextPoint.Null)
826                 return;
827             int index = this.View.LayoutLines.GetIndexFromTextPoint(tp);
828
829             FooMouseButtonEventArgs newEventArgs = new FooMouseButtonEventArgs(e.MouseDevice,
830                 e.Timestamp,
831                 e.ChangedButton,
832                 e.StylusDevice,
833                 index);
834             newEventArgs.RoutedEvent = e.RoutedEvent;
835             base.OnMouseDoubleClick(newEventArgs);
836
837             if (newEventArgs.Handled)
838                 return;
839
840             if (e.LeftButton == MouseButtonState.Pressed)
841             {
842                 if (p.X < this.Render.TextArea.X)
843                     this.Document.SelectLine((int)index);
844                 else
845                     this.Document.SelectWord((int)index);
846
847                 this.textStore.NotifySelectionChanged();
848                 if(this.peer != null)
849                     this.peer.OnNotifyCaretChanged();
850                 this.Refresh();
851             }
852         }
853
854         /// <summary>
855         /// マウスボタンが押されたときに呼ばれます
856         /// </summary>
857         /// <param name="e">イベントパラメーター</param>
858         /// <remarks>
859         /// イベントパラメーターはFooMouseEventArgsにキャスト可能です。
860         /// e.Handledを真にした場合、キャレットの移動処理が行われなくなります
861         /// </remarks>
862         protected override void OnMouseDown(MouseButtonEventArgs e)
863         {
864             this.CaptureMouse();
865
866             var p = this.GetDipFromPoint(e.GetPosition(this));
867             TextPoint tp = this.View.GetTextPointFromPostion(p);
868             if (tp == TextPoint.Null)
869                 return;
870             int index = this.View.LayoutLines.GetIndexFromTextPoint(tp);
871
872             FooMouseButtonEventArgs newEventArgs = new FooMouseButtonEventArgs(e.MouseDevice,
873                 e.Timestamp,
874                 e.ChangedButton,
875                 e.StylusDevice,
876                 index);
877             newEventArgs.RoutedEvent = e.RoutedEvent;
878             base.OnMouseDown(newEventArgs);
879
880             if (newEventArgs.Handled)
881                 return;
882
883             if (e.LeftButton == MouseButtonState.Pressed)
884             {
885                 FoldingItem foldingData = this.View.HitFoldingData(p.X,tp.row);
886                 if (foldingData != null)
887                 {
888                     if (foldingData.Expand)
889                         this.View.LayoutLines.FoldingCollection.Collapse(foldingData);
890                     else
891                         this.View.LayoutLines.FoldingCollection.Expand(foldingData);
892                     this._Controller.JumpCaret(foldingData.Start,false);
893                 }
894                 else
895                 {
896                     this._Controller.JumpCaret(tp.row, tp.col, false);
897                 }
898                 if (this.peer != null)
899                     this.peer.OnNotifyCaretChanged();
900                 this.View.IsFocused = true;
901                 this.Focus();
902                 this.Document.SelectGrippers.BottomLeft.Enabled = false;
903                 this.Document.SelectGrippers.BottomRight.Enabled = false;
904                 this.Refresh();
905             }
906         }
907
908         /// <summary>
909         /// マウスのボタンが離されたときに呼ばれます
910         /// </summary>
911         /// <param name="e"></param>
912         protected override void OnMouseUp(MouseButtonEventArgs e)
913         {
914             this.ReleaseMouseCapture();
915             base.OnMouseUp(e);
916         }
917
918         /// <summary>
919         /// マウスが移動したときに呼ばれます
920         /// </summary>
921         /// <param name="e">イベントパラメーター</param>
922         /// <remarks>
923         /// イベントパラメーターはFooMouseEventArgsにキャスト可能です。
924         /// e.Handledを真にした場合、選択処理と状況に応じたカーソルの変化が行われなくなります
925         /// </remarks>
926         protected override void  OnMouseMove(MouseEventArgs e)
927         {
928             bool leftPressed = e.LeftButton == MouseButtonState.Pressed;
929
930             var p = this.GetDipFromPoint(e.GetPosition(this));
931
932             TextPointSearchRange searchRange;
933             if (this.View.HitTextArea(p.X, p.Y))
934             {
935                 searchRange = TextPointSearchRange.TextAreaOnly;
936             }
937             else if (leftPressed)
938             {
939                 searchRange = TextPointSearchRange.Full;
940             }
941             else
942             {
943                 this.Cursor = Cursors.Arrow;
944                 base.OnMouseMove(e);
945                 return;
946             }
947
948             TextPoint tp = this.View.GetTextPointFromPostion(p, searchRange);
949
950             if (tp == TextPoint.Null)
951             {
952                 this.Cursor = Cursors.Arrow;
953                 base.OnMouseMove(e);
954                 return;
955             }
956
957             int index = this.View.GetIndexFromLayoutLine(tp);
958
959             FooMouseEventArgs newEventArgs = new FooMouseEventArgs(e.MouseDevice, e.Timestamp, e.StylusDevice, index);
960             newEventArgs.RoutedEvent = e.RoutedEvent;
961             base.OnMouseMove(newEventArgs);
962
963             if (newEventArgs.Handled)
964                 return;
965
966             //この状態のときはカーソルがテキストエリア内にある
967             if (searchRange == TextPointSearchRange.TextAreaOnly)
968             {
969                 if (this._Controller.IsMarker(tp, HilightType.Url))
970                     this.Cursor = Cursors.Hand;
971                 else
972                     this.Cursor = Cursors.IBeam;
973             }
974             else
975             {
976                 this.Cursor = Cursors.Arrow;
977             }
978             if (leftPressed)
979             {
980                 bool controlPressed = (Keyboard.GetKeyStates(Key.LeftCtrl) & KeyStates.Down) == KeyStates.Down;
981                 this._Controller.MoveCaretAndSelect(tp, controlPressed);
982                 if (this.peer != null)
983                     this.peer.OnNotifyCaretChanged();
984                 this.Refresh();
985             }
986         }
987
988         Gripper hittedGripper;
989         bool touchScrolled = false;
990
991         /// <inheritdoc/>
992         protected override void OnTouchDown(TouchEventArgs e)
993         {
994             var p = this.GetDipFromPoint(e.GetTouchPoint(this).Position);
995             this.hittedGripper = this.View.HitGripperFromPoint(p);
996             this.CaptureTouch(e.TouchDevice);
997         }
998
999         /// <inheritdoc/>
1000         protected override void OnTouchUp(TouchEventArgs e)
1001         {
1002             this.ReleaseTouchCapture(e.TouchDevice);
1003             if(this.hittedGripper != null || this.touchScrolled)
1004             {
1005                 this.hittedGripper = null;
1006                 this.touchScrolled = false;
1007                 return;
1008             }
1009
1010             var p = this.GetDipFromPoint(e.GetTouchPoint(this).Position);
1011             TextPoint tp = this.View.GetTextPointFromPostion(p);
1012             if (tp == TextPoint.Null)
1013                 return;
1014             int index = this.View.LayoutLines.GetIndexFromTextPoint(tp);
1015
1016             FoldingItem foldingData = this.View.HitFoldingData(p.X, tp.row);
1017             if (foldingData != null)
1018             {
1019                 if (foldingData.Expand)
1020                     this.View.LayoutLines.FoldingCollection.Collapse(foldingData);
1021                 else
1022                     this.View.LayoutLines.FoldingCollection.Expand(foldingData);
1023                 this._Controller.JumpCaret(foldingData.Start, false);
1024             }
1025             else
1026             {
1027                 this._Controller.JumpCaret(tp.row, tp.col, false);
1028             }
1029             if (this.peer != null)
1030                 this.peer.OnNotifyCaretChanged();
1031             this.View.IsFocused = true;
1032             this.Focus();
1033             this.Document.SelectGrippers.BottomLeft.Enabled = false;
1034             this.Document.SelectGrippers.BottomRight.Enabled = true;
1035             this.Refresh();
1036         }
1037
1038         /// <inheritdoc/>
1039         protected override void OnTouchMove(TouchEventArgs e)
1040         {
1041             var p = this.GetDipFromPoint(e.GetTouchPoint(this).Position);
1042             if (this.Controller.MoveCaretAndGripper(p, this.hittedGripper))
1043             {
1044                 if (this.peer != null)
1045                     this.peer.OnNotifyCaretChanged();
1046                 this.Refresh();
1047             }
1048         }
1049
1050         /// <inheritdoc/>
1051         protected override void OnManipulationInertiaStarting(ManipulationInertiaStartingEventArgs e)
1052         {
1053         }
1054
1055         /// <inheritdoc/>
1056         protected override void OnManipulationDelta(ManipulationDeltaEventArgs e)
1057         {
1058             if (this.hittedGripper != null)
1059                 return;
1060
1061             Point translation = new Point(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
1062
1063             //Xの絶対値が大きければ横方向のスクロールで、そうでなければ縦方向らしい
1064             if (Math.Abs(e.CumulativeManipulation.Translation.X) < Math.Abs(e.CumulativeManipulation.Translation.Y))
1065             {
1066                 int deltay = (int)Math.Abs(Math.Ceiling(translation.Y));
1067                 if (translation.Y < 0)
1068                     this._Controller.ScrollByPixel(ScrollDirection.Down, deltay, false, false);
1069                 else
1070                     this._Controller.ScrollByPixel(ScrollDirection.Up, deltay, false, false);
1071                 this.touchScrolled = true;
1072                 this.Refresh();
1073                 return;
1074             }
1075
1076             int deltax = (int)Math.Abs(Math.Ceiling(translation.X));
1077             if (deltax != 0)
1078             {
1079                 if (translation.X < 0)
1080                     this._Controller.Scroll(ScrollDirection.Left, deltax, false, false);
1081                 else
1082                     this._Controller.Scroll(ScrollDirection.Right, deltax, false, false);
1083                 this.touchScrolled = true;
1084                 this.Refresh();
1085             }
1086         }
1087
1088         private Point GetDipFromPoint(Point p)
1089         {
1090             float dpi;
1091             this.Render.GetDpi(out dpi,out dpi);
1092             double scale = dpi / 96.0;
1093             return p.Scale(1 / scale);
1094         }
1095
1096         /// <inheritdoc/>
1097         protected override void OnMouseWheel(MouseWheelEventArgs e)
1098         {
1099             if(Keyboard.Modifiers == ModifierKeys.None)
1100             {
1101                 if (e.Delta > 0)
1102                     this._Controller.Scroll(ScrollDirection.Up, SystemParameters.WheelScrollLines, false, false);
1103                 else
1104                     this._Controller.Scroll(ScrollDirection.Down, SystemParameters.WheelScrollLines, false, false);
1105             }
1106             else if (Keyboard.Modifiers == ModifierKeys.Control)
1107             {
1108                 double newFontSize = this.Render.FontSize;
1109                 if (e.Delta > 0)
1110                     newFontSize++;
1111                 else
1112                     newFontSize--;
1113                 if (newFontSize > MaxFontSize)
1114                     newFontSize = 72;
1115                 else if (newFontSize < MinFontSize)
1116                     newFontSize = 1;
1117                 this.Render.FontSize = newFontSize;
1118                 SetValue(MagnificationPowerPropertyKey, this.Render.FontSize / this.FontSize);
1119             }
1120             this.Refresh();
1121             base.OnMouseWheel(e);
1122         }
1123
1124         void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
1125         {
1126             if (e.Category == UserPreferenceCategory.Keyboard)
1127             {
1128                 int blinkTime = (int)NativeMethods.GetCaretBlinkTime();
1129                 this.View.CaretBlink = blinkTime >= 0;
1130                 this.View.CaretBlinkTime = blinkTime * 2;
1131             }
1132             if (e.Category == UserPreferenceCategory.General)
1133             {
1134                 this.View.CaretWidthOnInsertMode = SystemParameters.CaretWidth;
1135             }
1136         }
1137
1138         void Document_Update(object sender, DocumentUpdateEventArgs e)
1139         {
1140             if (this.textStore.IsLocked())
1141                 return;
1142             if(e.type == UpdateType.Replace)
1143                 TextStoreHelper.NotifyTextChanged(this.textStore, e.startIndex, e.removeLength, e.insertLength);
1144             if(this.peer != null)
1145                 this.peer.OnNotifyTextChanged();
1146         }
1147
1148         void timer_Tick(object sender, EventArgs e)
1149         {
1150             if (this.image.ActualWidth == 0 || this.image.ActualHeight == 0)
1151                 return;
1152             if (this.Resize(this.image.ActualWidth, this.image.ActualHeight))
1153             {
1154                 this.Refresh(this.View.PageBound);
1155                 return;
1156             }
1157
1158             bool updateAll = this.View.LayoutLines.HilightAll() || this.View.LayoutLines.GenerateFolding() || this.Document.IsRequestRedraw;
1159
1160             if (updateAll)
1161                 this.Refresh(this.View.PageBound);
1162             else
1163                 this.Refresh(this.View.GetCurrentCaretRect());
1164         }
1165
1166         void horizontalScrollBar_Scroll(object sender, ScrollEventArgs e)
1167         {
1168             if (this.horizontalScrollBar == null)
1169                 return;
1170             double toX;
1171             if (this.FlowDirection == System.Windows.FlowDirection.LeftToRight)
1172                 toX = this.horizontalScrollBar.Value;
1173             else
1174                 toX = -this.horizontalScrollBar.Value;
1175             this.Controller.ScrollByPixel(ScrollDirection.Left, (int)toX, false, false);
1176             this.Refresh();
1177         }
1178
1179         void verticalScrollBar_Scroll(object sender, ScrollEventArgs e)
1180         {
1181             if (this.verticalScrollBar == null)
1182                 return;
1183             this.Controller.Scroll(this.Document.Src.X, (int)this.verticalScrollBar.Value, false, false);
1184             this.Refresh();
1185         }
1186
1187         void View_SrcChanged(object sender, EventArgs e)
1188         {
1189             if (this.horizontalScrollBar == null || this.verticalScrollBar == null)
1190                 return;
1191             EditView view = this.View;
1192             if (view.Src.Row > this.Document.LayoutLines.Count)
1193                 this.verticalScrollBar.Maximum = this.Document.LayoutLines.Count - 1;
1194             double absoulteX = Math.Abs(view.Src.X);
1195             if(absoulteX > this.horizontalScrollBar.Maximum)
1196                 this.horizontalScrollBar.Maximum = absoulteX + view.PageBound.Width + 1;
1197             if(view.Src.Row != this.verticalScrollBar.Value)
1198                 this.verticalScrollBar.Value = view.Src.Row;
1199             if (view.Src.X != this.horizontalScrollBar.Value)
1200                 this.horizontalScrollBar.Value = Math.Abs(view.Src.X);
1201         }
1202
1203         void Controller_SelectionChanged(object sender, EventArgs e)
1204         {
1205             this.View.CaretBlink = this.View.CaretBlink;
1206             this.CaretMoved(this, null);
1207             //こうしないと選択できなくなってしまう
1208             this.isNotifyChanged = true;
1209             SetValue(SelectedTextProperty, this._Controller.SelectedText);
1210             SetValue(SelectionProperty, new TextRange(this._Controller.SelectionStart, this._Controller.SelectionLength));
1211             SetValue(CaretPostionProperty, this.Document.CaretPostion);
1212             this.isNotifyChanged = false;
1213             if (this.textStore.IsLocked() == false)
1214                 this.textStore.NotifySelectionChanged();
1215         }
1216
1217         void FooTextBox_Loaded(object sender, RoutedEventArgs e)
1218         {
1219             this.Resize(this.image.ActualWidth, this.image.ActualHeight);
1220             this.Focus();
1221             this.timer.Start();
1222         }
1223
1224         bool Resize(double width, double height)
1225         {
1226             if (width == 0 || height == 0)
1227                 throw new ArgumentOutOfRangeException();
1228             if (this.Render.Resize(width, height))
1229             {
1230                 double scale = this.Render.GetScale();
1231                 // RenderはレタリングはDIPだが、widthとheightの値はDPI依存なのでDIPに変換する
1232                 this.View.PageBound = new Rectangle(0, 0, width / scale, height / scale);
1233
1234                 if (this.horizontalScrollBar != null)
1235                 {
1236                     this.horizontalScrollBar.LargeChange = this.View.PageBound.Width;
1237                     this.horizontalScrollBar.Maximum = this.View.LongestWidth + this.horizontalScrollBar.LargeChange + 1;
1238                 }
1239                 if (this.verticalScrollBar != null)
1240                 {
1241                     this.verticalScrollBar.LargeChange = this.View.LineCountOnScreen;
1242                     this.verticalScrollBar.Maximum = this.View.LayoutLines.Count + this.verticalScrollBar.LargeChange + 1;
1243                 }
1244                 return true;
1245             }
1246             return false;
1247         }
1248
1249         private void SetDocument(Document value)
1250         {
1251             if (value == null)
1252                 return;
1253
1254             Document old_doc = this._Document;
1255             int oldLength = 0;
1256             if (this._Document != null)
1257             {
1258                 old_doc.Update -= new DocumentUpdateEventHandler(Document_Update);
1259                 old_doc.LoadProgress -= Document_LoadProgress;
1260                 old_doc.SelectionChanged -= new EventHandler(Controller_SelectionChanged);
1261                 old_doc.AutoCompleteChanged -= _Document_AutoCompleteChanged;
1262                 oldLength = old_doc.Length;
1263                 if (this._Document.AutoComplete != null)
1264                 {
1265                     ((AutoCompleteBox)this._Document.AutoComplete).TargetPopup = null;
1266                     this._Document.AutoComplete.GetPostion = null;
1267                     this._Document.AutoComplete = null;
1268                 }
1269             }
1270
1271             this._Document = value;
1272             this._Document.LayoutLines.Render = this.Render;
1273             this._Document.Update += new DocumentUpdateEventHandler(Document_Update);
1274             this._Document.LoadProgress += Document_LoadProgress;
1275             this._Document.AutoCompleteChanged += _Document_AutoCompleteChanged;
1276             if (this._Document.AutoComplete != null && this.Document.AutoComplete.GetPostion == null)
1277                 this._Document_AutoCompleteChanged(this.Document, null);
1278             //初期化が終わっていればすべて存在する
1279             if (this.Controller != null && this.View != null && this.textStore != null)
1280             {
1281                 this._Document.SelectionChanged += new EventHandler(Controller_SelectionChanged);
1282
1283                 this.Controller.Document = value;
1284                 this.View.Document = value;
1285                 this.Controller.AdjustCaret();
1286                 this.textStore.NotifyTextChanged(oldLength, value.Length);
1287
1288                 //依存プロパティとドキュメント内容が食い違っているので再設定する
1289                 this.ShowFullSpace = value.ShowFullSpace;
1290                 this.ShowHalfSpace = value.ShowHalfSpace;
1291                 this.ShowLineBreak = value.ShowLineBreak;
1292                 this.ShowTab = value.ShowTab;
1293                 this.FlowDirection = value.RightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
1294                 this.IndentMode = value.IndentMode;
1295                 this.DrawCaretLine = !value.HideLineMarker;
1296                 this.InsertMode = value.InsertMode;
1297                 this.DrawRuler = !value.HideRuler;
1298                 this.DrawLineNumber = value.DrawLineNumber;
1299                 this.MarkURL = value.UrlMark;
1300                 this.LineBreakMethod = value.LineBreak;
1301                 this.LineBreakCharCount = value.LineBreakCharCount;
1302                 this.TabChars = value.TabStops;
1303
1304                 this.Refresh();
1305             }
1306         }
1307
1308         private void _Document_AutoCompleteChanged(object sender, EventArgs e)
1309         {
1310             Document doc = (Document)sender;
1311             ((AutoCompleteBox)this._Document.AutoComplete).TargetPopup = this.popup;
1312             this._Document.AutoComplete.GetPostion = (tp, edoc) =>
1313             {
1314                 var p = this.View.GetPostionFromTextPoint(tp);
1315                 int height = (int)this.Render.emSize.Height;
1316                 p.Y += height;
1317                 return PointToScreen(this.TranslatePoint(p.Scale(Util.GetScale()), this));
1318             };
1319         }
1320
1321         /// <summary>
1322         /// プロパティーが変更されたときに呼ばれます
1323         /// </summary>
1324         /// <param name="e">イベントパラメーター</param>
1325         protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
1326         {
1327             switch (e.Property.Name)
1328             {
1329                 case "Document":
1330                     this.SetDocument(this.Document);
1331                     break;
1332                 case "Hilighter":
1333                     this.View.Hilighter = this.Hilighter;
1334                     break;
1335                 case "TextAntialiasMode":
1336                     this.Render.TextAntialiasMode = this.TextAntialiasMode;
1337                     break;
1338                 case "FoldingStrategy":
1339                     this.View.LayoutLines.FoldingStrategy = this.FoldingStrategy;
1340                     break;
1341                 case "SelectedText":
1342                     if (!this.isNotifyChanged)
1343                         this._Controller.SelectedText = this.SelectedText;
1344                     break;
1345                 case "IndentMode":
1346                     this._Controller.IndentMode = this.IndentMode;
1347                     break;
1348                 case "Selection":
1349                     if(!this.isNotifyChanged)
1350                         this.Select(this.Selection.Index, this.Selection.Length);
1351                     break;
1352                 case "CaretPostion":
1353                     if (!this.isNotifyChanged)
1354                         this.JumpCaret(this.CaretPostion.row, this.CaretPostion.col);
1355                     break;
1356                 case "LineBreakMethod":
1357                     this.Document.LineBreak = this.LineBreakMethod;
1358                     break;
1359                 case "LineBreakCharCount":
1360                     this.Document.LineBreakCharCount = this.LineBreakCharCount;
1361                     break;
1362                 case "InsertMode":
1363                     this.View.InsertMode = this.InsertMode;
1364                     break;
1365                 case "TabChars":
1366                     this.Document.TabStops = this.TabChars;
1367                     break;
1368                 case "RectSelectMode":
1369                     this._Controller.RectSelection = this.RectSelectMode;
1370                     break;
1371                 case "DrawCaret":
1372                     this.View.HideCaret = !this.DrawCaret;
1373                     break;
1374                 case "DrawCaretLine":
1375                     this.View.HideLineMarker = !this.DrawCaretLine;
1376                     break;
1377                 case "DrawLineNumber":
1378                     this.Document.DrawLineNumber = this.DrawLineNumber;
1379                     break;
1380                 case "FontFamily":
1381                     this.Render.FontFamily = this.FontFamily;
1382                     break;
1383                 case "FontSize":
1384                     this.Render.FontSize = this.FontSize;
1385                     break;
1386                 case "FontStyle":
1387                     this.Render.FontStyle = this.FontStyle;
1388                     break;
1389                 case "FontWeight":
1390                     this.Render.FontWeigth = this.FontWeight;
1391                     break;
1392                 case "Foreground":
1393                     this.Render.Foreground = D2DRender.ToColor4(this.Foreground);
1394                     break;
1395                 case "HilightForeground":
1396                     this.Render.HilightForeground = D2DRender.ToColor4(this.HilightForeground);
1397                     break;
1398                 case "Background":
1399                     this.Render.Background = D2DRender.ToColor4(this.Background);
1400                     break;
1401                 case "ControlChar":
1402                     this.Render.ControlChar =D2DRender.ToColor4( this.ControlChar);
1403                     break;
1404                 case "Hilight":
1405                     this.Render.Hilight = D2DRender.ToColor4(this.Hilight);
1406                     break;
1407                 case "Keyword1":
1408                     this.Render.Keyword1 = D2DRender.ToColor4(this.Keyword1);
1409                     break;
1410                 case "Keyword2":
1411                     this.Render.Keyword2 = D2DRender.ToColor4(this.Keyword2);
1412                     break;
1413                 case "Comment":
1414                     this.Render.Comment = D2DRender.ToColor4(this.Comment);
1415                     break;
1416                 case "Literal":
1417                     this.Render.Literal = D2DRender.ToColor4(this.Literal);
1418                     break;
1419                 case "URL":
1420                     this.Render.Url = D2DRender.ToColor4(this.URL);
1421                     break;
1422                 case "InsertCaret":
1423                     this.Render.InsertCaret = D2DRender.ToColor4(this.InsertCaret);
1424                     break;
1425                 case "OverwriteCaret":
1426                     this.Render.OverwriteCaret = D2DRender.ToColor4(this.OverwriteCaret);
1427                     break;
1428                 case "Padding":
1429                     this.View.Padding = new Padding((int)this.Padding.Left, (int)this.Padding.Top, (int)this.Padding.Right, (int)this.Padding.Bottom);
1430                     break;
1431                 case "LineMarker":
1432                     this.Render.LineMarker = D2DRender.ToColor4(this.LineMarker);
1433                     break;
1434                 case "MarkURL":
1435                     this.Document.UrlMark = this.MarkURL;
1436                     break;
1437                 case "ShowFullSpace":
1438                     this.Document.ShowFullSpace = this.ShowFullSpace;
1439                     break;
1440                 case "ShowHalfSpace":
1441                     this.Document.ShowHalfSpace = this.ShowHalfSpace;
1442                     break;
1443                 case "ShowTab":
1444                     this.Document.ShowTab = this.ShowTab;
1445                     break;
1446                 case "ShowLineBreak":
1447                     this.Document.ShowLineBreak = this.ShowLineBreak;
1448                     break;
1449                 case "FlowDirection":
1450                     this.Document.RightToLeft = this.FlowDirection == System.Windows.FlowDirection.RightToLeft;
1451                     this.horizontalScrollBar.FlowDirection = this.FlowDirection;
1452                     break;
1453                 case "DrawRuler":
1454                     this.Document.HideRuler = !this.DrawRuler;
1455                     this._Controller.JumpCaret(this.Document.CaretPostion.row, this.Document.CaretPostion.col);
1456                     break;
1457                 case "UpdateArea":
1458                     this.Render.UpdateArea = D2DRender.ToColor4(this.UpdateArea);
1459                     break;
1460                 case "LineNumber":
1461                     this.Render.LineNumber = D2DRender.ToColor4(this.LineNumber);
1462                     break;
1463             }
1464             base.OnPropertyChanged(e);
1465         }
1466         #endregion
1467         #region property
1468
1469         internal Controller Controller
1470         {
1471             get
1472             {
1473                 return this._Controller;
1474             }
1475         }
1476
1477         /// <summary>
1478         /// 文字列の描写に使用されるアンチエイリアシング モードを表します
1479         /// </summary>
1480         public TextAntialiasMode TextAntialiasMode
1481         {
1482             get { return (TextAntialiasMode)GetValue(TextAntialiasModeProperty); }
1483             set { SetValue(TextAntialiasModeProperty, value); }
1484         }
1485
1486         /// <summary>
1487         /// TextAntialiasModeの依存プロパティを表す
1488         /// </summary>
1489         public static readonly DependencyProperty TextAntialiasModeProperty =
1490             DependencyProperty.Register("TextAntialiasMode", typeof(TextAntialiasMode), typeof(FooTextBox), new PropertyMetadata(TextAntialiasMode.Default));
1491
1492         /// <summary>
1493         /// シンタックスハイライターを表す
1494         /// </summary>
1495         public IHilighter Hilighter
1496         {
1497             get { return (IHilighter)GetValue(HilighterProperty); }
1498             set { SetValue(HilighterProperty, value); }
1499         }
1500
1501         /// <summary>
1502         /// Hilighterの依存プロパティを表す
1503         /// </summary>
1504         public static readonly DependencyProperty HilighterProperty =
1505             DependencyProperty.Register("Hilighter", typeof(IHilighter), typeof(FooTextBox), new PropertyMetadata(null));
1506
1507         /// <summary>
1508         /// フォールティングを作成するインターフェイスを表す
1509         /// </summary>
1510         public IFoldingStrategy FoldingStrategy
1511         {
1512             get { return (IFoldingStrategy)GetValue(FoldingStrategyProperty); }
1513             set { SetValue(FoldingStrategyProperty, value); }
1514         }
1515
1516         /// <summary>
1517         /// FoldingStrategyの依存プロパティ
1518         /// </summary>
1519         public static readonly DependencyProperty FoldingStrategyProperty =
1520             DependencyProperty.Register("FoldingStrategy", typeof(IFoldingStrategy), typeof(FooTextBox), new PropertyMetadata(null));
1521
1522
1523         /// <summary>
1524         /// マーカーパターンセット
1525         /// </summary>
1526         public MarkerPatternSet MarkerPatternSet
1527         {
1528             get
1529             {
1530                 return this.Document.MarkerPatternSet;
1531             }
1532         }
1533
1534         /// <summary>
1535         /// ドキュメント表す
1536         /// </summary>
1537         public Document Document
1538         {
1539             get { return (Document)GetValue(DocumentProperty); }
1540             set { SetValue(DocumentProperty, value); }
1541         }
1542
1543         /// <summary>
1544         /// ドキュメント添付プロパティ
1545         /// </summary>
1546         public static readonly DependencyProperty DocumentProperty =
1547             DependencyProperty.Register("Document", typeof(Document), typeof(FooTextBox), new PropertyMetadata(null));
1548
1549
1550         /// <summary>
1551         /// レイアウト行を表す
1552         /// </summary>
1553         public LineToIndexTable LayoutLineCollection
1554         {
1555             get { return this.View.LayoutLines; }
1556         }
1557
1558         /// <summary>
1559         /// 選択中の文字列を表す
1560         /// </summary>
1561         public string SelectedText
1562         {
1563             get { return (string)GetValue(SelectedTextProperty); }
1564             set { SetValue(SelectedTextProperty, value); }
1565         }
1566
1567         /// <summary>
1568         /// SelectedTextの依存プロパティを表す
1569         /// </summary>
1570         public static readonly DependencyProperty SelectedTextProperty =
1571             DependencyProperty.Register("SelectedText", typeof(string), typeof(FooTextBox), new PropertyMetadata(null));
1572
1573         /// <summary>
1574         /// インデントの方法を表す
1575         /// </summary>
1576         public IndentMode IndentMode
1577         {
1578             get { return (IndentMode)GetValue(IndentModeProperty); }
1579             set { SetValue(IndentModeProperty, value); }
1580         }
1581
1582         /// <summary>
1583         /// IndentModeの依存プロパティを表す
1584         /// </summary>
1585         public static readonly DependencyProperty IndentModeProperty =
1586             DependencyProperty.Register("IndentMode", typeof(IndentMode), typeof(FooTextBox), new PropertyMetadata(IndentMode.Tab));
1587
1588         /// <summary>
1589         /// 選択範囲を表す
1590         /// </summary>
1591         /// <remarks>
1592         /// Lengthが0の場合はキャレット位置を表します。
1593         /// 矩形選択モードの場合、選択範囲の文字数ではなく、開始位置から終了位置までの長さとなります
1594         /// </remarks>
1595         public TextRange Selection
1596         {
1597             get { return (TextRange)GetValue(SelectionProperty); }
1598             set { SetValue(SelectionProperty, value); }
1599         }
1600
1601         /// <summary>
1602         /// Selectionの依存プロパティを表す
1603         /// </summary>
1604         public static readonly DependencyProperty SelectionProperty =
1605             DependencyProperty.Register("Selection", typeof(TextRange), typeof(FooTextBox), new PropertyMetadata(TextRange.Null));
1606
1607         /// <summary>
1608         /// 拡大率を表す
1609         /// </summary>
1610         public double MagnificationPower
1611         {
1612             get { return (double)GetValue(MagnificationPowerPropertyKey.DependencyProperty); }
1613         }
1614
1615         /// <summary>
1616         /// 拡大率を表す依存プロパティ
1617         /// </summary>
1618         public static readonly DependencyPropertyKey MagnificationPowerPropertyKey =
1619             DependencyProperty.RegisterReadOnly("MagnificationPower", typeof(double), typeof(FooTextBox), new PropertyMetadata(1.0));
1620
1621         /// <summary>
1622         /// レタリング方向を表す
1623         /// </summary>
1624         public new FlowDirection FlowDirection
1625         {
1626             get { return (FlowDirection)GetValue(FlowDirectionProperty); }
1627             set { SetValue(FlowDirectionProperty, value); }
1628         }
1629
1630         /// <summary>
1631         /// レタリング方向を表す。これは依存プロパティです
1632         /// </summary>
1633         public new static readonly DependencyProperty FlowDirectionProperty =
1634             DependencyProperty.Register("FlowDirection", typeof(FlowDirection), typeof(FooTextBox), new PropertyMetadata(FlowDirection.LeftToRight));        
1635
1636         /// <summary>
1637         /// キャレット位置を表す。これは依存プロパティです
1638         /// </summary>
1639         public TextPoint CaretPostion
1640         {
1641             get { return (TextPoint)GetValue(CaretPostionProperty); }
1642             set { SetValue(CaretPostionProperty, value); }
1643         }
1644
1645         /// <summary>
1646         /// CaretPostionの依存プロパティを表す
1647         /// </summary>
1648         public static readonly DependencyProperty CaretPostionProperty =
1649             DependencyProperty.Register("CaretPostion", typeof(TextPoint), typeof(FooTextBox), new PropertyMetadata(TextPoint.Null));
1650         
1651         /// <summary>
1652         /// デフォルトの文字色を表す。これは依存プロパティです
1653         /// </summary>
1654         public new System.Windows.Media.Color Foreground
1655         {
1656             get { return (System.Windows.Media.Color)GetValue(ForegroundProperty); }
1657             set { SetValue(ForegroundProperty, value); }
1658         }
1659
1660         /// <summary>
1661         /// Foregroundの依存プロパティを表す
1662         /// </summary>
1663         public new static readonly DependencyProperty ForegroundProperty =
1664             DependencyProperty.Register("Foreground", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(SystemColors.WindowTextColor));
1665
1666         /// <summary>
1667         /// 背景色を表す。これは依存プロパティです
1668         /// </summary>
1669         public new System.Windows.Media.Color Background
1670         {
1671             get { return (System.Windows.Media.Color)GetValue(BackgroundProperty); }
1672             set { SetValue(BackgroundProperty, value); }
1673         }
1674
1675         /// <summary>
1676         /// Backgroundの依存プロパティを表す
1677         /// </summary>
1678         public new static readonly DependencyProperty BackgroundProperty =
1679             DependencyProperty.Register("Background", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(SystemColors.WindowColor));
1680
1681         /// <summary>
1682         /// 選択時の文字色を表す。これは依存プロパティです
1683         /// </summary>
1684         public System.Windows.Media.Color HilightForeground
1685         {
1686             get { return (System.Windows.Media.Color)GetValue(HilightForegroundProperty); }
1687             set { SetValue(HilightForegroundProperty, value); }
1688         }
1689
1690         /// <summary>
1691         /// ControlCharの依存プロパティを表す
1692         /// </summary>
1693         public static readonly DependencyProperty HilightForegroundProperty =
1694             DependencyProperty.Register("HilightForeground", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.White));
1695
1696         /// <summary>
1697         /// コントロールコードの文字色を表す。これは依存プロパティです
1698         /// </summary>
1699         public System.Windows.Media.Color ControlChar
1700         {
1701             get { return (System.Windows.Media.Color)GetValue(ControlCharProperty); }
1702             set { SetValue(ControlCharProperty, value); }
1703         }
1704
1705         /// <summary>
1706         /// ControlCharの依存プロパティを表す
1707         /// </summary>
1708         public static readonly DependencyProperty ControlCharProperty =
1709             DependencyProperty.Register("ControlChar", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Gray));
1710         
1711         /// <summary>
1712         /// 選択時の背景色を表す。これは依存プロパティです
1713         /// </summary>
1714         public System.Windows.Media.Color Hilight
1715         {
1716             get { return (System.Windows.Media.Color)GetValue(HilightProperty); }
1717             set { SetValue(HilightProperty, value); }
1718         }
1719
1720         /// <summary>
1721         /// Hilightの依存プロパティを表す
1722         /// </summary>
1723         public static readonly DependencyProperty HilightProperty =
1724             DependencyProperty.Register("Hilight", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.DeepSkyBlue));
1725         
1726         /// <summary>
1727         /// キーワード1の文字色を表す。これは依存プロパティです
1728         /// </summary>
1729         public System.Windows.Media.Color Keyword1
1730         {
1731             get { return (System.Windows.Media.Color)GetValue(Keyword1Property); }
1732             set { SetValue(Keyword1Property, value); }
1733         }
1734
1735         /// <summary>
1736         /// Keyword1の依存プロパティを表す
1737         /// </summary>
1738         public static readonly DependencyProperty Keyword1Property =
1739             DependencyProperty.Register("Keyword1", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Blue));
1740
1741         /// <summary>
1742         /// キーワード2の文字色を表す。これは依存プロパティです
1743         /// </summary>
1744         public System.Windows.Media.Color Keyword2
1745         {
1746             get { return (System.Windows.Media.Color)GetValue(Keyword2Property); }
1747             set { SetValue(Keyword2Property, value); }
1748         }
1749
1750         /// <summary>
1751         /// Keyword2の依存プロパティを表す
1752         /// </summary>
1753         public static readonly DependencyProperty Keyword2Property =
1754             DependencyProperty.Register("Keyword2", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.DarkCyan));
1755
1756         /// <summary>
1757         /// コメントの文字色を表す。これは依存プロパティです
1758         /// </summary>
1759         public System.Windows.Media.Color Comment
1760         {
1761             get { return (System.Windows.Media.Color)GetValue(CommentProperty); }
1762             set { SetValue(CommentProperty, value); }
1763         }
1764
1765         /// <summary>
1766         /// Commentの依存プロパティを表す
1767         /// </summary>
1768         public static readonly DependencyProperty CommentProperty =
1769             DependencyProperty.Register("Comment", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Green));
1770
1771         /// <summary>
1772         /// 文字リテラルの文字色を表す。これは依存プロパティです
1773         /// </summary>
1774         public System.Windows.Media.Color Literal
1775         {
1776             get { return (System.Windows.Media.Color)GetValue(LiteralProperty); }
1777             set { SetValue(LiteralProperty, value); }
1778         }
1779
1780         /// <summary>
1781         /// Literalの依存プロパティを表す
1782         /// </summary>
1783         public static readonly DependencyProperty LiteralProperty =
1784             DependencyProperty.Register("Literal", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Brown));
1785
1786         /// <summary>
1787         /// URLの文字色を表す。これは依存プロパティです
1788         /// </summary>
1789         public System.Windows.Media.Color URL
1790         {
1791             get { return (System.Windows.Media.Color)GetValue(URLProperty); }
1792             set { SetValue(URLProperty, value); }
1793         }
1794
1795         /// <summary>
1796         /// URLの依存プロパティを表す
1797         /// </summary>
1798         public static readonly DependencyProperty URLProperty =
1799             DependencyProperty.Register("URL", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Blue));
1800
1801
1802         /// <summary>
1803         /// ラインマーカーの色を表す
1804         /// </summary>
1805         public System.Windows.Media.Color LineMarker
1806         {
1807             get { return (System.Windows.Media.Color)GetValue(LineMarkerProperty); }
1808             set { SetValue(LineMarkerProperty, value); }
1809         }
1810
1811         /// <summary>
1812         /// LineMarkerの依存プロパティを表す
1813         /// </summary>
1814         public static readonly DependencyProperty LineMarkerProperty =
1815             DependencyProperty.Register("LineMarker", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(Colors.Silver));
1816
1817         /// <summary>
1818         /// 挿入モード時のキャレットの色を表す
1819         /// </summary>
1820         public System.Windows.Media.Color InsertCaret
1821         {
1822             get { return (System.Windows.Media.Color)GetValue(InsertCaretProperty); }
1823             set { SetValue(InsertCaretProperty, value); }
1824         }
1825
1826         /// <summary>
1827         /// InsertCaretの依存プロパティを表す
1828         /// </summary>
1829         public static readonly DependencyProperty InsertCaretProperty =
1830             DependencyProperty.Register("InsertCaret", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(SystemColors.WindowTextColor));
1831
1832         /// <summary>
1833         /// 行更新フラグの色を表す
1834         /// </summary>
1835         public System.Windows.Media.Color UpdateArea
1836         {
1837             get { return (System.Windows.Media.Color)GetValue(UpdateAreaProperty); }
1838             set { SetValue(UpdateAreaProperty, value); }
1839         }
1840
1841         /// <summary>
1842         /// UpdateAreaの依存プロパティを表す
1843         /// </summary>
1844         public static readonly DependencyProperty UpdateAreaProperty =
1845             DependencyProperty.Register("UpdateArea", typeof(System.Windows.Media.Color), typeof(FooTextBox), new PropertyMetadata(Colors.MediumSeaGreen));        
1846
1847         /// <summary>
1848         /// 上書きモード時のキャレット職を表す
1849         /// </summary>
1850         public System.Windows.Media.Color OverwriteCaret
1851         {
1852             get { return (System.Windows.Media.Color)GetValue(OverwriteCaretProperty); }
1853             set { SetValue(OverwriteCaretProperty, value); }
1854         }
1855         
1856         /// <summary>
1857         /// OverwriteCaretの依存プロパティを表す
1858         /// </summary>
1859         public static readonly DependencyProperty OverwriteCaretProperty =
1860             DependencyProperty.Register("OverwriteCaret", typeof(System.Windows.Media.Color), typeof(FooTextBox), new FrameworkPropertyMetadata(SystemColors.WindowTextColor));
1861
1862         /// <summary>
1863         /// 行番号の色を表す
1864         /// </summary>
1865         public System.Windows.Media.Color LineNumber
1866         {
1867             get { return (System.Windows.Media.Color)GetValue(LineNumberProperty); }
1868             set { SetValue(LineNumberProperty, value); }
1869         }
1870
1871         /// <summary>
1872         /// Using a DependencyProperty as the backing store for LineNumber.  This enables animation, styling, binding, etc...
1873         /// </summary>
1874         public static readonly DependencyProperty LineNumberProperty =
1875             DependencyProperty.Register("LineNumber", typeof(System.Windows.Media.Color), typeof(FooTextBox), new PropertyMetadata(Colors.DimGray));
1876
1877         /// <summary>
1878         /// 挿入モードなら真を返し、そうでないなら、偽を返す。これは依存プロパティです
1879         /// </summary>
1880         public bool InsertMode
1881         {
1882             get { return (bool)GetValue(InsertModeProperty); }
1883             set { SetValue(InsertModeProperty, value); }
1884         }
1885
1886         /// <summary>
1887         /// InsertModeの依存プロパティを表す
1888         /// </summary>
1889         public static readonly DependencyProperty InsertModeProperty =
1890             DependencyProperty.Register("InsertMode",
1891             typeof(bool),
1892             typeof(FooTextBox),
1893             new FrameworkPropertyMetadata(true));
1894
1895         /// <summary>
1896         /// タブの文字数を表す。これは依存プロパティです
1897         /// </summary>
1898         public int TabChars
1899         {
1900             get { return (int)GetValue(TabCharsProperty); }
1901             set { SetValue(TabCharsProperty, value); }
1902         }
1903
1904         /// <summary>
1905         /// TabCharsの依存プロパティを表す
1906         /// </summary>
1907         public static readonly DependencyProperty TabCharsProperty =
1908             DependencyProperty.Register("TabChars",
1909             typeof(int),
1910             typeof(FooTextBox),
1911             new FrameworkPropertyMetadata(4));
1912
1913         /// <summary>
1914         /// 矩形選択モードなら真を返し、そうでないなら偽を返す。これは依存プロパティです
1915         /// </summary>
1916         public bool RectSelectMode
1917         {
1918             get { return (bool)GetValue(RectSelectModeProperty); }
1919             set { SetValue(RectSelectModeProperty, value); }
1920         }
1921
1922         /// <summary>
1923         /// RectSelectModeの依存プロパティを表す
1924         /// </summary>
1925         public static readonly DependencyProperty RectSelectModeProperty =
1926             DependencyProperty.Register("RectSelectMode", typeof(bool), typeof(FooTextBox), new FrameworkPropertyMetadata(false));
1927
1928         /// <summary>
1929         /// 折り返しの方法を指定する
1930         /// </summary>
1931         /// <remarks>
1932         /// 変更した場合、レイアウトの再構築を行う必要があります
1933         /// </remarks>
1934         public LineBreakMethod LineBreakMethod
1935         {
1936             get { return (LineBreakMethod)GetValue(LineBreakProperty); }
1937             set { SetValue(LineBreakProperty, value); }
1938         }
1939
1940         /// <summary>
1941         /// LineBreakMethodの依存プロパティを表す
1942         /// </summary>
1943         public static readonly DependencyProperty LineBreakProperty =
1944             DependencyProperty.Register("LineBreakMethod", typeof(LineBreakMethod), typeof(FooTextBox), new PropertyMetadata(LineBreakMethod.None));
1945
1946
1947         /// <summary>
1948         /// 折り返しの幅を指定する。LineBreakMethod.CharUnit以外の時は無視されます
1949         /// </summary>
1950         /// <remarks>
1951         /// 変更した場合、レイアウトの再構築を行う必要があります
1952         /// </remarks>
1953         public int LineBreakCharCount
1954         {
1955             get { return (int)GetValue(LineBreakCharCountProperty); }
1956             set { SetValue(LineBreakCharCountProperty, value); }
1957         }
1958
1959         /// <summary>
1960         /// LineBreakCharCountの依存プロパティを表す
1961         /// </summary>
1962         public static readonly DependencyProperty LineBreakCharCountProperty =
1963             DependencyProperty.Register("LineBreakCharCount", typeof(int), typeof(FooTextBox), new PropertyMetadata(80));
1964
1965         /// <summary>
1966         /// キャレットを描くなら真。そうでないなら偽を返す。これは依存プロパティです
1967         /// </summary>
1968         public bool DrawCaret
1969         {
1970             get { return (bool)GetValue(DrawCaretProperty); }
1971             set { SetValue(DrawCaretProperty, value); }
1972         }
1973
1974         /// <summary>
1975         /// DrawCaretの依存プロパティを表す
1976         /// </summary>
1977         public static readonly DependencyProperty DrawCaretProperty =
1978             DependencyProperty.Register("DrawCaret", typeof(bool), typeof(FooTextBox), new FrameworkPropertyMetadata(true));
1979
1980         
1981         /// <summary>
1982         /// キャレットラインを描くなら真。そうでないなら偽を返す。これは依存プロパティです
1983         /// </summary>
1984         public bool DrawCaretLine
1985         {
1986             get { return (bool)GetValue(DrawCaretLineProperty); }
1987             set { SetValue(DrawCaretLineProperty, value); }
1988         }
1989
1990         /// <summary>
1991         /// DrawCaretLineの依存プロパティを表す
1992         /// </summary>
1993         public static readonly DependencyProperty DrawCaretLineProperty =
1994             DependencyProperty.Register("DrawCaretLine", typeof(bool), typeof(FooTextBox), new FrameworkPropertyMetadata(false));
1995
1996         /// <summary>
1997         /// 行番号を描くなら真。そうでなければ偽。これは依存プロパティです
1998         /// </summary>
1999         public bool DrawLineNumber
2000         {
2001             get { return (bool)GetValue(DrawLineNumberProperty); }
2002             set { SetValue(DrawLineNumberProperty, value); }
2003         }
2004
2005         /// <summary>
2006         /// ルーラーを描くなら真。そうでなければ偽。これは依存プロパティです
2007         /// </summary>
2008         public bool DrawRuler
2009         {
2010             get { return (bool)GetValue(DrawRulerProperty); }
2011             set { SetValue(DrawRulerProperty, value); }
2012         }
2013
2014         /// <summary>
2015         /// DrawRulerの依存プロパティを表す
2016         /// </summary>
2017         public static readonly DependencyProperty DrawRulerProperty =
2018             DependencyProperty.Register("DrawRuler", typeof(bool), typeof(FooTextBox), new PropertyMetadata(false));
2019
2020         
2021         /// <summary>
2022         /// DrawLineNumberの依存プロパティを表す
2023         /// </summary>
2024         public static readonly DependencyProperty DrawLineNumberProperty =
2025             DependencyProperty.Register("DrawLineNumber", typeof(bool), typeof(FooTextBox), new FrameworkPropertyMetadata(false));
2026
2027         /// <summary>
2028         /// URLに下線を引くなら真。そうでないなら偽を表す。これは依存プロパティです
2029         /// </summary>
2030         public bool MarkURL
2031         {
2032             get { return (bool)GetValue(MarkURLProperty); }
2033             set { SetValue(MarkURLProperty, value); }
2034         }
2035
2036         /// <summary>
2037         /// MarkURLの依存プロパティを表す
2038         /// </summary>
2039         public static readonly DependencyProperty MarkURLProperty =
2040             DependencyProperty.Register("MarkURL", typeof(bool), typeof(FooTextBox), new FrameworkPropertyMetadata(false));
2041
2042         /// <summary>
2043         /// 全角スペースを表示するなら真。そうでないなら偽
2044         /// </summary>
2045         public bool ShowFullSpace
2046         {
2047             get { return (bool)GetValue(ShowFullSpaceProperty); }
2048             set { SetValue(ShowFullSpaceProperty, value); }
2049         }
2050
2051         /// <summary>
2052         /// ShowFullSpaceの依存プロパティを表す
2053         /// </summary>
2054         public static readonly DependencyProperty ShowFullSpaceProperty =
2055             DependencyProperty.Register("ShowFullSpace", typeof(bool), typeof(FooTextBox), new UIPropertyMetadata(false));
2056
2057         /// <summary>
2058         /// 半角スペースを表示するなら真。そうでないなら偽
2059         /// </summary>
2060         public bool ShowHalfSpace
2061         {
2062             get { return (bool)GetValue(ShowHalfSpaceProperty); }
2063             set { SetValue(ShowHalfSpaceProperty, value); }
2064         }
2065
2066         /// <summary>
2067         /// ShowHalfSpaceの依存プロパティを表す
2068         /// </summary>
2069         public static readonly DependencyProperty ShowHalfSpaceProperty =
2070             DependencyProperty.Register("ShowHalfSpace", typeof(bool), typeof(FooTextBox), new UIPropertyMetadata(false));
2071
2072         /// <summary>
2073         /// タブを表示するなら真。そうでないなら偽
2074         /// </summary>
2075         public bool ShowTab
2076         {
2077             get { return (bool)GetValue(ShowTabProperty); }
2078             set { SetValue(ShowTabProperty, value); }
2079         }
2080
2081         /// <summary>
2082         /// ShowTabの依存プロパティを表す
2083         /// </summary>
2084         public static readonly DependencyProperty ShowTabProperty =
2085             DependencyProperty.Register("ShowTab", typeof(bool), typeof(FooTextBox), new UIPropertyMetadata(false));
2086
2087         /// <summary>
2088         /// 改行マークを表示するなら真。そうでないなら偽
2089         /// </summary>
2090         public bool ShowLineBreak
2091         {
2092             get { return (bool)GetValue(ShowLineBreakProperty); }
2093             set { SetValue(ShowLineBreakProperty, value); }
2094         }
2095
2096         /// <summary>
2097         /// ShowLineBreakの依存プロパティを表す
2098         /// </summary>
2099         public static readonly DependencyProperty ShowLineBreakProperty =
2100             DependencyProperty.Register("ShowLineBreak", typeof(bool), typeof(FooTextBox), new PropertyMetadata(false));
2101         
2102         #endregion
2103     }
2104     /// <summary>
2105     /// マウスボタン関連のイベントクラス
2106     /// </summary>
2107     public sealed class FooMouseButtonEventArgs : MouseButtonEventArgs
2108     {
2109         /// <summary>
2110         /// イベントが発生したドキュメントのインデックス
2111         /// </summary>
2112         public int Index
2113         {
2114             get;
2115             private set;
2116         }
2117
2118         /// <summary>
2119         /// コンストラクター
2120         /// </summary>
2121         /// <param name="mouse">マウスデバイス</param>
2122         /// <param name="timestamp">タイムスタンプ</param>
2123         /// <param name="button">ボタン</param>
2124         /// <param name="stylusDevice">スタイラスデバイス</param>
2125         /// <param name="index">インデックス</param>
2126         public FooMouseButtonEventArgs(MouseDevice mouse, int timestamp, MouseButton button, StylusDevice stylusDevice, int index)
2127             : base(mouse, timestamp, button, stylusDevice)
2128         {
2129             this.Index = index;
2130         }
2131     }
2132     /// <summary>
2133     /// マウス関連のイベントクラス
2134     /// </summary>
2135     public sealed class FooMouseEventArgs : MouseEventArgs
2136     {
2137         /// <summary>
2138         /// イベントが発生したドキュメントのインデックス
2139         /// </summary>
2140         public int Index
2141         {
2142             get;
2143             private set;
2144         }
2145
2146         /// <summary>
2147         /// コンストラクター
2148         /// </summary>
2149         /// <param name="mouse">マウスデバイス</param>
2150         /// <param name="timestamp">タイムスタンプ</param>
2151         /// <param name="stylusDevice">スタイラスデバイス</param>
2152         /// <param name="index">インデックス</param>
2153         public FooMouseEventArgs(MouseDevice mouse,
2154             int timestamp,
2155             StylusDevice stylusDevice,
2156             int index)
2157             : base(mouse, timestamp, stylusDevice)
2158         {
2159             this.Index = index;
2160         }
2161     }
2162 }