Files
Keys/App/ViewModels/PasswordStoreShortcutCollection.cs

94 lines
3.0 KiB
C#

namespace Keychain.ViewModels;
using Adw;
using Gtk;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
public class PasswordStoreShortcutCollection : ObservableCollection<PasswordStoreViewModel>
{
private readonly PreferencesGroup shortcutsGroup;
private readonly Dictionary<PasswordStoreViewModel, ActionRow> itemToRowMap = new();
public PasswordStoreShortcutCollection(PreferencesGroup shortcutsGroup)
{
this.shortcutsGroup = shortcutsGroup;
CollectionChanged += OnCollectionChanged;
}
private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (PasswordStoreViewModel item in e.NewItems)
{
var row = CreateShortcutRow(item);
itemToRowMap[item] = row;
shortcutsGroup.Add(row);
// Subscribe to property changes for reactive updates
item.PropertyChanged += (sender, args) => UpdateRowFromItem(item, ref row);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (PasswordStoreViewModel item in e.OldItems)
{
if (itemToRowMap.TryGetValue(item, out var row))
{
shortcutsGroup.Remove(row);
itemToRowMap.Remove(item);
}
}
break;
case NotifyCollectionChangedAction.Reset:
foreach (var row in itemToRowMap.Values)
{
shortcutsGroup.Remove(row);
}
itemToRowMap.Clear();
break;
}
}
private ActionRow CreateShortcutRow(PasswordStoreViewModel shortcut)
{
var row = new ActionRow();
UpdateRowFromItem(shortcut, ref row);
row.SetActivatable(true);
row.OnActivated += (sender, args) => {
Console.WriteLine($"[DEBUG] Opening: {shortcut.Path}");
};
return row;
}
private void UpdateRowFromItem(PasswordStoreViewModel shortcut, ref ActionRow row)
{
row.SetTitle(shortcut.DisplayName);
row.SetSubtitle(shortcut.Path);
//Update icon
var existingIcon = row.GetFirstChild() as Gtk.Image;
if (existingIcon == null)
{
var icon = new Gtk.Image();
icon.SetFromIconName(shortcut.IconName);
row.AddPrefix(icon);
}
else
{
existingIcon.SetFromIconName(shortcut.IconName);
}
// Edit button
var edit = new Button();
edit.AddCssClass("flat");
edit.SetValign(Align.Center);
edit.IconName = "document-edit-symbolic";
row.AddSuffix(edit);
}
}