-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDrawingHelperTests.cs
More file actions
326 lines (290 loc) · 13.7 KB
/
Copy pathDrawingHelperTests.cs
File metadata and controls
326 lines (290 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using FancyMouse.Common.Helpers;
using FancyMouse.Drawing.Helpers;
using FancyMouse.Drawing.Screens;
using FancyMouse.Models.Display;
using FancyMouse.Models.Drawing;
using FancyMouse.Models.Styles;
namespace FancyMouse.Common.UnitTests.Helpers;
public static class DrawingHelperTests
{
[TestClass]
public sealed class GetPreviewLayoutTests
{
public sealed class TestCase
{
public TestCase(PreviewStyle previewStyle, DisplayInfo displayInfo, ScreenInfo activatedScreen, PointInfo activatedLocation, string desktopImageFilename, string expectedImageFilename)
{
this.PreviewStyle = previewStyle;
this.DisplayInfo = displayInfo;
this.ActivatedScreen = activatedScreen;
this.ActivatedLocation = activatedLocation;
this.DesktopImageFilename = desktopImageFilename;
this.ExpectedImageFilename = expectedImageFilename;
}
public PreviewStyle PreviewStyle { get; }
public DisplayInfo DisplayInfo { get; }
public ScreenInfo ActivatedScreen { get; }
public PointInfo ActivatedLocation { get; }
public string DesktopImageFilename { get; }
public string ExpectedImageFilename { get; }
}
public static IEnumerable<object[]> GetTestCases()
{
// colors like "SystemColors.Highlight" can change between versions of windows,
// so we'll use hard-coded colors instead to reduce false test failures
var systemHighlight = Color.FromArgb(0, 120, 215);
var previewStyle = StyleHelper.BezelledPreviewStyle;
previewStyle = new(
canvasSize: previewStyle.CanvasSize,
canvasStyle: new(
marginStyle: previewStyle.CanvasStyle.MarginStyle,
borderStyle: previewStyle.CanvasStyle.BorderStyle.WithColor(systemHighlight),
paddingStyle: previewStyle.CanvasStyle.PaddingStyle,
backgroundStyle: previewStyle.CanvasStyle.BackgroundStyle
),
screenStyle: previewStyle.ScreenStyle,
extraColors: previewStyle.ExtraColors
);
// 4-grid
var displayInfo = new DisplayInfo(
devices: new DeviceInfo[]
{
new(
hostname: "localhost",
localhost: true,
screens: new List<ScreenInfo>
{
new(
handle: 0,
primary: true,
displayArea: new(0, 0, 500, 500),
workingArea: new(0, 0, 500, 500)),
new(
handle: 0,
primary: false,
displayArea: new(500, 0, 500, 500),
workingArea: new(500, 0, 500, 500)),
new(
handle: 0,
primary: false,
displayArea: new(500, 500, 500, 500),
workingArea: new(500, 500, 500, 500)),
new(
handle: 0,
primary: false,
displayArea: new(0, 500, 500, 500),
workingArea: new(0, 500, 500, 500)),
}
),
});
yield return new object[]
{
new TestCase(
previewStyle: previewStyle,
displayInfo: displayInfo,
activatedScreen: displayInfo.Devices[0].Screens[0],
activatedLocation: new(x: 50, y: 50),
desktopImageFilename: "_test-4grid-desktop.png",
expectedImageFilename: "_test-4grid-expected.png"),
};
// win 11
displayInfo = new(
devices: new DeviceInfo[]
{
new(
hostname: "localhost",
localhost: true,
screens: new List<ScreenInfo>
{
new(
handle: 0,
primary: true,
displayArea: new(5120, 349, 1920, 1080),
workingArea: new(5120, 349, 1920, 1080)),
new(
handle: 0,
primary: false,
displayArea: new(0, 0, 5120, 1440),
workingArea: new(0, 0, 5120, 1440)),
}
),
}
);
yield return new object[]
{
new TestCase(
previewStyle: previewStyle,
displayInfo: displayInfo,
activatedScreen: displayInfo.Devices[0].Screens[0],
activatedLocation: new(x: 50, y: 50),
desktopImageFilename: "_test-win11-desktop.png",
expectedImageFilename: "_test-win11-expected.png"),
};
}
[TestMethod]
[DynamicData(nameof(GetTestCases))]
public async Task RunTestCases(TestCase data)
{
// load the fake desktop image
using var desktopImage = DrawingHelperTests.LoadImageResource(data.DesktopImageFilename);
var formLayout = LayoutHelper.GetFormLayout(
previewStyle: data.PreviewStyle,
displayInfo: data.DisplayInfo,
activatedScreen: data.ActivatedScreen,
activatedLocation: data.ActivatedLocation);
var imageCopyServices = formLayout.CanvasLayout.DeviceLayouts
.Select(
deviceLayout => (IImageRegionCopyService)new StaticImageRegionCopyService(desktopImage))
.ToList();
// draw the preview image
var logger = NLog.LogManager.CreateNullLogger();
using var actual = await DrawingHelper.RenderPreviewAsync(logger, formLayout.CanvasLayout, data.ActivatedScreen, imageCopyServices);
// save the actual image so we can pick it up as a build artifact
var actualFilename = Path.GetFileNameWithoutExtension(data.ExpectedImageFilename) + "_actual" + Path.GetExtension(data.ExpectedImageFilename);
actual.Save(actualFilename, ImageFormat.Png);
// load the expected image
var expected = DrawingHelperTests.LoadImageResource(data.ExpectedImageFilename);
// save the actual image so we can pick it up as a build artifact
var expectedFilename = Path.GetFileNameWithoutExtension(data.ExpectedImageFilename) + "_expected" + Path.GetExtension(data.ExpectedImageFilename);
expected.Save(expectedFilename, ImageFormat.Png);
// compare the images
AssertImagesEqual(expected, actual);
}
private static Bitmap LoadImageResource(string filename)
{
var referenceType = typeof(DrawingHelperTests);
var resourceAssembly = referenceType.Assembly;
var resourcePrefix = referenceType.Namespace;
var resourceName = $"{resourcePrefix}.{filename.Replace("/", ".")}";
var resourceNames = resourceAssembly.GetManifestResourceNames();
if (!resourceNames.Contains(resourceName))
{
var message = string.Join(
Environment.NewLine,
new List<string>([
$"Embedded resource '{resourceName}' does not exist.",
string.Empty,
"Valid resource names are:",
string.Empty])
.Concat(resourceNames));
throw new InvalidOperationException(message);
}
var stream = resourceAssembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException();
var image = (Bitmap)Image.FromStream(stream);
return image;
}
/// <summary>
/// Naive / brute force image comparison - we can optimize this later :-)
/// </summary>
private static void AssertImagesEqual(Bitmap expected, Bitmap actual)
{
Assert.AreEqual(
expected.Width,
actual.Width,
$"expected width: {expected.Width}, actual width: {actual.Width}");
Assert.AreEqual(
expected.Height,
actual.Height,
$"expected height: {expected.Height}, actual height: {actual.Height}");
for (var y = 0; y < expected.Height; y++)
{
for (var x = 0; x < expected.Width; x++)
{
var expectedPixel = expected.GetPixel(x, y);
var actualPixel = actual.GetPixel(x, y);
// allow a small tolerance for rounding differences in gdi
Assert.IsTrue(
(Math.Abs(expectedPixel.A - actualPixel.A) <= 1) &&
(Math.Abs(expectedPixel.R - actualPixel.R) <= 1) &&
(Math.Abs(expectedPixel.G - actualPixel.G) <= 1) &&
(Math.Abs(expectedPixel.B - actualPixel.B) <= 1),
$"images differ at pixel ({x}, {y}) - expected: {expectedPixel}, actual: {actualPixel}");
}
}
}
}
[TestClass]
public sealed class RenderPerformanceTests
{
[TestMethod]
public async Task MeasureRenderPreviewAsync()
{
const int iterations = 10;
var logger = NLog.LogManager.CreateNullLogger();
var systemHighlight = Color.FromArgb(0, 120, 215);
var previewStyle = StyleHelper.BezelledPreviewStyle;
previewStyle = new(
canvasSize: previewStyle.CanvasSize,
canvasStyle: new(
marginStyle: previewStyle.CanvasStyle.MarginStyle,
borderStyle: previewStyle.CanvasStyle.BorderStyle.WithColor(systemHighlight),
paddingStyle: previewStyle.CanvasStyle.PaddingStyle,
backgroundStyle: previewStyle.CanvasStyle.BackgroundStyle
),
screenStyle: previewStyle.ScreenStyle,
extraColors: previewStyle.ExtraColors
);
var displayInfo = new DisplayInfo(
devices: new DeviceInfo[]
{
new(
hostname: "localhost",
localhost: true,
screens: new List<ScreenInfo>
{
new(handle: 0, primary: true, displayArea: new(5120, 349, 1920, 1080), workingArea: new(5120, 349, 1920, 1080)),
new(handle: 0, primary: false, displayArea: new(0, 0, 5120, 1440), workingArea: new(0, 0, 5120, 1440)),
}
),
});
var activatedScreen = displayInfo.Devices[0].Screens[0];
var activatedLocation = new PointInfo(x: 50, y: 50);
using var desktopImage = DrawingHelperTests.LoadImageResource("Helpers/_test-win11-desktop.png");
async Task<Bitmap> Render()
{
var formLayout = LayoutHelper.GetFormLayout(
previewStyle: previewStyle,
displayInfo: displayInfo,
activatedScreen: activatedScreen,
activatedLocation: activatedLocation);
var imageCopyServices = formLayout.CanvasLayout.DeviceLayouts
.Select(_ => (IImageRegionCopyService)new StaticImageRegionCopyService(desktopImage))
.ToList();
return await DrawingHelper.RenderPreviewAsync(logger, formLayout.CanvasLayout, activatedScreen, imageCopyServices);
}
// warm-up — discarded to allow any lazy initialisation to complete
using (var warmup = await Render())
{
}
var elapsed = new long[iterations];
for (var i = 0; i < iterations; i++)
{
var sw = Stopwatch.StartNew();
using var image = await Render();
elapsed[i] = sw.ElapsedMilliseconds;
}
Console.WriteLine($"RenderPreviewAsync ({iterations} iterations, win11 layout):");
Console.WriteLine($" min={elapsed.Min()}ms avg={elapsed.Average():F1}ms max={elapsed.Max()}ms");
}
}
private static Bitmap LoadImageResource(string filename)
{
var assembly = Assembly.GetExecutingAssembly();
var assemblyName = new AssemblyName(assembly.FullName ?? throw new InvalidOperationException());
var resourceName = $"{assemblyName.Name}.{filename.Replace("/", ".")}";
var resourceNames = assembly.GetManifestResourceNames();
if (!resourceNames.Contains(resourceName))
{
throw new InvalidOperationException($"Embedded resource '{resourceName}' does not exist.");
}
var stream = assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException();
var image = (Bitmap)Image.FromStream(stream);
return image;
}
}