using System.ComponentModel; using System.Reflection; using System.Windows; using YukkuriMovieMaker.UndoRedo; using YukkuriMovieMaker.ViewModels; namespace UndoTree; internal sealed class UndoTreeHostModel { internal const string SavedFlagName = "IsProjectFileSaved"; const string ProjectPathName = "ProjectFilePath"; const string ManagerName = "UndoRedoManager"; readonly PropertyInfo savedFlag; readonly PropertyInfo? projectPath; public UndoTreeHostModel(INotifyPropertyChanged model) { Model = model; savedFlag = SavedFlagOf(model) ?? throw new ArgumentException($"The model has no {SavedFlagName} property.", nameof(model)); projectPath = model.GetType().GetProperty(ProjectPathName, typeof(string)); } public INotifyPropertyChanged Model { get; } public bool IsSaved => savedFlag.GetValue(Model) is true; public string? ProjectPath => projectPath?.GetValue(Model) as string; public static UndoTreeHostModel? Find(UndoRedoManager manager) { if (Application.Current is not { } application) return null; return application.Dispatcher.CheckAccess() ? Search(application, manager) : application.Dispatcher.Invoke(() => Search(application, manager)); } internal static bool IsModelOf(object candidate, UndoRedoManager manager) => SavedFlagOf(candidate) is not null && candidate.GetType().GetProperty(ManagerName, typeof(UndoRedoManager)) is { } property && ReferenceEquals(property.GetValue(candidate), manager); static UndoTreeHostModel? Search(Application application, UndoRedoManager manager) => application.Windows.OfType() .Select(window => window.DataContext) .OfType() .SelectMany(viewModel => viewModel.GetType() .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Select(field => field.GetValue(viewModel))) .OfType() .Where(candidate => IsModelOf(candidate, manager)) .Select(candidate => new UndoTreeHostModel(candidate)) .FirstOrDefault(); static PropertyInfo? SavedFlagOf(object model) => model.GetType().GetProperty(SavedFlagName, typeof(bool)); }