From 6673c882eefd5232198f8e8341e5ba14e7d12a35 Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Sat, 7 Nov 2015 17:16:42 +0000 Subject: [PATCH] Add helpers for truncating long labels. --- OpenRA.Game/Widgets/WidgetUtils.cs | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/OpenRA.Game/Widgets/WidgetUtils.cs b/OpenRA.Game/Widgets/WidgetUtils.cs index ac8c1ac7b2..95f467458e 100644 --- a/OpenRA.Game/Widgets/WidgetUtils.cs +++ b/OpenRA.Game/Widgets/WidgetUtils.cs @@ -227,6 +227,22 @@ namespace OpenRA.Widgets return text; } + public static string TruncateText(string text, int width, SpriteFont font) + { + var trimmedWidth = font.Measure(text).X; + if (trimmedWidth <= width) + return text; + + var trimmed = text; + while (trimmedWidth > width && trimmed.Length > 3) + { + trimmed = text.Substring(0, trimmed.Length - 4) + "..."; + trimmedWidth = font.Measure(trimmed).X; + } + + return trimmed; + } + public static Action Once(Action a) { return () => { if (a != null) { a(); a = null; } }; } public static string ChooseInitialMap(string initialUid) @@ -242,6 +258,32 @@ namespace OpenRA.Widgets } } + public class CachedTransform + { + readonly Func transform; + + bool initialized; + T lastInput; + U lastOutput; + + public CachedTransform(Func transform) + { + this.transform = transform; + } + + public U Update(T input) + { + if (initialized && ((input == null && lastInput == null) || input.Equals(lastInput))) + return lastOutput; + + lastInput = input; + lastOutput = transform(input); + initialized = true; + + return lastOutput; + } + } + [Flags] public enum PanelSides {