Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change Widget Pin flow to show preview images #2110

Merged
merged 3 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions CoreWidgetProvider/Widgets/SSHWalletWidget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public override void LoadContentData()
// Widget will remain in configuring state, waiting for config file path input.
if (string.IsNullOrWhiteSpace(ConfigFile))
{
ContentData = new JsonObject { { "configuring", true } }.ToJsonString();
ContentData = EmptyJson;
DataState = WidgetDataState.Okay;
return;
}
Expand Down Expand Up @@ -246,7 +246,7 @@ private void OnConfigFileRenamed(object sender, FileSystemEventArgs e)
UpdateWidget();
}

private JsonObject FillConfigurationData(bool hasConfiguration, string configFile, int numOfEntries = 0, bool configuring = true, string errorMessage = "")
private JsonObject FillConfigurationData(bool hasConfiguration, string configFile, int numOfEntries = 0, string errorMessage = "")
{
var configurationData = new JsonObject();

Expand All @@ -265,7 +265,6 @@ private JsonObject FillConfigurationData(bool hasConfiguration, string configFil
{ "numOfEntries", numOfEntries.ToString(CultureInfo.InvariantCulture) },
};

configurationData.Add("configuring", configuring);
configurationData.Add("hasConfiguration", hasConfiguration);
configurationData.Add("configuration", sshConfigData);
configurationData.Add("savedConfigFile", _savedConfigFile);
Expand Down Expand Up @@ -298,18 +297,18 @@ public override string GetConfiguration(string data)

var numberOfEntries = GetNumberOfHostEntries();

configurationData = FillConfigurationData(true, ConfigFile, numberOfEntries, false);
configurationData = FillConfigurationData(true, ConfigFile, numberOfEntries);
}
else
{
configurationData = FillConfigurationData(false, data, 0, true, Resources.GetResource(@"SSH_Widget_Template/ConfigFileNotFound", Logger()));
configurationData = FillConfigurationData(false, data, 0, Resources.GetResource(@"SSH_Widget_Template/ConfigFileNotFound", Logger()));
}
}
catch (Exception ex)
{
Log.Logger()?.ReportError(Name, ShortId, $"Failed getting configuration information for input config file path: {data}", ex);

configurationData = FillConfigurationData(false, data, 0, true, Resources.GetResource(@"SSH_Widget_Template/ErrorProcessingConfigFile", Logger()));
configurationData = FillConfigurationData(false, data, 0, Resources.GetResource(@"SSH_Widget_Template/ErrorProcessingConfigFile", Logger()));

return configurationData.ToString();
}
Expand Down Expand Up @@ -365,7 +364,7 @@ public override string GetData(WidgetPageState page)
{
WidgetPageState.Configure => GetConfiguration(ConfigFile),
WidgetPageState.Content => ContentData,
WidgetPageState.Loading => new JsonObject { { "configuring", true } }.ToJsonString(),
WidgetPageState.Loading => EmptyJson,

// In case of unknown state default to empty data
_ => EmptyJson,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@
{
"type": "ColumnSet",
"spacing": "ExtraLarge",
"$when": "${$root.savedConfigFile != \"\"}",
"columns": [
{
"type": "Column",
Expand All @@ -100,7 +99,8 @@
{
"type": "Action.Execute",
"title": "%Widget_Template_Button/Cancel%",
"verb": "Cancel"
"verb": "Cancel",
"isEnabled": "${$root.savedConfigFile != \"\"}"
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ public static IServiceCollection AddDashboard(this IServiceCollection services,
// View-models
services.AddSingleton<DashboardViewModel>();
services.AddTransient<DashboardBannerViewModel>();
services.AddTransient<AddWidgetViewModel>();

// Services
services.AddSingleton<IWidgetHostingService, WidgetHostingService>();
services.AddSingleton<IWidgetIconService, WidgetIconService>();
services.AddSingleton<IWidgetScreenshotService, WidgetScreenshotService>();
services.AddSingleton<IAdaptiveCardRenderingService, AdaptiveCardRenderingService>();

return services;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation and Contributors
// Licensed under the MIT license.

using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.Windows.Widgets.Hosts;

namespace DevHome.Dashboard.Services;

public interface IWidgetScreenshotService
{
public Task<BitmapImage> GetScreenshotFromCache(WidgetDefinition widgetDefinition, ElementTheme actualTheme);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright (c) Microsoft Corporation and Contributors
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.Windows.Widgets.Hosts;
using Windows.Storage.Streams;
using WinUIEx;

namespace DevHome.Dashboard.Services;

public class WidgetScreenshotService : IWidgetScreenshotService
{
private readonly WindowEx _windowEx;

private readonly Dictionary<string, BitmapImage> _widgetLightScreenshotCache;
private readonly Dictionary<string, BitmapImage> _widgetDarkScreenshotCache;

public WidgetScreenshotService(WindowEx windowEx)
{
_windowEx = windowEx;

_widgetLightScreenshotCache = new Dictionary<string, BitmapImage>();
_widgetDarkScreenshotCache = new Dictionary<string, BitmapImage>();
}

public async Task<BitmapImage> GetScreenshotFromCache(WidgetDefinition widgetDefinition, ElementTheme actualTheme)
{
var widgetDefinitionId = widgetDefinition.Id;
BitmapImage bitmapImage;

// First, check the cache to see if the screenshot is already there.
if (actualTheme == ElementTheme.Dark)
{
_widgetDarkScreenshotCache.TryGetValue(widgetDefinitionId, out bitmapImage);
}
else
{
_widgetLightScreenshotCache.TryGetValue(widgetDefinitionId, out bitmapImage);
}

if (bitmapImage != null)
{
return bitmapImage;
}

// If the screenshot wasn't already in the cache, get it from the widget definition and add it to the cache before returning.
if (actualTheme == ElementTheme.Dark)
{
bitmapImage = await WidgetScreenshotToBitmapImageAsync(widgetDefinition.GetThemeResource(WidgetTheme.Dark).GetScreenshots().FirstOrDefault().Image);
_widgetDarkScreenshotCache.TryAdd(widgetDefinitionId, bitmapImage);
}
else
{
bitmapImage = await WidgetScreenshotToBitmapImageAsync(widgetDefinition.GetThemeResource(WidgetTheme.Light).GetScreenshots().FirstOrDefault().Image);
_widgetLightScreenshotCache.TryAdd(widgetDefinitionId, bitmapImage);
}

return bitmapImage;
}

public void RemoveScreenshotsFromCache(string definitionId)
{
_widgetLightScreenshotCache.Remove(definitionId);
_widgetDarkScreenshotCache.Remove(definitionId);
}

private async Task<BitmapImage> WidgetScreenshotToBitmapImageAsync(IRandomAccessStreamReference iconStreamRef)
{
// Return the bitmap image via TaskCompletionSource. Using WCT's EnqueueAsync does not suffice here, since if
// we're already on the thread of the DispatcherQueue then it just directly calls the function, with no async involved.
var completionSource = new TaskCompletionSource<BitmapImage>();
_windowEx.DispatcherQueue.TryEnqueue(async () =>
{
using var bitmapStream = await iconStreamRef.OpenReadAsync();
var itemImage = new BitmapImage();
await itemImage.SetSourceAsync(bitmapStream);
completionSource.TrySetResult(itemImage);
});

var bitmapImage = await completionSource.Task;

return bitmapImage;
}
}
55 changes: 55 additions & 0 deletions tools/Dashboard/DevHome.Dashboard/ViewModels/AddWidgetViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation and Contributors
// Licensed under the MIT license.

using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using DevHome.Dashboard.Services;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.Windows.Widgets.Hosts;

namespace DevHome.Dashboard.ViewModels;

public partial class AddWidgetViewModel : ObservableObject
{
private readonly IWidgetScreenshotService _widgetScreenshotService;

[ObservableProperty]
private string _widgetDisplayTitle;

[ObservableProperty]
private string _widgetProviderDisplayTitle;

[ObservableProperty]
private Brush _widgetScreenshot;

[ObservableProperty]
private bool _pinButtonVisibility;

public AddWidgetViewModel(IWidgetScreenshotService widgetScreenshotService)
{
_widgetScreenshotService = widgetScreenshotService;
}

public async Task SetWidgetDefinition(WidgetDefinition selectedWidgetDefinition, ElementTheme actualTheme)
{
var bitmap = await _widgetScreenshotService.GetScreenshotFromCache(selectedWidgetDefinition, actualTheme);

WidgetDisplayTitle = selectedWidgetDefinition.DisplayTitle;
WidgetProviderDisplayTitle = selectedWidgetDefinition.ProviderDefinition.DisplayName;
WidgetScreenshot = new ImageBrush
{
ImageSource = bitmap,
};
PinButtonVisibility = true;
}

public void Clear()
{
WidgetDisplayTitle = string.Empty;
WidgetProviderDisplayTitle = string.Empty;
WidgetScreenshot = null;
PinButtonVisibility = false;
}
}
24 changes: 0 additions & 24 deletions tools/Dashboard/DevHome.Dashboard/ViewModels/WidgetViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,6 @@ public partial class WidgetViewModel : ObservableObject
[ObservableProperty]
private bool _isInEditMode;

[ObservableProperty]
private bool _configuring;

partial void OnWidgetChanging(Widget value)
{
if (Widget != null)
Expand Down Expand Up @@ -131,13 +128,6 @@ await Task.Run(async () =>
Log.Logger()?.ReportDebug("WidgetViewModel", $"cardTemplate = {cardTemplate}");
Log.Logger()?.ReportDebug("WidgetViewModel", $"cardData = {cardData}");

// If we're in the Add or Edit dialog, check the cardData to see if the card is in a configuration state
// or if it is able to be pinned yet. If still configuring, the Pin button will be disabled.
if (IsInAddMode || IsInEditMode)
{
GetConfiguring(cardData);
}

// Use the data to fill in the template.
AdaptiveCardParseResult card;
try
Expand Down Expand Up @@ -206,20 +196,6 @@ await Task.Run(async () =>
});
}

// Check if the card data indicates a configuration state. Configuring is bound to the Pin button and will disable it if true.
private void GetConfiguring(string cardData)
{
var jsonObj = JsonObject.Parse(cardData);
if (jsonObj != null)
{
var isConfiguring = jsonObj.GetNamedBoolean("configuring", false);
_dispatcher.TryEnqueue(() =>
{
Configuring = isConfiguring;
});
}
}

private async Task<bool> IsWidgetContentAvailable()
{
return await Task.Run(async () =>
Expand Down
45 changes: 27 additions & 18 deletions tools/Dashboard/DevHome.Dashboard/Views/AddWidgetDialog.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:commonviews="using:DevHome.Common.Views"
xmlns:converters="using:CommunityToolkit.WinUI.Converters"
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
mc:Ignorable="d"
Expand All @@ -24,18 +23,21 @@
<ContentDialog.Resources>
<x:Double x:Key="ContentDialogMinWidth">652</x:Double>
<x:Double x:Key="ContentDialogMaxWidth">652</x:Double>
<x:Double x:Key="ContentDialogMaxHeight">684</x:Double>
<x:Double x:Key="ContentDialogMaxHeight">590</x:Double>
<Thickness x:Key="ContentDialogTitleMargin">0,0,0,0</Thickness>
<Thickness x:Key="ContentDialogPadding">0,0,0,0</Thickness>
<Thickness x:Key="NavigationViewContentMargin">0,0,0,0</Thickness>
<converters:BoolNegationConverter x:Key="BoolNegation"/>
<Thickness x:Key="SmallPinButtonMargin">0,20</Thickness>
<Thickness x:Key="LargePinButtonMargin">0,42</Thickness>
<Thickness x:Key="SmallWidgetPreviewTopMargin">0,20,0,0</Thickness>
<Thickness x:Key="LargeWidgetPreviewTopMargin">0,42,0,0</Thickness>
</ContentDialog.Resources>

<StackPanel>
<!-- Title and Close button -->
<Grid x:Name="AddWidgetTitleBar">
<TextBlock x:Uid="AddWidgetsTitle" HorizontalAlignment="Left" Margin="16,10,0,0" />
<commonviews:CloseButton Click="CancelButton_Click" />
<commonviews:CloseButton Command="{x:Bind CancelButtonClickCommand}" />
</Grid>

<!-- Widgets available to pin-->
Expand All @@ -48,24 +50,25 @@
IsPaneToggleButtonVisible="False"
IsTitleBarAutoPaddingEnabled="False"
OpenPaneLength="218"
MaxHeight="650"
MaxHeight="560"
SelectionChanged="AddWidgetNavigationView_SelectionChanged">
<NavigationView.MenuItems>
</NavigationView.MenuItems>

<!-- Widget configuration UI -->
<Grid x:Name="ConfigurationContentGrid">
<!-- Widget preview -->
<Grid x:Name="WidgetPreviewContentGrid">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>

<StackPanel Grid.Row="0"
Margin="{StaticResource MediumTopMargin}"
x:Name="TitleRow"
HorizontalAlignment="Center">
<TextBlock Text="{x:Bind ViewModel.WidgetDisplayTitle, Mode=OneWay}"
Style="{StaticResource WidgetConfigHeaderTextStyle}"
Margin="{StaticResource MediumTopMargin}"
HorizontalAlignment="Center" />
<TextBlock Text="{x:Bind ViewModel.WidgetProviderDisplayTitle, Mode=OneWay}"
Style="{StaticResource WidgetConfigSubHeaderTextStyle}"
Expand All @@ -74,12 +77,19 @@
HorizontalAlignment="Center" />
</StackPanel>

<ScrollViewer Grid.Row="1"
x:Name="ConfigurationContentViewer"
VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch">
<Frame x:Name="ConfigurationContentFrame" Margin="45,45,45,150"
Content="{x:Bind ViewModel.WidgetFrameworkElement, Mode=OneWay}" />
</ScrollViewer>
<StackPanel Grid.Row="1"
x:Name="PreviewRow"
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Padding="{StaticResource LargeWidgetPreviewTopMargin}">
<Grid CornerRadius="8">
<Rectangle x:Name="ScreenshotRect"
Width="300"
Height="304"
VerticalAlignment="Stretch"
Fill="{x:Bind ViewModel.WidgetScreenshot, Mode=OneWay}" />
</Grid>
</StackPanel>

<!-- Pin button -->
<Grid Grid.Row="2"
Expand All @@ -88,11 +98,10 @@
x:Uid="PinButton"
Style="{ThemeResource AccentButtonStyle}"
VerticalAlignment="Bottom" HorizontalAlignment="Center"
Visibility="Collapsed"
IsEnabled="{x:Bind ViewModel.Configuring, Mode=OneWay, Converter={StaticResource BoolNegation}}"
Visibility="{x:Bind ViewModel.PinButtonVisibility, Mode=OneWay}"
MinHeight="32" MinWidth="118"
Click="PinButton_Click"
Margin="0,40">
Command="{x:Bind PinButtonClickCommand}"
Margin="{StaticResource LargePinButtonMargin}">
<StackPanel Orientation="Horizontal" Spacing="8">
<FontIcon FontFamily="{StaticResource SymbolThemeFontFamily}" FontSize="16" Glyph="&#xE840;" />
<TextBlock FontSize="14" x:Uid="PinButtonText" />
Expand Down
Loading
Loading