├── .gitignore ├── LICENSE ├── README.md ├── images ├── collectionoverview.png ├── detach.png ├── readonlywrapper.png └── syncCollections.png ├── pack.cmd └── src ├── StatefulModel.sln └── StatefulModel ├── AnonymousComparer.cs ├── AnonymousDisposable.cs ├── AnonymousSynchronizationContext.cs ├── Collections ├── FilteredObservableCollection.cs ├── ISynchronizableNotifyChangedCollection.cs ├── NotifyChangedCollection.cs ├── ObservableSynchronizedCollection.cs ├── ReadOnlyNotifyChangedCollection.cs ├── SortedObservableCollection.cs ├── SynchronizationContextCollection.cs └── Synchronizer.cs ├── EventListeners ├── AnonymousCollectionChangedEventHandlerBag.cs ├── AnonymousPropertyChangedEventHandlerBag.cs ├── CollectionChangedEventListener.cs ├── EventListener.cs ├── PropertyChangedEventListener.cs └── WeakEvents │ ├── CollectionChangedWeakEventListener.cs │ ├── PropertyChangedWeakEventListener.cs │ └── WeakEventListener.cs ├── MultipleDisposable.cs ├── Properties └── AssemblyInfo.cs ├── StatefulModel.csproj └── StatefulModel.nuspec /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studo 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # Uncomment if necessary however generally it will be regenerated when needed 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | *.[Cc]ache 155 | ClientBin/ 156 | [Ss]tyle[Cc]op.* 157 | ~$* 158 | *~ 159 | *.dbmdl 160 | *.dbproj.schemaview 161 | *.pfx 162 | *.publishsettings 163 | node_modules/ 164 | bower_components/ 165 | 166 | # RIA/Silverlight projects 167 | Generated_Code/ 168 | 169 | # Backup & report files from converting an old project file 170 | # to a newer Visual Studio version. Backup files are not needed, 171 | # because we have git ;-) 172 | _UpgradeReport_Files/ 173 | Backup*/ 174 | UpgradeLog*.XML 175 | UpgradeLog*.htm 176 | 177 | # SQL Server files 178 | *.mdf 179 | *.ldf 180 | 181 | # Business Intelligence projects 182 | *.rdl.data 183 | *.bim.layout 184 | *.bim_*.settings 185 | 186 | # Microsoft Fakes 187 | FakesAssemblies/ 188 | 189 | # Node.js Tools for Visual Studio 190 | .ntvs_analysis.dat 191 | 192 | # Visual Studio 6 build log 193 | *.plg 194 | 195 | # Visual Studio 6 workspace options file 196 | *.opt 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Masanori Onoue 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StatefulModel 2 | these classes are frequent use of stateful Models for M-V-Whatever. 3 | PCL(Portable Class Library) & MIT License. 4 | 5 | supported 6 | - .NET Framework 4.5 7 | - Windows 8 8 | - Windows Phone Silverlight 8 9 | - Xamarin.Android 10 | - Xamarin.iOS 11 | - Xamarin.iOS(Classic) 12 | 13 | ## License 14 | MIT License. 15 | 16 | ## NotifyCollections 17 | 18 | the classes that implement ISynchronizableNotifyChangedCollection < T > have ToSyncedXXX Methods (XXX ... any ISynchronizableNotifyChangedCollection < T >). 19 | 20 | ToSyncedXXX Methods is creating one-way synchronized collection with source collection. 21 | 22 | ![image](./images/collectionoverview.png) 23 | ![image](./images/readonlywrapper.png) 24 | 25 | ###Simple Usage 26 | ```csharp 27 | 28 | //thread-safe collection 29 | var source = new ObservableSynchronizedCollection(Enumerable.Range(1,3)); 30 | // sorted collection 31 | var sortedSource = new SortedObservableCollection(Enumerable.Range(1,4),i => i); 32 | //UI thread 33 | var context = new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher); 34 | //SynchronizationContext(send) bouded collection. 35 | var dispatcherSource = new SynchronizationContextCollection(Enumerable.Range(1,5),context); 36 | 37 | ``` 38 | 39 | ### Sync Collections 40 | While creating one-way synchronized collection, this method lock source collection, so no leak items. 41 | ![image](./images/syncCollections.png) 42 | ### Detach 43 | ISynchronizableNotifyChangedCollection < T > is IDisposable. When Dispose() called , all EventHandler from source collection will be detached. 44 | ![image](./images/detach.png) 45 | 46 | ## EventListeners 47 | 48 | PropertyChangedEventListener/CollectionChangedEventListener 49 | ```csharp 50 | //use collection initializer 51 | var listener = new PropertyChangedEventListener(NotifyObject) 52 | { 53 | {"Property1", (sender,e) => Hoge()}, 54 | {"Property2", (semder,e) => Huge()} 55 | }; 56 | 57 | listener.RegisterHandler((sender,e) => Hage()); 58 | listerer.RegisterHandler("Property3",(semder,e) => Fuga()); 59 | 60 | //when dispose() called, detach all handler 61 | listerner.Dispose(); 62 | ``` 63 | ### WeakEventListeners 64 | 65 | - PropertyChangedWeakEventListener (PropertyChangedEventListener by weak event) 66 | - CollectionChangedWeakEventListener (CollectionChangedWeakEventListener by weak event) 67 | - WeakEventListener (all‐purpose weak event listener) 68 | 69 | ```csharp 70 | 71 | var button = new Button(){Width = 100,Height = 100}; 72 | 73 | var weakListener = new WeakEventListener( 74 | h => new RoutedEventHandler(h), 75 | h => button.Click += h, 76 | h => button.Click -= h, 77 | (sender,e) => button.Content = "Clicked!!"); 78 | 79 | ``` 80 | ### Anonymouses 81 | 82 | - AnonymousComparer < T > 83 | - AnonymousDisposable 84 | - AnonymousSynchronizationContext 85 | etc 86 | 87 | ## Other Classes 88 | 89 | - CompositeDiposable - Rx like CompositeDisposable 90 | etc 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /images/collectionoverview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugaya40/StatefulModel/35fb62f29f3d32779425ea9143a110e77b78f298/images/collectionoverview.png -------------------------------------------------------------------------------- /images/detach.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugaya40/StatefulModel/35fb62f29f3d32779425ea9143a110e77b78f298/images/detach.png -------------------------------------------------------------------------------- /images/readonlywrapper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugaya40/StatefulModel/35fb62f29f3d32779425ea9143a110e77b78f298/images/readonlywrapper.png -------------------------------------------------------------------------------- /images/syncCollections.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ugaya40/StatefulModel/35fb62f29f3d32779425ea9143a110e77b78f298/images/syncCollections.png -------------------------------------------------------------------------------- /pack.cmd: -------------------------------------------------------------------------------- 1 | nuget pack .\src\StatefulModel\StatefulModel.csproj -Properties Configuration=Release 2 | -------------------------------------------------------------------------------- /src/StatefulModel.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StatefulModel", "StatefulModel\StatefulModel.csproj", "{87039EA4-0330-46CE-A4CE-B59584C52BBB}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x86 = Debug|x86 12 | Release|Any CPU = Release|Any CPU 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Debug|x86.ActiveCfg = Debug|Any CPU 19 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Debug|x86.Build.0 = Debug|Any CPU 20 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Release|x86.ActiveCfg = Release|Any CPU 23 | {87039EA4-0330-46CE-A4CE-B59584C52BBB}.Release|x86.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /src/StatefulModel/AnonymousComparer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace StatefulModel 5 | { 6 | public class AnonymousComparer : IComparer 7 | { 8 | private readonly Func _comparer; 9 | public AnonymousComparer(Func comparer) 10 | { 11 | _comparer = comparer; 12 | } 13 | 14 | public int Compare(T x, T y) 15 | { 16 | return _comparer(x, y); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/StatefulModel/AnonymousDisposable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StatefulModel 4 | { 5 | public class AnonymousDisposable : IDisposable 6 | { 7 | private readonly Action _releaseAction; 8 | private bool _disposed; 9 | 10 | public AnonymousDisposable(Action releaseAction) 11 | { 12 | _releaseAction = releaseAction; 13 | } 14 | 15 | public void Dispose() 16 | { 17 | Dispose(true); 18 | GC.SuppressFinalize(this); 19 | } 20 | 21 | protected virtual void Dispose(bool disposing) 22 | { 23 | if (_disposed) return; 24 | 25 | if (disposing) 26 | { 27 | _releaseAction(); 28 | } 29 | _disposed = true; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/StatefulModel/AnonymousSynchronizationContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace StatefulModel 5 | { 6 | public class AnonymousSynchronizationContext : SynchronizationContext 7 | { 8 | private Action _syncCallback; 9 | private Action _asyncCallback; 10 | 11 | private AnonymousSynchronizationContext() { } 12 | 13 | public static AnonymousSynchronizationContext CreateForSync(Action callback) 14 | { 15 | return Create(callback, null); 16 | } 17 | 18 | public static AnonymousSynchronizationContext CreateForAsync(Action callback) 19 | { 20 | return Create(null, callback); 21 | } 22 | 23 | public static AnonymousSynchronizationContext Create(Action syncCallback, Action asyncCallback) 24 | { 25 | var result = new AnonymousSynchronizationContext 26 | { 27 | _syncCallback = syncCallback, 28 | _asyncCallback = asyncCallback 29 | }; 30 | return result; 31 | } 32 | 33 | public override void Send(SendOrPostCallback d, object state) 34 | { 35 | if(_syncCallback != null) 36 | { 37 | _syncCallback(d); 38 | return; 39 | } 40 | 41 | base.Send(d, state); 42 | } 43 | 44 | public override void Post(SendOrPostCallback d, object state) 45 | { 46 | if (_asyncCallback != null) 47 | { 48 | _asyncCallback(d); 49 | return; 50 | } 51 | 52 | base.Post(d, state); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/FilteredObservableCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace StatefulModel.Collections 9 | { 10 | public sealed class FilteredObservableCollection : NotifyChangedCollection, ISynchronizableNotifyChangedCollection 11 | { 12 | public FilteredObservableCollection(Func filter) : this(Enumerable.Empty(), filter) { } 13 | 14 | public FilteredObservableCollection(IEnumerable collection, Func filter) : base(collection) 15 | { 16 | if (collection == null) throw new ArgumentNullException(nameof(collection)); 17 | if (filter == null) throw new ArgumentNullException(nameof(filter)); 18 | Synchronizer = new Synchronizer(this); 19 | Filter = filter; 20 | } 21 | 22 | public Func Filter { get; set; } 23 | public Synchronizer Synchronizer { get; } 24 | 25 | public void Move(int oldIndex, int newIndex) 26 | { 27 | base.MoveItem(oldIndex,newIndex); 28 | } 29 | 30 | protected override void InsertItem(int index, T newItem) 31 | { 32 | if(!Filter(newItem)) return; 33 | base.InsertItem(index, newItem); 34 | } 35 | 36 | protected override void ReplaceItem(int index, T newItem) 37 | { 38 | if (!Filter(newItem)) return; 39 | base.ReplaceItem(index, newItem); 40 | } 41 | 42 | public void Dispose() => Synchronizer.Dispose(); 43 | } 44 | 45 | public static class FilteredObservableCollectionExtensions 46 | { 47 | public static FilteredObservableCollection ToSyncedFilteredObservableCollection( 48 | this ISynchronizableNotifyChangedCollection source, Func filter) => ToSyncedFilteredObservableCollection(source, _ => _,filter); 49 | 50 | public static FilteredObservableCollection ToSyncedFilteredObservableCollection( 51 | this ISynchronizableNotifyChangedCollection source, 52 | Func converter, 53 | Func filter ) 54 | { 55 | var isDisposableType = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(TResult).GetTypeInfo()); 56 | 57 | lock (source.Synchronizer.LockObject) 58 | { 59 | var result = new FilteredObservableCollection(filter); 60 | foreach (var item in source) 61 | { 62 | result.Add(converter(item)); 63 | } 64 | 65 | var collectionChangedListener = 66 | SynchronizableNotifyChangedCollectionHelper.CreateSynchronizableCollectionChangedEventListener( 67 | source, result, 68 | converter, 69 | addAction: e => 70 | { 71 | var vm = converter((TSource) e.NewItems[0]); 72 | if(!filter(vm)) return; 73 | result.Insert(e.NewStartingIndex, vm); 74 | }, 75 | replaceAction: e => 76 | { 77 | if (isDisposableType) 78 | { 79 | ((IDisposable)result[e.NewStartingIndex]).Dispose(); 80 | } 81 | var replaceVm = converter((TSource)e.NewItems[0]); 82 | if (!filter(replaceVm)) return; 83 | result[e.NewStartingIndex] = replaceVm; 84 | }); 85 | result.Synchronizer.EventListeners.Add(collectionChangedListener); 86 | return result; 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/ISynchronizableNotifyChangedCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.ComponentModel; 5 | using System.Reflection; 6 | using StatefulModel.EventListeners.WeakEvents; 7 | 8 | namespace StatefulModel 9 | { 10 | public interface ISynchronizableNotifyChangedCollection : INotifyCollectionChanged, INotifyPropertyChanged, 11 | IDisposable 12 | { 13 | 14 | } 15 | 16 | public interface ISynchronizableNotifyChangedCollection : ISynchronizableNotifyChangedCollection,IList 17 | { 18 | Synchronizer Synchronizer { get; } 19 | void Move(int oldIndex, int newIndex); 20 | } 21 | 22 | public static class SynchronizableNotifyChangedCollectionHelper 23 | { 24 | public static CollectionChangedWeakEventListener CreateSynchronizableCollectionChangedEventListener 25 | ( 26 | ISynchronizableNotifyChangedCollection source, 27 | ISynchronizableNotifyChangedCollection target, 28 | Func converter, 29 | Action addAction = null, 30 | Action moveAction = null, 31 | Action removeAction = null, 32 | Action replaceAction = null, 33 | Action resetAction = null) 34 | { 35 | var isDisposableType = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(TResult).GetTypeInfo()); 36 | 37 | var collectionChangedListener = new CollectionChangedWeakEventListener(source); 38 | collectionChangedListener.RegisterHandler((sender, e) => 39 | { 40 | switch (e.Action) 41 | { 42 | case NotifyCollectionChangedAction.Add: 43 | if (addAction != null) 44 | { 45 | addAction(e); 46 | break; 47 | } 48 | var vm = converter((TSource) e.NewItems[0]); 49 | target.Insert(e.NewStartingIndex, vm); 50 | break; 51 | case NotifyCollectionChangedAction.Move: 52 | if (moveAction != null) 53 | { 54 | moveAction(e); 55 | break; 56 | } 57 | target.Move(e.OldStartingIndex, e.NewStartingIndex); 58 | break; 59 | case NotifyCollectionChangedAction.Remove: 60 | if (removeAction != null) 61 | { 62 | removeAction(e); 63 | break; 64 | } 65 | if (isDisposableType) 66 | { 67 | ((IDisposable) target[e.OldStartingIndex]).Dispose(); 68 | } 69 | target.RemoveAt(e.OldStartingIndex); 70 | break; 71 | case NotifyCollectionChangedAction.Replace: 72 | if (replaceAction != null) 73 | { 74 | replaceAction(e); 75 | break; 76 | } 77 | if (isDisposableType) 78 | { 79 | ((IDisposable) target[e.NewStartingIndex]).Dispose(); 80 | } 81 | var replaceVm = converter((TSource) e.NewItems[0]); 82 | target[e.NewStartingIndex] = replaceVm; 83 | break; 84 | case NotifyCollectionChangedAction.Reset: 85 | if (resetAction != null) 86 | { 87 | resetAction(e); 88 | break; 89 | } 90 | if (isDisposableType) 91 | { 92 | foreach (var result in target) 93 | { 94 | var item = (IDisposable) result; 95 | item.Dispose(); 96 | } 97 | } 98 | target.Clear(); 99 | break; 100 | default: 101 | throw new ArgumentException(); 102 | } 103 | }); 104 | return collectionChangedListener; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/NotifyChangedCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.ObjectModel; 5 | using System.Collections.Specialized; 6 | using System.ComponentModel; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace StatefulModel.Collections 12 | { 13 | internal static class EventArguments 14 | { 15 | public static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new PropertyChangedEventArgs("Count"); 16 | public static readonly PropertyChangedEventArgs ItemPropertyChangedEventArgs = new PropertyChangedEventArgs("Item[]"); 17 | } 18 | 19 | 20 | public class NotifyChangedCollection:IList, IList, IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged 21 | { 22 | private readonly IList _list; 23 | 24 | public event PropertyChangedEventHandler PropertyChanged; 25 | public event NotifyCollectionChangedEventHandler CollectionChanged; 26 | 27 | public NotifyChangedCollection() : this(Enumerable.Empty()) { } 28 | 29 | public NotifyChangedCollection(IEnumerable source) 30 | { 31 | if (source == null) throw new ArgumentNullException(nameof(source)); 32 | _list = new List(source); 33 | } 34 | 35 | public IEnumerator GetEnumerator() => ((IEnumerable)_list.ToArray()).GetEnumerator(); 36 | 37 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); 38 | 39 | protected virtual void InsertItem(int index,T newItem) 40 | { 41 | _list.Insert(index,newItem); 42 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 43 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 44 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,newItem,index)); 45 | } 46 | 47 | protected virtual void RemoveItem(int index) 48 | { 49 | var item = _list[index]; 50 | _list.RemoveAt(index); 51 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 52 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 53 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); 54 | } 55 | 56 | protected virtual void ReplaceItem(int index,T newItem) 57 | { 58 | var oldItem = _list[index]; 59 | _list[index] = newItem; 60 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 61 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, index)); 62 | } 63 | 64 | protected virtual void MoveItem(int oldIndex,int newIndex) 65 | { 66 | var item = _list[oldIndex]; 67 | _list.RemoveAt(oldIndex); 68 | _list.Insert(newIndex,item); 69 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 70 | CollectionChanged?.Invoke(this,new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move,item,newIndex,oldIndex)); 71 | } 72 | 73 | protected virtual void ClearItems() 74 | { 75 | if(_list.Count == 0) return; 76 | _list.Clear(); 77 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 78 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 79 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 80 | } 81 | 82 | public int Count => _list.Count; 83 | 84 | public bool IsReadOnly { get; } = false; 85 | 86 | public T this[int index] 87 | { 88 | get { return _list[index]; } 89 | 90 | set { ReplaceItem(index,value); } 91 | } 92 | 93 | public int IndexOf(T item) => _list.IndexOf(item); 94 | 95 | public void Insert(int index, T item) => InsertItem(index, item); 96 | 97 | public void RemoveAt(int index) => RemoveItem(index); 98 | 99 | public void Add(T item) => InsertItem(_list.Count, item); 100 | 101 | public void Clear() => ClearItems(); 102 | 103 | public bool Contains(T item) => _list.Contains(item); 104 | 105 | public void CopyTo(T[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); 106 | 107 | public bool Remove(T item) 108 | { 109 | if (!_list.Contains(item)) return false; 110 | RemoveItem(_list.IndexOf(item)); 111 | return true; 112 | } 113 | 114 | #region ICollection(non-generic) support 115 | void ICollection.CopyTo(Array array, int index) => CopyTo(array.Cast().ToArray(), index); 116 | bool ICollection.IsSynchronized { get; } = false; 117 | object ICollection.SyncRoot { get; } = new object(); 118 | #endregion 119 | 120 | #region IList(non-generic) support 121 | object IList.this[int index] 122 | { 123 | get { return _list[index]; } 124 | set { this[index] = (T)value; } 125 | } 126 | void IList.Remove(object value) => Remove((T)value); 127 | bool IList.IsFixedSize { get; } = false; 128 | int IList.Add(object value) 129 | { 130 | Add((T)value); 131 | return _list.Count - 1; 132 | } 133 | bool IList.Contains(object value) => Contains((T)value); 134 | int IList.IndexOf(object value) => IndexOf((T)value); 135 | void IList.Insert(int index, object value) => Insert(index, (T)value); 136 | #endregion 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/ObservableSynchronizedCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | using System.ComponentModel; 6 | using System.Linq; 7 | using System.Threading; 8 | using StatefulModel.Collections; 9 | 10 | namespace StatefulModel 11 | { 12 | public sealed class ObservableSynchronizedCollection :ICollection, IList, IReadOnlyList, ISynchronizableNotifyChangedCollection 13 | { 14 | private readonly IList _list; 15 | private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); 16 | 17 | public ObservableSynchronizedCollection() : this(Enumerable.Empty()) { } 18 | 19 | public ObservableSynchronizedCollection(IEnumerable source) 20 | { 21 | if (source == null) throw new ArgumentNullException(nameof(source)); 22 | _list = new List(source); 23 | Synchronizer = new Synchronizer(this); 24 | } 25 | 26 | public int IndexOf(T item) 27 | { 28 | return ReadWithLockAction(() => _list.IndexOf(item)); 29 | } 30 | 31 | public void Insert(int index, T item) 32 | { 33 | ReadAndWriteWithLockAction(() => _list.Insert(index, item), 34 | () => 35 | { 36 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 37 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 38 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); 39 | }); 40 | } 41 | 42 | public void RemoveAt(int index) 43 | { 44 | ReadAndWriteWithLockAction(() => _list[index], 45 | removeItem => _list.RemoveAt(index), 46 | removeItem => 47 | { 48 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 49 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 50 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removeItem, index)); 51 | }); 52 | } 53 | 54 | public T this[int index] 55 | { 56 | get 57 | { 58 | return ReadWithLockAction(() => _list[index]); 59 | } 60 | set 61 | { 62 | ReadAndWriteWithLockAction(() => _list[index], 63 | oldItem => 64 | { 65 | _list[index] = value; 66 | }, 67 | oldItem => 68 | { 69 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 70 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, _list[index], oldItem, index)); 71 | }); 72 | } 73 | } 74 | 75 | public void Add(T item) 76 | { 77 | ReadAndWriteWithLockAction(() => _list.Add(item), 78 | () => 79 | { 80 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 81 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 82 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, _list.Count - 1)); 83 | }); 84 | } 85 | 86 | public void Clear() 87 | { 88 | ReadAndWriteWithLockAction(() => _list.Count, 89 | count => 90 | { 91 | if (count != 0) 92 | { 93 | _list.Clear(); 94 | } 95 | }, 96 | count => 97 | { 98 | if (count != 0) 99 | { 100 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 101 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 102 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 103 | } 104 | }); 105 | } 106 | 107 | public bool Contains(T item) => ReadWithLockAction(() => _list.Contains(item)); 108 | 109 | public void CopyTo(T[] array, int arrayIndex) => ReadWithLockAction(() => _list.CopyTo(array, arrayIndex)); 110 | 111 | public int Count => ReadWithLockAction(() => _list.Count); 112 | 113 | public bool IsReadOnly => _list.IsReadOnly; 114 | 115 | public bool Remove(T item) 116 | { 117 | bool result = false; 118 | 119 | ReadAndWriteWithLockAction(() => _list.IndexOf(item), 120 | index => 121 | { 122 | result = _list.Remove(item); 123 | }, 124 | index => 125 | { 126 | if (result) 127 | { 128 | PropertyChanged?.Invoke(this, EventArguments.CountPropertyChangedEventArgs); 129 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 130 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); 131 | } 132 | }); 133 | 134 | return result; 135 | } 136 | 137 | public void Move(int oldIndex, int newIndex) 138 | { 139 | ReadAndWriteWithLockAction(() => _list[oldIndex], 140 | item => 141 | { 142 | _list.RemoveAt(oldIndex); 143 | _list.Insert(newIndex, item); 144 | }, 145 | item => 146 | { 147 | PropertyChanged?.Invoke(this, EventArguments.ItemPropertyChangedEventArgs); 148 | CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex)); 149 | }); 150 | } 151 | 152 | public IEnumerator GetEnumerator() => ReadWithLockAction(() => ((IEnumerable)_list.ToArray()).GetEnumerator()); 153 | 154 | IEnumerator IEnumerable.GetEnumerator() => ReadWithLockAction(() => ((IEnumerable)_list.ToArray()).GetEnumerator()); 155 | 156 | 157 | private void ReadWithLockAction(Action readAction) 158 | { 159 | if (!_lock.IsReadLockHeld) 160 | { 161 | _lock.EnterReadLock(); 162 | try 163 | { 164 | readAction(); 165 | } 166 | finally 167 | { 168 | _lock.ExitReadLock(); 169 | } 170 | } 171 | else 172 | { 173 | readAction(); 174 | } 175 | } 176 | 177 | private TResult ReadWithLockAction(Func readAction) 178 | { 179 | if (!_lock.IsReadLockHeld) 180 | { 181 | _lock.EnterReadLock(); 182 | try 183 | { 184 | return readAction(); 185 | } 186 | finally 187 | { 188 | _lock.ExitReadLock(); 189 | } 190 | } 191 | 192 | return readAction(); 193 | } 194 | 195 | private void ReadAndWriteWithLockAction(Action writeAction, Action readAfterWriteAction) 196 | { 197 | lock (Synchronizer.LockObject) 198 | { 199 | _lock.EnterUpgradeableReadLock(); 200 | try 201 | { 202 | _lock.EnterWriteLock(); 203 | try 204 | { 205 | writeAction(); 206 | } 207 | finally 208 | { 209 | _lock.ExitWriteLock(); 210 | } 211 | 212 | _lock.EnterReadLock(); 213 | 214 | try 215 | { 216 | readAfterWriteAction(); 217 | } 218 | finally 219 | { 220 | _lock.ExitReadLock(); 221 | } 222 | } 223 | finally 224 | { 225 | _lock.ExitUpgradeableReadLock(); 226 | } 227 | } 228 | } 229 | 230 | private void ReadAndWriteWithLockAction(Func readBeforeWriteAction, Action writeAction, Action readAfterWriteAction) 231 | { 232 | lock (Synchronizer.LockObject) 233 | { 234 | _lock.EnterUpgradeableReadLock(); 235 | try 236 | { 237 | TResult readActionResult = readBeforeWriteAction(); 238 | 239 | _lock.EnterWriteLock(); 240 | 241 | try 242 | { 243 | writeAction(readActionResult); 244 | } 245 | finally 246 | { 247 | _lock.ExitWriteLock(); 248 | } 249 | 250 | _lock.EnterReadLock(); 251 | 252 | try 253 | { 254 | readAfterWriteAction(readActionResult); 255 | } 256 | finally 257 | { 258 | _lock.ExitReadLock(); 259 | } 260 | } 261 | finally 262 | { 263 | _lock.ExitUpgradeableReadLock(); 264 | } 265 | } 266 | 267 | } 268 | 269 | public event NotifyCollectionChangedEventHandler CollectionChanged; 270 | 271 | public event PropertyChangedEventHandler PropertyChanged; 272 | 273 | public Synchronizer Synchronizer{get;} 274 | 275 | public void Dispose() => Synchronizer.Dispose(); 276 | 277 | #region ICollection(non-generic) support 278 | void ICollection.CopyTo(Array array, int index) => CopyTo(array.Cast().ToArray(), index); 279 | bool ICollection.IsSynchronized { get; } = false; 280 | object ICollection.SyncRoot { get; } = new object(); 281 | #endregion 282 | 283 | #region IList(non-generic) support 284 | object IList.this[int index] 285 | { 286 | get { return _list[index]; } 287 | set { this[index] = (T)value; } 288 | } 289 | void IList.Remove(object value) => Remove((T)value); 290 | bool IList.IsFixedSize { get; } = false; 291 | int IList.Add(object value) 292 | { 293 | Add((T)value); 294 | return _list.Count - 1; 295 | } 296 | bool IList.Contains(object value) => Contains((T)value); 297 | int IList.IndexOf(object value) => IndexOf((T)value); 298 | void IList.Insert(int index, object value) => Insert(index, (T)value); 299 | #endregion 300 | } 301 | 302 | public static class ObservableSynchronizedCollectionExtensions 303 | { 304 | public static ObservableSynchronizedCollection ToSyncedObservableSynchronizedCollection( 305 | this ISynchronizableNotifyChangedCollection source) => ToSyncedObservableSynchronizedCollection(source, _ => _); 306 | 307 | public static ObservableSynchronizedCollection ToSyncedObservableSynchronizedCollection( 308 | this ISynchronizableNotifyChangedCollection source, 309 | Func converter) 310 | { 311 | lock (source.Synchronizer.LockObject) 312 | { 313 | var result = new ObservableSynchronizedCollection(); 314 | foreach (var item in source) 315 | { 316 | result.Add(converter(item)); 317 | } 318 | 319 | var collectionChangedListener = 320 | SynchronizableNotifyChangedCollectionHelper.CreateSynchronizableCollectionChangedEventListener( 321 | source, result, 322 | converter); 323 | result.Synchronizer.EventListeners.Add(collectionChangedListener); 324 | return result; 325 | } 326 | } 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/ReadOnlyNotifyChangedCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.ObjectModel; 3 | using System.Collections.Specialized; 4 | using System.ComponentModel; 5 | using System.Reflection; 6 | using StatefulModel.EventListeners.WeakEvents; 7 | 8 | namespace StatefulModel 9 | { 10 | public sealed class ReadOnlyNotifyChangedCollection : ReadOnlyCollection, INotifyCollectionChanged, INotifyPropertyChanged, IDisposable 11 | { 12 | private readonly bool _isDisposableType; 13 | 14 | public ReadOnlyNotifyChangedCollection(ISynchronizableNotifyChangedCollection collection) 15 | : base(collection) 16 | { 17 | if (collection == null) throw new ArgumentNullException(nameof(collection)); 18 | 19 | EventListeners = new MultipleDisposable(); 20 | 21 | _isDisposableType = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); 22 | 23 | lock (collection.Synchronizer.LockObject) 24 | { 25 | SourceCollection = collection; 26 | 27 | EventListeners.Add(new PropertyChangedWeakEventListener(SourceCollection, (sender, e) => OnPropertyChanged(e))); 28 | EventListeners.Add(new CollectionChangedWeakEventListener(SourceCollection, (sender, e) => OnCollectionChanged(e))); 29 | } 30 | } 31 | 32 | public ISynchronizableNotifyChangedCollection SourceCollection { get;} 33 | 34 | public MultipleDisposable EventListeners { get;} 35 | 36 | public event NotifyCollectionChangedEventHandler CollectionChanged; 37 | 38 | public event PropertyChangedEventHandler PropertyChanged; 39 | 40 | private void OnCollectionChanged(NotifyCollectionChangedEventArgs args) => CollectionChanged?.Invoke(this, args); 41 | 42 | private void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args); 43 | 44 | public void Dispose() 45 | { 46 | if (EventListeners.Count != 0) 47 | { 48 | EventListeners.Dispose(); 49 | 50 | if (_isDisposableType) 51 | { 52 | foreach (var unknown in this) 53 | { 54 | var i = (IDisposable)unknown; 55 | i.Dispose(); 56 | } 57 | } 58 | } 59 | } 60 | } 61 | 62 | public static class ReadOnlyNotifyChangedCollectionExtensions 63 | { 64 | public static ReadOnlyNotifyChangedCollection ToSyncedReadOnlyNotifyChangedCollection( 65 | this ISynchronizableNotifyChangedCollection source) => new ReadOnlyNotifyChangedCollection(source); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/SortedObservableCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using StatefulModel.Collections; 6 | 7 | namespace StatefulModel 8 | { 9 | public sealed class SortedObservableCollection : NotifyChangedCollection,ISynchronizableNotifyChangedCollection 10 | { 11 | private readonly Func _keySelector; 12 | private readonly IComparer _comparer; 13 | 14 | public SortedObservableCollection(Func keySelector, bool isDescending = false) 15 | : this(Enumerable.Empty(), keySelector, null, isDescending) { } 16 | 17 | public SortedObservableCollection(Func keySelector, IComparer comparer,bool isDescending = false) 18 | : this(Enumerable.Empty(), keySelector, comparer, isDescending) { } 19 | 20 | public SortedObservableCollection(IEnumerable collection, Func keySelector, bool isDescending = false) 21 | : this(collection, keySelector, null, isDescending) { } 22 | 23 | public SortedObservableCollection(IEnumerable collection, Func keySelector, IComparer comparer, bool isDescending = false) 24 | { 25 | if (collection == null) throw new ArgumentNullException(nameof(collection)); 26 | if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); 27 | 28 | _keySelector = keySelector; 29 | 30 | if(comparer == null) 31 | { 32 | _comparer = new AnonymousComparer((x,y) => 33 | { 34 | var comparableSource = x as IComparable; 35 | var comparableTarget = y as IComparable; 36 | 37 | if (comparableSource != null) 38 | { 39 | return comparableSource.CompareTo(comparableTarget); 40 | } 41 | 42 | return 0; 43 | }); 44 | } 45 | var sourceComparer = _comparer; 46 | _comparer = isDescending ? new AnonymousComparer((x, y) => sourceComparer.Compare(x, y) * -1) : _comparer; 47 | 48 | Synchronizer = new Synchronizer(this); 49 | 50 | foreach (var item in collection) 51 | { 52 | Add(item); 53 | } 54 | } 55 | 56 | protected override void InsertItem(int index, TSource item) 57 | { 58 | lock (Synchronizer.LockObject) 59 | { 60 | base.InsertItem(FindNewIndex(item), item); 61 | } 62 | } 63 | protected override void MoveItem(int oldIndex, int newIndex) 64 | { 65 | throw new NotSupportedException("Move is not supported."); 66 | } 67 | 68 | protected override void RemoveItem(int index) 69 | { 70 | lock (Synchronizer.LockObject) 71 | { 72 | base.RemoveItem(index); 73 | } 74 | } 75 | 76 | protected override void ReplaceItem(int index, TSource newItem) 77 | { 78 | RemoveItem(index); 79 | InsertItem(FindNewIndex(newItem), newItem); 80 | } 81 | 82 | protected override void ClearItems() 83 | { 84 | lock (Synchronizer.LockObject) 85 | { 86 | base.ClearItems(); 87 | } 88 | } 89 | 90 | public void Move(int oldIndex, int newIndex) 91 | { 92 | MoveItem(oldIndex,newIndex); 93 | } 94 | 95 | public Synchronizer Synchronizer { get; } 96 | 97 | public void Dispose() => Synchronizer.Dispose(); 98 | 99 | private int FindNewIndex(TSource target) 100 | { 101 | if (Count == 0) return 0; 102 | 103 | if (Compare(target, this[0]) < 0) 104 | { 105 | return 0; 106 | } 107 | 108 | if (Compare(target, this[Count - 1]) > 0) 109 | { 110 | return Count; 111 | } 112 | 113 | var range = new IndexRange(0, Count - 1); 114 | return FindNextRangeCore(range, target).StartIndex; 115 | } 116 | 117 | private IndexRange FindNextRangeCore(IndexRange currentRange, TSource target) 118 | { 119 | if (currentRange.IsOne) return currentRange; 120 | 121 | if (currentRange.Count == 2 && Compare(target, this[currentRange.StartIndex]) > 0 && Compare(target, this[currentRange.EndIndex]) < 0) 122 | { 123 | return new IndexRange(currentRange.StartIndex + 1, currentRange.StartIndex + 1); 124 | } 125 | 126 | if (Compare(target, this[currentRange.CenterIndex]) == 0) 127 | { 128 | int i = currentRange.CenterIndex; 129 | while (i < Count && Compare(target, this[i]) == 0) 130 | { 131 | i++; 132 | } 133 | 134 | return new IndexRange(i, i); 135 | } 136 | 137 | if (Compare(target, this[currentRange.CenterIndex]) < 0) 138 | { 139 | return FindNextRangeCore(new IndexRange(currentRange.StartIndex, currentRange.CenterIndex), target); 140 | } 141 | else 142 | { 143 | return FindNextRangeCore(new IndexRange(currentRange.CenterIndex + 1, currentRange.EndIndex), target); 144 | } 145 | } 146 | 147 | private int Compare(TSource source, TSource target) 148 | { 149 | return _comparer.Compare(_keySelector(source), _keySelector(target)); 150 | } 151 | 152 | private class IndexRange 153 | { 154 | public IndexRange(int startIndex, int endIndex) 155 | { 156 | StartIndex = startIndex; 157 | EndIndex = endIndex; 158 | } 159 | 160 | public int StartIndex { get; } 161 | public int EndIndex { get;} 162 | public int CenterIndex => (StartIndex + EndIndex) / 2; 163 | public bool IsOne => StartIndex == EndIndex; 164 | public int Count => EndIndex - StartIndex + 1; 165 | } 166 | } 167 | 168 | public static class SortedObservableCollectionExtensions 169 | { 170 | public static SortedObservableCollection ToSyncedSortedObservableCollection( 171 | this ISynchronizableNotifyChangedCollection source, 172 | Func keySelector, 173 | IComparer comparer = null, 174 | bool isDescending = false) 175 | { 176 | var isDisposableType = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(TSource).GetTypeInfo()); 177 | 178 | lock (source.Synchronizer.LockObject) 179 | { 180 | var result = new SortedObservableCollection(keySelector, comparer, isDescending); 181 | 182 | foreach (var item in source) 183 | { 184 | result.Add(item); 185 | } 186 | 187 | var collectionChangedListener = SynchronizableNotifyChangedCollectionHelper.CreateSynchronizableCollectionChangedEventListener(source, result, 188 | _ => _, 189 | removeAction: e => 190 | { 191 | var removeSourceItem = (TSource)e.OldItems[0]; 192 | result.RemoveAt(result.IndexOf(removeSourceItem)); 193 | if (isDisposableType) 194 | { 195 | ((IDisposable)removeSourceItem).Dispose(); 196 | } 197 | }, 198 | moveAction: e => { }, 199 | replaceAction: e => 200 | { 201 | var removeSourceItem = (TSource)e.OldItems[0]; 202 | result.RemoveAt(result.IndexOf(removeSourceItem)); 203 | result.Add((TSource)e.NewItems[0]); 204 | if (isDisposableType) 205 | { 206 | ((IDisposable)removeSourceItem).Dispose(); 207 | } 208 | } 209 | ); 210 | result.Synchronizer.EventListeners.Add(collectionChangedListener); 211 | return result; 212 | } 213 | } 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/SynchronizationContextCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Threading; 6 | using StatefulModel.Collections; 7 | 8 | namespace StatefulModel 9 | { 10 | public sealed class SynchronizationContextCollection : NotifyChangedCollection,ISynchronizableNotifyChangedCollection 11 | { 12 | public SynchronizationContextCollection(SynchronizationContext context) : this(Enumerable.Empty(), context) { } 13 | 14 | public SynchronizationContextCollection(IEnumerable collection, SynchronizationContext context) : base(collection) 15 | { 16 | if (collection == null) throw new ArgumentNullException(nameof(collection)); 17 | if (context == null) throw new ArgumentNullException(nameof(context)); 18 | Synchronizer = new Synchronizer(this); 19 | Context = context; 20 | } 21 | 22 | protected override void InsertItem(int index, T newItem) => DoActionWithLockOnContext(() => base.InsertItem(index, newItem)); 23 | protected override void RemoveItem(int index) => DoActionWithLockOnContext(() => base.RemoveItem(index)); 24 | protected override void ReplaceItem(int index, T newItem) => DoActionWithLockOnContext(() => base.ReplaceItem(index, newItem)); 25 | protected override void MoveItem(int oldIndex, int newIndex) => DoActionWithLockOnContext(() => base.MoveItem(oldIndex,newIndex)); 26 | protected override void ClearItems() => DoActionWithLockOnContext(base.ClearItems); 27 | 28 | public void Move(int oldIndex, int newIndex) => MoveItem(oldIndex, newIndex); 29 | 30 | public SynchronizationContext Context { get; } 31 | 32 | private void DoActionWithLockOnContext(Action action) 33 | { 34 | lock (Synchronizer.LockObject) 35 | { 36 | Context.Post(_ => action(), null); 37 | } 38 | } 39 | 40 | public Synchronizer Synchronizer { get; } 41 | 42 | public void Dispose() => Synchronizer.Dispose(); 43 | } 44 | 45 | public static class SynchronizationContextCollectionExtensions 46 | { 47 | public static SynchronizationContextCollection ToSyncedSynchronizationContextCollection( 48 | this ISynchronizableNotifyChangedCollection source, 49 | SynchronizationContext context) => ToSyncedSynchronizationContextCollection(source, _ => _, context); 50 | 51 | public static SynchronizationContextCollection ToSyncedSynchronizationContextCollection( 52 | this ISynchronizableNotifyChangedCollection source, 53 | Func converter, 54 | SynchronizationContext context) 55 | { 56 | lock (source.Synchronizer.LockObject) 57 | { 58 | var result = new SynchronizationContextCollection(source.Select(converter),context); 59 | 60 | var collectionChangedListener = SynchronizableNotifyChangedCollectionHelper.CreateSynchronizableCollectionChangedEventListener(source, result, 61 | converter); 62 | result.Synchronizer.EventListeners.Add(collectionChangedListener); 63 | return result; 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/StatefulModel/Collections/Synchronizer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | 5 | namespace StatefulModel 6 | { 7 | public class Synchronizer : IDisposable 8 | { 9 | protected bool Disposed; 10 | 11 | private readonly bool _isDisposableType; 12 | 13 | public Synchronizer(IList currentCollection) 14 | { 15 | CurrentCollection = currentCollection; 16 | _isDisposableType = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); 17 | } 18 | 19 | public IList CurrentCollection { get; } 20 | 21 | public MultipleDisposable EventListeners { get; } = new MultipleDisposable(); 22 | 23 | public object LockObject { get; } = new object(); 24 | 25 | public void Dispose() 26 | { 27 | Dispose(true); 28 | GC.SuppressFinalize(this); 29 | } 30 | 31 | protected virtual void Dispose(bool disposing) 32 | { 33 | if (Disposed) return; 34 | 35 | if (disposing) 36 | { 37 | if (EventListeners.Count != 0) 38 | { 39 | EventListeners.Dispose(); 40 | if (_isDisposableType) 41 | { 42 | foreach (var unknown in CurrentCollection) 43 | { 44 | var i = (IDisposable) unknown; 45 | i.Dispose(); 46 | } 47 | } 48 | CurrentCollection.Clear(); 49 | } 50 | } 51 | Disposed = true; 52 | } 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/AnonymousCollectionChangedEventHandlerBag.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | using System.Linq; 6 | 7 | namespace StatefulModel.EventListeners 8 | { 9 | internal class AnonymousCollectionChangedEventHandlerBag : IEnumerable>> 10 | { 11 | private readonly Dictionary> _handlerDictionary = new Dictionary>(); 12 | private readonly WeakReference _source; 13 | 14 | private readonly List _allHandlerList = new List(); 15 | 16 | private readonly Dictionary, object> _lockObjectDictionary = new Dictionary, object>(); 17 | 18 | private readonly object _handlerDictionaryLockObject = new object(); 19 | private readonly object _allHandlerListLockObject = new object(); 20 | 21 | internal AnonymousCollectionChangedEventHandlerBag(INotifyCollectionChanged source) 22 | { 23 | if (source == null) throw new ArgumentNullException(nameof(source)); 24 | _source = new WeakReference(source); 25 | } 26 | 27 | internal AnonymousCollectionChangedEventHandlerBag(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler) 28 | : this(source) 29 | { 30 | if (handler == null) throw new ArgumentNullException(nameof(handler)); 31 | RegisterHandler(handler); 32 | } 33 | 34 | internal void RegisterHandler(NotifyCollectionChangedEventHandler handler) 35 | { 36 | lock (_allHandlerListLockObject) 37 | { 38 | _allHandlerList.Add(handler); 39 | } 40 | } 41 | 42 | internal void RegisterHandler(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) 43 | { 44 | lock (_handlerDictionaryLockObject) 45 | { 46 | List bag; 47 | if (!_handlerDictionary.TryGetValue(action, out bag)) 48 | { 49 | bag = new List(); 50 | _lockObjectDictionary.Add(bag, new object()); 51 | _handlerDictionary[action] = bag; 52 | } 53 | bag.Add(handler); 54 | } 55 | } 56 | 57 | internal void ExecuteHandler(NotifyCollectionChangedEventArgs e) 58 | { 59 | INotifyCollectionChanged sourceResult; 60 | var result = _source.TryGetTarget(out sourceResult); 61 | 62 | if (!result) return; 63 | 64 | List list; 65 | lock (_handlerDictionaryLockObject) 66 | { 67 | _handlerDictionary.TryGetValue(e.Action, out list); 68 | } 69 | if (list != null) 70 | { 71 | lock (_lockObjectDictionary[list]) 72 | { 73 | foreach (var handler in list) 74 | { 75 | handler(sourceResult, e); 76 | } 77 | } 78 | } 79 | 80 | lock (_allHandlerListLockObject) 81 | { 82 | if (_allHandlerList.Any()) 83 | { 84 | foreach (var handler in _allHandlerList) 85 | { 86 | handler(sourceResult, e); 87 | } 88 | } 89 | } 90 | } 91 | 92 | IEnumerator>> IEnumerable>>.GetEnumerator() 93 | => _handlerDictionary.GetEnumerator(); 94 | 95 | IEnumerator IEnumerable.GetEnumerator() => _handlerDictionary.GetEnumerator(); 96 | 97 | internal void Add(NotifyCollectionChangedEventHandler handler) => RegisterHandler(handler); 98 | 99 | internal void Add(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) => RegisterHandler(action, handler); 100 | 101 | 102 | internal void Add(NotifyCollectionChangedAction action, params NotifyCollectionChangedEventHandler[] handlers) 103 | { 104 | foreach (var handler in handlers) 105 | { 106 | RegisterHandler(action, handler); 107 | } 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/AnonymousPropertyChangedEventHandlerBag.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | 6 | namespace StatefulModel.EventListeners 7 | { 8 | internal class AnonymousPropertyChangedEventHandlerBag : IEnumerable>> 9 | { 10 | private readonly Dictionary> _handlerDictionary = new Dictionary>(); 11 | private readonly WeakReference _source; 12 | 13 | private readonly object _handlerDictionaryLockObject = new object(); 14 | private readonly Dictionary, object> _lockObjectDictionary = new Dictionary, object>(); 15 | 16 | internal AnonymousPropertyChangedEventHandlerBag(INotifyPropertyChanged source) 17 | { 18 | if (source == null) throw new ArgumentNullException(nameof(source)); 19 | 20 | _source = new WeakReference(source); 21 | } 22 | 23 | internal AnonymousPropertyChangedEventHandlerBag(INotifyPropertyChanged source, PropertyChangedEventHandler handler) 24 | : this(source) 25 | { 26 | if (handler == null) throw new ArgumentNullException(nameof(handler)); 27 | RegisterHandler(handler); 28 | } 29 | 30 | internal void RegisterHandler(PropertyChangedEventHandler handler) => RegisterHandler(string.Empty, handler); 31 | 32 | internal void RegisterHandler(string propertyName, PropertyChangedEventHandler handler) 33 | { 34 | lock (_handlerDictionaryLockObject) 35 | { 36 | List bag; 37 | if (!_handlerDictionary.TryGetValue(propertyName, out bag)) 38 | { 39 | bag = new List(); 40 | _lockObjectDictionary.Add(bag, new object()); 41 | _handlerDictionary[propertyName] = bag; 42 | } 43 | bag.Add(handler); 44 | } 45 | } 46 | 47 | internal void ExecuteHandler(PropertyChangedEventArgs e) 48 | { 49 | INotifyPropertyChanged sourceResult; 50 | var result = _source.TryGetTarget(out sourceResult); 51 | 52 | if (!result) return; 53 | 54 | if (e.PropertyName != null) 55 | { 56 | List list; 57 | lock (_handlerDictionaryLockObject) 58 | { 59 | _handlerDictionary.TryGetValue(e.PropertyName, out list); 60 | } 61 | 62 | if (list != null) 63 | { 64 | lock (_lockObjectDictionary[list]) 65 | { 66 | foreach (var handler in list) 67 | { 68 | handler(sourceResult, e); 69 | } 70 | } 71 | } 72 | } 73 | 74 | lock (_handlerDictionaryLockObject) 75 | { 76 | List allList; 77 | _handlerDictionary.TryGetValue(string.Empty, out allList); 78 | if (allList != null) 79 | { 80 | lock (_lockObjectDictionary[allList]) 81 | { 82 | foreach (var handler in allList) 83 | { 84 | handler(sourceResult, e); 85 | } 86 | } 87 | } 88 | } 89 | } 90 | 91 | IEnumerator>> IEnumerable>>.GetEnumerator() 92 | => _handlerDictionary.GetEnumerator(); 93 | 94 | IEnumerator IEnumerable.GetEnumerator() => _handlerDictionary.GetEnumerator(); 95 | 96 | internal void Add(PropertyChangedEventHandler handler) => RegisterHandler(handler); 97 | 98 | internal void Add(string propertyName, PropertyChangedEventHandler handler) => RegisterHandler(propertyName, handler); 99 | 100 | internal void Add(string propertyName, params PropertyChangedEventHandler[] handlers) 101 | { 102 | foreach (var handler in handlers) 103 | { 104 | RegisterHandler(propertyName, handler); 105 | } 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/CollectionChangedEventListener.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | 5 | namespace StatefulModel.EventListeners 6 | { 7 | public sealed class CollectionChangedEventListener : EventListener, IEnumerable>> 8 | { 9 | private readonly AnonymousCollectionChangedEventHandlerBag _bag; 10 | 11 | public CollectionChangedEventListener(INotifyCollectionChanged source) 12 | { 13 | _bag = new AnonymousCollectionChangedEventHandlerBag(source); 14 | Initialize(h => source.CollectionChanged += h, h => source.CollectionChanged -= h, (sender, e) => _bag.ExecuteHandler(e)); 15 | } 16 | 17 | public CollectionChangedEventListener(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler) 18 | { 19 | _bag = new AnonymousCollectionChangedEventHandlerBag(source, handler); 20 | Initialize(h => source.CollectionChanged += h, h => source.CollectionChanged -= h, (sender, e) => _bag.ExecuteHandler(e)); 21 | } 22 | 23 | public void RegisterHandler(NotifyCollectionChangedEventHandler handler) 24 | { 25 | ThrowExceptionIfDisposed(); 26 | _bag.RegisterHandler(handler); 27 | } 28 | 29 | public void RegisterHandler(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) 30 | { 31 | ThrowExceptionIfDisposed(); 32 | _bag.RegisterHandler(action, handler); 33 | } 34 | 35 | IEnumerator>> IEnumerable>>.GetEnumerator() 36 | { 37 | return 38 | (( 39 | IEnumerable 40 | >>) 41 | _bag).GetEnumerator(); 42 | } 43 | 44 | IEnumerator IEnumerable.GetEnumerator() 45 | { 46 | return (( 47 | IEnumerable 48 | >>) 49 | _bag).GetEnumerator(); 50 | } 51 | 52 | public void Add(NotifyCollectionChangedEventHandler handler) 53 | { 54 | ThrowExceptionIfDisposed(); 55 | _bag.Add(handler); 56 | } 57 | 58 | public void Add(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) 59 | { 60 | ThrowExceptionIfDisposed(); 61 | _bag.Add(action, handler); 62 | } 63 | 64 | 65 | public void Add(NotifyCollectionChangedAction action, params NotifyCollectionChangedEventHandler[] handlers) 66 | { 67 | ThrowExceptionIfDisposed(); 68 | _bag.Add(action, handlers); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/EventListener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StatefulModel.EventListeners 4 | { 5 | public class EventListener : IDisposable where THandler : class 6 | { 7 | private THandler _handler; 8 | private Action _add; 9 | private Action _remove; 10 | private bool _disposed; 11 | 12 | private readonly bool _initialized; 13 | 14 | public EventListener(Action add, Action remove, THandler handler) 15 | { 16 | Initialize(add, remove, handler); 17 | _initialized = true; 18 | } 19 | 20 | protected EventListener() 21 | { 22 | 23 | } 24 | 25 | protected void Initialize(Action add, Action remove, THandler handler) 26 | { 27 | if (_initialized) return; 28 | 29 | if (add == null) throw new ArgumentNullException(nameof(add)); 30 | if (remove == null) throw new ArgumentNullException(nameof(remove)); 31 | if (handler == null) throw new ArgumentNullException(nameof(handler)); 32 | 33 | _add = add; 34 | _handler = handler; 35 | _remove = remove; 36 | _add(handler); 37 | } 38 | 39 | protected void ThrowExceptionIfDisposed() 40 | { 41 | if (_disposed) 42 | { 43 | throw new ObjectDisposedException("EventListener"); 44 | } 45 | } 46 | 47 | public void Dispose() 48 | { 49 | Dispose(true); 50 | GC.SuppressFinalize(this); 51 | } 52 | 53 | protected virtual void Dispose(bool disposing) 54 | { 55 | if (_disposed) return; 56 | 57 | if (disposing) 58 | { 59 | _remove(_handler); 60 | _add = null; 61 | _remove = null; 62 | _handler = null; 63 | } 64 | _disposed = true; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/PropertyChangedEventListener.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | 5 | namespace StatefulModel.EventListeners 6 | { 7 | public sealed class PropertyChangedEventListener : EventListener, IEnumerable>> 8 | { 9 | private readonly AnonymousPropertyChangedEventHandlerBag _bag; 10 | 11 | public PropertyChangedEventListener(INotifyPropertyChanged source) 12 | { 13 | _bag = new AnonymousPropertyChangedEventHandlerBag(source); 14 | Initialize(h => source.PropertyChanged += h, h => source.PropertyChanged -= h, (sender, e) => _bag.ExecuteHandler(e)); 15 | } 16 | 17 | public PropertyChangedEventListener(INotifyPropertyChanged source, PropertyChangedEventHandler handler) 18 | { 19 | _bag = new AnonymousPropertyChangedEventHandlerBag(source, handler); 20 | Initialize(h => source.PropertyChanged += h, h => source.PropertyChanged -= h, (sender, e) => _bag.ExecuteHandler(e)); 21 | } 22 | 23 | public void RegisterHandler(PropertyChangedEventHandler handler) 24 | { 25 | ThrowExceptionIfDisposed(); 26 | _bag.RegisterHandler(handler); 27 | } 28 | 29 | public void RegisterHandler(string propertyName, PropertyChangedEventHandler handler) 30 | { 31 | ThrowExceptionIfDisposed(); 32 | _bag.RegisterHandler(propertyName, handler); 33 | } 34 | 35 | IEnumerator>> IEnumerable>>.GetEnumerator() 36 | => ((IEnumerable>>)_bag) 37 | .GetEnumerator(); 38 | 39 | IEnumerator IEnumerable.GetEnumerator() 40 | => ((IEnumerable>>)_bag).GetEnumerator(); 41 | 42 | public void Add(PropertyChangedEventHandler handler) 43 | { 44 | ThrowExceptionIfDisposed(); 45 | _bag.Add(handler); 46 | } 47 | 48 | public void Add(string propertyName, PropertyChangedEventHandler handler) 49 | { 50 | ThrowExceptionIfDisposed(); 51 | _bag.Add(propertyName, handler); 52 | } 53 | 54 | 55 | public void Add(string propertyName, params PropertyChangedEventHandler[] handlers) 56 | { 57 | ThrowExceptionIfDisposed(); 58 | _bag.Add(propertyName, handlers); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/WeakEvents/CollectionChangedWeakEventListener.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | 5 | namespace StatefulModel.EventListeners.WeakEvents 6 | { 7 | public sealed class CollectionChangedWeakEventListener : WeakEventListener, IEnumerable>> 8 | { 9 | private readonly AnonymousCollectionChangedEventHandlerBag _bag; 10 | 11 | public CollectionChangedWeakEventListener(INotifyCollectionChanged source) 12 | { 13 | _bag = new AnonymousCollectionChangedEventHandlerBag(source); 14 | Initialize( 15 | h => new NotifyCollectionChangedEventHandler(h), 16 | h => source.CollectionChanged += h, 17 | h => source.CollectionChanged -= h, 18 | (sender, e) => _bag.ExecuteHandler(e)); 19 | } 20 | 21 | public CollectionChangedWeakEventListener(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler) 22 | { 23 | _bag = new AnonymousCollectionChangedEventHandlerBag(source, handler); 24 | Initialize( 25 | h => new NotifyCollectionChangedEventHandler(h), 26 | h => source.CollectionChanged += h, 27 | h => source.CollectionChanged -= h, 28 | (sender, e) => _bag.ExecuteHandler(e)); 29 | } 30 | 31 | public void RegisterHandler(NotifyCollectionChangedEventHandler handler) 32 | { 33 | ThrowExceptionIfDisposed(); 34 | _bag.RegisterHandler(handler); 35 | } 36 | 37 | public void RegisterHandler(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) 38 | { 39 | ThrowExceptionIfDisposed(); 40 | _bag.RegisterHandler(action, handler); 41 | } 42 | 43 | IEnumerator>> IEnumerable>>.GetEnumerator() 44 | { 45 | return 46 | (( 47 | IEnumerable 48 | >>) 49 | _bag).GetEnumerator(); 50 | } 51 | 52 | IEnumerator IEnumerable.GetEnumerator() 53 | { 54 | return (( 55 | IEnumerable 56 | >>) 57 | _bag).GetEnumerator(); 58 | } 59 | 60 | public void Add(NotifyCollectionChangedEventHandler handler) 61 | { 62 | ThrowExceptionIfDisposed(); 63 | _bag.Add(handler); 64 | } 65 | 66 | public void Add(NotifyCollectionChangedAction action, NotifyCollectionChangedEventHandler handler) 67 | { 68 | ThrowExceptionIfDisposed(); 69 | _bag.Add(action, handler); 70 | } 71 | 72 | public void Add(NotifyCollectionChangedAction action, params NotifyCollectionChangedEventHandler[] handlers) 73 | { 74 | ThrowExceptionIfDisposed(); 75 | _bag.Add(action, handlers); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/WeakEvents/PropertyChangedWeakEventListener.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | 5 | namespace StatefulModel.EventListeners.WeakEvents 6 | { 7 | public sealed class PropertyChangedWeakEventListener : WeakEventListener, IEnumerable>> 8 | { 9 | private readonly AnonymousPropertyChangedEventHandlerBag _bag; 10 | 11 | public PropertyChangedWeakEventListener(INotifyPropertyChanged source) 12 | { 13 | _bag = new AnonymousPropertyChangedEventHandlerBag(source); 14 | Initialize( 15 | h => new PropertyChangedEventHandler(h), 16 | h => source.PropertyChanged += h, 17 | h => source.PropertyChanged -= h, 18 | (sender, e) => _bag.ExecuteHandler(e)); 19 | } 20 | 21 | public PropertyChangedWeakEventListener(INotifyPropertyChanged source, PropertyChangedEventHandler handler) 22 | { 23 | _bag = new AnonymousPropertyChangedEventHandlerBag(source, handler); 24 | Initialize( 25 | h => new PropertyChangedEventHandler(h), 26 | h => source.PropertyChanged += h, 27 | h => source.PropertyChanged -= h, 28 | (sender, e) => _bag.ExecuteHandler(e)); 29 | } 30 | 31 | public void RegisterHandler(PropertyChangedEventHandler handler) 32 | { 33 | ThrowExceptionIfDisposed(); 34 | _bag.RegisterHandler(handler); 35 | } 36 | 37 | public void RegisterHandler(string propertyName, PropertyChangedEventHandler handler) 38 | { 39 | ThrowExceptionIfDisposed(); 40 | _bag.RegisterHandler(propertyName, handler); 41 | } 42 | 43 | IEnumerator>> IEnumerable>>.GetEnumerator() 44 | { 45 | ThrowExceptionIfDisposed(); 46 | return 47 | ((IEnumerable>>)_bag) 48 | .GetEnumerator(); 49 | } 50 | 51 | IEnumerator IEnumerable.GetEnumerator() 52 | { 53 | ThrowExceptionIfDisposed(); 54 | return ((IEnumerable>>)_bag).GetEnumerator(); 55 | } 56 | 57 | public void Add(PropertyChangedEventHandler handler) 58 | { 59 | ThrowExceptionIfDisposed(); 60 | _bag.Add(handler); 61 | } 62 | 63 | public void Add(string propertyName, PropertyChangedEventHandler handler) 64 | { 65 | ThrowExceptionIfDisposed(); 66 | _bag.Add(propertyName, handler); 67 | } 68 | 69 | 70 | public void Add(string propertyName, params PropertyChangedEventHandler[] handlers) 71 | { 72 | ThrowExceptionIfDisposed(); 73 | _bag.Add(propertyName, handlers); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/StatefulModel/EventListeners/WeakEvents/WeakEventListener.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StatefulModel.EventListeners.WeakEvents 4 | { 5 | public class WeakEventListener : IDisposable where TEventArgs : EventArgs 6 | { 7 | private bool _disposed; 8 | 9 | private EventHandler _handler; 10 | private THandler _resultHandler; 11 | private Action _remove; 12 | private readonly bool _initialized; 13 | 14 | private static void ReceiveEvent(WeakReference> listenerWeakReference, object sender, TEventArgs args) 15 | { 16 | WeakEventListener listenerResult; 17 | 18 | if (listenerWeakReference.TryGetTarget(out listenerResult)) 19 | { 20 | listenerResult._handler?.Invoke(sender,args); 21 | } 22 | } 23 | 24 | private static THandler GetStaticHandler(WeakReference> listenerWeakReference, Func, THandler> conversion) 25 | { 26 | return conversion((sender, e) => ReceiveEvent(listenerWeakReference, sender, e)); 27 | } 28 | 29 | protected WeakEventListener() 30 | { 31 | 32 | } 33 | 34 | protected void Initialize(Func, THandler> conversion, Action add, Action remove, EventHandler handler) 35 | { 36 | if (_initialized) return; 37 | 38 | if (conversion == null) throw new ArgumentNullException(nameof(conversion)); 39 | if (add == null) throw new ArgumentNullException(nameof(add)); 40 | if (remove == null) throw new ArgumentNullException(nameof(remove)); 41 | if (handler == null) throw new ArgumentNullException(nameof(handler)); 42 | 43 | _handler = handler; 44 | _remove = remove; 45 | 46 | _resultHandler = GetStaticHandler(new WeakReference>(this), conversion); 47 | 48 | add(_resultHandler); 49 | } 50 | 51 | public WeakEventListener(Func, THandler> conversion, Action add, Action remove, EventHandler handler) 52 | { 53 | Initialize(conversion, add, remove, handler); 54 | _initialized = true; 55 | } 56 | 57 | protected void ThrowExceptionIfDisposed() 58 | { 59 | if (_disposed) 60 | { 61 | throw new ObjectDisposedException("LivetWeakEventListener"); 62 | } 63 | } 64 | 65 | public void Dispose() 66 | { 67 | Dispose(true); 68 | GC.SuppressFinalize(this); 69 | } 70 | 71 | protected virtual void Dispose(bool disposing) 72 | { 73 | if (_disposed) return; 74 | 75 | if (disposing) 76 | { 77 | _remove(_resultHandler); 78 | _handler = null; 79 | _resultHandler = default(THandler); 80 | _remove = null; 81 | } 82 | _disposed = true; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/StatefulModel/MultipleDisposable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace StatefulModel 6 | { 7 | public class MultipleDisposable : IDisposable, ICollection 8 | { 9 | private readonly List _targetLists; 10 | private bool _disposed; 11 | private readonly object _lockObject = new object(); 12 | 13 | public MultipleDisposable() 14 | { 15 | _targetLists = new List(); 16 | } 17 | 18 | public MultipleDisposable(IEnumerable sourceDisposableList) 19 | { 20 | if (sourceDisposableList == null) throw new ArgumentNullException(nameof(sourceDisposableList)); 21 | 22 | _targetLists = new List(sourceDisposableList); 23 | } 24 | 25 | public IEnumerator GetEnumerator() 26 | { 27 | ThrowExceptionIfDisposed(); 28 | lock (_lockObject) 29 | { 30 | return ((IEnumerable)_targetLists.ToArray()).GetEnumerator(); 31 | } 32 | } 33 | 34 | IEnumerator IEnumerable.GetEnumerator() 35 | { 36 | ThrowExceptionIfDisposed(); 37 | lock (_lockObject) 38 | { 39 | return ((IEnumerable)_targetLists.ToArray()).GetEnumerator(); 40 | } 41 | } 42 | 43 | public void Add(IDisposable item) 44 | { 45 | ThrowExceptionIfDisposed(); 46 | lock (_lockObject) 47 | { 48 | _targetLists.Add(item); 49 | } 50 | } 51 | 52 | public void Add(Action releaseAction) 53 | { 54 | ThrowExceptionIfDisposed(); 55 | var disposable = new AnonymousDisposable(releaseAction); 56 | lock (_lockObject) 57 | { 58 | _targetLists.Add(disposable); 59 | } 60 | } 61 | 62 | public void AddFirst(IDisposable item) 63 | { 64 | ThrowExceptionIfDisposed(); 65 | lock (_lockObject) 66 | { 67 | _targetLists.Insert(0, item); 68 | } 69 | } 70 | 71 | public void AddFirst(Action releaseAction) 72 | { 73 | ThrowExceptionIfDisposed(); 74 | var disposable = new AnonymousDisposable(releaseAction); 75 | lock (_lockObject) 76 | { 77 | _targetLists.Insert(0, disposable); 78 | } 79 | } 80 | 81 | public void Clear() 82 | { 83 | ThrowExceptionIfDisposed(); 84 | lock (_lockObject) 85 | { 86 | _targetLists.Clear(); 87 | } 88 | } 89 | 90 | public bool Contains(IDisposable item) 91 | { 92 | ThrowExceptionIfDisposed(); 93 | lock (_lockObject) 94 | { 95 | return _targetLists.Contains(item); 96 | } 97 | } 98 | 99 | public void CopyTo(IDisposable[] array, int arrayIndex) 100 | { 101 | ThrowExceptionIfDisposed(); 102 | lock (_lockObject) 103 | { 104 | _targetLists.CopyTo(array, arrayIndex); 105 | } 106 | } 107 | 108 | public int Count 109 | { 110 | get 111 | { 112 | ThrowExceptionIfDisposed(); 113 | lock (_lockObject) 114 | { 115 | return _targetLists.Count; 116 | } 117 | } 118 | } 119 | 120 | public bool IsReadOnly 121 | { 122 | get 123 | { 124 | ThrowExceptionIfDisposed(); 125 | return false; 126 | } 127 | 128 | } 129 | 130 | public bool Remove(IDisposable item) 131 | { 132 | ThrowExceptionIfDisposed(); 133 | 134 | lock (_lockObject) 135 | { 136 | return _targetLists.Remove(item); 137 | } 138 | } 139 | 140 | public void Dispose() 141 | { 142 | Dispose(true); 143 | GC.SuppressFinalize(this); 144 | } 145 | 146 | protected virtual void Dispose(bool disposing) 147 | { 148 | if (_disposed) return; 149 | 150 | if (disposing) 151 | { 152 | lock (_lockObject) 153 | { 154 | foreach(var item in _targetLists) 155 | { 156 | item.Dispose(); 157 | } 158 | } 159 | } 160 | _disposed = true; 161 | } 162 | 163 | protected void ThrowExceptionIfDisposed() 164 | { 165 | if (_disposed) 166 | { 167 | throw new ObjectDisposedException("CompositeDisposable"); 168 | } 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/StatefulModel/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Resources; 3 | 4 | // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 5 | // アセンブリに関連付けられている情報を変更するには、 6 | // これらの属性値を変更してください。 7 | [assembly: AssemblyTitle("StatefulModel")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("StatefulModel")] 12 | [assembly: AssemblyCopyright("Copyright (C) Masanori Onoue (@ugaya40), 2015")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | [assembly: NeutralResourcesLanguage("en-US")] 16 | 17 | // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: 18 | // 19 | // メジャー バージョン 20 | // マイナー バージョン 21 | // ビルド番号 22 | // リビジョン 23 | // 24 | // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を 25 | // 既定値にすることができます: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("0.6.0.0")] 28 | [assembly: AssemblyFileVersion("0.6.0.0")] 29 | -------------------------------------------------------------------------------- /src/StatefulModel/StatefulModel.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 10.0 6 | Debug 7 | AnyCPU 8 | {87039EA4-0330-46CE-A4CE-B59584C52BBB} 9 | Library 10 | Properties 11 | StatefulModel 12 | StatefulModel 13 | ja-JP 14 | 512 15 | {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 16 | Profile78 17 | v4.5 18 | 19 | 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | 28 | 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 70 | -------------------------------------------------------------------------------- /src/StatefulModel/StatefulModel.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StatefulModel 5 | 0.6.0 6 | StatefulModel 7 | Masanori Onoue (@ugaya40) 8 | Masanori Onoue (@ugaya40) 9 | https://github.com/ugaya40/StatefulModel/blob/master/LICENSE 10 | https://github.com/ugaya40/StatefulModel 11 | false 12 | Frequent use of stateful Models for M-V-Whatever. example,synced - ObservableCollection etc. 13 | Frequent use of stateful Models for M-V-Whatever. example,synced - ObservableCollection etc. 14 | Copyright (C) Masanori Onoue (@ugaya40), 2015 15 | en-US 16 | MVVM 17 | 18 | 19 | --------------------------------------------------------------------------------