OSDN Git Service

ナレーターと単語単位の選択のロジックが似ていたのでまとめた
[fooeditengine/FooEditEngine.git] / Core / Document.cs
index cfbdb60..9c5932f 100644 (file)
@@ -9,8 +9,6 @@
 You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
 
-//#define TEST_ASYNC
-
 using System;
 using System.IO;
 using System.ComponentModel;
@@ -25,6 +23,13 @@ using System.Runtime.CompilerServices;
 namespace FooEditEngine
 {
     /// <summary>
+    /// オートインデントを行うためのデリゲートを表す
+    /// </summary>
+    /// <param name="sender">イベント発生元のオブジェクト</param>
+    /// <param name="e">イベントデーター</param>
+    public delegate void AutoIndentHookerHandler(object sender, EventArgs e);
+
+    /// <summary>
     /// 進行状況を表す列挙体
     /// </summary>
     public enum ProgressState
@@ -77,6 +82,10 @@ namespace FooEditEngine
         /// ドキュメント全体が削除されたことを表す
         /// </summary>
         Clear,
+        /// <summary>
+        /// レイアウトが再構築されたことを表す
+        /// </summary>
+        RebuildLayout,
     }
 
     /// <summary>
@@ -137,15 +146,13 @@ namespace FooEditEngine
     /// ドキュメントの管理を行う
     /// </summary>
     /// <remarks>この型のすべてのメソッド・プロパティはスレッドセーフです</remarks>
-    public sealed class Document : IEnumerable<char>, IRandomEnumrator<char>
+    public sealed class Document : IEnumerable<char>, IRandomEnumrator<char>, IDisposable
     {
-        const int MaxSemaphoreCount = 1;
         Regex regex;
         Match match;
         StringBuffer buffer;
         LineToIndexTable _LayoutLines;
         bool _EnableFireUpdateEvent = true,_UrlMark = false, _DrawLineNumber = false, _HideRuler = true, _RightToLeft = false;
-        SemaphoreSlim Semaphore = new SemaphoreSlim(MaxSemaphoreCount);
         LineBreakMethod _LineBreak;
         int _TabStops, _LineBreakCharCount = 80;
         bool _ShowFullSpace, _ShowHalfSpace, _ShowTab, _ShowLineBreak,_InsertMode, _HideCaret, _HideLineMarker, _RectSelection;
@@ -176,7 +183,6 @@ namespace FooEditEngine
             else
                 this.buffer = new StringBuffer(doc.buffer);
             this.buffer.Update = new DocumentUpdateEventHandler(buffer_Update);
-            this.UpdateCalledAlways += (s, e) => { };
             this.Update += new DocumentUpdateEventHandler((s, e) => { });
             this.ChangeFireUpdateEvent += new EventHandler((s, e) => { });
             this.StatusUpdate += new EventHandler((s, e) => { });
@@ -194,6 +200,10 @@ namespace FooEditEngine
             this.HideLineMarker = true;
             this.SelectGrippers = new GripperRectangle(new Gripper(), new Gripper());
             this.SelectionChanged += new EventHandler((s, e) => { });
+            this.CaretChanged += (s, e) => { };
+            this.AutoIndentHook += (s, e) => { };
+            this.LineBreakChanged += (s, e) => { };
+            this.Dirty = false;
         }
 
         void WacthDogPattern_Updated(object sender, EventArgs e)
@@ -202,6 +212,15 @@ namespace FooEditEngine
         }
 
         /// <summary>
+        /// ダーティフラグ。保存されていなければ真、そうでなければ偽。
+        /// </summary>
+        public bool Dirty
+        {
+            get;
+            set;
+        }
+
+        /// <summary>
         /// キャレットでの選択の起点となる位置
         /// </summary>
         internal int AnchorIndex
@@ -229,6 +248,34 @@ namespace FooEditEngine
         }
 
         /// <summary>
