Compare commits
1 Commits
main
...
dependabot
Author | SHA1 | Date |
---|---|---|
dependabot[bot] | da56b8959f | 11 months ago |
456 changed files with 4782 additions and 39324 deletions
@ -1,37 +0,0 @@
|
||||
name: Automatic Backport |
||||
|
||||
on: |
||||
pull_request: |
||||
types: ["closed", "labeled"] |
||||
|
||||
jobs: |
||||
backport: |
||||
if: ${{ (github.event.pull_request.merged == true) && (contains(github.event.pull_request.labels.*.name, 'backport-to-main') == true) }} |
||||
name: Backport PR |
||||
runs-on: ubuntu-latest |
||||
steps: |
||||
- name: Write json |
||||
id: create-json |
||||
uses: jsdaniell/create-json@v1.2.3 |
||||
with: |
||||
name: ".backportrc.json" |
||||
json: | |
||||
{ |
||||
"targetPRLabels": "backport", |
||||
"prTitle": "[{{sourceBranch}} to {{targetBranch}}] backport: {{sourcePullRequest.title}} ({{sourcePullRequest.number}})" |
||||
} |
||||
|
||||
- name: Backport Action |
||||
uses: sorenlouv/backport-github-action@v9.3.0 |
||||
with: |
||||
github_token: ${{ secrets.GITHUB_TOKEN }} |
||||
auto_backport_label_prefix: backport-to- |
||||
|
||||
- name: Info log |
||||
if: ${{ success() }} |
||||
run: cat ~/.backport/backport.info.log |
||||
|
||||
- name: Debug log |
||||
if: ${{ failure() }} |
||||
run: cat ~/.backport/backport.debug.log |
||||
|
@ -1,18 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk"> |
||||
<PropertyGroup> |
||||
<TargetFramework>net8.0</TargetFramework> |
||||
<LangVersion>latest</LangVersion> |
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> |
||||
<RuntimeIdentifiers>win-x64;linux-x64;osx-x64;osx-arm64</RuntimeIdentifiers> |
||||
<ImplicitUsings>enable</ImplicitUsings> |
||||
<Nullable>enable</Nullable> |
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport> |
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting> |
||||
</PropertyGroup> |
||||
<ItemGroup> |
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> |
||||
<PackageReference Include="SkiaSharp" Version="2.88.7" /> |
||||
<PackageReference Include="DotNet.Bundle" Version="0.9.13" /> |
||||
</ItemGroup> |
||||
|
||||
</Project> |
@ -1,10 +0,0 @@
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
internal enum BgWorkerCommand |
||||
{ |
||||
Null, |
||||
Play, |
||||
Pause, |
||||
Dispose |
||||
} |
||||
} |
@ -1,12 +0,0 @@
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
internal enum BgWorkerState |
||||
{ |
||||
Null, |
||||
Start, |
||||
Running, |
||||
Paused, |
||||
Complete, |
||||
Dispose |
||||
} |
||||
} |
@ -1,10 +0,0 @@
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
internal enum BlockTypes |
||||
{ |
||||
Empty = 0, |
||||
Extension = 0x21, |
||||
ImageDescriptor = 0x2C, |
||||
Trailer = 0x3B, |
||||
} |
||||
} |
@ -1,8 +0,0 @@
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
internal enum ExtensionType |
||||
{ |
||||
GraphicsControl = 0xF9, |
||||
Application = 0xFF |
||||
} |
||||
} |
@ -1,10 +0,0 @@
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public enum FrameDisposal |
||||
{ |
||||
Unknown = 0, |
||||
Leave = 1, |
||||
Background = 2, |
||||
Restore = 3 |
||||
} |
||||
} |
@ -1,36 +0,0 @@
|
||||
using System.Runtime.InteropServices; |
||||
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
[StructLayout(LayoutKind.Explicit)] |
||||
public readonly struct GifColor |
||||
{ |
||||
[FieldOffset(3)] |
||||
public readonly byte A; |
||||
|
||||
[FieldOffset(2)] |
||||
public readonly byte R; |
||||
|
||||
[FieldOffset(1)] |
||||
public readonly byte G; |
||||
|
||||
[FieldOffset(0)] |
||||
public readonly byte B; |
||||
|
||||
/// <summary> |
||||
/// A struct that represents a ARGB color and is aligned as |
||||
/// a BGRA bytefield in memory. |
||||
/// </summary> |
||||
/// <param name="r">Red</param> |
||||
/// <param name="g">Green</param> |
||||
/// <param name="b">Blue</param> |
||||
/// <param name="a">Alpha</param> |
||||
public GifColor(byte r, byte g, byte b, byte a = byte.MaxValue) |
||||
{ |
||||
A = a; |
||||
R = r; |
||||
G = g; |
||||
B = b; |
||||
} |
||||
} |
||||
} |
@ -1,653 +0,0 @@
|
||||
// This source file's Lempel-Ziv-Welch algorithm is derived from Chromium's Android GifPlayer |
||||
// as seen here (https://github.com/chromium/chromium/blob/master/third_party/gif_player/src/jp/tomorrowkey/android/gifplayer) |
||||
// Licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0) |
||||
// Copyright (C) 2015 The Gifplayer Authors. All Rights Reserved. |
||||
|
||||
// The rest of the source file is licensed under MIT License. |
||||
// Copyright (C) 2018 Jumar A. Macato, All Rights Reserved. |
||||
|
||||
using System; |
||||
using System.Buffers; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using System.Linq; |
||||
using System.Runtime.CompilerServices; |
||||
using System.Runtime.InteropServices; |
||||
using System.Text; |
||||
using System.Threading; |
||||
using Avalonia; |
||||
using Avalonia.Media.Imaging; |
||||
using static Avalonia.Gif.Extensions.StreamExtensions; |
||||
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public sealed class GifDecoder : IDisposable |
||||
{ |
||||
private static readonly ReadOnlyMemory<byte> G87AMagic = "GIF87a"u8.ToArray().AsMemory(); |
||||
|
||||
private static readonly ReadOnlyMemory<byte> G89AMagic = "GIF89a"u8.ToArray().AsMemory(); |
||||
|
||||
private static readonly ReadOnlyMemory<byte> NetscapeMagic = "NETSCAPE2.0"u8.ToArray().AsMemory(); |
||||
|
||||
private static readonly TimeSpan FrameDelayThreshold = TimeSpan.FromMilliseconds(10); |
||||
private static readonly TimeSpan FrameDelayDefault = TimeSpan.FromMilliseconds(100); |
||||
private static readonly GifColor TransparentColor = new(0, 0, 0, 0); |
||||
private static readonly int MaxTempBuf = 768; |
||||
private static readonly int MaxStackSize = 4096; |
||||
private static readonly int MaxBits = 4097; |
||||
|
||||
private readonly Stream _fileStream; |
||||
private readonly CancellationToken _currentCtsToken; |
||||
private readonly bool _hasFrameBackups; |
||||
|
||||
private int _gctSize, |
||||
_bgIndex, |
||||
_prevFrame = -1, |
||||
_backupFrame = -1; |
||||
private bool _gctUsed; |
||||
|
||||
private GifRect _gifDimensions; |
||||
|
||||
// private ulong _globalColorTable; |
||||
private readonly int _backBufferBytes; |
||||
private GifColor[] _bitmapBackBuffer; |
||||
|
||||
private short[] _prefixBuf; |
||||
private byte[] _suffixBuf; |
||||
private byte[] _pixelStack; |
||||
private byte[] _indexBuf; |
||||
private byte[] _backupFrameIndexBuf; |
||||
private volatile bool _hasNewFrame; |
||||
|
||||
public GifHeader Header { get; private set; } |
||||
|
||||
public readonly List<GifFrame> Frames = new(); |
||||
|
||||
public PixelSize Size => new PixelSize(Header.Dimensions.Width, Header.Dimensions.Height); |
||||
|
||||
public GifDecoder(Stream fileStream, CancellationToken currentCtsToken) |
||||
{ |
||||
_fileStream = fileStream; |
||||
_currentCtsToken = currentCtsToken; |
||||
|
||||
ProcessHeaderData(); |
||||
ProcessFrameData(); |
||||
|
||||
Header.IterationCount = Header.Iterations switch |
||||
{ |
||||
-1 => new GifRepeatBehavior { Count = 1 }, |
||||
0 => new GifRepeatBehavior { LoopForever = true }, |
||||
> 0 => new GifRepeatBehavior { Count = Header.Iterations }, |
||||
_ => Header.IterationCount |
||||
}; |
||||
|
||||
var pixelCount = _gifDimensions.TotalPixels; |
||||
|
||||
_hasFrameBackups = Frames.Any(f => f.FrameDisposalMethod == FrameDisposal.Restore); |
||||
|
||||
_bitmapBackBuffer = new GifColor[pixelCount]; |
||||
_indexBuf = new byte[pixelCount]; |
||||
|
||||
if (_hasFrameBackups) |
||||
_backupFrameIndexBuf = new byte[pixelCount]; |
||||
|
||||
_prefixBuf = new short[MaxStackSize]; |
||||
_suffixBuf = new byte[MaxStackSize]; |
||||
_pixelStack = new byte[MaxStackSize + 1]; |
||||
|
||||
_backBufferBytes = pixelCount * Marshal.SizeOf(typeof(GifColor)); |
||||
} |
||||
|
||||
public void Dispose() |
||||
{ |
||||
Frames.Clear(); |
||||
|
||||
_bitmapBackBuffer = null; |
||||
_prefixBuf = null; |
||||
_suffixBuf = null; |
||||
_pixelStack = null; |
||||
_indexBuf = null; |
||||
_backupFrameIndexBuf = null; |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private int PixCoord(int x, int y) => x + y * _gifDimensions.Width; |
||||
|
||||
static readonly (int Start, int Step)[] Pass = { (0, 8), (4, 8), (2, 4), (1, 2) }; |
||||
|
||||
private void ClearImage() |
||||
{ |
||||
Array.Fill(_bitmapBackBuffer, TransparentColor); |
||||
//ClearArea(_gifDimensions); |
||||
|
||||
_prevFrame = -1; |
||||
_backupFrame = -1; |
||||
} |
||||
|
||||
public void RenderFrame(int fIndex, WriteableBitmap writeableBitmap, bool forceClear = false) |
||||
{ |
||||
if (_currentCtsToken.IsCancellationRequested) |
||||
return; |
||||
|
||||
if (fIndex < 0 | fIndex >= Frames.Count) |
||||
return; |
||||
|
||||
if (_prevFrame == fIndex) |
||||
return; |
||||
|
||||
if (fIndex == 0 || forceClear || fIndex < _prevFrame) |
||||
ClearImage(); |
||||
|
||||
DisposePreviousFrame(); |
||||
|
||||
_prevFrame++; |
||||
|
||||
// render intermediate frame |
||||
for (int idx = _prevFrame; idx < fIndex; ++idx) |
||||
{ |
||||
var prevFrame = Frames[idx]; |
||||
|
||||
if (prevFrame.FrameDisposalMethod == FrameDisposal.Restore) |
||||
continue; |
||||
|
||||
if (prevFrame.FrameDisposalMethod == FrameDisposal.Background) |
||||
{ |
||||
ClearArea(prevFrame.Dimensions); |
||||
continue; |
||||
} |
||||
|
||||
RenderFrameAt(idx, writeableBitmap); |
||||
} |
||||
|
||||
RenderFrameAt(fIndex, writeableBitmap); |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private void RenderFrameAt(int idx, WriteableBitmap writeableBitmap) |
||||
{ |
||||
var tmpB = ArrayPool<byte>.Shared.Rent(MaxTempBuf); |
||||
|
||||
var curFrame = Frames[idx]; |
||||
DecompressFrameToIndexBuffer(curFrame, _indexBuf, tmpB); |
||||
|
||||
if (_hasFrameBackups & curFrame.ShouldBackup) |
||||
{ |
||||
Buffer.BlockCopy(_indexBuf, 0, _backupFrameIndexBuf, 0, curFrame.Dimensions.TotalPixels); |
||||
_backupFrame = idx; |
||||
} |
||||
|
||||
DrawFrame(curFrame, _indexBuf); |
||||
|
||||
_prevFrame = idx; |
||||
_hasNewFrame = true; |
||||
|
||||
using var lockedBitmap = writeableBitmap.Lock(); |
||||
WriteBackBufToFb(lockedBitmap.Address); |
||||
|
||||
ArrayPool<byte>.Shared.Return(tmpB); |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private void DrawFrame(GifFrame curFrame, Memory<byte> frameIndexSpan) |
||||
{ |
||||
var activeColorTable = curFrame.IsLocalColorTableUsed ? curFrame.LocalColorTable : Header.GlobarColorTable; |
||||
|
||||
var cX = curFrame.Dimensions.X; |
||||
var cY = curFrame.Dimensions.Y; |
||||
var cH = curFrame.Dimensions.Height; |
||||
var cW = curFrame.Dimensions.Width; |
||||
var tC = curFrame.TransparentColorIndex; |
||||
var hT = curFrame.HasTransparency; |
||||
|
||||
if (curFrame.IsInterlaced) |
||||
{ |
||||
for (var i = 0; i < 4; i++) |
||||
{ |
||||
var curPass = Pass[i]; |
||||
var y = curPass.Start; |
||||
while (y < cH) |
||||
{ |
||||
DrawRow(y); |
||||
y += curPass.Step; |
||||
} |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
for (var i = 0; i < cH; i++) |
||||
DrawRow(i); |
||||
} |
||||
|
||||
//for (var row = 0; row < cH; row++) |
||||
void DrawRow(int row) |
||||
{ |
||||
// Get the starting point of the current row on frame's index stream. |
||||
var indexOffset = row * cW; |
||||
|
||||
// Get the target backbuffer offset from the frames coords. |
||||
var targetOffset = PixCoord(cX, row + cY); |
||||
var len = _bitmapBackBuffer.Length; |
||||
|
||||
for (var i = 0; i < cW; i++) |
||||
{ |
||||
var indexColor = frameIndexSpan.Span[indexOffset + i]; |
||||
|
||||
if (activeColorTable == null || targetOffset >= len || indexColor > activeColorTable.Length) |
||||
return; |
||||
|
||||
if (!(hT & indexColor == tC)) |
||||
_bitmapBackBuffer[targetOffset] = activeColorTable[indexColor]; |
||||
|
||||
targetOffset++; |
||||
} |
||||
} |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private void DisposePreviousFrame() |
||||
{ |
||||
if (_prevFrame == -1) |
||||
return; |
||||
|
||||
var prevFrame = Frames[_prevFrame]; |
||||
|
||||
switch (prevFrame.FrameDisposalMethod) |
||||
{ |
||||
case FrameDisposal.Background: |
||||
ClearArea(prevFrame.Dimensions); |
||||
break; |
||||
case FrameDisposal.Restore: |
||||
if (_hasFrameBackups && _backupFrame != -1) |
||||
DrawFrame(Frames[_backupFrame], _backupFrameIndexBuf); |
||||
else |
||||
ClearArea(prevFrame.Dimensions); |
||||
break; |
||||
} |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private void ClearArea(GifRect area) |
||||
{ |
||||
for (var y = 0; y < area.Height; y++) |
||||
{ |
||||
var targetOffset = PixCoord(area.X, y + area.Y); |
||||
for (var x = 0; x < area.Width; x++) |
||||
_bitmapBackBuffer[targetOffset + x] = TransparentColor; |
||||
} |
||||
} |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
private void DecompressFrameToIndexBuffer(GifFrame curFrame, Span<byte> indexSpan, byte[] tempBuf) |
||||
{ |
||||
_fileStream.Position = curFrame.LzwStreamPosition; |
||||
var totalPixels = curFrame.Dimensions.TotalPixels; |
||||
|
||||
// Initialize GIF data stream decoder. |
||||
var dataSize = curFrame.LzwMinCodeSize; |
||||
var clear = 1 << dataSize; |
||||
var endOfInformation = clear + 1; |
||||
var available = clear + 2; |
||||
var oldCode = -1; |
||||
var codeSize = dataSize + 1; |
||||
var codeMask = (1 << codeSize) - 1; |
||||
|
||||
for (var code = 0; code < clear; code++) |
||||
{ |
||||
_prefixBuf[code] = 0; |
||||
_suffixBuf[code] = (byte)code; |
||||
} |
||||
|
||||
// Decode GIF pixel stream. |
||||
int bits, |
||||
first, |
||||
top, |
||||
pixelIndex; |
||||
var datum = bits = first = top = pixelIndex = 0; |
||||
|
||||
while (pixelIndex < totalPixels) |
||||
{ |
||||
var blockSize = _fileStream.ReadBlock(tempBuf); |
||||
|
||||
if (blockSize == 0) |
||||
break; |
||||
|
||||
var blockPos = 0; |
||||
|
||||
while (blockPos < blockSize) |
||||
{ |
||||
datum += tempBuf[blockPos] << bits; |
||||
blockPos++; |
||||
|
||||
bits += 8; |
||||
|
||||
while (bits >= codeSize) |
||||
{ |
||||
// Get the next code. |
||||
var code = datum & codeMask; |
||||
datum >>= codeSize; |
||||
bits -= codeSize; |
||||
|
||||
// Interpret the code |
||||
if (code == clear) |
||||
{ |
||||
// Reset decoder. |
||||
codeSize = dataSize + 1; |
||||
codeMask = (1 << codeSize) - 1; |
||||
available = clear + 2; |
||||
oldCode = -1; |
||||
continue; |
||||
} |
||||
|
||||
// Check for explicit end-of-stream |
||||
if (code == endOfInformation) |
||||
return; |
||||
|
||||
if (oldCode == -1) |
||||
{ |
||||
indexSpan[pixelIndex++] = _suffixBuf[code]; |
||||
oldCode = code; |
||||
first = code; |
||||
continue; |
||||
} |
||||
|
||||
var inCode = code; |
||||
if (code >= available) |
||||
{ |
||||
_pixelStack[top++] = (byte)first; |
||||
code = oldCode; |
||||
|
||||
if (top == MaxBits) |
||||
ThrowException(); |
||||
} |
||||
|
||||
while (code >= clear) |
||||
{ |
||||
if (code >= MaxBits || code == _prefixBuf[code]) |
||||
ThrowException(); |
||||
|
||||
_pixelStack[top++] = _suffixBuf[code]; |
||||
code = _prefixBuf[code]; |
||||
|
||||
if (top == MaxBits) |
||||
ThrowException(); |
||||
} |
||||
|
||||
first = _suffixBuf[code]; |
||||
_pixelStack[top++] = (byte)first; |
||||
|
||||
// Add new code to the dictionary |
||||
if (available < MaxStackSize) |
||||
{ |
||||
_prefixBuf[available] = (short)oldCode; |
||||
_suffixBuf[available] = (byte)first; |
||||
available++; |
||||
|
||||
if ((available & codeMask) == 0 && available < MaxStackSize) |
||||
{ |
||||
codeSize++; |
||||
codeMask += available; |
||||
} |
||||
} |
||||
|
||||
oldCode = inCode; |
||||
|
||||
// Drain the pixel stack. |
||||
do |
||||
{ |
||||
indexSpan[pixelIndex++] = _pixelStack[--top]; |
||||
} while (top > 0); |
||||
} |
||||
} |
||||
} |
||||
|
||||
while (pixelIndex < totalPixels) |
||||
indexSpan[pixelIndex++] = 0; // clear missing pixels |
||||
|
||||
void ThrowException() => throw new LzwDecompressionException(); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Directly copies the <see cref="GifColor"/> struct array to a bitmap IntPtr. |
||||
/// </summary> |
||||
private void WriteBackBufToFb(IntPtr targetPointer) |
||||
{ |
||||
if (_currentCtsToken.IsCancellationRequested) |
||||
return; |
||||
|
||||
if (!(_hasNewFrame & _bitmapBackBuffer != null)) |
||||
return; |
||||
|
||||
unsafe |
||||
{ |
||||
fixed (void* src = &_bitmapBackBuffer[0]) |
||||
Buffer.MemoryCopy(src, targetPointer.ToPointer(), (uint)_backBufferBytes, (uint)_backBufferBytes); |
||||
_hasNewFrame = false; |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Processes GIF Header. |
||||
/// </summary> |
||||
private void ProcessHeaderData() |
||||
{ |
||||
var str = _fileStream; |
||||
var tmpB = ArrayPool<byte>.Shared.Rent(MaxTempBuf); |
||||
var tempBuf = tmpB.AsSpan(); |
||||
|
||||
var _ = str.Read(tmpB, 0, 6); |
||||
|
||||
if (!tempBuf[..3].SequenceEqual(G87AMagic[..3].Span)) |
||||
throw new InvalidGifStreamException("Not a GIF stream."); |
||||
|
||||
if (!(tempBuf[..6].SequenceEqual(G87AMagic.Span) | tempBuf[..6].SequenceEqual(G89AMagic.Span))) |
||||
throw new InvalidGifStreamException( |
||||
"Unsupported GIF Version: " + Encoding.ASCII.GetString(tempBuf[..6].ToArray()) |
||||
); |
||||
|
||||
ProcessScreenDescriptor(tmpB); |
||||
|
||||
Header = new GifHeader |
||||
{ |
||||
Dimensions = _gifDimensions, |
||||
HasGlobalColorTable = _gctUsed, |
||||
// GlobalColorTableCacheID = _globalColorTable, |
||||
GlobarColorTable = ProcessColorTable(ref str, tmpB, _gctSize), |
||||
GlobalColorTableSize = _gctSize, |
||||
BackgroundColorIndex = _bgIndex, |
||||
HeaderSize = _fileStream.Position |
||||
}; |
||||
|
||||
ArrayPool<byte>.Shared.Return(tmpB); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Parses colors from file stream to target color table. |
||||
/// </summary> |
||||
private static GifColor[] ProcessColorTable(ref Stream stream, byte[] rawBufSpan, int nColors) |
||||
{ |
||||
var nBytes = 3 * nColors; |
||||
var target = new GifColor[nColors]; |
||||
|
||||
var n = stream.Read(rawBufSpan, 0, nBytes); |
||||
|
||||
if (n < nBytes) |
||||
throw new InvalidOperationException("Wrong color table bytes."); |
||||
|
||||
int i = 0, |
||||
j = 0; |
||||
|
||||
while (i < nColors) |
||||
{ |
||||
var r = rawBufSpan[j++]; |
||||
var g = rawBufSpan[j++]; |
||||
var b = rawBufSpan[j++]; |
||||
target[i++] = new GifColor(r, g, b); |
||||
} |
||||
|
||||
return target; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Parses screen and other GIF descriptors. |
||||
/// </summary> |
||||
private void ProcessScreenDescriptor(byte[] tempBuf) |
||||
{ |
||||
var width = _fileStream.ReadUShortS(tempBuf); |
||||
var height = _fileStream.ReadUShortS(tempBuf); |
||||
|
||||
var packed = _fileStream.ReadByteS(tempBuf); |
||||
|
||||
_gctUsed = (packed & 0x80) != 0; |
||||
_gctSize = 2 << (packed & 7); |
||||
_bgIndex = _fileStream.ReadByteS(tempBuf); |
||||
|
||||
_gifDimensions = new GifRect(0, 0, width, height); |
||||
_fileStream.Skip(1); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Parses all frame data. |
||||
/// </summary> |
||||
private void ProcessFrameData() |
||||
{ |
||||
_fileStream.Position = Header.HeaderSize; |
||||
|
||||
var tempBuf = ArrayPool<byte>.Shared.Rent(MaxTempBuf); |
||||
|
||||
var terminate = false; |
||||
var curFrame = 0; |
||||
|
||||
Frames.Add(new GifFrame()); |
||||
|
||||
do |
||||
{ |
||||
var blockType = (BlockTypes)_fileStream.ReadByteS(tempBuf); |
||||
|
||||
switch (blockType) |
||||
{ |
||||
case BlockTypes.Empty: |
||||
break; |
||||
|
||||
case BlockTypes.Extension: |
||||
ProcessExtensions(ref curFrame, tempBuf); |
||||
break; |
||||
|
||||
case BlockTypes.ImageDescriptor: |
||||
ProcessImageDescriptor(ref curFrame, tempBuf); |
||||
_fileStream.SkipBlocks(tempBuf); |
||||
break; |
||||
|
||||
case BlockTypes.Trailer: |
||||
Frames.RemoveAt(Frames.Count - 1); |
||||
terminate = true; |
||||
break; |
||||
|
||||
default: |
||||
_fileStream.SkipBlocks(tempBuf); |
||||
break; |
||||
} |
||||
|
||||
// Break the loop when the stream is not valid anymore. |
||||
if (_fileStream.Position >= _fileStream.Length & terminate == false) |
||||
throw new InvalidProgramException("Reach the end of the filestream without trailer block."); |
||||
} while (!terminate); |
||||
|
||||
ArrayPool<byte>.Shared.Return(tempBuf); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Parses GIF Image Descriptor Block. |
||||
/// </summary> |
||||
private void ProcessImageDescriptor(ref int curFrame, byte[] tempBuf) |
||||
{ |
||||
var str = _fileStream; |
||||
var currentFrame = Frames[curFrame]; |
||||
|
||||
// Parse frame dimensions. |
||||
var frameX = str.ReadUShortS(tempBuf); |
||||
var frameY = str.ReadUShortS(tempBuf); |
||||
var frameW = str.ReadUShortS(tempBuf); |
||||
var frameH = str.ReadUShortS(tempBuf); |
||||
|
||||
frameW = (ushort)Math.Min(frameW, _gifDimensions.Width - frameX); |
||||
frameH = (ushort)Math.Min(frameH, _gifDimensions.Height - frameY); |
||||
|
||||
currentFrame.Dimensions = new GifRect(frameX, frameY, frameW, frameH); |
||||
|
||||
// Unpack interlace and lct info. |
||||
var packed = str.ReadByteS(tempBuf); |
||||
currentFrame.IsInterlaced = (packed & 0x40) != 0; |
||||
currentFrame.IsLocalColorTableUsed = (packed & 0x80) != 0; |
||||
currentFrame.LocalColorTableSize = (int)Math.Pow(2, (packed & 0x07) + 1); |
||||
|
||||
if (currentFrame.IsLocalColorTableUsed) |
||||
currentFrame.LocalColorTable = ProcessColorTable(ref str, tempBuf, currentFrame.LocalColorTableSize); |
||||
|
||||
currentFrame.LzwMinCodeSize = str.ReadByteS(tempBuf); |
||||
currentFrame.LzwStreamPosition = str.Position; |
||||
|
||||
curFrame += 1; |
||||
Frames.Add(new GifFrame()); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Parses GIF Extension Blocks. |
||||
/// </summary> |
||||
private void ProcessExtensions(ref int curFrame, byte[] tempBuf) |
||||
{ |
||||
var extType = (ExtensionType)_fileStream.ReadByteS(tempBuf); |
||||
|
||||
switch (extType) |
||||
{ |
||||
case ExtensionType.GraphicsControl: |
||||
|
||||
_fileStream.ReadBlock(tempBuf); |
||||
var currentFrame = Frames[curFrame]; |
||||
var packed = tempBuf[0]; |
||||
|
||||
currentFrame.FrameDisposalMethod = (FrameDisposal)((packed & 0x1c) >> 2); |
||||
|
||||
if ( |
||||
currentFrame.FrameDisposalMethod != FrameDisposal.Restore |
||||
&& currentFrame.FrameDisposalMethod != FrameDisposal.Background |
||||
) |
||||
currentFrame.ShouldBackup = true; |
||||
|
||||
currentFrame.HasTransparency = (packed & 1) != 0; |
||||
|
||||
currentFrame.FrameDelay = TimeSpan.FromMilliseconds(SpanToShort(tempBuf.AsSpan(1)) * 10); |
||||
|
||||
if (currentFrame.FrameDelay <= FrameDelayThreshold) |
||||
currentFrame.FrameDelay = FrameDelayDefault; |
||||
|
||||
currentFrame.TransparentColorIndex = tempBuf[3]; |
||||
break; |
||||
|
||||
case ExtensionType.Application: |
||||
var blockLen = _fileStream.ReadBlock(tempBuf); |
||||
var _ = tempBuf.AsSpan(0, blockLen); |
||||
var blockHeader = tempBuf.AsSpan(0, NetscapeMagic.Length); |
||||
|
||||
if (blockHeader.SequenceEqual(NetscapeMagic.Span)) |
||||
{ |
||||
var count = 1; |
||||
|
||||
while (count > 0) |
||||
count = _fileStream.ReadBlock(tempBuf); |
||||
|
||||
var iterationCount = SpanToShort(tempBuf.AsSpan(1)); |
||||
|
||||
Header.Iterations = iterationCount; |
||||
} |
||||
else |
||||
_fileStream.SkipBlocks(tempBuf); |
||||
|
||||
break; |
||||
|
||||
default: |
||||
_fileStream.SkipBlocks(tempBuf); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,20 +0,0 @@
|
||||
using System; |
||||
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public class GifFrame |
||||
{ |
||||
public bool HasTransparency, |
||||
IsInterlaced, |
||||
IsLocalColorTableUsed; |
||||
public byte TransparentColorIndex; |
||||
public int LzwMinCodeSize, |
||||
LocalColorTableSize; |
||||
public long LzwStreamPosition; |
||||
public TimeSpan FrameDelay; |
||||
public FrameDisposal FrameDisposalMethod; |
||||
public bool ShouldBackup; |
||||
public GifRect Dimensions; |
||||
public GifColor[] LocalColorTable; |
||||
} |
||||
} |
@ -1,19 +0,0 @@
|
||||
// Licensed under the MIT License. |
||||
// Copyright (C) 2018 Jumar A. Macato, All Rights Reserved. |
||||
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public class GifHeader |
||||
{ |
||||
public bool HasGlobalColorTable; |
||||
public int GlobalColorTableSize; |
||||
public ulong GlobalColorTableCacheId; |
||||
public int BackgroundColorIndex; |
||||
public long HeaderSize; |
||||
internal int Iterations = -1; |
||||
public GifRepeatBehavior IterationCount; |
||||
public GifRect Dimensions; |
||||
private GifColor[] _globarColorTable; |
||||
public GifColor[] GlobarColorTable; |
||||
} |
||||
} |
@ -1,43 +0,0 @@
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public readonly struct GifRect |
||||
{ |
||||
public int X { get; } |
||||
public int Y { get; } |
||||
public int Width { get; } |
||||
public int Height { get; } |
||||
public int TotalPixels { get; } |
||||
|
||||
public GifRect(int x, int y, int width, int height) |
||||
{ |
||||
X = x; |
||||
Y = y; |
||||
Width = width; |
||||
Height = height; |
||||
TotalPixels = width * height; |
||||
} |
||||
|
||||
public static bool operator ==(GifRect a, GifRect b) |
||||
{ |
||||
return a.X == b.X && a.Y == b.Y && a.Width == b.Width && a.Height == b.Height; |
||||
} |
||||
|
||||
public static bool operator !=(GifRect a, GifRect b) |
||||
{ |
||||
return !(a == b); |
||||
} |
||||
|
||||
public override bool Equals(object obj) |
||||
{ |
||||
if (obj == null || GetType() != obj.GetType()) |
||||
return false; |
||||
|
||||
return this == (GifRect)obj; |
||||
} |
||||
|
||||
public override int GetHashCode() |
||||
{ |
||||
return X.GetHashCode() ^ Y.GetHashCode() | Width.GetHashCode() ^ Height.GetHashCode(); |
||||
} |
||||
} |
||||
} |
@ -1,8 +0,0 @@
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
public class GifRepeatBehavior |
||||
{ |
||||
public bool LoopForever { get; set; } |
||||
public int? Count { get; set; } |
||||
} |
||||
} |
@ -1,23 +0,0 @@
|
||||
// Licensed under the MIT License. |
||||
// Copyright (C) 2018 Jumar A. Macato, All Rights Reserved. |
||||
|
||||
using System; |
||||
using System.Runtime.Serialization; |
||||
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
[Serializable] |
||||
public class InvalidGifStreamException : Exception |
||||
{ |
||||
public InvalidGifStreamException() { } |
||||
|
||||
public InvalidGifStreamException(string message) |
||||
: base(message) { } |
||||
|
||||
public InvalidGifStreamException(string message, Exception innerException) |
||||
: base(message, innerException) { } |
||||
|
||||
protected InvalidGifStreamException(SerializationInfo info, StreamingContext context) |
||||
: base(info, context) { } |
||||
} |
||||
} |
@ -1,23 +0,0 @@
|
||||
// Licensed under the MIT License. |
||||
// Copyright (C) 2018 Jumar A. Macato, All Rights Reserved. |
||||
|
||||
using System; |
||||
using System.Runtime.Serialization; |
||||
|
||||
namespace Avalonia.Gif.Decoding |
||||
{ |
||||
[Serializable] |
||||
public class LzwDecompressionException : Exception |
||||
{ |
||||
public LzwDecompressionException() { } |
||||
|
||||
public LzwDecompressionException(string message) |
||||
: base(message) { } |
||||
|
||||
public LzwDecompressionException(string message, Exception innerException) |
||||
: base(message, innerException) { } |
||||
|
||||
protected LzwDecompressionException(SerializationInfo info, StreamingContext context) |
||||
: base(info, context) { } |
||||
} |
||||
} |
@ -1,81 +0,0 @@
|
||||
using System; |
||||
using System.Diagnostics; |
||||
using System.IO; |
||||
using System.Runtime.CompilerServices; |
||||
|
||||
namespace Avalonia.Gif.Extensions |
||||
{ |
||||
[DebuggerStepThrough] |
||||
internal static class StreamExtensions |
||||
{ |
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static ushort SpanToShort(Span<byte> b) => (ushort)(b[0] | (b[1] << 8)); |
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static void Skip(this Stream stream, long count) |
||||
{ |
||||
stream.Position += count; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Read a Gif block from stream while advancing the position. |
||||
/// </summary> |
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static int ReadBlock(this Stream stream, byte[] tempBuf) |
||||
{ |
||||
stream.Read(tempBuf, 0, 1); |
||||
|
||||
var blockLength = (int)tempBuf[0]; |
||||
|
||||
if (blockLength > 0) |
||||
stream.Read(tempBuf, 0, blockLength); |
||||
|
||||
// Guard against infinite loop. |
||||
if (stream.Position >= stream.Length) |
||||
throw new InvalidGifStreamException("Reach the end of the filestream without trailer block."); |
||||
|
||||
return blockLength; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Skips GIF blocks until it encounters an empty block. |
||||
/// </summary> |
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static void SkipBlocks(this Stream stream, byte[] tempBuf) |
||||
{ |
||||
int blockLength; |
||||
do |
||||
{ |
||||
stream.Read(tempBuf, 0, 1); |
||||
|
||||
blockLength = tempBuf[0]; |
||||
stream.Position += blockLength; |
||||
|
||||
// Guard against infinite loop. |
||||
if (stream.Position >= stream.Length) |
||||
throw new InvalidGifStreamException("Reach the end of the filestream without trailer block."); |
||||
} while (blockLength > 0); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Read a <see cref="ushort"/> from stream by providing a temporary buffer. |
||||
/// </summary> |
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static ushort ReadUShortS(this Stream stream, byte[] tempBuf) |
||||
{ |
||||
stream.Read(tempBuf, 0, 2); |
||||
return SpanToShort(tempBuf); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Read a <see cref="ushort"/> from stream by providing a temporary buffer. |
||||
/// </summary> |
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)] |
||||
public static byte ReadByteS(this Stream stream, byte[] tempBuf) |
||||
{ |
||||
stream.Read(tempBuf, 0, 1); |
||||
var finalVal = tempBuf[0]; |
||||
return finalVal; |
||||
} |
||||
} |
||||
} |
@ -1,297 +0,0 @@
|
||||
using System; |
||||
using System.IO; |
||||
using System.Numerics; |
||||
using Avalonia; |
||||
using Avalonia.Animation; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Logging; |
||||
using Avalonia.Media; |
||||
using Avalonia.Rendering.Composition; |
||||
using Avalonia.VisualTree; |
||||
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
public class GifImage : Control |
||||
{ |
||||
public static readonly StyledProperty<string> SourceUriRawProperty = AvaloniaProperty.Register< |
||||
GifImage, |
||||
string |
||||
>("SourceUriRaw"); |
||||
|
||||
public static readonly StyledProperty<Uri> SourceUriProperty = AvaloniaProperty.Register<GifImage, Uri>( |
||||
"SourceUri" |
||||
); |
||||
|
||||
public static readonly StyledProperty<Stream> SourceStreamProperty = AvaloniaProperty.Register< |
||||
GifImage, |
||||
Stream |
||||
>("SourceStream"); |
||||
|
||||
public static readonly StyledProperty<IterationCount> IterationCountProperty = AvaloniaProperty.Register< |
||||
GifImage, |
||||
IterationCount |
||||
>("IterationCount", IterationCount.Infinite); |
||||
|
||||
private IGifInstance? _gifInstance; |
||||
|
||||
public static readonly StyledProperty<StretchDirection> StretchDirectionProperty = AvaloniaProperty.Register< |
||||
GifImage, |
||||
StretchDirection |
||||
>("StretchDirection"); |
||||
|
||||
public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register<GifImage, Stretch>( |
||||
"Stretch" |
||||
); |
||||
|
||||
private CompositionCustomVisual? _customVisual; |
||||
|
||||
private object? _initialSource = null; |
||||
|
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) |
||||
{ |
||||
switch (change.Property.Name) |
||||
{ |
||||
case nameof(SourceUriRaw): |
||||
case nameof(SourceUri): |
||||
case nameof(SourceStream): |
||||
SourceChanged(change); |
||||
break; |
||||
case nameof(Stretch): |
||||
case nameof(StretchDirection): |
||||
InvalidateArrange(); |
||||
InvalidateMeasure(); |
||||
Update(); |
||||
break; |
||||
case nameof(IterationCount): |
||||
IterationCountChanged(change); |
||||
break; |
||||
case nameof(Bounds): |
||||
Update(); |
||||
break; |
||||
} |
||||
|
||||
base.OnPropertyChanged(change); |
||||
} |
||||
|
||||
public string SourceUriRaw |
||||
{ |
||||
get => GetValue(SourceUriRawProperty); |
||||
set => SetValue(SourceUriRawProperty, value); |
||||
} |
||||
|
||||
public Uri SourceUri |
||||
{ |
||||
get => GetValue(SourceUriProperty); |
||||
set => SetValue(SourceUriProperty, value); |
||||
} |
||||
|
||||
public Stream SourceStream |
||||
{ |
||||
get => GetValue(SourceStreamProperty); |
||||
set => SetValue(SourceStreamProperty, value); |
||||
} |
||||
|
||||
public IterationCount IterationCount |
||||
{ |
||||
get => GetValue(IterationCountProperty); |
||||
set => SetValue(IterationCountProperty, value); |
||||
} |
||||
|
||||
public StretchDirection StretchDirection |
||||
{ |
||||
get => GetValue(StretchDirectionProperty); |
||||
set => SetValue(StretchDirectionProperty, value); |
||||
} |
||||
|
||||
public Stretch Stretch |
||||
{ |
||||
get => GetValue(StretchProperty); |
||||
set => SetValue(StretchProperty, value); |
||||
} |
||||
|
||||
private static void IterationCountChanged(AvaloniaPropertyChangedEventArgs e) |
||||
{ |
||||
var image = e.Sender as GifImage; |
||||
if (image is null || e.NewValue is not IterationCount iterationCount) |
||||
return; |
||||
|
||||
image.IterationCount = iterationCount; |
||||
} |
||||
|
||||
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) |
||||
{ |
||||
var compositor = ElementComposition.GetElementVisual(this)?.Compositor; |
||||
if (compositor == null || _customVisual?.Compositor == compositor) |
||||
return; |
||||
_customVisual = compositor.CreateCustomVisual(new CustomVisualHandler()); |
||||
ElementComposition.SetElementChildVisual(this, _customVisual); |
||||
_customVisual.SendHandlerMessage(CustomVisualHandler.StartMessage); |
||||
|
||||
if (_initialSource is not null) |
||||
{ |
||||
UpdateGifInstance(_initialSource); |
||||
_initialSource = null; |
||||
} |
||||
|
||||
Update(); |
||||
base.OnAttachedToVisualTree(e); |
||||
} |
||||
|
||||
private void Update() |
||||
{ |
||||
if (_customVisual is null || _gifInstance is null) |
||||
return; |
||||
|
||||
var dpi = this.GetVisualRoot()?.RenderScaling ?? 1.0; |
||||
var sourceSize = _gifInstance.GifPixelSize.ToSize(dpi); |
||||
var viewPort = new Rect(Bounds.Size); |
||||
|
||||
var scale = Stretch.CalculateScaling(Bounds.Size, sourceSize, StretchDirection); |
||||
var scaledSize = sourceSize * scale; |
||||
var destRect = viewPort.CenterRect(new Rect(scaledSize)).Intersect(viewPort); |
||||
|
||||
if (Stretch == Stretch.None) |
||||
{ |
||||
_customVisual.Size = new Vector2((float)sourceSize.Width, (float)sourceSize.Height); |
||||
} |
||||
else |
||||
{ |
||||
_customVisual.Size = new Vector2((float)destRect.Size.Width, (float)destRect.Size.Height); |
||||
} |
||||
|
||||
_customVisual.Offset = new Vector3((float)destRect.Position.X, (float)destRect.Position.Y, 0); |
||||
} |
||||
|
||||
private class CustomVisualHandler : CompositionCustomVisualHandler |
||||
{ |
||||
private TimeSpan _animationElapsed; |
||||
private TimeSpan? _lastServerTime; |
||||
private IGifInstance? _currentInstance; |
||||
private bool _running; |
||||
|
||||
public static readonly object StopMessage = new(), |
||||
StartMessage = new(); |
||||
|
||||
public override void OnMessage(object message) |
||||
{ |
||||
if (message == StartMessage) |
||||
{ |
||||
_running = true; |
||||
_lastServerTime = null; |
||||
RegisterForNextAnimationFrameUpdate(); |
||||
} |
||||
else if (message == StopMessage) |
||||
{ |
||||
_running = false; |
||||
} |
||||
else if (message is IGifInstance instance) |
||||
{ |
||||
_currentInstance?.Dispose(); |
||||
_currentInstance = instance; |
||||
} |
||||
} |
||||
|
||||
public override void OnAnimationFrameUpdate() |
||||
{ |
||||
if (!_running) |
||||
return; |
||||
Invalidate(); |
||||
RegisterForNextAnimationFrameUpdate(); |
||||
} |
||||
|
||||
public override void OnRender(ImmediateDrawingContext drawingContext) |
||||
{ |
||||
if (_running) |
||||
{ |
||||
if (_lastServerTime.HasValue) |
||||
_animationElapsed += (CompositionNow - _lastServerTime.Value); |
||||
_lastServerTime = CompositionNow; |
||||
} |
||||
|
||||
try |
||||
{ |
||||
if (_currentInstance is null || _currentInstance.IsDisposed) |
||||
return; |
||||
|
||||
var bitmap = _currentInstance.ProcessFrameTime(_animationElapsed); |
||||
if (bitmap is not null) |
||||
{ |
||||
drawingContext.DrawBitmap( |
||||
bitmap, |
||||
new Rect(_currentInstance.GifPixelSize.ToSize(1)), |
||||
GetRenderBounds() |
||||
); |
||||
} |
||||
} |
||||
catch (Exception e) |
||||
{ |
||||
Logger.Sink?.Log(LogEventLevel.Error, "GifImage Renderer ", this, e.ToString()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Measures the control. |
||||
/// </summary> |
||||
/// <param name="availableSize">The available size.</param> |
||||
/// <returns>The desired size of the control.</returns> |
||||
protected override Size MeasureOverride(Size availableSize) |
||||
{ |
||||
var result = new Size(); |
||||
var scaling = this.GetVisualRoot()?.RenderScaling ?? 1.0; |
||||
if (_gifInstance != null) |
||||
{ |
||||
result = Stretch.CalculateSize( |
||||
availableSize, |
||||
_gifInstance.GifPixelSize.ToSize(scaling), |
||||
StretchDirection |
||||
); |
||||
} |
||||
|
||||
return result; |
||||
} |
||||
|
||||
/// <inheritdoc/> |
||||
protected override Size ArrangeOverride(Size finalSize) |
||||
{ |
||||
if (_gifInstance is null) |
||||
return new Size(); |
||||
var scaling = this.GetVisualRoot()?.RenderScaling ?? 1.0; |
||||
var sourceSize = _gifInstance.GifPixelSize.ToSize(scaling); |
||||
var result = Stretch.CalculateSize(finalSize, sourceSize); |
||||
return result; |
||||
} |
||||
|
||||
private void SourceChanged(AvaloniaPropertyChangedEventArgs e) |
||||
{ |
||||
if ( |
||||
e.NewValue is null |
||||
|| (e.NewValue is string value && !Uri.IsWellFormedUriString(value, UriKind.Absolute)) |
||||
) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
if (_customVisual is null) |
||||
{ |
||||
_initialSource = e.NewValue; |
||||
return; |
||||
} |
||||
|
||||
UpdateGifInstance(e.NewValue); |
||||
|
||||
InvalidateArrange(); |
||||
InvalidateMeasure(); |
||||
Update(); |
||||
} |
||||
|
||||
private void UpdateGifInstance(object source) |
||||
{ |
||||
_gifInstance?.Dispose(); |
||||
_gifInstance = new WebpInstance(source); |
||||
// _gifInstance = new GifInstance(source); |
||||
_gifInstance.IterationCount = IterationCount; |
||||
_customVisual?.SendHandlerMessage(_gifInstance); |
||||
} |
||||
} |
||||
} |
@ -1,147 +0,0 @@
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using System.Linq; |
||||
using System.Threading; |
||||
using Avalonia; |
||||
using Avalonia.Animation; |
||||
using Avalonia.Gif.Decoding; |
||||
using Avalonia.Media.Imaging; |
||||
using Avalonia.Platform; |
||||
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
public class GifInstance : IGifInstance |
||||
{ |
||||
public IterationCount IterationCount { get; set; } |
||||
public bool AutoStart { get; private set; } = true; |
||||
private readonly GifDecoder _gifDecoder; |
||||
private readonly WriteableBitmap? _targetBitmap; |
||||
private TimeSpan _totalTime; |
||||
private readonly List<TimeSpan> _frameTimes; |
||||
private uint _iterationCount; |
||||
private int _currentFrameIndex; |
||||
private readonly List<ulong> _colorTableIdList; |
||||
|
||||
public CancellationTokenSource CurrentCts { get; } |
||||
|
||||
internal GifInstance(object newValue) |
||||
: this( |
||||
newValue switch |
||||
{ |
||||
Stream s => s, |
||||
Uri u => GetStreamFromUri(u), |
||||
string str => GetStreamFromString(str), |
||||
_ => throw new InvalidDataException("Unsupported source object") |
||||
} |
||||
) { } |
||||
|
||||
public GifInstance(string uri) |
||||
: this(GetStreamFromString(uri)) { } |
||||
|
||||
public GifInstance(Uri uri) |
||||
: this(GetStreamFromUri(uri)) { } |
||||
|
||||
public GifInstance(Stream currentStream) |
||||
{ |
||||
if (!currentStream.CanSeek) |
||||
throw new InvalidDataException("The provided stream is not seekable."); |
||||
|
||||
if (!currentStream.CanRead) |
||||
throw new InvalidOperationException("Can't read the stream provided."); |
||||
|
||||
currentStream.Seek(0, SeekOrigin.Begin); |
||||
|
||||
CurrentCts = new CancellationTokenSource(); |
||||
|
||||
_gifDecoder = new GifDecoder(currentStream, CurrentCts.Token); |
||||
var pixSize = new PixelSize(_gifDecoder.Header.Dimensions.Width, _gifDecoder.Header.Dimensions.Height); |
||||
|
||||
_targetBitmap = new WriteableBitmap(pixSize, new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Opaque); |
||||
GifPixelSize = pixSize; |
||||
|
||||
_totalTime = TimeSpan.Zero; |
||||
|
||||
_frameTimes = _gifDecoder |
||||
.Frames |
||||
.Select(frame => |
||||
{ |
||||
_totalTime = _totalTime.Add(frame.FrameDelay); |
||||
return _totalTime; |
||||
}) |
||||
.ToList(); |
||||
|
||||
_gifDecoder.RenderFrame(0, _targetBitmap); |
||||
} |
||||
|
||||
private static Stream GetStreamFromString(string str) |
||||
{ |
||||
if (!Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var res)) |
||||
{ |
||||
throw new InvalidCastException("The string provided can't be converted to URI."); |
||||
} |
||||
|
||||
return GetStreamFromUri(res); |
||||
} |
||||
|
||||
private static Stream GetStreamFromUri(Uri uri) |
||||
{ |
||||
var uriString = uri.OriginalString.Trim(); |
||||
|
||||
if (!uriString.StartsWith("resm") && !uriString.StartsWith("avares")) |
||||
{ |
||||
return new FileStream(uriString, FileMode.Open, FileAccess.Read); |
||||
} |
||||
|
||||
return AssetLoader.Open(uri); |
||||
} |
||||
|
||||
public int GifFrameCount => _frameTimes.Count; |
||||
|
||||
public PixelSize GifPixelSize { get; } |
||||
|
||||
public void Dispose() |
||||
{ |
||||
IsDisposed = true; |
||||
CurrentCts.Cancel(); |
||||
_targetBitmap?.Dispose(); |
||||
} |
||||
|
||||
public bool IsDisposed { get; private set; } |
||||
|
||||
public WriteableBitmap? ProcessFrameTime(TimeSpan stopwatchElapsed) |
||||
{ |
||||
if (!IterationCount.IsInfinite && _iterationCount > IterationCount.Value) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
if (CurrentCts.IsCancellationRequested || _targetBitmap is null) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
var elapsedTicks = stopwatchElapsed.Ticks; |
||||
var timeModulus = TimeSpan.FromTicks(elapsedTicks % _totalTime.Ticks); |
||||
var targetFrame = _frameTimes.FirstOrDefault(x => timeModulus < x); |
||||
var currentFrame = _frameTimes.IndexOf(targetFrame); |
||||
if (currentFrame == -1) |
||||
currentFrame = 0; |
||||
|
||||
if (_currentFrameIndex == currentFrame) |
||||
return _targetBitmap; |
||||
|
||||
_iterationCount = (uint)(elapsedTicks / _totalTime.Ticks); |
||||
|
||||
return ProcessFrameIndex(currentFrame); |
||||
} |
||||
|
||||
internal WriteableBitmap ProcessFrameIndex(int frameIndex) |
||||
{ |
||||
_gifDecoder.RenderFrame(frameIndex, _targetBitmap); |
||||
_currentFrameIndex = frameIndex; |
||||
|
||||
return _targetBitmap; |
||||
} |
||||
} |
||||
} |
@ -1,15 +0,0 @@
|
||||
using Avalonia.Animation; |
||||
using Avalonia.Media.Imaging; |
||||
|
||||
namespace Avalonia.Gif; |
||||
|
||||
public interface IGifInstance : IDisposable |
||||
{ |
||||
IterationCount IterationCount { get; set; } |
||||
bool AutoStart { get; } |
||||
CancellationTokenSource CurrentCts { get; } |
||||
int GifFrameCount { get; } |
||||
PixelSize GifPixelSize { get; } |
||||
bool IsDisposed { get; } |
||||
WriteableBitmap? ProcessFrameTime(TimeSpan stopwatchElapsed); |
||||
} |
@ -1,20 +0,0 @@
|
||||
using System; |
||||
using System.Runtime.Serialization; |
||||
|
||||
namespace Avalonia.Gif |
||||
{ |
||||
[Serializable] |
||||
internal class InvalidGifStreamException : Exception |
||||
{ |
||||
public InvalidGifStreamException() { } |
||||
|
||||
public InvalidGifStreamException(string message) |
||||
: base(message) { } |
||||
|
||||
public InvalidGifStreamException(string message, Exception innerException) |
||||
: base(message, innerException) { } |
||||
|
||||
protected InvalidGifStreamException(SerializationInfo info, StreamingContext context) |
||||
: base(info, context) { } |
||||
} |
||||
} |
@ -1,180 +0,0 @@
|
||||
using Avalonia.Animation; |
||||
using Avalonia.Media.Imaging; |
||||
using Avalonia.Platform; |
||||
using SkiaSharp; |
||||
|
||||
namespace Avalonia.Gif; |
||||
|
||||
public class WebpInstance : IGifInstance |
||||
{ |
||||
public IterationCount IterationCount { get; set; } |
||||
public bool AutoStart { get; private set; } = true; |
||||
|
||||
private readonly WriteableBitmap? _targetBitmap; |
||||
private TimeSpan _totalTime; |
||||
private readonly List<TimeSpan> _frameTimes; |
||||
private uint _iterationCount; |
||||
private int _currentFrameIndex; |
||||
|
||||
private SKCodec? _codec; |
||||
|
||||
public CancellationTokenSource CurrentCts { get; } |
||||
|
||||
internal WebpInstance(object newValue) |
||||
: this( |
||||
newValue switch |
||||
{ |
||||
Stream s => s, |
||||
Uri u => GetStreamFromUri(u), |
||||
string str => GetStreamFromString(str), |
||||
_ => throw new InvalidDataException("Unsupported source object") |
||||
} |
||||
) { } |
||||
|
||||
public WebpInstance(string uri) |
||||
: this(GetStreamFromString(uri)) { } |
||||
|
||||
public WebpInstance(Uri uri) |
||||
: this(GetStreamFromUri(uri)) { } |
||||
|
||||
public WebpInstance(Stream currentStream) |
||||
{ |
||||
if (!currentStream.CanSeek) |
||||
throw new InvalidDataException("The provided stream is not seekable."); |
||||
|
||||
if (!currentStream.CanRead) |
||||
throw new InvalidOperationException("Can't read the stream provided."); |
||||
|
||||
currentStream.Seek(0, SeekOrigin.Begin); |
||||
|
||||
CurrentCts = new CancellationTokenSource(); |
||||
|
||||
var managedStream = new SKManagedStream(currentStream); |
||||
_codec = SKCodec.Create(managedStream); |
||||
|
||||
var pixSize = new PixelSize(_codec.Info.Width, _codec.Info.Height); |
||||
|
||||
_targetBitmap = new WriteableBitmap(pixSize, new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Opaque); |
||||
GifPixelSize = pixSize; |
||||
|
||||
_totalTime = TimeSpan.Zero; |
||||
|
||||
_frameTimes = _codec |
||||
.FrameInfo |
||||
.Select(frame => |
||||
{ |
||||
_totalTime = _totalTime.Add(TimeSpan.FromMilliseconds(frame.Duration)); |
||||
return _totalTime; |
||||
}) |
||||
.ToList(); |
||||
|
||||
RenderFrame(_codec, _targetBitmap, 0); |
||||
} |
||||
|
||||
private static void RenderFrame(SKCodec codec, WriteableBitmap targetBitmap, int index) |
||||
{ |
||||
codec.GetFrameInfo(index, out var frameInfo); |
||||
|
||||
var info = new SKImageInfo(codec.Info.Width, codec.Info.Height); |
||||
var decodeInfo = info.WithAlphaType(frameInfo.AlphaType); |
||||
|
||||
using var frameBuffer = targetBitmap.Lock(); |
||||
|
||||
var result = codec.GetPixels(decodeInfo, frameBuffer.Address, new SKCodecOptions(index)); |
||||
|
||||
if (result != SKCodecResult.Success) |
||||
throw new InvalidDataException($"Could not decode frame {index} of {codec.FrameCount}."); |
||||
} |
||||
|
||||
private static void RenderFrame(SKCodec codec, WriteableBitmap targetBitmap, int index, int priorIndex) |
||||
{ |
||||
codec.GetFrameInfo(index, out var frameInfo); |
||||
|
||||
var info = new SKImageInfo(codec.Info.Width, codec.Info.Height); |
||||
var decodeInfo = info.WithAlphaType(frameInfo.AlphaType); |
||||
|
||||
using var frameBuffer = targetBitmap.Lock(); |
||||
|
||||
var result = codec.GetPixels(decodeInfo, frameBuffer.Address, new SKCodecOptions(index, priorIndex)); |
||||
|
||||
if (result != SKCodecResult.Success) |
||||
throw new InvalidDataException($"Could not decode frame {index} of {codec.FrameCount}."); |
||||
} |
||||
|
||||
private static Stream GetStreamFromString(string str) |
||||
{ |
||||
if (!Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var res)) |
||||
{ |
||||
throw new InvalidCastException("The string provided can't be converted to URI."); |
||||
} |
||||
|
||||
return GetStreamFromUri(res); |
||||
} |
||||
|
||||
private static Stream GetStreamFromUri(Uri uri) |
||||
{ |
||||
var uriString = uri.OriginalString.Trim(); |
||||
|
||||
if (!uriString.StartsWith("resm") && !uriString.StartsWith("avares")) |
||||
{ |
||||
return new FileStream(uriString, FileMode.Open, FileAccess.Read); |
||||
} |
||||
|
||||
return AssetLoader.Open(uri); |
||||
} |
||||
|
||||
public int GifFrameCount => _frameTimes.Count; |
||||
|
||||
public PixelSize GifPixelSize { get; } |
||||
|
||||
public void Dispose() |
||||
{ |
||||
IsDisposed = true; |
||||
CurrentCts.Cancel(); |
||||
_targetBitmap?.Dispose(); |
||||
_codec?.Dispose(); |
||||
} |
||||
|
||||
public bool IsDisposed { get; private set; } |
||||
|
||||
public WriteableBitmap? ProcessFrameTime(TimeSpan stopwatchElapsed) |
||||
{ |
||||
if (!IterationCount.IsInfinite && _iterationCount > IterationCount.Value) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
if (CurrentCts.IsCancellationRequested || _targetBitmap is null) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
var elapsedTicks = stopwatchElapsed.Ticks; |
||||
var timeModulus = TimeSpan.FromTicks(elapsedTicks % _totalTime.Ticks); |
||||
var targetFrame = _frameTimes.FirstOrDefault(x => timeModulus < x); |
||||
var currentFrame = _frameTimes.IndexOf(targetFrame); |
||||
if (currentFrame == -1) |
||||
currentFrame = 0; |
||||
|
||||
if (_currentFrameIndex == currentFrame) |
||||
return _targetBitmap; |
||||
|
||||
_iterationCount = (uint)(elapsedTicks / _totalTime.Ticks); |
||||
|
||||
return ProcessFrameIndex(currentFrame); |
||||
} |
||||
|
||||
internal WriteableBitmap ProcessFrameIndex(int frameIndex) |
||||
{ |
||||
if (_codec is null) |
||||
throw new InvalidOperationException("The codec is null."); |
||||
|
||||
if (_targetBitmap is null) |
||||
throw new InvalidOperationException("The target bitmap is null."); |
||||
|
||||
RenderFrame(_codec, _targetBitmap, frameIndex, _currentFrameIndex); |
||||
_currentFrameIndex = frameIndex; |
||||
|
||||
return _targetBitmap; |
||||
} |
||||
} |
@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
||||
<plist version="1.0"> |
||||
<dict> |
||||
<key>com.apple.security.cs.allow-jit</key> |
||||
<true/> |
||||
</dict> |
||||
</plist> |
@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
||||
<plist version="1.0"> |
||||
<dict> |
||||
<key>com.apple.security.cs.allow-jit</key> |
||||
<true/> |
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key> |
||||
<true/> |
||||
<key>com.apple.security.cs.disable-library-validation</key> |
||||
<true/> |
||||
</dict> |
||||
</plist> |
@ -1,26 +0,0 @@
|
||||
#!/bin/sh |
||||
|
||||
while getopts v: flag |
||||
do |
||||
case "${flag}" in |
||||
v) version=${OPTARG};; |
||||
*) echo "Invalid option";; |
||||
esac |
||||
done |
||||
|
||||
dotnet \ |
||||
msbuild \ |
||||
StabilityMatrix.Avalonia \ |
||||
-t:BundleApp \ |
||||
-p:RuntimeIdentifier=osx-arm64 \ |
||||
-p:UseAppHost=true \ |
||||
-p:Configuration=Release \ |
||||
-p:CFBundleShortVersionString="$version" \ |
||||
-p:SelfContained=true \ |
||||
-p:CFBundleName="Stability Matrix" \ |
||||
-p:CFBundleDisplayName="Stability Matrix" \ |
||||
-p:CFBundleVersion="$version" \ |
||||
-p:PublishDir="$(pwd)/out/osx-arm64/bin" \ |
||||
|
||||
# Copy the app out of bin |
||||
cp -r ./out/osx-arm64/bin/Stability\ Matrix.app ./out/osx-arm64/Stability\ Matrix.app |
@ -1,62 +0,0 @@
|
||||
#!/bin/sh |
||||
|
||||
echo "Signing file: $1" |
||||
|
||||
# Setup keychain in CI |
||||
if [ -n "$CI" ]; then |
||||
# Turn our base64-encoded certificate back to a regular .p12 file |
||||
|
||||
echo "$MACOS_CERTIFICATE" | base64 --decode -o certificate.p12 |
||||
|
||||
# We need to create a new keychain, otherwise using the certificate will prompt |
||||
# with a UI dialog asking for the certificate password, which we can't |
||||
# use in a headless CI environment |
||||
|
||||
security create-keychain -p "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
security default-keychain -s build.keychain |
||||
security unlock-keychain -p "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
security import certificate.p12 -k build.keychain -P "$MACOS_CERTIFICATE_PWD" -T /usr/bin/codesign |
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
fi |
||||
|
||||
# Sign all files |
||||
PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" || return ; pwd -P ) |
||||
ENTITLEMENTS="$PARENT_PATH/EmbeddedEntitlements.entitlements" |
||||
|
||||
echo "Using entitlements file: $ENTITLEMENTS" |
||||
|
||||
# App |
||||
if [ "$1" == "*.app" ]; then |
||||
echo "[INFO] Signing app contents" |
||||
|
||||
find "$1/Contents/MacOS/"|while read fname; do |
||||
if [[ -f $fname ]]; then |
||||
echo "[INFO] Signing $fname" |
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$fname" |
||||
fi |
||||
done |
||||
|
||||
echo "[INFO] Signing app file" |
||||
|
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$1" -v |
||||
# Directory |
||||
elif [ -d "$1" ]; then |
||||
echo "[INFO] Signing directory contents" |
||||
|
||||
find "$1"|while read fname; do |
||||
if [[ -f $fname ]] && [[ ! $fname =~ /(*.(py|msg|enc))/ ]]; then |
||||
echo "[INFO] Signing $fname" |
||||
|
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$fname" |
||||
fi |
||||
done |
||||
# File |
||||
elif [ -f "$1" ]; then |
||||
echo "[INFO] Signing file" |
||||
|
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$1" -v |
||||
# Not matched |
||||
else |
||||
echo "[ERROR] Unknown file type" |
||||
exit 1 |
||||
fi |
@ -1,37 +0,0 @@
|
||||
#!/bin/sh |
||||
|
||||
echo "Signing file: $1" |
||||
|
||||
# Setup keychain in CI |
||||
if [ -n "$CI" ]; then |
||||
# Turn our base64-encoded certificate back to a regular .p12 file |
||||
|
||||
echo "$MACOS_CERTIFICATE" | base64 --decode -o certificate.p12 |
||||
|
||||
# We need to create a new keychain, otherwise using the certificate will prompt |
||||
# with a UI dialog asking for the certificate password, which we can't |
||||
# use in a headless CI environment |
||||
|
||||
security create-keychain -p "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
security default-keychain -s build.keychain |
||||
security unlock-keychain -p "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
security import certificate.p12 -k build.keychain -P "$MACOS_CERTIFICATE_PWD" -T /usr/bin/codesign |
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_CI_KEYCHAIN_PWD" build.keychain |
||||
fi |
||||
|
||||
# Sign all files |
||||
PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" || return ; pwd -P ) |
||||
ENTITLEMENTS="$PARENT_PATH/AppEntitlements.entitlements" |
||||
|
||||
echo "Using entitlements file: $ENTITLEMENTS" |
||||
|
||||
find "$1/Contents/MacOS/"|while read fname; do |
||||
if [[ -f $fname ]]; then |
||||
echo "[INFO] Signing $fname" |
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$fname" |
||||
fi |
||||
done |
||||
|
||||
echo "[INFO] Signing app file" |
||||
|
||||
codesign --force --timestamp -s "$MACOS_CERTIFICATE_NAME" --options=runtime --entitlements "$ENTITLEMENTS" "$1" -v |
@ -1,32 +0,0 @@
|
||||
#!/bin/sh |
||||
|
||||
echo "Notarizing file: $1" |
||||
|
||||
# Store the notarization credentials so that we can prevent a UI password dialog |
||||
# from blocking the CI |
||||
|
||||
echo "Create keychain profile" |
||||
xcrun notarytool store-credentials "notarytool-profile" \ |
||||
--apple-id "$MACOS_NOTARIZATION_APPLE_ID" \ |
||||
--team-id "$MACOS_NOTARIZATION_TEAM_ID" \ |
||||
--password "$MACOS_NOTARIZATION_PWD" |
||||
|
||||
# We can't notarize an app bundle directly, but we need to compress it as an archive. |
||||
# Therefore, we create a zip file containing our app bundle, so that we can send it to the |
||||
# notarization service |
||||
|
||||
echo "Creating temp notarization archive" |
||||
ditto -c -k --keepParent "$1" "notarization.zip" |
||||
|
||||
# Here we send the notarization request to the Apple's Notarization service, waiting for the result. |
||||
# This typically takes a few seconds inside a CI environment, but it might take more depending on the App |
||||
# characteristics. Visit the Notarization docs for more information and strategies on how to optimize it if |
||||
# you're curious |
||||
|
||||
echo "Notarize app" |
||||
xcrun notarytool submit "notarization.zip" --keychain-profile "notarytool-profile" --wait |
||||
|
||||
# Finally, we need to "attach the staple" to our executable, which will allow our app to be |
||||
# validated by macOS even when an internet connection is not available. |
||||
echo "Attach staple" |
||||
xcrun stapler staple "$1" |
@ -1,5 +0,0 @@
|
||||
<Project> |
||||
<PropertyGroup> |
||||
<AvaloniaVersion>11.0.9</AvaloniaVersion> |
||||
</PropertyGroup> |
||||
</Project> |
Binary file not shown.
@ -1,141 +0,0 @@
|
||||
using System; |
||||
using System.Linq; |
||||
using System.Reactive; |
||||
using System.Reactive.Disposables; |
||||
using System.Reactive.Linq; |
||||
using DynamicData; |
||||
using DynamicData.Binding; |
||||
using JetBrains.Annotations; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Collections; |
||||
|
||||
[PublicAPI] |
||||
public class SearchCollection<TObject, TKey, TQuery> : AbstractNotifyPropertyChanged, IDisposable |
||||
where TObject : notnull |
||||
where TKey : notnull |
||||
{ |
||||
private readonly IDisposable cleanUp; |
||||
|
||||
private Func<TQuery?, Func<TObject, bool>>? PredicateSelector { get; } |
||||
private Func<TQuery?, Func<TObject, (bool, int)>>? ScorerSelector { get; } |
||||
private Func<TObject, (bool, int)>? Scorer { get; set; } |
||||
|
||||
private TQuery? _query; |
||||
public TQuery? Query |
||||
{ |
||||
get => _query; |
||||
set => SetAndRaise(ref _query, value); |
||||
} |
||||
|
||||
private SortExpressionComparer<TObject> _sortComparer = []; |
||||
public SortExpressionComparer<TObject> SortComparer |
||||
{ |
||||
get => _sortComparer; |
||||
set => SetAndRaise(ref _sortComparer, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Converts <see cref="SortComparer"/> to <see cref="SortExpressionComparer{SearchItem}"/>. |
||||
/// </summary> |
||||
private SortExpressionComparer<SearchItem> SearchItemSortComparer => |
||||
[ |
||||
..SortComparer |
||||
.Select(sortExpression => new SortExpression<SearchItem>( |
||||
item => sortExpression.Expression(item.Item), |
||||
sortExpression.Direction |
||||
)).Prepend(new SortExpression<SearchItem>(item => item.Score, SortDirection.Descending)) |
||||
]; |
||||
|
||||
public IObservableCollection<TObject> Items { get; } = new ObservableCollectionExtended<TObject>(); |
||||
|
||||
public IObservableCollection<TObject> FilteredItems { get; } = |
||||
new ObservableCollectionExtended<TObject>(); |
||||
|
||||
public SearchCollection( |
||||
IObservable<IChangeSet<TObject, TKey>> source, |
||||
Func<TQuery?, Func<TObject, bool>> predicateSelector, |
||||
SortExpressionComparer<TObject>? sortComparer = null |
||||
) |
||||
{ |
||||
PredicateSelector = predicateSelector; |
||||
|
||||
if (sortComparer is not null) |
||||
{ |
||||
SortComparer = sortComparer; |
||||
} |
||||
|
||||
// Observable which creates a new predicate whenever Query property changes |
||||
var dynamicPredicate = this.WhenValueChanged(@this => @this.Query).Select(predicateSelector); |
||||
|
||||
cleanUp = source |
||||
.Bind(Items) |
||||
.Filter(dynamicPredicate) |
||||
.Sort(SortComparer) |
||||
.Bind(FilteredItems) |
||||
.Subscribe(); |
||||
} |
||||
|
||||
public SearchCollection( |
||||
IObservable<IChangeSet<TObject, TKey>> source, |
||||
Func<TQuery?, Func<TObject, (bool, int)>> scorerSelector, |
||||
SortExpressionComparer<TObject>? sortComparer = null |
||||
) |
||||
{ |
||||
ScorerSelector = scorerSelector; |
||||
|
||||
if (sortComparer is not null) |
||||
{ |
||||
SortComparer = sortComparer; |
||||
} |
||||
|
||||
// Monitor Query property for changes |
||||
var queryChanged = this.WhenValueChanged(@this => @this.Query).Select(_ => Unit.Default); |
||||
|
||||
cleanUp = new CompositeDisposable( |
||||
// Update Scorer property whenever Query property changes |
||||
queryChanged.Subscribe(_ => Scorer = scorerSelector(Query)), |
||||
// Transform source items into SearchItems |
||||
source |
||||
.Transform( |
||||
obj => |
||||
{ |
||||
var (isMatch, score) = Scorer?.Invoke(obj) ?? (true, 0); |
||||
|
||||
return new SearchItem |
||||
{ |
||||
Item = obj, |
||||
IsMatch = isMatch, |
||||
Score = score |
||||
}; |
||||
}, |
||||
forceTransform: queryChanged |
||||
) |
||||
.Filter(item => item.IsMatch) |
||||
.Sort(SearchItemSortComparer, SortOptimisations.ComparesImmutableValuesOnly) |
||||
.Transform(searchItem => searchItem.Item) |
||||
.Bind(FilteredItems) |
||||
.Subscribe() |
||||
); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Clears <see cref="Query"/> property by setting it to default value. |
||||
/// </summary> |
||||
public void ClearQuery() |
||||
{ |
||||
Query = default; |
||||
} |
||||
|
||||
public void Dispose() |
||||
{ |
||||
cleanUp.Dispose(); |
||||
GC.SuppressFinalize(this); |
||||
} |
||||
|
||||
private readonly record struct SearchItem |
||||
{ |
||||
public TObject Item { get; init; } |
||||
public int Score { get; init; } |
||||
public bool IsMatch { get; init; } |
||||
} |
||||
} |
@ -1,38 +0,0 @@
|
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Controls.Primitives; |
||||
using Avalonia.Controls.Templates; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
public class BetterComboBox : ComboBox |
||||
{ |
||||
public static readonly DirectProperty<BetterComboBox, IDataTemplate?> SelectionBoxItemTemplateProperty = |
||||
AvaloniaProperty.RegisterDirect<BetterComboBox, IDataTemplate?>( |
||||
nameof(SelectionBoxItemTemplate), |
||||
v => v.SelectionBoxItemTemplate, |
||||
(x, v) => x.SelectionBoxItemTemplate = v |
||||
); |
||||
|
||||
private IDataTemplate? _selectionBoxItemTemplate; |
||||
|
||||
public IDataTemplate? SelectionBoxItemTemplate |
||||
{ |
||||
get => _selectionBoxItemTemplate; |
||||
set => SetAndRaise(SelectionBoxItemTemplateProperty, ref _selectionBoxItemTemplate, value); |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) |
||||
{ |
||||
base.OnApplyTemplate(e); |
||||
|
||||
if (e.NameScope.Find<ContentControl>("ContentPresenter") is { } contentPresenter) |
||||
{ |
||||
if (SelectionBoxItemTemplate is { } template) |
||||
{ |
||||
contentPresenter.ContentTemplate = template; |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,208 +0,0 @@
|
||||
using System; |
||||
using System.Threading.Tasks; |
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Input; |
||||
using Avalonia.Interactivity; |
||||
using Avalonia.Xaml.Interactions.DragAndDrop; |
||||
using Avalonia.Xaml.Interactivity; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
public class BetterContextDragBehavior : Behavior<Control> |
||||
{ |
||||
private Point _dragStartPoint; |
||||
private PointerEventArgs? _triggerEvent; |
||||
private bool _lock; |
||||
private bool _captured; |
||||
|
||||
public static readonly StyledProperty<object?> ContextProperty = AvaloniaProperty.Register< |
||||
ContextDragBehavior, |
||||
object? |
||||
>(nameof(Context)); |
||||
|
||||
public static readonly StyledProperty<IDragHandler?> HandlerProperty = AvaloniaProperty.Register< |
||||
ContextDragBehavior, |
||||
IDragHandler? |
||||
>(nameof(Handler)); |
||||
|
||||
public static readonly StyledProperty<double> HorizontalDragThresholdProperty = AvaloniaProperty.Register< |
||||
ContextDragBehavior, |
||||
double |
||||
>(nameof(HorizontalDragThreshold), 3); |
||||
|
||||
public static readonly StyledProperty<double> VerticalDragThresholdProperty = AvaloniaProperty.Register< |
||||
ContextDragBehavior, |
||||
double |
||||
>(nameof(VerticalDragThreshold), 3); |
||||
|
||||
public static readonly StyledProperty<string> DataFormatProperty = AvaloniaProperty.Register< |
||||
BetterContextDragBehavior, |
||||
string |
||||
>("DataFormat"); |
||||
|
||||
public string DataFormat |
||||
{ |
||||
get => GetValue(DataFormatProperty); |
||||
set => SetValue(DataFormatProperty, value); |
||||
} |
||||
|
||||
public object? Context |
||||
{ |
||||
get => GetValue(ContextProperty); |
||||
set => SetValue(ContextProperty, value); |
||||
} |
||||
|
||||
public IDragHandler? Handler |
||||
{ |
||||
get => GetValue(HandlerProperty); |
||||
set => SetValue(HandlerProperty, value); |
||||
} |
||||
|
||||
public double HorizontalDragThreshold |
||||
{ |
||||
get => GetValue(HorizontalDragThresholdProperty); |
||||
set => SetValue(HorizontalDragThresholdProperty, value); |
||||
} |
||||
|
||||
public double VerticalDragThreshold |
||||
{ |
||||
get => GetValue(VerticalDragThresholdProperty); |
||||
set => SetValue(VerticalDragThresholdProperty, value); |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnAttachedToVisualTree() |
||||
{ |
||||
AssociatedObject?.AddHandler( |
||||
InputElement.PointerPressedEvent, |
||||
AssociatedObject_PointerPressed, |
||||
RoutingStrategies.Direct | RoutingStrategies.Tunnel | RoutingStrategies.Bubble |
||||
); |
||||
AssociatedObject?.AddHandler( |
||||
InputElement.PointerReleasedEvent, |
||||
AssociatedObject_PointerReleased, |
||||
RoutingStrategies.Direct | RoutingStrategies.Tunnel | RoutingStrategies.Bubble |
||||
); |
||||
AssociatedObject?.AddHandler( |
||||
InputElement.PointerMovedEvent, |
||||
AssociatedObject_PointerMoved, |
||||
RoutingStrategies.Direct | RoutingStrategies.Tunnel | RoutingStrategies.Bubble |
||||
); |
||||
AssociatedObject?.AddHandler( |
||||
InputElement.PointerCaptureLostEvent, |
||||
AssociatedObject_CaptureLost, |
||||
RoutingStrategies.Direct | RoutingStrategies.Tunnel | RoutingStrategies.Bubble |
||||
); |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnDetachedFromVisualTree() |
||||
{ |
||||
AssociatedObject?.RemoveHandler(InputElement.PointerPressedEvent, AssociatedObject_PointerPressed); |
||||
AssociatedObject?.RemoveHandler(InputElement.PointerReleasedEvent, AssociatedObject_PointerReleased); |
||||
AssociatedObject?.RemoveHandler(InputElement.PointerMovedEvent, AssociatedObject_PointerMoved); |
||||
AssociatedObject?.RemoveHandler(InputElement.PointerCaptureLostEvent, AssociatedObject_CaptureLost); |
||||
} |
||||
|
||||
private async Task DoDragDrop(PointerEventArgs triggerEvent, object? value) |
||||
{ |
||||
var data = new DataObject(); |
||||
data.Set(DataFormat, value!); |
||||
|
||||
var effect = DragDropEffects.None; |
||||
|
||||
if (triggerEvent.KeyModifiers.HasFlag(KeyModifiers.Alt)) |
||||
{ |
||||
effect |= DragDropEffects.Link; |
||||
} |
||||
else if (triggerEvent.KeyModifiers.HasFlag(KeyModifiers.Shift)) |
||||
{ |
||||
effect |= DragDropEffects.Move; |
||||
} |
||||
else if (triggerEvent.KeyModifiers.HasFlag(KeyModifiers.Control)) |
||||
{ |
||||
effect |= DragDropEffects.Copy; |
||||
} |
||||
else |
||||
{ |
||||
effect |= DragDropEffects.Move; |
||||
} |
||||
|
||||
await DragDrop.DoDragDrop(triggerEvent, data, effect); |
||||
} |
||||
|
||||
private void Released() |
||||
{ |
||||
_triggerEvent = null; |
||||
_lock = false; |
||||
} |
||||
|
||||
private void AssociatedObject_PointerPressed(object? sender, PointerPressedEventArgs e) |
||||
{ |
||||
var properties = e.GetCurrentPoint(AssociatedObject).Properties; |
||||
if (properties.IsLeftButtonPressed) |
||||
{ |
||||
if (e.Source is Control control && AssociatedObject?.DataContext == control.DataContext) |
||||
{ |
||||
_dragStartPoint = e.GetPosition(null); |
||||
_triggerEvent = e; |
||||
_lock = true; |
||||
_captured = true; |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void AssociatedObject_PointerReleased(object? sender, PointerReleasedEventArgs e) |
||||
{ |
||||
if (_captured) |
||||
{ |
||||
if (e.InitialPressMouseButton == MouseButton.Left && _triggerEvent is { }) |
||||
{ |
||||
Released(); |
||||
} |
||||
|
||||
_captured = false; |
||||
} |
||||
} |
||||
|
||||
private async void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e) |
||||
{ |
||||
var properties = e.GetCurrentPoint(AssociatedObject).Properties; |
||||
if (_captured && properties.IsLeftButtonPressed && _triggerEvent is { }) |
||||
{ |
||||
var point = e.GetPosition(null); |
||||
var diff = _dragStartPoint - point; |
||||
var horizontalDragThreshold = HorizontalDragThreshold; |
||||
var verticalDragThreshold = VerticalDragThreshold; |
||||
|
||||
if (Math.Abs(diff.X) > horizontalDragThreshold || Math.Abs(diff.Y) > verticalDragThreshold) |
||||
{ |
||||
if (_lock) |
||||
{ |
||||
_lock = false; |
||||
} |
||||
else |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
var context = Context ?? AssociatedObject?.DataContext; |
||||
|
||||
Handler?.BeforeDragDrop(sender, _triggerEvent, context); |
||||
|
||||
await DoDragDrop(_triggerEvent, context); |
||||
|
||||
Handler?.AfterDragDrop(sender, _triggerEvent, context); |
||||
|
||||
_triggerEvent = null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void AssociatedObject_CaptureLost(object? sender, PointerCaptureLostEventArgs e) |
||||
{ |
||||
Released(); |
||||
_captured = false; |
||||
} |
||||
} |
@ -1,46 +0,0 @@
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Controls.Templates; |
||||
using Avalonia.Metadata; |
||||
using JetBrains.Annotations; |
||||
using StabilityMatrix.Avalonia.Models; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
/// <summary> |
||||
/// Selector for objects implementing <see cref="ITemplateKey{T}"/> |
||||
/// </summary> |
||||
[PublicAPI] |
||||
public class DataTemplateSelector<TKey> : IDataTemplate |
||||
where TKey : notnull |
||||
{ |
||||
/// <summary> |
||||
/// Key that is used when no other key matches |
||||
/// </summary> |
||||
public TKey? DefaultKey { get; set; } |
||||
|
||||
[Content] |
||||
public Dictionary<TKey, IDataTemplate> Templates { get; } = new(); |
||||
|
||||
public bool Match(object? data) => data is ITemplateKey<TKey>; |
||||
|
||||
/// <inheritdoc /> |
||||
public Control Build(object? data) |
||||
{ |
||||
if (data is not ITemplateKey<TKey> key) |
||||
throw new ArgumentException(null, nameof(data)); |
||||
|
||||
if (Templates.TryGetValue(key.TemplateKey, out var template)) |
||||
{ |
||||
return template.Build(data)!; |
||||
} |
||||
|
||||
if (DefaultKey is not null && Templates.TryGetValue(DefaultKey, out var defaultTemplate)) |
||||
{ |
||||
return defaultTemplate.Build(data)!; |
||||
} |
||||
|
||||
throw new ArgumentException(null, nameof(data)); |
||||
} |
||||
} |
@ -1,122 +1,13 @@
|
||||
using System; |
||||
using System.Diagnostics; |
||||
using System.IO; |
||||
using AsyncAwaitBestPractices; |
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Controls.Presenters; |
||||
using Avalonia.Logging; |
||||
using FluentAvalonia.UI.Controls; |
||||
using StabilityMatrix.Core.Processes; |
||||
using Symbol = FluentIcons.Common.Symbol; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
/// <summary> |
||||
/// Like <see cref="HyperlinkButton"/>, but with a link icon left of the text content. |
||||
/// </summary> |
||||
public class HyperlinkIconButton : Button |
||||
public class HyperlinkIconButton : HyperlinkButton |
||||
{ |
||||
private Uri? _navigateUri; |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="NavigateUri"/> property |
||||
/// </summary> |
||||
public static readonly DirectProperty<HyperlinkIconButton, Uri?> NavigateUriProperty = |
||||
AvaloniaProperty.RegisterDirect<HyperlinkIconButton, Uri?>( |
||||
nameof(NavigateUri), |
||||
x => x.NavigateUri, |
||||
(x, v) => x.NavigateUri = v |
||||
); |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the Uri that the button should navigate to upon clicking. In assembly paths are not supported, (e.g., avares://...) |
||||
/// </summary> |
||||
public Uri? NavigateUri |
||||
{ |
||||
get => _navigateUri; |
||||
set => SetAndRaise(NavigateUriProperty, ref _navigateUri, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<Symbol> IconProperty = AvaloniaProperty.Register< |
||||
HyperlinkIconButton, |
||||
Symbol |
||||
>("Icon", Symbol.Link); |
||||
|
||||
public Symbol Icon |
||||
{ |
||||
get => GetValue(IconProperty); |
||||
set => SetValue(IconProperty, value); |
||||
} |
||||
|
||||
protected override Type StyleKeyOverride => typeof(HyperlinkIconButton); |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) |
||||
{ |
||||
base.OnPropertyChanged(change); |
||||
|
||||
// Update icon |
||||
if (change.Property == NavigateUriProperty) |
||||
{ |
||||
var uri = change.GetNewValue<Uri?>(); |
||||
|
||||
if (uri is not null && uri.IsFile && Icon == Symbol.Link) |
||||
{ |
||||
Icon = Symbol.Open; |
||||
} |
||||
} |
||||
} |
||||
|
||||
protected override void OnClick() |
||||
{ |
||||
base.OnClick(); |
||||
|
||||
if (NavigateUri is null) |
||||
return; |
||||
|
||||
// File or Folder URIs |
||||
if (NavigateUri.IsFile) |
||||
{ |
||||
var path = NavigateUri.LocalPath; |
||||
|
||||
if (Directory.Exists(path)) |
||||
{ |
||||
ProcessRunner |
||||
.OpenFolderBrowser(path) |
||||
.SafeFireAndForget(ex => |
||||
{ |
||||
Logger.TryGet(LogEventLevel.Error, $"Unable to open directory Uri {NavigateUri}"); |
||||
}); |
||||
} |
||||
else if (File.Exists(path)) |
||||
{ |
||||
ProcessRunner |
||||
.OpenFileBrowser(path) |
||||
.SafeFireAndForget(ex => |
||||
{ |
||||
Logger.TryGet(LogEventLevel.Error, $"Unable to open file Uri {NavigateUri}"); |
||||
}); |
||||
} |
||||
} |
||||
// Web |
||||
else |
||||
{ |
||||
try |
||||
{ |
||||
Process.Start( |
||||
new ProcessStartInfo(NavigateUri.ToString()) { UseShellExecute = true, Verb = "open" } |
||||
); |
||||
} |
||||
catch |
||||
{ |
||||
Logger.TryGet(LogEventLevel.Error, $"Unable to open Uri {NavigateUri}"); |
||||
} |
||||
} |
||||
} |
||||
|
||||
protected override bool RegisterContentPresenter(ContentPresenter presenter) |
||||
{ |
||||
return presenter.Name == "ContentPresenter"; |
||||
} |
||||
protected override Type StyleKeyOverride => typeof(HyperlinkIconButton); |
||||
} |
||||
|
@ -1,48 +0,0 @@
|
||||
<Styles |
||||
xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:controls="using:StabilityMatrix.Avalonia.Controls" |
||||
xmlns:sg="clr-namespace:SpacedGridControl.Avalonia;assembly=SpacedGridControl.Avalonia" |
||||
xmlns:ui="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia" |
||||
xmlns:vmInference="clr-namespace:StabilityMatrix.Avalonia.ViewModels.Inference" |
||||
xmlns:converters="clr-namespace:StabilityMatrix.Avalonia.Converters" |
||||
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
x:DataType="vmInference:LayerDiffuseCardViewModel"> |
||||
<Design.PreviewWith> |
||||
<Panel Width="400" Height="200"> |
||||
<StackPanel Width="300" VerticalAlignment="Center"> |
||||
<controls:LayerDiffuseCard DataContext="{x:Static mocks:DesignData.LayerDiffuseCardViewModel}"/> |
||||
</StackPanel> |
||||
</Panel> |
||||
</Design.PreviewWith> |
||||
|
||||
<Style Selector="controls|LayerDiffuseCard"> |
||||
<Setter Property="HorizontalAlignment" Value="Stretch" /> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<controls:Card Padding="12"> |
||||
<sg:SpacedGrid |
||||
ColumnDefinitions="Auto,*" |
||||
ColumnSpacing="8" |
||||
RowDefinitions="*,*,*,*" |
||||
RowSpacing="0"> |
||||
<!-- Mode Selection --> |
||||
<TextBlock |
||||
Grid.Column="0" |
||||
VerticalAlignment="Center" |
||||
Text="Mode" |
||||
TextAlignment="Left" /> |
||||
|
||||
<ui:FAComboBox |
||||
Grid.Row="0" |
||||
Grid.Column="1" |
||||
HorizontalAlignment="Stretch" |
||||
DisplayMemberBinding="{Binding Converter={x:Static converters:EnumAttributeConverters.DisplayName}}" |
||||
ItemsSource="{Binding AvailableModes}" |
||||
SelectedItem="{Binding SelectedMode}" /> |
||||
</sg:SpacedGrid> |
||||
</controls:Card> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -1,7 +0,0 @@
|
||||
using Avalonia.Controls.Primitives; |
||||
using StabilityMatrix.Core.Attributes; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
[Transient] |
||||
public class LayerDiffuseCard : TemplatedControl; |
@ -1,96 +0,0 @@
|
||||
<Styles |
||||
xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:controls="using:StabilityMatrix.Avalonia.Controls" |
||||
xmlns:converters="clr-namespace:StabilityMatrix.Avalonia.Converters" |
||||
xmlns:inference="clr-namespace:StabilityMatrix.Avalonia.ViewModels.Inference" |
||||
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages" |
||||
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
xmlns:models="clr-namespace:StabilityMatrix.Core.Models;assembly=StabilityMatrix.Core" |
||||
xmlns:sg="clr-namespace:SpacedGridControl.Avalonia;assembly=SpacedGridControl.Avalonia" |
||||
xmlns:ui="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia" |
||||
xmlns:input="clr-namespace:FluentAvalonia.UI.Input;assembly=FluentAvalonia" |
||||
xmlns:fluentIcons="clr-namespace:FluentIcons.Avalonia.Fluent;assembly=FluentIcons.Avalonia.Fluent" |
||||
xmlns:local="clr-namespace:StabilityMatrix.Avalonia" |
||||
x:DataType="inference:PromptExpansionCardViewModel"> |
||||
|
||||
<Design.PreviewWith> |
||||
<Panel Width="400" Height="200"> |
||||
<StackPanel Width="300" VerticalAlignment="Center"> |
||||
<controls:PromptExpansionCard /> |
||||
</StackPanel> |
||||
</Panel> |
||||
</Design.PreviewWith> |
||||
|
||||
<Style Selector="controls|PromptExpansionCard"> |
||||
<Setter Property="HorizontalAlignment" Value="Stretch" /> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<controls:Card Padding="12"> |
||||
<sg:SpacedGrid |
||||
ColumnDefinitions="Auto,*" |
||||
ColumnSpacing="8" |
||||
RowDefinitions="*,*,*,*" |
||||
RowSpacing="0"> |
||||
<!-- Model --> |
||||
<TextBlock |
||||
Grid.Column="0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_Model}" |
||||
TextAlignment="Left" /> |
||||
|
||||
<ui:FAComboBox |
||||
x:Name="PART_ModelComboBox" |
||||
Grid.Row="0" |
||||
Grid.Column="1" |
||||
HorizontalAlignment="Stretch" |
||||
ItemContainerTheme="{StaticResource FAComboBoxItemHybridModelTheme}" |
||||
ItemsSource="{Binding ClientManager.PromptExpansionModels}" |
||||
SelectedItem="{Binding SelectedModel}"> |
||||
|
||||
<ui:FAComboBox.Resources> |
||||
<input:StandardUICommand x:Key="RemoteDownloadCommand" |
||||
Command="{Binding RemoteDownloadCommand}" /> |
||||
</ui:FAComboBox.Resources> |
||||
|
||||
<ui:FAComboBox.DataTemplates> |
||||
<controls:HybridModelTemplateSelector> |
||||
<DataTemplate x:Key="{x:Static models:HybridModelType.Downloadable}" DataType="models:HybridModelFile"> |
||||
<Grid ColumnDefinitions="*,Auto"> |
||||
<TextBlock Foreground="{DynamicResource ThemeGreyColor}" Text="{Binding ShortDisplayName}" /> |
||||
<Button |
||||
Grid.Column="1" |
||||
Margin="8,0,0,0" |
||||
Padding="0" |
||||
Classes="transparent-full"> |
||||
<fluentIcons:SymbolIcon |
||||
VerticalAlignment="Center" |
||||
FontSize="18" |
||||
Foreground="{DynamicResource ThemeGreyColor}" |
||||
IsFilled="True" |
||||
Symbol="CloudArrowDown" /> |
||||
</Button> |
||||
</Grid> |
||||
</DataTemplate> |
||||
<DataTemplate x:Key="{x:Static models:HybridModelType.None}" DataType="models:HybridModelFile"> |
||||
<TextBlock Text="{Binding ShortDisplayName}" /> |
||||
</DataTemplate> |
||||
</controls:HybridModelTemplateSelector> |
||||
</ui:FAComboBox.DataTemplates> |
||||
|
||||
</ui:FAComboBox> |
||||
|
||||
<!--<controls:BetterComboBox |
||||
Grid.Row="0" |
||||
Grid.Column="1" |
||||
Padding="8,6,4,6" |
||||
HorizontalAlignment="Stretch" |
||||
ItemsSource="{Binding ClientManager.Upscalers}" |
||||
SelectedItem="{Binding SelectedModel}" |
||||
Theme="{StaticResource BetterComboBoxHybridModelTheme}" />--> |
||||
</sg:SpacedGrid> |
||||
</controls:Card> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -1,52 +0,0 @@
|
||||
using AsyncAwaitBestPractices; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Controls.Primitives; |
||||
using FluentAvalonia.UI.Controls; |
||||
using StabilityMatrix.Avalonia.ViewModels.Inference; |
||||
using StabilityMatrix.Core.Attributes; |
||||
using StabilityMatrix.Core.Models; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
[Transient] |
||||
public class PromptExpansionCard : TemplatedControl |
||||
{ |
||||
/// <inheritdoc /> |
||||
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) |
||||
{ |
||||
base.OnApplyTemplate(e); |
||||
|
||||
var upscalerComboBox = e.NameScope.Find("PART_ModelComboBox") as FAComboBox; |
||||
upscalerComboBox!.SelectionChanged += UpscalerComboBox_OnSelectionChanged; |
||||
} |
||||
|
||||
private void UpscalerComboBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e) |
||||
{ |
||||
if (e.AddedItems.Count == 0) |
||||
return; |
||||
|
||||
var item = e.AddedItems[0]; |
||||
if (item is HybridModelFile { IsDownloadable: true }) |
||||
{ |
||||
// Reset the selection |
||||
e.Handled = true; |
||||
|
||||
if ( |
||||
e.RemovedItems.Count > 0 |
||||
&& e.RemovedItems[0] is HybridModelFile { IsDownloadable: false } removedItem |
||||
) |
||||
{ |
||||
(sender as FAComboBox)!.SelectedItem = removedItem; |
||||
} |
||||
else |
||||
{ |
||||
(sender as FAComboBox)!.SelectedItem = null; |
||||
} |
||||
|
||||
// Show dialog to download the model |
||||
(DataContext as PromptExpansionCardViewModel)! |
||||
.RemoteDownloadCommand.ExecuteAsync(item) |
||||
.SafeFireAndForget(); |
||||
} |
||||
} |
||||
} |
@ -1,65 +0,0 @@
|
||||
<Styles |
||||
xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:controls="using:StabilityMatrix.Avalonia.Controls" |
||||
xmlns:system="using:System" |
||||
xmlns:treeFileExplorer="clr-namespace:StabilityMatrix.Avalonia.Models.TreeFileExplorer" |
||||
xmlns:mock="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
xmlns:sg="clr-namespace:SpacedGridControl.Avalonia;assembly=SpacedGridControl.Avalonia" |
||||
xmlns:fluentIcons="clr-namespace:FluentIcons.Avalonia.Fluent;assembly=FluentIcons.Avalonia.Fluent"> |
||||
<Design.PreviewWith> |
||||
<StackPanel Spacing="16"> |
||||
<Panel Height="300" Margin="4"> |
||||
<controls:TreeFileExplorer |
||||
RootPath="{x:Static mock:DesignData.CurrentDirectory}" /> |
||||
</Panel> |
||||
|
||||
<Panel Height="300" Margin="4"> |
||||
<controls:TreeFileExplorer |
||||
IndexFiles="False" |
||||
CanSelectFiles="False" |
||||
RootPath="{x:Static mock:DesignData.CurrentDirectory}" /> |
||||
</Panel> |
||||
</StackPanel> |
||||
</Design.PreviewWith> |
||||
|
||||
<Style Selector="controls|TreeFileExplorer"> |
||||
<!-- Set Defaults --> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<Grid> |
||||
<TreeView |
||||
ScrollViewer.VerticalScrollBarVisibility="Auto" |
||||
ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=RootItem.Children}"> |
||||
<TreeView.DataTemplates> |
||||
<DataTemplate |
||||
DataType="treeFileExplorer:TreeFileExplorerFile"> |
||||
<sg:SpacedGrid ColumnDefinitions="Auto,*" RowSpacing="0" ColumnSpacing="4"> |
||||
<fluentIcons:SymbolIcon |
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}" |
||||
Symbol="Document" /> |
||||
<TextBlock |
||||
Grid.Column="1" |
||||
Text="{Binding Path.Name}" /> |
||||
</sg:SpacedGrid> |
||||
</DataTemplate> |
||||
<TreeDataTemplate |
||||
DataType="treeFileExplorer:TreeFileExplorerDirectory" |
||||
ItemsSource="{Binding Children}"> |
||||
<sg:SpacedGrid ColumnDefinitions="Auto,*" RowSpacing="0" ColumnSpacing="4"> |
||||
<fluentIcons:SymbolIcon |
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}" |
||||
IsFilled="True" |
||||
Symbol="Folder" /> |
||||
<TextBlock |
||||
Grid.Column="1" |
||||
Text="{Binding Path.Name}" /> |
||||
</sg:SpacedGrid> |
||||
</TreeDataTemplate> |
||||
</TreeView.DataTemplates> |
||||
</TreeView> |
||||
</Grid> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -1,135 +0,0 @@
|
||||
using Avalonia; |
||||
using Avalonia.Controls.Primitives; |
||||
using StabilityMatrix.Avalonia.Models.TreeFileExplorer; |
||||
using StabilityMatrix.Core.Models.FileInterfaces; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
public class TreeFileExplorer : TemplatedControl |
||||
{ |
||||
public static readonly StyledProperty<TreeFileExplorerDirectory?> RootItemProperty = |
||||
AvaloniaProperty.Register<TreeFileExplorer, TreeFileExplorerDirectory?>("RootItem"); |
||||
|
||||
public TreeFileExplorerDirectory? RootItem |
||||
{ |
||||
get => GetValue(RootItemProperty); |
||||
set => SetValue(RootItemProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<string?> RootPathProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
string? |
||||
>("RootPath"); |
||||
|
||||
public string? RootPath |
||||
{ |
||||
get => GetValue(RootPathProperty); |
||||
set => SetValue(RootPathProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<IPathObject?> SelectedPathProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
IPathObject? |
||||
>("SelectedPath"); |
||||
|
||||
public IPathObject? SelectedPath |
||||
{ |
||||
get => GetValue(SelectedPathProperty); |
||||
set => SetValue(SelectedPathProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<bool> CanSelectFilesProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
bool |
||||
>("CanSelectFiles", true); |
||||
|
||||
public bool CanSelectFiles |
||||
{ |
||||
get => GetValue(CanSelectFilesProperty); |
||||
set => SetValue(CanSelectFilesProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<bool> CanSelectFoldersProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
bool |
||||
>("CanSelectFolders", true); |
||||
|
||||
public bool CanSelectFolders |
||||
{ |
||||
get => GetValue(CanSelectFoldersProperty); |
||||
set => SetValue(CanSelectFoldersProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<bool> IndexFilesProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
bool |
||||
>("IndexFiles", true); |
||||
|
||||
public bool IndexFiles |
||||
{ |
||||
get => GetValue(IndexFilesProperty); |
||||
set => SetValue(IndexFilesProperty, value); |
||||
} |
||||
|
||||
public static readonly StyledProperty<bool> IndexFoldersProperty = AvaloniaProperty.Register< |
||||
TreeFileExplorer, |
||||
bool |
||||
>("IndexFolders", true); |
||||
|
||||
public bool IndexFolders |
||||
{ |
||||
get => GetValue(IndexFoldersProperty); |
||||
set => SetValue(IndexFoldersProperty, value); |
||||
} |
||||
|
||||
private TreeFileExplorerOptions GetOptions() |
||||
{ |
||||
var options = TreeFileExplorerOptions.None; |
||||
|
||||
if (CanSelectFiles) |
||||
{ |
||||
options |= TreeFileExplorerOptions.CanSelectFiles; |
||||
} |
||||
if (CanSelectFolders) |
||||
{ |
||||
options |= TreeFileExplorerOptions.CanSelectFolders; |
||||
} |
||||
if (IndexFiles) |
||||
{ |
||||
options |= TreeFileExplorerOptions.IndexFiles; |
||||
} |
||||
if (IndexFolders) |
||||
{ |
||||
options |= TreeFileExplorerOptions.IndexFolders; |
||||
} |
||||
|
||||
return options; |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) |
||||
{ |
||||
base.OnApplyTemplate(e); |
||||
|
||||
if (RootItem is null) |
||||
{ |
||||
RootItem = RootPath is null |
||||
? null |
||||
: new TreeFileExplorerDirectory(new DirectoryPath(RootPath), GetOptions()); |
||||
} |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) |
||||
{ |
||||
base.OnPropertyChanged(change); |
||||
|
||||
if (change.Property == RootPathProperty) |
||||
{ |
||||
var path = change.GetNewValue<string?>(); |
||||
RootItem = path is null |
||||
? null |
||||
: new TreeFileExplorerDirectory(new DirectoryPath(path), GetOptions()); |
||||
} |
||||
} |
||||
} |
@ -1,20 +0,0 @@
|
||||
using System; |
||||
using Avalonia.Interactivity; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs; |
||||
|
||||
public partial class BetterAsyncImage |
||||
{ |
||||
public class AsyncImageFailedEventArgs : RoutedEventArgs |
||||
{ |
||||
internal AsyncImageFailedEventArgs(Exception? errorException = null, string errorMessage = "") |
||||
: base(FailedEvent) |
||||
{ |
||||
ErrorException = errorException; |
||||
ErrorMessage = errorMessage; |
||||
} |
||||
|
||||
public Exception? ErrorException { get; private set; } |
||||
public string ErrorMessage { get; private set; } |
||||
} |
||||
} |
@ -1,42 +0,0 @@
|
||||
using System; |
||||
using Avalonia.Interactivity; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs; |
||||
|
||||
public partial class BetterAsyncImage |
||||
{ |
||||
/// <summary> |
||||
/// Deines the <see cref="Opened"/> event |
||||
/// </summary> |
||||
public static readonly RoutedEvent<RoutedEventArgs> OpenedEvent = RoutedEvent.Register< |
||||
BetterAsyncImage, |
||||
RoutedEventArgs |
||||
>(nameof(Opened), RoutingStrategies.Bubble); |
||||
|
||||
/// <summary> |
||||
/// Deines the <see cref="Failed"/> event |
||||
/// </summary> |
||||
public static readonly RoutedEvent<global::Avalonia.Labs.Controls.AsyncImage.AsyncImageFailedEventArgs> FailedEvent = |
||||
RoutedEvent.Register< |
||||
BetterAsyncImage, |
||||
global::Avalonia.Labs.Controls.AsyncImage.AsyncImageFailedEventArgs |
||||
>(nameof(Failed), RoutingStrategies.Bubble); |
||||
|
||||
/// <summary> |
||||
/// Occurs when the image is successfully loaded. |
||||
/// </summary> |
||||
public event EventHandler<RoutedEventArgs>? Opened |
||||
{ |
||||
add => AddHandler(OpenedEvent, value); |
||||
remove => RemoveHandler(OpenedEvent, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Occurs when the image fails to load the uri provided. |
||||
/// </summary> |
||||
public event EventHandler<global::Avalonia.Labs.Controls.AsyncImage.AsyncImageFailedEventArgs>? Failed |
||||
{ |
||||
add => AddHandler(FailedEvent, value); |
||||
remove => RemoveHandler(FailedEvent, value); |
||||
} |
||||
} |
@ -1,135 +0,0 @@
|
||||
using System; |
||||
using Avalonia; |
||||
using Avalonia.Animation; |
||||
using Avalonia.Labs.Controls; |
||||
using Avalonia.Media; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs; |
||||
|
||||
public partial class BetterAsyncImage |
||||
{ |
||||
/// <summary> |
||||
/// Defines the <see cref="PlaceholderSource"/> property. |
||||
/// </summary> |
||||
public static readonly StyledProperty<IImage?> PlaceholderSourceProperty = AvaloniaProperty.Register< |
||||
BetterAsyncImage, |
||||
IImage? |
||||
>(nameof(PlaceholderSource)); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="Source"/> property. |
||||
/// </summary> |
||||
public static readonly StyledProperty<Uri?> SourceProperty = AvaloniaProperty.Register< |
||||
BetterAsyncImage, |
||||
Uri? |
||||
>(nameof(Source)); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="Stretch"/> property. |
||||
/// </summary> |
||||
public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register< |
||||
BetterAsyncImage, |
||||
Stretch |
||||
>(nameof(Stretch), Stretch.Uniform); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="PlaceholderStretch"/> property. |
||||
/// </summary> |
||||
public static readonly StyledProperty<Stretch> PlaceholderStretchProperty = AvaloniaProperty.Register< |
||||
BetterAsyncImage, |
||||
Stretch |
||||
>(nameof(PlaceholderStretch), Stretch.Uniform); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="State"/> property. |
||||
/// </summary> |
||||
public static readonly DirectProperty<BetterAsyncImage, AsyncImageState> StateProperty = |
||||
AvaloniaProperty.RegisterDirect<BetterAsyncImage, AsyncImageState>( |
||||
nameof(State), |
||||
o => o.State, |
||||
(o, v) => o.State = v |
||||
); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="ImageTransition"/> property. |
||||
/// </summary> |
||||
public static readonly StyledProperty<IPageTransition?> ImageTransitionProperty = |
||||
AvaloniaProperty.Register<BetterAsyncImage, IPageTransition?>( |
||||
nameof(ImageTransition), |
||||
new CrossFade(TimeSpan.FromSeconds(0.25)) |
||||
); |
||||
|
||||
/// <summary> |
||||
/// Defines the <see cref="IsCacheEnabled"/> property. |
||||
/// </summary> |
||||
public static readonly DirectProperty<BetterAsyncImage, bool> IsCacheEnabledProperty = |
||||
AvaloniaProperty.RegisterDirect<BetterAsyncImage, bool>( |
||||
nameof(IsCacheEnabled), |
||||
o => o.IsCacheEnabled, |
||||
(o, v) => o.IsCacheEnabled = v |
||||
); |
||||
private bool _isCacheEnabled; |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the placeholder image. |
||||
/// </summary> |
||||
public IImage? PlaceholderSource |
||||
{ |
||||
get => GetValue(PlaceholderSourceProperty); |
||||
set => SetValue(PlaceholderSourceProperty, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the uri pointing to the image resource |
||||
/// </summary> |
||||
public Uri? Source |
||||
{ |
||||
get => GetValue(SourceProperty); |
||||
set => SetValue(SourceProperty, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets a value controlling how the image will be stretched. |
||||
/// </summary> |
||||
public Stretch Stretch |
||||
{ |
||||
get { return GetValue(StretchProperty); } |
||||
set { SetValue(StretchProperty, value); } |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets a value controlling how the placeholder will be stretched. |
||||
/// </summary> |
||||
public Stretch PlaceholderStretch |
||||
{ |
||||
get { return GetValue(StretchProperty); } |
||||
set { SetValue(StretchProperty, value); } |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets the current loading state of the image. |
||||
/// </summary> |
||||
public AsyncImageState State |
||||
{ |
||||
get => _state; |
||||
private set => SetAndRaise(StateProperty, ref _state, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the transition to run when the image is loaded. |
||||
/// </summary> |
||||
public IPageTransition? ImageTransition |
||||
{ |
||||
get => GetValue(ImageTransitionProperty); |
||||
set => SetValue(ImageTransitionProperty, value); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets whether to use cache for retrieved images |
||||
/// </summary> |
||||
public bool IsCacheEnabled |
||||
{ |
||||
get => _isCacheEnabled; |
||||
set => SetAndRaise(IsCacheEnabledProperty, ref _isCacheEnabled, value); |
||||
} |
||||
} |
@ -1,248 +0,0 @@
|
||||
using System; |
||||
using System.IO; |
||||
using System.Net.Http; |
||||
using System.Threading; |
||||
using System.Threading.Tasks; |
||||
using Avalonia; |
||||
using Avalonia.Controls; |
||||
using Avalonia.Controls.Metadata; |
||||
using Avalonia.Controls.Primitives; |
||||
using Avalonia.Interactivity; |
||||
using Avalonia.Labs.Controls; |
||||
using Avalonia.Media; |
||||
using Avalonia.Media.Imaging; |
||||
using Avalonia.Platform; |
||||
using Avalonia.Threading; |
||||
using StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs; |
||||
|
||||
/// <summary> |
||||
/// An image control that asynchronously retrieves an image using a <see cref="Uri"/>. |
||||
/// </summary> |
||||
[TemplatePart("PART_Image", typeof(Image))] |
||||
[TemplatePart("PART_PlaceholderImage", typeof(Image))] |
||||
public partial class BetterAsyncImage : TemplatedControl |
||||
{ |
||||
protected Image? ImagePart { get; private set; } |
||||
protected Image? PlaceholderPart { get; private set; } |
||||
|
||||
private bool _isInitialized; |
||||
private CancellationTokenSource? _tokenSource; |
||||
private AsyncImageState _state; |
||||
|
||||
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) |
||||
{ |
||||
base.OnApplyTemplate(e); |
||||
|
||||
ImagePart = e.NameScope.Get<Image>("PART_Image"); |
||||
PlaceholderPart = e.NameScope.Get<Image>("PART_PlaceholderImage"); |
||||
|
||||
_tokenSource = new CancellationTokenSource(); |
||||
|
||||
_isInitialized = true; |
||||
|
||||
if (Source != null) |
||||
{ |
||||
SetSource(Source); |
||||
} |
||||
} |
||||
|
||||
private async void SetSource(object? source) |
||||
{ |
||||
if (!_isInitialized) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
_tokenSource?.Cancel(); |
||||
|
||||
_tokenSource = new CancellationTokenSource(); |
||||
|
||||
AttachSource(null); |
||||
|
||||
if (source == null) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
State = AsyncImageState.Loading; |
||||
|
||||
if (Source is IImage image) |
||||
{ |
||||
AttachSource(image); |
||||
|
||||
return; |
||||
} |
||||
|
||||
if (Source == null) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
var uri = Source; |
||||
|
||||
if (uri != null && uri.IsAbsoluteUri) |
||||
{ |
||||
if (uri.Scheme == "http" || uri.Scheme == "https") |
||||
{ |
||||
Bitmap? bitmap = null; |
||||
// Android doesn't allow network requests on the main thread, even though we are using async apis. |
||||
#if NET6_0_OR_GREATER |
||||
if (OperatingSystem.IsAndroid()) |
||||
{ |
||||
await Task.Run(async () => |
||||
{ |
||||
try |
||||
{ |
||||
bitmap = await LoadImageAsync(uri, _tokenSource.Token); |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
await Dispatcher.UIThread.InvokeAsync(() => |
||||
{ |
||||
State = AsyncImageState.Failed; |
||||
|
||||
RaiseEvent(new AsyncImageFailedEventArgs(ex)); |
||||
}); |
||||
} |
||||
}); |
||||
} |
||||
else |
||||
#endif |
||||
{ |
||||
try |
||||
{ |
||||
bitmap = await LoadImageAsync(uri, _tokenSource.Token); |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
await Dispatcher.UIThread.InvokeAsync(() => |
||||
{ |
||||
State = AsyncImageState.Failed; |
||||
|
||||
RaiseEvent(new AsyncImageFailedEventArgs(ex)); |
||||
}); |
||||
} |
||||
} |
||||
|
||||
AttachSource(bitmap); |
||||
} |
||||
else if (uri.Scheme == "avares") |
||||
{ |
||||
try |
||||
{ |
||||
AttachSource(new Bitmap(AssetLoader.Open(uri))); |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
State = AsyncImageState.Failed; |
||||
|
||||
RaiseEvent(new AsyncImageFailedEventArgs(ex)); |
||||
} |
||||
} |
||||
else if (uri.Scheme == "file" && File.Exists(uri.LocalPath)) |
||||
{ |
||||
// Added error handling here for local files |
||||
try |
||||
{ |
||||
AttachSource(new Bitmap(uri.LocalPath)); |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
State = AsyncImageState.Failed; |
||||
|
||||
RaiseEvent(new AsyncImageFailedEventArgs(ex)); |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
RaiseEvent( |
||||
new AsyncImageFailedEventArgs( |
||||
new UriFormatException($"Uri has unsupported scheme. Uri:{source}") |
||||
) |
||||
); |
||||
} |
||||
} |
||||
else |
||||
{ |
||||
RaiseEvent( |
||||
new AsyncImageFailedEventArgs( |
||||
new UriFormatException($"Relative paths aren't supported. Uri:{source}") |
||||
) |
||||
); |
||||
} |
||||
} |
||||
|
||||
private void AttachSource(IImage? image) |
||||
{ |
||||
if (ImagePart != null) |
||||
{ |
||||
ImagePart.Source = image; |
||||
} |
||||
|
||||
_tokenSource?.Cancel(); |
||||
_tokenSource = new CancellationTokenSource(); |
||||
|
||||
if (image == null) |
||||
{ |
||||
State = AsyncImageState.Unloaded; |
||||
|
||||
ImageTransition?.Start(ImagePart, PlaceholderPart, true, _tokenSource.Token); |
||||
} |
||||
else if (image.Size != default) |
||||
{ |
||||
State = AsyncImageState.Loaded; |
||||
|
||||
ImageTransition?.Start(PlaceholderPart, ImagePart, true, _tokenSource.Token); |
||||
|
||||
RaiseEvent(new RoutedEventArgs(OpenedEvent)); |
||||
} |
||||
} |
||||
|
||||
private async Task<Bitmap> LoadImageAsync(Uri? url, CancellationToken token) |
||||
{ |
||||
if (await ProvideCachedResourceAsync(url, token) is { } bitmap) |
||||
{ |
||||
return bitmap; |
||||
} |
||||
#if NET6_0_OR_GREATER |
||||
using var client = new HttpClient(); |
||||
var stream = await client.GetStreamAsync(url, token).ConfigureAwait(false); |
||||
|
||||
await using var memoryStream = new MemoryStream(); |
||||
await stream.CopyToAsync(memoryStream, token).ConfigureAwait(false); |
||||
#elif NETSTANDARD2_0 |
||||
using var client = new HttpClient(); |
||||
var response = await client.GetAsync(url, token).ConfigureAwait(false); |
||||
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); |
||||
|
||||
using var memoryStream = new MemoryStream(); |
||||
await stream.CopyToAsync(memoryStream).ConfigureAwait(false); |
||||
#endif |
||||
|
||||
memoryStream.Position = 0; |
||||
return new Bitmap(memoryStream); |
||||
} |
||||
|
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) |
||||
{ |
||||
base.OnPropertyChanged(change); |
||||
|
||||
if (change.Property == SourceProperty) |
||||
{ |
||||
SetSource(Source); |
||||
} |
||||
} |
||||
|
||||
protected virtual async Task<Bitmap?> ProvideCachedResourceAsync(Uri? imageUri, CancellationToken token) |
||||
{ |
||||
if (IsCacheEnabled && imageUri != null) |
||||
{ |
||||
return await ImageCache |
||||
.Instance.GetFromCacheAsync(imageUri, cancellationToken: token) |
||||
.ConfigureAwait(false); |
||||
} |
||||
return null; |
||||
} |
||||
} |
@ -1,565 +0,0 @@
|
||||
// Parts of this file was taken from Windows Community Toolkit CacheBase implementation |
||||
// https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/main/Microsoft.Toolkit.Uwp.UI/Cache/ImageCache.cs |
||||
|
||||
// Licensed to the .NET Foundation under one or more agreements. |
||||
// The .NET Foundation licenses this file to you under the MIT license. |
||||
// See the LICENSE file in the project root for more information. |
||||
|
||||
using System; |
||||
using System.Collections.Concurrent; |
||||
using System.Collections.Generic; |
||||
using System.IO; |
||||
using System.Linq; |
||||
using System.Net.Http; |
||||
using System.Threading; |
||||
using System.Threading.Tasks; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
internal abstract class CacheBase<T> |
||||
{ |
||||
private class ConcurrentRequest |
||||
{ |
||||
public Task<T?>? Task { get; set; } |
||||
|
||||
public bool EnsureCachedCopy { get; set; } |
||||
} |
||||
|
||||
private readonly SemaphoreSlim _cacheFolderSemaphore = new SemaphoreSlim(1); |
||||
private string? _baseFolder = null; |
||||
private string? _cacheFolderName = null; |
||||
|
||||
private string? _cacheFolder = null; |
||||
private InMemoryStorage<T>? _inMemoryFileStorage = null; |
||||
|
||||
private ConcurrentDictionary<string, ConcurrentRequest> _concurrentTasks = |
||||
new ConcurrentDictionary<string, ConcurrentRequest>(); |
||||
|
||||
private HttpClient? _httpClient = null; |
||||
|
||||
/// <summary> |
||||
/// Initializes a new instance of the <see cref="CacheBase{T}"/> class. |
||||
/// </summary> |
||||
protected CacheBase() |
||||
{ |
||||
var options = CacheOptions.Default; |
||||
CacheDuration = options?.CacheDuration ?? TimeSpan.FromDays(1); |
||||
_baseFolder = options?.BaseCachePath ?? null; |
||||
_inMemoryFileStorage = new InMemoryStorage<T>(); |
||||
RetryCount = 1; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the life duration of every cache entry. |
||||
/// </summary> |
||||
public TimeSpan CacheDuration { get; set; } |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the number of retries trying to ensure the file is cached. |
||||
/// </summary> |
||||
public uint RetryCount { get; set; } |
||||
|
||||
/// <summary> |
||||
/// Gets or sets max in-memory item storage count |
||||
/// </summary> |
||||
public int MaxMemoryCacheCount |
||||
{ |
||||
get { return _inMemoryFileStorage?.MaxItemCount ?? 0; } |
||||
set |
||||
{ |
||||
if (_inMemoryFileStorage != null) |
||||
_inMemoryFileStorage.MaxItemCount = value; |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets instance of <see cref="HttpClient"/> |
||||
/// </summary> |
||||
protected HttpClient HttpClient |
||||
{ |
||||
get |
||||
{ |
||||
if (_httpClient == null) |
||||
{ |
||||
var messageHandler = new HttpClientHandler(); |
||||
|
||||
_httpClient = new HttpClient(messageHandler); |
||||
} |
||||
|
||||
return _httpClient; |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Initializes FileCache and provides root folder and cache folder name |
||||
/// </summary> |
||||
/// <param name="folder">Folder that is used as root for cache</param> |
||||
/// <param name="folderName">Cache folder name</param> |
||||
/// <param name="httpMessageHandler">instance of <see cref="HttpMessageHandler"/></param> |
||||
/// <returns>awaitable task</returns> |
||||
public virtual async Task InitializeAsync( |
||||
string? folder = null, |
||||
string? folderName = null, |
||||
HttpMessageHandler? httpMessageHandler = null |
||||
) |
||||
{ |
||||
_baseFolder = folder; |
||||
_cacheFolderName = folderName; |
||||
|
||||
_cacheFolder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
|
||||
if (httpMessageHandler != null) |
||||
{ |
||||
_httpClient = new HttpClient(httpMessageHandler); |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Clears all files in the cache |
||||
/// </summary> |
||||
/// <returns>awaitable task</returns> |
||||
public async Task ClearAsync() |
||||
{ |
||||
var folder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
var files = Directory.EnumerateFiles(folder!); |
||||
|
||||
await InternalClearAsync(files.Select(x => x as string)).ConfigureAwait(false); |
||||
|
||||
_inMemoryFileStorage?.Clear(); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Clears file if it has expired |
||||
/// </summary> |
||||
/// <param name="duration">timespan to compute whether file has expired or not</param> |
||||
/// <returns>awaitable task</returns> |
||||
public Task ClearAsync(TimeSpan duration) |
||||
{ |
||||
return RemoveExpiredAsync(duration); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Removes cached files that have expired |
||||
/// </summary> |
||||
/// <param name="duration">Optional timespan to compute whether file has expired or not. If no value is supplied, <see cref="CacheDuration"/> is used.</param> |
||||
/// <returns>awaitable task</returns> |
||||
public async Task RemoveExpiredAsync(TimeSpan? duration = null) |
||||
{ |
||||
TimeSpan expiryDuration = duration ?? CacheDuration; |
||||
|
||||
var folder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
var files = Directory.EnumerateFiles(folder!); |
||||
|
||||
var filesToDelete = new List<string>(); |
||||
|
||||
foreach (var file in files) |
||||
{ |
||||
if (file == null) |
||||
{ |
||||
continue; |
||||
} |
||||
|
||||
if (await IsFileOutOfDateAsync(file, expiryDuration, false).ConfigureAwait(false)) |
||||
{ |
||||
filesToDelete.Add(file); |
||||
} |
||||
} |
||||
|
||||
await InternalClearAsync(filesToDelete).ConfigureAwait(false); |
||||
|
||||
_inMemoryFileStorage?.Clear(expiryDuration); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Removed items based on uri list passed |
||||
/// </summary> |
||||
/// <param name="uriForCachedItems">Enumerable uri list</param> |
||||
/// <returns>awaitable Task</returns> |
||||
public async Task RemoveAsync(IEnumerable<Uri> uriForCachedItems) |
||||
{ |
||||
if (uriForCachedItems == null || !uriForCachedItems.Any()) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
var folder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
var files = Directory.EnumerateFiles(folder!); |
||||
var filesToDelete = new List<string>(); |
||||
var keys = new List<string>(); |
||||
|
||||
Dictionary<string, string> hashDictionary = new Dictionary<string, string>(); |
||||
|
||||
foreach (var file in files) |
||||
{ |
||||
hashDictionary.Add(Path.GetFileName(file), file); |
||||
} |
||||
|
||||
foreach (var uri in uriForCachedItems) |
||||
{ |
||||
string fileName = GetCacheFileName(uri); |
||||
if (hashDictionary.TryGetValue(fileName, out var file)) |
||||
{ |
||||
filesToDelete.Add(file); |
||||
keys.Add(fileName); |
||||
} |
||||
} |
||||
|
||||
await InternalClearAsync(filesToDelete).ConfigureAwait(false); |
||||
|
||||
_inMemoryFileStorage?.Remove(keys); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Assures that item represented by Uri is cached. |
||||
/// </summary> |
||||
/// <param name="uri">Uri of the item</param> |
||||
/// <param name="throwOnError">Indicates whether or not exception should be thrown if item cannot be cached</param> |
||||
/// <param name="storeToMemoryCache">Indicates if item should be loaded into the in-memory storage</param> |
||||
/// <param name="cancellationToken">instance of <see cref="CancellationToken"/></param> |
||||
/// <returns>Awaitable Task</returns> |
||||
public Task PreCacheAsync( |
||||
Uri uri, |
||||
bool throwOnError = false, |
||||
bool storeToMemoryCache = false, |
||||
CancellationToken cancellationToken = default(CancellationToken) |
||||
) |
||||
{ |
||||
return GetItemAsync(uri, throwOnError, !storeToMemoryCache, cancellationToken); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Retrieves item represented by Uri from the cache. If the item is not found in the cache, it will try to downloaded and saved before returning it to the caller. |
||||
/// </summary> |
||||
/// <param name="uri">Uri of the item.</param> |
||||
/// <param name="throwOnError">Indicates whether or not exception should be thrown if item cannot be found / downloaded.</param> |
||||
/// <param name="cancellationToken">instance of <see cref="CancellationToken"/></param> |
||||
/// <returns>an instance of Generic type</returns> |
||||
public Task<T?> GetFromCacheAsync( |
||||
Uri uri, |
||||
bool throwOnError = false, |
||||
CancellationToken cancellationToken = default(CancellationToken) |
||||
) |
||||
{ |
||||
return GetItemAsync(uri, throwOnError, false, cancellationToken); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Gets the string containing cached item for given Uri |
||||
/// </summary> |
||||
/// <param name="uri">Uri of the item.</param> |
||||
/// <returns>a string</returns> |
||||
public async Task<string> GetFileFromCacheAsync(Uri uri) |
||||
{ |
||||
var folder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
|
||||
return Path.Combine(folder!, GetCacheFileName(uri)); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Retrieves item represented by Uri from the in-memory cache if it exists and is not out of date. If item is not found or is out of date, default instance of the generic type is returned. |
||||
/// </summary> |
||||
/// <param name="uri">Uri of the item.</param> |
||||
/// <returns>an instance of Generic type</returns> |
||||
public T? GetFromMemoryCache(Uri uri) |
||||
{ |
||||
T? instance = default(T); |
||||
|
||||
string fileName = GetCacheFileName(uri); |
||||
|
||||
if (_inMemoryFileStorage?.MaxItemCount > 0) |
||||
{ |
||||
var msi = _inMemoryFileStorage?.GetItem(fileName, CacheDuration); |
||||
if (msi != null) |
||||
{ |
||||
instance = msi.Item; |
||||
} |
||||
} |
||||
|
||||
return instance; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Cache specific hooks to process items from HTTP response |
||||
/// </summary> |
||||
/// <param name="stream">input stream</param> |
||||
/// <returns>awaitable task</returns> |
||||
protected abstract Task<T> ConvertFromAsync(Stream stream); |
||||
|
||||
/// <summary> |
||||
/// Cache specific hooks to process items from HTTP response |
||||
/// </summary> |
||||
/// <param name="baseFile">storage file</param> |
||||
/// <returns>awaitable task</returns> |
||||
protected abstract Task<T> ConvertFromAsync(string baseFile); |
||||
|
||||
/// <summary> |
||||
/// Override-able method that checks whether file is valid or not. |
||||
/// </summary> |
||||
/// <param name="file">storage file</param> |
||||
/// <param name="duration">cache duration</param> |
||||
/// <param name="treatNullFileAsOutOfDate">option to mark uninitialized file as expired</param> |
||||
/// <returns>bool indicate whether file has expired or not</returns> |
||||
protected virtual async Task<bool> IsFileOutOfDateAsync( |
||||
string file, |
||||
TimeSpan duration, |
||||
bool treatNullFileAsOutOfDate = true |
||||
) |
||||
{ |
||||
if (file == null) |
||||
{ |
||||
return treatNullFileAsOutOfDate; |
||||
} |
||||
|
||||
var info = new FileInfo(file); |
||||
|
||||
return info.Length == 0 || DateTime.Now.Subtract(info.LastWriteTime) > duration; |
||||
} |
||||
|
||||
private static string GetCacheFileName(Uri uri) |
||||
{ |
||||
return CreateHash64(uri.ToString()).ToString(); |
||||
} |
||||
|
||||
private static ulong CreateHash64(string str) |
||||
{ |
||||
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes(str); |
||||
|
||||
ulong value = (ulong)utf8.Length; |
||||
for (int n = 0; n < utf8.Length; n++) |
||||
{ |
||||
value += (ulong)utf8[n] << ((n * 5) % 56); |
||||
} |
||||
|
||||
return value; |
||||
} |
||||
|
||||
private async Task<T?> GetItemAsync( |
||||
Uri uri, |
||||
bool throwOnError, |
||||
bool preCacheOnly, |
||||
CancellationToken cancellationToken |
||||
) |
||||
{ |
||||
T? instance = default(T); |
||||
|
||||
string fileName = GetCacheFileName(uri); |
||||
_concurrentTasks.TryGetValue(fileName, out var request); |
||||
|
||||
// if similar request exists check if it was preCacheOnly and validate that current request isn't preCacheOnly |
||||
if (request != null && request.EnsureCachedCopy && !preCacheOnly) |
||||
{ |
||||
if (request.Task != null) |
||||
await request.Task.ConfigureAwait(false); |
||||
request = null; |
||||
} |
||||
|
||||
if (request == null) |
||||
{ |
||||
request = new ConcurrentRequest() |
||||
{ |
||||
Task = GetFromCacheOrDownloadAsync(uri, fileName, preCacheOnly, cancellationToken), |
||||
EnsureCachedCopy = preCacheOnly |
||||
}; |
||||
|
||||
_concurrentTasks[fileName] = request; |
||||
} |
||||
|
||||
try |
||||
{ |
||||
if (request.Task != null) |
||||
instance = await request.Task.ConfigureAwait(false); |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
System.Diagnostics.Debug.WriteLine(ex.Message); |
||||
if (throwOnError) |
||||
{ |
||||
throw; |
||||
} |
||||
} |
||||
finally |
||||
{ |
||||
_concurrentTasks.TryRemove(fileName, out _); |
||||
} |
||||
|
||||
return instance; |
||||
} |
||||
|
||||
private async Task<T?> GetFromCacheOrDownloadAsync( |
||||
Uri uri, |
||||
string fileName, |
||||
bool preCacheOnly, |
||||
CancellationToken cancellationToken |
||||
) |
||||
{ |
||||
T? instance = default(T); |
||||
|
||||
if (_inMemoryFileStorage?.MaxItemCount > 0) |
||||
{ |
||||
var msi = _inMemoryFileStorage?.GetItem(fileName, CacheDuration); |
||||
if (msi != null) |
||||
{ |
||||
instance = msi.Item; |
||||
} |
||||
} |
||||
|
||||
if (instance != null) |
||||
{ |
||||
return instance; |
||||
} |
||||
|
||||
var folder = await GetCacheFolderAsync().ConfigureAwait(false); |
||||
var baseFile = Path.Combine(folder!, fileName); |
||||
|
||||
bool downloadDataFile = |
||||
!File.Exists(baseFile) |
||||
|| await IsFileOutOfDateAsync(baseFile, CacheDuration).ConfigureAwait(false); |
||||
|
||||
if (!File.Exists(baseFile)) |
||||
{ |
||||
File.Create(baseFile).Dispose(); |
||||
} |
||||
|
||||
if (downloadDataFile) |
||||
{ |
||||
uint retries = 0; |
||||
try |
||||
{ |
||||
while (retries < RetryCount) |
||||
{ |
||||
try |
||||
{ |
||||
instance = await DownloadFileAsync(uri, baseFile, preCacheOnly, cancellationToken) |
||||
.ConfigureAwait(false); |
||||
|
||||
if (instance != null) |
||||
{ |
||||
break; |
||||
} |
||||
} |
||||
catch (FileNotFoundException) { } |
||||
|
||||
retries++; |
||||
} |
||||
} |
||||
catch (Exception ex) |
||||
{ |
||||
File.Delete(baseFile); |
||||
throw; // re-throwing the exception changes the stack trace. just throw |
||||
} |
||||
} |
||||
|
||||
if (EqualityComparer<T>.Default.Equals(instance, default(T)) && !preCacheOnly) |
||||
{ |
||||
instance = await ConvertFromAsync(baseFile).ConfigureAwait(false); |
||||
|
||||
if (_inMemoryFileStorage?.MaxItemCount > 0) |
||||
{ |
||||
var properties = new FileInfo(baseFile); |
||||
|
||||
var msi = new InMemoryStorageItem<T>(fileName, properties.LastWriteTime, instance); |
||||
_inMemoryFileStorage?.SetItem(msi); |
||||
} |
||||
} |
||||
return instance; |
||||
} |
||||
|
||||
private async Task<T?> DownloadFileAsync( |
||||
Uri uri, |
||||
string baseFile, |
||||
bool preCacheOnly, |
||||
CancellationToken cancellationToken |
||||
) |
||||
{ |
||||
T? instance = default(T); |
||||
|
||||
using (MemoryStream ms = new MemoryStream()) |
||||
{ |
||||
using (var stream = await HttpClient.GetStreamAsync(uri)) |
||||
{ |
||||
stream.CopyTo(ms); |
||||
ms.Flush(); |
||||
|
||||
ms.Position = 0; |
||||
|
||||
using (var fs = File.Open(baseFile, FileMode.OpenOrCreate, FileAccess.Write)) |
||||
{ |
||||
ms.CopyTo(fs); |
||||
|
||||
fs.Flush(); |
||||
|
||||
ms.Position = 0; |
||||
} |
||||
} |
||||
|
||||
// if its pre-cache we aren't looking to load items in memory |
||||
if (!preCacheOnly) |
||||
{ |
||||
instance = await ConvertFromAsync(ms).ConfigureAwait(false); |
||||
} |
||||
} |
||||
|
||||
return instance; |
||||
} |
||||
|
||||
private async Task InternalClearAsync(IEnumerable<string?> files) |
||||
{ |
||||
foreach (var file in files) |
||||
{ |
||||
try |
||||
{ |
||||
File.Delete(file!); |
||||
} |
||||
catch |
||||
{ |
||||
// Just ignore errors for now} |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Initializes with default values if user has not initialized explicitly |
||||
/// </summary> |
||||
/// <returns>awaitable task</returns> |
||||
private async Task ForceInitialiseAsync() |
||||
{ |
||||
if (_cacheFolder != null) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
await _cacheFolderSemaphore.WaitAsync().ConfigureAwait(false); |
||||
|
||||
_inMemoryFileStorage = new InMemoryStorage<T>(); |
||||
|
||||
if (_baseFolder == null) |
||||
{ |
||||
_baseFolder = Path.GetTempPath(); |
||||
} |
||||
|
||||
if (string.IsNullOrWhiteSpace(_cacheFolderName)) |
||||
{ |
||||
_cacheFolderName = GetType().Name; |
||||
} |
||||
|
||||
try |
||||
{ |
||||
_cacheFolder = Path.Combine(_baseFolder, _cacheFolderName); |
||||
Directory.CreateDirectory(_cacheFolder); |
||||
} |
||||
finally |
||||
{ |
||||
_cacheFolderSemaphore.Release(); |
||||
} |
||||
} |
||||
|
||||
private async Task<string?> GetCacheFolderAsync() |
||||
{ |
||||
if (_cacheFolder == null) |
||||
{ |
||||
await ForceInitialiseAsync().ConfigureAwait(false); |
||||
} |
||||
|
||||
return _cacheFolder; |
||||
} |
||||
} |
@ -1,18 +0,0 @@
|
||||
using System; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
public class CacheOptions |
||||
{ |
||||
private static CacheOptions? _cacheOptions; |
||||
|
||||
public static CacheOptions Default => _cacheOptions ??= new CacheOptions(); |
||||
|
||||
public static void SetDefault(CacheOptions defaultCacheOptions) |
||||
{ |
||||
_cacheOptions = defaultCacheOptions; |
||||
} |
||||
|
||||
public string? BaseCachePath { get; set; } |
||||
public TimeSpan? CacheDuration { get; set; } |
||||
} |
@ -1,36 +0,0 @@
|
||||
using System.IO; |
||||
using System.Threading.Tasks; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
/// <summary> |
||||
/// Provides methods and tools to cache files in a folder |
||||
/// </summary> |
||||
internal class FileCache : CacheBase<string> |
||||
{ |
||||
/// <summary> |
||||
/// Private singleton field. |
||||
/// </summary> |
||||
private static FileCache? _instance; |
||||
|
||||
/// <summary> |
||||
/// Gets public singleton property. |
||||
/// </summary> |
||||
public static FileCache Instance => _instance ?? (_instance = new FileCache()); |
||||
|
||||
protected override Task<string> ConvertFromAsync(Stream stream) |
||||
{ |
||||
// nothing to do in this instance; |
||||
return Task.FromResult<string>(""); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Returns a cached path |
||||
/// </summary> |
||||
/// <param name="baseFile">storage file</param> |
||||
/// <returns>awaitable task</returns> |
||||
protected override Task<string> ConvertFromAsync(string baseFile) |
||||
{ |
||||
return Task.FromResult(baseFile); |
||||
} |
||||
} |
@ -1,76 +0,0 @@
|
||||
using System; |
||||
using System.IO; |
||||
using System.Threading.Tasks; |
||||
using Avalonia.Media.Imaging; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
/// <summary> |
||||
/// Provides methods and tools to cache images in a folder |
||||
/// </summary> |
||||
internal class ImageCache : CacheBase<Bitmap> |
||||
{ |
||||
/// <summary> |
||||
/// Private singleton field. |
||||
/// </summary> |
||||
[ThreadStatic] |
||||
private static ImageCache? _instance; |
||||
|
||||
/// <summary> |
||||
/// Gets public singleton property. |
||||
/// </summary> |
||||
public static ImageCache Instance => _instance ?? (_instance = new ImageCache()); |
||||
|
||||
/// <summary> |
||||
/// Creates a bitmap from a stream |
||||
/// </summary> |
||||
/// <param name="stream">input stream</param> |
||||
/// <returns>awaitable task</returns> |
||||
protected override async Task<Bitmap> ConvertFromAsync(Stream stream) |
||||
{ |
||||
if (stream.Length == 0) |
||||
{ |
||||
throw new FileNotFoundException(); |
||||
} |
||||
|
||||
return new Bitmap(stream); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Creates a bitmap from a cached file |
||||
/// </summary> |
||||
/// <param name="baseFile">file</param> |
||||
/// <returns>awaitable task</returns> |
||||
protected override async Task<Bitmap> ConvertFromAsync(string baseFile) |
||||
{ |
||||
using (var stream = File.OpenRead(baseFile)) |
||||
{ |
||||
return await ConvertFromAsync(stream).ConfigureAwait(false); |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Checks whether file is valid or not. |
||||
/// </summary> |
||||
/// <param name="file">file</param> |
||||
/// <param name="duration">cache duration</param> |
||||
/// <param name="treatNullFileAsOutOfDate">option to mark uninitialized file as expired</param> |
||||
/// <returns>bool indicate whether file has expired or not</returns> |
||||
protected override async Task<bool> IsFileOutOfDateAsync( |
||||
string file, |
||||
TimeSpan duration, |
||||
bool treatNullFileAsOutOfDate = true |
||||
) |
||||
{ |
||||
if (file == null) |
||||
{ |
||||
return treatNullFileAsOutOfDate; |
||||
} |
||||
|
||||
var fileInfo = new FileInfo(file); |
||||
|
||||
return fileInfo.Length == 0 |
||||
|| DateTime.Now.Subtract(File.GetLastAccessTime(file)) > duration |
||||
|| DateTime.Now.Subtract(File.GetLastWriteTime(file)) > duration; |
||||
} |
||||
} |
@ -1,156 +0,0 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements. |
||||
// The .NET Foundation licenses this file to you under the MIT license. |
||||
// See the LICENSE file in the project root for more information. |
||||
|
||||
using System; |
||||
using System.Collections.Concurrent; |
||||
using System.Collections.Generic; |
||||
using System.Linq; |
||||
using Avalonia.Labs.Controls.Cache; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
/// <summary> |
||||
/// Generic in-memory storage of items |
||||
/// </summary> |
||||
/// <typeparam name="T">T defines the type of item stored</typeparam> |
||||
public class InMemoryStorage<T> |
||||
{ |
||||
private int _maxItemCount; |
||||
private ConcurrentDictionary<string, InMemoryStorageItem<T>> _inMemoryStorage = |
||||
new ConcurrentDictionary<string, InMemoryStorageItem<T>>(); |
||||
private object _settingMaxItemCountLocker = new object(); |
||||
|
||||
/// <summary> |
||||
/// Gets or sets the maximum count of Items that can be stored in this InMemoryStorage instance. |
||||
/// </summary> |
||||
public int MaxItemCount |
||||
{ |
||||
get { return _maxItemCount; } |
||||
set |
||||
{ |
||||
if (_maxItemCount == value) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
_maxItemCount = value; |
||||
|
||||
lock (_settingMaxItemCountLocker) |
||||
{ |
||||
EnsureStorageBounds(value); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Clears all items stored in memory |
||||
/// </summary> |
||||
public void Clear() |
||||
{ |
||||
_inMemoryStorage.Clear(); |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Clears items stored in memory based on duration passed |
||||
/// </summary> |
||||
/// <param name="duration">TimeSpan to identify expired items</param> |
||||
public void Clear(TimeSpan duration) |
||||
{ |
||||
var expirationDate = DateTime.Now.Subtract(duration); |
||||
|
||||
var itemsToRemove = _inMemoryStorage |
||||
.Where(kvp => kvp.Value.LastUpdated <= expirationDate) |
||||
.Select(kvp => kvp.Key); |
||||
|
||||
if (itemsToRemove.Any()) |
||||
{ |
||||
Remove(itemsToRemove); |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Remove items based on provided keys |
||||
/// </summary> |
||||
/// <param name="keys">identified of the in-memory storage item</param> |
||||
public void Remove(IEnumerable<string> keys) |
||||
{ |
||||
foreach (var key in keys) |
||||
{ |
||||
if (string.IsNullOrWhiteSpace(key)) |
||||
{ |
||||
continue; |
||||
} |
||||
|
||||
_inMemoryStorage.TryRemove(key, out _); |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Add new item to in-memory storage |
||||
/// </summary> |
||||
/// <param name="item">item to be stored</param> |
||||
public void SetItem(InMemoryStorageItem<T> item) |
||||
{ |
||||
if (MaxItemCount == 0) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
_inMemoryStorage[item.Id] = item; |
||||
|
||||
// ensure max limit is maintained. trim older entries first |
||||
if (_inMemoryStorage.Count > MaxItemCount) |
||||
{ |
||||
var itemsToRemove = _inMemoryStorage |
||||
.OrderBy(kvp => kvp.Value.Created) |
||||
.Take(_inMemoryStorage.Count - MaxItemCount) |
||||
.Select(kvp => kvp.Key); |
||||
Remove(itemsToRemove); |
||||
} |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Get item from in-memory storage as long as it has not ex |
||||
/// </summary> |
||||
/// <param name="id">id of the in-memory storage item</param> |
||||
/// <param name="duration">timespan denoting expiration</param> |
||||
/// <returns>Valid item if not out of date or return null if out of date or item does not exist</returns> |
||||
public InMemoryStorageItem<T>? GetItem(string id, TimeSpan duration) |
||||
{ |
||||
if (!_inMemoryStorage.TryGetValue(id, out var tempItem)) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
var expirationDate = DateTime.Now.Subtract(duration); |
||||
|
||||
if (tempItem.LastUpdated > expirationDate) |
||||
{ |
||||
return tempItem; |
||||
} |
||||
|
||||
_inMemoryStorage.TryRemove(id, out _); |
||||
|
||||
return null; |
||||
} |
||||
|
||||
private void EnsureStorageBounds(int maxCount) |
||||
{ |
||||
if (_inMemoryStorage.Count == 0) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
if (maxCount == 0) |
||||
{ |
||||
_inMemoryStorage.Clear(); |
||||
return; |
||||
} |
||||
|
||||
if (_inMemoryStorage.Count > maxCount) |
||||
{ |
||||
Remove(_inMemoryStorage.Keys.Take(_inMemoryStorage.Count - maxCount)); |
||||
} |
||||
} |
||||
} |
@ -1,49 +0,0 @@
|
||||
// Licensed to the .NET Foundation under one or more agreements. |
||||
// The .NET Foundation licenses this file to you under the MIT license. |
||||
// See the LICENSE file in the project root for more information. |
||||
|
||||
using System; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls.VendorLabs.Cache; |
||||
|
||||
/// <summary> |
||||
/// Generic InMemoryStorageItem holds items for InMemoryStorage. |
||||
/// </summary> |
||||
/// <typeparam name="T">Type is set by consuming cache</typeparam> |
||||
public class InMemoryStorageItem<T> |
||||
{ |
||||
/// <summary> |
||||
/// Gets the item identifier |
||||
/// </summary> |
||||
public string Id { get; private set; } |
||||
|
||||
/// <summary> |
||||
/// Gets the item created timestamp. |
||||
/// </summary> |
||||
public DateTime Created { get; private set; } |
||||
|
||||
/// <summary> |
||||
/// Gets the item last updated timestamp. |
||||
/// </summary> |
||||
public DateTime LastUpdated { get; private set; } |
||||
|
||||
/// <summary> |
||||
/// Gets the item being stored. |
||||
/// </summary> |
||||
public T Item { get; private set; } |
||||
|
||||
/// <summary> |
||||
/// Initializes a new instance of the <see cref="InMemoryStorageItem{T}"/> class. |
||||
/// Constructor for InMemoryStorageItem |
||||
/// </summary> |
||||
/// <param name="id">uniquely identifies the item</param> |
||||
/// <param name="lastUpdated">last updated timestamp</param> |
||||
/// <param name="item">the item being stored</param> |
||||
public InMemoryStorageItem(string id, DateTime lastUpdated, T item) |
||||
{ |
||||
Id = id; |
||||
LastUpdated = lastUpdated; |
||||
Item = item; |
||||
Created = DateTime.Now; |
||||
} |
||||
} |
@ -1,21 +0,0 @@
|
||||
MIT License |
||||
|
||||
Copyright (c) 2023 AvaloniaUI |
||||
|
||||
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. |
@ -1,48 +0,0 @@
|
||||
<ResourceDictionary |
||||
xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:vendorLabs="clr-namespace:StabilityMatrix.Avalonia.Controls.VendorLabs"> |
||||
<Design.PreviewWith> |
||||
<Border Width="200" |
||||
Height="200"> |
||||
|
||||
</Border> |
||||
</Design.PreviewWith> |
||||
|
||||
<ControlTheme x:Key="{x:Type vendorLabs:BetterAsyncImage}" |
||||
TargetType="vendorLabs:BetterAsyncImage"> |
||||
<Setter Property="Background" Value="Transparent" /> |
||||
<Setter Property="IsTabStop" Value="False" /> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<Border Margin="0" |
||||
Padding="0" |
||||
ClipToBounds="True" |
||||
Background="{TemplateBinding Background}" |
||||
BorderBrush="{TemplateBinding BorderBrush}" |
||||
BorderThickness="{TemplateBinding BorderThickness}" |
||||
CornerRadius="{TemplateBinding CornerRadius}"> |
||||
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> |
||||
<Image Name="PART_PlaceholderImage" |
||||
HorizontalAlignment="{TemplateBinding HorizontalAlignment}" |
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}" |
||||
Source="{TemplateBinding PlaceholderSource}" |
||||
Stretch="{TemplateBinding PlaceholderStretch}"/> |
||||
<Image Name="PART_Image" |
||||
HorizontalAlignment="{TemplateBinding HorizontalAlignment}" |
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}" |
||||
Stretch="{TemplateBinding Stretch}"/> |
||||
</Grid> |
||||
</Border> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
<Style Selector="^[State=Failed] /template/ Image#PART_Image"> |
||||
<Setter Property="Opacity" |
||||
Value="0.0" /> |
||||
</Style> |
||||
<Style Selector="^[State=Failed] /template/ Image#PART_PlaceholderImage"> |
||||
<Setter Property="Opacity" |
||||
Value="1.0" /> |
||||
</Style> |
||||
</ControlTheme> |
||||
</ResourceDictionary> |
@ -1,122 +0,0 @@
|
||||
<Styles xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:controls="using:StabilityMatrix.Avalonia.Controls" |
||||
x:DataType="video:SvdImgToVidConditioningViewModel" |
||||
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
xmlns:video="clr-namespace:StabilityMatrix.Avalonia.ViewModels.Inference.Video" |
||||
xmlns:controls1="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia" |
||||
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"> |
||||
<Design.PreviewWith> |
||||
<Grid MinWidth="400"> |
||||
<controls:VideoGenerationSettingsCard DataContext="{x:Static mocks:DesignData.SvdImgToVidConditioningViewModel}" /> |
||||
</Grid> |
||||
</Design.PreviewWith> |
||||
|
||||
<Style Selector="controls|VideoGenerationSettingsCard"> |
||||
<!-- Set Defaults --> |
||||
<Setter Property="HorizontalAlignment" Value="Stretch" /> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<controls:Card Padding="8" HorizontalAlignment="{TemplateBinding HorizontalAlignment}"> |
||||
<Grid Margin="4" RowDefinitions="Auto,Auto,Auto,Auto,Auto" ColumnDefinitions="Auto, *"> |
||||
<TextBlock |
||||
Grid.Row="0" |
||||
Grid.Column="0" |
||||
Margin="0,0,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_Frames}" /> |
||||
<controls1:NumberBox |
||||
Grid.Row="0" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding NumFrames}" |
||||
Margin="8,0,0,0" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline"/> |
||||
|
||||
<TextBlock |
||||
Grid.Row="1" |
||||
Grid.Column="0" |
||||
Margin="0,8,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_Fps}" /> |
||||
<controls1:NumberBox |
||||
Grid.Row="1" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding Fps}" |
||||
Margin="8,8,0,0" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline"/> |
||||
|
||||
<TextBlock |
||||
Grid.Row="2" |
||||
Grid.Column="0" |
||||
Margin="0,8,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_MinCfg}" /> |
||||
<controls1:NumberBox |
||||
Margin="8,8,0,0" |
||||
Grid.Row="2" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding MinCfg}" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline"/> |
||||
|
||||
<TextBlock |
||||
Margin="0,8,8,0" |
||||
Grid.Row="3" |
||||
Grid.Column="0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_MotionBucketId}" /> |
||||
<controls1:NumberBox |
||||
Margin="8,8,0,0" |
||||
Grid.Row="3" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding MotionBucketId}" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline"/> |
||||
|
||||
<StackPanel Grid.Column="0" |
||||
Grid.ColumnSpan="2" |
||||
Grid.Row="4" |
||||
Margin="0,16,0,0"> |
||||
<Grid ColumnDefinitions="*,Auto"> |
||||
<TextBlock |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_AugmentationLevel}" /> |
||||
<controls1:NumberBox |
||||
Grid.Column="1" |
||||
Margin="4,0,0,0" |
||||
ValidationMode="InvalidInputOverwritten" |
||||
SmallChange="0.01" |
||||
SimpleNumberFormat="F2" |
||||
Value="{Binding AugmentationLevel}" |
||||
HorizontalAlignment="Stretch" |
||||
MinWidth="100" |
||||
SpinButtonPlacementMode="Compact"/> |
||||
</Grid> |
||||
<Slider |
||||
Minimum="0" |
||||
Maximum="10" |
||||
Value="{Binding AugmentationLevel}" |
||||
TickFrequency="1" |
||||
Margin="0,0,0,-4" |
||||
TickPlacement="BottomRight"/> |
||||
</StackPanel> |
||||
</Grid> |
||||
</controls:Card> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -1,7 +0,0 @@
|
||||
using Avalonia.Controls.Primitives; |
||||
using StabilityMatrix.Core.Attributes; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
[Transient] |
||||
public class VideoGenerationSettingsCard : TemplatedControl { } |
@ -1,98 +0,0 @@
|
||||
<Styles xmlns="https://github.com/avaloniaui" |
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
xmlns:controls="using:StabilityMatrix.Avalonia.Controls" |
||||
x:DataType="video:VideoOutputSettingsCardViewModel" |
||||
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" |
||||
xmlns:video="clr-namespace:StabilityMatrix.Avalonia.ViewModels.Inference.Video" |
||||
xmlns:controls1="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia" |
||||
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"> |
||||
<Design.PreviewWith> |
||||
<Grid MinWidth="400"> |
||||
<controls:VideoOutputSettingsCard |
||||
DataContext="{x:Static mocks:DesignData.SvdImgToVidConditioningViewModel}" /> |
||||
</Grid> |
||||
</Design.PreviewWith> |
||||
|
||||
<Style Selector="controls|VideoOutputSettingsCard"> |
||||
<!-- Set Defaults --> |
||||
<Setter Property="HorizontalAlignment" Value="Stretch" /> |
||||
<Setter Property="Template"> |
||||
<ControlTemplate> |
||||
<controls:Card Padding="8" HorizontalAlignment="{TemplateBinding HorizontalAlignment}"> |
||||
<Grid Margin="4" RowDefinitions="Auto,Auto,Auto,Auto,Auto" ColumnDefinitions="Auto, *"> |
||||
<TextBlock |
||||
Grid.Row="0" |
||||
Grid.Column="0" |
||||
Grid.ColumnSpan="2" |
||||
Text="Video Output Settings" |
||||
FontSize="16" |
||||
FontWeight="DemiBold" |
||||
Margin="0,0,0,16" |
||||
/> |
||||
<TextBlock |
||||
Grid.Row="1" |
||||
Grid.Column="0" |
||||
Margin="0,0,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_Fps}" /> |
||||
<controls1:NumberBox |
||||
Grid.Row="1" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding Fps}" |
||||
Margin="8,0,0,0" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline" /> |
||||
|
||||
<TextBlock |
||||
Grid.Row="2" |
||||
Grid.Column="0" |
||||
Margin="0,8,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_Lossless}" /> |
||||
<CheckBox |
||||
Grid.Row="2" |
||||
Grid.Column="1" |
||||
IsChecked="{Binding Lossless}" |
||||
Margin="8,8,0,0" |
||||
HorizontalAlignment="Stretch" /> |
||||
|
||||
<TextBlock |
||||
Grid.Row="3" |
||||
Grid.Column="0" |
||||
Margin="0,8,8,0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_VideoQuality}" /> |
||||
<controls1:NumberBox |
||||
Margin="8,8,0,0" |
||||
Grid.Row="3" |
||||
Grid.Column="1" |
||||
SelectionHighlightColor="Transparent" |
||||
Value="{Binding Quality}" |
||||
SimpleNumberFormat="F0" |
||||
SmallChange="1" |
||||
Maximum="100" |
||||
HorizontalAlignment="Stretch" |
||||
SpinButtonPlacementMode="Inline" /> |
||||
|
||||
<TextBlock |
||||
Margin="0,8,8,0" |
||||
Grid.Row="4" |
||||
Grid.Column="0" |
||||
VerticalAlignment="Center" |
||||
Text="{x:Static lang:Resources.Label_VideoOutputMethod}" /> |
||||
<ComboBox |
||||
Grid.Row="4" |
||||
Grid.Column="1" |
||||
Margin="8,8,0,0" |
||||
MinWidth="100" |
||||
ItemsSource="{Binding AvailableMethods}" |
||||
SelectedIndex="{Binding SelectedMethod}" /> |
||||
</Grid> |
||||
</controls:Card> |
||||
</ControlTemplate> |
||||
</Setter> |
||||
</Style> |
||||
</Styles> |
@ -1,7 +0,0 @@
|
||||
using Avalonia.Controls.Primitives; |
||||
using StabilityMatrix.Core.Attributes; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Controls; |
||||
|
||||
[Transient] |
||||
public class VideoOutputSettingsCard : TemplatedControl { } |
@ -1,40 +0,0 @@
|
||||
using System; |
||||
using System.Globalization; |
||||
using System.Linq; |
||||
using System.Reflection; |
||||
using Avalonia.Data.Converters; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Converters; |
||||
|
||||
/// <summary> |
||||
/// Converts an enum value to an attribute |
||||
/// </summary> |
||||
/// <typeparam name="TAttribute">Type of attribute</typeparam> |
||||
public class EnumAttributeConverter<TAttribute>(Func<TAttribute, object?>? accessor = null) : IValueConverter |
||||
where TAttribute : Attribute |
||||
{ |
||||
/// <inheritdoc /> |
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
if (value is null) |
||||
return null; |
||||
|
||||
if (value is not Enum @enum) |
||||
throw new ArgumentException("Value must be an enum"); |
||||
|
||||
var field = @enum.GetType().GetField(@enum.ToString()); |
||||
if (field is null) |
||||
throw new ArgumentException("Value must be an enum"); |
||||
|
||||
if (field.GetCustomAttributes<TAttribute>().FirstOrDefault() is not { } attribute) |
||||
throw new ArgumentException($"Enum value {@enum} does not have attribute {typeof(TAttribute)}"); |
||||
|
||||
return accessor is not null ? accessor(attribute) : attribute; |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
throw new NotSupportedException(); |
||||
} |
||||
} |
@ -1,13 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Converters; |
||||
|
||||
internal static class EnumAttributeConverters |
||||
{ |
||||
public static EnumAttributeConverter<DisplayAttribute> Display => new(); |
||||
|
||||
public static EnumAttributeConverter<DisplayAttribute> DisplayName => new(attribute => attribute.Name); |
||||
|
||||
public static EnumAttributeConverter<DisplayAttribute> DisplayDescription => |
||||
new(attribute => attribute.Description); |
||||
} |
@ -1,37 +0,0 @@
|
||||
using System; |
||||
using System.Globalization; |
||||
using Avalonia.Data.Converters; |
||||
using StabilityMatrix.Core.Extensions; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Converters; |
||||
|
||||
public class FileUriConverter : IValueConverter |
||||
{ |
||||
/// <inheritdoc /> |
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
if (targetType != typeof(Uri)) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
return value switch |
||||
{ |
||||
string str when str.StartsWith("avares://") => new Uri(str), |
||||
string str => new Uri("file://" + str), |
||||
IFormattable formattable => new Uri("file://" + formattable.ToString(null, culture)), |
||||
_ => null |
||||
}; |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
if (targetType == typeof(string) && value is Uri uri) |
||||
{ |
||||
return uri.ToString().StripStart("file://"); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
} |
@ -1,53 +0,0 @@
|
||||
using System; |
||||
using System.Globalization; |
||||
using System.Windows.Input; |
||||
using Avalonia.Data.Converters; |
||||
using PropertyModels.ComponentModel; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Converters; |
||||
|
||||
/// <summary> |
||||
/// Converts an object's named <see cref="Func{TResult}"/> to a <see cref="ICommand"/>. |
||||
/// </summary> |
||||
public class FuncCommandConverter : IValueConverter |
||||
{ |
||||
/// <inheritdoc /> |
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
if (value is null || parameter is null) |
||||
{ |
||||
return null; |
||||
} |
||||
|
||||
// Parameter is the name of the Func<T> to convert. |
||||
if (parameter is not string funcName) |
||||
{ |
||||
// ReSharper disable once LocalizableElement |
||||
throw new ArgumentException("Parameter must be a string.", nameof(parameter)); |
||||
} |
||||
|
||||
// Find the Func<T> on the object. |
||||
if (value.GetType().GetMethod(funcName) is not { } methodInfo) |
||||
{ |
||||
// ReSharper disable once LocalizableElement |
||||
throw new ArgumentException( |
||||
$"Method {funcName} not found on {value.GetType().Name}.", |
||||
nameof(parameter) |
||||
); |
||||
} |
||||
|
||||
// Create a delegate from the method info. |
||||
var func = (Action)methodInfo.CreateDelegate(typeof(Action), value); |
||||
|
||||
// Create ICommand |
||||
var command = ReactiveCommand.Create(func); |
||||
|
||||
return command; |
||||
} |
||||
|
||||
/// <inheritdoc /> |
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) |
||||
{ |
||||
throw new NotSupportedException(); |
||||
} |
||||
} |
@ -1,22 +1,9 @@
|
||||
using System.Threading; |
||||
using System.Threading.Tasks; |
||||
using StabilityMatrix.Core.Services; |
||||
using StabilityMatrix.Core.Services; |
||||
|
||||
namespace StabilityMatrix.Avalonia.DesignData; |
||||
|
||||
public class MockSettingsManager : SettingsManager |
||||
{ |
||||
protected override void LoadSettings(CancellationToken cancellationToken = default) { } |
||||
|
||||
protected override Task LoadSettingsAsync(CancellationToken cancellationToken = default) |
||||
{ |
||||
return Task.CompletedTask; |
||||
} |
||||
|
||||
protected override void SaveSettings(CancellationToken cancellationToken = default) { } |
||||
|
||||
protected override Task SaveSettingsAsync(CancellationToken cancellationToken = default) |
||||
{ |
||||
return Task.CompletedTask; |
||||
} |
||||
protected override void LoadSettings() {} |
||||
protected override void SaveSettings() {} |
||||
} |
||||
|
@ -1,20 +0,0 @@
|
||||
using System; |
||||
using Avalonia.Controls.Notifications; |
||||
using StabilityMatrix.Core.Models.Settings; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Extensions; |
||||
|
||||
public static class NotificationLevelExtensions |
||||
{ |
||||
public static NotificationType ToNotificationType(this NotificationLevel level) |
||||
{ |
||||
return level switch |
||||
{ |
||||
NotificationLevel.Information => NotificationType.Information, |
||||
NotificationLevel.Success => NotificationType.Success, |
||||
NotificationLevel.Warning => NotificationType.Warning, |
||||
NotificationLevel.Error => NotificationType.Error, |
||||
_ => throw new ArgumentOutOfRangeException(nameof(level), level, null) |
||||
}; |
||||
} |
||||
} |
@ -1,54 +0,0 @@
|
||||
using System.Threading.Tasks; |
||||
using AsyncAwaitBestPractices; |
||||
using DesktopNotifications; |
||||
using NLog; |
||||
using StabilityMatrix.Avalonia.Services; |
||||
using StabilityMatrix.Core.Models.PackageModification; |
||||
using StabilityMatrix.Core.Models.Settings; |
||||
|
||||
namespace StabilityMatrix.Avalonia.Extensions; |
||||
|
||||
public static class NotificationServiceExtensions |
||||
{ |
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); |
||||
|
||||
public static void OnPackageInstallCompleted( |
||||
this INotificationService notificationService, |
||||
IPackageModificationRunner runner |
||||
) |
||||
{ |
||||
OnPackageInstallCompletedAsync(notificationService, runner) |
||||
.SafeFireAndForget(ex => Logger.Error(ex, "Error Showing Notification")); |
||||
} |
||||
|
||||
private static async Task OnPackageInstallCompletedAsync( |
||||
this INotificationService notificationService, |
||||
IPackageModificationRunner runner |
||||
) |
||||
{ |
||||
if (runner.Failed) |
||||
{ |
||||
Logger.Error(runner.Exception, "Error Installing Package"); |
||||
|
||||
await notificationService.ShowAsync( |
||||
NotificationKey.Package_Install_Failed, |
||||
new Notification |
||||
{ |
||||
Title = runner.ModificationFailedTitle, |
||||
Body = runner.ModificationFailedMessage |
||||
} |
||||
); |
||||
} |
||||
else |
||||
{ |
||||
await notificationService.ShowAsync( |
||||
NotificationKey.Package_Install_Completed, |
||||
new Notification |
||||
{ |
||||
Title = runner.ModificationCompleteTitle, |
||||
Body = runner.ModificationCompleteMessage |
||||
} |
||||
); |
||||
} |
||||
} |
||||
} |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue