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

Adds QOI support to Peek #29919

Merged
merged 8 commits into from
Dec 18, 2023
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
28 changes: 28 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,34 @@ SOFTWARE.

## Utility: Peek

### The Quite OK Image Format reference decoder

**Source**: https://github.com/phoboslab/qoi

**Note**: [@pedrolamas](https://github.com/pedrolamas) translated and adapted the reference decoder code to C# that is in PowerToys from the original C++ implementation.

MIT License

Copyright (c) 2022 Dominic Szablewski

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.

### UTF Unknown

We use the UTF.Unknown NuGet package for detecting encoding in text/code files.
Expand Down
7 changes: 5 additions & 2 deletions src/common/FilePreviewCommon/FilePreviewCommon.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
<RuntimeIdentifiers>win-x64;win-arm64</RuntimeIdentifiers>
<Version>$(Version).0</Version>
<Authors>Microsoft Corporation</Authors>
<Product>PowerToys</Product>
<Description>PowerToys FilePreviewCommon</Description>
<AssemblyName>PowerToys.FilePreviewCommon</AssemblyName>
<UseWindowsForms>true</UseWindowsForms>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand All @@ -32,7 +35,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<Content Include="Assets\Monaco\monacoSRC\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Update="Assets\Monaco\monaco_languages.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
Expand Down
2 changes: 1 addition & 1 deletion src/common/FilePreviewCommon/Formatters/XmlFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public string Format(string value)
var stringBuilder = new StringBuilder();
var xmlWriterSettings = new XmlWriterSettings()
{
OmitXmlDeclaration = xmlDocument.FirstChild.NodeType != XmlNodeType.XmlDeclaration,
OmitXmlDeclaration = xmlDocument.FirstChild?.NodeType != XmlNodeType.XmlDeclaration,
Indent = true,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using System.Linq;
using System.Text;

namespace Common.Utilities
namespace Microsoft.PowerToys.FilePreviewCommon
{
/// <summary>
/// Gcode file helper class.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
using System;
using System.Drawing;
using System.IO;
using PreviewHandlerCommon.Utilities;

namespace Common.Utilities
namespace Microsoft.PowerToys.FilePreviewCommon
{
/// <summary>
/// Represents a gcode thumbnail.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Common.Utilities
namespace Microsoft.PowerToys.FilePreviewCommon
{
/// <summary>
/// The gcode thumbnail image format.
Expand Down
2 changes: 1 addition & 1 deletion src/common/FilePreviewCommon/MarkdownHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static string MarkdownHtml(string fileContent, string theme, string fileP

// Extension to modify markdown AST.
HTMLParsingExtension extension = new HTMLParsingExtension(imagesBlockedCallBack);
extension.FilePath = Path.GetDirectoryName(filePath);
extension.FilePath = Path.GetDirectoryName(filePath) ?? string.Empty;

// if you have a string with double space, some people view it as a new line.
// while this is against spec, even GH supports this. Technically looks like GH just trims whitespace
Expand Down
6 changes: 3 additions & 3 deletions src/common/FilePreviewCommon/MonacoHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@ public static class MonacoHelper
new XmlFormatter(),
}.AsReadOnly();

private static string _monacoDirectory;
private static string? _monacoDirectory;

public static string GetRuntimeMonacoDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().Location;
string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(codeBase), "Assets", "Monaco"));
string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(codeBase) ?? string.Empty, "Assets", "Monaco"));
if (Path.Exists(path))
{
return path;
}
else
{
// We're likely in WinUI3Apps directory and need to go back to the base directory.
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(codeBase), "..", "Assets", "Monaco"));
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(codeBase) ?? string.Empty, "..", "Assets", "Monaco"));
}
}

Expand Down
177 changes: 177 additions & 0 deletions src/common/FilePreviewCommon/QoiImage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// 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;
using System.Buffers.Binary;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

//// Based on https://github.com/phoboslab/qoi/blob/master/qoi.h

