Files
PowerToys/src/modules/cmdpal/Microsoft.CmdPal.UI/Helpers/IconCacheService.cs
Jiří Polášek 4785af2425 CmdPal: Handle exceptions when enqueuing callbacks to UI thread in IconCacheService (#40716)
## Summary of the Pull Request

Handle exceptions thrown in TryEnqueue callbacks so they don’t crash the
app (as they cannot be caught by the global exception handler). Any
exceptions are now returned to the caller for handling. Additionally, a
failure to enqueue the operation onto the dispatcher will also result in
an exception.

This is not a breaking change, as exceptions only propagate within the
class and do not affect external callers.

Ref: #38260

## PR Checklist

- [ ] **Closes:** #38260 
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
2025-07-28 16:41:27 -05:00

100 lines
3.1 KiB
C#

// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CmdPal.Core.ViewModels;
using Microsoft.Terminal.UI;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
namespace Microsoft.CmdPal.UI.Helpers;
public sealed class IconCacheService(DispatcherQueue dispatcherQueue)
{
public Task<IconSource?> GetIconSource(IconDataViewModel icon) =>
// todo: actually implement a cache of some sort
IconToSource(icon);
private async Task<IconSource?> IconToSource(IconDataViewModel icon)
{
try
{
if (!string.IsNullOrEmpty(icon.Icon))
{
var source = IconPathConverter.IconSourceMUX(icon.Icon, false);
return source;
}
else if (icon.Data != null)
{
try
{
return await StreamToIconSource(icon.Data.Unsafe!);
}
catch (Exception ex)
{
Debug.WriteLine("Failed to load icon from stream: " + ex);
}
}
}
catch
{
}
return null;
}
private async Task<IconSource?> StreamToIconSource(IRandomAccessStreamReference iconStreamRef)
{
if (iconStreamRef == null)
{
return null;
}
var bitmap = await IconStreamToBitmapImageAsync(iconStreamRef);
var icon = new ImageIconSource() { ImageSource = bitmap };
return icon;
}
private async Task<BitmapImage> IconStreamToBitmapImageAsync(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.
return await TryEnqueueAsync(dispatcherQueue, async () =>
{
using var bitmapStream = await iconStreamRef.OpenReadAsync();
var itemImage = new BitmapImage();
await itemImage.SetSourceAsync(bitmapStream);
return itemImage;
});
}
private static Task<T> TryEnqueueAsync<T>(DispatcherQueue dispatcher, Func<Task<T>> function)
{
var completionSource = new TaskCompletionSource<T>();
var enqueued = dispatcher.TryEnqueue(DispatcherQueuePriority.Normal, async void () =>
{
try
{
var result = await function();
completionSource.SetResult(result);
}
catch (Exception ex)
{
completionSource.SetException(ex);
}
});
if (!enqueued)
{
completionSource.SetException(new InvalidOperationException("Failed to enqueue the operation on the UI dispatcher"));
}
return completionSource.Task;
}
}