Skip to content

Commit

Permalink
Introduce IGlyphTypeface2 and expose TryGetStream
Browse files Browse the repository at this point in the history
  • Loading branch information
Gillibald committed Aug 30, 2023
1 parent f6809ad commit f624518
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/Avalonia.Base/Media/IGlyphTypeface.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Avalonia.Metadata;

namespace Avalonia.Media
Expand Down Expand Up @@ -111,4 +113,15 @@ public interface IGlyphTypeface : IDisposable
/// <returns>Returns <c>true</c> if the content exists, otherwise <c>false</c>.</returns>
bool TryGetTable(uint tag, out byte[] table);
}

internal interface IGlyphTypeface2 : IGlyphTypeface
{

/// <summary>
/// Returns the font file stream represented by the <see cref="IGlyphTypeface"/> object.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>Returns <c>true</c> if the stream can be obtained, otherwise <c>false</c>.</returns>
bool TryGetStream([NotNullWhen(true)] out Stream? stream);
}
}
40 changes: 39 additions & 1 deletion src/Skia/Avalonia.Skia/GlyphTypefaceImpl.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using Avalonia.Media;
using HarfBuzzSharp;
using SkiaSharp;

namespace Avalonia.Skia
{
internal class GlyphTypefaceImpl : IGlyphTypeface
internal class GlyphTypefaceImpl : IGlyphTypeface, IGlyphTypeface2
{
private bool _isDisposed;
private readonly SKTypeface _typeface;
Expand Down Expand Up @@ -198,5 +200,41 @@ public bool TryGetTable(uint tag, out byte[] table)
{
return _typeface.TryGetTableData(tag, out table);
}

public bool TryGetStream([NotNullWhen(true)] out Stream? stream)
{
try
{
var asset = _typeface.OpenStream();
var size = asset.Length;
var memoryBase = asset.GetMemoryBase();

if (memoryBase != IntPtr.Zero)
{
unsafe
{
stream = new UnmanagedMemoryStream((byte*)memoryBase, size);

return true;
}
}
else
{
var buffer = new byte[size];

asset.Read(buffer, size);

stream = new MemoryStream(buffer);

return true;
}
}
catch
{
stream = null;

return false;
}
}
}
}

0 comments on commit f624518

Please sign in to comment.