using Moli.Desktop.Configuration;
|
using Moli.Desktop.Diagnostics;
|
using Moli.Desktop.Plugins;
|
using Moli.Desktop.Runtime;
|
|
namespace Moli.Desktop.Layout;
|
|
public sealed class LayoutManager : ILayoutManager
|
{
|
public const double MinWidth = 80;
|
public const double MinHeight = 40;
|
public const double MinVisibleDip = 48;
|
public const double MinScale = 0.5;
|
public const double MaxScale = 3;
|
public const double MinOpacity = 0.1;
|
public const double MaxOpacity = 1;
|
|
private readonly IConfigurationService _configuration;
|
private readonly IDiagnosticsService _diagnostics;
|
private readonly object _gate = new();
|
private LayoutDocument _document = new();
|
|
public LayoutManager(IConfigurationService configuration, IDiagnosticsService diagnostics)
|
{
|
_configuration = configuration;
|
_diagnostics = diagnostics;
|
}
|
|
public async Task LoadAsync(CancellationToken cancellationToken = default)
|
{
|
var document = await _configuration.LoadLayoutAsync(cancellationToken).ConfigureAwait(false);
|
lock (_gate)
|
{
|
_document = document;
|
}
|
}
|
|
public Task SaveAsync(CancellationToken cancellationToken = default)
|
{
|
LayoutDocument snapshot;
|
lock (_gate)
|
{
|
snapshot = _document;
|
}
|
|
return _configuration.SaveLayoutAsync(snapshot, cancellationToken);
|
}
|
|
public IReadOnlyList<WidgetLayout> GetAll()
|
{
|
lock (_gate)
|
{
|
return [.. _document.Instances];
|
}
|
}
|
|
public WidgetLayout? Get(WidgetInstanceId instanceId)
|
{
|
lock (_gate)
|
{
|
return _document.Instances.FirstOrDefault(instance => instance.InstanceId == instanceId);
|
}
|
}
|
|
public WidgetLayout CreateFromPlugin(PluginDescriptor plugin, MonitorId monitorId)
|
{
|
if (plugin.Type != PluginType.Widget)
|
{
|
throw new InvalidOperationException("Only widget plugins can create widget layouts.");
|
}
|
|
var layout = new WidgetLayout
|
{
|
InstanceId = new WidgetInstanceId($"{plugin.Id.Value}-{Guid.NewGuid():N}"),
|
PluginId = plugin.Id,
|
MonitorId = monitorId,
|
Bounds = new RectD(
|
plugin.Manifest.DefaultLayout.X,
|
plugin.Manifest.DefaultLayout.Y,
|
Math.Max(MinWidth, plugin.Manifest.DefaultLayout.Width),
|
Math.Max(MinHeight, plugin.Manifest.DefaultLayout.Height)),
|
IsLocked = plugin.Manifest.DefaultLayout.Locked,
|
ClickThrough = plugin.Manifest.DefaultLayout.ClickThrough,
|
Opacity = Clamp(plugin.Manifest.DefaultLayout.Opacity, MinOpacity, MaxOpacity),
|
Scale = Clamp(plugin.Manifest.DefaultLayout.Scale, MinScale, MaxScale),
|
DisplayLayer = plugin.Manifest.DefaultLayout.DisplayLayer
|
};
|
|
lock (_gate)
|
{
|
_document.Instances.Add(layout);
|
}
|
|
return layout;
|
}
|
|
public OperationResult<WidgetLayout> Move(WidgetInstanceId instanceId, PointD position)
|
{
|
return Mutate(instanceId, layout => layout with
|
{
|
Bounds = layout.Bounds with { X = position.X, Y = position.Y }
|
});
|
}
|
|
public OperationResult<WidgetLayout> Resize(WidgetInstanceId instanceId, SizeD size)
|
{
|
return Mutate(instanceId, layout => layout with
|
{
|
Bounds = layout.Bounds with { Width = size.Width, Height = size.Height }
|
});
|
}
|
|
public OperationResult<WidgetLayout> Update(WidgetInstanceId instanceId, WidgetLayoutPatch patch)
|
{
|
return Mutate(instanceId, layout => layout with
|
{
|
Bounds = patch.Bounds ?? layout.Bounds,
|
MonitorId = patch.MonitorId ?? layout.MonitorId,
|
IsVisible = patch.IsVisible ?? layout.IsVisible,
|
IsLocked = patch.IsLocked ?? layout.IsLocked,
|
Opacity = patch.Opacity ?? layout.Opacity,
|
ClickThrough = patch.ClickThrough ?? layout.ClickThrough,
|
Scale = patch.Scale ?? layout.Scale,
|
DisplayLayer = patch.DisplayLayer ?? layout.DisplayLayer
|
}, allowLocked: IsUnlockPatch(patch));
|
}
|
|
public IReadOnlyList<WidgetLayout> ReconcileMonitors(IReadOnlyList<MonitorInfo> monitors)
|
{
|
if (monitors.Count == 0)
|
{
|
return GetAll();
|
}
|
|
var primary = monitors.FirstOrDefault(monitor => monitor.IsPrimary) ?? monitors[0];
|
var byId = monitors.ToDictionary(monitor => monitor.Id, monitor => monitor);
|
lock (_gate)
|
{
|
for (var i = 0; i < _document.Instances.Count; i++)
|
{
|
var layout = _document.Instances[i];
|
var monitor = byId.GetValueOrDefault(layout.MonitorId);
|
if (monitor is null)
|
{
|
var migrated = MigrateToPrimary(layout, primary);
|
_document.Instances[i] = migrated;
|
_diagnostics.Record(
|
DiagnosticSeverity.Info,
|
"LayoutReconciled",
|
"Widget layout migrated to primary monitor after monitor topology changed.",
|
new Dictionary<string, string>
|
{
|
["instanceId"] = layout.InstanceId.Value,
|
["monitorId"] = layout.MonitorId.Value,
|
["targetMonitorId"] = primary.Id.Value
|
});
|
continue;
|
}
|
|
var scaled = ScaleToWorkArea(layout, monitor);
|
var constrained = Constrain(scaled, monitor);
|
if (constrained != layout)
|
{
|
_document.Instances[i] = constrained;
|
}
|
}
|
|
_document.Monitors.Add(new MonitorSnapshot
|
{
|
CapturedAt = DateTimeOffset.UtcNow,
|
Monitors = [.. monitors]
|
});
|
while (_document.Monitors.Count > 5)
|
{
|
_document.Monitors.RemoveAt(0);
|
}
|
|
return [.. _document.Instances];
|
}
|
}
|
|
private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update, bool allowLocked = false)
|
{
|
lock (_gate)
|
{
|
var index = _document.Instances.FindIndex(instance => instance.InstanceId == instanceId);
|
if (index < 0)
|
{
|
return OperationResult<WidgetLayout>.Failure("WidgetLayoutNotFound", $"Widget layout {instanceId} was not found.");
|
}
|
|
var current = _document.Instances[index];
|
if (current.IsLocked && !allowLocked)
|
{
|
return OperationResult<WidgetLayout>.Failure("WidgetLayoutLocked", $"Widget layout {instanceId} is locked.");
|
}
|
|
var updated = ApplyScalarConstraints(update(current));
|
var monitor = FindLatestMonitor(updated.MonitorId);
|
if (monitor is not null)
|
{
|
updated = Constrain(updated, monitor);
|
}
|
|
_document.Instances[index] = updated;
|
return OperationResult<WidgetLayout>.Success(updated);
|
}
|
}
|
|
private MonitorInfo? FindLatestMonitor(MonitorId monitorId)
|
{
|
var latest = _document.Monitors.OrderByDescending(snapshot => snapshot.CapturedAt).FirstOrDefault();
|
return latest?.Monitors.FirstOrDefault(monitor => monitor.Id == monitorId);
|
}
|
|
private static WidgetLayout ApplyScalarConstraints(WidgetLayout layout)
|
{
|
return layout with
|
{
|
Bounds = layout.Bounds with
|
{
|
Width = Math.Max(MinWidth, layout.Bounds.Width),
|
Height = Math.Max(MinHeight, layout.Bounds.Height)
|
},
|
Scale = Clamp(layout.Scale, MinScale, MaxScale),
|
Opacity = Clamp(layout.Opacity, MinOpacity, MaxOpacity)
|
};
|
}
|
|
private static WidgetLayout Constrain(WidgetLayout layout, MonitorInfo monitor)
|
{
|
var work = monitor.WorkArea;
|
var width = Clamp(layout.Bounds.Width, MinWidth, Math.Max(MinWidth, work.Width));
|
var height = Clamp(layout.Bounds.Height, MinHeight, Math.Max(MinHeight, work.Height));
|
var minX = work.X - width + MinVisibleDip;
|
var maxX = work.Right - MinVisibleDip;
|
var minY = work.Y - height + MinVisibleDip;
|
var maxY = work.Bottom - MinVisibleDip;
|
|
return ApplyScalarConstraints(layout with
|
{
|
MonitorId = monitor.Id,
|
Bounds = new RectD(
|
Clamp(layout.Bounds.X, minX, maxX),
|
Clamp(layout.Bounds.Y, minY, maxY),
|
width,
|
height)
|
});
|
}
|
|
private static WidgetLayout CenterInMonitor(WidgetLayout layout, MonitorInfo monitor)
|
{
|
var constrained = ApplyScalarConstraints(layout);
|
var work = monitor.WorkArea;
|
var width = Math.Min(constrained.Bounds.Width, work.Width);
|
var height = Math.Min(constrained.Bounds.Height, work.Height);
|
return constrained with
|
{
|
MonitorId = monitor.Id,
|
Bounds = new RectD(
|
work.X + (work.Width - width) / 2,
|
work.Y + (work.Height - height) / 2,
|
width,
|
height)
|
};
|
}
|
|
private WidgetLayout MigrateToPrimary(WidgetLayout layout, MonitorInfo primary)
|
{
|
var previousPrimary = _document.Monitors
|
.OrderByDescending(snapshot => snapshot.CapturedAt)
|
.SelectMany(snapshot => snapshot.Monitors)
|
.FirstOrDefault(m => m.IsPrimary);
|
|
if (previousPrimary is null || previousPrimary.WorkArea.Width <= 0 || previousPrimary.WorkArea.Height <= 0)
|
{
|
return layout with { MonitorId = primary.Id };
|
}
|
|
var scaleX = primary.WorkArea.Width / previousPrimary.WorkArea.Width;
|
var scaleY = primary.WorkArea.Height / previousPrimary.WorkArea.Height;
|
var relX = (layout.Bounds.X - previousPrimary.WorkArea.X) / previousPrimary.WorkArea.Width;
|
var relY = (layout.Bounds.Y - previousPrimary.WorkArea.Y) / previousPrimary.WorkArea.Height;
|
|
return ApplyScalarConstraints(layout with
|
{
|
MonitorId = primary.Id,
|
Bounds = new RectD(
|
primary.WorkArea.X + relX * primary.WorkArea.Width,
|
primary.WorkArea.Y + relY * primary.WorkArea.Height,
|
layout.Bounds.Width * scaleX,
|
layout.Bounds.Height * scaleY)
|
});
|
}
|
|
private WidgetLayout ScaleToWorkArea(WidgetLayout layout, MonitorInfo current)
|
{
|
var previous = _document.Monitors
|
.OrderByDescending(snapshot => snapshot.CapturedAt)
|
.SelectMany(snapshot => snapshot.Monitors)
|
.FirstOrDefault(m => m.Id == current.Id);
|
|
if (previous is null || previous.WorkArea == current.WorkArea ||
|
previous.WorkArea.Width <= 0 || previous.WorkArea.Height <= 0)
|
{
|
return layout;
|
}
|
|
var scaleX = current.WorkArea.Width / previous.WorkArea.Width;
|
var scaleY = current.WorkArea.Height / previous.WorkArea.Height;
|
var relX = (layout.Bounds.X - previous.WorkArea.X) / previous.WorkArea.Width;
|
var relY = (layout.Bounds.Y - previous.WorkArea.Y) / previous.WorkArea.Height;
|
|
return layout with
|
{
|
Bounds = new RectD(
|
current.WorkArea.X + relX * current.WorkArea.Width,
|
current.WorkArea.Y + relY * current.WorkArea.Height,
|
layout.Bounds.Width * scaleX,
|
layout.Bounds.Height * scaleY)
|
};
|
}
|
|
private static double Clamp(double value, double min, double max)
|
=> Math.Min(Math.Max(value, min), max);
|
|
private static bool IsUnlockPatch(WidgetLayoutPatch patch)
|
=> patch.IsLocked == false &&
|
patch.Bounds is null &&
|
patch.MonitorId is null &&
|
patch.IsVisible is null &&
|
patch.Opacity is null &&
|
patch.ClickThrough is null &&
|
patch.Scale is null &&
|
patch.DisplayLayer is null;
|
}
|