-
-
Notifications
You must be signed in to change notification settings - Fork 466
/
HostBackdropAcrylicBrush.cs
355 lines (308 loc) · 14.1 KB
/
HostBackdropAcrylicBrush.cs
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2019-2024, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Notepads.Brushes
{
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.DirectX;
using Windows.Graphics.Display;
using Windows.Graphics.Effects;
using Windows.Graphics.Imaging;
using Windows.System;
using Windows.System.Power;
using Windows.UI;
using Windows.UI.Composition;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Microsoft.AppCenter.Analytics;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI.Composition;
using Controls.Helpers;
public sealed class HostBackdropAcrylicBrush : XamlCompositionBrushBase, IDisposable
{
private static readonly DependencyProperty TintOpacityProperty = DependencyProperty.Register(
nameof(TintOpacity),
typeof(float),
typeof(HostBackdropAcrylicBrush),
new PropertyMetadata(0.0f, OnTintOpacityChanged)
);
public float TintOpacity
{
get => (float)GetValue(TintOpacityProperty);
set => SetValue(TintOpacityProperty, value);
}
private static void OnTintOpacityChanged(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs args)
{
if (!(dependencyObject is HostBackdropAcrylicBrush brush)) return;
if (brush.CompositionBrush is CompositionEffectBrush)
{
TintOpacityToArithmeticCompositeEffectSourceAmount((float)args.NewValue,
_acrylicTintOpacityMinThreshold,
out var source1Amount,
out var source2Amount);
brush.CompositionBrush?.Properties.InsertScalar("LuminosityBlender.Source1Amount", source1Amount);
brush.CompositionBrush?.Properties.InsertScalar("LuminosityBlender.Source2Amount", source2Amount);
}
else if (brush.CompositionBrush is CompositionColorBrush)
{
// Do nothing since we are falling back to CompositionColorBrush here
// TintOpacity only applies to the CompositionEffectBrush we created
}
}
private static readonly DependencyProperty LuminosityColorProperty = DependencyProperty.Register(
nameof(LuminosityColor),
typeof(Color),
typeof(HostBackdropAcrylicBrush),
new PropertyMetadata(Colors.Transparent, OnLuminosityColorChanged)
);
public Color LuminosityColor
{
get => (Color)GetValue(LuminosityColorProperty);
set => SetValue(LuminosityColorProperty, value);
}
private static void OnLuminosityColorChanged(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs args)
{
if (!(dependencyObject is HostBackdropAcrylicBrush brush)) return;
switch (brush.CompositionBrush)
{
case CompositionEffectBrush _
when brush.CompositionBrush?.Properties.TryGetColor("LuminosityColor.Color", out var currentColor)
== CompositionGetValueStatus.Succeeded:
{
var easing = Window.Current.Compositor.CreateLinearEasingFunction();
var animation = Window.Current.Compositor.CreateColorKeyFrameAnimation();
animation.InsertKeyFrame(0.0f, currentColor);
animation.InsertKeyFrame(1.0f, (Color)args.NewValue, easing);
animation.Duration = TimeSpan.FromMilliseconds(167);
brush.CompositionBrush.StartAnimation("LuminosityColor.Color", animation);
break;
}
case CompositionEffectBrush _:
brush.CompositionBrush?.Properties.InsertColor("LuminosityColor.Color", (Color)args.NewValue);
break;
case CompositionColorBrush colorBrush:
colorBrush.Color = (Color)args.NewValue;
break;
}
}
public Uri NoiseTextureUri { get; set; }
private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1);
private readonly UISettings UISettings = new UISettings();
private const float _acrylicTintOpacityMinThreshold = 0.35f;
private readonly DispatcherQueue _dispatcherQueue;
private CompositionSurfaceBrush _noiseBrush;
public HostBackdropAcrylicBrush()
{
_dispatcherQueue = DispatcherQueue.GetForCurrentThread();
}
protected override async void OnConnected()
{
if (CompositionBrush == null)
{
await BuildInternalAsync();
}
base.OnConnected();
}
private async Task BuildInternalAsync()
{
await _semaphoreSlim.WaitAsync();
try
{
if (PowerManager.EnergySaverStatus == EnergySaverStatus.On || !UISettings.AdvancedEffectsEnabled)
{
CompositionBrush = Window.Current.Compositor.CreateColorBrush(LuminosityColor);
}
else
{
CompositionBrush = await BuildHostBackdropAcrylicBrushInternalAsync();
}
// Register energy saver event
PowerManager.EnergySaverStatusChanged -= OnEnergySaverStatusChanged;
PowerManager.EnergySaverStatusChanged += OnEnergySaverStatusChanged;
// Register system level transparency effects settings change event
UISettings.AdvancedEffectsEnabledChanged -= OnAdvancedEffectsEnabledChanged;
UISettings.AdvancedEffectsEnabledChanged += OnAdvancedEffectsEnabledChanged;
}
catch (Exception)
{
// Fallback to color brush if unable to create HostBackdropAcrylicBrush
CompositionBrush = Window.Current.Compositor.CreateColorBrush(LuminosityColor);
}
finally
{
_semaphoreSlim.Release();
}
}
private async void OnEnergySaverStatusChanged(object sender, object e)
{
await _dispatcherQueue.ExecuteOnUIThreadAsync(async () =>
{
await BuildInternalAsync();
});
}
private async void OnAdvancedEffectsEnabledChanged(UISettings sender, object args)
{
await _dispatcherQueue.ExecuteOnUIThreadAsync(async () =>
{
await BuildInternalAsync();
});
}
protected override async void OnDisconnected()
{
await _semaphoreSlim.WaitAsync();
if (CompositionBrush != null)
{
PowerManager.EnergySaverStatusChanged -= OnEnergySaverStatusChanged;
UISettings.AdvancedEffectsEnabledChanged -= OnAdvancedEffectsEnabledChanged;
CompositionBrush.Dispose();
CompositionBrush = null;
}
_semaphoreSlim.Release();
base.OnDisconnected();
}
private async Task<CompositionBrush> BuildHostBackdropAcrylicBrushInternalAsync()
{
int stage = 0;
try
{
stage = 1;
var luminosityColorEffect = new ColorSourceEffect()
{
Name = "LuminosityColor",
Color = LuminosityColor
};
TintOpacityToArithmeticCompositeEffectSourceAmount(TintOpacity, _acrylicTintOpacityMinThreshold,
out var source1Amount,
out var source2Amount);
stage = 2;
var luminosityBlendingEffect = new ArithmeticCompositeEffect
{
Name = "LuminosityBlender",
Source1 = new CompositionEffectSourceParameter("Backdrop"),
Source2 = luminosityColorEffect,
MultiplyAmount = 0,
Source1Amount = source1Amount,
Source2Amount = source2Amount,
Offset = 0
};
stage = 3;
var noiseBorderEffect = new BorderEffect()
{
ExtendX = CanvasEdgeBehavior.Wrap,
ExtendY = CanvasEdgeBehavior.Wrap,
Source = new CompositionEffectSourceParameter("Noise"),
};
stage = 4;
var noiseBlendingEffect = new BlendEffect()
{
Name = "NoiseBlender",
Mode = BlendEffectMode.Overlay,
Background = luminosityBlendingEffect,
Foreground = noiseBorderEffect
};
stage = 5;
_noiseBrush = _noiseBrush ?? await LoadImageBrushAsync(NoiseTextureUri);
IGraphicsEffect finalEffect;
if (_noiseBrush == null)
{
finalEffect = luminosityBlendingEffect;
}
else
{
finalEffect = noiseBlendingEffect;
}
stage = 6;
CompositionEffectFactory effectFactory = Window.Current.Compositor.CreateEffectFactory(finalEffect,
new[]
{
"LuminosityColor.Color",
"LuminosityBlender.Source1Amount",
"LuminosityBlender.Source2Amount"
});
stage = 7;
CompositionEffectBrush brush = effectFactory.CreateBrush();
stage = 8;
var hostBackdropBrush = Window.Current.Compositor.CreateHostBackdropBrush();
brush.SetSourceParameter("Backdrop", hostBackdropBrush);
stage = 9;
if (_noiseBrush != null)
{
brush.SetSourceParameter("Noise", _noiseBrush);
}
return brush;
}
catch (Exception ex)
{
Analytics.TrackEvent("FailedToBuildAcrylicBrushInternal",
new Dictionary<string, string>
{
{ "Exception", ex.ToString() },
{ "FailedAtStage", stage.ToString() },
});
throw; // rethrow here
}
}
private static async Task<CompositionSurfaceBrush> LoadImageBrushAsync(Uri textureUri)
{
try
{
using (CanvasDevice sharedDevice = CanvasDevice.GetSharedDevice())
{
DisplayInformation display = DisplayInformation.GetForCurrentView();
float dpi = display.LogicalDpi;
CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(sharedDevice, textureUri, dpi >= 96 ? dpi : 96);
CompositionGraphicsDevice device = CanvasComposition.CreateCompositionGraphicsDevice(Window.Current.Compositor, sharedDevice);
CompositionDrawingSurface surface = device.CreateDrawingSurface(default, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
Size size = bitmap.Size;
Size sizeInPixels = new Size(bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height);
CanvasComposition.Resize(surface, sizeInPixels);
using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface, new Rect(0, 0, sizeInPixels.Width, sizeInPixels.Height), dpi))
{
session.Clear(Color.FromArgb(0, 0, 0, 0));
session.DrawImage(bitmap, new Rect(0, 0, size.Width, size.Height), new Rect(0, 0, size.Width, size.Height));
session.EffectTileSize = new BitmapSize { Width = (uint)size.Width, Height = (uint)size.Height };
CompositionSurfaceBrush brush = surface.Compositor.CreateSurfaceBrush(surface);
brush.Stretch = CompositionStretch.None;
double pixels = display.RawPixelsPerViewPixel;
if (pixels > 1)
{
brush.Scale = new Vector2((float)(1 / pixels));
brush.BitmapInterpolationMode = CompositionBitmapInterpolationMode.NearestNeighbor;
}
return brush;
}
}
}
catch (Exception ex)
{
Analytics.TrackEvent("FailedToLoadImageBrush", new Dictionary<string, string> { { "Exception", ex.ToString() } });
return null;
}
}
private static void TintOpacityToArithmeticCompositeEffectSourceAmount(float tintOpacity, float minThreshold,
out float source1Amount, out float source2Amount)
{
minThreshold = Math.Clamp(minThreshold, 0, 1);
var adjustedTintOpacity = Math.Clamp(tintOpacity, 0, 1);
adjustedTintOpacity = ((1 - minThreshold) * adjustedTintOpacity) + minThreshold;
source1Amount = 1 - adjustedTintOpacity;
source2Amount = adjustedTintOpacity;
}
public void Dispose()
{
PowerManager.EnergySaverStatusChanged -= OnEnergySaverStatusChanged;
UISettings.AdvancedEffectsEnabledChanged -= OnAdvancedEffectsEnabledChanged;
_semaphoreSlim?.Dispose();
}
}
}