namespace Microsoft.PowerToys.FilePreviewCommon
{
/// <summary>
/// QOI Image helper.
/// </summary>
public static class QoiImage
{
#pragma warning disable SA1310 // Field names should not contain underscore
private const byte QOI_OP_INDEX = 0x00; // 00xxxxxx
private const byte QOI_OP_DIFF = 0x40; // 01xxxxxx
private const byte QOI_OP_LUMA = 0x80; // 10xxxxxx
private const byte QOI_OP_RUN = 0xc0; // 11xxxxxx
private const byte QOI_OP_RGB = 0xfe; // 11111110
private const byte QOI_OP_RGBA = 0xff; // 11111111

private const byte QOI_MASK_2 = 0xc0; // 11000000

private const int QOI_MAGIC = 'q' << 24 | 'o' << 16 | 'i' << 8 | 'f';
private const int QOI_HEADER_SIZE = 14;

private const uint QOI_PIXELS_MAX = 400000000;

private const byte QOI_PADDING_LENGTH = 8;
#pragma warning restore SA1310 // Field names should not contain underscore

private record struct QoiPixel(byte R, byte G, byte B, byte A)
{
public readonly int GetColorHash() => (R * 3) + (G * 5) + (B * 7) + (A * 11);
}

/// <summary>
/// Creates a <see cref="Bitmap"/> from the specified QOI data stream.
/// </summary>
/// <param name="stream">A <see cref="Stream"/> that contains the QOI data.</param>
/// <returns>The <see cref="Bitmap"/> this method creates.</returns>
/// <exception cref="ArgumentException">The stream does not have a valid QOI image format.</exception>
public static Bitmap FromStream(Stream stream)
{
var fileSize = stream.Length;

if (fileSize < QOI_HEADER_SIZE + QOI_PADDING_LENGTH)
{
throw new ArgumentException("Not enough data for a QOI file");
}

Bitmap? bitmap = null;

try
{
using var reader = new BinaryReader(stream, Encoding.UTF8, true);

var headerMagic = ReadUInt32BigEndian(reader);

if (headerMagic != QOI_MAGIC)
{
throw new ArgumentException("Invalid QOI file header");
}

var width = ReadUInt32BigEndian(reader);
var height = ReadUInt32BigEndian(reader);
var channels = reader.ReadByte();
var colorSpace = reader.ReadByte();

if (width == 0 || height == 0 || channels < 3 || channels > 4 || colorSpace > 1 || height >= QOI_PIXELS_MAX / width)
{
throw new ArgumentException("Invalid QOI file data");
}

var pixelFormat = channels == 4 ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb;

bitmap = new Bitmap((int)width, (int)height, pixelFormat);

var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, pixelFormat);
var dataLength = bitmapData.Height * bitmapData.Stride;

var index = new QoiPixel[64];
var pixel = new QoiPixel(0, 0, 0, 255);

var run = 0;
var chunksLen = fileSize - QOI_PADDING_LENGTH;

for (var dataIndex = 0; dataIndex < dataLength; dataIndex += channels)
{
if (run > 0)
{
run--;
}
else if (stream.Position < chunksLen)
{
var b1 = reader.ReadByte();

if (b1 == QOI_OP_RGB)
{
pixel.R = reader.ReadByte();
pixel.G = reader.ReadByte();
pixel.B = reader.ReadByte();
}
else if (b1 == QOI_OP_RGBA)
{
pixel.R = reader.ReadByte();
pixel.G = reader.ReadByte();
pixel.B = reader.ReadByte();
pixel.A = reader.ReadByte();
}
else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX)
{
pixel = index[b1];
}
else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF)
{
pixel.R += (byte)(((b1 >> 4) & 0x03) - 2);
pixel.G += (byte)(((b1 >> 2) & 0x03) - 2);
pixel.B += (byte)((b1 & 0x03) - 2);
}
else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA)
{
var b2 = reader.ReadByte();
var vg = (b1 & 0x3f) - 32;
pixel.R += (byte)(vg - 8 + ((b2 >> 4) & 0x0f));
pixel.G += (byte)vg;
pixel.B += (byte)(vg - 8 + (b2 & 0x0f));
}
else if ((b1 & QOI_MASK_2) == QOI_OP_RUN)
{
run = b1 & 0x3f;
}

index[pixel.GetColorHash() % 64] = pixel;
}

unsafe
{
var bitmapPixel = (byte*)bitmapData.Scan0 + dataIndex;

bitmapPixel[0] = pixel.B;
bitmapPixel[1] = pixel.G;
bitmapPixel[2] = pixel.R;
if (channels == 4)
{
bitmapPixel[3] = pixel.A;
}
}
}

bitmap.UnlockBits(bitmapData);

return bitmap;
}
catch
{
bitmap?.Dispose();

throw;
}
}

private static uint ReadUInt32BigEndian(BinaryReader reader)
{
var buffer = reader.ReadBytes(4);

return BinaryPrimitives.ReadUInt32BigEndian(buffer);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// 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;
using System.Buffers.Binary;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -77,6 +77,31 @@ public static class IFileSystemItemExtensions
return size;
}

public static Size? GetQoiSize(this IFileSystemItem item)
{
Size? size = null;
using (FileStream stream = new FileStream(item.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
if (stream.Length >= 12)
{
stream.Position = 4;

using (var reader = new BinaryReader(stream))
{
uint widthValue = BinaryPrimitives.ReadUInt32BigEndian(reader.ReadBytes(4));
uint heightValue = BinaryPrimitives.ReadUInt32BigEndian(reader.ReadBytes(4));

if (widthValue > 0 && heightValue > 0)
{
size = new Size(widthValue, heightValue);
}
}
}
}

return size;
}

public static ulong GetSizeInBytes(this IFileSystemItem item)
{
ulong sizeInBytes = 0;
Expand Down
Loading
Loading