+        /// 補完候補プロセッサーが切り替わったときに発生するイベント
+        /// </summary>
+        public event EventHandler AutoCompleteChanged;
+
+        AutoCompleteBoxBase _AutoComplete;
+        /// <summary>
+        /// 補完候補プロセッサー
+        /// </summary>
+        public AutoCompleteBoxBase AutoComplete
+        {
+            get
+            {
+                return this._AutoComplete;
+            }
+            set
+            {
+                this._AutoComplete = value;
+                if (this.AutoCompleteChanged != null)
+                    this.AutoCompleteChanged(this, null);
+            }
+        }
+
+        /// <summary>
+        /// 読み込み中に発生するイベント
+        /// </summary>
+        public event ProgressEventHandler LoadProgress;
+
+        /// <summary>
         /// ルーラーやキャレット・行番号などの表示すべきものが変化した場合に呼び出される。ドキュメントの内容が変化した通知を受け取り場合はUpdateを使用してください
         /// </summary>
         public event EventHandler StatusUpdate;
@@ -412,14 +459,30 @@ namespace FooEditEngine
             }
         }
 
+        TextPoint _CaretPostion;
         /// <summary>
         /// レイアウト行のどこにキャレットがあるかを表す
         /// </summary>
-        /// <remarks>この値を変更しても反映されないので、EditView側でAdjustCaret()メソッドを呼び出す必要があります</remarks>
         public TextPoint CaretPostion
         {
-            get;
-            set;
+            get
+            {
+                return this._CaretPostion;
+            }
+            set
+            {
+                if(this._CaretPostion != value)
+                {
+                    this._CaretPostion = value;
+                    this.CaretChanged(this, null);
+                }
+            }
+        }
+
+        internal void SetCaretPostionWithoutEvent(TextPoint value)
+        {
+            if (this._CaretPostion != value)
+                this._CaretPostion = value;
         }
 
         /// <summary>
@@ -591,14 +654,6 @@ namespace FooEditEngine
         public event DocumentUpdateEventHandler Update;
 
         /// <summary>
-        /// ドキュメントが更新された時に呼びされるイベント
-        /// </summary>
-        /// <remarks>
-        /// FireUpdateEventの値に関わらず常に呼びされます
-        /// </remarks>
-        internal event DocumentUpdateEventHandler UpdateCalledAlways;
-
-        /// <summary>
         /// FireUpdateEventの値が変わったときに呼び出されるイベント
         /// </summary>
         public event EventHandler ChangeFireUpdateEvent;
@@ -614,17 +669,6 @@ namespace FooEditEngine
         public const char EndOfFile = '\u001a';
 
         /// <summary>
-        /// ロック中なら真を返し、そうでないなら偽を返す
-        /// </summary>
-        public bool IsLocked
-        {
-            get
-            {
-                return this.Semaphore.CurrentCount == 0;
-            }
-        }
-
-        /// <summary>
         /// アンドゥ管理クラスを表す
         /// </summary>
         public UndoManager UndoManager
@@ -691,11 +735,53 @@ namespace FooEditEngine
         }
 
         /// <summary>
+        /// 再描写を要求しているなら真
+        /// </summary>
+        public bool IsRequestRedraw { get; internal set; }
+
+        /// <summary>
+        /// 再描写を要求する
+        /// </summary>
+        public void RequestRedraw()
+        {
+            this.IsRequestRedraw = true;
+        }
+
+        /// <summary>
+        /// レイアウト行が再構成されたときに発生するイベント
+        /// </summary>
+        public event EventHandler PerformLayouted;
+        /// <summary>
+        /// レイアウト行をすべて破棄し、再度レイアウトを行う
+        /// </summary>
+        public void PerformLayout()
+        {
+            this.LayoutLines.IsFrozneDirtyFlag = true;
+            this.FireUpdate(new DocumentUpdateEventArgs(UpdateType.RebuildLayout, -1, -1, -1));
+            this.LayoutLines.IsFrozneDirtyFlag = false;
+            if (this.PerformLayouted != null)
+                this.PerformLayouted(this, null);
+        }
+
+        /// <summary>
+        /// オードインデントが可能になった時に通知される
+        /// </summary>
+        /// <remarks>
+        /// FireUpdateEventの影響を受けます
+        /// </remarks>
+        public event AutoIndentHookerHandler AutoIndentHook;
+
+        /// <summary>
         /// 選択領域変更時に通知される
         /// </summary>
         public event EventHandler SelectionChanged;
 
         /// <summary>
