forked from microsoft/Windows-appsample-photo-lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DetailPage.xaml.cs
347 lines (313 loc) · 13.3 KB
/
DetailPage.xaml.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
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Composition;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
namespace PhotoLab
{
public sealed partial class DetailPage : Page
{
ImageFileInfo item;
Compositor compositor;
CompositionEffectBrush combinedBrush;
CultureInfo culture = CultureInfo.CurrentCulture;
ContrastEffect contrastEffect;
ExposureEffect exposureEffect;
TemperatureAndTintEffect temperatureAndTintEffect;
GaussianBlurEffect graphicsEffect;
SaturationEffect saturationEffect;
bool editingInitialized = false;
bool canNavigateWithUnsavedChanges = false;
public DetailPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
item = e.Parameter as ImageFileInfo;
canNavigateWithUnsavedChanges = false;
ResetEffects();
if (item != null)
{
item.PropertyChanged += (s, e2) => UpdateEffectBrush(e2.PropertyName);
targetImage.Source = item.ImageSource;
ConnectedAnimation imageAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("itemAnimation");
if (imageAnimation != null)
{
imageAnimation.Completed += (s, e_) =>
{
MainImage.Source = item.ImageSource;
targetImage.Source = null;
};
imageAnimation.TryStart(targetImage);
}
}
else
{
// error
}
if (this.Frame.CanGoBack)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}
else
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
// If the photo has unsaved changes, we want to show a dialog
// that warns the user before the navigation happens
// To give the user a chance to view the dialog and respond,
// we go ahead and cancel the navigation.
// If the user wants to leave the page, we restart the
// navigation. We use the canNavigateWithUnsavedChanges field to
// track whether the user has been asked.
if (item.NeedsSaved && !canNavigateWithUnsavedChanges)
{
// The item has unsaved changes and we haven't shown the
// dialog yet. Cancel navigation and show the dialog.
e.Cancel = true;
ShowSaveDialog(e);
}
else
{
canNavigateWithUnsavedChanges = false;
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("backAnimation", MainImage);
base.OnNavigatingFrom(e);
}
}
/// <summary>
/// Gives users a chance to save the image before navigating
/// to a different page.
/// </summary>
private async void ShowSaveDialog(NavigatingCancelEventArgs e)
{
ContentDialog saveDialog = new ContentDialog()
{
Title = "Unsaved changes",
Content = "You have unsaved changes that will be lost if you leave this page.",
PrimaryButtonText = "Leave this page",
SecondaryButtonText = "Stay"
};
ContentDialogResult result = await saveDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
// The user decided to leave the page. Restart
// the navigation attempt.
canNavigateWithUnsavedChanges = true;
Frame.Navigate(e.SourcePageType, e.Parameter);
}
}
private void ZoomSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (MainImageScroller != null)
{
MainImageScroller.ChangeView(null, null, (float)e.NewValue);
}
}
private void MainImageScroller_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
ZoomSlider.Value = ((ScrollViewer)sender).ZoomFactor;
}
private void FitToScreen()
{
var zoomFactor = (float)Math.Min(MainImageScroller.ActualWidth / item.ImageSource.PixelWidth,
MainImageScroller.ActualHeight / item.ImageSource.PixelHeight);
MainImageScroller.ChangeView(null, null, zoomFactor);
}
private void ShowActualSize()
{
MainImageScroller.ChangeView(null, null, 1);
}
private void UpdateZoomState()
{
if (MainImageScroller.ZoomFactor == 1)
{
FitToScreen();
}
else
{
ShowActualSize();
}
}
private void InitializeEffects()
{
saturationEffect = new SaturationEffect()
{
Name = "SaturationEffect",
Saturation = item.Saturation,
Source = new CompositionEffectSourceParameter("Backdrop")
};
contrastEffect = new ContrastEffect()
{
Name = "ContrastEffect",
Contrast = item.Contrast,
Source = saturationEffect
};
exposureEffect = new ExposureEffect()
{
Name = "ExposureEffect",
Source = contrastEffect,
Exposure = item.Exposure,
};
temperatureAndTintEffect = new TemperatureAndTintEffect()
{
Name = "TemperatureAndTintEffect",
Source = exposureEffect,
Temperature = item.Temperature,
Tint = item.Tint
};
graphicsEffect = new GaussianBlurEffect()
{
Name = "Blur",
Source = temperatureAndTintEffect,
BlurAmount = item.Blur,
BorderMode = EffectBorderMode.Hard,
};
}
private void InitializeCompositor()
{
compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
InitializeEffects();
MainImage.Source = item.ImageSource;
MainImage.InvalidateArrange();
var destinationBrush = compositor.CreateBackdropBrush();
var graphicsEffectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] {
"SaturationEffect.Saturation", "ExposureEffect.Exposure", "Blur.BlurAmount",
"TemperatureAndTintEffect.Temperature", "TemperatureAndTintEffect.Tint",
"ContrastEffect.Contrast" });
combinedBrush = graphicsEffectFactory.CreateBrush();
combinedBrush.SetSourceParameter("Backdrop", destinationBrush);
var effectSprite = compositor.CreateSpriteVisual();
effectSprite.Size = new Vector2((float)item.ImageSource.PixelWidth, (float)item.ImageSource.PixelHeight);
effectSprite.Brush = combinedBrush;
ElementCompositionPreview.SetElementChildVisual(MainImage, effectSprite);
editingInitialized = true;
}
private void ToggleEditState()
{
if (MainSplitView.IsPaneOpen)
{
MainSplitView.IsPaneOpen = false;
}
else
{
if (!editingInitialized)
{
InitializeCompositor();
}
MainSplitView.IsPaneOpen = true;
}
}
private void UpdateEffectBrush(string propertyName)
{
void update(string effectName, float effectValue) =>
combinedBrush?.Properties.InsertScalar(effectName, effectValue);
switch (propertyName)
{
case nameof(item.Exposure): update("ExposureEffect.Exposure", item.Exposure); break;
case nameof(item.Temperature): update("TemperatureAndTintEffect.Temperature", item.Temperature); break;
case nameof(item.Tint): update("TemperatureAndTintEffect.Tint", item.Tint); break;
case nameof(item.Contrast): update("ContrastEffect.Contrast", item.Contrast); break;
case nameof(item.Saturation): update("SaturationEffect.Saturation", item.Saturation); break;
case nameof(item.Blur): update("Blur.BlurAmount", item.Blur); break;
default: break;
}
}
private async void ExportImage()
{
CanvasDevice device = CanvasDevice.GetSharedDevice();
using (CanvasRenderTarget offscreen = new CanvasRenderTarget(
device, item.ImageSource.PixelWidth, item.ImageSource.PixelHeight, 96))
{
using (IRandomAccessStream stream = await item.ImageFile.OpenReadAsync())
using (CanvasBitmap image = await CanvasBitmap.LoadAsync(offscreen, stream, 96))
{
saturationEffect.Source = image;
using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
{
ds.Clear(Windows.UI.Colors.Black);
// Need to copy the value of each effect setting.
contrastEffect.Contrast = item.Contrast;
exposureEffect.Exposure = item.Exposure;
temperatureAndTintEffect.Temperature = item.Temperature;
temperatureAndTintEffect.Tint = item.Tint;
saturationEffect.Saturation = item.Saturation;
graphicsEffect.BlurAmount = item.Blur;
ds.DrawImage(graphicsEffect);
}
var fileSavePicker = new FileSavePicker()
{
SuggestedSaveFile = item.ImageFile
};
fileSavePicker.FileTypeChoices.Add("JPEG files", new List<string>() { ".jpg" });
var outputFile = await fileSavePicker.PickSaveFileAsync();
if (outputFile != null)
{
using (IRandomAccessStream outStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
await offscreen.SaveAsync(outStream, CanvasBitmapFileFormat.Jpeg);
}
ResetEffects();
var newItem = await MainPage.LoadImageInfo(outputFile);
if (outputFile.Path == item.ImageFile.Path)
{
item.ImageSource = newItem.ImageSource;
}
else
{
item = newItem;
}
MainImage.Source = item.ImageSource;
}
}
}
}
private void ResetEffects()
{
item.Exposure =
item.Blur =
item.Tint =
item.Temperature =
item.Contrast = 0;
item.Saturation = 1;
}
}
}