Updated Microsoft.Toolkit.Uwp.Notifications which brings a lot more to Greenshot [skip ci]

This commit is contained in:
Robin Krom 2021-03-19 22:53:19 +01:00
commit c303c07320
No known key found for this signature in database
GPG key ID: BCC01364F1371490
3 changed files with 67 additions and 121 deletions

View file

@ -12,7 +12,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" version="6.1.1" /> <PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" version="7.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\GreenshotPlugin\GreenshotPlugin.csproj" /> <ProjectReference Include="..\GreenshotPlugin\GreenshotPlugin.csproj" />

View file

@ -1,44 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Runtime.InteropServices;
using log4net;
using Microsoft.Toolkit.Uwp.Notifications;
namespace GreenshotWin10Plugin.Native
{
/// <summary>
/// This implements the NotificationActivator
/// </summary>
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(NotificationActivator.INotificationActivationCallback))]
[Guid("F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08"), ComVisible(true)]
public class GreenshotNotificationActivator : NotificationActivator
{
private static readonly ILog Log = LogManager.GetLogger(typeof(GreenshotNotificationActivator));
public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId)
{
// TODO: Handle activation
Log.Info("Activated");
}
}
}

View file

@ -22,13 +22,12 @@
using System; using System;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Linq; using Windows.Foundation.Collections;
using Windows.Foundation.Metadata; using Windows.Foundation.Metadata;
using Windows.UI.Notifications; using Windows.UI.Notifications;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.IniFile; using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces; using GreenshotPlugin.Interfaces;
using GreenshotWin10Plugin.Native;
using log4net; using log4net;
using Microsoft.Toolkit.Uwp.Notifications; using Microsoft.Toolkit.Uwp.Notifications;
@ -45,10 +44,21 @@ namespace GreenshotWin10Plugin
private readonly string _imageFilePath; private readonly string _imageFilePath;
public ToastNotificationService() public ToastNotificationService()
{ {
// Register AUMID and COM server (for Desktop Bridge apps, this no-ops) if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated())
DesktopNotificationManagerCompat.RegisterAumidAndComServer<GreenshotNotificationActivator>("Greenshot"); {
// Register COM server and activator type Log.Info("Greenshot was activated due to a toast.");
DesktopNotificationManagerCompat.RegisterActivator<GreenshotNotificationActivator>(); }
// Listen to notification activation
ToastNotificationManagerCompat.OnActivated += toastArgs =>
{
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
// Obtain any user input (text boxes, menu selections) from the notification
ValueSet userInput = toastArgs.UserInput;
Log.Info("Toast activated. Args: " + toastArgs.Argument);
};
var localAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Greenshot"); var localAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Greenshot");
if (!Directory.Exists(localAppData)) if (!Directory.Exists(localAppData))
@ -81,7 +91,7 @@ namespace GreenshotWin10Plugin
return; return;
} }
// Prepare the toast notifier. Be sure to specify the AppUserModelId on your application's shortcut! // Prepare the toast notifier. Be sure to specify the AppUserModelId on your application's shortcut!
var toastNotifier = DesktopNotificationManagerCompat.CreateToastNotifier(); var toastNotifier = ToastNotificationManagerCompat.CreateToastNotifier();
// Here is an interesting article on reading the settings: https://www.rudyhuyn.com/blog/2018/02/10/toastnotifier-and-settings-careful-with-non-uwp-applications/ // Here is an interesting article on reading the settings: https://www.rudyhuyn.com/blog/2018/02/10/toastnotifier-and-settings-careful-with-non-uwp-applications/
try try
@ -97,82 +107,62 @@ namespace GreenshotWin10Plugin
Log.Info("Ignoring exception as this means that there was no stored settings."); Log.Info("Ignoring exception as this means that there was no stored settings.");
} }
// Get a toast XML template // Generate the toast and send it off
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01); new ToastContentBuilder()
// Fill in the text elements .AddArgument("ToastID", 100)
var stringElement = toastXml.GetElementsByTagName("text").First(); // Inline image
stringElement.AppendChild(toastXml.CreateTextNode(message)); .AddText(message)
// Profile (app logo override) image
if (_imageFilePath != null && File.Exists(_imageFilePath)) //.AddAppLogoOverride(new Uri($@"file://{_imageFilePath}"), ToastGenericAppLogoCrop.None)
{ .Show(toast =>
// Specify the absolute path to an image
var imageElement = toastXml.GetElementsByTagName("image").First();
var imageSrcNode = imageElement.Attributes.GetNamedItem("src");
if (imageSrcNode != null)
{ {
imageSrcNode.NodeValue = _imageFilePath; // Windows 10 first with 1903: ExpiresOnReboot = true
} toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?) null;
} void ToastActivatedHandler(ToastNotification toastNotification, object sender)
{
try
{
onClickAction?.Invoke();
}
catch (Exception ex)
{
Log.Warn("Exception while handling the onclick action: ", ex);
}
// Create the toast and attach event listeners toast.Activated -= ToastActivatedHandler;
var toast = new ToastNotification(toastXml) }
{
// Windows 10 first with 1903: ExpiresOnReboot = true,
ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?)null
};
void ToastActivatedHandler(ToastNotification toastNotification, object sender) if (onClickAction != null)
{ {
try toast.Activated += ToastActivatedHandler;
{ }
onClickAction?.Invoke();
}
catch (Exception ex)
{
Log.Warn("Exception while handling the onclick action: ", ex);
}
toast.Activated -= ToastActivatedHandler; void ToastDismissedHandler(ToastNotification toastNotification, ToastDismissedEventArgs eventArgs)
} {
Log.Debug($"Toast closed with reason {eventArgs.Reason}");
if (eventArgs.Reason != ToastDismissalReason.UserCanceled)
{
return;
}
try
{
onClosedAction?.Invoke();
}
catch (Exception ex)
{
Log.Warn("Exception while handling the onClosed action: ", ex);
}
if (onClickAction != null) toast.Dismissed -= ToastDismissedHandler;
{ // Remove the other handler too
toast.Activated += ToastActivatedHandler; toast.Activated -= ToastActivatedHandler;
} toast.Failed -= ToastOnFailed;
void ToastDismissedHandler(ToastNotification toastNotification, ToastDismissedEventArgs eventArgs) }
{ toast.Dismissed += ToastDismissedHandler;
Log.Debug($"Toast closed with reason {eventArgs.Reason}"); toast.Failed += ToastOnFailed;
if (eventArgs.Reason != ToastDismissalReason.UserCanceled) });
{
return;
}
try
{
onClosedAction?.Invoke();
}
catch (Exception ex)
{
Log.Warn("Exception while handling the onClosed action: ", ex);
}
toast.Dismissed -= ToastDismissedHandler;
// Remove the other handler too
toast.Activated -= ToastActivatedHandler;
toast.Failed -= ToastOnFailed;
}
toast.Dismissed += ToastDismissedHandler;
toast.Failed += ToastOnFailed;
try
{
toastNotifier.Show(toast);
}
catch (Exception ex)
{
Log.Error("Couldn't show notification.", ex);
}
} }
private void ToastOnFailed(ToastNotification sender, ToastFailedEventArgs args) private void ToastOnFailed(ToastNotification sender, ToastFailedEventArgs args)