+        /// キャレット移動時に通知される
+        /// </summary>
+        public event EventHandler CaretChanged;
+
+        /// <summary>
         /// 指定された範囲を選択する
         /// </summary>
         /// <param name="start"></param>
@@ -707,6 +793,9 @@ namespace FooEditEngine
                 throw new InvalidOperationException("");
             if (start < 0 || start + length < 0 || start + length > this.Length)
                 throw new ArgumentOutOfRangeException("startかendが指定できる範囲を超えてます");
+            //選択範囲が消されたとき
+            foreach (Selection sel in this.Selections)
+                this.LayoutLines.ClearLayoutCache(sel.start, sel.length);
             this.Selections.Clear();
             if (length < 0)
             {
@@ -719,10 +808,12 @@ namespace FooEditEngine
                 TextPoint startTextPoint = this.LayoutLines.GetTextPointFromIndex(start);
                 TextPoint endTextPoint = this.LayoutLines.GetTextPointFromIndex(start + length);
                 this.SelectByRectangle(new TextRectangle(startTextPoint, endTextPoint));
+                this.LayoutLines.ClearLayoutCache(start, length);
             }
             else if (length != 0)
             {
                 this.Selections.Add(Selection.Create(start, length));
+                this.LayoutLines.ClearLayoutCache(start, length);
             }
             this.SelectionChanged(this, null);
         }
@@ -789,25 +880,71 @@ namespace FooEditEngine
         /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
         public void SelectWord(int index, bool changeAnchor = false)
         {
-            if (this.FireUpdateEvent == false)
-                throw new InvalidOperationException("");
+            this.SelectSepartor(index, (c) => Util.IsWordSeparator(c), changeAnchor);
+        }
+
+        /// <summary>
+        /// 行単位で選択する
+        /// </summary>
+        /// <param name="index">探索を開始するインデックス</param>
+        /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
+        public void SelectLine(int index,bool changeAnchor = false)
+        {
+            this.SelectSepartor(index, (c) => c == Document.NewLine, changeAnchor);
+        }
+
+        /// <summary>
+        /// セパレーターで区切られた領域を取得する
+        /// </summary>
+        /// <param name="index">探索を開始するインデックス</param>
+        /// <param name="find_sep_func">セパレーターなら真を返し、そうでないなら偽を返す</param>
+        /// <returns>開始インデックス、終了インデックス</returns>
+        public Tuple<int,int> GetSepartor(int index, Func<char, bool> find_sep_func)
+        {
+            if (find_sep_func == null)
+                throw new ArgumentNullException("find_sep_func must not be null");
 
             if (this.Length <= 0 || index >= this.Length)
-                return;
+                return null;
 
             Document str = this;
 
             int start = index;
-            while (start > 0 && !Util.IsWordSeparator(str[start]))
+            while (start > 0 && !find_sep_func(str[start]))
                 start--;
 
-            if (Util.IsWordSeparator(str[start]))
+            if (find_sep_func(str[start]))
+            {
                 start++;
+            }
 
             int end = index;
-            while (end < this.Length && !Util.IsWordSeparator(str[end]))
+            while (end < this.Length && !find_sep_func(str[end]))
                 end++;
 
+            return new Tuple<int, int>(start, end);
+        }
+
+        /// <summary>
+        /// セパレーターで囲まれた範囲内を選択する
+        /// </summary>
+        /// <param name="index">探索を開始するインデックス</param>
+        /// <param name="find_sep_func">セパレーターなら真を返し、そうでないなら偽を返す</param>
+        /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
+        public void SelectSepartor(int index,Func<char,bool> find_sep_func, bool changeAnchor = false)
+        {
+            if (this.FireUpdateEvent == false)
+                throw new InvalidOperationException("");
+
+            if (find_sep_func == null)
+                throw new ArgumentNullException("find_sep_func must not be null");
+
+            var t = this.GetSepartor(index, find_sep_func);
+            if (t == null)
+                return;
+
+            int start = t.Item1, end = t.Item2;
+
             this.Select(start, end - start);
 
             if (changeAnchor)
@@ -824,31 +961,6 @@ namespace FooEditEngine
         }
 
         /// <summary>
