using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; using Titano.App.Infrastructure; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Sync; using Titano.Ui.Controls; namespace Titano.App.Server; /// Filter chips of the sync table (Server.html). public enum SyncFilter { All, LocalOnly, Remote, Conflicts, } /// What a row of the sync table offers. public enum SyncAction { Upload, OpenWithProxies, DownloadOriginals, SyncSettings, KeepMine, TakeServer, SaveBoth, GetExports, SendExports, Pause, Resume, } /// What the signed-in account may do (server permission bits). /// Send originals, settings and renders (upload and edit rights). /// Download originals (editors and render nodes). /// Change the server's copy of a sequence's settings, title, tags, rating and notes. public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit) { public static SyncRights Of(long permissions) => new( (permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0, (permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 0, (permissions & (long)Permissions.Edit) != 0); } /// The words, glyphs and actions of the sync table (BRIEF §12.7): plain functions of a . public static class SyncText { /// Resource keys of the settings and sequence fields a conflict can show, by JSON path (sections, then members). private static readonly Dictionary SettingKeys = new(StringComparer.OrdinalIgnoreCase) { ["sequence.title"] = "Server.Setting.Title", ["sequence.tags"] = "Server.Setting.Tags", ["sequence.rating"] = "Server.Setting.Rating", ["sequence.notes"] = "Server.Setting.Notes", ["timing.mode"] = "Server.Setting.TimingMode", ["timing.frameRate"] = "Server.Setting.FrameRate", ["timing.fitToSeconds"] = "Server.Setting.FitToDuration", ["timing.remapCurve"] = "Server.Setting.TimeRemap", ["exposure.deflicker"] = "Server.Setting.Deflicker", ["exposure.deflickerWindow"] = "Server.Setting.DeflickerWindow", ["exposure.deflickerStrength"] = "Server.Setting.DeflickerStrength", ["exposure.regions"] = "Server.Setting.Regions", ["exposure.holyGrail"] = "Server.Setting.HolyGrail", ["exposure.transitionLength"] = "Server.Setting.Transitions", ["exposure.whiteBalanceSmoothing"] = "Server.Setting.WhiteBalance", ["exposure.exposureOffsetEv"] = "Server.Setting.ExposureOffset", ["exposure.highlightKnee"] = "Server.Setting.HighlightKnee", ["motion.motionBlur"] = "Server.Setting.MotionBlur", ["motion.targetShutterAngle"] = "Server.Setting.ShutterAngle", ["motion.flowQuality"] = "Server.Setting.FlowQuality", ["motion.stabilize"] = "Server.Setting.Stabilize", ["motion.stabilizeSmoothing"] = "Server.Setting.StabilizeSmoothing", ["camera.crop"] = "Server.Setting.Crop", ["camera.aspect"] = "Server.Setting.Aspect", ["camera.offsetX"] = "Server.Setting.CameraOffset", ["camera.offsetY"] = "Server.Setting.CameraOffset", ["camera.keyframes"] = "Server.Setting.Keyframes", ["stack.mode"] = "Server.Setting.Stacking", ["stack.length"] = "Server.Setting.TrailLength", ["export.preset"] = "Server.Setting.ExportPreset", ["export.overrides"] = "Server.Setting.ExportValues", ["export.nameTemplate"] = "Server.Setting.OutputName", ["export.folder"] = "Server.Setting.ExportFolder", ["export.batch"] = "Server.Setting.Batch", ["excludedFrames"] = "Server.Setting.ExcludedFrames", ["heroFrame"] = "Server.Setting.HeroFrame", }; /// "originals · proxies", "proxies" (cached server proxies) or "—". public static string Local(SyncEntry entry) { if (entry.HasLocalOriginals) { return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0 ? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies")) : Loc.L("Server.Sync.Originals"); } return entry.Link is { ProxiesCached: > 0 } ? Loc.L("Server.Sync.Proxies") : Loc.L("Server.Sync.None"); } /// "originals · proxies · 3 exports", "46 % received" while uploading, or "—". public static string Server(SyncEntry entry) { if (entry.Transfer is { Kind: JobKind.UploadCommit, State: JobState.Running, ProgressTotal: > 0 } upload) return Loc.L("Server.Sync.Received", Formatting.Percent((double)upload.ProgressDone / upload.ProgressTotal)); if (entry.Link is not { } link) return Loc.L("Server.Sync.None"); var parts = new List(3) { Loc.L("Server.Sync.Originals") }; if (link.ServerHasProxies) parts.Add(Loc.L("Server.Sync.Proxies")); if (link.RenderCount > 0) parts.Add(Loc.Plural("Server.Sync.Exports", link.RenderCount)); return Join([.. parts]); } /// The State column: glyph kind, word and tooltip (never colour alone). public static (StatusKind Kind, string Text, string ToolTip) State(SyncEntry entry) { if (entry.Transfer is { } job) { var upload = job.Kind == JobKind.UploadCommit; return job.State switch { JobState.Paused => (StatusKind.Paused, Loc.L("Server.Sync.State.Paused"), Loc.L("Tooltips.Server.Sync.State.Paused")), JobState.Queued => (StatusKind.Queued, Loc.L("Server.Sync.State.Waiting"), Loc.L("Tooltips.Server.Sync.State.Waiting")), _ => (StatusKind.Running, Loc.L(upload ? "Server.Sync.State.Uploading" : "Server.Sync.State.Downloading"), Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")), }; } if (entry.Link?.Error is { } error) return (StatusKind.Warning, Loc.L("Server.Sync.State.Failed"), Loc.L("Tooltips.Server.Sync.State.Failed", error)); return entry.Status switch { SyncStatus.InSync => (StatusKind.Done, Loc.L("Server.Sync.State.InSync"), Loc.L("Tooltips.Server.Sync.State.InSync")), SyncStatus.LocalOnly => (StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly"), Loc.L("Tooltips.Server.Sync.State.LocalOnly")), SyncStatus.RemoteOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly"), Loc.L("Tooltips.Server.Sync.State.RemoteOnly")), SyncStatus.ProxiesOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.ProxiesOnly"), Loc.L("Tooltips.Server.Sync.State.ProxiesOnly")), SyncStatus.LocalAhead => (StatusKind.Synced, Loc.L("Server.Sync.State.LocalAhead"), Loc.L("Tooltips.Server.Sync.State.LocalAhead")), SyncStatus.ServerAhead => (StatusKind.Remote, Loc.L("Server.Sync.State.ServerAhead"), Loc.L("Tooltips.Server.Sync.State.ServerAhead")), _ => (StatusKind.Warning, Loc.L("Server.Sync.State.Conflict"), ConflictSummary(entry)), }; } /// One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2". public static string ConflictSummary(SyncEntry entry) { var lines = Conflict(entry, int.MaxValue); return lines.Count switch { 0 => Loc.L("Tooltips.Server.Sync.State.Conflict"), 1 => lines[0], _ => Loc.L("Server.Conflict.More", lines[0], Formatting.Count(lines.Count - 1)), }; } /// /// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the /// server", "Tags differ"), at most . /// public static IReadOnlyList Conflict(SyncEntry entry, int max) { if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return []; var lines = new List(); var shown = new HashSet(StringComparer.Ordinal); foreach (var difference in SyncRules.Differences(SyncPayload.Of(local), theirs, 64)) { var (key, field) = Setting(difference.Path); if (!shown.Add(key)) continue; var label = Loc.L(key); var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal); lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine && (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server ? Loc.L("Server.Conflict.Difference", label, mine, server) : Loc.L("Server.Conflict.Changed", label)); if (lines.Count == max) break; } return lines; } /// The row's buttons, in the order the mockup shows them. public static IReadOnlyList Actions(SyncEntry entry, SyncRights rights) { if (entry.Transfer is { } job) return job.State == JobState.Paused ? [SyncAction.Resume] : [SyncAction.Pause]; var actions = new List(3); switch (entry.Status) { case SyncStatus.LocalOnly when rights.CanUpload: actions.Add(SyncAction.Upload); break; case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly: actions.Add(SyncAction.OpenWithProxies); if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals); break; case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }: if (rights.CanUpload) actions.Add(SyncAction.Upload); break; case SyncStatus.ServerAhead when entry.Link is { MissingLocal: > 0 }: if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals); break; case SyncStatus.LocalAhead when rights.CanEdit: case SyncStatus.ServerAhead: actions.Add(SyncAction.SyncSettings); break; case SyncStatus.Conflict: if (rights.CanEdit) actions.Add(SyncAction.KeepMine); actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]); return actions; } // Renders travel on request once no original is waiting to go either way. if (entry is { Local: not null, Link: { MissingRemote: 0, MissingLocal: 0 } link }) { if (link.ExportsToGet > 0) actions.Add(SyncAction.GetExports); if (link.ExportsToSend > 0 && rights.CanUpload) actions.Add(SyncAction.SendExports); } return actions; } /// The bytes an action moves (for the tooltips). public static long Size(SyncEntry entry, SyncAction action) => action switch { SyncAction.Upload => entry.Local?.TotalBytes ?? 0, SyncAction.DownloadOriginals => entry.Link?.TotalBytes ?? 0, SyncAction.GetExports => entry.Link?.ExportsToGetBytes ?? 0, SyncAction.SendExports => entry.Link?.ExportsToSendBytes ?? 0, _ => 0, }; /// The tooltip of a row button: what it does and, for transfers, what it moves. public static string ToolTip(SyncEntry entry, SyncAction action) => action switch { SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))), SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))), SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))), _ => Loc.L("Tooltips.Server.Sync." + action), }; /// /// The chips sort by where the originals are: a sequence being transferred still counts as only on this PC (no server /// copy yet) or only on the server (no local originals yet), as the chip tooltips say. /// public static bool Matches(SyncEntry entry, SyncFilter filter, string search) => (filter switch { SyncFilter.LocalOnly => entry.Status == SyncStatus.LocalOnly || entry is { Status: SyncStatus.Transferring, Link: null }, SyncFilter.Remote => entry.Status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly || entry is { Status: SyncStatus.Transferring, HasLocalOriginals: false, Link: not null }, SyncFilter.Conflicts => entry.Status == SyncStatus.Conflict, _ => true, }) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase)); /// /// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an /// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value. /// private static (string Key, string? Field) Setting(string path) { var segments = path.Split('.'); for (var length = segments.Length; length > 0; length--) { if (SettingKeys.TryGetValue(string.Join('.', segments[..length]), out var key)) return (key, length < segments.Length ? segments[length] : null); } return ("Server.Setting.Other", segments[^1]); } /// A title, tags, rating or notes value as shown ("—" when empty). private static string Text(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") : Shorten(value); /// A side's value as shown ("41", "on", "auto"); null when it is not a single value worth printing. private static string? Value(string? json, string? field) { if (json is null) return field is null or "manual" ? Loc.L("Server.Sync.None") : null; if (field is not (null or "manual" or "autoValue" or "isAuto")) return null; JsonNode? node; try { node = JsonNode.Parse(json); } catch (JsonException) { return null; } if (field == "isAuto") return node is JsonValue v && v.TryGetValue(out var auto) ? Loc.L(auto ? "Server.Setting.Auto" : "Server.Setting.Manual") : null; return node switch { null => Loc.L("Server.Sync.None"), JsonValue value when value.TryGetValue(out var flag) => Loc.L(flag ? "Server.Setting.On" : "Server.Setting.Off"), JsonValue value when value.TryGetValue(out var number) => number.ToString("0.###", Loc.Culture), JsonValue value when value.TryGetValue(out var text) => Shorten(text), _ => null, }; } private static string Shorten(string text) => text.Length <= 40 ? text : string.Concat(text.AsSpan(0, 39), "…"); private static string Join(params string[] parts) => string.Join(" · ", parts); }