Skip to content

Commit

Permalink
[Peek] add extra logic to properly render PNG files with transparency (
Browse files Browse the repository at this point in the history
…#22613)

* [Peek] added extra logic to render PNG files with proper transparency

* Moved logic to ThumbnailHelper
Cleanup

* Created a separated previewer for PNG to only load the preview image with thumbnail logic

* removed unused code

* Updated state loading change
  • Loading branch information
RobsonPontin authored Dec 8, 2022
1 parent 5590eb9 commit 5bd9dd5
Show file tree
Hide file tree
Showing 4 changed files with 153 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ namespace Peek.FilePreviewer.Previewers
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.UI.Xaml.Media.Imaging;
using Peek.Common;
using Peek.Common.Models;

Expand Down Expand Up @@ -59,5 +61,32 @@ public static HResult GetThumbnail(string filename, out IntPtr hbitmap, NativeSi

return hr;
}

public static async Task<BitmapImage?> GetThumbnailAsync(string path, uint size)
{
BitmapImage? bitmapImage = null;

// preview image
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);
if (file == null)
{
return bitmapImage;
}

var imageStream = await file.GetThumbnailAsync(
Windows.Storage.FileProperties.ThumbnailMode.SingleItem,
size,
Windows.Storage.FileProperties.ThumbnailOptions.None);

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

bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream);

return bitmapImage;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ namespace Peek.FilePreviewer.Previewers
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Imaging;
using Peek.Common;
using Peek.Common.Extensions;
Expand Down Expand Up @@ -233,7 +232,8 @@ public static bool IsFileTypeSupported(string fileExt)
".jif",
".jpeg",
".jpe",
".png",

// ".png", // The current ImagePreviewer logic does not support transparency so PNG has it's own logic in PngPreviewer
".tif",
".tiff",
".dib",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// 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.

namespace Peek.FilePreviewer.Previewers
{
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Media.Imaging;
using Peek.Common;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using File = Peek.Common.Models.File;

public partial class PngPreviewer : ObservableObject, IBitmapPreviewer
{
private readonly uint _png_image_size = 1280;

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsPreviewLoaded))]
private BitmapSource? preview;

[ObservableProperty]
private PreviewState state;

public PngPreviewer(File file)
{
File = file;
Dispatcher = DispatcherQueue.GetForCurrentThread();

PropertyChanged += OnPropertyChanged;
}

public bool IsPreviewLoaded => preview != null;

private File File { get; }

private DispatcherQueue Dispatcher { get; }

private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

private CancellationToken CancellationToken => _cancellationTokenSource.Token;

public void Dispose()
{
_cancellationTokenSource.Dispose();
GC.SuppressFinalize(this);
}

public async Task<Size> GetPreviewSizeAsync()
{
var propertyImageSize = await PropertyHelper.GetImageSize(File.Path);
if (propertyImageSize != Size.Empty)
{
return propertyImageSize;
}

return await WICHelper.GetImageSize(File.Path);
}

public async Task LoadPreviewAsync()
{
State = PreviewState.Loading;

var previewTask = LoadPreviewImageAsync();

await Task.WhenAll(previewTask);

if (Preview == null)
{
State = PreviewState.Error;
}
}

public static bool IsFileTypeSupported(string fileExt)
{
return fileExt == ".png" ? true : false;
}

private void OnPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Preview))
{
if (Preview != null)
{
State = PreviewState.Loaded;
}
}
}