-        /// ロックを解除します
-        /// </summary>
-        public void UnLock()
-        {
-            this.Semaphore.Release();
-        }
-
-        /// <summary>
-        /// ロックします
-        /// </summary>
-        public void Lock()
-        {
-            this.Semaphore.Wait();
-        }
-
-        /// <summary>
-        /// ロックします
-        /// </summary>
-        /// <returns>Taskオブジェクト</returns>
-        public Task LockAsync()
-        {
-            return this.Semaphore.WaitAsync();
-        }
-
-        /// <summary>
         /// マーカーを設定する
         /// </summary>
         /// <param name="id">マーカーID</param>
@@ -984,8 +1096,9 @@ namespace FooEditEngine
         /// <param name="index">開始インデックス</param>
         /// <param name="length">長さ</param>
         /// <param name="s">文字列</param>
+        /// <param name="UserInput">ユーザーからの入力として扱うなら真</param>
         /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
-        public void Replace(int index, int length, string s)
+        public void Replace(int index, int length, string s, bool UserInput = false)
         {
             if (index < 0 || index > this.buffer.Length || index + length > this.buffer.Length || length < 0)
                 throw new ArgumentOutOfRangeException();
@@ -998,6 +1111,20 @@ namespace FooEditEngine
             ReplaceCommand cmd = new ReplaceCommand(this.buffer, index, length, s);
             this.UndoManager.push(cmd);
             cmd.redo();
+
+            if (this.FireUpdateEvent && UserInput)
+            {
+                var input_str = string.Empty;
+                if (s == Document.NewLine.ToString())
+                    input_str = s;
+                else if (s == string.Empty && length > 0)
+                    input_str = "\b";
+                //入力は終わっているので空文字を渡すが処理の都合で一部文字だけはそのまま渡す
+                if (this.AutoComplete != null)
+                    this.AutoComplete.ParseInput(input_str);
+                if (s == Document.NewLine.ToString())
+                    this.AutoIndentHook(this, null);
+            }
         }
 
         /// <summary>
@@ -1008,6 +1135,7 @@ namespace FooEditEngine
         public void Clear()
         {
             this.buffer.Clear();
+            this.Dirty = false;
         }
 
         /// <summary>
@@ -1020,25 +1148,24 @@ namespace FooEditEngine
         /// 読み取り操作は別スレッドで行われます。
         /// また、非同期操作中はこのメソッドを実行することはできません。
         /// </remarks>
-        internal async Task LoadAsync(IStreamReader fs, CancellationTokenSource tokenSource = null)
+        public async Task LoadAsync(TextReader fs, CancellationTokenSource tokenSource = null)
         {
-            if (fs.IsEnd())
+            if (fs.Peek() == -1)
                 return;
 
+            if (this.LoadProgress != null)
+                this.LoadProgress(this, new ProgressEventArgs(ProgressState.Start));
+
             try
             {
-                await this.LockAsync().ConfigureAwait(false);
                 this.Clear();
-                this.FireUpdateEvent = false;
-                this.LayoutLines.IsFrozneDirtyFlag = true;
                 await this.buffer.LoadAsync(fs, tokenSource);
             }
             finally
             {
-                this.FireUpdateEvent = true;
-                //これ以降の操作にだけダーティフラグを適用しないとおかしなことになる
-                this.LayoutLines.IsFrozneDirtyFlag = false;
-                this.UnLock();
+                this.PerformLayout();
+                if (this.LoadProgress != null)
+                    this.LoadProgress(this, new ProgressEventArgs(ProgressState.Complete));
             }
         }
 
@@ -1049,34 +1176,9 @@ namespace FooEditEngine
         /// <param name="tokenSource">キャンセルトークン</param>
         /// <returns>Taskオブジェクト</returns>
         /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
