diff --git a/samples/ControlCatalog/Assets/kooten.ttf b/samples/ControlCatalog/Assets/kooten.ttf new file mode 100644 index 0000000000..3b052635fb Binary files /dev/null and b/samples/ControlCatalog/Assets/kooten.ttf differ diff --git a/samples/ControlCatalog/ControlCatalog.csproj b/samples/ControlCatalog/ControlCatalog.csproj index b8a8479a49..291c9283be 100644 --- a/samples/ControlCatalog/ControlCatalog.csproj +++ b/samples/ControlCatalog/ControlCatalog.csproj @@ -11,6 +11,9 @@ + + + diff --git a/samples/ControlCatalog/Pages/BorderPage.xaml b/samples/ControlCatalog/Pages/BorderPage.xaml index a81bd13ddd..a95bc945ae 100644 --- a/samples/ControlCatalog/Pages/BorderPage.xaml +++ b/samples/ControlCatalog/Pages/BorderPage.xaml @@ -1,32 +1,36 @@ - - Border - A control which decorates a child with a border and background + + Border + A control which decorates a child with a border and background - - - Border - - + Border + + - Border and Background - - Border and Background + + - Rounded Corners - - Rounded Corners + + - Rounded Corners - - - + + Rounded Corners + Rounded Corners + Rounded Corners + + + + \ No newline at end of file diff --git a/src/Avalonia.Controls/Primitives/TemplatedControl.cs b/src/Avalonia.Controls/Primitives/TemplatedControl.cs index 77735f3f12..65b245e36c 100644 --- a/src/Avalonia.Controls/Primitives/TemplatedControl.cs +++ b/src/Avalonia.Controls/Primitives/TemplatedControl.cs @@ -38,7 +38,7 @@ namespace Avalonia.Controls.Primitives /// /// Defines the property. /// - public static readonly StyledProperty FontFamilyProperty = + public static readonly StyledProperty FontFamilyProperty = TextBlock.FontFamilyProperty.AddOwner(); /// @@ -141,7 +141,7 @@ namespace Avalonia.Controls.Primitives /// /// Gets or sets the font family used to draw the control's text. /// - public string FontFamily + public FontFamily FontFamily { get { return GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 88a9fe077d..bb2bae2ac3 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -28,10 +28,10 @@ namespace Avalonia.Controls /// /// Defines the property. /// - public static readonly AttachedProperty FontFamilyProperty = - AvaloniaProperty.RegisterAttached( + public static readonly AttachedProperty FontFamilyProperty = + AvaloniaProperty.RegisterAttached( nameof(FontFamily), - defaultValue: "Courier New", + defaultValue: new FontFamily("Courier New"), inherits: true); /// @@ -146,7 +146,7 @@ namespace Avalonia.Controls /// /// Gets or sets the font family. /// - public string FontFamily + public FontFamily FontFamily { get { return GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } @@ -227,7 +227,7 @@ namespace Avalonia.Controls /// /// The control. /// The font family. - public static string GetFontFamily(Control control) + public static FontFamily GetFontFamily(Control control) { return control.GetValue(FontFamilyProperty); } diff --git a/src/Avalonia.Visuals/Media/FontFamily.cs b/src/Avalonia.Visuals/Media/FontFamily.cs index ea2d3701b2..d702a311a2 100644 --- a/src/Avalonia.Visuals/Media/FontFamily.cs +++ b/src/Avalonia.Visuals/Media/FontFamily.cs @@ -26,18 +26,9 @@ namespace Avalonia.Media internal FontFamilyKey FontFamilyKey { get; } - internal IFontFamily LoadedFamily - { - get - { - if (_loadedFamily == null) - { - _loadedFamily = AvaloniaLocator.Current.GetService().LoadFontFamily(FontFamilyKey); - } - - return _loadedFamily; - } - } + internal IFontFamily LoadedFamily => _loadedFamily ?? (_loadedFamily = AvaloniaLocator.Current + .GetService() + .LoadFontFamily(FontFamilyKey)); public IEnumerable AvailableTypefaces => LoadedFamily.SupportedTypefaces; } @@ -92,6 +83,18 @@ namespace Avalonia.Media public IEnumerable SupportedTypefaces { get; } } + internal class CustomFont : IFontFamily + { + public CustomFont() : this(new List { new FamilyTypeface() }) { } + + public CustomFont(IEnumerable supportedTypefaces) + { + SupportedTypefaces = new ReadOnlyCollection(new List(supportedTypefaces)); + } + + public IEnumerable SupportedTypefaces { get; } + } + internal interface IFontFamilyLoader { IFontFamily LoadFontFamily(FontFamilyKey fontFamilyKey); diff --git a/src/Avalonia.Visuals/Media/Typeface.cs b/src/Avalonia.Visuals/Media/Typeface.cs index c85144d48e..6baec1a246 100644 --- a/src/Avalonia.Visuals/Media/Typeface.cs +++ b/src/Avalonia.Visuals/Media/Typeface.cs @@ -7,7 +7,7 @@ namespace Avalonia.Media /// public class Typeface { - public Typeface(FontFamily fontFamily, double fontSize, FontStyle style = FontStyle.Normal, + public Typeface(FontFamily fontFamily, double fontSize = 12, FontStyle style = FontStyle.Normal, FontWeight weight = FontWeight.Normal) { if (fontSize <= 0) @@ -35,7 +35,7 @@ namespace Avalonia.Media /// The font weight. public Typeface( string fontFamilyName, - double fontSize, + double fontSize = 12, FontStyle style = FontStyle.Normal, FontWeight weight = FontWeight.Normal) : this(new FontFamily(fontFamilyName), fontSize, style, weight) { } diff --git a/src/Avalonia.Visuals/Rendering/RendererBase.cs b/src/Avalonia.Visuals/Rendering/RendererBase.cs index eac362e997..ed464ec7f9 100644 --- a/src/Avalonia.Visuals/Rendering/RendererBase.cs +++ b/src/Avalonia.Visuals/Rendering/RendererBase.cs @@ -18,7 +18,7 @@ namespace Avalonia.Rendering { _fpsText = new FormattedText { - Typeface = new Typeface(null, 18), + Typeface = s_fpsTypeface }; } diff --git a/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj b/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj index bd6acfdad1..6447dca2b2 100644 --- a/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj +++ b/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj @@ -32,6 +32,7 @@ + diff --git a/src/Markup/Avalonia.Markup.Xaml/Converters/FontFamilyTypeConverter.cs b/src/Markup/Avalonia.Markup.Xaml/Converters/FontFamilyTypeConverter.cs new file mode 100644 index 0000000000..51d35fabff --- /dev/null +++ b/src/Markup/Avalonia.Markup.Xaml/Converters/FontFamilyTypeConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.ComponentModel; +using System.Globalization; +using Avalonia.Media; + +namespace Avalonia.Markup.Xaml.Converters +{ + public class FontFamilyTypeConverter : TypeConverter + { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + return sourceType == typeof(string); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + var s = (string)value; + + if (string.IsNullOrEmpty(s)) throw new ArgumentException("Specified family is not supported."); + + var fontFamilyExpression = s.Split('#'); + + switch (fontFamilyExpression.Length) + { + case 1: + { + return new FontFamily(fontFamilyExpression[0]); + } + case 2: + { + return new FontFamily(fontFamilyExpression[1], new Uri(fontFamilyExpression[0], UriKind.RelativeOrAbsolute)); + } + default: + { + throw new ArgumentException("Specified family is not supported."); + } + } + } + } +} \ No newline at end of file diff --git a/src/Markup/Avalonia.Markup.Xaml/PortableXaml/AvaloniaDefaultTypeConverters.cs b/src/Markup/Avalonia.Markup.Xaml/PortableXaml/AvaloniaDefaultTypeConverters.cs index 1ae24c8a34..6b523cae6f 100644 --- a/src/Markup/Avalonia.Markup.Xaml/PortableXaml/AvaloniaDefaultTypeConverters.cs +++ b/src/Markup/Avalonia.Markup.Xaml/PortableXaml/AvaloniaDefaultTypeConverters.cs @@ -49,6 +49,7 @@ namespace Avalonia.Markup.Xaml.PortableXaml { typeof(Cursor), typeof(CursorTypeConverter) }, { typeof(WindowIcon), typeof(IconTypeConverter) }, //{ typeof(FontWeight), typeof(FontWeightConverter) }, + { typeof(FontFamily), typeof(FontFamilyTypeConverter)} }; public static Type GetTypeConverter(Type type) diff --git a/src/Skia/Avalonia.Skia/FormattedTextImpl.cs b/src/Skia/Avalonia.Skia/FormattedTextImpl.cs index f22722a0b5..baf3a210d5 100644 --- a/src/Skia/Avalonia.Skia/FormattedTextImpl.cs +++ b/src/Skia/Avalonia.Skia/FormattedTextImpl.cs @@ -26,9 +26,9 @@ namespace Avalonia.Skia Text = Text.Replace((char)0, (char)0x200B); var skiaTypeface = TypefaceCache.GetTypeface( - typeface?.FontFamilyName ?? "monospace", - typeface?.Style ?? FontStyle.Normal, - typeface?.Weight ?? FontWeight.Normal); + typeface.FontFamily.Name ?? "monospace", + typeface.Style, + typeface.Weight); _paint = new SKPaint(); @@ -40,7 +40,7 @@ namespace Avalonia.Skia _paint.LcdRenderText = true; _paint.SubpixelText = true; _paint.Typeface = skiaTypeface; - _paint.TextSize = (float)(typeface?.FontSize ?? 12); + _paint.TextSize = (float)typeface.FontSize; _paint.TextAlign = textAlignment.ToSKTextAlign(); _wrapping = wrapping; diff --git a/src/Windows/Avalonia.Direct2D1/Media/FormattedTextImpl.cs b/src/Windows/Avalonia.Direct2D1/Media/FormattedTextImpl.cs index 5578abc32c..2b3aa31c64 100644 --- a/src/Windows/Avalonia.Direct2D1/Media/FormattedTextImpl.cs +++ b/src/Windows/Avalonia.Direct2D1/Media/FormattedTextImpl.cs @@ -3,9 +3,11 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Avalonia.Media; using Avalonia.Platform; +using SharpDX; using DWrite = SharpDX.DirectWrite; namespace Avalonia.Direct2D1.Media @@ -21,28 +23,56 @@ namespace Avalonia.Direct2D1.Media IReadOnlyList spans) { Text = text; + var factory = AvaloniaLocator.Current.GetService(); - using (var format = new DWrite.TextFormat( - factory, - typeface?.FontFamilyName ?? "Courier New", - (DWrite.FontWeight)(typeface?.Weight ?? FontWeight.Normal), - (DWrite.FontStyle)(typeface?.Style ?? FontStyle.Normal), - (float)(typeface?.FontSize ?? 12))) + if (typeface.FontFamily.BaseUri != null) { - format.WordWrapping = wrapping == TextWrapping.Wrap ? - DWrite.WordWrapping.Wrap : - DWrite.WordWrapping.NoWrap; + var fontLoader = new ResourceFontLoader(factory, typeface.FontFamily.BaseUri); + + var fontCollection = new DWrite.FontCollection(factory, fontLoader, fontLoader.Key); + + using (var textFormat = + new DWrite.TextFormat(factory, typeface.FontFamily.Name, fontCollection, DWrite.FontWeight.Normal, + DWrite.FontStyle.Normal, DWrite.FontStretch.Normal, (float)typeface.FontSize)) + { + textFormat.TextAlignment = DWrite.TextAlignment.Center; + textFormat.ParagraphAlignment = DWrite.ParagraphAlignment.Center; + + textFormat.WordWrapping = wrapping == TextWrapping.Wrap ? + DWrite.WordWrapping.Wrap : + DWrite.WordWrapping.NoWrap; - TextLayout = new DWrite.TextLayout( + TextLayout = new DWrite.TextLayout(factory, Text ?? string.Empty, textFormat, (float)constraint.Width, + (float)constraint.Height) + { + TextAlignment = textAlignment.ToDirect2D() + }; + } + } + else + { + using (var format = new DWrite.TextFormat( factory, - text ?? string.Empty, - format, - (float)constraint.Width, - (float)constraint.Height) + typeface?.FontFamily.Name ?? "Courier New", + (DWrite.FontWeight)(typeface.Weight), + (DWrite.FontStyle)(typeface.Style), + (float)typeface.FontSize)) { - TextAlignment = textAlignment.ToDirect2D() - }; + format.WordWrapping = wrapping == TextWrapping.Wrap ? + DWrite.WordWrapping.Wrap : + DWrite.WordWrapping.NoWrap; + + TextLayout = new DWrite.TextLayout( + factory, + text ?? string.Empty, + format, + (float)constraint.Width, + (float)constraint.Height) + { + TextAlignment = textAlignment.ToDirect2D() + }; + } } if (spans != null) @@ -140,4 +170,245 @@ namespace Avalonia.Direct2D1.Media return new Size(width, TextLayout.Metrics.Height); } } + + public class ResourceFontLoader : CallbackBase, DWrite.FontCollectionLoader, DWrite.FontFileLoader + { + private readonly List _fontStreams = new List(); + private readonly List _enumerators = new List(); + private readonly DataStream _keyStream; + private readonly DWrite.Factory _factory; + + + /// + /// Initializes a new instance of the class. + /// + /// The factory. + /// + public ResourceFontLoader(DWrite.Factory factory, Uri fontResource) + { + _factory = factory; + + var assets = AvaloniaLocator.Current.GetService(); + + var resourceStream = assets.Open(fontResource); + + var dataStream = new DataStream((int)resourceStream.Length, true, true); + + resourceStream.CopyTo(dataStream); + + dataStream.Position = 0; + + _fontStreams.Add(new ResourceFontFileStream(dataStream)); + + // Build a Key storage that stores the index of the font + _keyStream = new DataStream(sizeof(int) * _fontStreams.Count, true, true); + + for (int i = 0; i < _fontStreams.Count; i++) + { + _keyStream.Write(i); + } + + _keyStream.Position = 0; + + // Register the + _factory.RegisterFontFileLoader(this); + _factory.RegisterFontCollectionLoader(this); + } + + + /// + /// Gets the key used to identify the FontCollection as well as storing index for fonts. + /// + /// The key. + public DataStream Key + { + get + { + return _keyStream; + } + } + + /// + /// Creates a font file enumerator object that encapsulates a collection of font files. The font system calls back to this interface to create a font collection. + /// + /// Pointer to the object that was used to create the current font collection. + /// A font collection key that uniquely identifies the collection of font files within the scope of the font collection loader being used. The buffer allocated for this key must be at least the size, in bytes, specified by collectionKeySize. + /// + /// a reference to the newly created font file enumerator. + /// + /// HRESULT IDWriteFontCollectionLoader::CreateEnumeratorFromKey([None] IDWriteFactory* factory,[In, Buffer] const void* collectionKey,[None] int collectionKeySize,[Out] IDWriteFontFileEnumerator** fontFileEnumerator) + DWrite.FontFileEnumerator DWrite.FontCollectionLoader.CreateEnumeratorFromKey(DWrite.Factory factory, DataPointer collectionKey) + { + var enumerator = new ResourceFontFileEnumerator(factory, this, collectionKey); + + _enumerators.Add(enumerator); + + return enumerator; + } + + /// + /// Creates a font file stream object that encapsulates an open file resource. + /// + /// A reference to a font file reference key that uniquely identifies the font file resource within the scope of the font loader being used. The buffer allocated for this key must at least be the size, in bytes, specified by fontFileReferenceKeySize. + /// + /// a reference to the newly created object. + /// + /// + /// The resource is closed when the last reference to fontFileStream is released. + /// + /// HRESULT IDWriteFontFileLoader::CreateStreamFromKey([In, Buffer] const void* fontFileReferenceKey,[None] int fontFileReferenceKeySize,[Out] IDWriteFontFileStream** fontFileStream) + DWrite.FontFileStream DWrite.FontFileLoader.CreateStreamFromKey(DataPointer fontFileReferenceKey) + { + var index = SharpDX.Utilities.Read(fontFileReferenceKey.Pointer); + + return _fontStreams[index]; + } + } + + /// + /// This FontFileStream implem is reading data from a . + /// + public class ResourceFontFileStream : CallbackBase, DWrite.FontFileStream + { + private readonly DataStream _stream; + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + public ResourceFontFileStream(DataStream stream) + { + this._stream = stream; + } + + /// + /// Reads a fragment from a font file. + /// + /// When this method returns, contains an address of a reference to the start of the font file fragment. This parameter is passed uninitialized. + /// The offset of the fragment, in bytes, from the beginning of the font file. + /// The size of the file fragment, in bytes. + /// When this method returns, contains the address of + /// + /// Note that ReadFileFragment implementations must check whether the requested font file fragment is within the file bounds. Otherwise, an error should be returned from ReadFileFragment. {{DirectWrite}} may invoke methods on the same object from multiple threads simultaneously. Therefore, ReadFileFragment implementations that rely on internal mutable state must serialize access to such state across multiple threads. For example, an implementation that uses separate Seek and Read operations to read a file fragment must place the code block containing Seek and Read calls under a lock or a critical section. + /// + /// HRESULT IDWriteFontFileStream::ReadFileFragment([Out, Buffer] const void** fragmentStart,[None] __int64 fileOffset,[None] __int64 fragmentSize,[Out] void** fragmentContext) + void DWrite.FontFileStream.ReadFileFragment(out IntPtr fragmentStart, long fileOffset, long fragmentSize, out IntPtr fragmentContext) + { + lock (this) + { + fragmentContext = IntPtr.Zero; + + _stream.Position = fileOffset; + + fragmentStart = _stream.PositionPointer; + + } + } + + /// + /// Releases a fragment from a file. + /// + /// A reference to the client-defined context of a font fragment returned from {{ReadFileFragment}}. + /// void IDWriteFontFileStream::ReleaseFileFragment([None] void* fragmentContext) + void DWrite.FontFileStream.ReleaseFileFragment(IntPtr fragmentContext) + { + // Nothing to release. No context are used + } + + /// + /// Obtains the total size of a file. + /// + /// the total size of the file. + /// + /// Implementing GetFileSize() for asynchronously loaded font files may require downloading the complete file contents. Therefore, this method should be used only for operations that either require a complete font file to be loaded (for example, copying a font file) or that need to make decisions based on the value of the file size (for example, validation against a persisted file size). + /// + /// HRESULT IDWriteFontFileStream::GetFileSize([Out] __int64* fileSize) + long DWrite.FontFileStream.GetFileSize() + { + return _stream.Length; + } + + /// + /// Obtains the last modified time of the file. + /// + /// + /// the last modified time of the file in the format that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). + /// + /// + /// The "last modified time" is used by DirectWrite font selection algorithms to determine whether one font resource is more up to date than another one. + /// + /// HRESULT IDWriteFontFileStream::GetLastWriteTime([Out] __int64* lastWriteTime) + long DWrite.FontFileStream.GetLastWriteTime() + { + return 0; + } + } + + /// + /// Resource FontFileEnumerator. + /// + public class ResourceFontFileEnumerator : CallbackBase, DWrite.FontFileEnumerator + { + private DWrite.Factory _factory; + private DWrite.FontFileLoader _loader; + private DataStream keyStream; + private DWrite.FontFile _currentFontFile; + + /// + /// Initializes a new instance of the class. + /// + /// The factory. + /// The loader. + /// The key. + public ResourceFontFileEnumerator(DWrite.Factory factory, DWrite.FontFileLoader loader, DataPointer key) + { + _factory = factory; + + _loader = loader; + + keyStream = new DataStream(key.Pointer, key.Size, true, false); + } + + /// + /// Advances to the next font file in the collection. When it is first created, the enumerator is positioned before the first element of the collection and the first call to MoveNext advances to the first file. + /// + /// + /// the value TRUE if the enumerator advances to a file; otherwise, FALSE if the enumerator advances past the last file in the collection. + /// + /// HRESULT IDWriteFontFileEnumerator::MoveNext([Out] BOOL* hasCurrentFile) + bool DWrite.FontFileEnumerator.MoveNext() + { + bool moveNext = keyStream.RemainingLength != 0; + + if (moveNext) + { + if (_currentFontFile != null) + { + _currentFontFile.Dispose(); + } + + _currentFontFile = new DWrite.FontFile(_factory, keyStream.PositionPointer, 4, _loader); + + keyStream.Position += 4; + } + + return moveNext; + } + + /// + /// Gets a reference to the current font file. + /// + /// + /// a reference to the newly created object. + /// HRESULT IDWriteFontFileEnumerator::GetCurrentFontFile([Out] IDWriteFontFile** fontFile) + DWrite.FontFile DWrite.FontFileEnumerator.CurrentFontFile + { + get + { + ((IUnknown)_currentFontFile).AddReference(); + + return _currentFontFile; + } + } + } }