private Task LoadPreviewImageAsync()
{
var thumbnailTCS = new TaskCompletionSource();
Dispatcher.TryEnqueue(async () =>
{
if (CancellationToken.IsCancellationRequested)
{
_cancellationTokenSource = new CancellationTokenSource();
return;
}
Preview = await ThumbnailHelper.GetThumbnailAsync(File.Path, _png_image_size);
thumbnailTCS.SetResult();
});

return thumbnailTCS.Task;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ public class PreviewerFactory
{
public IPreviewer Create(File file)
{
if (ImagePreviewer.IsFileTypeSupported(file.Extension))
if (PngPreviewer.IsFileTypeSupported(file.Extension))
{
return new PngPreviewer(file);
}
else if (ImagePreviewer.IsFileTypeSupported(file.Extension))
{
return new ImagePreviewer(file);
}
Expand Down

1 comment on commit 5bd9dd5

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

🔴 Please review

See the 📜action log for details.

Unrecognized words (140)
Abbrivation
apidl
ari
arw
BESTEFFORT
BHIDSF
BVal
calpwstr
CARRAY
CElems
Chromakey
cidl
crw
CVal
DANGEROUSLYCOMMITMERELYTODISKCACHE
dcr
dcs
Dct
DDEIf
Dds
DELAYCREATION
drf
Dwma
eip
Exa
exabyte
Excep
EXCEPINFO
EXTRINSICPROPERTIES
EXTRINSICPROPERTIESONLY
FASTPROPERTIESONLY
filetime
HANDLERPROPERTIESONLY
HDR
hicon
hif
HVal
IBitmap
IBlock
IColor
icolumn
IContext
IDecoder
IEncoder
IEnum
IIDI
iiq
IMetadata
IPalette
IQuery
IReader
ISource
ISurface
ithumbnail
jfi
jif
kdc
Keybd
Lcid
LOCKBYTES
LOCKTYPE
LVal
mdc
mef
Mega
mrw
neighborings
NOOPEN
nrw
ONLYIFCURRENT
ONLYONCE
OPENSLOWITEM
openspecs
OPLOCK
ori
overriden
pbgra
PBlob
pcch
pcelt
pcs
pef
PElems
Percision
petabyte
pkey
ppenum
pprop
PREFERQUERYPROPERTIES
Previer
PRGBA
PROPERTYNOTFOUND
PROPVARIANT
pscid
psfi
pstatstg
pstm
pui
pvar
raf
retunred
rfid
RGBE
rgelt
rgf
rwl
rwz
sachaple
SAFEARRAY
SCID
Scode
Shcontf
SHELLDETAILS
Shgno
Softcoded
srf
SRGB
STGC
STGTY
Stroe
Strret
tcs
terabyte
titlebar
tlbimp
toogle
UMsg
UOffset
USERDEFINED
UType
VARTYPE
VERSIONED
webbrowser
windowsapp
WMSDK
WReserved
WScan
wsp
WVk
YQuantized
Previously acknowledged words that are now absent brucelindbloom chromaticities companding DCR Eqn ffaa FILETIME HICON ITHUMBNAIL Pbgra PKEY Windowsapp :arrow_right:
To accept ✔️ these unrecognized words as correct and remove the previously acknowledged and now absent words, run the following commands

... in a clone of the git@github.com:microsoft/PowerToys.git repository
on the peek branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/v0.0.21/apply.pl' |
perl - 'https://github.com/microsoft/PowerToys/actions/runs/3653068527/attempts/1'
Available 📚 dictionaries could cover words not in the 📘 dictionary

This includes both expected items (2140) from .github/actions/spell-check/expect.txt and unrecognized words (140)

Dictionary Entries Covers
cspell:win32/src/win32.txt 53509 133
cspell:cpp/src/cpp.txt 30216 129
cspell:python/src/python/python-lib.txt 3873 32
cspell:php/php.txt 2597 17
cspell:node/node.txt 1768 14
cspell:typescript/typescript.txt 1211 12
cspell:python/src/python/python.txt 453 11
cspell:java/java.txt 7642 11
cspell:aws/aws.txt 218 8
cspell:r/src/r.txt 808 7

Consider adding them using (in .github/workflows/spelling2.yml):

      with:
        extra_dictionaries:
          cspell:win32/src/win32.txt
          cspell:cpp/src/cpp.txt
          cspell:python/src/python/python-lib.txt
          cspell:php/php.txt
          cspell:node/node.txt
          cspell:typescript/typescript.txt
          cspell:python/src/python/python.txt
          cspell:java/java.txt
          cspell:aws/aws.txt
          cspell:r/src/r.txt

To stop checking additional dictionaries, add:

      with:
        check_extra_dictionaries: ''
Errors (1)

See the 📜action log for details.

❌ Errors Count
❌ forbidden-pattern 1

See ❌ Event descriptions for more information.

If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

Please sign in to comment.