-        internal async Task SaveAsync(IStreamWriter fs, CancellationTokenSource tokenSource = null)
+        public async Task SaveAsync(TextWriter fs, CancellationTokenSource tokenSource = null)
         {
-            try
-            {
-                await this.LockAsync().ConfigureAwait(false);
-                StringBuilder line = new StringBuilder();
-                for (int i = 0; i < this.Length; i++)
-                {
-                    char c = this[i];
-                    line.Append(c);
-                    if (c == Document.NewLine || i == this.Length - 1)
-                    {
-                        string str = line.ToString();
-                        str = str.Replace(Document.NewLine.ToString(), fs.NewLine);
-                        await fs.WriteAsync(str).ConfigureAwait(false);
-                        line.Clear();
-                        if (tokenSource != null)
-                            tokenSource.Token.ThrowIfCancellationRequested();
-#if TEST_ASYNC
-                    System.Threading.Thread.Sleep(10);
-#endif
-                    }
-                }
-            }
-            finally
-            {
-                this.UnLock();
-            }
+            await this.buffer.SaveAsync(fs, tokenSource);
         }
 
         /// <summary>
@@ -1224,6 +1326,10 @@ namespace FooEditEngine
         {
             switch (e.type)
             {
+                case UpdateType.RebuildLayout:
+                    this._LayoutLines.Clear();
+                    this._LayoutLines.UpdateAsReplace(0, 0, this.Length);
+                    break;
                 case UpdateType.Replace:
                     if (e.row == null)
                     {
@@ -1235,59 +1341,42 @@ namespace FooEditEngine
                         this._LayoutLines.UpdateLineAsReplace(e.row.Value, e.removeLength, e.insertLength);
                         this.Markers.UpdateMarkers(this.LayoutLines.GetIndexFromLineNumber(e.row.Value), e.insertLength, e.removeLength);
                     }
+                    this.Dirty = true;
                     break;
                 case UpdateType.Clear:
                     this._LayoutLines.Clear();
+                    this.Dirty = true;
                     break;
             }
-            this.UpdateCalledAlways(this, e);
             if(this.FireUpdateEvent)
                 this.Update(this, e);
         }
-    }
 
-    /// <summary>
-    /// IStreamReaderインターフェイス
-    /// </summary>
-    public interface IStreamReader
-    {
-        /// <summary>
-        /// ストリームが空かどうかを返す
-        /// </summary>
-        bool IsEnd();
+        #region IDisposable Support
+        private bool disposedValue = false; // 重複する呼び出しを検出するには
 
-        /// <summary>
-        /// ストリームから行を読み取った物を返す。LoadAsyncを呼び出す場合は必ず実装してください
-        /// </summary>
-        Task<string> ReadLineAsync();
-        /// <summary>
-        /// ストリームから指定した文字数だけ読み取る
-        /// </summary>
-        /// <param name="buffer">書き込み先バッファー</param>
-        /// <param name="index">書き込み先バッファーのインデックス</param>
-        /// <param name="count">読み取る文字数</param>
-        /// <returns>読み取った文字数</returns>
-        Task<int> ReadAsync(char[] buffer, int index, int count);
-    }
+        void Dispose(bool disposing)
+        {
+            if (!disposedValue)
+            {
+                if (disposing)
+                {
+                    this.buffer.Clear();
+                    this.LayoutLines.Clear();
+                }
 
-    /// <summary>
-    /// IStreamWriter
-    /// </summary>
-    public interface IStreamWriter
-    {
-        /// <summary>
-        /// ストリームに書き込む。SaveAsyncを呼び出す場合は必ず実装してください
-        /// </summary>
-        Task WriteAsync(string str);
+                disposedValue = true;
+            }
+        }
 
         /// <summary>
-        /// 書き込む際に使用する改行コード
+        /// ドキュメントを破棄する
         /// </summary>
-        string NewLine
+        public void Dispose()
         {
-            get;
-            set;
+            Dispose(true);
         }
+        #endregion
     }
 
     /// <summary>