diff --git a/.gitmodules b/.gitmodules
index 10c780c09f..9dbc50ef61 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -3,4 +3,4 @@
url = https://github.com/kekekeks/Numerge.git
[submodule "src/Markup/Avalonia.Markup.Xaml/XamlIl/xamlil.github"]
path = src/Markup/Avalonia.Markup.Xaml/XamlIl/xamlil.github
- url = https://github.com/kekekeks/XamlIl.git
+ url = https://github.com/kekekeks/XamlX.git
diff --git a/Avalonia.sln b/Avalonia.sln
index f6dc039c2f..4ab647a25e 100644
--- a/Avalonia.sln
+++ b/Avalonia.sln
@@ -207,6 +207,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NativeEmbedSample", "sample
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Avalonia.Themes.Fluent", "src\Avalonia.Themes.Fluent\Avalonia.Themes.Fluent.csproj", "{C42D2FC1-A531-4ED4-84B9-89AEC7C962FC}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Headless", "src\Avalonia.Headless\Avalonia.Headless.csproj", "{8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Avalonia.Headless.Vnc", "src\Avalonia.Headless.Vnc\Avalonia.Headless.Vnc.csproj", "{B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}"
+EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
src\Shared\RenderHelpers\RenderHelpers.projitems*{3c4c0cb4-0c0f-4450-a37b-148c84ff905f}*SharedItemsImports = 13
@@ -1826,6 +1830,54 @@ Global
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhone.Build.0 = Release|Any CPU
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
{3278F3A9-9509-4A3F-A15B-BDC8B5BFF632}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|Any CPU.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhone.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhone.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhone.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhone.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|Any CPU.Build.0 = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhone.ActiveCfg = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhone.Build.0 = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
+ {8C89950F-F5D9-47FC-8066-CBC1EC3DF8FC}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|Any CPU.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhone.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhone.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhone.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhone.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhone.ActiveCfg = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhone.Build.0 = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU
+ {B859AE7C-F34F-4A9E-88AE-E0E7229FDE1E}.Release|iPhoneSimulator.Build.0 = Release|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU
{4D55985A-1EE2-4F25-AD39-6EA8BC04F8FB}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU
diff --git a/build/HarfBuzzSharp.props b/build/HarfBuzzSharp.props
index 873048ef21..88c4d36282 100644
--- a/build/HarfBuzzSharp.props
+++ b/build/HarfBuzzSharp.props
@@ -1,6 +1,6 @@
-
-
+
+
diff --git a/build/SkiaSharp.props b/build/SkiaSharp.props
index 4def44cbd0..a8d9332c57 100644
--- a/build/SkiaSharp.props
+++ b/build/SkiaSharp.props
@@ -1,6 +1,6 @@
-
-
+
+
diff --git a/native/Avalonia.Native/inc/avalonia-native.h b/native/Avalonia.Native/inc/avalonia-native.h
index 6800ff7d68..9ff6130e5f 100644
--- a/native/Avalonia.Native/inc/avalonia-native.h
+++ b/native/Avalonia.Native/inc/avalonia-native.h
@@ -205,6 +205,15 @@ enum AvnMenuItemToggleType
Radio
};
+enum AvnExtendClientAreaChromeHints
+{
+ AvnNoChrome = 0,
+ AvnSystemChrome = 0x01,
+ AvnPreferSystemChrome = 0x02,
+ AvnOSXThickTitleBar = 0x08,
+ AvnDefaultChrome = AvnSystemChrome,
+};
+
AVNCOM(IAvaloniaNativeFactory, 01) : IUnknown
{
public:
@@ -279,6 +288,10 @@ AVNCOM(IAvnWindow, 04) : virtual IAvnWindowBase
virtual HRESULT SetWindowState(AvnWindowState state) = 0;
virtual HRESULT GetWindowState(AvnWindowState*ret) = 0;
virtual HRESULT TakeFocusFromChildren() = 0;
+ virtual HRESULT SetExtendClientArea (bool enable) = 0;
+ virtual HRESULT SetExtendClientAreaHints (AvnExtendClientAreaChromeHints hints) = 0;
+ virtual HRESULT GetExtendTitleBarHeight (double*ret) = 0;
+ virtual HRESULT SetExtendTitleBarHeight (double value) = 0;
};
AVNCOM(IAvnWindowBaseEvents, 05) : IUnknown
diff --git a/native/Avalonia.Native/src/OSX/window.h b/native/Avalonia.Native/src/OSX/window.h
index bdf3007a28..b1f64bca88 100644
--- a/native/Avalonia.Native/src/OSX/window.h
+++ b/native/Avalonia.Native/src/OSX/window.h
@@ -3,9 +3,6 @@
class WindowBaseImpl;
-@interface AutoFitContentVisualEffectView : NSVisualEffectView
-@end
-
@interface AvnView : NSView
-(AvnView* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
-(NSEvent* _Nonnull) lastMouseDownEvent;
@@ -15,6 +12,14 @@ class WindowBaseImpl;
-(AvnPixelSize) getPixelSize;
@end
+@interface AutoFitContentView : NSView
+-(AutoFitContentView* _Nonnull) initWithContent: (NSView* _Nonnull) content;
+-(void) ShowTitleBar: (bool) show;
+-(void) SetTitleBarHeightHint: (double) height;
+-(void) SetContent: (NSView* _Nonnull) content;
+-(void) ShowBlur: (bool) show;
+@end
+
@interface AvnWindow : NSWindow
+(void) closeAll;
-(AvnWindow* _Nonnull) initWithParent: (WindowBaseImpl* _Nonnull) parent;
@@ -27,6 +32,8 @@ class WindowBaseImpl;
-(void) showWindowMenuWithAppMenu;
-(void) applyMenu:(NSMenu* _Nullable)menu;
-(double) getScaling;
+-(double) getExtendedTitleBarHeight;
+-(void) setIsExtended:(bool)value;
@end
struct INSWindowHolder
diff --git a/native/Avalonia.Native/src/OSX/window.mm b/native/Avalonia.Native/src/OSX/window.mm
index 7f8a6e1393..872269bb26 100644
--- a/native/Avalonia.Native/src/OSX/window.mm
+++ b/native/Avalonia.Native/src/OSX/window.mm
@@ -6,8 +6,6 @@
#include
#include "rendertarget.h"
-
-
class WindowBaseImpl : public virtual ComSingleObject, public INSWindowHolder
{
private:
@@ -20,7 +18,7 @@ public:
View = NULL;
Window = NULL;
}
- NSVisualEffectView* VisualEffect;
+ AutoFitContentView* StandardContainer;
AvnView* View;
AvnWindow* Window;
ComPtr BaseEvents;
@@ -39,6 +37,7 @@ public:
_glContext = gl;
renderTarget = [[IOSurfaceRenderTarget alloc] initWithOpenGlContext: gl];
View = [[AvnView alloc] initWithParent:this];
+ StandardContainer = [[AutoFitContentView new] initWithContent:View];
Window = [[AvnWindow alloc] initWithParent:this];
@@ -49,12 +48,8 @@ public:
[Window setStyleMask:NSWindowStyleMaskBorderless];
[Window setBackingType:NSBackingStoreBuffered];
- VisualEffect = [AutoFitContentVisualEffectView new];
- [VisualEffect setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
- [VisualEffect setMaterial:NSVisualEffectMaterialLight];
- [VisualEffect setAutoresizesSubviews:true];
-
- [Window setContentView: View];
+ [Window setOpaque:false];
+ [Window setContentView: StandardContainer];
}
virtual HRESULT ObtainNSWindowHandle(void** ret) override
@@ -410,12 +405,7 @@ public:
virtual HRESULT SetBlurEnabled (bool enable) override
{
- [Window setContentView: enable ? VisualEffect : View];
-
- if(enable)
- {
- [VisualEffect addSubview:View];
- }
+ [StandardContainer ShowBlur:enable];
return S_OK;
}
@@ -492,6 +482,8 @@ private:
bool _inSetWindowState;
NSRect _preZoomSize;
bool _transitioningWindowState;
+ bool _isClientAreaExtended;
+ AvnExtendClientAreaChromeHints _extendClientHints;
FORWARD_IUNKNOWN()
BEGIN_INTERFACE_MAP()
@@ -505,6 +497,8 @@ private:
ComPtr WindowEvents;
WindowImpl(IAvnWindowEvents* events, IAvnGlContext* gl) : WindowBaseImpl(events, gl)
{
+ _isClientAreaExtended = false;
+ _extendClientHints = AvnDefaultChrome;
_fullScreenActive = false;
_canResize = true;
_decorations = SystemDecorationsFull;
@@ -523,8 +517,20 @@ private:
if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")]) {
NSView *titlebarView = [subview subviews][0];
for (id button in titlebarView.subviews) {
- if ([button isKindOfClass:[NSButton class]]) {
- [button setHidden: (_decorations != SystemDecorationsFull)];
+ if ([button isKindOfClass:[NSButton class]])
+ {
+ if(_isClientAreaExtended)
+ {
+ auto wantsChrome = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
+
+ [button setHidden: !wantsChrome];
+ }
+ else
+ {
+ [button setHidden: (_decorations != SystemDecorationsFull)];
+ }
+
+ [button setWantsLayer:true];
}
}
}
@@ -600,6 +606,35 @@ private:
if(_lastWindowState != state)
{
+ if(_isClientAreaExtended)
+ {
+ if(_lastWindowState == FullScreen)
+ {
+ // we exited fs.
+ if(_extendClientHints & AvnOSXThickTitleBar)
+ {
+ Window.toolbar = [NSToolbar new];
+ Window.toolbar.showsBaselineSeparator = false;
+ }
+
+ [Window setTitlebarAppearsTransparent:true];
+
+ [StandardContainer setFrameSize: StandardContainer.frame.size];
+ }
+ else if(state == FullScreen)
+ {
+ // we entered fs.
+ if(_extendClientHints & AvnOSXThickTitleBar)
+ {
+ Window.toolbar = nullptr;
+ }
+
+ [Window setTitlebarAppearsTransparent:false];
+
+ [StandardContainer setFrameSize: StandardContainer.frame.size];
+ }
+ }
+
_lastWindowState = state;
WindowEvents->WindowStateChanged(state);
}
@@ -656,8 +691,6 @@ private:
return S_OK;
}
- auto currentFrame = [Window frame];
-
UpdateStyle();
HideOrShowTrafficLights();
@@ -790,6 +823,81 @@ private:
return S_OK;
if([Window isKeyWindow])
[Window makeFirstResponder: View];
+
+ return S_OK;
+ }
+
+ virtual HRESULT SetExtendClientArea (bool enable) override
+ {
+ _isClientAreaExtended = enable;
+
+ if(enable)
+ {
+ Window.titleVisibility = NSWindowTitleHidden;
+
+ [Window setTitlebarAppearsTransparent:true];
+
+ auto wantsTitleBar = (_extendClientHints & AvnSystemChrome) || (_extendClientHints & AvnPreferSystemChrome);
+
+ if (wantsTitleBar)
+ {
+ [StandardContainer ShowTitleBar:true];
+ }
+ else
+ {
+ [StandardContainer ShowTitleBar:false];
+ }
+
+ if(_extendClientHints & AvnOSXThickTitleBar)
+ {
+ Window.toolbar = [NSToolbar new];
+ Window.toolbar.showsBaselineSeparator = false;
+ }
+ else
+ {
+ Window.toolbar = nullptr;
+ }
+ }
+ else
+ {
+ Window.titleVisibility = NSWindowTitleVisible;
+ Window.toolbar = nullptr;
+ [Window setTitlebarAppearsTransparent:false];
+ View.layer.zPosition = 0;
+ }
+
+ [Window setIsExtended:enable];
+
+ HideOrShowTrafficLights();
+
+ UpdateStyle();
+
+ return S_OK;
+ }
+
+ virtual HRESULT SetExtendClientAreaHints (AvnExtendClientAreaChromeHints hints) override
+ {
+ _extendClientHints = hints;
+
+ SetExtendClientArea(_isClientAreaExtended);
+ return S_OK;
+ }
+
+ virtual HRESULT GetExtendTitleBarHeight (double*ret) override
+ {
+ if(ret == nullptr)
+ {
+ return E_POINTER;
+ }
+
+ *ret = [Window getExtendedTitleBarHeight];
+
+ return S_OK;
+ }
+
+ virtual HRESULT SetExtendTitleBarHeight (double value) override
+ {
+ [StandardContainer SetTitleBarHeightHint:value];
return S_OK;
}
@@ -802,8 +910,9 @@ private:
[Window setTitlebarAppearsTransparent:NO];
[Window setTitle:_lastTitle];
- [Window setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskResizable];
-
+ Window.styleMask = Window.styleMask | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable;
+ Window.styleMask = Window.styleMask & ~NSWindowStyleMaskFullSizeContentView;
+
[Window toggleFullScreen:nullptr];
}
@@ -951,19 +1060,120 @@ protected:
{
s |= NSWindowStyleMaskMiniaturizable;
}
+
+ if(_isClientAreaExtended)
+ {
+ s |= NSWindowStyleMaskFullSizeContentView | NSWindowStyleMaskTexturedBackground;
+ }
return s;
}
};
NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode, NSRunLoopCommonModes, NSConnectionReplyMode, nil];
-@implementation AutoFitContentVisualEffectView
+@implementation AutoFitContentView
+{
+ NSVisualEffectView* _titleBarMaterial;
+ NSBox* _titleBarUnderline;
+ NSView* _content;
+ NSVisualEffectView* _blurBehind;
+ double _titleBarHeightHint;
+ bool _settingSize;
+}
+
+-(AutoFitContentView* _Nonnull) initWithContent:(NSView *)content
+{
+ _titleBarHeightHint = -1;
+ _content = content;
+ _settingSize = false;
+
+ [self setAutoresizesSubviews:true];
+ [self setWantsLayer:true];
+
+ _titleBarMaterial = [NSVisualEffectView new];
+ [_titleBarMaterial setBlendingMode:NSVisualEffectBlendingModeWithinWindow];
+ [_titleBarMaterial setMaterial:NSVisualEffectMaterialTitlebar];
+ [_titleBarMaterial setWantsLayer:true];
+ _titleBarMaterial.hidden = true;
+
+ _titleBarUnderline = [NSBox new];
+ _titleBarUnderline.boxType = NSBoxSeparator;
+ _titleBarUnderline.fillColor = [NSColor underPageBackgroundColor];
+ _titleBarUnderline.hidden = true;
+
+ [self addSubview:_titleBarMaterial];
+ [self addSubview:_titleBarUnderline];
+
+ _blurBehind = [NSVisualEffectView new];
+ [_blurBehind setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
+ [_blurBehind setMaterial:NSVisualEffectMaterialLight];
+ [_blurBehind setWantsLayer:true];
+ _blurBehind.hidden = true;
+
+ [self addSubview:_blurBehind];
+ [self addSubview:_content];
+
+ [self setWantsLayer:true];
+ return self;
+}
+
+-(void) ShowBlur:(bool)show
+{
+ _blurBehind.hidden = !show;
+}
+
+-(void) ShowTitleBar: (bool) show
+{
+ _titleBarMaterial.hidden = !show;
+ _titleBarUnderline.hidden = !show;
+}
+
+-(void) SetTitleBarHeightHint: (double) height
+{
+ _titleBarHeightHint = height;
+
+ [self setFrameSize:self.frame.size];
+}
+
-(void)setFrameSize:(NSSize)newSize
{
- [super setFrameSize:newSize];
- if([[self subviews] count] == 0)
+ if(_settingSize)
+ {
return;
- [[self subviews][0] setFrameSize: newSize];
+ }
+
+ _settingSize = true;
+ [super setFrameSize:newSize];
+
+ [_blurBehind setFrameSize:newSize];
+ [_content setFrameSize:newSize];
+
+ auto window = objc_cast([self window]);
+
+ // TODO get actual titlebar size
+
+ double height = _titleBarHeightHint == -1 ? [window getExtendedTitleBarHeight] : _titleBarHeightHint;
+
+ NSRect tbar;
+ tbar.origin.x = 0;
+ tbar.origin.y = newSize.height - height;
+ tbar.size.width = newSize.width;
+ tbar.size.height = height;
+
+ [_titleBarMaterial setFrame:tbar];
+ tbar.size.height = height < 1 ? 0 : 1;
+ [_titleBarUnderline setFrame:tbar];
+ _settingSize = false;
+}
+
+-(void) SetContent: (NSView* _Nonnull) content
+{
+ if(content != nullptr)
+ {
+ [content removeFromSuperview];
+ [self addSubview:content];
+ _content = content;
+ }
}
@end
@@ -1523,15 +1733,43 @@ NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEvent
bool _canBecomeKeyAndMain;
bool _closed;
bool _isEnabled;
+ bool _isExtended;
AvnMenu* _menu;
double _lastScaling;
}
+-(void) setIsExtended:(bool)value;
+{
+ _isExtended = value;
+}
+
-(double) getScaling
{
return _lastScaling;
}
+-(double) getExtendedTitleBarHeight
+{
+ if(_isExtended)
+ {
+ for (id subview in self.contentView.superview.subviews)
+ {
+ if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")])
+ {
+ NSView *titlebarView = [subview subviews][0];
+
+ return (double)titlebarView.frame.size.height;
+ }
+ }
+
+ return -1;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+(void)closeAll
{
NSArray* windows = [NSArray arrayWithArray:[NSApp windows]];
@@ -1650,6 +1888,7 @@ NSArray* AllLoopModes = [NSArray arrayWithObjects: NSDefaultRunLoopMode, NSEvent
[self setOpaque:NO];
[self setBackgroundColor: [NSColor clearColor]];
[self invalidateShadow];
+ _isExtended = false;
return self;
}
diff --git a/nukebuild/Build.cs b/nukebuild/Build.cs
index 890967ae4f..fe877dc49c 100644
--- a/nukebuild/Build.cs
+++ b/nukebuild/Build.cs
@@ -268,6 +268,8 @@ partial class Build : NukeBuild
.DependsOn(CreateIntermediateNugetPackages)
.Executes(() =>
{
+ BuildTasksPatcher.PatchBuildTasksInPackage(Parameters.NugetIntermediateRoot / "Avalonia.Build.Tasks." +
+ Parameters.Version + ".nupkg");
var config = Numerge.MergeConfiguration.LoadFile(RootDirectory / "nukebuild" / "numerge.config");
EnsureCleanDirectory(Parameters.NugetRoot);
if(!Numerge.NugetPackageMerger.Merge(Parameters.NugetIntermediateRoot, Parameters.NugetRoot, config,
diff --git a/nukebuild/BuildTasksPatcher.cs b/nukebuild/BuildTasksPatcher.cs
new file mode 100644
index 0000000000..44f01da669
--- /dev/null
+++ b/nukebuild/BuildTasksPatcher.cs
@@ -0,0 +1,76 @@
+using System;
+using System.IO;
+using System.IO.Compression;
+using System.Linq;
+using ILRepacking;
+using Mono.Cecil;
+
+public class BuildTasksPatcher
+{
+ public static void PatchBuildTasksInPackage(string packagePath)
+ {
+ using (var archive = new ZipArchive(File.Open(packagePath, FileMode.Open, FileAccess.ReadWrite),
+ ZipArchiveMode.Update))
+ {
+
+ foreach (var entry in archive.Entries.ToList())
+ {
+ if (entry.Name == "Avalonia.Build.Tasks.dll")
+ {
+ var temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".dll");
+ var output = temp + ".output";
+ var patched = new MemoryStream();
+ try
+ {
+ entry.ExtractToFile(temp, true);
+ var repack = new ILRepacking.ILRepack(new RepackOptions()
+ {
+ Internalize = true,
+ InputAssemblies = new[]
+ {
+ temp, typeof(Mono.Cecil.AssemblyDefinition).Assembly.GetModules()[0]
+ .FullyQualifiedName
+ },
+ SearchDirectories = new string[0],
+ OutputFile = output
+ });
+ repack.Repack();
+
+
+ // 'hurr-durr assembly with the same name is already loaded' prevention
+ using (var asm = AssemblyDefinition.ReadAssembly(output,
+ new ReaderParameters { ReadWrite = true, InMemory = true, }))
+ {
+ asm.Name = new AssemblyNameDefinition(
+ "Avalonia.Build.Tasks."
+ + Guid.NewGuid().ToString().Replace("-", ""),
+ new Version(0, 0, 0));
+ asm.Write(patched);
+ patched.Position = 0;
+ }
+ }
+ finally
+ {
+ try
+ {
+ if (File.Exists(temp))
+ File.Delete(temp);
+ if (File.Exists(output))
+ File.Delete(output);
+ }
+ catch
+ {
+ //ignore
+ }
+ }
+
+ var fn = entry.FullName;
+ entry.Delete();
+ var newEntry = archive.CreateEntry(fn, CompressionLevel.Optimal);
+ using (var s = newEntry.Open())
+ patched.CopyTo(s);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/nukebuild/_build.csproj b/nukebuild/_build.csproj
index 584c36d033..4c64d4ff93 100644
--- a/nukebuild/_build.csproj
+++ b/nukebuild/_build.csproj
@@ -14,6 +14,9 @@
+
+
+
diff --git a/readme.md b/readme.md
index 6a04c7e31e..19a9a8420d 100644
--- a/readme.md
+++ b/readme.md
@@ -16,7 +16,7 @@ To see the status of some of our features, please see our [Roadmap](https://gith
## 🚀 Getting Started
-The Avalonia [Visual Studio Extension](https://marketplace.visualstudio.com/items?itemName=AvaloniaTeam.AvaloniaforVisualStudio) contains project and control templates that will help you get started, or you can use the .NET Core CLI. For a starer guide see our [documentation](http://avaloniaui.net/docs/quickstart/create-new-project).
+The Avalonia [Visual Studio Extension](https://marketplace.visualstudio.com/items?itemName=AvaloniaTeam.AvaloniaforVisualStudio) contains project and control templates that will help you get started, or you can use the .NET Core CLI. For a starter guide see our [documentation](http://avaloniaui.net/docs/quickstart/create-new-project).
Avalonia is delivered via NuGet package manager. You can find the packages here: https://www.nuget.org/packages/Avalonia/
diff --git a/samples/BindingDemo/MainWindow.xaml b/samples/BindingDemo/MainWindow.xaml
index 26a62ebca6..14c371efef 100644
--- a/samples/BindingDemo/MainWindow.xaml
+++ b/samples/BindingDemo/MainWindow.xaml
@@ -5,7 +5,8 @@
xmlns:local="clr-namespace:BindingDemo"
Title="AvaloniaUI Bindings Test"
Width="800"
- Height="600">
+ Height="600"
+ x:DataType="vm:MainWindowViewModel">
+
@@ -55,6 +56,7 @@
+
@@ -66,6 +68,7 @@
+
@@ -79,7 +82,7 @@
Simple - Light
Simple - Dark
-
+
None
Transparent
Blur
diff --git a/samples/ControlCatalog/MainView.xaml.cs b/samples/ControlCatalog/MainView.xaml.cs
index d6d4a71ad3..b0c205246e 100644
--- a/samples/ControlCatalog/MainView.xaml.cs
+++ b/samples/ControlCatalog/MainView.xaml.cs
@@ -58,13 +58,6 @@ namespace ControlCatalog
if (VisualRoot is Window window)
window.SystemDecorations = (SystemDecorations)decorations.SelectedIndex;
};
-
- var transparencyLevels = this.Find("TransparencyLevels");
- transparencyLevels.SelectionChanged += (sender, e) =>
- {
- if (VisualRoot is Window window)
- window.TransparencyLevelHint = (WindowTransparencyLevel)transparencyLevels.SelectedIndex;
- };
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
diff --git a/samples/ControlCatalog/MainWindow.xaml b/samples/ControlCatalog/MainWindow.xaml
index 76422bc130..97bd88f5e4 100644
--- a/samples/ControlCatalog/MainWindow.xaml
+++ b/samples/ControlCatalog/MainWindow.xaml
@@ -7,7 +7,12 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ControlCatalog.ViewModels"
xmlns:v="clr-namespace:ControlCatalog.Views"
- x:Class="ControlCatalog.MainWindow" WindowState="{Binding WindowState, Mode=TwoWay}" Background="{DynamicResource SystemControlPageBackgroundAltHighBrush}">
+ ExtendClientAreaToDecorationsHint="{Binding ExtendClientAreaEnabled}"
+ ExtendClientAreaChromeHints="{Binding ChromeHints}"
+ ExtendClientAreaTitleBarHeightHint="{Binding TitleBarHeight}"
+ TransparencyLevelHint="{Binding TransparencyLevel}"
+ x:Name="MainWindow"
+ x:Class="ControlCatalog.MainWindow" WindowState="{Binding WindowState, Mode=TwoWay}">
@@ -56,20 +61,30 @@
-
+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ControlCatalog/Pages/AcrylicPage.xaml b/samples/ControlCatalog/Pages/AcrylicPage.xaml
new file mode 100644
index 0000000000..96cfcc5288
--- /dev/null
+++ b/samples/ControlCatalog/Pages/AcrylicPage.xaml
@@ -0,0 +1,139 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ControlCatalog/Pages/AcrylicPage.xaml.cs b/samples/ControlCatalog/Pages/AcrylicPage.xaml.cs
new file mode 100644
index 0000000000..44e7c4b92b
--- /dev/null
+++ b/samples/ControlCatalog/Pages/AcrylicPage.xaml.cs
@@ -0,0 +1,19 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+
+namespace ControlCatalog.Pages
+{
+ public class AcrylicPage : UserControl
+ {
+ public AcrylicPage()
+ {
+ this.InitializeComponent();
+ }
+
+ private void InitializeComponent()
+ {
+ AvaloniaXamlLoader.Load(this);
+ }
+ }
+}
diff --git a/samples/ControlCatalog/Pages/BorderPage.xaml b/samples/ControlCatalog/Pages/BorderPage.xaml
index 8133d0e408..bfd14cc627 100644
--- a/samples/ControlCatalog/Pages/BorderPage.xaml
+++ b/samples/ControlCatalog/Pages/BorderPage.xaml
@@ -9,27 +9,27 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
-
+
Border
-
Border and Background
-
Rounded Corners
-
Rounded Corners
-
diff --git a/samples/ControlCatalog/Pages/ButtonPage.xaml b/samples/ControlCatalog/Pages/ButtonPage.xaml
index 8b697b7948..a4427c70c5 100644
--- a/samples/ControlCatalog/Pages/ButtonPage.xaml
+++ b/samples/ControlCatalog/Pages/ButtonPage.xaml
@@ -9,10 +9,10 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
-
-
+
+
-
+
diff --git a/samples/ControlCatalog/Pages/ComboBoxPage.xaml b/samples/ControlCatalog/Pages/ComboBoxPage.xaml
index 486cc55d44..369f703718 100644
--- a/samples/ControlCatalog/Pages/ComboBoxPage.xaml
+++ b/samples/ControlCatalog/Pages/ComboBoxPage.xaml
@@ -16,7 +16,7 @@
-
+
Control Items
diff --git a/samples/ControlCatalog/Pages/ContextMenuPage.xaml b/samples/ControlCatalog/Pages/ContextMenuPage.xaml
index 8f147638b5..8ccd8e97f7 100644
--- a/samples/ControlCatalog/Pages/ContextMenuPage.xaml
+++ b/samples/ControlCatalog/Pages/ContextMenuPage.xaml
@@ -9,7 +9,7 @@
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
-
@@ -34,7 +34,7 @@
-
diff --git a/samples/ControlCatalog/Pages/DragAndDropPage.xaml b/samples/ControlCatalog/Pages/DragAndDropPage.xaml
index 65a798e53c..c22cf68b68 100644
--- a/samples/ControlCatalog/Pages/DragAndDropPage.xaml
+++ b/samples/ControlCatalog/Pages/DragAndDropPage.xaml
@@ -10,15 +10,15 @@
HorizontalAlignment="Center"
Spacing="16">
-
+
Drag Me
-
+
Drag Me (custom)
-
Drop some text or files here
diff --git a/samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs b/samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs
index 82c44508b8..9e898c4536 100644
--- a/samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs
+++ b/samples/ControlCatalog/Pages/ItemsRepeaterPage.xaml.cs
@@ -85,6 +85,26 @@ namespace ControlCatalog.Pages
MinItemHeight = 200,
};
break;
+ case 4:
+ _scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
+ _scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
+ _repeater.Layout = new WrapLayout
+ {
+ Orientation = Orientation.Vertical,
+ HorizontalSpacing = 20,
+ VerticalSpacing = 20
+ };
+ break;
+ case 5:
+ _scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
+ _scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
+ _repeater.Layout = new WrapLayout
+ {
+ Orientation = Orientation.Horizontal,
+ HorizontalSpacing = 20,
+ VerticalSpacing = 20
+ };
+ break;
}
}
diff --git a/samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml b/samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml
index 446dfd7ce1..8cf3610b47 100644
--- a/samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml
+++ b/samples/ControlCatalog/Pages/LayoutTransformControlPage.xaml
@@ -11,10 +11,10 @@
RowDefinitions="24,Auto,24"
HorizontalAlignment="Center"
VerticalAlignment="Center">
-
-
-
-
+
+
+
+
diff --git a/samples/ControlCatalog/Pages/RelativePanelPage.axaml b/samples/ControlCatalog/Pages/RelativePanelPage.axaml
new file mode 100644
index 0000000000..3657d52bd9
--- /dev/null
+++ b/samples/ControlCatalog/Pages/RelativePanelPage.axaml
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ControlCatalog/Pages/RelativePanelPage.axaml.cs b/samples/ControlCatalog/Pages/RelativePanelPage.axaml.cs
new file mode 100644
index 0000000000..11d0a5152e
--- /dev/null
+++ b/samples/ControlCatalog/Pages/RelativePanelPage.axaml.cs
@@ -0,0 +1,19 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+
+namespace ControlCatalog.Pages
+{
+ public class RelativePanelPage : UserControl
+ {
+ public RelativePanelPage()
+ {
+ this.InitializeComponent();
+ }
+
+ private void InitializeComponent()
+ {
+ AvaloniaXamlLoader.Load(this);
+ }
+ }
+}
diff --git a/samples/ControlCatalog/Pages/SliderPage.xaml b/samples/ControlCatalog/Pages/SliderPage.xaml
index c6f5521e60..ea31ed0050 100644
--- a/samples/ControlCatalog/Pages/SliderPage.xaml
+++ b/samples/ControlCatalog/Pages/SliderPage.xaml
@@ -6,11 +6,22 @@
A control that lets the user select from a range of values by moving a Thumb control along a Track.
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+ StrokeThicknessUnit="Pixel"
+ StrokeThickness="2">
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+ StrokeThicknessUnit="Pixel"
+ StrokeThickness="1">
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+ StrokeThicknessUnit="Pixel"
+ StrokeThickness="2">
+
+
+
+
+
+
+
+
diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml b/samples/ControlCatalog/Pages/ToolTipPage.xaml
index 73d83e08f1..ec073d48a9 100644
--- a/samples/ControlCatalog/Pages/ToolTipPage.xaml
+++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml
@@ -12,7 +12,7 @@
HorizontalAlignment="Center">
@@ -26,7 +26,7 @@
diff --git a/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml b/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml
new file mode 100644
index 0000000000..b90f43c3b6
--- /dev/null
+++ b/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+ None
+ Transparent
+ Blur
+ AcrylicBlur
+
+
+
diff --git a/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml.cs b/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml.cs
new file mode 100644
index 0000000000..d8d4f3f371
--- /dev/null
+++ b/samples/ControlCatalog/Pages/WindowCustomizationsPage.xaml.cs
@@ -0,0 +1,19 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Markup.Xaml;
+
+namespace ControlCatalog.Pages
+{
+ public class WindowCustomizationsPage : UserControl
+ {
+ public WindowCustomizationsPage()
+ {
+ this.InitializeComponent();
+ }
+
+ private void InitializeComponent()
+ {
+ AvaloniaXamlLoader.Load(this);
+ }
+ }
+}
diff --git a/samples/ControlCatalog/SideBar.xaml b/samples/ControlCatalog/SideBar.xaml
index 1ee6bf7a29..7c911e91e9 100644
--- a/samples/ControlCatalog/SideBar.xaml
+++ b/samples/ControlCatalog/SideBar.xaml
@@ -12,7 +12,7 @@
diff --git a/samples/ControlCatalog/ViewModels/MainWindowViewModel.cs b/samples/ControlCatalog/ViewModels/MainWindowViewModel.cs
index 0257b4ce66..4356a032fa 100644
--- a/samples/ControlCatalog/ViewModels/MainWindowViewModel.cs
+++ b/samples/ControlCatalog/ViewModels/MainWindowViewModel.cs
@@ -3,6 +3,8 @@ using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Notifications;
using Avalonia.Dialogs;
+using Avalonia.Platform;
+using System;
using ReactiveUI;
namespace ControlCatalog.ViewModels
@@ -14,6 +16,12 @@ namespace ControlCatalog.ViewModels
private bool _isMenuItemChecked = true;
private WindowState _windowState;
private WindowState[] _windowStates;
+ private int _transparencyLevel;
+ private ExtendClientAreaChromeHints _chromeHints;
+ private bool _extendClientAreaEnabled;
+ private bool _systemTitleBarEnabled;
+ private bool _preferSystemChromeEnabled;
+ private double _titleBarHeight;
public MainWindowViewModel(IManagedNotificationManager notificationManager)
{
@@ -62,6 +70,63 @@ namespace ControlCatalog.ViewModels
WindowState.Maximized,
WindowState.FullScreen,
};
+
+ this.WhenAnyValue(x => x.SystemTitleBarEnabled, x=>x.PreferSystemChromeEnabled)
+ .Subscribe(x =>
+ {
+ var hints = ExtendClientAreaChromeHints.NoChrome | ExtendClientAreaChromeHints.OSXThickTitleBar;
+
+ if(x.Item1)
+ {
+ hints |= ExtendClientAreaChromeHints.SystemChrome;
+ }
+
+ if(x.Item2)
+ {
+ hints |= ExtendClientAreaChromeHints.PreferSystemChrome;
+ }
+
+ ChromeHints = hints;
+ });
+
+ SystemTitleBarEnabled = true;
+ TitleBarHeight = -1;
+ }
+
+ public int TransparencyLevel
+ {
+ get { return _transparencyLevel; }
+ set { this.RaiseAndSetIfChanged(ref _transparencyLevel, value); }
+ }
+
+ public ExtendClientAreaChromeHints ChromeHints
+ {
+ get { return _chromeHints; }
+ set { this.RaiseAndSetIfChanged(ref _chromeHints, value); }
+ }
+
+ public bool ExtendClientAreaEnabled
+ {
+ get { return _extendClientAreaEnabled; }
+ set { this.RaiseAndSetIfChanged(ref _extendClientAreaEnabled, value); }
+ }
+
+ public bool SystemTitleBarEnabled
+ {
+ get { return _systemTitleBarEnabled; }
+ set { this.RaiseAndSetIfChanged(ref _systemTitleBarEnabled, value); }
+ }
+
+ public bool PreferSystemChromeEnabled
+ {
+ get { return _preferSystemChromeEnabled; }
+ set { this.RaiseAndSetIfChanged(ref _preferSystemChromeEnabled, value); }
+ }
+
+ public double TitleBarHeight
+ {
+ get { return _titleBarHeight; }
+ set { this.RaiseAndSetIfChanged(ref _titleBarHeight, value); }
}
public WindowState WindowState
diff --git a/samples/RenderDemo/Pages/ClippingPage.xaml b/samples/RenderDemo/Pages/ClippingPage.xaml
index 8920b8a123..10225f7c49 100644
--- a/samples/RenderDemo/Pages/ClippingPage.xaml
+++ b/samples/RenderDemo/Pages/ClippingPage.xaml
@@ -43,7 +43,7 @@
C 72.078834 28.113269 74.047517 25.960974 74.931641 23.777344
C 78.93827 14.586564 73.049722 2.8815081 63.248047 0.67382812
C 61.721916 0.22817968 60.165597 0.038541919 58.625 0.07421875 z ">
-
+
@@ -53,4 +53,4 @@
Apply Geometry Clip
-
\ No newline at end of file
+
diff --git a/samples/RenderDemo/SideBar.xaml b/samples/RenderDemo/SideBar.xaml
index d6bde0b146..07fdb91a16 100644
--- a/samples/RenderDemo/SideBar.xaml
+++ b/samples/RenderDemo/SideBar.xaml
@@ -3,7 +3,7 @@
diff --git a/samples/interop/NativeEmbedSample/NativeEmbedSample.csproj b/samples/interop/NativeEmbedSample/NativeEmbedSample.csproj
index c623ae68b5..cc831ef8ae 100644
--- a/samples/interop/NativeEmbedSample/NativeEmbedSample.csproj
+++ b/samples/interop/NativeEmbedSample/NativeEmbedSample.csproj
@@ -10,6 +10,7 @@
+
diff --git a/src/Avalonia.Base/AvaloniaProperty.cs b/src/Avalonia.Base/AvaloniaProperty.cs
index daa7191cc5..a873d5fd42 100644
--- a/src/Avalonia.Base/AvaloniaProperty.cs
+++ b/src/Avalonia.Base/AvaloniaProperty.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using Avalonia.Data;
+using Avalonia.Data.Core;
using Avalonia.Utilities;
namespace Avalonia
@@ -9,7 +10,7 @@ namespace Avalonia
///
/// Base class for avalonia properties.
///
- public abstract class AvaloniaProperty : IEquatable
+ public abstract class AvaloniaProperty : IEquatable, IPropertyInfo
{
///
/// Represents an unset property value.
@@ -159,8 +160,6 @@ namespace Avalonia
///
internal int Id { get; }
- internal bool HasChangedSubscriptions => _changed?.HasObservers ?? false;
-
///
/// Provides access to a property's binding via the
/// indexer.
@@ -512,7 +511,7 @@ namespace Avalonia
///
/// An if setting the property can be undone, otherwise null.
///
- internal abstract IDisposable? RouteSetValue(
+ internal abstract IDisposable RouteSetValue(
IAvaloniaObject o,
object value,
BindingPriority priority);
@@ -584,6 +583,11 @@ namespace Avalonia
return _defaultMetadata;
}
+
+ bool IPropertyInfo.CanGet => true;
+ bool IPropertyInfo.CanSet => true;
+ object IPropertyInfo.Get(object target) => ((AvaloniaObject)target).GetValue(this);
+ void IPropertyInfo.Set(object target, object value) => ((AvaloniaObject)target).SetValue(this, value);
}
///
diff --git a/src/Avalonia.Base/AvaloniaPropertyRegistry.cs b/src/Avalonia.Base/AvaloniaPropertyRegistry.cs
index 4a3b104f2a..4cde965400 100644
--- a/src/Avalonia.Base/AvaloniaPropertyRegistry.cs
+++ b/src/Avalonia.Base/AvaloniaPropertyRegistry.cs
@@ -362,7 +362,7 @@ namespace Avalonia
/// The property.
///
/// You won't usually want to call this method directly, instead use the
- ///
+ ///
/// method.
///
public void Register(Type type, AvaloniaProperty property)
@@ -413,7 +413,7 @@ namespace Avalonia
/// The property.
///
/// You won't usually want to call this method directly, instead use the
- ///
+ ///
/// method.
///
public void RegisterAttached(Type type, AvaloniaProperty property)
diff --git a/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs b/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs
index 9bc3609dc5..7a233a62ab 100644
--- a/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs
+++ b/src/Avalonia.Base/Collections/Pooled/IReadOnlyPooledList.cs
@@ -13,9 +13,11 @@ namespace Avalonia.Collections.Pooled
public interface IReadOnlyPooledList : IReadOnlyList
{
+#pragma warning disable CS0419
///
/// Gets a for the items currently in the collection.
///
+#pragma warning restore CS0419
ReadOnlySpan Span { get; }
}
}
diff --git a/src/Avalonia.Base/Collections/Pooled/PooledList.cs b/src/Avalonia.Base/Collections/Pooled/PooledList.cs
index f0d6b292cc..e50e100d32 100644
--- a/src/Avalonia.Base/Collections/Pooled/PooledList.cs
+++ b/src/Avalonia.Base/Collections/Pooled/PooledList.cs
@@ -138,7 +138,6 @@ namespace Avalonia.Collections.Pooled
/// initially empty, but will have room for the given number of elements
/// before any reallocations are required.
///
- /// If true, Count of list equals capacity. Depending on ClearMode, rented items may or may not hold dirty values.
public PooledList(int capacity, ClearMode clearMode, ArrayPool customPool, bool sizeToCapacity)
{
if (capacity < 0)
@@ -499,11 +498,13 @@ namespace Avalonia.Collections.Pooled
public void AddRange(T[] array)
=> AddRange(array.AsSpan());
+#pragma warning disable CS0419
///
/// Adds the elements of the given to the end of this list. If
/// required, the capacity of the list is increased to twice the previous
/// capacity or the new size, whichever is larger.
///
+#pragma warning restore CS0419
public void AddRange(ReadOnlySpan span)
{
var newSpan = InsertSpan(_size, span.Length, false);
diff --git a/src/Avalonia.Base/Data/BindingValue.cs b/src/Avalonia.Base/Data/BindingValue.cs
index 9aac1bacba..6e3c9ae67b 100644
--- a/src/Avalonia.Base/Data/BindingValue.cs
+++ b/src/Avalonia.Base/Data/BindingValue.cs
@@ -1,4 +1,5 @@
using System;
+using System.Diagnostics.CodeAnalysis;
using Avalonia.Utilities;
#nullable enable
@@ -81,14 +82,14 @@ namespace Avalonia.Data
///
public readonly struct BindingValue
{
- private readonly T _value;
+ [AllowNull] private readonly T _value;
///
/// Initializes a new instance of the struct with a type of
///
///
/// The value.
- public BindingValue(T value)
+ public BindingValue([AllowNull] T value)
{
ValidateValue(value);
_value = value;
@@ -96,7 +97,7 @@ namespace Avalonia.Data
Error = null;
}
- private BindingValue(BindingValueType type, T value, Exception? error)
+ private BindingValue(BindingValueType type, [AllowNull] T value, Exception? error)
{
_value = value;
Type = type;
@@ -154,7 +155,7 @@ namespace Avalonia.Data
BindingValueType.UnsetValue => AvaloniaProperty.UnsetValue,
BindingValueType.DoNothing => BindingOperations.DoNothing,
BindingValueType.Value => _value,
- BindingValueType.BindingError =>
+ BindingValueType.BindingError =>
new BindingNotification(Error, BindingErrorType.Error),
BindingValueType.BindingErrorWithFallback =>
new BindingNotification(Error, BindingErrorType.Error, Value),
@@ -175,7 +176,7 @@ namespace Avalonia.Data
/// The binding type is or
/// .
///
- public BindingValue WithValue(T value)
+ public BindingValue WithValue([AllowNull] T value)
{
if (Type == BindingValueType.DoNothing)
{
@@ -190,6 +191,7 @@ namespace Avalonia.Data
/// Gets the value of the binding value if present, otherwise the default value.
///
/// The value.
+ [return: MaybeNull]
public T GetValueOrDefault() => HasValue ? _value : default;
///
@@ -206,6 +208,7 @@ namespace Avalonia.Data
/// The value if present and of the correct type, `default(TResult)` if the value is
/// not present or of an incorrect type.
///
+ [return: MaybeNull]
public TResult GetValueOrDefault()
{
return HasValue ?
@@ -222,7 +225,8 @@ namespace Avalonia.Data
/// present but not of the correct type or null, or if the
/// value is not present.
///
- public TResult GetValueOrDefault(TResult defaultValue)
+ [return: MaybeNull]
+ public TResult GetValueOrDefault([AllowNull] TResult defaultValue)
{
return HasValue ?
_value is TResult result ? result : default
@@ -242,7 +246,7 @@ namespace Avalonia.Data
UnsetValueType _ => Unset,
DoNothingType _ => DoNothing,
BindingNotification n => n.ToBindingValue().Cast(),
- _ => (T)value
+ _ => new BindingValue((T)value)
};
}
@@ -250,7 +254,7 @@ namespace Avalonia.Data
/// Creates a binding value from an instance of the underlying value type.
///
/// The value.
- public static implicit operator BindingValue(T value) => new BindingValue(value);
+ public static implicit operator BindingValue([AllowNull] T value) => new BindingValue(value);
///
/// Creates a binding value from an .
@@ -278,7 +282,7 @@ namespace Avalonia.Data
/// The binding error.
public static BindingValue BindingError(Exception e)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(BindingValueType.BindingError, default, e);
}
@@ -290,7 +294,7 @@ namespace Avalonia.Data
/// The fallback value.
public static BindingValue BindingError(Exception e, T fallbackValue)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(BindingValueType.BindingErrorWithFallback, fallbackValue, e);
}
@@ -303,7 +307,7 @@ namespace Avalonia.Data
/// The fallback value.
public static BindingValue BindingError(Exception e, Optional fallbackValue)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(
fallbackValue.HasValue ?
@@ -319,7 +323,7 @@ namespace Avalonia.Data
/// The data validation error.
public static BindingValue DataValidationError(Exception e)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(BindingValueType.DataValidationError, default, e);
}
@@ -331,7 +335,7 @@ namespace Avalonia.Data
/// The fallback value.
public static BindingValue DataValidationError(Exception e, T fallbackValue)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(BindingValueType.DataValidationErrorWithFallback, fallbackValue, e);
}
@@ -344,7 +348,7 @@ namespace Avalonia.Data
/// The fallback value.
public static BindingValue DataValidationError(Exception e, Optional fallbackValue)
{
- e = e ?? throw new ArgumentNullException("e");
+ e = e ?? throw new ArgumentNullException(nameof(e));
return new BindingValue(
fallbackValue.HasValue ?
@@ -354,7 +358,7 @@ namespace Avalonia.Data
e);
}
- private static void ValidateValue(T value)
+ private static void ValidateValue([AllowNull] T value)
{
if (value is UnsetValueType)
{
diff --git a/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs b/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs
new file mode 100644
index 0000000000..f66411c2c2
--- /dev/null
+++ b/src/Avalonia.Base/Data/Core/ClrPropertyInfo.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Linq.Expressions;
+using System.Reflection;
+
+namespace Avalonia.Data.Core
+{
+ public class ClrPropertyInfo : IPropertyInfo
+ {
+ private readonly Func
-
-
-
-
- $(MSBuildThisFileDirectory)bin\$(Configuration)\$(TargetFramework)
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs b/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs
index f94f10f792..5a2c74e16f 100644
--- a/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs
+++ b/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.Helpers.cs
@@ -5,7 +5,7 @@ using Avalonia.Utilities;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
-using XamlIl.TypeSystem;
+using XamlX.TypeSystem;
namespace Avalonia.Build.Tasks
{
diff --git a/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs b/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs
index 30e8f120d7..c1cc0e7bf0 100644
--- a/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs
+++ b/src/Avalonia.Build.Tasks/XamlCompilerTaskExecutor.cs
@@ -7,17 +7,18 @@ using System.Text;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Microsoft.Build.Framework;
using Mono.Cecil;
-using XamlIl.TypeSystem;
using Avalonia.Utilities;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
-using XamlIl;
-using XamlIl.Ast;
-using XamlIl.Parsers;
-using XamlIl.Transform;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Parsers;
+using XamlX.Transform;
+using XamlX.TypeSystem;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
+using XamlX.IL;
namespace Avalonia.Build.Tasks
{
@@ -50,23 +51,32 @@ namespace Avalonia.Build.Tasks
if (avares.Resources.Count(CheckXamlName) == 0 && emres.Resources.Count(CheckXamlName) == 0)
// Nothing to do
return new CompileResult(true);
-
- var xamlLanguage = AvaloniaXamlIlLanguage.Configure(typeSystem);
- var compilerConfig = new XamlIlTransformerConfiguration(typeSystem,
+
+ var clrPropertiesDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlHelpers",
+ TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
+ asm.MainModule.Types.Add(clrPropertiesDef);
+ var indexerAccessorClosure = new TypeDefinition("CompiledAvaloniaXaml", "!IndexerAccessorFactoryClosure",
+ TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
+ asm.MainModule.Types.Add(indexerAccessorClosure);
+
+ var (xamlLanguage , emitConfig) = AvaloniaXamlIlLanguage.Configure(typeSystem);
+ var compilerConfig = new AvaloniaXamlIlCompilerConfiguration(typeSystem,
typeSystem.TargetAssembly,
xamlLanguage,
- XamlIlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
- AvaloniaXamlIlLanguage.CustomValueConverter);
+ XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
+ AvaloniaXamlIlLanguage.CustomValueConverter,
+ new XamlIlClrPropertyInfoEmitter(typeSystem.CreateTypeBuilder(clrPropertiesDef)),
+ new XamlIlPropertyInfoAccessorFactoryEmitter(typeSystem.CreateTypeBuilder(indexerAccessorClosure)));
var contextDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlContext",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(contextDef);
- var contextClass = XamlIlContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
- xamlLanguage);
+ var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
+ xamlLanguage, emitConfig);
- var compiler = new AvaloniaXamlIlCompiler(compilerConfig, contextClass) { EnableIlVerification = verifyIl };
+ var compiler = new AvaloniaXamlIlCompiler(compilerConfig, emitConfig, contextClass) { EnableIlVerification = verifyIl };
var editorBrowsableAttribute = typeSystem
.GetTypeReference(typeSystem.FindType("System.ComponentModel.EditorBrowsableAttribute"))
@@ -126,35 +136,35 @@ namespace Avalonia.Build.Tasks
// StreamReader is needed here to handle BOM
var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd();
- var parsed = XDocumentXamlIlParser.Parse(xaml);
+ var parsed = XDocumentXamlParser.Parse(xaml);
- var initialRoot = (XamlIlAstObjectNode)parsed.Root;
+ var initialRoot = (XamlAstObjectNode)parsed.Root;
- var precompileDirective = initialRoot.Children.OfType()
+ var precompileDirective = initialRoot.Children.OfType()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Precompile");
if (precompileDirective != null)
{
- var precompileText = (precompileDirective.Values[0] as XamlIlAstTextNode)?.Text.Trim()
+ var precompileText = (precompileDirective.Values[0] as XamlAstTextNode)?.Text.Trim()
.ToLowerInvariant();
if (precompileText == "false")
continue;
if (precompileText != "true")
- throw new XamlIlParseException("Invalid value for x:Precompile", precompileDirective);
+ throw new XamlParseException("Invalid value for x:Precompile", precompileDirective);
}
- var classDirective = initialRoot.Children.OfType()
+ var classDirective = initialRoot.Children.OfType()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class");
- IXamlIlType classType = null;
+ IXamlType classType = null;
if (classDirective != null)
{
- if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlIlAstTextNode tn))
- throw new XamlIlParseException("x:Class should have a string value", classDirective);
+ if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlAstTextNode tn))
+ throw new XamlParseException("x:Class should have a string value", classDirective);
classType = typeSystem.TargetAssembly.FindType(tn.Text);
if (classType == null)
- throw new XamlIlParseException($"Unable to find type `{tn.Text}`", classDirective);
+ throw new XamlParseException($"Unable to find type `{tn.Text}`", classDirective);
compiler.OverrideRootType(parsed,
- new XamlIlAstClrTypeReference(classDirective, classType, false));
+ new XamlAstClrTypeReference(classDirective, classType, false));
initialRoot.Children.Remove(classDirective);
}
@@ -323,7 +333,7 @@ namespace Avalonia.Build.Tasks
catch (Exception e)
{
int lineNumber = 0, linePosition = 0;
- if (e is XamlIlParseException xe)
+ if (e is XamlParseException xe)
{
lineNumber = xe.LineNumber;
linePosition = xe.LinePosition;
diff --git a/src/Avalonia.Controls.DataGrid/DataGrid.cs b/src/Avalonia.Controls.DataGrid/DataGrid.cs
index 7e893d131e..fe9656a00b 100644
--- a/src/Avalonia.Controls.DataGrid/DataGrid.cs
+++ b/src/Avalonia.Controls.DataGrid/DataGrid.cs
@@ -3920,6 +3920,8 @@ namespace Avalonia.Controls
dataGridColumn: CurrentColumn,
dataGridRow: EditingRow,
dataGridCell: editingCell);
+
+ EditingRow.InvalidateDesiredHeight();
}
// We're done, so raise the CellEditEnded event
diff --git a/src/Avalonia.Controls.DataGrid/DataGridRow.cs b/src/Avalonia.Controls.DataGrid/DataGridRow.cs
index 830eff1102..d5115c983a 100644
--- a/src/Avalonia.Controls.DataGrid/DataGridRow.cs
+++ b/src/Avalonia.Controls.DataGrid/DataGridRow.cs
@@ -767,6 +767,11 @@ namespace Avalonia.Controls
}
}
+ internal void InvalidateDesiredHeight()
+ {
+ _cellsElement?.InvalidateDesiredHeight();
+ }
+
internal void ResetGridLine()
{
_bottomGridLine = null;
diff --git a/src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs b/src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs
index 6e0703c90f..c5fe9f0cb2 100644
--- a/src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs
+++ b/src/Avalonia.Controls.DataGrid/Primitives/DataGridCellsPresenter.cs
@@ -299,6 +299,11 @@ namespace Avalonia.Controls.Primitives
DesiredHeight = 0;
}
+ internal void InvalidateDesiredHeight()
+ {
+ DesiredHeight = 0;
+ }
+
private bool ShouldDisplayCell(DataGridColumn column, double frozenLeftEdge, double scrollingLeftEdge)
{
if (!column.IsVisible)
diff --git a/src/Avalonia.Controls.DataGrid/Themes/Default.xaml b/src/Avalonia.Controls.DataGrid/Themes/Default.xaml
index 17e7ecba43..738732f671 100644
--- a/src/Avalonia.Controls.DataGrid/Themes/Default.xaml
+++ b/src/Avalonia.Controls.DataGrid/Themes/Default.xaml
@@ -188,7 +188,7 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Default/ComboBox.xaml b/src/Avalonia.Themes.Default/ComboBox.xaml
index 95bd9550a5..ae5b902ae8 100644
--- a/src/Avalonia.Themes.Default/ComboBox.xaml
+++ b/src/Avalonia.Themes.Default/ComboBox.xaml
@@ -1,10 +1,29 @@
+
+
+
+
+ Item 1
+ Item 2
+
+
+ Item 1
+ Item 2
+
+
+
+
-
+
+
diff --git a/src/Avalonia.Themes.Default/TitleBar.xaml b/src/Avalonia.Themes.Default/TitleBar.xaml
new file mode 100644
index 0000000000..45798d3fa1
--- /dev/null
+++ b/src/Avalonia.Themes.Default/TitleBar.xaml
@@ -0,0 +1,53 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Default/ToggleSwitch.xaml b/src/Avalonia.Themes.Default/ToggleSwitch.xaml
index 88266ac979..893d64f505 100644
--- a/src/Avalonia.Themes.Default/ToggleSwitch.xaml
+++ b/src/Avalonia.Themes.Default/ToggleSwitch.xaml
@@ -43,8 +43,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Default/Window.xaml b/src/Avalonia.Themes.Default/Window.xaml
index 0e7ec42856..739887fb35 100644
--- a/src/Avalonia.Themes.Default/Window.xaml
+++ b/src/Avalonia.Themes.Default/Window.xaml
@@ -5,7 +5,9 @@
-
+
+
+
#FF0066CC
#FFFFFFFF
#FF000000
- Segoe UI
+ avares://Avalonia.Themes.Fluent/Assets#Roboto
14
diff --git a/src/Avalonia.Themes.Fluent/Accents/BaseDark.xaml b/src/Avalonia.Themes.Fluent/Accents/BaseDark.xaml
index 68b33d104a..fb08b97b47 100644
--- a/src/Avalonia.Themes.Fluent/Accents/BaseDark.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/BaseDark.xaml
@@ -158,8 +158,6 @@
XamlAutoFontFamily
Segoe WP
Segoe WP SemiLight
- XamlAutoFontFamily
- XamlAutoFontFamily
XamlAutoFontFamily
Segoe MDL2 Assets
XamlAutoFontFamily
@@ -217,9 +215,6 @@
96
8
16
- 24
- 40
- 14
0.6
4
2
@@ -262,7 +257,6 @@
44
44
12
- -25
0,0,0,0
0,0,0,0
0,0,0,0
@@ -312,12 +306,6 @@
19,19,19,0
19,37,19,0
0,0,0,32.5
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
0
2
1
@@ -346,8 +334,6 @@
Normal
SemiLight
Normal
- SemiLight
- Bold
Normal
Normal
Normal
diff --git a/src/Avalonia.Themes.Fluent/Accents/BaseLight.xaml b/src/Avalonia.Themes.Fluent/Accents/BaseLight.xaml
index d8a641e8ac..6c8d16ddfa 100644
--- a/src/Avalonia.Themes.Fluent/Accents/BaseLight.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/BaseLight.xaml
@@ -157,8 +157,6 @@
XamlAutoFontFamily
Segoe WP
Segoe WP SemiLight
- XamlAutoFontFamily
- XamlAutoFontFamily
XamlAutoFontFamily
Segoe MDL2 Assets
XamlAutoFontFamily
@@ -216,9 +214,6 @@
96
8
16
- 24
- 40
- 14
0.6
4
2
@@ -261,7 +256,6 @@
44
44
12
- -25
0,0,0,0
0,0,0,0
0,0,0,0
@@ -311,12 +305,6 @@
19,19,19,0
19,37,19,0
0,0,0,32.5
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
0
0
1
@@ -345,8 +333,6 @@
Normal
SemiLight
Normal
- SemiLight
- Bold
Normal
Normal
Normal
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentBaseDark.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentBaseDark.xaml
index 8647e7f0dc..1c65911593 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentBaseDark.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentBaseDark.xaml
@@ -11,8 +11,8 @@
- 2,2,2,2
- 4,4,4,4
+ 3
+ 5
1,1,1,1
@@ -373,74 +373,33 @@
-
- XamlAutoFontFamily
- XamlAutoFontFamily
- 24
- 40
- 14
- -25
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
- SemiLight
- Bold
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+ XamlAutoFontFamily
+ 24
+ 40
+ -25
+ 12,0,12,0
+ 12,0,12,0
+ SemiLight
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentBaseLight.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentBaseLight.xaml
index 2b960259d0..ad23955776 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentBaseLight.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentBaseLight.xaml
@@ -11,8 +11,8 @@
- 2,2,2,2
- 4,4,4,4
+ 3
+ 5
1,1,1,1
@@ -376,74 +376,33 @@
-
- XamlAutoFontFamily
- XamlAutoFontFamily
- 24
- 40
- 14
- -25
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
- SemiLight
- Bold
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+ XamlAutoFontFamily
+ 24
+ 40
+ -25
+ 12,0,12,0
+ 12,0,12,0
+ SemiLight
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesDark.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesDark.xaml
index 5ab50f5b73..653e4733cb 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesDark.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesDark.xaml
@@ -254,9 +254,7 @@
1
32
0,0
-
12,0,0,0
-
12,4,12,4
@@ -266,31 +264,12 @@
-
-
-
-
@@ -300,51 +279,16 @@
1
-
-
-
-
-
-
-
0.6
4
- 0
+ 0
-
+
@@ -700,7 +644,7 @@
-
+
@@ -727,75 +671,34 @@
-
-
- XamlAutoFontFamily
- XamlAutoFontFamily
- 24
- 40
- 14
- -25
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
- SemiLight
- Bold
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+ XamlAutoFontFamily
+ 24
+ 40
+ -25
+ 12,0,12,0
+ 12,0,12,0
+ SemiLight
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
0
@@ -891,5 +794,11 @@
32
+
+
+
+
+
+ 1
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesLight.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesLight.xaml
index 88040a69e7..6a2a04f732 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesLight.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentControlResourcesLight.xaml
@@ -261,9 +261,7 @@
1
32
0,0
-
12,0,0,0
-
12,4,12,4
@@ -273,31 +271,12 @@
-
-
-
@@ -307,40 +286,6 @@
1
-
-
-
-
-
-
@@ -490,6 +435,15 @@
+
+
+
+
+
+
+
+
+
1
@@ -725,74 +679,33 @@
-
- XamlAutoFontFamily
- XamlAutoFontFamily
- 24
- 40
- 14
- -25
- 12,0,12,0
- 12,0,12,0
- 12,14,0,13
- 0
- 0,6,0,0
- 12,14,0,13
- SemiLight
- Bold
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+ XamlAutoFontFamily
+ 24
+ 40
+ -25
+ 12,0,12,0
+ 12,0,12,0
+ SemiLight
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
0
@@ -888,5 +801,11 @@
32
+
+
+
+
+
+ 1
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentDark.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentDark.xaml
index d29db79e7b..9ef92a44d5 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentDark.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentDark.xaml
@@ -1,9 +1,9 @@
-
-
-
-
-
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/Accents/FluentLight.xaml b/src/Avalonia.Themes.Fluent/Accents/FluentLight.xaml
index 43867f6e97..8c92040122 100644
--- a/src/Avalonia.Themes.Fluent/Accents/FluentLight.xaml
+++ b/src/Avalonia.Themes.Fluent/Accents/FluentLight.xaml
@@ -1,9 +1,9 @@
-
-
-
-
-
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Black.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Black.ttf
new file mode 100644
index 0000000000..38f809991d
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Black.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Bold.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Bold.ttf
new file mode 100644
index 0000000000..5fd9dd9eed
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Bold.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Light.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Light.ttf
new file mode 100644
index 0000000000..113d545eea
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Light.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Medium.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Medium.ttf
new file mode 100644
index 0000000000..98c4538462
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Medium.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Regular.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Regular.ttf
new file mode 100644
index 0000000000..c1c3700fe5
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Regular.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/Assets/Roboto-Thin.ttf b/src/Avalonia.Themes.Fluent/Assets/Roboto-Thin.ttf
new file mode 100644
index 0000000000..04b15402d9
Binary files /dev/null and b/src/Avalonia.Themes.Fluent/Assets/Roboto-Thin.ttf differ
diff --git a/src/Avalonia.Themes.Fluent/AutoCompleteBox.xaml b/src/Avalonia.Themes.Fluent/AutoCompleteBox.xaml
index 44e7962e17..0d5d733cd9 100644
--- a/src/Avalonia.Themes.Fluent/AutoCompleteBox.xaml
+++ b/src/Avalonia.Themes.Fluent/AutoCompleteBox.xaml
@@ -22,8 +22,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/Avalonia.Themes.Fluent.csproj b/src/Avalonia.Themes.Fluent/Avalonia.Themes.Fluent.csproj
index 84bf799d8d..c2a1359e8a 100644
--- a/src/Avalonia.Themes.Fluent/Avalonia.Themes.Fluent.csproj
+++ b/src/Avalonia.Themes.Fluent/Avalonia.Themes.Fluent.csproj
@@ -11,13 +11,10 @@
-
-
-
-
-
-
+
+
+
-
\ No newline at end of file
+
diff --git a/src/Avalonia.Themes.Fluent/Button.xaml b/src/Avalonia.Themes.Fluent/Button.xaml
index 345a74512c..34bcd0f0c1 100644
--- a/src/Avalonia.Themes.Fluent/Button.xaml
+++ b/src/Avalonia.Themes.Fluent/Button.xaml
@@ -19,8 +19,7 @@
-
-
+
+
+
+
-
+
-
+
-
+
-
-
-
+
-
+
-
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/ComboBoxItem.xaml b/src/Avalonia.Themes.Fluent/ComboBoxItem.xaml
index c26dec3d34..66ccea99b5 100644
--- a/src/Avalonia.Themes.Fluent/ComboBoxItem.xaml
+++ b/src/Avalonia.Themes.Fluent/ComboBoxItem.xaml
@@ -1,17 +1,19 @@
-
-
+
+
Item 1
- Item 2
-
-
-
- Item 1
- Item 2
-
-
+ Item 2 long
+ Item 3
+ Item 4
+
+
@@ -19,12 +21,11 @@
-
-
+ Padding="{TemplateBinding Padding}" />
+
+
+
+
+
+
+
+
-
+
-
diff --git a/src/Avalonia.Themes.Fluent/ContextMenu.xaml b/src/Avalonia.Themes.Fluent/ContextMenu.xaml
index 44783a8dea..a6b6156944 100644
--- a/src/Avalonia.Themes.Fluent/ContextMenu.xaml
+++ b/src/Avalonia.Themes.Fluent/ContextMenu.xaml
@@ -1,7 +1,7 @@
-
-
diff --git a/src/Avalonia.Themes.Fluent/NotificationCard.xaml b/src/Avalonia.Themes.Fluent/NotificationCard.xaml
index 47d5988e8c..5a0fa32657 100644
--- a/src/Avalonia.Themes.Fluent/NotificationCard.xaml
+++ b/src/Avalonia.Themes.Fluent/NotificationCard.xaml
@@ -1,92 +1,104 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
-
-
-
-
-
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/NumericUpDown.xaml b/src/Avalonia.Themes.Fluent/NumericUpDown.xaml
index 08de50c6e3..d1610b343c 100644
--- a/src/Avalonia.Themes.Fluent/NumericUpDown.xaml
+++ b/src/Avalonia.Themes.Fluent/NumericUpDown.xaml
@@ -25,8 +25,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/OverlayPopupHost.xaml b/src/Avalonia.Themes.Fluent/OverlayPopupHost.xaml
index 36dbc1b761..3809e11251 100644
--- a/src/Avalonia.Themes.Fluent/OverlayPopupHost.xaml
+++ b/src/Avalonia.Themes.Fluent/OverlayPopupHost.xaml
@@ -1,5 +1,5 @@
diff --git a/src/Avalonia.Themes.Fluent/RadioButton.xaml b/src/Avalonia.Themes.Fluent/RadioButton.xaml
index 23bcfc616a..acde4ea0be 100644
--- a/src/Avalonia.Themes.Fluent/RadioButton.xaml
+++ b/src/Avalonia.Themes.Fluent/RadioButton.xaml
@@ -17,8 +17,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/RepeatButton.xaml b/src/Avalonia.Themes.Fluent/RepeatButton.xaml
index 12ba38d614..5afaf05e9f 100644
--- a/src/Avalonia.Themes.Fluent/RepeatButton.xaml
+++ b/src/Avalonia.Themes.Fluent/RepeatButton.xaml
@@ -17,8 +17,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/TabControl.xaml b/src/Avalonia.Themes.Fluent/TabControl.xaml
index 3cfdf60ae0..c38ecb0452 100644
--- a/src/Avalonia.Themes.Fluent/TabControl.xaml
+++ b/src/Avalonia.Themes.Fluent/TabControl.xaml
@@ -19,10 +19,14 @@
+
+ 0 0 0 2
+
+
diff --git a/src/Avalonia.Themes.Fluent/TabItem.xaml b/src/Avalonia.Themes.Fluent/TabItem.xaml
index 694e86a184..2b0a0c1ea0 100644
--- a/src/Avalonia.Themes.Fluent/TabItem.xaml
+++ b/src/Avalonia.Themes.Fluent/TabItem.xaml
@@ -15,11 +15,11 @@
diff --git a/src/Avalonia.Themes.Fluent/TabStripItem.xaml b/src/Avalonia.Themes.Fluent/TabStripItem.xaml
index d45f705a40..628ab8dddd 100644
--- a/src/Avalonia.Themes.Fluent/TabStripItem.xaml
+++ b/src/Avalonia.Themes.Fluent/TabStripItem.xaml
@@ -14,11 +14,11 @@
diff --git a/src/Avalonia.Themes.Fluent/TextBox.xaml b/src/Avalonia.Themes.Fluent/TextBox.xaml
index 49fc4b59b0..c1b60d061c 100644
--- a/src/Avalonia.Themes.Fluent/TextBox.xaml
+++ b/src/Avalonia.Themes.Fluent/TextBox.xaml
@@ -8,8 +8,7 @@
-
-
+
@@ -50,7 +49,7 @@
Margin="{TemplateBinding BorderThickness}">
@@ -103,7 +102,6 @@
diff --git a/src/Avalonia.Themes.Fluent/TimePicker.xaml b/src/Avalonia.Themes.Fluent/TimePicker.xaml
index 4a411796d8..f82e194a73 100644
--- a/src/Avalonia.Themes.Fluent/TimePicker.xaml
+++ b/src/Avalonia.Themes.Fluent/TimePicker.xaml
@@ -31,8 +31,7 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Avalonia.Themes.Fluent/ToggleButton.xaml b/src/Avalonia.Themes.Fluent/ToggleButton.xaml
index a3c300f6f5..f2f07d3e2a 100644
--- a/src/Avalonia.Themes.Fluent/ToggleButton.xaml
+++ b/src/Avalonia.Themes.Fluent/ToggleButton.xaml
@@ -20,8 +20,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/ToggleSwitch.xaml b/src/Avalonia.Themes.Fluent/ToggleSwitch.xaml
index 88266ac979..e7f8fb1641 100644
--- a/src/Avalonia.Themes.Fluent/ToggleSwitch.xaml
+++ b/src/Avalonia.Themes.Fluent/ToggleSwitch.xaml
@@ -43,8 +43,7 @@
-
-
+
@@ -156,8 +155,7 @@
-
-
-
@@ -264,10 +258,6 @@
-
-
diff --git a/src/Avalonia.Themes.Fluent/ToolTip.xaml b/src/Avalonia.Themes.Fluent/ToolTip.xaml
index 47ad494bbf..f7a1ebbc6b 100644
--- a/src/Avalonia.Themes.Fluent/ToolTip.xaml
+++ b/src/Avalonia.Themes.Fluent/ToolTip.xaml
@@ -45,8 +45,7 @@
-
-
+
diff --git a/src/Avalonia.Themes.Fluent/Window.xaml b/src/Avalonia.Themes.Fluent/Window.xaml
index aee15347eb..794f516f71 100644
--- a/src/Avalonia.Themes.Fluent/Window.xaml
+++ b/src/Avalonia.Themes.Fluent/Window.xaml
@@ -1,7 +1,9 @@
+
-
+
-
+
-
+
-
+
diff --git a/src/Avalonia.Visuals/Media/AcrylicBackgroundSource.cs b/src/Avalonia.Visuals/Media/AcrylicBackgroundSource.cs
new file mode 100644
index 0000000000..34cede4018
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/AcrylicBackgroundSource.cs
@@ -0,0 +1,20 @@
+namespace Avalonia.Media
+{
+ ///
+ /// Background Sources for Acrylic.
+ ///
+ public enum AcrylicBackgroundSource
+ {
+ ///
+ /// The acrylic has no background.
+ ///
+ None,
+
+ ///
+ /// Cuts through all render layers to reveal the window background.
+ /// This means if your window is transparent or blurred it
+ /// will be blended with the material.
+ ///
+ Digger
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/ExperimentalAcrylicMaterial.cs b/src/Avalonia.Visuals/Media/ExperimentalAcrylicMaterial.cs
new file mode 100644
index 0000000000..6b699acd2e
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/ExperimentalAcrylicMaterial.cs
@@ -0,0 +1,345 @@
+using System;
+
+namespace Avalonia.Media
+{
+ public class ExperimentalAcrylicMaterial : AvaloniaObject, IMutableExperimentalAcrylicMaterial
+ {
+ private Color _effectiveTintColor;
+ private Color _effectiveLuminosityColor;
+
+ static ExperimentalAcrylicMaterial()
+ {
+ AffectsRender(
+ TintColorProperty,
+ BackgroundSourceProperty,
+ TintOpacityProperty,
+ MaterialOpacityProperty,
+ PlatformTransparencyCompensationLevelProperty);
+
+ TintColorProperty.Changed.AddClassHandler((b, e) =>
+ {
+ b._effectiveTintColor = GetEffectiveTintColor(b.TintColor, b.TintOpacity);
+ b._effectiveLuminosityColor = b.GetEffectiveLuminosityColor();
+ });
+
+ TintOpacityProperty.Changed.AddClassHandler((b, e) =>
+ {
+ b._effectiveTintColor = GetEffectiveTintColor(b.TintColor, b.TintOpacity);
+ b._effectiveLuminosityColor = b.GetEffectiveLuminosityColor();
+ });
+
+ MaterialOpacityProperty.Changed.AddClassHandler((b, e) =>
+ {
+ b._effectiveTintColor = GetEffectiveTintColor(b.TintColor, b.TintOpacity);
+ b._effectiveLuminosityColor = b.GetEffectiveLuminosityColor();
+ });
+
+ PlatformTransparencyCompensationLevelProperty.Changed.AddClassHandler((b, e) =>
+ {
+ b._effectiveTintColor = GetEffectiveTintColor(b.TintColor, b.TintOpacity);
+ b._effectiveLuminosityColor = b.GetEffectiveLuminosityColor();
+ });
+ }
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty TintColorProperty =
+ AvaloniaProperty.Register(nameof(TintColor));
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty BackgroundSourceProperty =
+ AvaloniaProperty.Register(nameof(BackgroundSource));
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty TintOpacityProperty =
+ AvaloniaProperty.Register(nameof(TintOpacity), 0.8);
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty MaterialOpacityProperty =
+ AvaloniaProperty.Register(nameof(MaterialOpacity), 0.5);
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty PlatformTransparencyCompensationLevelProperty =
+ AvaloniaProperty.Register(nameof(PlatformTransparencyCompensationLevel), 0.0);
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty FallbackColorProperty =
+ AvaloniaProperty.Register(nameof(FallbackColor));
+
+ ///
+ public event EventHandler Invalidated;
+
+ ///
+ /// Gets or Sets the BackgroundSource .
+ ///
+ public AcrylicBackgroundSource BackgroundSource
+ {
+ get => GetValue(BackgroundSourceProperty);
+ set => SetValue(BackgroundSourceProperty, value);
+ }
+
+ ///
+ /// Gets or Sets the TintColor.
+ ///
+ public Color TintColor
+ {
+ get => GetValue(TintColorProperty);
+ set => SetValue(TintColorProperty, value);
+ }
+
+ ///
+ /// Gets or Sets the Tint Opacity.
+ ///
+ public double TintOpacity
+ {
+ get => GetValue(TintOpacityProperty);
+ set => SetValue(TintOpacityProperty, value);
+ }
+
+ ///
+ /// Gets or Sets the Fallback Color.
+ /// This is used on rendering plaforms that dont support acrylic.
+ ///
+ public Color FallbackColor
+ {
+ get => GetValue(FallbackColorProperty);
+ set => SetValue(FallbackColorProperty, value);
+ }
+
+ ///
+ /// Gets or Sets the MaterialOpacity.
+ /// This makes the material more or less opaque.
+ ///
+ public double MaterialOpacity
+ {
+ get => GetValue(MaterialOpacityProperty);
+ set => SetValue(MaterialOpacityProperty, value);
+ }
+
+ ///
+ /// Gets or Sets the PlatformTransparencyCompensationLevel.
+ /// This value defines the minimum that can be used.
+ /// It means material opacity is re-scaled from this value to 1.
+ ///
+ public double PlatformTransparencyCompensationLevel
+ {
+ get => GetValue(PlatformTransparencyCompensationLevelProperty);
+ set => SetValue(PlatformTransparencyCompensationLevelProperty, value);
+ }
+
+ Color IExperimentalAcrylicMaterial.MaterialColor => _effectiveLuminosityColor;
+
+ Color IExperimentalAcrylicMaterial.TintColor => _effectiveTintColor;
+
+ private struct HsvColor
+ {
+ public float Hue { get; set; }
+ public float Saturation { get; set; }
+ public float Value { get; set; }
+ }
+
+ private static HsvColor RgbToHsv(Color color)
+ {
+ var r = color.R / 255.0f;
+ var g = color.G / 255.0f;
+ var b = color.B / 255.0f;
+ var max = Math.Max(r, Math.Max(g, b));
+ var min = Math.Min(r, Math.Min(g, b));
+
+ float h, s, v;
+ h = v = max;
+
+ var d = max - min;
+ s = max == 0 ? 0 : d / max;
+
+ if (max == min)
+ {
+ h = 0; // achromatic
+ }
+ else
+ {
+ if (max == r)
+ {
+ h = (g - b) / d + (g < b ? 6 : 0);
+ }
+ else if (max == g)
+ {
+ h = (b - r) / d + 2;
+ }
+ else if (max == b)
+ {
+ h = (r - g) / d + 4;
+ }
+
+ h /= 6;
+ }
+
+ return new HsvColor { Hue = h, Saturation = s, Value = v };
+ }
+
+ private static Color GetEffectiveTintColor(Color tintColor, double tintOpacity)
+ {
+ // Update tintColor's alpha with the combined opacity value
+ double tintOpacityModifier = GetTintOpacityModifier(tintColor);
+
+ return new Color((byte)(255 * ((255.0 / tintColor.A) * tintOpacity) * tintOpacityModifier), tintColor.R, tintColor.G, tintColor.B);
+ }
+
+ private static double GetTintOpacityModifier(Color tintColor)
+ {
+ // This method supresses the maximum allowable tint opacity depending on the luminosity and saturation of a color by
+ // compressing the range of allowable values - for example, a user-defined value of 100% will be mapped to 45% for pure
+ // white (100% luminosity), 85% for pure black (0% luminosity), and 90% for pure gray (50% luminosity). The intensity of
+ // the effect increases linearly as luminosity deviates from 50%. After this effect is calculated, we cancel it out
+ // linearly as saturation increases from zero.
+
+ const double midPoint = 0.5; // Mid point of HsvV range that these calculations are based on. This is here for easy tuning.
+
+ const double whiteMaxOpacity = 0.2; // 100% luminosity
+ const double midPointMaxOpacity = 0.45; // 50% luminosity
+ const double blackMaxOpacity = 0.45; // 0% luminosity
+
+ var hsv = RgbToHsv(tintColor);
+
+ double opacityModifier = midPointMaxOpacity;
+
+ if (hsv.Value != midPoint)
+ {
+ // Determine maximum suppression amount
+ double lowestMaxOpacity = midPointMaxOpacity;
+ double maxDeviation = midPoint;
+
+ if (hsv.Value > midPoint)
+ {
+ lowestMaxOpacity = whiteMaxOpacity; // At white (100% hsvV)
+ maxDeviation = 1 - maxDeviation;
+ }
+ else if (hsv.Value < midPoint)
+ {
+ lowestMaxOpacity = blackMaxOpacity; // At black (0% hsvV)
+ }
+
+ double maxOpacitySuppression = midPointMaxOpacity - lowestMaxOpacity;
+
+ // Determine normalized deviation from the midpoint
+ double deviation = Math.Abs(hsv.Value - midPoint);
+ double normalizedDeviation = deviation / maxDeviation;
+
+ // If we have saturation, reduce opacity suppression to allow that color to come through more
+ if (hsv.Saturation > 0)
+ {
+ // Dampen opacity suppression based on how much saturation there is
+ maxOpacitySuppression *= Math.Max(1 - (hsv.Saturation * 2), 0.0);
+ }
+
+ double opacitySuppression = maxOpacitySuppression * normalizedDeviation;
+
+ opacityModifier = midPointMaxOpacity - opacitySuppression;
+ }
+
+ return opacityModifier;
+ }
+
+ private Color GetEffectiveLuminosityColor()
+ {
+ double? luminosityOpacity = MaterialOpacity;
+
+ return GetLuminosityColor(luminosityOpacity);
+ }
+
+ private static byte Trim(double value)
+ {
+ value = Math.Min(Math.Floor(value * 256), 255);
+
+ if (value < 0)
+ {
+ return 0;
+ }
+ else if (value > 255)
+ {
+ return 255;
+ }
+
+ return (byte)value;
+ }
+
+ private static float RGBMax(Color color)
+ {
+ if (color.R > color.G)
+ return (color.R > color.B) ? color.R : color.B;
+ else
+ return (color.G > color.B) ? color.G : color.B;
+ }
+
+ private static float RGBMin(Color color)
+ {
+ if (color.R < color.G)
+ return (color.R < color.B) ? color.R : color.B;
+ else
+ return (color.G < color.B) ? color.G : color.B;
+ }
+
+ // The tintColor passed into this method should be the original, unmodified color created using user values for TintColor + TintOpacity
+ private Color GetLuminosityColor(double? luminosityOpacity)
+ {
+ // Calculate the HSL lightness value of the color.
+ var max = (float)RGBMax(TintColor) / 255.0f;
+ var min = (float)RGBMin(TintColor) / 255.0f;
+
+ var lightness = (max + min) / 2.0;
+
+ lightness = 1 - ((1 - lightness) * luminosityOpacity.Value);
+
+ lightness = 0.13 + (lightness * 0.74);
+
+ var luminosityColor = new Color(255, Trim(lightness), Trim(lightness), Trim(lightness));
+
+ var compensationMultiplier = 1 - PlatformTransparencyCompensationLevel;
+ return new Color((byte)(255 * Math.Max(Math.Min(PlatformTransparencyCompensationLevel + (luminosityOpacity.Value * compensationMultiplier), 1.0), 0.0)), luminosityColor.R, luminosityColor.G, luminosityColor.B);
+ }
+
+ ///
+ /// Marks a property as affecting the brush's visual representation.
+ ///
+ /// The properties.
+ ///
+ /// After a call to this method in a brush's static constructor, any change to the
+ /// property will cause the event to be raised on the brush.
+ ///
+ protected static void AffectsRender(params AvaloniaProperty[] properties)
+ where T : ExperimentalAcrylicMaterial
+ {
+ static void Invalidate(AvaloniaPropertyChangedEventArgs e)
+ {
+ (e.Sender as T)?.RaiseInvalidated(EventArgs.Empty);
+ }
+
+ foreach (var property in properties)
+ {
+ property.Changed.Subscribe(e => Invalidate(e));
+ }
+ }
+
+ ///
+ /// Raises the event.
+ ///
+ /// The event args.
+ protected void RaiseInvalidated(EventArgs e) => Invalidated?.Invoke(this, e);
+
+ public IExperimentalAcrylicMaterial ToImmutable()
+ {
+ return new ImmutableExperimentalAcrylicMaterial(this);
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/FontManager.cs b/src/Avalonia.Visuals/Media/FontManager.cs
index f9410afe6a..ad3fee7eb7 100644
--- a/src/Avalonia.Visuals/Media/FontManager.cs
+++ b/src/Avalonia.Visuals/Media/FontManager.cs
@@ -79,12 +79,13 @@ namespace Avalonia.Media
/// Returns a new typeface, or an existing one if a matching typeface exists.
///
/// The font family.
- /// The font weight.
/// The font style.
+ /// The font weight.
///
/// The typeface.
///
- public Typeface GetOrAddTypeface(FontFamily fontFamily, FontWeight fontWeight = FontWeight.Normal, FontStyle fontStyle = FontStyle.Normal)
+ public Typeface GetOrAddTypeface(FontFamily fontFamily, FontStyle fontStyle = FontStyle.Normal,
+ FontWeight fontWeight = FontWeight.Normal)
{
while (true)
{
@@ -93,14 +94,14 @@ namespace Avalonia.Media
fontFamily = _defaultFontFamily;
}
- var key = new FontKey(fontFamily.Name, fontWeight, fontStyle);
+ var key = new FontKey(fontFamily.Name, fontStyle, fontWeight);
if (_typefaceCache.TryGetValue(key, out var typeface))
{
return typeface;
}
- typeface = new Typeface(fontFamily, fontWeight, fontStyle);
+ typeface = new Typeface(fontFamily, fontStyle, fontWeight);
if (_typefaceCache.TryAdd(key, typeface))
{
@@ -121,15 +122,16 @@ namespace Avalonia.Media
/// Returns null if no fallback was found.
///
/// The codepoint to match against.
- /// The font weight.
/// The font style.
+ /// The font weight.
/// The font family. This is optional and used for fallback lookup.
/// The culture.
///
/// The matched typeface.
///
- public Typeface MatchCharacter(int codepoint, FontWeight fontWeight = FontWeight.Normal,
+ public Typeface MatchCharacter(int codepoint,
FontStyle fontStyle = FontStyle.Normal,
+ FontWeight fontWeight = FontWeight.Normal,
FontFamily fontFamily = null, CultureInfo culture = null)
{
foreach (var cachedTypeface in _typefaceCache.Values)
@@ -142,8 +144,8 @@ namespace Avalonia.Media
}
}
- var matchedTypeface = PlatformImpl.TryMatchCharacter(codepoint, fontWeight, fontStyle, fontFamily, culture, out var key) ?
- _typefaceCache.GetOrAdd(key, new Typeface(key.FamilyName, key.Weight, key.Style)) :
+ var matchedTypeface = PlatformImpl.TryMatchCharacter(codepoint, fontStyle, fontWeight, fontFamily, culture, out var key) ?
+ _typefaceCache.GetOrAdd(key, new Typeface(key.FamilyName, key.Style, key.Weight)) :
null;
return matchedTypeface;
diff --git a/src/Avalonia.Visuals/Media/Fonts/FontKey.cs b/src/Avalonia.Visuals/Media/Fonts/FontKey.cs
index a8d81648ba..b330db8462 100644
--- a/src/Avalonia.Visuals/Media/Fonts/FontKey.cs
+++ b/src/Avalonia.Visuals/Media/Fonts/FontKey.cs
@@ -4,7 +4,7 @@ namespace Avalonia.Media.Fonts
{
public readonly struct FontKey : IEquatable
{
- public FontKey(string familyName, FontWeight weight, FontStyle style)
+ public FontKey(string familyName, FontStyle style, FontWeight weight)
{
FamilyName = familyName;
Style = style;
diff --git a/src/Avalonia.Visuals/Media/GlyphRun.cs b/src/Avalonia.Visuals/Media/GlyphRun.cs
index 29c9d93560..a32a3e1b6c 100644
--- a/src/Avalonia.Visuals/Media/GlyphRun.cs
+++ b/src/Avalonia.Visuals/Media/GlyphRun.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using Avalonia.Platform;
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media
{
@@ -205,13 +205,16 @@ namespace Avalonia.Media
var glyphIndex = FindGlyphIndex(characterHit.FirstCharacterIndex);
- var currentCluster = _glyphClusters[glyphIndex];
-
- if (characterHit.TrailingLength > 0)
+ if (!GlyphClusters.IsEmpty)
{
- while (glyphIndex < _glyphClusters.Length && _glyphClusters[glyphIndex] == currentCluster)
+ var currentCluster = GlyphClusters[glyphIndex];
+
+ if (characterHit.TrailingLength > 0)
{
- glyphIndex++;
+ while (glyphIndex < GlyphClusters.Length && GlyphClusters[glyphIndex] == currentCluster)
+ {
+ glyphIndex++;
+ }
}
}
@@ -302,7 +305,7 @@ namespace Avalonia.Media
}
}
- var characterHit = FindNearestCharacterHit(GlyphClusters[index], out var width);
+ var characterHit = FindNearestCharacterHit(GlyphClusters.IsEmpty ? index : GlyphClusters[index], out var width);
var offset = GetDistanceFromCharacterHit(new CharacterHit(characterHit.FirstCharacterIndex));
@@ -370,26 +373,31 @@ namespace Avalonia.Media
///
public int FindGlyphIndex(int characterIndex)
{
+ if (GlyphClusters.IsEmpty)
+ {
+ return characterIndex;
+ }
+
if (IsLeftToRight)
{
- if (characterIndex < _glyphClusters[0])
+ if (characterIndex < GlyphClusters[0])
{
return 0;
}
- if (characterIndex > _glyphClusters[_glyphClusters.Length - 1])
+ if (characterIndex > GlyphClusters[GlyphClusters.Length - 1])
{
return _glyphClusters.End;
}
}
else
{
- if (characterIndex < _glyphClusters[_glyphClusters.Length - 1])
+ if (characterIndex < GlyphClusters[GlyphClusters.Length - 1])
{
return _glyphClusters.End;
}
- if (characterIndex > _glyphClusters[0])
+ if (characterIndex > GlyphClusters[0])
{
return 0;
}
@@ -397,7 +405,7 @@ namespace Avalonia.Media
var comparer = IsLeftToRight ? s_ascendingComparer : s_descendingComparer;
- var clusters = _glyphClusters.Buffer.Span;
+ var clusters = GlyphClusters.Buffer.Span;
// Find the start of the cluster at the character index.
var start = clusters.BinarySearch((ushort)characterIndex, comparer);
@@ -418,9 +426,19 @@ namespace Avalonia.Media
}
}
- while (start > 0 && clusters[start - 1] == clusters[start])
+ if (IsLeftToRight)
{
- start--;
+ while (start > 0 && clusters[start - 1] == clusters[start])
+ {
+ start--;
+ }
+ }
+ else
+ {
+ while (start + 1 < clusters.Length && clusters[start + 1] == clusters[start])
+ {
+ start++;
+ }
}
return start;
@@ -440,34 +458,74 @@ namespace Avalonia.Media
var start = FindGlyphIndex(index);
- var currentCluster = _glyphClusters[start];
+ if (GlyphClusters.IsEmpty)
+ {
+ width = GetGlyphWidth(index);
+
+ return new CharacterHit(start, 1);
+ }
- var trailingLength = 0;
+ var cluster = GlyphClusters[start];
- while (start < _glyphClusters.Length && _glyphClusters[start] == currentCluster)
+ var nextCluster = cluster;
+
+ var currentIndex = start;
+
+ while (nextCluster == cluster)
{
- if (GlyphAdvances.IsEmpty)
+ width += GetGlyphWidth(currentIndex);
+
+ if (IsLeftToRight)
{
- var glyph = GlyphIndices[start];
+ currentIndex++;
- width += GlyphTypeface.GetGlyphAdvance(glyph) * Scale;
+ if (currentIndex == GlyphClusters.Length)
+ {
+ break;
+ }
}
else
{
- width += GlyphAdvances[start];
+ currentIndex--;
+
+ if (currentIndex < 0)
+ {
+ break;
+ }
}
- trailingLength++;
- start++;
+ nextCluster = GlyphClusters[currentIndex];
+ }
+
+ int trailingLength;
+
+ if (nextCluster == cluster)
+ {
+ trailingLength = Characters.Start + Characters.Length - cluster;
+ }
+ else
+ {
+ trailingLength = nextCluster - cluster;
}
- if (start == _glyphClusters.Length &&
- currentCluster + trailingLength != Characters.Start + Characters.Length)
+ return new CharacterHit(cluster, trailingLength);
+ }
+
+ ///
+ /// Gets a glyph's width.
+ ///
+ /// The glyph index.
+ /// The glyph's width.
+ private double GetGlyphWidth(int index)
+ {
+ if (GlyphAdvances.IsEmpty)
{
- trailingLength = Characters.Start + Characters.Length - currentCluster;
+ var glyph = GlyphIndices[index];
+
+ return GlyphTypeface.GetGlyphAdvance(glyph) * Scale;
}
- return new CharacterHit(currentCluster, trailingLength);
+ return GlyphAdvances[index];
}
///
diff --git a/src/Avalonia.Visuals/Media/IBrush.cs b/src/Avalonia.Visuals/Media/IBrush.cs
index 7756e94598..15b7681be4 100644
--- a/src/Avalonia.Visuals/Media/IBrush.cs
+++ b/src/Avalonia.Visuals/Media/IBrush.cs
@@ -13,4 +13,4 @@ namespace Avalonia.Media
///
double Opacity { get; }
}
-}
\ No newline at end of file
+}
diff --git a/src/Avalonia.Visuals/Media/IExperimentalAcrylicMaterial.cs b/src/Avalonia.Visuals/Media/IExperimentalAcrylicMaterial.cs
new file mode 100644
index 0000000000..e71584258a
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/IExperimentalAcrylicMaterial.cs
@@ -0,0 +1,33 @@
+namespace Avalonia.Media
+{
+ ///
+ /// Experimental Interface for producing Acrylic-like materials.
+ ///
+ public interface IExperimentalAcrylicMaterial
+ {
+ ///
+ /// Gets the of the material.
+ ///
+ AcrylicBackgroundSource BackgroundSource { get; }
+
+ ///
+ /// Gets the TintColor of the material.
+ ///
+ Color TintColor { get; }
+
+ ///
+ /// Gets the TintOpacity of the material.
+ ///
+ double TintOpacity { get; }
+
+ ///
+ /// Gets the effective material color.
+ ///
+ Color MaterialColor { get; }
+
+ ///
+ /// Gets the fallback color.
+ ///
+ Color FallbackColor { get; }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/IMutableExperimentalAcrylicMaterial.cs b/src/Avalonia.Visuals/Media/IMutableExperimentalAcrylicMaterial.cs
new file mode 100644
index 0000000000..fcfe4631a6
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/IMutableExperimentalAcrylicMaterial.cs
@@ -0,0 +1,14 @@
+namespace Avalonia.Media
+{
+ ///
+ /// Represents a mutable brush which can return an immutable clone of itself.
+ ///
+ public interface IMutableExperimentalAcrylicMaterial : IExperimentalAcrylicMaterial, IAffectsRender
+ {
+ ///
+ /// Creates an immutable clone of the brush.
+ ///
+ /// The immutable clone.
+ IExperimentalAcrylicMaterial ToImmutable();
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/ImmutableExperimentalAcrylicMaterial.cs b/src/Avalonia.Visuals/Media/ImmutableExperimentalAcrylicMaterial.cs
new file mode 100644
index 0000000000..f46d76cf3f
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/ImmutableExperimentalAcrylicMaterial.cs
@@ -0,0 +1,73 @@
+using System;
+
+namespace Avalonia.Media
+{
+ public readonly struct ImmutableExperimentalAcrylicMaterial : IExperimentalAcrylicMaterial, IEquatable
+ {
+ public ImmutableExperimentalAcrylicMaterial(IExperimentalAcrylicMaterial brush)
+ {
+ BackgroundSource = brush.BackgroundSource;
+ TintColor = brush.TintColor;
+ TintOpacity = brush.TintOpacity;
+ FallbackColor = brush.FallbackColor;
+ MaterialColor = brush.MaterialColor;
+ }
+
+ public AcrylicBackgroundSource BackgroundSource { get; }
+
+ public Color TintColor { get; }
+
+ public Color MaterialColor { get; }
+
+ public double TintOpacity { get; }
+
+ public Color FallbackColor { get; }
+
+ public bool Equals(ImmutableExperimentalAcrylicMaterial other)
+ {
+ // ReSharper disable once CompareOfFloatsByEqualityOperator
+ return
+ TintColor == other.TintColor &&
+ TintOpacity == other.TintOpacity &&
+ BackgroundSource == other.BackgroundSource &&
+ FallbackColor == other.FallbackColor && MaterialColor == other.MaterialColor;
+
+ }
+
+ public override bool Equals(object obj)
+ {
+ return obj is ImmutableExperimentalAcrylicMaterial other && Equals(other);
+ }
+
+ public Color GetEffectiveTintColor()
+ {
+ return TintColor;
+ }
+
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ int hash = 17;
+
+ hash = (hash * 23) + TintColor.GetHashCode();
+ hash = (hash * 23) + TintOpacity.GetHashCode();
+ hash = (hash * 23) + BackgroundSource.GetHashCode();
+ hash = (hash * 23) + FallbackColor.GetHashCode();
+ hash = (hash * 23) + MaterialColor.GetHashCode();
+
+ return hash;
+ }
+ }
+
+ public static bool operator ==(ImmutableExperimentalAcrylicMaterial left, ImmutableExperimentalAcrylicMaterial right)
+ {
+ return left.Equals(right);
+ }
+
+ public static bool operator !=(ImmutableExperimentalAcrylicMaterial left, ImmutableExperimentalAcrylicMaterial right)
+ {
+ return !left.Equals(right);
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/MaterialExtensions.cs b/src/Avalonia.Visuals/Media/MaterialExtensions.cs
new file mode 100644
index 0000000000..c0b445c357
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/MaterialExtensions.cs
@@ -0,0 +1,22 @@
+using System;
+
+namespace Avalonia.Media
+{
+ public static class MaterialExtensions
+ {
+ ///
+ /// Converts a brush to an immutable brush.
+ ///
+ /// The brush.
+ ///
+ /// The result of calling if the brush is mutable,
+ /// otherwise .
+ ///
+ public static IExperimentalAcrylicMaterial ToImmutable(this IExperimentalAcrylicMaterial material)
+ {
+ Contract.Requires(material != null);
+
+ return (material as IMutableExperimentalAcrylicMaterial)?.ToImmutable() ?? material;
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextDecoration.cs b/src/Avalonia.Visuals/Media/TextDecoration.cs
index a83555946b..681fc5d499 100644
--- a/src/Avalonia.Visuals/Media/TextDecoration.cs
+++ b/src/Avalonia.Visuals/Media/TextDecoration.cs
@@ -1,4 +1,5 @@
-using Avalonia.Media.Immutable;
+using Avalonia.Collections;
+using Avalonia.Media.TextFormatting;
namespace Avalonia.Media
{
@@ -14,28 +15,52 @@ namespace Avalonia.Media
AvaloniaProperty.Register(nameof(Location));
///
- /// Defines the property.
+ /// Defines the property.
///
- public static readonly StyledProperty PenProperty =
- AvaloniaProperty.Register(nameof(Pen));
+ public static readonly StyledProperty StrokeProperty =
+ AvaloniaProperty.Register(nameof(Stroke));
///
- /// Defines the property.
+ /// Defines the property.
///
- public static readonly StyledProperty PenThicknessUnitProperty =
- AvaloniaProperty.Register(nameof(PenThicknessUnit));
+ public static readonly StyledProperty StrokeThicknessUnitProperty =
+ AvaloniaProperty.Register(nameof(StrokeThicknessUnit));
///
- /// Defines the property.
+ /// Defines the property.
///
- public static readonly StyledProperty PenOffsetProperty =
- AvaloniaProperty.Register(nameof(PenOffset));
+ public static readonly StyledProperty> StrokeDashArrayProperty =
+ AvaloniaProperty.Register>(nameof(StrokeDashArray));
///
- /// Defines the property.
+ /// Defines the property.
///
- public static readonly StyledProperty PenOffsetUnitProperty =
- AvaloniaProperty.Register(nameof(PenOffsetUnit));
+ public static readonly StyledProperty StrokeDashOffsetProperty =
+ AvaloniaProperty.Register(nameof(StrokeDashOffset));
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty StrokeThicknessProperty =
+ AvaloniaProperty.Register(nameof(StrokeThickness), 1);
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty StrokeLineCapProperty =
+ AvaloniaProperty.Register(nameof(StrokeLineCap));
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty StrokeOffsetProperty =
+ AvaloniaProperty.Register(nameof(StrokeOffset));
+
+ ///
+ /// Defines the property.
+ ///
+ public static readonly StyledProperty StrokeOffsetUnitProperty =
+ AvaloniaProperty.Register(nameof(StrokeOffsetUnit));
///
/// Gets or sets the location.
@@ -50,54 +75,139 @@ namespace Avalonia.Media
}
///
- /// Gets or sets the pen.
+ /// Gets or sets the that specifies how the is painted.
///
- ///
- /// The pen.
- ///
- public IPen Pen
+ public IBrush Stroke
+ {
+ get { return GetValue(StrokeProperty); }
+ set { SetValue(StrokeProperty, value); }
+ }
+
+ ///
+ /// Gets the units in which the thickness of the is expressed.
+ ///
+ public TextDecorationUnit StrokeThicknessUnit
+ {
+ get => GetValue(StrokeThicknessUnitProperty);
+ set => SetValue(StrokeThicknessUnitProperty, value);
+ }
+
+ ///
+ /// Gets or sets a collection of values that indicate the pattern of dashes and gaps
+ /// that is used to draw the .
+ ///
+ public AvaloniaList StrokeDashArray
+ {
+ get { return GetValue(StrokeDashArrayProperty); }
+ set { SetValue(StrokeDashArrayProperty, value); }
+ }
+
+ ///
+ /// Gets or sets a value that specifies the distance within the dash pattern where a dash begins.
+ ///
+ public double StrokeDashOffset
+ {
+ get { return GetValue(StrokeDashOffsetProperty); }
+ set { SetValue(StrokeDashOffsetProperty, value); }
+ }
+
+ ///
+ /// Gets or sets the thickness of the .
+ ///
+ public double StrokeThickness
{
- get => GetValue(PenProperty);
- set => SetValue(PenProperty, value);
+ get { return GetValue(StrokeThicknessProperty); }
+ set { SetValue(StrokeThicknessProperty, value); }
}
///
- /// Gets the units in which the Thickness of the text decoration's is expressed.
+ /// Gets or sets a enumeration value that describes the shape at the ends of a line.
///
- public TextDecorationUnit PenThicknessUnit
+ public PenLineCap StrokeLineCap
{
- get => GetValue(PenThicknessUnitProperty);
- set => SetValue(PenThicknessUnitProperty, value);
+ get { return GetValue(StrokeLineCapProperty); }
+ set { SetValue(StrokeLineCapProperty, value); }
}
///
- /// Gets or sets the pen offset.
+ /// The stroke's offset.
///
///
/// The pen offset.
///
- public double PenOffset
+ public double StrokeOffset
{
- get => GetValue(PenOffsetProperty);
- set => SetValue(PenOffsetProperty, value);
+ get => GetValue(StrokeOffsetProperty);
+ set => SetValue(StrokeOffsetProperty, value);
}
///
- /// Gets the units in which the value is expressed.
+ /// Gets the units in which the value is expressed.
///
- public TextDecorationUnit PenOffsetUnit
+ public TextDecorationUnit StrokeOffsetUnit
{
- get => GetValue(PenOffsetUnitProperty);
- set => SetValue(PenOffsetUnitProperty, value);
+ get => GetValue(StrokeOffsetUnitProperty);
+ set => SetValue(StrokeOffsetUnitProperty, value);
}
///
- /// Creates an immutable clone of the .
+ /// Draws the at given origin.
///
- /// The immutable clone.
- public ImmutableTextDecoration ToImmutable()
+ /// The drawing context.
+ /// The shaped characters that are decorated.
+ /// The origin.
+ internal void Draw(DrawingContext drawingContext, ShapedTextCharacters shapedTextCharacters, Point origin)
{
- return new ImmutableTextDecoration(Location, Pen?.ToImmutable(), PenThicknessUnit, PenOffset, PenOffsetUnit);
+ var fontRenderingEmSize = shapedTextCharacters.Properties.FontRenderingEmSize;
+ var fontMetrics = shapedTextCharacters.FontMetrics;
+ var thickness = StrokeThickness;
+
+ switch (StrokeThicknessUnit)
+ {
+ case TextDecorationUnit.FontRecommended:
+ switch (Location)
+ {
+ case TextDecorationLocation.Underline:
+ thickness = fontMetrics.UnderlineThickness;
+ break;
+ case TextDecorationLocation.Strikethrough:
+ thickness = fontMetrics.StrikethroughThickness;
+ break;
+ }
+
+ break;
+ case TextDecorationUnit.FontRenderingEmSize:
+ thickness = fontRenderingEmSize * thickness;
+ break;
+ }
+
+ switch (Location)
+ {
+ case TextDecorationLocation.Overline:
+ origin += new Point(0, fontMetrics.Ascent);
+ break;
+ case TextDecorationLocation.Strikethrough:
+ origin += new Point(0, -fontMetrics.StrikethroughPosition);
+ break;
+ case TextDecorationLocation.Underline:
+ origin += new Point(0, -fontMetrics.UnderlinePosition);
+ break;
+ }
+
+ switch (StrokeOffsetUnit)
+ {
+ case TextDecorationUnit.FontRenderingEmSize:
+ origin += new Point(0, StrokeOffset * fontRenderingEmSize);
+ break;
+ case TextDecorationUnit.Pixel:
+ origin += new Point(0, StrokeOffset);
+ break;
+ }
+
+ var pen = new Pen(Stroke ?? shapedTextCharacters.Properties.ForegroundBrush, thickness,
+ new DashStyle(StrokeDashArray, StrokeDashOffset), StrokeLineCap);
+
+ drawingContext.DrawLine(pen, origin, origin + new Point(shapedTextCharacters.Bounds.Width, 0));
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextDecorationCollection.cs b/src/Avalonia.Visuals/Media/TextDecorationCollection.cs
index 21e2e2484c..2dced2252e 100644
--- a/src/Avalonia.Visuals/Media/TextDecorationCollection.cs
+++ b/src/Avalonia.Visuals/Media/TextDecorationCollection.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using Avalonia.Collections;
-using Avalonia.Media.Immutable;
using Avalonia.Utilities;
namespace Avalonia.Media
@@ -11,22 +10,6 @@ namespace Avalonia.Media
///
public class TextDecorationCollection : AvaloniaList
{
- ///
- /// Creates an immutable clone of the .
- ///
- /// The immutable clone.
- public ImmutableTextDecoration[] ToImmutable()
- {
- var immutable = new ImmutableTextDecoration[Count];
-
- for (var i = 0; i < Count; i++)
- {
- immutable[i] = this[i].ToImmutable();
- }
-
- return immutable;
- }
-
///
/// Parses a string.
///
diff --git a/src/Avalonia.Visuals/Media/TextDecorationUnit.cs b/src/Avalonia.Visuals/Media/TextDecorationUnit.cs
index dde425bb94..a61983e8d5 100644
--- a/src/Avalonia.Visuals/Media/TextDecorationUnit.cs
+++ b/src/Avalonia.Visuals/Media/TextDecorationUnit.cs
@@ -1,7 +1,7 @@
namespace Avalonia.Media
{
///
- /// Specifies the unit type of either a or a thickness value.
+ /// Specifies the unit type of either a or a value.
///
public enum TextDecorationUnit
{
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/DrawableTextRun.cs b/src/Avalonia.Visuals/Media/TextFormatting/DrawableTextRun.cs
index 4903342cea..56790cc0db 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/DrawableTextRun.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/DrawableTextRun.cs
@@ -1,6 +1,4 @@
-using Avalonia.Platform;
-
-namespace Avalonia.Media.TextFormatting
+namespace Avalonia.Media.TextFormatting
{
///
/// A text run that supports drawing content.
@@ -17,6 +15,6 @@ namespace Avalonia.Media.TextFormatting
///
/// The drawing context.
/// The origin.
- public abstract void Draw(IDrawingContextImpl drawingContext, Point origin);
+ public abstract void Draw(DrawingContext drawingContext, Point origin);
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/GenericTextParagraphProperties.cs b/src/Avalonia.Visuals/Media/TextFormatting/GenericTextParagraphProperties.cs
new file mode 100644
index 0000000000..c4302aecec
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/GenericTextParagraphProperties.cs
@@ -0,0 +1,69 @@
+namespace Avalonia.Media.TextFormatting
+{
+ public class GenericTextParagraphProperties : TextParagraphProperties
+ {
+ private TextAlignment _textAlignment;
+ private TextWrapping _textWrapping;
+ private TextTrimming _textTrimming;
+ private double _lineHeight;
+
+ public GenericTextParagraphProperties(
+ TextRunProperties defaultTextRunProperties,
+ TextAlignment textAlignment = TextAlignment.Left,
+ TextWrapping textWrapping = TextWrapping.WrapWithOverflow,
+ TextTrimming textTrimming = TextTrimming.None,
+ double lineHeight = 0)
+ {
+ DefaultTextRunProperties = defaultTextRunProperties;
+
+ _textAlignment = textAlignment;
+
+ _textWrapping = textWrapping;
+
+ _textTrimming = textTrimming;
+
+ _lineHeight = lineHeight;
+ }
+
+ public override TextRunProperties DefaultTextRunProperties { get; }
+
+ public override TextAlignment TextAlignment => _textAlignment;
+
+ public override TextWrapping TextWrapping => _textWrapping;
+
+ public override TextTrimming TextTrimming => _textTrimming;
+
+ public override double LineHeight => _lineHeight;
+
+ ///
+ /// Set text alignment
+ ///
+ internal void SetTextAlignment(TextAlignment textAlignment)
+ {
+ _textAlignment = textAlignment;
+ }
+
+ ///
+ /// Set text wrap
+ ///
+ internal void SetTextWrapping(TextWrapping textWrapping)
+ {
+ _textWrapping = textWrapping;
+ }
+ ///
+ /// Set text trimming
+ ///
+ internal void SetTextTrimming(TextTrimming textTrimming)
+ {
+ _textTrimming = textTrimming;
+ }
+
+ ///
+ /// Set line height
+ ///
+ internal void SetLineHeight(double lineHeight)
+ {
+ _lineHeight = lineHeight;
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/GenericTextRunProperties.cs b/src/Avalonia.Visuals/Media/TextFormatting/GenericTextRunProperties.cs
new file mode 100644
index 0000000000..3db3589498
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/GenericTextRunProperties.cs
@@ -0,0 +1,40 @@
+using System.Globalization;
+
+namespace Avalonia.Media.TextFormatting
+{
+ ///
+ /// Generic implementation of TextRunProperties
+ ///
+ public class GenericTextRunProperties : TextRunProperties
+ {
+ public GenericTextRunProperties(Typeface typeface, double fontRenderingEmSize = 12,
+ TextDecorationCollection textDecorations = null, IBrush foregroundBrush = null, IBrush backgroundBrush = null,
+ CultureInfo cultureInfo = null)
+ {
+ Typeface = typeface;
+ FontRenderingEmSize = fontRenderingEmSize;
+ TextDecorations = textDecorations;
+ ForegroundBrush = foregroundBrush;
+ BackgroundBrush = backgroundBrush;
+ CultureInfo = cultureInfo;
+ }
+
+ ///
+ public override Typeface Typeface { get; }
+
+ ///
+ public override double FontRenderingEmSize { get; }
+
+ ///
+ public override TextDecorationCollection TextDecorations { get; }
+
+ ///
+ public override IBrush ForegroundBrush { get; }
+
+ ///
+ public override IBrush BackgroundBrush { get; }
+
+ ///
+ public override CultureInfo CultureInfo { get; }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/ShapeableTextCharacters.cs b/src/Avalonia.Visuals/Media/TextFormatting/ShapeableTextCharacters.cs
new file mode 100644
index 0000000000..0c6c722941
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/ShapeableTextCharacters.cs
@@ -0,0 +1,23 @@
+using Avalonia.Utilities;
+
+namespace Avalonia.Media.TextFormatting
+{
+ ///
+ /// A group of characters that can be shaped.
+ ///
+ public sealed class ShapeableTextCharacters : TextRun
+ {
+ public ShapeableTextCharacters(ReadOnlySlice text, TextRunProperties properties)
+ {
+ TextSourceLength = text.Length;
+ Text = text;
+ Properties = properties;
+ }
+
+ public override int TextSourceLength { get; }
+
+ public override ReadOnlySlice Text { get; }
+
+ public override TextRunProperties Properties { get; }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextCharacters.cs b/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextCharacters.cs
new file mode 100644
index 0000000000..b71fe5bc3c
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextCharacters.cs
@@ -0,0 +1,155 @@
+using Avalonia.Media.TextFormatting.Unicode;
+using Avalonia.Utilities;
+
+namespace Avalonia.Media.TextFormatting
+{
+ ///
+ /// A text run that holds shaped characters.
+ ///
+ public sealed class ShapedTextCharacters : DrawableTextRun
+ {
+ public ShapedTextCharacters(GlyphRun glyphRun, TextRunProperties properties)
+ {
+ Text = glyphRun.Characters;
+ Properties = properties;
+ TextSourceLength = Text.Length;
+ FontMetrics = new FontMetrics(Properties.Typeface, Properties.FontRenderingEmSize);
+ GlyphRun = glyphRun;
+ }
+
+ ///
+ public override ReadOnlySlice Text { get; }
+
+ ///
+ public override TextRunProperties Properties { get; }
+
+ ///
+ public override int TextSourceLength { get; }
+
+ ///
+ public override Rect Bounds => GlyphRun.Bounds;
+
+ ///
+ /// Gets the font metrics.
+ ///
+ ///
+ /// The font metrics.
+ ///
+ public FontMetrics FontMetrics { get; }
+
+ ///
+ /// Gets the glyph run.
+ ///
+ ///
+ /// The glyphs.
+ ///
+ public GlyphRun GlyphRun { get; }
+
+ ///
+ public override void Draw(DrawingContext drawingContext, Point origin)
+ {
+ if (GlyphRun.GlyphIndices.Length == 0)
+ {
+ return;
+ }
+
+ if (Properties.Typeface == null)
+ {
+ return;
+ }
+
+ if (Properties.ForegroundBrush == null)
+ {
+ return;
+ }
+
+ if (Properties.BackgroundBrush != null)
+ {
+ drawingContext.DrawRectangle(Properties.BackgroundBrush, null,
+ new Rect(origin.X, origin.Y + FontMetrics.Ascent, Bounds.Width, Bounds.Height));
+ }
+
+ drawingContext.DrawGlyphRun(Properties.ForegroundBrush, GlyphRun, origin);
+
+ if (Properties.TextDecorations == null)
+ {
+ return;
+ }
+
+ foreach (var textDecoration in Properties.TextDecorations)
+ {
+ textDecoration.Draw(drawingContext, this, origin);
+ }
+ }
+
+ ///
+ /// Splits the at specified length.
+ ///
+ /// The length.
+ /// The split result.
+ public SplitTextCharactersResult Split(int length)
+ {
+ var glyphCount = GlyphRun.FindGlyphIndex(GlyphRun.Characters.Start + length);
+
+ if (GlyphRun.Characters.Length == length)
+ {
+ return new SplitTextCharactersResult(this, null);
+ }
+
+ if (GlyphRun.GlyphIndices.Length == glyphCount)
+ {
+ return new SplitTextCharactersResult(this, null);
+ }
+
+ var firstGlyphRun = new GlyphRun(
+ Properties.Typeface.GlyphTypeface,
+ Properties.FontRenderingEmSize,
+ GlyphRun.GlyphIndices.Take(glyphCount),
+ GlyphRun.GlyphAdvances.Take(glyphCount),
+ GlyphRun.GlyphOffsets.Take(glyphCount),
+ GlyphRun.Characters.Take(length),
+ GlyphRun.GlyphClusters.Take(glyphCount));
+
+ var firstTextRun = new ShapedTextCharacters(firstGlyphRun, Properties);
+
+ var secondGlyphRun = new GlyphRun(
+ Properties.Typeface.GlyphTypeface,
+ Properties.FontRenderingEmSize,
+ GlyphRun.GlyphIndices.Skip(glyphCount),
+ GlyphRun.GlyphAdvances.Skip(glyphCount),
+ GlyphRun.GlyphOffsets.Skip(glyphCount),
+ GlyphRun.Characters.Skip(length),
+ GlyphRun.GlyphClusters.Skip(glyphCount));
+
+ var secondTextRun = new ShapedTextCharacters(secondGlyphRun, Properties);
+
+ return new SplitTextCharactersResult(firstTextRun, secondTextRun);
+ }
+
+ public readonly struct SplitTextCharactersResult
+ {
+ public SplitTextCharactersResult(ShapedTextCharacters first, ShapedTextCharacters second)
+ {
+ First = first;
+
+ Second = second;
+ }
+
+ ///
+ /// Gets the first text run.
+ ///
+ ///
+ /// The first text run.
+ ///
+ public ShapedTextCharacters First { get; }
+
+ ///
+ /// Gets the second text run.
+ ///
+ ///
+ /// The second text run.
+ ///
+ public ShapedTextCharacters Second { get; }
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextRun.cs b/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextRun.cs
deleted file mode 100644
index 00f9b918cb..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/ShapedTextRun.cs
+++ /dev/null
@@ -1,212 +0,0 @@
-using Avalonia.Media.Immutable;
-using Avalonia.Media.TextFormatting.Unicode;
-using Avalonia.Platform;
-using Avalonia.Utility;
-
-namespace Avalonia.Media.TextFormatting
-{
- ///
- /// A text run that holds a shaped glyph run.
- ///
- public sealed class ShapedTextRun : DrawableTextRun
- {
- public ShapedTextRun(ReadOnlySlice text, TextStyle style) : this(
- TextShaper.Current.ShapeText(text, style.TextFormat), style)
- {
- }
-
- public ShapedTextRun(GlyphRun glyphRun, TextStyle style)
- {
- Text = glyphRun.Characters;
- Style = style;
- GlyphRun = glyphRun;
- }
-
- ///
- public override Rect Bounds => GlyphRun.Bounds;
-
- ///
- /// Gets the glyph run.
- ///
- ///
- /// The glyphs.
- ///
- public GlyphRun GlyphRun { get; }
-
- ///
- public override void Draw(IDrawingContextImpl drawingContext, Point origin)
- {
- if (GlyphRun.GlyphIndices.Length == 0)
- {
- return;
- }
-
- if (Style.TextFormat.Typeface == null)
- {
- return;
- }
-
- if (Style.Foreground == null)
- {
- return;
- }
-
- drawingContext.DrawGlyphRun(Style.Foreground, GlyphRun, origin);
-
- if (Style.TextDecorations == null)
- {
- return;
- }
-
- foreach (var textDecoration in Style.TextDecorations)
- {
- DrawTextDecoration(drawingContext, textDecoration, origin);
- }
- }
-
- ///
- /// Draws the at given origin.
- ///
- /// The drawing context.
- /// The text decoration.
- /// The origin.
- private void DrawTextDecoration(IDrawingContextImpl drawingContext, ImmutableTextDecoration textDecoration, Point origin)
- {
- var textFormat = Style.TextFormat;
-
- var fontMetrics = Style.TextFormat.FontMetrics;
-
- var thickness = textDecoration.Pen?.Thickness ?? 1.0;
-
- switch (textDecoration.PenThicknessUnit)
- {
- case TextDecorationUnit.FontRecommended:
- switch (textDecoration.Location)
- {
- case TextDecorationLocation.Underline:
- thickness = fontMetrics.UnderlineThickness;
- break;
- case TextDecorationLocation.Strikethrough:
- thickness = fontMetrics.StrikethroughThickness;
- break;
- }
- break;
- case TextDecorationUnit.FontRenderingEmSize:
- thickness = textFormat.FontRenderingEmSize * thickness;
- break;
- }
-
- switch (textDecoration.Location)
- {
- case TextDecorationLocation.Overline:
- origin += new Point(0, textFormat.FontMetrics.Ascent);
- break;
- case TextDecorationLocation.Strikethrough:
- origin += new Point(0, -textFormat.FontMetrics.StrikethroughPosition);
- break;
- case TextDecorationLocation.Underline:
- origin += new Point(0, -textFormat.FontMetrics.UnderlinePosition);
- break;
- }
-
- switch (textDecoration.PenOffsetUnit)
- {
- case TextDecorationUnit.FontRenderingEmSize:
- origin += new Point(0, textDecoration.PenOffset * textFormat.FontRenderingEmSize);
- break;
- case TextDecorationUnit.Pixel:
- origin += new Point(0, textDecoration.PenOffset);
- break;
- }
-
- var pen = new ImmutablePen(
- textDecoration.Pen?.Brush ?? Style.Foreground.ToImmutable(),
- thickness,
- textDecoration.Pen?.DashStyle?.ToImmutable(),
- textDecoration.Pen?.LineCap ?? default,
- textDecoration.Pen?.LineJoin ?? PenLineJoin.Miter,
- textDecoration.Pen?.MiterLimit ?? 10.0);
-
- drawingContext.DrawLine(pen, origin, origin + new Point(GlyphRun.Bounds.Width, 0));
- }
-
- ///
- /// Splits the at specified length.
- ///
- /// The length.
- /// The split result.
- public SplitTextCharactersResult Split(int length)
- {
- var glyphCount = 0;
-
- var firstCharacters = GlyphRun.Characters.Take(length);
-
- var codepointEnumerator = new CodepointEnumerator(firstCharacters);
-
- while (codepointEnumerator.MoveNext())
- {
- glyphCount++;
- }
-
- if (GlyphRun.Characters.Length == length)
- {
- return new SplitTextCharactersResult(this, null);
- }
-
- if (GlyphRun.GlyphIndices.Length == glyphCount)
- {
- return new SplitTextCharactersResult(this, null);
- }
-
- var firstGlyphRun = new GlyphRun(
- Style.TextFormat.Typeface.GlyphTypeface,
- Style.TextFormat.FontRenderingEmSize,
- GlyphRun.GlyphIndices.Take(glyphCount),
- GlyphRun.GlyphAdvances.Take(glyphCount),
- GlyphRun.GlyphOffsets.Take(glyphCount),
- GlyphRun.Characters.Take(length),
- GlyphRun.GlyphClusters.Take(length));
-
- var firstTextRun = new ShapedTextRun(firstGlyphRun, Style);
-
- var secondGlyphRun = new GlyphRun(
- Style.TextFormat.Typeface.GlyphTypeface,
- Style.TextFormat.FontRenderingEmSize,
- GlyphRun.GlyphIndices.Skip(glyphCount),
- GlyphRun.GlyphAdvances.Skip(glyphCount),
- GlyphRun.GlyphOffsets.Skip(glyphCount),
- GlyphRun.Characters.Skip(length),
- GlyphRun.GlyphClusters.Skip(length));
-
- var secondTextRun = new ShapedTextRun(secondGlyphRun, Style);
-
- return new SplitTextCharactersResult(firstTextRun, secondTextRun);
- }
-
- public readonly struct SplitTextCharactersResult
- {
- public SplitTextCharactersResult(ShapedTextRun first, ShapedTextRun second)
- {
- First = first;
-
- Second = second;
- }
-
- ///
- /// Gets the first text run.
- ///
- ///
- /// The first text run.
- ///
- public ShapedTextRun First { get; }
-
- ///
- /// Gets the second text run.
- ///
- ///
- /// The second text run.
- ///
- public ShapedTextRun Second { get; }
- }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextFormatter.cs b/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextFormatter.cs
deleted file mode 100644
index f84e45d4c6..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextFormatter.cs
+++ /dev/null
@@ -1,395 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Avalonia.Media.TextFormatting.Unicode;
-using Avalonia.Platform;
-using Avalonia.Utility;
-
-namespace Avalonia.Media.TextFormatting
-{
- internal class SimpleTextFormatter : TextFormatter
- {
- private static readonly ReadOnlySlice s_ellipsis = new ReadOnlySlice(new[] { '\u2026' });
-
- ///
- public override TextLine FormatLine(ITextSource textSource, int firstTextSourceIndex, double paragraphWidth,
- TextParagraphProperties paragraphProperties)
- {
- var textTrimming = paragraphProperties.TextTrimming;
- var textWrapping = paragraphProperties.TextWrapping;
- TextLine textLine;
-
- var textRuns = FormatTextRuns(textSource, firstTextSourceIndex, out var textPointer);
-
- if (textTrimming != TextTrimming.None)
- {
- textLine = PerformTextTrimming(textPointer, textRuns, paragraphWidth, paragraphProperties);
- }
- else
- {
- if (textWrapping == TextWrapping.Wrap)
- {
- textLine = PerformTextWrapping(textPointer, textRuns, paragraphWidth, paragraphProperties);
- }
- else
- {
- var textLineMetrics =
- TextLineMetrics.Create(textRuns, paragraphWidth, paragraphProperties.TextAlignment);
-
- textLine = new SimpleTextLine(textPointer, textRuns, textLineMetrics);
- }
- }
-
- return textLine;
- }
-
- ///
- /// Formats text runs with optional text style overrides.
- ///
- /// The text source.
- /// The first text source index.
- /// The text pointer that covers the formatted text runs.
- ///
- /// The formatted text runs.
- ///
- private List FormatTextRuns(ITextSource textSource, int firstTextSourceIndex, out TextPointer textPointer)
- {
- var start = -1;
- var length = 0;
-
- var textRuns = new List();
-
- while (true)
- {
- var textRun = textSource.GetTextRun(firstTextSourceIndex + length);
-
- if (start == -1)
- {
- start = textRun.Text.Start;
- }
-
- if (textRun is TextEndOfLine)
- {
- break;
- }
-
- switch (textRun)
- {
- case TextCharacters textCharacters:
-
- var runText = textCharacters.Text;
-
- while (!runText.IsEmpty)
- {
- var shapableTextStyleRun = CreateShapableTextStyleRun(runText, textRun.Style);
-
- var shapedRun = new ShapedTextRun(runText.Take(shapableTextStyleRun.TextPointer.Length),
- shapableTextStyleRun.Style);
-
- textRuns.Add(shapedRun);
-
- runText = runText.Skip(shapedRun.Text.Length);
- }
-
- break;
- default:
- throw new NotSupportedException("Run type not supported by the formatter.");
- }
-
- length += textRun.Text.Length;
- }
-
- textPointer = new TextPointer(start, length);
-
- return textRuns;
- }
-
- ///
- /// Performs text trimming and returns a trimmed line.
- ///
- /// A value that specifies the width of the paragraph that the line fills.
- /// A value that represents paragraph properties,
- /// such as TextWrapping, TextAlignment, or TextStyle.
- /// The text runs to perform the trimming on.
- /// The text that was used to construct the text runs.
- ///
- private static TextLine PerformTextTrimming(TextPointer text, IReadOnlyList textRuns,
- double paragraphWidth, TextParagraphProperties paragraphProperties)
- {
- var textTrimming = paragraphProperties.TextTrimming;
- var availableWidth = paragraphWidth;
- var currentWidth = 0.0;
- var runIndex = 0;
-
- while (runIndex < textRuns.Count)
- {
- var currentRun = textRuns[runIndex];
-
- currentWidth += currentRun.GlyphRun.Bounds.Width;
-
- if (currentWidth > availableWidth)
- {
- var ellipsisRun = CreateEllipsisRun(currentRun.Style);
-
- var measuredLength = MeasureText(currentRun, availableWidth - ellipsisRun.GlyphRun.Bounds.Width);
-
- if (textTrimming == TextTrimming.WordEllipsis)
- {
- if (measuredLength < text.End)
- {
- var currentBreakPosition = 0;
-
- var lineBreaker = new LineBreakEnumerator(currentRun.Text);
-
- while (currentBreakPosition < measuredLength && lineBreaker.MoveNext())
- {
- var nextBreakPosition = lineBreaker.Current.PositionWrap;
-
- if (nextBreakPosition == 0)
- {
- break;
- }
-
- if (nextBreakPosition > measuredLength)
- {
- break;
- }
-
- currentBreakPosition = nextBreakPosition;
- }
-
- measuredLength = currentBreakPosition;
- }
- }
-
- var splitResult = SplitTextRuns(textRuns, measuredLength);
-
- var trimmedRuns = new List(splitResult.First.Count + 1);
-
- trimmedRuns.AddRange(splitResult.First);
-
- trimmedRuns.Add(ellipsisRun);
-
- var textLineMetrics =
- TextLineMetrics.Create(trimmedRuns, paragraphWidth, paragraphProperties.TextAlignment);
-
- return new SimpleTextLine(text.Take(measuredLength), trimmedRuns, textLineMetrics);
- }
-
- availableWidth -= currentRun.GlyphRun.Bounds.Width;
-
- runIndex++;
- }
-
- return new SimpleTextLine(text, textRuns,
- TextLineMetrics.Create(textRuns, paragraphWidth, paragraphProperties.TextAlignment));
- }
-
- ///
- /// Performs text wrapping returns a list of text lines.
- ///
- /// The text paragraph properties.
- /// The text run'S.
- /// The text to analyze for break opportunities.
- ///
- ///
- private static TextLine PerformTextWrapping(TextPointer text, IReadOnlyList textRuns,
- double paragraphWidth, TextParagraphProperties paragraphProperties)
- {
- var availableWidth = paragraphWidth;
- var currentWidth = 0.0;
- var runIndex = 0;
- var length = 0;
-
- while (runIndex < textRuns.Count)
- {
- var currentRun = textRuns[runIndex];
-
- if (currentWidth + currentRun.GlyphRun.Bounds.Width > availableWidth)
- {
- var measuredLength = MeasureText(currentRun, paragraphWidth - currentWidth);
-
- if (measuredLength < currentRun.Text.Length)
- {
- var currentBreakPosition = -1;
-
- var lineBreaker = new LineBreakEnumerator(currentRun.Text);
-
- while (currentBreakPosition < measuredLength && lineBreaker.MoveNext())
- {
- var nextBreakPosition = lineBreaker.Current.PositionWrap;
-
- if (nextBreakPosition == 0)
- {
- break;
- }
-
- if (nextBreakPosition > measuredLength)
- {
- break;
- }
-
- currentBreakPosition = nextBreakPosition;
- }
-
- if (currentBreakPosition != -1)
- {
- measuredLength = currentBreakPosition;
- }
- }
-
- length += measuredLength;
-
- var splitResult = SplitTextRuns(textRuns, length);
-
- var textLineMetrics =
- TextLineMetrics.Create(splitResult.First, paragraphWidth, paragraphProperties.TextAlignment);
-
- return new SimpleTextLine(text.Take(length), splitResult.First, textLineMetrics);
- }
-
- currentWidth += currentRun.GlyphRun.Bounds.Width;
-
- length += currentRun.GlyphRun.Characters.Length;
-
- runIndex++;
- }
-
- return new SimpleTextLine(text, textRuns,
- TextLineMetrics.Create(textRuns, paragraphWidth, paragraphProperties.TextAlignment));
- }
-
- ///
- /// Measures the number of characters that fits into available width.
- ///
- /// The text run.
- /// The available width.
- ///
- private static int MeasureText(ShapedTextRun textRun, double availableWidth)
- {
- var glyphRun = textRun.GlyphRun;
-
- var characterHit = glyphRun.GetCharacterHitFromDistance(availableWidth, out _);
-
- return characterHit.FirstCharacterIndex + characterHit.TrailingLength - textRun.Text.Start;
- }
-
- ///
- /// Creates an ellipsis.
- ///
- /// The text style.
- ///
- private static ShapedTextRun CreateEllipsisRun(TextStyle textStyle)
- {
- var formatterImpl = AvaloniaLocator.Current.GetService();
-
- var glyphRun = formatterImpl.ShapeText(s_ellipsis, textStyle.TextFormat);
-
- return new ShapedTextRun(glyphRun, textStyle);
- }
-
- private readonly struct SplitTextRunsResult
- {
- public SplitTextRunsResult(IReadOnlyList first, IReadOnlyList second)
- {
- First = first;
-
- Second = second;
- }
-
- ///
- /// Gets the first text runs.
- ///
- ///
- /// The first text runs.
- ///
- public IReadOnlyList First { get; }
-
- ///
- /// Gets the second text runs.
- ///
- ///
- /// The second text runs.
- ///
- public IReadOnlyList Second { get; }
- }
-
- ///
- /// Split a sequence of runs into two segments at specified length.
- ///
- /// The text run's.
- /// The length to split at.
- ///
- private static SplitTextRunsResult SplitTextRuns(IReadOnlyList textRuns, int length)
- {
- var currentLength = 0;
-
- for (var i = 0; i < textRuns.Count; i++)
- {
- var currentRun = textRuns[i];
-
- if (currentLength + currentRun.GlyphRun.Characters.Length < length)
- {
- currentLength += currentRun.GlyphRun.Characters.Length;
- continue;
- }
-
- var firstCount = currentRun.GlyphRun.Characters.Length >= 1 ? i + 1 : i;
-
- var first = new ShapedTextRun[firstCount];
-
- if (firstCount > 1)
- {
- for (var j = 0; j < i; j++)
- {
- first[j] = textRuns[j];
- }
- }
-
- var secondCount = textRuns.Count - firstCount;
-
- if (currentLength + currentRun.GlyphRun.Characters.Length == length)
- {
- var second = new ShapedTextRun[secondCount];
-
- var offset = currentRun.GlyphRun.Characters.Length > 1 ? 1 : 0;
-
- if (secondCount > 0)
- {
- for (var j = 0; j < secondCount; j++)
- {
- second[j] = textRuns[i + j + offset];
- }
- }
-
- first[i] = currentRun;
-
- return new SplitTextRunsResult(first, second);
- }
- else
- {
- secondCount++;
-
- var second = new ShapedTextRun[secondCount];
-
- if (secondCount > 0)
- {
- for (var j = 1; j < secondCount; j++)
- {
- second[j] = textRuns[i + j];
- }
- }
-
- var split = currentRun.Split(length - currentLength);
-
- first[i] = split.First;
-
- second[0] = split.Second;
-
- return new SplitTextRunsResult(first, second);
- }
- }
-
- return new SplitTextRunsResult(textRuns, null);
- }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextLine.cs b/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextLine.cs
deleted file mode 100644
index 11d241bc34..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/SimpleTextLine.cs
+++ /dev/null
@@ -1,259 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Avalonia.Platform;
-
-namespace Avalonia.Media.TextFormatting
-{
- internal class SimpleTextLine : TextLine
- {
- private readonly IReadOnlyList _textRuns;
-
- public SimpleTextLine(TextPointer textPointer, IReadOnlyList textRuns, TextLineMetrics lineMetrics)
- {
- Text = textPointer;
- _textRuns = textRuns;
- LineMetrics = lineMetrics;
- }
-
- ///
- public override TextPointer Text { get; }
-
- ///
- public override IReadOnlyList TextRuns => _textRuns;
-
- ///
- public override TextLineMetrics LineMetrics { get; }
-
- ///
- public override void Draw(IDrawingContextImpl drawingContext, Point origin)
- {
- var currentX = origin.X;
-
- foreach (var textRun in _textRuns)
- {
- var baselineOrigin = new Point(currentX + LineMetrics.BaselineOrigin.X,
- origin.Y + LineMetrics.BaselineOrigin.Y);
-
- textRun.Draw(drawingContext, baselineOrigin);
-
- currentX += textRun.Bounds.Width;
- }
- }
-
- ///
- public override CharacterHit GetCharacterHitFromDistance(double distance)
- {
- if (distance < 0)
- {
- // hit happens before the line, return the first position
- return new CharacterHit(Text.Start);
- }
-
- // process hit that happens within the line
- var characterHit = new CharacterHit();
-
- foreach (var run in _textRuns)
- {
- characterHit = run.GlyphRun.GetCharacterHitFromDistance(distance, out _);
-
- if (distance <= run.Bounds.Width)
- {
- break;
- }
-
- distance -= run.Bounds.Width;
- }
-
- return characterHit;
- }
-
- ///
- public override double GetDistanceFromCharacterHit(CharacterHit characterHit)
- {
- return DistanceFromCodepointIndex(characterHit.FirstCharacterIndex + (characterHit.TrailingLength != 0 ? 1 : 0));
- }
-
- ///
- public override CharacterHit GetNextCaretCharacterHit(CharacterHit characterHit)
- {
- int nextVisibleCp;
- bool navigableCpFound;
-
- if (characterHit.TrailingLength == 0)
- {
- navigableCpFound = FindNextCodepointIndex(characterHit.FirstCharacterIndex, out nextVisibleCp);
-
- if (navigableCpFound)
- {
- // Move from leading to trailing edge
- return new CharacterHit(nextVisibleCp, 1);
- }
- }
-
- navigableCpFound = FindNextCodepointIndex(characterHit.FirstCharacterIndex + 1, out nextVisibleCp);
-
- if (navigableCpFound)
- {
- // Move from trailing edge of current character to trailing edge of next
- return new CharacterHit(nextVisibleCp, 1);
- }
-
- // Can't move, we're after the last character
- return characterHit;
- }
-
- ///
- public override CharacterHit GetPreviousCaretCharacterHit(CharacterHit characterHit)
- {
- int previousCodepointIndex;
- bool codepointIndexFound;
-
- var cpHit = characterHit.FirstCharacterIndex;
- var trailingHit = characterHit.TrailingLength != 0;
-
- // Input can be right after the end of the current line. Snap it to be at the end of the line.
- if (cpHit >= Text.Start + Text.Length)
- {
- cpHit = Text.Start + Text.Length - 1;
-
- trailingHit = true;
- }
-
- if (trailingHit)
- {
- codepointIndexFound = FindPreviousCodepointIndex(cpHit, out previousCodepointIndex);
-
- if (codepointIndexFound)
- {
- // Move from trailing to leading edge
- return new CharacterHit(previousCodepointIndex, 0);
- }
- }
-
- codepointIndexFound = FindPreviousCodepointIndex(cpHit - 1, out previousCodepointIndex);
-
- if (codepointIndexFound)
- {
- // Move from leading edge of current character to leading edge of previous
- return new CharacterHit(previousCodepointIndex, 0);
- }
-
- // Can't move, we're before the first character
- return characterHit;
- }
-
- ///
- public override CharacterHit GetBackspaceCaretCharacterHit(CharacterHit characterHit)
- {
- // same operation as move-to-previous
- return GetPreviousCaretCharacterHit(characterHit);
- }
-
- ///
- /// Get distance from line start to the specified codepoint index
- ///
- private double DistanceFromCodepointIndex(int codepointIndex)
- {
- var currentDistance = 0.0;
-
- foreach (var textRun in _textRuns)
- {
- if (codepointIndex > textRun.Text.End)
- {
- currentDistance += textRun.Bounds.Width;
-
- continue;
- }
-
- return currentDistance + textRun.GlyphRun.GetDistanceFromCharacterHit(new CharacterHit(codepointIndex));
- }
-
- return currentDistance;
- }
-
- ///
- /// Search forward from the given codepoint index (inclusive) to find the next navigable codepoint index.
- /// Return true if one such codepoint index is found, false otherwise.
- ///
- private bool FindNextCodepointIndex(int codepointIndex, out int nextCodepointIndex)
- {
- nextCodepointIndex = codepointIndex;
-
- if (codepointIndex >= Text.Start + Text.Length)
- {
- return false; // Cannot go forward anymore
- }
-
- GetRunIndexAtCodepointIndex(codepointIndex, out var runIndex, out var cpRunStart);
-
- while (runIndex < TextRuns.Count)
- {
- // When navigating forward, only the trailing edge of visible content is
- // navigable.
- if (runIndex < TextRuns.Count)
- {
- nextCodepointIndex = Math.Max(cpRunStart, codepointIndex);
- return true;
- }
-
- cpRunStart += TextRuns[runIndex++].Text.Length;
- }
-
- return false;
- }
-
- ///
- /// Search backward from the given codepoint index (inclusive) to find the previous navigable codepoint index.
- /// Return true if one such codepoint is found, false otherwise.
- ///
- private bool FindPreviousCodepointIndex(int codepointIndex, out int previousCodepointIndex)
- {
- previousCodepointIndex = codepointIndex;
-
- if (codepointIndex < Text.Start)
- {
- return false; // Cannot go backward anymore.
- }
-
- // Position the cpRunEnd at the end of the span that contains the given cp
- GetRunIndexAtCodepointIndex(codepointIndex, out var runIndex, out var codepointIndexAtRunEnd);
-
- codepointIndexAtRunEnd += TextRuns[runIndex].Text.End;
-
- while (runIndex >= 0)
- {
- // Visible content has caret stops at its leading edge.
- if (runIndex + 1 < TextRuns.Count)
- {
- previousCodepointIndex = Math.Min(codepointIndexAtRunEnd, codepointIndex);
- return true;
- }
-
- // Newline sequence has caret stops at its leading edge.
- if (runIndex == TextRuns.Count)
- {
- // Get the cp index at the beginning of the newline sequence.
- previousCodepointIndex = codepointIndexAtRunEnd - TextRuns[runIndex].Text.Length + 1;
- return true;
- }
-
- codepointIndexAtRunEnd -= TextRuns[runIndex--].Text.Length;
- }
-
- return false;
- }
-
- private void GetRunIndexAtCodepointIndex(int codepointIndex, out int runIndex, out int codepointIndexAtRunStart)
- {
- codepointIndexAtRunStart = Text.Start;
- runIndex = 0;
-
- // Find the span that contains the given cp
- while (runIndex < TextRuns.Count &&
- codepointIndexAtRunStart + TextRuns[runIndex].Text.Length <= codepointIndex)
- {
- codepointIndexAtRunStart += TextRuns[runIndex++].Text.Length;
- }
- }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextCharacters.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextCharacters.cs
index d9b27958ab..47e716982c 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextCharacters.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextCharacters.cs
@@ -1,4 +1,6 @@
-using Avalonia.Utility;
+using System.Collections.Generic;
+using Avalonia.Media.TextFormatting.Unicode;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting
{
@@ -7,15 +9,182 @@ namespace Avalonia.Media.TextFormatting
///
public class TextCharacters : TextRun
{
- protected TextCharacters()
+ public TextCharacters(ReadOnlySlice text, TextRunProperties properties)
{
-
+ TextSourceLength = text.Length;
+ Text = text;
+ Properties = properties;
}
- public TextCharacters(ReadOnlySlice text, TextStyle style)
+ ///
+ public override int TextSourceLength { get; }
+
+ ///
+ public override ReadOnlySlice Text { get; }
+
+ ///
+ public override TextRunProperties Properties { get; }
+
+ ///
+ /// Gets a list of .
+ ///
+ /// The shapeable text characters.
+ internal IList GetShapeableCharacters()
{
- Text = text;
- Style = style;
+ var shapeableCharacters = new List(2);
+
+ var runText = Text;
+
+ while (!runText.IsEmpty)
+ {
+ var shapeableRun = CreateShapeableRun(runText, Properties);
+
+ shapeableCharacters.Add(shapeableRun);
+
+ runText = runText.Skip(shapeableRun.Text.Length);
+ }
+
+ return shapeableCharacters;
+ }
+
+ ///
+ /// Creates a shapeable text run with unique properties.
+ ///
+ /// The text to create text runs from.
+ /// The default text run properties.
+ /// A list of shapeable text runs.
+ private ShapeableTextCharacters CreateShapeableRun(ReadOnlySlice text, TextRunProperties defaultProperties)
+ {
+ var defaultTypeface = defaultProperties.Typeface;
+
+ var currentTypeface = defaultTypeface;
+
+ if (TryGetRunProperties(text, currentTypeface, defaultTypeface, out var count))
+ {
+ return new ShapeableTextCharacters(text.Take(count),
+ new GenericTextRunProperties(currentTypeface, defaultProperties.FontRenderingEmSize,
+ defaultProperties.TextDecorations, defaultProperties.ForegroundBrush));
+
+ }
+
+ var codepoint = Codepoint.ReadAt(text, count, out _);
+
+ //ToDo: Fix FontFamily fallback
+ currentTypeface =
+ FontManager.Current.MatchCharacter(codepoint, defaultTypeface.Style, defaultTypeface.Weight, defaultTypeface.FontFamily);
+
+ if (currentTypeface != null && TryGetRunProperties(text, currentTypeface, defaultTypeface, out count))
+ {
+ //Fallback found
+ return new ShapeableTextCharacters(text.Take(count),
+ new GenericTextRunProperties(currentTypeface, defaultProperties.FontRenderingEmSize,
+ defaultProperties.TextDecorations, defaultProperties.ForegroundBrush));
+ }
+
+ // no fallback found
+ currentTypeface = defaultTypeface;
+
+ var glyphTypeface = currentTypeface.GlyphTypeface;
+
+ var enumerator = new GraphemeEnumerator(text);
+
+ while (enumerator.MoveNext())
+ {
+ var grapheme = enumerator.Current;
+
+ if (!grapheme.FirstCodepoint.IsWhiteSpace && glyphTypeface.TryGetGlyph(grapheme.FirstCodepoint, out _))
+ {
+ break;
+ }
+
+ count += grapheme.Text.Length;
+ }
+
+ return new ShapeableTextCharacters(text.Take(count),
+ new GenericTextRunProperties(currentTypeface, defaultProperties.FontRenderingEmSize,
+ defaultProperties.TextDecorations, defaultProperties.ForegroundBrush));
+ }
+
+ ///
+ /// Tries to get run properties.
+ ///
+ ///
+ ///
+ /// The typeface that is used to find matching characters.
+ ///
+ ///
+ protected bool TryGetRunProperties(ReadOnlySlice text, Typeface typeface, Typeface defaultTypeface,
+ out int count)
+ {
+ if (text.Length == 0)
+ {
+ count = 0;
+ return false;
+ }
+
+ var isFallback = typeface != defaultTypeface;
+
+ count = 0;
+ var script = Script.Common;
+ //var direction = BiDiClass.LeftToRight;
+
+ var font = typeface.GlyphTypeface;
+ var defaultFont = defaultTypeface.GlyphTypeface;
+
+ var enumerator = new GraphemeEnumerator(text);
+
+ while (enumerator.MoveNext())
+ {
+ var grapheme = enumerator.Current;
+
+ var currentScript = grapheme.FirstCodepoint.Script;
+
+ //var currentDirection = grapheme.FirstCodepoint.BiDiClass;
+
+ //// ToDo: Implement BiDi algorithm
+ //if (currentScript.HorizontalDirection != direction)
+ //{
+ // if (!UnicodeUtility.IsWhiteSpace(grapheme.FirstCodepoint))
+ // {
+ // break;
+ // }
+ //}
+
+ if (currentScript != script)
+ {
+ if (currentScript != Script.Inherited && currentScript != Script.Common)
+ {
+ if (script == Script.Inherited || script == Script.Common)
+ {
+ script = currentScript;
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ if (isFallback)
+ {
+ if (defaultFont.TryGetGlyph(grapheme.FirstCodepoint, out _))
+ {
+ break;
+ }
+ }
+
+ if (!font.TryGetGlyph(grapheme.FirstCodepoint, out _))
+ {
+ if (!grapheme.FirstCodepoint.IsWhiteSpace)
+ {
+ break;
+ }
+ }
+
+ count += grapheme.Text.Length;
+ }
+
+ return count > 0;
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextFormat.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextFormat.cs
deleted file mode 100644
index 18dd6c7c10..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextFormat.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using System;
-
-namespace Avalonia.Media.TextFormatting
-{
- ///
- /// Unique text formatting properties that are used by the .
- ///
- public readonly struct TextFormat : IEquatable
- {
- public TextFormat(Typeface typeface, double fontRenderingEmSize)
- {
- Typeface = typeface;
- FontRenderingEmSize = fontRenderingEmSize;
- FontMetrics = new FontMetrics(typeface, fontRenderingEmSize);
- }
-
- ///
- /// Gets the typeface.
- ///
- ///
- /// The typeface.
- ///
- public Typeface Typeface { get; }
-
- ///
- /// Gets the font rendering em size.
- ///
- ///
- /// The em rendering size of the font.
- ///
- public double FontRenderingEmSize { get; }
-
- ///
- /// Gets the font metrics.
- ///
- ///
- /// The metrics of the font.
- ///
- public FontMetrics FontMetrics { get; }
-
- public static bool operator ==(TextFormat self, TextFormat other)
- {
- return self.Equals(other);
- }
-
- public static bool operator !=(TextFormat self, TextFormat other)
- {
- return !(self == other);
- }
-
- public bool Equals(TextFormat other)
- {
- return Typeface.Equals(other.Typeface) && FontRenderingEmSize.Equals(other.FontRenderingEmSize);
- }
-
- public override bool Equals(object obj)
- {
- return obj is TextFormat other && Equals(other);
- }
-
- public override int GetHashCode()
- {
- unchecked
- {
- var hashCode = (Typeface != null ? Typeface.GetHashCode() : 0);
- hashCode = (hashCode * 397) ^ FontRenderingEmSize.GetHashCode();
- return hashCode;
- }
- }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextFormatter.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextFormatter.cs
index 7da39dc5dc..e4c898e2b8 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextFormatter.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextFormatter.cs
@@ -1,5 +1,4 @@
using Avalonia.Media.TextFormatting.Unicode;
-using Avalonia.Utility;
namespace Avalonia.Media.TextFormatting
{
@@ -22,7 +21,7 @@ namespace Avalonia.Media.TextFormatting
return current;
}
- current = new SimpleTextFormatter();
+ current = new TextFormatterImpl();
AvaloniaLocator.CurrentMutable.Bind().ToConstant(current);
@@ -38,149 +37,10 @@ namespace Avalonia.Media.TextFormatting
/// A value that specifies the width of the paragraph that the line fills.
/// A value that represents paragraph properties,
/// such as TextWrapping, TextAlignment, or TextStyle.
+ /// A value that specifies the text formatter state,
+ /// in terms of where the previous line in the paragraph was broken by the text formatting process.
/// The formatted line.
public abstract TextLine FormatLine(ITextSource textSource, int firstTextSourceIndex, double paragraphWidth,
- TextParagraphProperties paragraphProperties);
-
- ///
- /// Creates a text style run with unique properties.
- ///
- /// The text to create text runs from.
- ///
- /// A list of text runs.
- protected TextStyleRun CreateShapableTextStyleRun(ReadOnlySlice text, TextStyle defaultStyle)
- {
- var defaultTypeface = defaultStyle.TextFormat.Typeface;
-
- var currentTypeface = defaultTypeface;
-
- if (TryGetRunProperties(text, currentTypeface, defaultTypeface, out var count))
- {
- return new TextStyleRun(new TextPointer(text.Start, count), new TextStyle(currentTypeface,
- defaultStyle.TextFormat.FontRenderingEmSize,
- defaultStyle.Foreground, defaultStyle.TextDecorations));
-
- }
-
- var codepoint = Codepoint.ReadAt(text, count, out _);
-
- //ToDo: Fix FontFamily fallback
- currentTypeface =
- FontManager.Current.MatchCharacter(codepoint, defaultTypeface.Weight, defaultTypeface.Style, defaultStyle.TextFormat.Typeface.FontFamily);
-
- if (currentTypeface != null && TryGetRunProperties(text, currentTypeface, defaultTypeface, out count))
- {
- //Fallback found
- return new TextStyleRun(new TextPointer(text.Start, count), new TextStyle(currentTypeface,
- defaultStyle.TextFormat.FontRenderingEmSize,
- defaultStyle.Foreground, defaultStyle.TextDecorations));
-
- }
-
- // no fallback found
- currentTypeface = defaultTypeface;
-
- var glyphTypeface = currentTypeface.GlyphTypeface;
-
- var enumerator = new GraphemeEnumerator(text);
-
- while (enumerator.MoveNext())
- {
- var grapheme = enumerator.Current;
-
- if (!grapheme.FirstCodepoint.IsWhiteSpace && glyphTypeface.TryGetGlyph(grapheme.FirstCodepoint, out _))
- {
- break;
- }
-
- count += grapheme.Text.Length;
- }
-
- return new TextStyleRun(new TextPointer(text.Start, count),
- new TextStyle(currentTypeface, defaultStyle.TextFormat.FontRenderingEmSize,
- defaultStyle.Foreground, defaultStyle.TextDecorations));
- }
-
- ///
- /// Tries to get run properties.
- ///
- ///
- ///
- /// The typeface that is used to find matching characters.
- ///
- ///
- protected bool TryGetRunProperties(ReadOnlySlice text, Typeface typeface, Typeface defaultTypeface,
- out int count)
- {
- if (text.Length == 0)
- {
- count = 0;
- return false;
- }
-
- var isFallback = typeface != defaultTypeface;
-
- count = 0;
- var script = Script.Common;
- //var direction = BiDiClass.LeftToRight;
-
- var font = typeface.GlyphTypeface;
- var defaultFont = defaultTypeface.GlyphTypeface;
-
- var enumerator = new GraphemeEnumerator(text);
-
- while (enumerator.MoveNext())
- {
- var grapheme = enumerator.Current;
-
- var currentScript = grapheme.FirstCodepoint.Script;
-
- //var currentDirection = grapheme.FirstCodepoint.BiDiClass;
-
- //// ToDo: Implement BiDi algorithm
- //if (currentScript.HorizontalDirection != direction)
- //{
- // if (!UnicodeUtility.IsWhiteSpace(grapheme.FirstCodepoint))
- // {
- // break;
- // }
- //}
-
- if (currentScript != script)
- {
- if (currentScript != Script.Inherited && currentScript != Script.Common)
- {
- if (script == Script.Inherited || script == Script.Common)
- {
- script = currentScript;
- }
- else
- {
- break;
- }
- }
- }
-
- if (isFallback)
- {
- if (defaultFont.TryGetGlyph(grapheme.FirstCodepoint, out _))
- {
- break;
- }
- }
-
- if (!font.TryGetGlyph(grapheme.FirstCodepoint, out _))
- {
- if (!grapheme.FirstCodepoint.IsWhiteSpace)
- {
- break;
- }
- }
-
- count += grapheme.Text.Length;
- }
-
- return count > 0;
- }
+ TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak = null);
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextFormatterImpl.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextFormatterImpl.cs
new file mode 100644
index 0000000000..3ad23f3504
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextFormatterImpl.cs
@@ -0,0 +1,607 @@
+using System.Collections.Generic;
+using Avalonia.Media.TextFormatting.Unicode;
+using Avalonia.Platform;
+using Avalonia.Utilities;
+
+namespace Avalonia.Media.TextFormatting
+{
+ internal class TextFormatterImpl : TextFormatter
+ {
+ private static readonly ReadOnlySlice s_ellipsis = new ReadOnlySlice(new[] { '\u2026' });
+
+ ///
+ public override TextLine FormatLine(ITextSource textSource, int firstTextSourceIndex, double paragraphWidth,
+ TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak = null)
+ {
+ var textTrimming = paragraphProperties.TextTrimming;
+ var textWrapping = paragraphProperties.TextWrapping;
+ TextLine textLine = null;
+
+ var textRuns = FetchTextRuns(textSource, firstTextSourceIndex, previousLineBreak, out var nextLineBreak);
+
+ var textRange = GetTextRange(textRuns);
+
+ if (textTrimming != TextTrimming.None)
+ {
+ textLine = PerformTextTrimming(textRuns, textRange, paragraphWidth, paragraphProperties);
+ }
+ else
+ {
+ switch (textWrapping)
+ {
+ case TextWrapping.NoWrap:
+ {
+ var textLineMetrics =
+ TextLineMetrics.Create(textRuns, textRange, paragraphWidth, paragraphProperties);
+
+ textLine = new TextLineImpl(textRuns, textLineMetrics, nextLineBreak);
+ break;
+ }
+ case TextWrapping.WrapWithOverflow:
+ case TextWrapping.Wrap:
+ {
+ textLine = PerformTextWrapping(textRuns, textRange, paragraphWidth, paragraphProperties);
+ break;
+ }
+ }
+ }
+
+ return textLine;
+ }
+
+ ///
+ /// Fetches text runs.
+ ///
+ /// The text source.
+ /// The first text source index.
+ /// Previous line break. Can be null.
+ /// Next line break. Can be null.
+ ///
+ /// The formatted text runs.
+ ///
+ private static IReadOnlyList FetchTextRuns(ITextSource textSource,
+ int firstTextSourceIndex, TextLineBreak previousLineBreak, out TextLineBreak nextLineBreak)
+ {
+ nextLineBreak = default;
+
+ var currentLength = 0;
+
+ var textRuns = new List();
+
+ if (previousLineBreak != null)
+ {
+ foreach (var shapedCharacters in previousLineBreak.RemainingCharacters)
+ {
+ if (shapedCharacters == null)
+ {
+ continue;
+ }
+
+ textRuns.Add(shapedCharacters);
+
+ if (TryGetLineBreak(shapedCharacters, out var runLineBreak))
+ {
+ var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
+
+ nextLineBreak = new TextLineBreak(splitResult.Second);
+
+ return splitResult.First;
+ }
+
+ currentLength += shapedCharacters.Text.Length;
+ }
+ }
+
+ firstTextSourceIndex += currentLength;
+
+ var textRunEnumerator = new TextRunEnumerator(textSource, firstTextSourceIndex);
+
+ while (textRunEnumerator.MoveNext())
+ {
+ var textRun = textRunEnumerator.Current;
+
+ switch (textRun)
+ {
+ case TextCharacters textCharacters:
+ {
+ var shapeableRuns = textCharacters.GetShapeableCharacters();
+
+ foreach (var run in shapeableRuns)
+ {
+ var glyphRun = TextShaper.Current.ShapeText(run.Text, run.Properties.Typeface,
+ run.Properties.FontRenderingEmSize, run.Properties.CultureInfo);
+
+ var shapedCharacters = new ShapedTextCharacters(glyphRun, run.Properties);
+
+ textRuns.Add(shapedCharacters);
+ }
+
+ break;
+ }
+ }
+
+ if (TryGetLineBreak(textRun, out var runLineBreak))
+ {
+ var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
+
+ nextLineBreak = new TextLineBreak(splitResult.Second);
+
+ return splitResult.First;
+ }
+
+ currentLength += textRun.Text.Length;
+ }
+
+ return textRuns;
+ }
+
+ private static bool TryGetLineBreak(TextRun textRun, out LineBreak lineBreak)
+ {
+ lineBreak = default;
+
+ if (textRun.Text.IsEmpty)
+ {
+ return false;
+ }
+
+ var lineBreakEnumerator = new LineBreakEnumerator(textRun.Text);
+
+ while (lineBreakEnumerator.MoveNext())
+ {
+ if (!lineBreakEnumerator.Current.Required)
+ {
+ continue;
+ }
+
+ lineBreak = lineBreakEnumerator.Current;
+
+ if (lineBreak.PositionWrap >= textRun.Text.Length)
+ {
+ return true;
+ }
+
+ //The line breaker isn't treating \n\r as a pair so we have to fix that here.
+ if (textRun.Text[lineBreak.PositionMeasure] == '\n'
+ && textRun.Text[lineBreak.PositionWrap] == '\r')
+ {
+ lineBreak = new LineBreak(lineBreak.PositionMeasure, lineBreak.PositionWrap + 1,
+ lineBreak.Required);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ ///
+ /// Performs text trimming and returns a trimmed line.
+ ///
+ /// The text runs to perform the trimming on.
+ /// The text range that is covered by the text runs.
+ /// A value that specifies the width of the paragraph that the line fills.
+ /// A value that represents paragraph properties,
+ /// such as TextWrapping, TextAlignment, or TextStyle.
+ ///
+ private static TextLine PerformTextTrimming(IReadOnlyList textRuns, TextRange textRange,
+ double paragraphWidth, TextParagraphProperties paragraphProperties)
+ {
+ var textTrimming = paragraphProperties.TextTrimming;
+ var availableWidth = paragraphWidth;
+ var currentWidth = 0.0;
+ var runIndex = 0;
+
+ while (runIndex < textRuns.Count)
+ {
+ var currentRun = textRuns[runIndex];
+
+ currentWidth += currentRun.GlyphRun.Bounds.Width;
+
+ if (currentWidth > availableWidth)
+ {
+ var ellipsisRun = CreateEllipsisRun(currentRun.Properties);
+
+ var measuredLength = MeasureText(currentRun, availableWidth - ellipsisRun.GlyphRun.Bounds.Width);
+
+ if (textTrimming == TextTrimming.WordEllipsis)
+ {
+ if (measuredLength < textRange.End)
+ {
+ var currentBreakPosition = 0;
+
+ var lineBreaker = new LineBreakEnumerator(currentRun.Text);
+
+ while (currentBreakPosition < measuredLength && lineBreaker.MoveNext())
+ {
+ var nextBreakPosition = lineBreaker.Current.PositionWrap;
+
+ if (nextBreakPosition == 0)
+ {
+ break;
+ }
+
+ if (nextBreakPosition > measuredLength)
+ {
+ break;
+ }
+
+ currentBreakPosition = nextBreakPosition;
+ }
+
+ measuredLength = currentBreakPosition;
+ }
+ }
+
+ var splitResult = SplitTextRuns(textRuns, measuredLength);
+
+ var trimmedRuns = new List(splitResult.First.Count + 1);
+
+ trimmedRuns.AddRange(splitResult.First);
+
+ trimmedRuns.Add(ellipsisRun);
+
+ var textLineMetrics =
+ TextLineMetrics.Create(trimmedRuns, textRange, paragraphWidth, paragraphProperties);
+
+ return new TextLineImpl(trimmedRuns, textLineMetrics);
+ }
+
+ availableWidth -= currentRun.GlyphRun.Bounds.Width;
+
+ runIndex++;
+ }
+
+ return new TextLineImpl(textRuns,
+ TextLineMetrics.Create(textRuns, textRange, paragraphWidth, paragraphProperties));
+ }
+
+ ///
+ /// Performs text wrapping returns a list of text lines.
+ ///
+ /// The text run's.
+ /// The text range that is covered by the text runs.
+ /// The paragraph width.
+ /// The text paragraph properties.
+ /// The wrapped text line.
+ private static TextLine PerformTextWrapping(IReadOnlyList textRuns, TextRange textRange,
+ double paragraphWidth, TextParagraphProperties paragraphProperties)
+ {
+ var availableWidth = paragraphWidth;
+ var currentWidth = 0.0;
+ var runIndex = 0;
+ var length = 0;
+
+ while (runIndex < textRuns.Count)
+ {
+ var currentRun = textRuns[runIndex];
+
+ if (currentWidth + currentRun.GlyphRun.Bounds.Width > availableWidth)
+ {
+ var measuredLength = MeasureText(currentRun, paragraphWidth - currentWidth);
+
+ if (measuredLength < currentRun.Text.Length)
+ {
+ if (paragraphProperties.TextWrapping == TextWrapping.WrapWithOverflow)
+ {
+ var lineBreaker = new LineBreakEnumerator(currentRun.Text.Skip(measuredLength));
+
+ if (lineBreaker.MoveNext())
+ {
+ measuredLength += lineBreaker.Current.PositionWrap;
+ }
+ else
+ {
+ measuredLength = currentRun.Text.Length;
+ }
+ }
+ else
+ {
+ var currentBreakPosition = -1;
+
+ var lineBreaker = new LineBreakEnumerator(currentRun.Text);
+
+ while (currentBreakPosition < measuredLength && lineBreaker.MoveNext())
+ {
+ var nextBreakPosition = lineBreaker.Current.PositionWrap;
+
+ if (nextBreakPosition == 0)
+ {
+ break;
+ }
+
+ if (nextBreakPosition > measuredLength)
+ {
+ break;
+ }
+
+ currentBreakPosition = nextBreakPosition;
+ }
+
+ if (currentBreakPosition != -1)
+ {
+ measuredLength = currentBreakPosition;
+ }
+
+ }
+ }
+
+ length += measuredLength;
+
+ var splitResult = SplitTextRuns(textRuns, length);
+
+ var textLineMetrics = TextLineMetrics.Create(splitResult.First,
+ new TextRange(textRange.Start, length), paragraphWidth, paragraphProperties);
+
+ var lineBreak = splitResult.Second != null && splitResult.Second.Count > 0 ?
+ new TextLineBreak(splitResult.Second) :
+ null;
+
+ return new TextLineImpl(splitResult.First, textLineMetrics, lineBreak);
+ }
+
+ currentWidth += currentRun.GlyphRun.Bounds.Width;
+
+ length += currentRun.GlyphRun.Characters.Length;
+
+ runIndex++;
+ }
+
+ return new TextLineImpl(textRuns,
+ TextLineMetrics.Create(textRuns, textRange, paragraphWidth, paragraphProperties));
+ }
+
+ ///
+ /// Measures the number of characters that fits into available width.
+ ///
+ /// The text run.
+ /// The available width.
+ ///
+ private static int MeasureText(ShapedTextCharacters textCharacters, double availableWidth)
+ {
+ var glyphRun = textCharacters.GlyphRun;
+
+ if (glyphRun.Bounds.Width < availableWidth)
+ {
+ return glyphRun.Characters.Length;
+ }
+
+ var glyphCount = 0;
+
+ var currentWidth = 0.0;
+
+ if (glyphRun.GlyphAdvances.IsEmpty)
+ {
+ var glyphTypeface = glyphRun.GlyphTypeface;
+
+ for (var i = 0; i < glyphRun.GlyphClusters.Length; i++)
+ {
+ var glyph = glyphRun.GlyphIndices[i];
+
+ var advance = glyphTypeface.GetGlyphAdvance(glyph) * glyphRun.Scale;
+
+ if (currentWidth + advance > availableWidth)
+ {
+ break;
+ }
+
+ currentWidth += advance;
+
+ glyphCount++;
+ }
+ }
+ else
+ {
+ for (var i = 0; i < glyphRun.GlyphAdvances.Length; i++)
+ {
+ var advance = glyphRun.GlyphAdvances[i];
+
+ if (currentWidth + advance > availableWidth)
+ {
+ break;
+ }
+
+ currentWidth += advance;
+
+ glyphCount++;
+ }
+ }
+
+ if (glyphCount == glyphRun.GlyphIndices.Length)
+ {
+ return glyphRun.Characters.Length;
+ }
+
+ if (glyphRun.GlyphClusters.IsEmpty)
+ {
+ return glyphCount;
+ }
+
+ var firstCluster = glyphRun.GlyphClusters[0];
+
+ var lastCluster = glyphRun.GlyphClusters[glyphCount];
+
+ return lastCluster - firstCluster;
+ }
+
+ ///
+ /// Creates an ellipsis.
+ ///
+ /// The text run properties.
+ ///
+ private static ShapedTextCharacters CreateEllipsisRun(TextRunProperties properties)
+ {
+ var formatterImpl = AvaloniaLocator.Current.GetService();
+
+ var glyphRun = formatterImpl.ShapeText(s_ellipsis, properties.Typeface, properties.FontRenderingEmSize,
+ properties.CultureInfo);
+
+ return new ShapedTextCharacters(glyphRun, properties);
+ }
+
+ ///
+ /// Gets the text range that is covered by the text runs.
+ ///
+ /// The text runs.
+ /// The text range that is covered by the text runs.
+ private static TextRange GetTextRange(IReadOnlyList textRuns)
+ {
+ if (textRuns is null || textRuns.Count == 0)
+ {
+ return new TextRange();
+ }
+
+ var firstTextRun = textRuns[0];
+
+ if (textRuns.Count == 1)
+ {
+ return new TextRange(firstTextRun.Text.Start, firstTextRun.Text.Length);
+ }
+
+ var start = firstTextRun.Text.Start;
+
+ var end = textRuns[textRuns.Count - 1].Text.End + 1;
+
+ return new TextRange(start, end - start);
+ }
+
+ ///
+ /// Split a sequence of runs into two segments at specified length.
+ ///
+ /// The text run's.
+ /// The length to split at.
+ /// The split text runs.
+ private static SplitTextRunsResult SplitTextRuns(IReadOnlyList textRuns, int length)
+ {
+ var currentLength = 0;
+
+ for (var i = 0; i < textRuns.Count; i++)
+ {
+ var currentRun = textRuns[i];
+
+ if (currentLength + currentRun.GlyphRun.Characters.Length < length)
+ {
+ currentLength += currentRun.GlyphRun.Characters.Length;
+ continue;
+ }
+
+ var firstCount = currentRun.GlyphRun.Characters.Length >= 1 ? i + 1 : i;
+
+ var first = new ShapedTextCharacters[firstCount];
+
+ if (firstCount > 1)
+ {
+ for (var j = 0; j < i; j++)
+ {
+ first[j] = textRuns[j];
+ }
+ }
+
+ var secondCount = textRuns.Count - firstCount;
+
+ if (currentLength + currentRun.GlyphRun.Characters.Length == length)
+ {
+ var second = new ShapedTextCharacters[secondCount];
+
+ var offset = currentRun.GlyphRun.Characters.Length > 1 ? 1 : 0;
+
+ if (secondCount > 0)
+ {
+ for (var j = 0; j < secondCount; j++)
+ {
+ second[j] = textRuns[i + j + offset];
+ }
+ }
+
+ first[i] = currentRun;
+
+ return new SplitTextRunsResult(first, second);
+ }
+ else
+ {
+ secondCount++;
+
+ var second = new ShapedTextCharacters[secondCount];
+
+ if (secondCount > 0)
+ {
+ for (var j = 1; j < secondCount; j++)
+ {
+ second[j] = textRuns[i + j];
+ }
+ }
+
+ var split = currentRun.Split(length - currentLength);
+
+ first[i] = split.First;
+
+ second[0] = split.Second;
+
+ return new SplitTextRunsResult(first, second);
+ }
+ }
+
+ return new SplitTextRunsResult(textRuns, null);
+ }
+
+ private readonly struct SplitTextRunsResult
+ {
+ public SplitTextRunsResult(IReadOnlyList first, IReadOnlyList second)
+ {
+ First = first;
+
+ Second = second;
+ }
+
+ ///
+ /// Gets the first text runs.
+ ///
+ ///
+ /// The first text runs.
+ ///
+ public IReadOnlyList First { get; }
+
+ ///
+ /// Gets the second text runs.
+ ///
+ ///
+ /// The second text runs.
+ ///
+ public IReadOnlyList Second { get; }
+ }
+
+ private struct TextRunEnumerator
+ {
+ private readonly ITextSource _textSource;
+ private int _pos;
+
+ public TextRunEnumerator(ITextSource textSource, int firstTextSourceIndex)
+ {
+ _textSource = textSource;
+ _pos = firstTextSourceIndex;
+ Current = null;
+ }
+
+ // ReSharper disable once MemberHidesStaticFromOuterClass
+ public TextRun Current { get; private set; }
+
+ public bool MoveNext()
+ {
+ Current = _textSource.GetTextRun(_pos);
+
+ if (Current is null)
+ {
+ return false;
+ }
+
+ if (Current.TextSourceLength == 0)
+ {
+ return false;
+ }
+
+ _pos += Current.TextSourceLength;
+
+ return !(Current is TextEndOfLine);
+ }
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextLayout.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextLayout.cs
index 0292398782..54745144c8 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextLayout.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextLayout.cs
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting.Unicode;
-using Avalonia.Platform;
using Avalonia.Utilities;
-using Avalonia.Utility;
+using Avalonia.Platform;
namespace Avalonia.Media.TextFormatting
{
@@ -14,11 +12,11 @@ namespace Avalonia.Media.TextFormatting
///
public class TextLayout
{
- private static readonly ReadOnlySlice s_empty = new ReadOnlySlice(new[] { '\u200B' });
+ private static readonly char[] s_empty = { '\u200B' };
private readonly ReadOnlySlice _text;
private readonly TextParagraphProperties _paragraphProperties;
- private readonly IReadOnlyList _textStyleOverrides;
+ private readonly IReadOnlyList> _textStyleOverrides;
///
/// Initializes a new instance of the class.
@@ -33,6 +31,7 @@ namespace Avalonia.Media.TextFormatting
/// The text decorations.
/// The maximum width.
/// The maximum height.
+ /// The height of each line of text.
/// The maximum number of text lines.
/// The text style overrides.
public TextLayout(
@@ -46,18 +45,22 @@ namespace Avalonia.Media.TextFormatting
TextDecorationCollection textDecorations = null,
double maxWidth = double.PositiveInfinity,
double maxHeight = double.PositiveInfinity,
+ double lineHeight = double.NaN,
int maxLines = 0,
- IReadOnlyList textStyleOverrides = null)
+ IReadOnlyList> textStyleOverrides = null)
{
_text = string.IsNullOrEmpty(text) ?
new ReadOnlySlice() :
new ReadOnlySlice(text.AsMemory());
_paragraphProperties =
- CreateTextParagraphProperties(typeface, fontSize, foreground, textAlignment, textWrapping, textTrimming, textDecorations?.ToImmutable());
+ CreateTextParagraphProperties(typeface, fontSize, foreground, textAlignment, textWrapping, textTrimming,
+ textDecorations, lineHeight);
_textStyleOverrides = textStyleOverrides;
+ LineHeight = lineHeight;
+
MaxWidth = maxWidth;
MaxHeight = maxHeight;
@@ -67,22 +70,29 @@ namespace Avalonia.Media.TextFormatting
UpdateLayout();
}
+ ///
+ /// Gets or sets the height of each line of text.
+ ///
+ ///
+ /// A value of NaN (equivalent to an attribute value of "Auto") indicates that the line height
+ /// is determined automatically from the current font characteristics. The default is NaN.
+ ///
+ public double LineHeight { get; }
+
///
/// Gets the maximum width.
///
public double MaxWidth { get; }
-
///
/// Gets the maximum height.
///
public double MaxHeight { get; }
-
///
/// Gets the maximum number of text lines.
///
- public double MaxLines { get; }
+ public int MaxLines { get; }
///
/// Gets the text lines.
@@ -93,19 +103,19 @@ namespace Avalonia.Media.TextFormatting
public IReadOnlyList TextLines { get; private set; }
///
- /// Gets the bounds of the layout.
+ /// Gets the size of the layout.
///
///
/// The bounds.
///
- public Rect Bounds { get; private set; }
+ public Size Size { get; private set; }
///
/// Draws the text layout.
///
/// The drawing context.
/// The origin.
- public void Draw(IDrawingContextImpl context, Point origin)
+ public void Draw(DrawingContext context, Point origin)
{
if (!TextLines.Any())
{
@@ -116,7 +126,10 @@ namespace Avalonia.Media.TextFormatting
foreach (var textLine in TextLines)
{
- textLine.Draw(context, new Point(origin.X, currentY));
+ var offsetX = TextLine.GetParagraphOffsetX(textLine.LineMetrics.Size.Width, Size.Width,
+ _paragraphProperties.TextAlignment);
+
+ textLine.Draw(context, new Point(origin.X + offsetX, currentY));
currentY += textLine.LineMetrics.Size.Height;
}
@@ -132,36 +145,32 @@ namespace Avalonia.Media.TextFormatting
/// The text wrapping.
/// The text trimming.
/// The text decorations.
+ /// The height of each line of text.
///
private static TextParagraphProperties CreateTextParagraphProperties(Typeface typeface, double fontSize,
IBrush foreground, TextAlignment textAlignment, TextWrapping textWrapping, TextTrimming textTrimming,
- ImmutableTextDecoration[] textDecorations)
+ TextDecorationCollection textDecorations, double lineHeight)
{
- var textRunStyle = new TextStyle(typeface, fontSize, foreground, textDecorations);
+ var textRunStyle = new GenericTextRunProperties(typeface, fontSize, textDecorations, foreground);
- return new TextParagraphProperties(textRunStyle, textAlignment, textWrapping, textTrimming);
+ return new GenericTextParagraphProperties(textRunStyle, textAlignment, textWrapping, textTrimming,
+ lineHeight);
}
///
/// Updates the current bounds.
///
/// The text line.
- /// The left.
- /// The right.
- /// The bottom.
- private static void UpdateBounds(TextLine textLine, ref double left, ref double right, ref double bottom)
+ /// The current width.
+ /// The current height.
+ private static void UpdateBounds(TextLine textLine, ref double width, ref double height)
{
- if (right < textLine.LineMetrics.BaselineOrigin.X + textLine.LineMetrics.Size.Width)
- {
- right = textLine.LineMetrics.BaselineOrigin.X + textLine.LineMetrics.Size.Width;
- }
-
- if (left < textLine.LineMetrics.BaselineOrigin.X)
+ if (width < textLine.LineMetrics.Size.Width)
{
- left = textLine.LineMetrics.BaselineOrigin.X;
+ width = textLine.LineMetrics.Size.Width;
}
- bottom += textLine.LineMetrics.Size.Height;
+ height += textLine.LineMetrics.Size.Height;
}
///
@@ -170,14 +179,15 @@ namespace Avalonia.Media.TextFormatting
/// The empty text line.
private TextLine CreateEmptyTextLine(int startingIndex)
{
- var textFormat = _paragraphProperties.DefaultTextStyle.TextFormat;
+ var properties = _paragraphProperties.DefaultTextRunProperties;
- var glyphRun = TextShaper.Current.ShapeText(s_empty, textFormat);
+ var glyphRun = TextShaper.Current.ShapeText(new ReadOnlySlice(s_empty, startingIndex, 1),
+ properties.Typeface, properties.FontRenderingEmSize, properties.CultureInfo);
- var textRuns = new[] { new ShapedTextRun(glyphRun, _paragraphProperties.DefaultTextStyle) };
+ var textRuns = new[] { new ShapedTextCharacters(glyphRun, _paragraphProperties.DefaultTextRunProperties) };
- return new SimpleTextLine(new TextPointer(startingIndex, 0), textRuns,
- TextLineMetrics.Create(textRuns, MaxWidth, _paragraphProperties.TextAlignment));
+ return new TextLineImpl(textRuns,
+ TextLineMetrics.Create(textRuns, new TextRange(startingIndex, 1), MaxWidth, _paragraphProperties));
}
///
@@ -191,110 +201,76 @@ namespace Avalonia.Media.TextFormatting
TextLines = new List { textLine };
- Bounds = new Rect(textLine.LineMetrics.BaselineOrigin.X, 0, 0, textLine.LineMetrics.Size.Height);
+ Size = new Size(0, textLine.LineMetrics.Size.Height);
}
else
{
var textLines = new List();
- double left = 0.0, right = 0.0, bottom = 0.0;
-
- var lineBreaker = new LineBreakEnumerator(_text);
+ double width = 0.0, height = 0.0;
var currentPosition = 0;
+ var textSource = new FormattedTextSource(_text,
+ _paragraphProperties.DefaultTextRunProperties, _textStyleOverrides);
+
+ TextLineBreak previousLineBreak = null;
+
while (currentPosition < _text.Length && (MaxLines == 0 || textLines.Count < MaxLines))
{
- int length;
+ var textLine = TextFormatter.Current.FormatLine(textSource, currentPosition, MaxWidth,
+ _paragraphProperties, previousLineBreak);
- if (lineBreaker.MoveNext())
- {
- if (!lineBreaker.Current.Required)
- {
- continue;
- }
+ previousLineBreak = textLine.LineBreak;
- length = lineBreaker.Current.PositionWrap - currentPosition;
+ textLines.Add(textLine);
- if (currentPosition + length < _text.Length)
- {
- //The line breaker isn't treating \n\r as a pair so we have to fix that here.
- if (_text[lineBreaker.Current.PositionMeasure] == '\n'
- && _text[lineBreaker.Current.PositionWrap] == '\r')
- {
- length++;
- }
- }
- }
- else
+ UpdateBounds(textLine, ref width, ref height);
+
+ if (!double.IsPositiveInfinity(MaxHeight) && height > MaxHeight)
{
- length = _text.Length - currentPosition;
+ break;
}
- var remainingLength = length;
+ currentPosition += textLine.TextRange.Length;
- while (remainingLength > 0 && (MaxLines == 0 || textLines.Count < MaxLines))
+ if (currentPosition != _text.Length || textLine.LineBreak == null)
{
- var textSlice = _text.AsSlice(currentPosition, remainingLength);
-
- var textSource = new FormattedTextSource(textSlice, _paragraphProperties.DefaultTextStyle, _textStyleOverrides);
-
- var textLine = TextFormatter.Current.FormatLine(textSource, 0, MaxWidth, _paragraphProperties);
-
- UpdateBounds(textLine, ref left, ref right, ref bottom);
-
- textLines.Add(textLine);
-
- if (!double.IsPositiveInfinity(MaxHeight) && bottom + textLine.LineMetrics.Size.Height > MaxHeight)
- {
- currentPosition = _text.Length;
- break;
- }
-
- if (_paragraphProperties.TextTrimming != TextTrimming.None)
- {
- currentPosition += remainingLength;
-
- break;
- }
-
- remainingLength -= textLine.Text.Length;
-
- currentPosition += textLine.Text.Length;
+ continue;
}
- }
- if (lineBreaker.Current.Required && currentPosition == _text.Length)
- {
var emptyTextLine = CreateEmptyTextLine(currentPosition);
- UpdateBounds(emptyTextLine, ref left, ref right, ref bottom);
-
textLines.Add(emptyTextLine);
}
- Bounds = new Rect(left, 0, right, bottom);
+ Size = new Size(width, height);
TextLines = textLines;
}
}
- private struct FormattedTextSource : ITextSource
+ private readonly struct FormattedTextSource : ITextSource
{
private readonly ReadOnlySlice _text;
- private readonly TextStyle _defaultStyle;
- private readonly IReadOnlyList _textStyleOverrides;
+ private readonly TextRunProperties _defaultProperties;
+ private readonly IReadOnlyList> _textModifier;
- public FormattedTextSource(ReadOnlySlice text, TextStyle defaultStyle,
- IReadOnlyList textStyleOverrides)
+ public FormattedTextSource(ReadOnlySlice text, TextRunProperties defaultProperties,
+ IReadOnlyList> textModifier)
{
_text = text;
- _defaultStyle = defaultStyle;
- _textStyleOverrides = textStyleOverrides;
+ _defaultProperties = defaultProperties;
+ _textModifier = textModifier;
}
public TextRun GetTextRun(int textSourceIndex)
{
+ if (textSourceIndex > _text.End)
+ {
+ return new TextEndOfLine();
+ }
+
var runText = _text.Skip(textSourceIndex);
if (runText.IsEmpty)
@@ -302,30 +278,29 @@ namespace Avalonia.Media.TextFormatting
return new TextEndOfLine();
}
- var textStyleRun = CreateTextStyleRunWithOverride(runText, _defaultStyle, _textStyleOverrides);
+ var textStyleRun = CreateTextStyleRun(runText, _defaultProperties, _textModifier);
- return new TextCharacters(runText.Take(textStyleRun.TextPointer.Length), textStyleRun.Style);
+ return new TextCharacters(runText.Take(textStyleRun.Length), textStyleRun.Value);
}
///
- /// Creates a text style run that has overrides applied. Only overrides with equal TextStyle.
- /// If optimizeForShaping is true Foreground is ignored.
+ /// Creates a span of text run properties that has modifier applied.
///
- /// The text to create the run for.
- /// The default text style for segments that don't have an override.
- /// The text style overrides.
+ /// The text to create the properties for.
+ /// The default text properties.
+ /// The text properties modifier.
///
/// The created text style run.
///
- private static TextStyleRun CreateTextStyleRunWithOverride(ReadOnlySlice text,
- TextStyle defaultTextStyle, IReadOnlyList textStyleOverrides)
+ private static ValueSpan CreateTextStyleRun(ReadOnlySlice text,
+ TextRunProperties defaultProperties, IReadOnlyList> textModifier)
{
- if(textStyleOverrides == null || textStyleOverrides.Count == 0)
+ if (textModifier == null || textModifier.Count == 0)
{
- return new TextStyleRun(new TextPointer(text.Start, text.Length), defaultTextStyle);
+ return new ValueSpan(text.Start, text.Length, defaultProperties);
}
- var currentTextStyle = defaultTextStyle;
+ var currentProperties = defaultProperties;
var hasOverride = false;
@@ -333,35 +308,34 @@ namespace Avalonia.Media.TextFormatting
var length = 0;
- for (; i < textStyleOverrides.Count; i++)
+ for (; i < textModifier.Count; i++)
{
- var styleOverride = textStyleOverrides[i];
+ var propertiesOverride = textModifier[i];
- var textPointer = styleOverride.TextPointer;
+ var textRange = new TextRange(propertiesOverride.Start, propertiesOverride.Length);
- if (textPointer.End < text.Start)
+ if (textRange.End < text.Start)
{
continue;
}
- if (textPointer.Start > text.End)
+ if (textRange.Start > text.End)
{
length = text.Length;
break;
}
- if (textPointer.Start > text.Start)
+ if (textRange.Start > text.Start)
{
- if (styleOverride.Style.TextFormat != currentTextStyle.TextFormat ||
- !currentTextStyle.Foreground.Equals(styleOverride.Style.Foreground))
+ if (propertiesOverride.Value != currentProperties)
{
- length = Math.Min(Math.Abs(textPointer.Start - text.Start), text.Length);
+ length = Math.Min(Math.Abs(textRange.Start - text.Start), text.Length);
break;
}
}
- length += Math.Min(text.Length - length, textPointer.Length);
+ length += Math.Min(text.Length - length, textRange.Length);
if (hasOverride)
{
@@ -370,13 +344,12 @@ namespace Avalonia.Media.TextFormatting
hasOverride = true;
- currentTextStyle = styleOverride.Style;
+ currentProperties = propertiesOverride.Value;
}
- if (length < text.Length && i == textStyleOverrides.Count)
+ if (length < text.Length && i == textModifier.Count)
{
- if (currentTextStyle.Foreground.Equals(defaultTextStyle.Foreground) &&
- currentTextStyle.TextFormat == defaultTextStyle.TextFormat)
+ if (currentProperties == defaultProperties)
{
length = text.Length;
}
@@ -387,7 +360,7 @@ namespace Avalonia.Media.TextFormatting
text = text.Take(length);
}
- return new TextStyleRun(new TextPointer(text.Start, length), currentTextStyle);
+ return new ValueSpan(text.Start, length, currentProperties);
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextLine.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextLine.cs
index a0f7b44882..c3b7dfc77a 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextLine.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextLine.cs
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-using Avalonia.Platform;
namespace Avalonia.Media.TextFormatting
{
@@ -9,12 +8,12 @@ namespace Avalonia.Media.TextFormatting
public abstract class TextLine
{
///
- /// Gets the text.
+ /// Gets the text range that is covered by the line.
///
///
- /// The text pointer.
+ /// The text range that is covered by the line.
///
- public abstract TextPointer Text { get; }
+ public abstract TextRange TextRange { get; }
///
/// Gets the text runs.
@@ -32,12 +31,20 @@ namespace Avalonia.Media.TextFormatting
///
public abstract TextLineMetrics LineMetrics { get; }
+ ///
+ /// Gets the state of the line when broken by line breaking process.
+ ///
+ ///
+ /// A value that represents the line break.
+ ///
+ public abstract TextLineBreak LineBreak { get; }
+
///
/// Draws the at the given origin.
///
/// The drawing context.
/// The origin.
- public abstract void Draw(IDrawingContextImpl drawingContext, Point origin);
+ public abstract void Draw(DrawingContext drawingContext, Point origin);
///
/// Client to get the character hit corresponding to the specified
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextLineBreak.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextLineBreak.cs
new file mode 100644
index 0000000000..c24454cb76
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextLineBreak.cs
@@ -0,0 +1,17 @@
+using System.Collections.Generic;
+
+namespace Avalonia.Media.TextFormatting
+{
+ public class TextLineBreak
+ {
+ public TextLineBreak(IReadOnlyList remainingCharacters)
+ {
+ RemainingCharacters = remainingCharacters;
+ }
+
+ ///
+ /// Get the remaining shaped characters that were split up by the during the formatting process.
+ ///
+ public IReadOnlyList RemainingCharacters { get; }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextLineImpl.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextLineImpl.cs
new file mode 100644
index 0000000000..a1a9b50793
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextLineImpl.cs
@@ -0,0 +1,234 @@
+using System.Collections.Generic;
+
+namespace Avalonia.Media.TextFormatting
+{
+ internal class TextLineImpl : TextLine
+ {
+ private readonly IReadOnlyList _textRuns;
+
+ public TextLineImpl(IReadOnlyList textRuns, TextLineMetrics lineMetrics,
+ TextLineBreak lineBreak = null)
+ {
+ _textRuns = textRuns;
+ LineMetrics = lineMetrics;
+ LineBreak = lineBreak;
+ }
+
+ ///
+ public override TextRange TextRange => LineMetrics.TextRange;
+
+ ///
+ public override IReadOnlyList TextRuns => _textRuns;
+
+ ///
+ public override TextLineMetrics LineMetrics { get; }
+
+ ///
+ public override TextLineBreak LineBreak { get; }
+
+ ///
+ public override void Draw(DrawingContext drawingContext, Point origin)
+ {
+ var currentX = origin.X;
+
+ foreach (var textRun in _textRuns)
+ {
+ var baselineOrigin = new Point(currentX, origin.Y + LineMetrics.TextBaseline);
+
+ textRun.Draw(drawingContext, baselineOrigin);
+
+ currentX += textRun.Bounds.Width;
+ }
+ }
+
+ ///
+ public override CharacterHit GetCharacterHitFromDistance(double distance)
+ {
+ if (distance < 0)
+ {
+ // hit happens before the line, return the first position
+ return new CharacterHit(TextRange.Start);
+ }
+
+ // process hit that happens within the line
+ var characterHit = new CharacterHit();
+
+ foreach (var run in _textRuns)
+ {
+ characterHit = run.GlyphRun.GetCharacterHitFromDistance(distance, out _);
+
+ if (distance <= run.Bounds.Width)
+ {
+ break;
+ }
+
+ distance -= run.Bounds.Width;
+ }
+
+ return characterHit;
+ }
+
+ ///
+ public override double GetDistanceFromCharacterHit(CharacterHit characterHit)
+ {
+ return DistanceFromCodepointIndex(characterHit.FirstCharacterIndex + (characterHit.TrailingLength != 0 ? 1 : 0));
+ }
+
+ ///
+ public override CharacterHit GetNextCaretCharacterHit(CharacterHit characterHit)
+ {
+ if (TryFindNextCharacterHit(characterHit, out var nextCharacterHit))
+ {
+ return nextCharacterHit;
+ }
+
+ return new CharacterHit(TextRange.End); // Can't move, we're after the last character
+ }
+
+ ///
+ public override CharacterHit GetPreviousCaretCharacterHit(CharacterHit characterHit)
+ {
+ if (TryFindPreviousCharacterHit(characterHit, out var previousCharacterHit))
+ {
+ return previousCharacterHit;
+ }
+
+ return new CharacterHit(TextRange.Start); // Can't move, we're before the first character
+ }
+
+ ///
+ public override CharacterHit GetBackspaceCaretCharacterHit(CharacterHit characterHit)
+ {
+ // same operation as move-to-previous
+ return GetPreviousCaretCharacterHit(characterHit);
+ }
+
+ ///
+ /// Get distance from line start to the specified codepoint index.
+ ///
+ private double DistanceFromCodepointIndex(int codepointIndex)
+ {
+ var currentDistance = 0.0;
+
+ foreach (var textRun in _textRuns)
+ {
+ if (codepointIndex > textRun.Text.End)
+ {
+ currentDistance += textRun.Bounds.Width;
+
+ continue;
+ }
+
+ return currentDistance + textRun.GlyphRun.GetDistanceFromCharacterHit(new CharacterHit(codepointIndex));
+ }
+
+ return currentDistance;
+ }
+
+ ///
+ /// Tries to find the next character hit.
+ ///
+ /// The current character hit.
+ /// The next character hit.
+ ///
+ private bool TryFindNextCharacterHit(CharacterHit characterHit, out CharacterHit nextCharacterHit)
+ {
+ nextCharacterHit = characterHit;
+
+ var codepointIndex = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
+
+ if (codepointIndex >= TextRange.Start + TextRange.Length)
+ {
+ return false; // Cannot go forward anymore
+ }
+
+ var runIndex = GetRunIndexAtCodepointIndex(codepointIndex);
+
+ while (runIndex < TextRuns.Count)
+ {
+ var run = _textRuns[runIndex];
+
+ nextCharacterHit = run.GlyphRun.FindNearestCharacterHit(characterHit.FirstCharacterIndex + characterHit.TrailingLength, out _);
+
+ if (codepointIndex <= nextCharacterHit.FirstCharacterIndex + nextCharacterHit.TrailingLength)
+ {
+ return true;
+ }
+
+ runIndex++;
+ }
+
+ return false;
+ }
+
+ ///
+ /// Tries to find the previous character hit.
+ ///
+ /// The current character hit.
+ /// The previous character hit.
+ ///
+ private bool TryFindPreviousCharacterHit(CharacterHit characterHit, out CharacterHit previousCharacterHit)
+ {
+ previousCharacterHit = characterHit;
+
+ var codepointIndex = characterHit.FirstCharacterIndex + characterHit.TrailingLength;
+
+ if (codepointIndex < TextRange.Start)
+ {
+ return false; // Cannot go backward anymore.
+ }
+
+ var runIndex = GetRunIndexAtCodepointIndex(codepointIndex);
+
+ while (runIndex >= 0)
+ {
+ var run = _textRuns[runIndex];
+
+ previousCharacterHit = run.GlyphRun.FindNearestCharacterHit(characterHit.FirstCharacterIndex - 1, out _);
+
+ if (previousCharacterHit.FirstCharacterIndex < codepointIndex)
+ {
+ return true;
+ }
+
+ runIndex--;
+ }
+
+ return false;
+ }
+
+ ///
+ /// Gets the run index of the specified codepoint index.
+ ///
+ /// The codepoint index.
+ /// The text run index.
+ private int GetRunIndexAtCodepointIndex(int codepointIndex)
+ {
+ if (codepointIndex >= TextRange.End)
+ {
+ return _textRuns.Count - 1;
+ }
+
+ if (codepointIndex <= 0)
+ {
+ return 0;
+ }
+
+ var runIndex = 0;
+
+ while (runIndex < _textRuns.Count)
+ {
+ var run = _textRuns[runIndex];
+
+ if (run.Text.End > codepointIndex)
+ {
+ return runIndex;
+ }
+
+ runIndex++;
+ }
+
+ return runIndex;
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextLineMetrics.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextLineMetrics.cs
index 096305c09c..2f7809ff35 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextLineMetrics.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextLineMetrics.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting
{
@@ -8,38 +9,20 @@ namespace Avalonia.Media.TextFormatting
///
public readonly struct TextLineMetrics
{
- public TextLineMetrics(double width, double xOrigin, double ascent, double descent, double lineGap)
+ public TextLineMetrics(Size size, double textBaseline, TextRange textRange)
{
- Ascent = ascent;
- Descent = descent;
- LineGap = lineGap;
- Size = new Size(width, descent - ascent + lineGap);
- BaselineOrigin = new Point(xOrigin, -ascent);
+ Size = size;
+ TextBaseline = textBaseline;
+ TextRange = textRange;
}
///
- /// Gets the overall recommended distance above the baseline.
+ /// Gets the text range that is covered by the text line.
///
///
- /// The ascent.
+ /// The text range that is covered by the text line.
///
- public double Ascent { get; }
-
- ///
- /// Gets the overall recommended distance under the baseline.
- ///
- ///
- /// The descent.
- ///
- public double Descent { get; }
-
- ///
- /// Gets the overall recommended additional space between two lines of text.
- ///
- ///
- /// The leading.
- ///
- public double LineGap { get; }
+ public TextRange TextRange { get; }
///
/// Gets the size of the text line.
@@ -50,21 +33,20 @@ namespace Avalonia.Media.TextFormatting
public Size Size { get; }
///
- /// Gets the baseline origin.
+ /// Gets the distance from the top to the baseline of the line of text.
///
- ///
- /// The baseline origin.
- ///
- public Point BaselineOrigin { get; }
+ public double TextBaseline { get; }
///
/// Creates the text line metrics.
///
/// The text runs.
+ /// The text range that is covered by the text line.
/// The paragraph width.
- /// The text alignment.
+ /// The text alignment.
///
- public static TextLineMetrics Create(IEnumerable textRuns, double paragraphWidth, TextAlignment textAlignment)
+ public static TextLineMetrics Create(IEnumerable textRuns, TextRange textRange, double paragraphWidth,
+ TextParagraphProperties paragraphProperties)
{
var lineWidth = 0.0;
var ascent = 0.0;
@@ -73,31 +55,35 @@ namespace Avalonia.Media.TextFormatting
foreach (var textRun in textRuns)
{
- var shapedRun = (ShapedTextRun)textRun;
+ var shapedRun = (ShapedTextCharacters)textRun;
- lineWidth += shapedRun.Bounds.Width;
+ var fontMetrics =
+ new FontMetrics(shapedRun.Properties.Typeface, shapedRun.Properties.FontRenderingEmSize);
- var textFormat = textRun.Style.TextFormat;
+ lineWidth += shapedRun.Bounds.Width;
- if (ascent > textRun.Style.TextFormat.FontMetrics.Ascent)
+ if (ascent > fontMetrics.Ascent)
{
- ascent = textFormat.FontMetrics.Ascent;
+ ascent = fontMetrics.Ascent;
}
- if (descent < textFormat.FontMetrics.Descent)
+ if (descent < fontMetrics.Descent)
{
- descent = textFormat.FontMetrics.Descent;
+ descent = fontMetrics.Descent;
}
- if (lineGap < textFormat.FontMetrics.LineGap)
+ if (lineGap < fontMetrics.LineGap)
{
- lineGap = textFormat.FontMetrics.LineGap;
+ lineGap = fontMetrics.LineGap;
}
}
- var xOrigin = TextLine.GetParagraphOffsetX(lineWidth, paragraphWidth, textAlignment);
+ var size = new Size(lineWidth,
+ double.IsNaN(paragraphProperties.LineHeight) || MathUtilities.IsZero(paragraphProperties.LineHeight) ?
+ descent - ascent + lineGap :
+ paragraphProperties.LineHeight);
- return new TextLineMetrics(lineWidth, xOrigin, ascent, descent, lineGap);
+ return new TextLineMetrics(size, -ascent, textRange);
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextParagraphProperties.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextParagraphProperties.cs
index 1368f1777a..39eb695404 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextParagraphProperties.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextParagraphProperties.cs
@@ -3,38 +3,37 @@
///
/// Provides a set of properties that are used during the paragraph layout.
///
- public readonly struct TextParagraphProperties
+ public abstract class TextParagraphProperties
{
- public TextParagraphProperties(
- TextStyle defaultTextStyle,
- TextAlignment textAlignment = TextAlignment.Left,
- TextWrapping textWrapping = TextWrapping.NoWrap,
- TextTrimming textTrimming = TextTrimming.None)
- {
- DefaultTextStyle = defaultTextStyle;
- TextAlignment = textAlignment;
- TextWrapping = textWrapping;
- TextTrimming = textTrimming;
- }
+ ///
+ /// Gets the text alignment.
+ ///
+ public abstract TextAlignment TextAlignment { get; }
///
/// Gets the default text style.
///
- public TextStyle DefaultTextStyle { get; }
+ public abstract TextRunProperties DefaultTextRunProperties { get; }
///
- /// Gets the text alignment.
+ /// If not null, text decorations to apply to all runs in the line. This is in addition
+ /// to any text decorations specified by the TextRunProperties for individual text runs.
///
- public TextAlignment TextAlignment { get; }
+ public virtual TextDecorationCollection TextDecorations => null;
///
/// Gets the text wrapping.
///
- public TextWrapping TextWrapping { get; }
+ public abstract TextWrapping TextWrapping { get; }
///
/// Gets the text trimming.
///
- public TextTrimming TextTrimming { get; }
+ public abstract TextTrimming TextTrimming { get; }
+
+ ///
+ /// Paragraph's line height
+ ///
+ public abstract double LineHeight { get; }
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextPointer.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextRange.cs
similarity index 73%
rename from src/Avalonia.Visuals/Media/TextFormatting/TextPointer.cs
rename to src/Avalonia.Visuals/Media/TextFormatting/TextRange.cs
index 65d5c04b4c..1177c758f4 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextPointer.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextRange.cs
@@ -5,9 +5,9 @@ namespace Avalonia.Media.TextFormatting
///
/// References a portion of a text buffer.
///
- public readonly struct TextPointer
+ public readonly struct TextRange
{
- public TextPointer(int start, int length)
+ public TextRange(int start, int length)
{
Start = start;
Length = length;
@@ -41,30 +41,30 @@ namespace Avalonia.Media.TextFormatting
/// Returns a specified number of contiguous elements from the start of the slice.
///
/// The number of elements to return.
- /// A that contains the specified number of elements from the start of this slice.
- public TextPointer Take(int length)
+ /// A that contains the specified number of elements from the start of this slice.
+ public TextRange Take(int length)
{
if (length > Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
- return new TextPointer(Start, length);
+ return new TextRange(Start, length);
}
///
/// Bypasses a specified number of elements in the slice and then returns the remaining elements.
///
/// The number of elements to skip before returning the remaining elements.
- /// A that contains the elements that occur after the specified index in this slice.
- public TextPointer Skip(int length)
+ /// A that contains the elements that occur after the specified index in this slice.
+ public TextRange Skip(int length)
{
if (length > Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
- return new TextPointer(Start + length, Length - length);
+ return new TextRange(Start + length, Length - length);
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextRun.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextRun.cs
index 28b83333b9..c15a771755 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextRun.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextRun.cs
@@ -1,5 +1,5 @@
using System.Diagnostics;
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting
{
@@ -9,15 +9,22 @@ namespace Avalonia.Media.TextFormatting
[DebuggerTypeProxy(typeof(TextRunDebuggerProxy))]
public abstract class TextRun
{
+ public static readonly int DefaultTextSourceLength = 1;
+
+ ///
+ /// Gets the text source length.
+ ///
+ public virtual int TextSourceLength => DefaultTextSourceLength;
+
///
/// Gets the text run's text.
///
- public ReadOnlySlice Text { get; protected set; }
+ public virtual ReadOnlySlice Text => default;
///
- /// Gets the text run's style.
+ /// A set of properties shared by every characters in the run
///
- public TextStyle Style { get; protected set; }
+ public virtual TextRunProperties Properties => null;
private class TextRunDebuggerProxy
{
@@ -42,7 +49,7 @@ namespace Avalonia.Media.TextFormatting
}
}
- public TextStyle Style => _textRun.Style;
+ public TextRunProperties Properties => _textRun.Properties;
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextRunProperties.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextRunProperties.cs
new file mode 100644
index 0000000000..bbcdfe2d8e
--- /dev/null
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextRunProperties.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Globalization;
+
+namespace Avalonia.Media.TextFormatting
+{
+ ///
+ /// Properties that can change from one run to the next, such as typeface or foreground brush.
+ ///
+ ///
+ /// The client provides a concrete implementation of this abstract run properties class. This
+ /// allows client to implement their run properties the way that fits with their run formatting
+ /// store.
+ ///
+ public abstract class TextRunProperties : IEquatable
+ {
+ ///
+ /// Run typeface
+ ///
+ public abstract Typeface Typeface { get; }
+
+ ///
+ /// Em size of font used to format and display text
+ ///
+ public abstract double FontRenderingEmSize { get; }
+
+ ///
+ /// Run TextDecorations.
+ ///
+ public abstract TextDecorationCollection TextDecorations { get; }
+
+ ///
+ /// Brush used to fill text.
+ ///
+ public abstract IBrush ForegroundBrush { get; }
+
+ ///
+ /// Brush used to paint background of run.
+ ///
+ public abstract IBrush BackgroundBrush { get; }
+
+ ///
+ /// Run text culture.
+ ///
+ public abstract CultureInfo CultureInfo { get; }
+
+ public bool Equals(TextRunProperties other)
+ {
+ if (ReferenceEquals(null, other))
+ return false;
+ if (ReferenceEquals(this, other))
+ return true;
+
+ return Typeface.Equals(other.Typeface) &&
+ FontRenderingEmSize.Equals(other.FontRenderingEmSize)
+ && Equals(TextDecorations, other.TextDecorations) &&
+ Equals(ForegroundBrush, other.ForegroundBrush) &&
+ Equals(BackgroundBrush, other.BackgroundBrush) &&
+ Equals(CultureInfo, other.CultureInfo);
+ }
+
+ public override bool Equals(object obj)
+ {
+ return ReferenceEquals(this, obj) || obj is TextRunProperties other && Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ var hashCode = (Typeface != null ? Typeface.GetHashCode() : 0);
+ hashCode = (hashCode * 397) ^ FontRenderingEmSize.GetHashCode();
+ hashCode = (hashCode * 397) ^ (TextDecorations != null ? TextDecorations.GetHashCode() : 0);
+ hashCode = (hashCode * 397) ^ (ForegroundBrush != null ? ForegroundBrush.GetHashCode() : 0);
+ hashCode = (hashCode * 397) ^ (BackgroundBrush != null ? BackgroundBrush.GetHashCode() : 0);
+ hashCode = (hashCode * 397) ^ (CultureInfo != null ? CultureInfo.GetHashCode() : 0);
+ return hashCode;
+ }
+ }
+
+ public static bool operator ==(TextRunProperties left, TextRunProperties right)
+ {
+ return Equals(left, right);
+ }
+
+ public static bool operator !=(TextRunProperties left, TextRunProperties right)
+ {
+ return !Equals(left, right);
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextShaper.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextShaper.cs
index eb3a4129bc..a02ace408f 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextShaper.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/TextShaper.cs
@@ -1,6 +1,7 @@
using System;
+using System.Globalization;
using Avalonia.Platform;
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting
{
@@ -44,9 +45,10 @@ namespace Avalonia.Media.TextFormatting
}
///
- public GlyphRun ShapeText(ReadOnlySlice text, TextFormat textFormat)
+ public GlyphRun ShapeText(ReadOnlySlice text, Typeface typeface, double fontRenderingEmSize,
+ CultureInfo culture)
{
- return _platformImpl.ShapeText(text, textFormat);
+ return _platformImpl.ShapeText(text, typeface, fontRenderingEmSize, culture);
}
}
}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextStyle.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextStyle.cs
deleted file mode 100644
index cf52c3ca17..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextStyle.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Avalonia.Media.Immutable;
-
-namespace Avalonia.Media.TextFormatting
-{
- ///
- /// Unique text formatting properties that effect the styling of a text.
- ///
- public readonly struct TextStyle
- {
- public TextStyle(Typeface typeface, double fontRenderingEmSize = 12, IBrush foreground = null,
- ImmutableTextDecoration[] textDecorations = null)
- : this(new TextFormat(typeface, fontRenderingEmSize), foreground, textDecorations)
- {
- }
-
- public TextStyle(TextFormat textFormat, IBrush foreground = null,
- ImmutableTextDecoration[] textDecorations = null)
- {
- TextFormat = textFormat;
- Foreground = foreground;
- TextDecorations = textDecorations;
- }
-
- ///
- /// Gets the text format.
- ///
- public TextFormat TextFormat { get; }
-
- ///
- /// Gets the foreground.
- ///
- public IBrush Foreground { get; }
-
- ///
- /// Gets the text decorations.
- ///
- public ImmutableTextDecoration[] TextDecorations { get; }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/TextStyleRun.cs b/src/Avalonia.Visuals/Media/TextFormatting/TextStyleRun.cs
deleted file mode 100644
index 55f8999182..0000000000
--- a/src/Avalonia.Visuals/Media/TextFormatting/TextStyleRun.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Avalonia.Media.TextFormatting
-{
- ///
- /// Represents a text run's style and is used during the layout process of the .
- ///
- public readonly struct TextStyleRun
- {
- public TextStyleRun(TextPointer textPointer, TextStyle style)
- {
- TextPointer = textPointer;
- Style = style;
- }
-
- ///
- /// Gets the text pointer.
- ///
- public TextPointer TextPointer { get; }
-
- ///
- /// Gets the text style.
- ///
- public TextStyle Style { get; }
- }
-}
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Codepoint.cs b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Codepoint.cs
index 94171b7324..20fe345d93 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Codepoint.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Codepoint.cs
@@ -1,4 +1,4 @@
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting.Unicode
{
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/CodepointEnumerator.cs b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/CodepointEnumerator.cs
index 2ff4952cab..9e1f748ebb 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/CodepointEnumerator.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/CodepointEnumerator.cs
@@ -1,4 +1,4 @@
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting.Unicode
{
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Grapheme.cs b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Grapheme.cs
index a6791b4a53..f268340eb9 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Grapheme.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/Grapheme.cs
@@ -1,4 +1,4 @@
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting.Unicode
{
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/GraphemeEnumerator.cs b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/GraphemeEnumerator.cs
index fd7831dfe6..1e4ac8fe0f 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/GraphemeEnumerator.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/GraphemeEnumerator.cs
@@ -4,7 +4,7 @@
// Licensed to The Avalonia Project under MIT License, courtesy of The .NET Foundation.
using System.Runtime.InteropServices;
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting.Unicode
{
diff --git a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/LineBreakEnumerator.cs b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/LineBreakEnumerator.cs
index 25a32bb1a3..26f7721128 100644
--- a/src/Avalonia.Visuals/Media/TextFormatting/Unicode/LineBreakEnumerator.cs
+++ b/src/Avalonia.Visuals/Media/TextFormatting/Unicode/LineBreakEnumerator.cs
@@ -16,7 +16,7 @@
// Ported from: https://github.com/foliojs/linebreak
// Copied from: https://github.com/toptensoftware/RichTextKit
-using Avalonia.Utility;
+using Avalonia.Utilities;
namespace Avalonia.Media.TextFormatting.Unicode
{
diff --git a/src/Avalonia.Visuals/Media/TextWrapping.cs b/src/Avalonia.Visuals/Media/TextWrapping.cs
index 56df3670bd..d649bda23f 100644
--- a/src/Avalonia.Visuals/Media/TextWrapping.cs
+++ b/src/Avalonia.Visuals/Media/TextWrapping.cs
@@ -5,6 +5,13 @@ namespace Avalonia.Media
///
public enum TextWrapping
{
+ ///
+ /// Line-breaking occurs if the line overflows the available block width.
+ /// However, a line may overflow the block width if the line breaking algorithm
+ /// cannot determine a break opportunity, as in the case of a very long word.
+ ///
+ WrapWithOverflow,
+
///
/// Text should not wrap.
///
@@ -15,4 +22,4 @@ namespace Avalonia.Media
///
Wrap
}
-}
\ No newline at end of file
+}
diff --git a/src/Avalonia.Visuals/Media/Typeface.cs b/src/Avalonia.Visuals/Media/Typeface.cs
index 7618598a3f..677e930804 100644
--- a/src/Avalonia.Visuals/Media/Typeface.cs
+++ b/src/Avalonia.Visuals/Media/Typeface.cs
@@ -16,11 +16,11 @@ namespace Avalonia.Media
/// Initializes a new instance of the class.
///
/// The font family.
- /// The font weight.
/// The font style.
+ /// The font weight.
public Typeface([NotNull]FontFamily fontFamily,
- FontWeight weight = FontWeight.Normal,
- FontStyle style = FontStyle.Normal)
+ FontStyle style = FontStyle.Normal,
+ FontWeight weight = FontWeight.Normal)
{
if (weight <= 0)
{
@@ -39,9 +39,9 @@ namespace Avalonia.Media
/// The font style.
/// The font weight.
public Typeface(string fontFamilyName,
- FontWeight weight = FontWeight.Normal,
- FontStyle style = FontStyle.Normal)
- : this(new FontFamily(fontFamilyName), weight, style)
+ FontStyle style = FontStyle.Normal,
+ FontWeight weight = FontWeight.Normal)
+ : this(new FontFamily(fontFamilyName), style, weight)
{
}
diff --git a/src/Avalonia.Visuals/Platform/IDrawingContextWithAcrylicLikeSupport.cs b/src/Avalonia.Visuals/Platform/IDrawingContextWithAcrylicLikeSupport.cs
new file mode 100644
index 0000000000..a3cf0298dd
--- /dev/null
+++ b/src/Avalonia.Visuals/Platform/IDrawingContextWithAcrylicLikeSupport.cs
@@ -0,0 +1,9 @@
+using Avalonia.Media;
+
+namespace Avalonia.Platform
+{
+ public interface IDrawingContextWithAcrylicLikeSupport
+ {
+ void DrawRectangle(IExperimentalAcrylicMaterial material, RoundedRect rect);
+ }
+}
diff --git a/src/Avalonia.Visuals/Platform/IFontManagerImpl.cs b/src/Avalonia.Visuals/Platform/IFontManagerImpl.cs
index 3d0bea8c80..59b08aae0a 100644
--- a/src/Avalonia.Visuals/Platform/IFontManagerImpl.cs
+++ b/src/Avalonia.Visuals/Platform/IFontManagerImpl.cs
@@ -22,15 +22,16 @@ namespace Avalonia.Platform
/// Tries to match a specified character to a typeface that supports specified font properties.
///
/// The codepoint to match against.
- /// The font weight.
/// The font style.
+ /// The font weight.
/// The font family. This is optional and used for fallback lookup.
/// The culture.
/// The matching font key.
///
/// True, if the could match the character to specified parameters, False otherwise.
///
- bool TryMatchCharacter(int codepoint, FontWeight fontWeight, FontStyle fontStyle,
+ bool TryMatchCharacter(int codepoint, FontStyle fontStyle,
+ FontWeight fontWeight,
FontFamily fontFamily, CultureInfo culture, out FontKey fontKey);
///
diff --git a/src/Avalonia.Visuals/Platform/ITextShaperImpl.cs b/src/Avalonia.Visuals/Platform/ITextShaperImpl.cs
index 4d770a6c6e..d915da2603 100644
--- a/src/Avalonia.Visuals/Platform/ITextShaperImpl.cs
+++ b/src/Avalonia.Visuals/Platform/ITextShaperImpl.cs
@@ -1,6 +1,6 @@
-using Avalonia.Media;
-using Avalonia.Media.TextFormatting;
-using Avalonia.Utility;
+using System.Globalization;
+using Avalonia.Media;
+using Avalonia.Utilities;
namespace Avalonia.Platform
{
@@ -13,8 +13,10 @@ namespace Avalonia.Platform
/// Shapes the specified region within the text and returns a resulting glyph run.
///
/// The text.
- /// The text format.
+ /// The typeface.
+ /// The font rendering em size.
+ /// The culture.
/// A shaped glyph run.
- GlyphRun ShapeText(ReadOnlySlice text, TextFormat textFormat);
+ GlyphRun ShapeText(ReadOnlySlice text, Typeface typeface, double fontRenderingEmSize, CultureInfo culture);
}
}
diff --git a/src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs b/src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs
index dfb21a0289..4a364998fd 100644
--- a/src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs
+++ b/src/Avalonia.Visuals/Rendering/SceneGraph/DeferredDrawingContextImpl.cs
@@ -11,7 +11,7 @@ namespace Avalonia.Rendering.SceneGraph
///
/// A drawing context which builds a scene graph.
///
- internal class DeferredDrawingContextImpl : IDrawingContextImpl
+ internal class DeferredDrawingContextImpl : IDrawingContextImpl, IDrawingContextWithAcrylicLikeSupport
{
private readonly ISceneBuilder _sceneBuilder;
private VisualNode _node;
@@ -164,6 +164,21 @@ namespace Avalonia.Rendering.SceneGraph
}
}
+ ///
+ public void DrawRectangle(IExperimentalAcrylicMaterial material, RoundedRect rect)
+ {
+ var next = NextDrawAs();
+
+ if (next == null || !next.Item.Equals(Transform, material, rect))
+ {
+ Add(new ExperimentalAcrylicNode(Transform, material, rect));
+ }
+ else
+ {
+ ++_drawOperationindex;
+ }
+ }
+
public void Custom(ICustomDrawOperation custom)
{
var next = NextDrawAs();
diff --git a/src/Avalonia.Visuals/Rendering/SceneGraph/ExperimentalAcrylicNode.cs b/src/Avalonia.Visuals/Rendering/SceneGraph/ExperimentalAcrylicNode.cs
new file mode 100644
index 0000000000..336d11e3fd
--- /dev/null
+++ b/src/Avalonia.Visuals/Rendering/SceneGraph/ExperimentalAcrylicNode.cs
@@ -0,0 +1,94 @@
+using System;
+using Avalonia.Media;
+using Avalonia.Media.Immutable;
+using Avalonia.Platform;
+
+namespace Avalonia.Rendering.SceneGraph
+{
+ ///
+ /// A node in the scene graph which represents a rectangle draw.
+ ///
+ internal class ExperimentalAcrylicNode : DrawOperation
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The transform.
+ /// The rectangle to draw.
+ /// The box shadow parameters
+ /// Child scenes for drawing visual brushes.
+ public ExperimentalAcrylicNode(
+ Matrix transform,
+ IExperimentalAcrylicMaterial material,
+ RoundedRect rect)
+ : base(rect.Rect, transform)
+ {
+ Transform = transform;
+ Material = material?.ToImmutable();
+ Rect = rect;
+ }
+
+ ///
+ /// Gets the transform with which the node will be drawn.
+ ///
+ public Matrix Transform { get; }
+
+ public IExperimentalAcrylicMaterial Material { get; }
+
+ ///
+ /// Gets the rectangle to draw.
+ ///
+ public RoundedRect Rect { get; }
+
+ ///
+ /// Determines if this draw operation equals another.
+ ///
+ /// The transform of the other draw operation.
+ /// The fill of the other draw operation.
+ /// The rectangle of the other draw operation.
+ /// True if the draw operations are the same, otherwise false.
+ ///
+ /// The properties of the other draw operation are passed in as arguments to prevent
+ /// allocation of a not-yet-constructed draw operation object.
+ ///
+ public bool Equals(Matrix transform, IExperimentalAcrylicMaterial material, RoundedRect rect)
+ {
+ return transform == Transform &&
+ Equals(material, Material) &&
+ rect.Equals(Rect);
+ }
+
+ ///
+ public override void Render(IDrawingContextImpl context)
+ {
+ context.Transform = Transform;
+
+ if(context is IDrawingContextWithAcrylicLikeSupport idc)
+ {
+ idc.DrawRectangle(Material, Rect);
+ }
+ else
+ {
+ context.DrawRectangle(new ImmutableSolidColorBrush(Material.FallbackColor), null, Rect);
+ }
+ }
+
+ ///
+ public override bool HitTest(Point p)
+ {
+ // TODO: This doesn't respect CornerRadius yet.
+ if (Transform.HasInverse)
+ {
+ p *= Transform.Invert();
+
+ if (Material != null)
+ {
+ var rect = Rect.Rect;
+ return rect.Contains(p);
+ }
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/Avalonia.Visuals/Rendering/SceneGraph/RectangleNode.cs b/src/Avalonia.Visuals/Rendering/SceneGraph/RectangleNode.cs
index 5059a6d042..ec1a7753b1 100644
--- a/src/Avalonia.Visuals/Rendering/SceneGraph/RectangleNode.cs
+++ b/src/Avalonia.Visuals/Rendering/SceneGraph/RectangleNode.cs
@@ -19,7 +19,7 @@ namespace Avalonia.Rendering.SceneGraph
/// The fill brush.
/// The stroke pen.
/// The rectangle to draw.
- /// The box shadow parameters
+ /// The box shadow parameters
/// Child scenes for drawing visual brushes.
public RectangleNode(
Matrix transform,
diff --git a/src/Avalonia.Visuals/Utility/ReadOnlySlice.cs b/src/Avalonia.Visuals/Utilities/ReadOnlySlice.cs
similarity index 98%
rename from src/Avalonia.Visuals/Utility/ReadOnlySlice.cs
rename to src/Avalonia.Visuals/Utilities/ReadOnlySlice.cs
index ff2b3b9363..5feaa88e26 100644
--- a/src/Avalonia.Visuals/Utility/ReadOnlySlice.cs
+++ b/src/Avalonia.Visuals/Utilities/ReadOnlySlice.cs
@@ -2,9 +2,8 @@
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using Avalonia.Utilities;
-namespace Avalonia.Utility
+namespace Avalonia.Utilities
{
///
/// ReadOnlySlice enables the ability to work with a sequence within a region of memory and retains the position in within that region.
@@ -47,7 +46,7 @@ namespace Avalonia.Utility
public int Length { get; }
///
- /// Gets a value that indicates whether this instance of is Empty.
+ /// Gets a value that indicates whether this instance of is Empty.
///
public bool IsEmpty => Length == 0;
diff --git a/src/Avalonia.Visuals/Utilities/ValueSpan.cs b/src/Avalonia.Visuals/Utilities/ValueSpan.cs
new file mode 100644
index 0000000000..7a10d865ef
--- /dev/null
+++ b/src/Avalonia.Visuals/Utilities/ValueSpan.cs
@@ -0,0 +1,30 @@
+namespace Avalonia.Utilities
+{
+ ///
+ /// Pairing of value and positions sharing that value.
+ ///
+ public readonly struct ValueSpan
+ {
+ public ValueSpan(int start, int length, T value)
+ {
+ Start = start;
+ Length = length;
+ Value = value;
+ }
+
+ ///
+ /// Get's the start of the span.
+ ///
+ public int Start { get; }
+
+ ///
+ /// Get's the length of the span.
+ ///
+ public int Length { get; }
+
+ ///
+ /// Get's the value of the span.
+ ///
+ public T Value { get; }
+ }
+}
diff --git a/src/Avalonia.X11/X11Screens.cs b/src/Avalonia.X11/X11Screens.cs
index e247a4241a..af6d2674b6 100644
--- a/src/Avalonia.X11/X11Screens.cs
+++ b/src/Avalonia.X11/X11Screens.cs
@@ -48,9 +48,13 @@ namespace Avalonia.X11
var pwa = (IntPtr*)prop;
var wa = new PixelRect(pwa[0].ToInt32(), pwa[1].ToInt32(), pwa[2].ToInt32(), pwa[3].ToInt32());
-
- foreach (var s in screens)
+
+ foreach (var s in screens)
+ {
s.WorkingArea = s.Bounds.Intersect(wa);
+ if (s.WorkingArea.Width <= 0 || s.WorkingArea.Height <= 0)
+ s.WorkingArea = s.Bounds;
+ }
XFree(prop);
return screens;
@@ -134,8 +138,14 @@ namespace Avalonia.X11
settings.GlobalScaleFactor)
});
}
-
- Screens = new[] {new X11Screen(new PixelRect(0, 0, 1920, 1280), true, "Default", null, settings.GlobalScaleFactor)};
+ else
+ {
+ Screens = new[]
+ {
+ new X11Screen(new PixelRect(0, 0, 1920, 1280), true, "Default", null,
+ settings.GlobalScaleFactor)
+ };
+ }
}
public X11Screen[] Screens { get; }
diff --git a/src/Avalonia.X11/X11Window.cs b/src/Avalonia.X11/X11Window.cs
index 499fe5a67a..2a13999e8d 100644
--- a/src/Avalonia.X11/X11Window.cs
+++ b/src/Avalonia.X11/X11Window.cs
@@ -312,7 +312,15 @@ namespace Avalonia.X11
{
get => _transparencyHelper.TransparencyLevelChanged;
set => _transparencyHelper.TransparencyLevelChanged = value;
- }
+ }
+
+ public Action ExtendClientAreaToDecorationsChanged { get; set; }
+
+ public Thickness ExtendedMargins { get; } = new Thickness();
+
+ public Thickness OffScreenMargin { get; } = new Thickness();
+
+ public bool IsClientAreaExtendedToDecorations { get; }
public Action Closed { get; set; }
public Action PositionChanged { get; set; }
@@ -1039,6 +1047,18 @@ namespace Avalonia.X11
_disabled = !enable;
}
+ public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
+ {
+ }
+
+ public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
+ {
+ }
+
+ public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
+ {
+ }
+
public Action GotInputWhenDisabled { get; set; }
public void SetIcon(IWindowIconImpl icon)
@@ -1107,5 +1127,9 @@ namespace Avalonia.X11
}
public WindowTransparencyLevel TransparencyLevel => _transparencyHelper.CurrentLevel;
+
+ public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0.8, 0.8);
+
+ public bool NeedsManagedDecorations => false;
}
}
diff --git a/src/Linux/Avalonia.LinuxFramebuffer/FramebufferToplevelImpl.cs b/src/Linux/Avalonia.LinuxFramebuffer/FramebufferToplevelImpl.cs
index 2153344363..b8ae2eb4d8 100644
--- a/src/Linux/Avalonia.LinuxFramebuffer/FramebufferToplevelImpl.cs
+++ b/src/Linux/Avalonia.LinuxFramebuffer/FramebufferToplevelImpl.cs
@@ -82,5 +82,7 @@ namespace Avalonia.LinuxFramebuffer
public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) { }
public WindowTransparencyLevel TransparencyLevel { get; private set; }
+
+ public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1);
}
}
diff --git a/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj b/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj
index 985a6b9f5a..3979312ce0 100644
--- a/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj
+++ b/src/Markup/Avalonia.Markup.Xaml/Avalonia.Markup.Xaml.csproj
@@ -1,7 +1,7 @@
netstandard2.0
- PCL;NETSTANDARD;NETSTANDARD2_0;HAS_TYPE_CONVERTER;HAS_CUSTOM_ATTRIBUTE_PROVIDER;XAMLIL_INTERNAL
+ PCL;NETSTANDARD;NETSTANDARD2_0;HAS_TYPE_CONVERTER;HAS_CUSTOM_ATTRIBUTE_PROVIDER;XAMLX_INTERNAL
false
$(DefineConstants);RUNTIME_XAML_CECIL
False
@@ -16,7 +16,16 @@
+
+
+
+
+
+
+
+
+
@@ -25,7 +34,7 @@
-
+
@@ -37,13 +46,22 @@
-
+
+
+
+
+
+
+
+
+
+
@@ -54,14 +72,18 @@
+
+
+
-
-
+
+
+
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindingExtension.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindingExtension.cs
new file mode 100644
index 0000000000..aab733cb43
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindingExtension.cs
@@ -0,0 +1,79 @@
+using System;
+using Avalonia.Data;
+using Avalonia.Controls;
+using Avalonia.Styling;
+using Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings;
+using Avalonia.Data.Core;
+using Avalonia.Markup.Parsers;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions
+{
+ public class CompiledBindingExtension : BindingBase
+ {
+ public CompiledBindingExtension()
+ {
+ Path = new CompiledBindingPath();
+ }
+
+ public CompiledBindingExtension(CompiledBindingPath path)
+ {
+ Path = path;
+ }
+
+ public CompiledBindingExtension ProvideValue(IServiceProvider provider)
+ {
+ return new CompiledBindingExtension
+ {
+ Path = Path,
+ Converter = Converter,
+ FallbackValue = FallbackValue,
+ Mode = Mode,
+ Priority = Priority,
+ StringFormat = StringFormat,
+ DefaultAnchor = new WeakReference(GetDefaultAnchor(provider))
+ };
+ }
+
+ private static object GetDefaultAnchor(IServiceProvider provider)
+ {
+ // If the target is not a control, so we need to find an anchor that will let us look
+ // up named controls and style resources. First look for the closest IControl in
+ // the context.
+ object anchor = provider.GetFirstParent();
+
+ // If a control was not found, then try to find the highest-level style as the XAML
+ // file could be a XAML file containing only styles.
+ return anchor ??
+ provider.GetService()?.RootObject as IStyle ??
+ provider.GetLastParent();
+ }
+
+ protected override ExpressionObserver CreateExpressionObserver(IAvaloniaObject target, AvaloniaProperty targetProperty, object anchor, bool enableDataValidation)
+ {
+ if (Path.RawSource != null)
+ {
+ return CreateSourceObserver(
+ Path.RawSource,
+ Path.BuildExpression(enableDataValidation));
+ }
+
+ if (Path.SourceMode == SourceMode.Data)
+ {
+ return CreateDataContextObserver(
+ target,
+ Path.BuildExpression(enableDataValidation),
+ targetProperty == StyledElement.DataContextProperty,
+ anchor);
+ }
+ else
+ {
+ return CreateSourceObserver(
+ (target as IStyledElement) ?? (anchor as IStyledElement),
+ Path.BuildExpression(enableDataValidation));
+ }
+ }
+
+ [ConstructorArgument("path")]
+ public CompiledBindingPath Path { get; set; }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ArrayElementPlugin.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ArrayElementPlugin.cs
new file mode 100644
index 0000000000..7cbe4942e5
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ArrayElementPlugin.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Avalonia.Data;
+using Avalonia.Data.Core.Plugins;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ class ArrayElementPlugin : IPropertyAccessorPlugin
+ {
+ private readonly int[] _indices;
+ private readonly Type _elementType;
+
+ public ArrayElementPlugin(int[] indices, Type elementType)
+ {
+ _indices = indices;
+ _elementType = elementType;
+ }
+
+ public bool Match(object obj, string propertyName)
+ {
+ throw new InvalidOperationException("The ArrayElementPlugin does not support dynamic matching");
+ }
+
+ public IPropertyAccessor Start(WeakReference reference, string propertyName)
+ {
+ if (reference.TryGetTarget(out var target) && target is Array arr)
+ {
+ return new Accessor(new WeakReference(arr), _indices, _elementType);
+ }
+ return null;
+ }
+
+ class Accessor : PropertyAccessorBase
+ {
+ private readonly int[] _indices;
+ private readonly WeakReference _reference;
+
+ public Accessor(WeakReference reference, int[] indices, Type elementType)
+ {
+ _reference = reference;
+ _indices = indices;
+ PropertyType = elementType;
+ }
+
+ public override Type PropertyType { get; }
+
+ public override object Value => _reference.TryGetTarget(out var arr) ? arr.GetValue(_indices) : null;
+
+ public override bool SetValue(object value, BindingPriority priority)
+ {
+ if (_reference.TryGetTarget(out var arr))
+ {
+ arr.SetValue(value, _indices);
+ return true;
+ }
+ return false;
+ }
+
+ protected override void SubscribeCore()
+ {
+ PublishValue(Value);
+ }
+
+ protected override void UnsubscribeCore()
+ {
+ }
+ }
+ }
+
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/CompiledBindingPath.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/CompiledBindingPath.cs
new file mode 100644
index 0000000000..d627fe3cd3
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/CompiledBindingPath.cs
@@ -0,0 +1,233 @@
+using System;
+using System.Collections.Generic;
+using Avalonia.Controls;
+using Avalonia.Data.Core;
+using Avalonia.Data.Core.Plugins;
+using Avalonia.Markup.Parsers;
+using Avalonia.Markup.Parsers.Nodes;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ public class CompiledBindingPath
+ {
+ private readonly List _elements = new List();
+
+ public CompiledBindingPath() { }
+
+ internal CompiledBindingPath(IEnumerable bindingPath, object rawSource)
+ {
+ _elements = new List(bindingPath);
+ RawSource = rawSource;
+ }
+
+ public ExpressionNode BuildExpression(bool enableValidation)
+ {
+ ExpressionNode pathRoot = null;
+ ExpressionNode path = null;
+ foreach (var element in _elements)
+ {
+ ExpressionNode node = null;
+ switch (element)
+ {
+ case NotExpressionPathElement _:
+ node = new LogicalNotNode();
+ break;
+ case PropertyElement prop:
+ node = new PropertyAccessorNode(prop.Property.Name, enableValidation, new PropertyInfoAccessorPlugin(prop.Property, prop.AccessorFactory));
+ break;
+ case ArrayElementPathElement arr:
+ node = new PropertyAccessorNode(CommonPropertyNames.IndexerName, enableValidation, new ArrayElementPlugin(arr.Indices, arr.ElementType));
+ break;
+ case VisualAncestorPathElement visualAncestor:
+ node = new FindVisualAncestorNode(visualAncestor.AncestorType, visualAncestor.Level);
+ break;
+ case AncestorPathElement ancestor:
+ node = new FindAncestorNode(ancestor.AncestorType, ancestor.Level);
+ break;
+ case SelfPathElement _:
+ node = new SelfNode();
+ break;
+ case ElementNameElement name:
+ node = new ElementNameNode(name.NameScope, name.Name);
+ break;
+ case IStronglyTypedStreamElement stream:
+ node = new StreamNode(stream.CreatePlugin());
+ break;
+ default:
+ throw new InvalidOperationException($"Unknown binding path element type {element.GetType().FullName}");
+ }
+
+ path = pathRoot is null ? (pathRoot = node) : path.Next = node;
+ }
+
+ return pathRoot ?? new EmptyExpressionNode();
+ }
+
+ internal SourceMode SourceMode => _elements.Count > 0 && _elements[0] is IControlSourceBindingPathElement ? SourceMode.Control : SourceMode.Data;
+
+ internal object RawSource { get; }
+ }
+
+ public class CompiledBindingPathBuilder
+ {
+ private object _rawSource;
+ private List _elements = new List();
+
+ public CompiledBindingPathBuilder Not()
+ {
+ _elements.Add(new NotExpressionPathElement());
+ return this;
+ }
+
+ public CompiledBindingPathBuilder Property(IPropertyInfo info, Func, IPropertyInfo, IPropertyAccessor> accessorFactory)
+ {
+ _elements.Add(new PropertyElement(info, accessorFactory));
+ return this;
+ }
+
+ public CompiledBindingPathBuilder StreamTask()
+ {
+ _elements.Add(new TaskStreamPathElement());
+ return this;
+ }
+
+ public CompiledBindingPathBuilder StreamObservable()
+ {
+ _elements.Add(new ObservableStreamPathElement());
+ return this;
+ }
+
+ public CompiledBindingPathBuilder Self()
+ {
+ _elements.Add(new SelfPathElement());
+ return this;
+ }
+
+ public CompiledBindingPathBuilder Ancestor(Type ancestorType, int level)
+ {
+ _elements.Add(new AncestorPathElement(ancestorType, level));
+ return this;
+ }
+ public CompiledBindingPathBuilder VisualAncestor(Type ancestorType, int level)
+ {
+ _elements.Add(new VisualAncestorPathElement(ancestorType, level));
+ return this;
+ }
+
+ public CompiledBindingPathBuilder ElementName(INameScope nameScope, string name)
+ {
+ _elements.Add(new ElementNameElement(nameScope, name));
+ return this;
+ }
+
+ public CompiledBindingPathBuilder ArrayElement(int[] indices, Type elementType)
+ {
+ _elements.Add(new ArrayElementPathElement(indices, elementType));
+ return this;
+ }
+
+ public CompiledBindingPathBuilder SetRawSource(object rawSource)
+ {
+ _rawSource = rawSource;
+ return this;
+ }
+
+ public CompiledBindingPath Build() => new CompiledBindingPath(_elements, _rawSource);
+ }
+
+ public interface ICompiledBindingPathElement
+ {
+ }
+
+ internal interface IControlSourceBindingPathElement { }
+
+ internal class NotExpressionPathElement : ICompiledBindingPathElement
+ {
+ public static readonly NotExpressionPathElement Instance = new NotExpressionPathElement();
+ }
+
+ internal class PropertyElement : ICompiledBindingPathElement
+ {
+ public PropertyElement(IPropertyInfo property, Func, IPropertyInfo, IPropertyAccessor> accessorFactory)
+ {
+ Property = property;
+ AccessorFactory = accessorFactory;
+ }
+
+ public IPropertyInfo Property { get; }
+
+ public Func, IPropertyInfo, IPropertyAccessor> AccessorFactory { get; }
+ }
+
+ internal interface IStronglyTypedStreamElement : ICompiledBindingPathElement
+ {
+ IStreamPlugin CreatePlugin();
+ }
+
+ internal class TaskStreamPathElement : IStronglyTypedStreamElement
+ {
+ public static readonly TaskStreamPathElement Instance = new TaskStreamPathElement();
+
+ public IStreamPlugin CreatePlugin() => new TaskStreamPlugin();
+ }
+
+ internal class ObservableStreamPathElement : IStronglyTypedStreamElement
+ {
+ public static readonly ObservableStreamPathElement Instance = new ObservableStreamPathElement();
+
+ public IStreamPlugin CreatePlugin() => new ObservableStreamPlugin();
+ }
+
+ internal class SelfPathElement : ICompiledBindingPathElement, IControlSourceBindingPathElement
+ {
+ public static readonly SelfPathElement Instance = new SelfPathElement();
+ }
+
+ internal class AncestorPathElement : ICompiledBindingPathElement, IControlSourceBindingPathElement
+ {
+ public AncestorPathElement(Type ancestorType, int level)
+ {
+ AncestorType = ancestorType;
+ Level = level;
+ }
+
+ public Type AncestorType { get; }
+ public int Level { get; }
+ }
+
+ internal class VisualAncestorPathElement : ICompiledBindingPathElement, IControlSourceBindingPathElement
+ {
+ public VisualAncestorPathElement(Type ancestorType, int level)
+ {
+ AncestorType = ancestorType;
+ Level = level;
+ }
+
+ public Type AncestorType { get; }
+ public int Level { get; }
+ }
+
+ internal class ElementNameElement : ICompiledBindingPathElement, IControlSourceBindingPathElement
+ {
+ public ElementNameElement(INameScope nameScope, string name)
+ {
+ NameScope = nameScope;
+ Name = name;
+ }
+
+ public INameScope NameScope { get; }
+ public string Name { get; }
+ }
+
+ internal class ArrayElementPathElement : ICompiledBindingPathElement
+ {
+ public ArrayElementPathElement(int[] indices, Type elementType)
+ {
+ Indices = indices;
+ ElementType = elementType;
+ }
+
+ public int[] Indices { get; }
+ public Type ElementType { get; }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/FindVisualAncestorNode.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/FindVisualAncestorNode.cs
new file mode 100644
index 0000000000..5820f47fbb
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/FindVisualAncestorNode.cs
@@ -0,0 +1,52 @@
+using System;
+using Avalonia.Data.Core;
+using Avalonia.VisualTree;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ class FindVisualAncestorNode : ExpressionNode
+ {
+ private readonly int _level;
+ private readonly Type _ancestorType;
+ private IDisposable _subscription;
+
+ public FindVisualAncestorNode(Type ancestorType, int level)
+ {
+ _level = level;
+ _ancestorType = ancestorType;
+ }
+
+ public override string Description
+ {
+ get
+ {
+ if (_ancestorType == null)
+ {
+ return $"$visualparent[{_level}]";
+ }
+ else
+ {
+ return $"$visualparent[{_ancestorType.Name}, {_level}]";
+ }
+ }
+ }
+
+ protected override void StartListeningCore(WeakReference reference)
+ {
+ if (reference.TryGetTarget(out object target) && target is IVisual visual)
+ {
+ _subscription = VisualLocator.Track(visual, _level, _ancestorType).Subscribe(ValueChanged);
+ }
+ else
+ {
+ _subscription = null;
+ }
+ }
+
+ protected override void StopListeningCore()
+ {
+ _subscription?.Dispose();
+ _subscription = null;
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ObservableStreamPlugin.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ObservableStreamPlugin.cs
new file mode 100644
index 0000000000..3e3174123a
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/ObservableStreamPlugin.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Reactive.Linq;
+using System.Text;
+using Avalonia.Data.Core.Plugins;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ class ObservableStreamPlugin : IStreamPlugin
+ {
+ public bool Match(WeakReference reference)
+ {
+ return reference.TryGetTarget(out var target) && target is IObservable;
+ }
+
+ public IObservable Start(WeakReference reference)
+ {
+ if (!(reference.TryGetTarget(out var target) && target is IObservable obs))
+ {
+ return Observable.Empty();
+ }
+ else if (target is IObservable obj)
+ {
+ return obj;
+ }
+
+ return obs.Select(x => (object)x);
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorFactory.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorFactory.cs
new file mode 100644
index 0000000000..b3f78bfbe3
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorFactory.cs
@@ -0,0 +1,225 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Text;
+using Avalonia.Data;
+using Avalonia.Data.Core;
+using Avalonia.Data.Core.Plugins;
+using Avalonia.Utilities;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ public static class PropertyInfoAccessorFactory
+ {
+ public static IPropertyAccessor CreateInpcPropertyAccessor(WeakReference target, IPropertyInfo property)
+ => new InpcPropertyAccessor(target, property);
+
+ public static IPropertyAccessor CreateAvaloniaPropertyAccessor(WeakReference target, IPropertyInfo property)
+ => new AvaloniaPropertyAccessor(new WeakReference((AvaloniaObject)(target.TryGetTarget(out var o) ? o : null)), (AvaloniaProperty)property);
+
+ public static IPropertyAccessor CreateIndexerPropertyAccessor(WeakReference target, IPropertyInfo property, int argument)
+ => new IndexerAccessor(target, property, argument);
+ }
+
+ internal class AvaloniaPropertyAccessor : PropertyAccessorBase
+ {
+ private readonly WeakReference _reference;
+ private readonly AvaloniaProperty _property;
+ private IDisposable _subscription;
+
+ public AvaloniaPropertyAccessor(WeakReference reference, AvaloniaProperty property)
+ {
+ Contract.Requires(reference != null);
+ Contract.Requires(property != null);
+
+ _reference = reference;
+ _property = property;
+ }
+
+ public AvaloniaObject Instance
+ {
+ get
+ {
+ _reference.TryGetTarget(out var result);
+ return result;
+ }
+ }
+
+ public override Type PropertyType => _property.PropertyType;
+ public override object Value => Instance?.GetValue(_property);
+
+ public override bool SetValue(object value, BindingPriority priority)
+ {
+ if (!_property.IsReadOnly)
+ {
+ Instance.SetValue(_property, value, priority);
+ return true;
+ }
+
+ return false;
+ }
+
+ protected override void SubscribeCore()
+ {
+ _subscription = Instance?.GetObservable(_property).Subscribe(PublishValue);
+ }
+
+ protected override void UnsubscribeCore()
+ {
+ _subscription?.Dispose();
+ _subscription = null;
+ }
+ }
+
+ internal class InpcPropertyAccessor : PropertyAccessorBase
+ {
+ protected readonly WeakReference _reference;
+ private readonly IPropertyInfo _property;
+
+ public InpcPropertyAccessor(WeakReference reference, IPropertyInfo property)
+ {
+ Contract.Requires(reference != null);
+ Contract.Requires(property != null);
+
+ _reference = reference;
+ _property = property;
+ }
+
+ public override Type PropertyType => _property.PropertyType;
+
+ public override object Value
+ {
+ get
+ {
+ return _reference.TryGetTarget(out var o) ? _property.Get(o) : null;
+ }
+ }
+
+ public override bool SetValue(object value, BindingPriority priority)
+ {
+ if (_property.CanSet && _reference.TryGetTarget(out var o))
+ {
+ _property.Set(o, value);
+
+ SendCurrentValue();
+
+ return true;
+ }
+
+ return false;
+ }
+
+ void OnNotifyPropertyChanged(object sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName == _property.Name || string.IsNullOrEmpty(e.PropertyName))
+ {
+ SendCurrentValue();
+ }
+ }
+
+ protected override void SubscribeCore()
+ {
+ SendCurrentValue();
+ SubscribeToChanges();
+ }
+
+ protected override void UnsubscribeCore()
+ {
+ if (_reference.TryGetTarget(out var o) && o is INotifyPropertyChanged inpc)
+ {
+ WeakEventHandlerManager.Unsubscribe(
+ inpc,
+ nameof(INotifyPropertyChanged.PropertyChanged),
+ OnNotifyPropertyChanged);
+ }
+ }
+
+ protected void SendCurrentValue()
+ {
+ try
+ {
+ var value = Value;
+ PublishValue(value);
+ }
+ catch { }
+ }
+
+ private void SubscribeToChanges()
+ {
+ if (_reference.TryGetTarget(out var o) && o is INotifyPropertyChanged inpc)
+ {
+ WeakEventHandlerManager.Subscribe(
+ inpc,
+ nameof(INotifyPropertyChanged.PropertyChanged),
+ OnNotifyPropertyChanged);
+ }
+ }
+ }
+
+ internal class IndexerAccessor : InpcPropertyAccessor
+ {
+ private int _index;
+
+ public IndexerAccessor(WeakReference target, IPropertyInfo basePropertyInfo, int argument)
+ :base(target, basePropertyInfo)
+ {
+ _index = argument;
+ }
+
+
+ protected override void SubscribeCore()
+ {
+ base.SubscribeCore();
+ if (_reference.TryGetTarget(out var o) && o is INotifyCollectionChanged incc)
+ {
+ WeakEventHandlerManager.Subscribe(
+ incc,
+ nameof(INotifyCollectionChanged.CollectionChanged),
+ OnNotifyCollectionChanged);
+ }
+ }
+
+ protected override void UnsubscribeCore()
+ {
+ base.UnsubscribeCore();
+ if (_reference.TryGetTarget(out var o) && o is INotifyCollectionChanged incc)
+ {
+ WeakEventHandlerManager.Unsubscribe(
+ incc,
+ nameof(INotifyCollectionChanged.CollectionChanged),
+ OnNotifyCollectionChanged);
+ }
+ }
+
+ void OnNotifyCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
+ {
+ if (ShouldNotifyListeners(args))
+ {
+ SendCurrentValue();
+ }
+ }
+
+ bool ShouldNotifyListeners(NotifyCollectionChangedEventArgs e)
+ {
+ switch (e.Action)
+ {
+ case NotifyCollectionChangedAction.Add:
+ return _index >= e.NewStartingIndex;
+ case NotifyCollectionChangedAction.Remove:
+ return _index >= e.OldStartingIndex;
+ case NotifyCollectionChangedAction.Replace:
+ return _index >= e.NewStartingIndex &&
+ _index < e.NewStartingIndex + e.NewItems.Count;
+ case NotifyCollectionChangedAction.Move:
+ return (_index >= e.NewStartingIndex &&
+ _index < e.NewStartingIndex + e.NewItems.Count) ||
+ (_index >= e.OldStartingIndex &&
+ _index < e.OldStartingIndex + e.OldItems.Count);
+ case NotifyCollectionChangedAction.Reset:
+ return true;
+ }
+ return false;
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorPlugin.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorPlugin.cs
new file mode 100644
index 0000000000..6e7463776b
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/PropertyInfoAccessorPlugin.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+using Avalonia.Data;
+using Avalonia.Data.Core;
+using Avalonia.Data.Core.Plugins;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ class PropertyInfoAccessorPlugin : IPropertyAccessorPlugin
+ {
+ private readonly IPropertyInfo _propertyInfo;
+ private readonly Func, IPropertyInfo, IPropertyAccessor> _accessorFactory;
+
+ public PropertyInfoAccessorPlugin(IPropertyInfo propertyInfo, Func, IPropertyInfo, IPropertyAccessor> accessorFactory)
+ {
+ _propertyInfo = propertyInfo;
+ _accessorFactory = accessorFactory;
+ }
+
+ public bool Match(object obj, string propertyName)
+ {
+ throw new InvalidOperationException("The PropertyInfoAccessorPlugin does not support dynamic matching");
+ }
+
+ public IPropertyAccessor Start(WeakReference reference, string propertyName)
+ {
+ Debug.Assert(_propertyInfo.Name == propertyName);
+ return _accessorFactory(reference, _propertyInfo);
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/TaskStreamPlugin.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/TaskStreamPlugin.cs
new file mode 100644
index 0000000000..164d38e3ae
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/CompiledBindings/TaskStreamPlugin.cs
@@ -0,0 +1,53 @@
+using System;
+using System.Reactive.Linq;
+using System.Reactive.Subjects;
+using System.Threading.Tasks;
+using Avalonia.Data;
+using Avalonia.Data.Core.Plugins;
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings
+{
+ class TaskStreamPlugin : IStreamPlugin
+ {
+ public bool Match(WeakReference reference)
+ {
+ return reference.TryGetTarget(out var target) && target is Task;
+ }
+
+ public IObservable Start(WeakReference reference)
+ {
+ if(!(reference.TryGetTarget(out var target) && target is Task task))
+ {
+ return Observable.Empty();
+ }
+
+ switch (task.Status)
+ {
+ case TaskStatus.RanToCompletion:
+ case TaskStatus.Faulted:
+ return HandleCompleted(task);
+ default:
+ var subject = new Subject();
+ task.ContinueWith(
+ x => HandleCompleted(task).Subscribe(subject),
+ TaskScheduler.FromCurrentSynchronizationContext())
+ .ConfigureAwait(false);
+ return subject;
+ }
+ }
+
+
+ private static IObservable HandleCompleted(Task task)
+ {
+ switch (task.Status)
+ {
+ case TaskStatus.RanToCompletion:
+ return Observable.Return((object)task.Result);
+ case TaskStatus.Faulted:
+ return Observable.Return(new BindingNotification(task.Exception, BindingErrorType.Error));
+ default:
+ throw new AvaloniaInternalException("HandleCompleted called for non-completed Task.");
+ }
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/BindingExtension.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ReflectionBindingExtension.cs
similarity index 95%
rename from src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/BindingExtension.cs
rename to src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ReflectionBindingExtension.cs
index cc66efa5fd..10770365a3 100644
--- a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/BindingExtension.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ReflectionBindingExtension.cs
@@ -9,13 +9,13 @@ namespace Avalonia.Markup.Xaml.MarkupExtensions
using Avalonia.Styling;
using System.ComponentModel;
- public class BindingExtension
+ public class ReflectionBindingExtension
{
- public BindingExtension()
+ public ReflectionBindingExtension()
{
}
- public BindingExtension(string path)
+ public ReflectionBindingExtension(string path)
{
Path = path;
}
diff --git a/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ResolveByNameExtension.cs b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ResolveByNameExtension.cs
new file mode 100644
index 0000000000..8561aa898b
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ResolveByNameExtension.cs
@@ -0,0 +1,36 @@
+using System;
+using Avalonia.Controls;
+using Avalonia.Data.Core;
+
+#nullable enable
+
+namespace Avalonia.Markup.Xaml.MarkupExtensions
+{
+ public class ResolveByNameExtension
+ {
+ public ResolveByNameExtension(string name)
+ {
+ Name = name;
+ }
+
+ public string Name { get; }
+
+ public object? ProvideValue(IServiceProvider serviceProvider)
+ {
+ var nameScope = serviceProvider.GetService();
+
+ var value = nameScope.FindAsync(Name);
+
+ if(value.IsCompleted)
+ return value.GetResult();
+
+ var provideValueTarget = serviceProvider.GetService();
+ var target = provideValueTarget.TargetObject;
+
+ if (provideValueTarget.TargetProperty is IPropertyInfo property)
+ value.OnCompleted(() => property.Set(target, value.GetResult()));
+
+ return null;
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/AvaloniaXamlIlRuntimeCompiler.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/AvaloniaXamlIlRuntimeCompiler.cs
index 5a5da518d0..d9b4cd70da 100644
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/AvaloniaXamlIlRuntimeCompiler.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/AvaloniaXamlIlRuntimeCompiler.cs
@@ -10,12 +10,15 @@ using System.Runtime.InteropServices;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Avalonia.Markup.Xaml.XamlIl.Runtime;
using Avalonia.Platform;
-using XamlIl.Transform;
-using XamlIl.TypeSystem;
+using XamlX.Transform;
+using XamlX.TypeSystem;
+using XamlX.IL;
+using XamlX.Emit;
#if RUNTIME_XAML_CECIL
using TypeAttributes = Mono.Cecil.TypeAttributes;
using Mono.Cecil;
-using XamlIl.Ast;
+using XamlX.Ast;
+using XamlX.IL.Cecil;
#endif
namespace Avalonia.Markup.Xaml.XamlIl
{
@@ -24,9 +27,10 @@ namespace Avalonia.Markup.Xaml.XamlIl
#if !RUNTIME_XAML_CECIL
private static SreTypeSystem _sreTypeSystem;
private static ModuleBuilder _sreBuilder;
- private static IXamlIlType _sreContextType;
- private static XamlIlLanguageTypeMappings _sreMappings;
- private static XamlIlXmlnsMappings _sreXmlns;
+ private static IXamlType _sreContextType;
+ private static XamlLanguageTypeMappings _sreMappings;
+ private static XamlLanguageEmitMappings _sreEmitMappings;
+ private static XamlXmlnsMappings _sreXmlns;
private static AssemblyBuilder _sreAsm;
private static bool _sreCanSave;
@@ -82,13 +86,14 @@ namespace Avalonia.Markup.Xaml.XamlIl
}
if (_sreMappings == null)
- _sreMappings = AvaloniaXamlIlLanguage.Configure(_sreTypeSystem);
+ (_sreMappings, _sreEmitMappings) = AvaloniaXamlIlLanguage.Configure(_sreTypeSystem);
if (_sreXmlns == null)
- _sreXmlns = XamlIlXmlnsMappings.Resolve(_sreTypeSystem, _sreMappings);
+ _sreXmlns = XamlXmlnsMappings.Resolve(_sreTypeSystem, _sreMappings);
if (_sreContextType == null)
- _sreContextType = XamlIlContextDefinition.GenerateContextClass(
+ _sreContextType = XamlILContextDefinition.GenerateContextClass(
_sreTypeSystem.CreateTypeBuilder(
- _sreBuilder.DefineType("XamlIlContext")), _sreTypeSystem, _sreMappings);
+ _sreBuilder.DefineType("XamlIlContext")), _sreTypeSystem, _sreMappings,
+ _sreEmitMappings);
}
@@ -114,13 +119,19 @@ namespace Avalonia.Markup.Xaml.XamlIl
InitializeSre();
var asm = localAssembly == null ? null : _sreTypeSystem.GetAssembly(localAssembly);
+ var tb = _sreBuilder.DefineType("Builder_" + Guid.NewGuid().ToString("N") + "_" + uri);
+ var clrPropertyBuilder = tb.DefineNestedType("ClrProperties_" + Guid.NewGuid().ToString("N"));
+ var indexerClosureType = _sreBuilder.DefineType("IndexerClosure_" + Guid.NewGuid().ToString("N"));
- var compiler = new AvaloniaXamlIlCompiler(new XamlIlTransformerConfiguration(_sreTypeSystem, asm,
- _sreMappings, _sreXmlns, AvaloniaXamlIlLanguage.CustomValueConverter),
+ var compiler = new AvaloniaXamlIlCompiler(new AvaloniaXamlIlCompilerConfiguration(_sreTypeSystem, asm,
+ _sreMappings, _sreXmlns, AvaloniaXamlIlLanguage.CustomValueConverter,
+ new XamlIlClrPropertyInfoEmitter(_sreTypeSystem.CreateTypeBuilder(clrPropertyBuilder)),
+ new XamlIlPropertyInfoAccessorFactoryEmitter(_sreTypeSystem.CreateTypeBuilder(indexerClosureType))),
+ _sreEmitMappings,
_sreContextType) { EnableIlVerification = true };
- var tb = _sreBuilder.DefineType("Builder_" + Guid.NewGuid().ToString("N") + "_" + uri);
+
- IXamlIlType overrideType = null;
+ IXamlType overrideType = null;
if (rootInstance != null)
{
overrideType = _sreTypeSystem.GetType(rootInstance.GetType());
@@ -129,6 +140,7 @@ namespace Avalonia.Markup.Xaml.XamlIl
compiler.IsDesignMode = isDesignMode;
compiler.ParseAndCompile(xaml, uri?.ToString(), null, _sreTypeSystem.CreateTypeBuilder(tb), overrideType);
var created = tb.CreateTypeInfo();
+ clrPropertyBuilder.CreateTypeInfo();
return LoadOrPopulate(created, rootInstance);
}
@@ -203,6 +215,7 @@ namespace Avalonia.Markup.Xaml.XamlIl
private static string _cecilEmitDir;
private static CecilTypeSystem _cecilTypeSystem;
private static XamlIlLanguageTypeMappings _cecilMappings;
+ private static XamlLanguageEmitMappings _cecilEmitMappings;
private static XamlIlXmlnsMappings _cecilXmlns;
private static bool _cecilInitialized;
@@ -215,7 +228,7 @@ namespace Avalonia.Markup.Xaml.XamlIl
Directory.CreateDirectory(_cecilEmitDir);
var refs = new[] {path}.Concat(File.ReadAllLines(path + ".refs"));
_cecilTypeSystem = new CecilTypeSystem(refs);
- _cecilMappings = AvaloniaXamlIlLanguage.Configure(_cecilTypeSystem);
+ (_cecilMappings, _cecilEmitMappings) = AvaloniaXamlIlLanguage.Configure(_cecilTypeSystem);
_cecilXmlns = XamlIlXmlnsMappings.Resolve(_cecilTypeSystem, _cecilMappings);
_cecilInitialized = true;
}
@@ -226,7 +239,7 @@ namespace Avalonia.Markup.Xaml.XamlIl
if (uri == null)
throw new InvalidOperationException("Please, go away");
InitializeCecil();
- IXamlIlType overrideType = null;
+ IXamlType overrideType = null;
if (rootInstance != null)
{
overrideType = _cecilTypeSystem.GetType(rootInstance.GetType().FullName);
@@ -261,6 +274,7 @@ namespace Avalonia.Markup.Xaml.XamlIl
localAssembly == null ? null : _cecilTypeSystem.FindAssembly(localAssembly.GetName().Name),
_cecilMappings, XamlIlXmlnsMappings.Resolve(_cecilTypeSystem, _cecilMappings),
AvaloniaXamlIlLanguage.CustomValueConverter),
+ _cecilEmitMappings,
_cecilTypeSystem.CreateTypeBuilder(contextDef));
compiler.ParseAndCompile(xaml, uri.ToString(), tb, overrideType);
var asmPath = Path.Combine(_cecilEmitDir, safeUri + ".dll");
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompiler.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompiler.cs
index b84f50fa8d..abff763bb1 100644
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompiler.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompiler.cs
@@ -1,29 +1,33 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers;
-using XamlIl;
-using XamlIl.Ast;
-using XamlIl.Parsers;
-using XamlIl.Transform;
-using XamlIl.Transform.Transformers;
-using XamlIl.TypeSystem;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Emit;
+using XamlX.IL;
+using XamlX.Parsers;
+using XamlX.Transform;
+using XamlX.Transform.Transformers;
+using XamlX.TypeSystem;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
{
- class AvaloniaXamlIlCompiler : XamlIlCompiler
+ class AvaloniaXamlIlCompiler : XamlILCompiler
{
- private readonly XamlIlTransformerConfiguration _configuration;
- private readonly IXamlIlType _contextType;
+ private readonly TransformerConfiguration _configuration;
+ private readonly IXamlType _contextType;
private readonly AvaloniaXamlIlDesignPropertiesTransformer _designTransformer;
+ private readonly AvaloniaBindingExtensionTransformer _bindingTransformer;
- private AvaloniaXamlIlCompiler(XamlIlTransformerConfiguration configuration) : base(configuration, true)
+ private AvaloniaXamlIlCompiler(TransformerConfiguration configuration, XamlLanguageEmitMappings emitMappings)
+ : base(configuration, emitMappings, true)
{
_configuration = configuration;
- void InsertAfter(params IXamlIlAstTransformer[] t)
+ void InsertAfter(params IXamlAstTransformer[] t)
=> Transformers.InsertRange(Transformers.FindIndex(x => x is T) + 1, t);
- void InsertBefore(params IXamlIlAstTransformer[] t)
+ void InsertBefore(params IXamlAstTransformer[] t)
=> Transformers.InsertRange(Transformers.FindIndex(x => x is T), t);
@@ -32,40 +36,53 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
Transformers.Insert(0, new XNameTransformer());
Transformers.Insert(1, new IgnoredDirectivesTransformer());
Transformers.Insert(2, _designTransformer = new AvaloniaXamlIlDesignPropertiesTransformer());
- Transformers.Insert(3, new AvaloniaBindingExtensionHackTransformer());
+ Transformers.Insert(3, _bindingTransformer = new AvaloniaBindingExtensionTransformer());
// Targeted
-
- InsertBefore(new AvaloniaXamlIlTransformInstanceAttachedProperties());
- InsertAfter(new AvaloniaXamlIlAvaloniaPropertyResolver());
-
-
-
- InsertBefore(
+ InsertBefore(
+ new AvaloniaXamlIlTransformInstanceAttachedProperties(),
+ new AvaloniaXamlIlTransformSyntheticCompiledBindingMembers());
+ InsertAfter(
+ new AvaloniaXamlIlAvaloniaPropertyResolver());
+
+ InsertBefore(
+ new AvaloniaXamlIlBindingPathParser(),
new AvaloniaXamlIlSelectorTransformer(),
- new AvaloniaXamlIlSetterTransformer(),
new AvaloniaXamlIlControlTemplateTargetTypeMetadataTransformer(),
+ new AvaloniaXamlIlPropertyPathTransformer(),
+ new AvaloniaXamlIlSetterTransformer(),
new AvaloniaXamlIlConstructorServiceProviderTransformer(),
- new AvaloniaXamlIlTransitionsTypeMetadataTransformer()
+ new AvaloniaXamlIlTransitionsTypeMetadataTransformer(),
+ new AvaloniaXamlIlResolveByNameMarkupExtensionReplacer()
);
-
+
// After everything else
-
- Transformers.Add(new AddNameScopeRegistration());
+ InsertBefore(
+ new AddNameScopeRegistration(),
+ new AvaloniaXamlIlDataContextTypeTransformer(),
+ new AvaloniaXamlIlBindingPathTransformer(),
+ new AvaloniaXamlIlCompiledBindingsMetadataRemover()
+ );
+
Transformers.Add(new AvaloniaXamlIlMetadataRemover());
+ Transformers.Add(new AvaloniaXamlIlRootObjectScope());
+ Emitters.Add(new AvaloniaNameScopeRegistrationXamlIlNodeEmitter());
+ Emitters.Add(new AvaloniaXamlIlRootObjectScope.Emitter());
}
-
- public AvaloniaXamlIlCompiler(XamlIlTransformerConfiguration configuration,
- IXamlIlTypeBuilder contextTypeBuilder) : this(configuration)
+ public AvaloniaXamlIlCompiler(TransformerConfiguration configuration,
+ XamlLanguageEmitMappings emitMappings,
+ IXamlTypeBuilder contextTypeBuilder)
+ : this(configuration, emitMappings)
{
_contextType = CreateContextType(contextTypeBuilder);
}
- public AvaloniaXamlIlCompiler(XamlIlTransformerConfiguration configuration,
- IXamlIlType contextType) : this(configuration)
+ public AvaloniaXamlIlCompiler(TransformerConfiguration configuration,
+ XamlLanguageEmitMappings emitMappings,
+ IXamlType contextType) : this(configuration, emitMappings)
{
_contextType = contextType;
}
@@ -79,37 +96,41 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
set => _designTransformer.IsDesignMode = value;
}
- public void ParseAndCompile(string xaml, string baseUri, IFileSource fileSource, IXamlIlTypeBuilder tb, IXamlIlType overrideRootType)
+ public bool DefaultCompileBindings
{
- var parsed = XDocumentXamlIlParser.Parse(xaml, new Dictionary
+ get => _bindingTransformer.CompileBindingsByDefault;
+ set => _bindingTransformer.CompileBindingsByDefault = value;
+ }
+
+ public void ParseAndCompile(string xaml, string baseUri, IFileSource fileSource, IXamlTypeBuilder tb, IXamlType overrideRootType)
+ {
+ var parsed = XDocumentXamlParser.Parse(xaml, new Dictionary
{
{XamlNamespaces.Blend2008, XamlNamespaces.Blend2008}
});
- var rootObject = (XamlIlAstObjectNode)parsed.Root;
+ var rootObject = (XamlAstObjectNode)parsed.Root;
var classDirective = rootObject.Children
- .OfType().FirstOrDefault(x =>
+ .OfType().FirstOrDefault(x =>
x.Namespace == XamlNamespaces.Xaml2006
&& x.Name == "Class");
var rootType =
classDirective != null ?
- new XamlIlAstClrTypeReference(classDirective,
- _configuration.TypeSystem.GetType(((XamlIlAstTextNode)classDirective.Values[0]).Text),
+ new XamlAstClrTypeReference(classDirective,
+ _configuration.TypeSystem.GetType(((XamlAstTextNode)classDirective.Values[0]).Text),
false) :
- XamlIlTypeReferenceResolver.ResolveType(CreateTransformationContext(parsed, true),
- (XamlIlAstXmlTypeReference)rootObject.Type, true);
+ TypeReferenceResolver.ResolveType(CreateTransformationContext(parsed, true),
+ (XamlAstXmlTypeReference)rootObject.Type, true);
if (overrideRootType != null)
{
-
-
if (!rootType.Type.IsAssignableFrom(overrideRootType))
- throw new XamlIlLoadException(
+ throw new XamlX.XamlLoadException(
$"Unable to substitute {rootType.Type.GetFqn()} with {overrideRootType.GetFqn()}", rootObject);
- rootType = new XamlIlAstClrTypeReference(rootObject, overrideRootType, false);
+ rootType = new XamlAstClrTypeReference(rootObject, overrideRootType, false);
}
OverrideRootType(parsed, rootType);
@@ -119,17 +140,17 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
}
- public void OverrideRootType(XamlIlDocument doc, IXamlIlAstTypeReference newType)
+ public void OverrideRootType(XamlDocument doc, IXamlAstTypeReference newType)
{
- var root = (XamlIlAstObjectNode)doc.Root;
+ var root = (XamlAstObjectNode)doc.Root;
var oldType = root.Type;
if (oldType.Equals(newType))
return;
root.Type = newType;
- foreach (var child in root.Children.OfType())
+ foreach (var child in root.Children.OfType())
{
- if (child.Property is XamlIlAstNamePropertyReference prop)
+ if (child.Property is XamlAstNamePropertyReference prop)
{
if (prop.DeclaringType.Equals(oldType))
prop.DeclaringType = newType;
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompilerConfiguration.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompilerConfiguration.cs
new file mode 100644
index 0000000000..0c0dcb1634
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlCompilerConfiguration.cs
@@ -0,0 +1,26 @@
+using XamlX.Transform;
+using XamlX.TypeSystem;
+
+namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
+{
+ class AvaloniaXamlIlCompilerConfiguration : TransformerConfiguration
+ {
+ public XamlIlClrPropertyInfoEmitter ClrPropertyEmitter { get; }
+ public XamlIlPropertyInfoAccessorFactoryEmitter AccessorFactoryEmitter { get; }
+
+ public AvaloniaXamlIlCompilerConfiguration(IXamlTypeSystem typeSystem,
+ IXamlAssembly defaultAssembly,
+ XamlLanguageTypeMappings typeMappings,
+ XamlXmlnsMappings xmlnsMappings,
+ XamlValueConverter customValueConverter,
+ XamlIlClrPropertyInfoEmitter clrPropertyEmitter,
+ XamlIlPropertyInfoAccessorFactoryEmitter accessorFactoryEmitter)
+ : base(typeSystem, defaultAssembly, typeMappings, xmlnsMappings, customValueConverter)
+ {
+ ClrPropertyEmitter = clrPropertyEmitter;
+ AccessorFactoryEmitter = accessorFactoryEmitter;
+ AddExtra(ClrPropertyEmitter);
+ AddExtra(AccessorFactoryEmitter);
+ }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlLanguage.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlLanguage.cs
index a1fe6976b7..99ec3744bf 100644
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlLanguage.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/AvaloniaXamlIlLanguage.cs
@@ -2,10 +2,12 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers;
-using XamlIl;
-using XamlIl.Ast;
-using XamlIl.Transform;
-using XamlIl.TypeSystem;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Emit;
+using XamlX.IL;
+using XamlX.Transform;
+using XamlX.TypeSystem;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
{
@@ -17,12 +19,12 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
class AvaloniaXamlIlLanguage
{
- public static XamlIlLanguageTypeMappings Configure(IXamlIlTypeSystem typeSystem)
+ public static (XamlLanguageTypeMappings language, XamlLanguageEmitMappings emit) Configure(IXamlTypeSystem typeSystem)
{
var runtimeHelpers = typeSystem.GetType("Avalonia.Markup.Xaml.XamlIl.Runtime.XamlIlRuntimeHelpers");
var assignBindingAttribute = typeSystem.GetType("Avalonia.Data.AssignBindingAttribute");
var bindingType = typeSystem.GetType("Avalonia.Data.IBinding");
- var rv = new XamlIlLanguageTypeMappings(typeSystem)
+ var rv = new XamlLanguageTypeMappings(typeSystem)
{
SupportInitialize = typeSystem.GetType("System.ComponentModel.ISupportInitialize"),
XmlnsAttributes =
@@ -51,18 +53,22 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
},
InnerServiceProviderFactoryMethod =
runtimeHelpers.FindMethod(m => m.Name == "CreateInnerServiceProviderV1"),
- ProvideValueTargetPropertyEmitter = XamlIlAvaloniaPropertyHelper.Emit,
};
rv.CustomAttributeResolver = new AttributeResolver(typeSystem, rv);
- rv.ContextTypeBuilderCallback = (b, c) => EmitNameScopeField(rv, typeSystem, b, c);
- return rv;
+
+ var emit = new XamlLanguageEmitMappings
+ {
+ ProvideValueTargetPropertyEmitter = XamlIlAvaloniaPropertyHelper.EmitProvideValueTarget,
+ ContextTypeBuilderCallback = (b, c) => EmitNameScopeField(rv, typeSystem, b, c)
+ };
+ return (rv, emit);
}
public const string ContextNameScopeFieldName = "AvaloniaNameScope";
- private static void EmitNameScopeField(XamlIlLanguageTypeMappings mappings,
- IXamlIlTypeSystem typeSystem,
- IXamlIlTypeBuilder typebuilder, IXamlIlEmitter constructor)
+ private static void EmitNameScopeField(XamlLanguageTypeMappings mappings,
+ IXamlTypeSystem typeSystem,
+ IXamlTypeBuilder typebuilder, IXamlILEmitter constructor)
{
var nameScopeType = typeSystem.FindType("Avalonia.Controls.INameScope");
@@ -78,23 +84,23 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
}
- class AttributeResolver : IXamlIlCustomAttributeResolver
+ class AttributeResolver : IXamlCustomAttributeResolver
{
- private readonly IXamlIlType _typeConverterAttribute;
+ private readonly IXamlType _typeConverterAttribute;
- private readonly List> _converters =
- new List>();
+ private readonly List> _converters =
+ new List>();
- private readonly IXamlIlType _avaloniaList;
- private readonly IXamlIlType _avaloniaListConverter;
+ private readonly IXamlType _avaloniaList;
+ private readonly IXamlType _avaloniaListConverter;
- public AttributeResolver(IXamlIlTypeSystem typeSystem, XamlIlLanguageTypeMappings mappings)
+ public AttributeResolver(IXamlTypeSystem typeSystem, XamlLanguageTypeMappings mappings)
{
_typeConverterAttribute = mappings.TypeConverterAttributes.First();
- void AddType(IXamlIlType type, IXamlIlType conv)
- => _converters.Add(new KeyValuePair(type, conv));
+ void AddType(IXamlType type, IXamlType conv)
+ => _converters.Add(new KeyValuePair(type, conv));
void Add(string type, string conv)
=> AddType(typeSystem.GetType(type), typeSystem.GetType(conv));
@@ -113,7 +119,7 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
_avaloniaListConverter = typeSystem.GetType("Avalonia.Collections.AvaloniaListConverter`1");
}
- IXamlIlType LookupConverter(IXamlIlType type)
+ IXamlType LookupConverter(IXamlType type)
{
foreach(var p in _converters)
if (p.Key.Equals(type))
@@ -123,15 +129,15 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
return null;
}
- class ConstructedAttribute : IXamlIlCustomAttribute
+ class ConstructedAttribute : IXamlCustomAttribute
{
- public bool Equals(IXamlIlCustomAttribute other) => false;
+ public bool Equals(IXamlCustomAttribute other) => false;
- public IXamlIlType Type { get; }
+ public IXamlType Type { get; }
public List Parameters { get; }
public Dictionary Properties { get; }
- public ConstructedAttribute(IXamlIlType type, List parameters, Dictionary properties)
+ public ConstructedAttribute(IXamlType type, List parameters, Dictionary properties)
{
Type = type;
Parameters = parameters ?? new List();
@@ -139,7 +145,7 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
}
}
- public IXamlIlCustomAttribute GetCustomAttribute(IXamlIlType type, IXamlIlType attributeType)
+ public IXamlCustomAttribute GetCustomAttribute(IXamlType type, IXamlType attributeType)
{
if (attributeType.Equals(_typeConverterAttribute))
{
@@ -151,25 +157,25 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
return null;
}
- public IXamlIlCustomAttribute GetCustomAttribute(IXamlIlProperty property, IXamlIlType attributeType)
+ public IXamlCustomAttribute GetCustomAttribute(IXamlProperty property, IXamlType attributeType)
{
return null;
}
}
- public static bool CustomValueConverter(XamlIlAstTransformationContext context,
- IXamlIlAstValueNode node, IXamlIlType type, out IXamlIlAstValueNode result)
+ public static bool CustomValueConverter(AstTransformationContext context,
+ IXamlAstValueNode node, IXamlType type, out IXamlAstValueNode result)
{
if (type.FullName == "System.TimeSpan"
- && node is XamlIlAstTextNode tn
+ && node is XamlAstTextNode tn
&& !tn.Text.Contains(":"))
{
var seconds = double.Parse(tn.Text, CultureInfo.InvariantCulture);
- result = new XamlIlStaticOrTargetedReturnMethodCallNode(tn,
+ result = new XamlStaticOrTargetedReturnMethodCallNode(tn,
type.FindMethod("FromSeconds", type, false, context.Configuration.WellKnownTypes.Double),
new[]
{
- new XamlIlConstantNode(tn, context.Configuration.WellKnownTypes.Double, seconds)
+ new XamlConstantNode(tn, context.Configuration.WellKnownTypes.Double, seconds)
});
return true;
}
@@ -178,9 +184,9 @@ namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions
{
var scope = context.ParentNodes().OfType().FirstOrDefault();
if (scope == null)
- throw new XamlIlLoadException("Unable to find the parent scope for AvaloniaProperty lookup", node);
- if (!(node is XamlIlAstTextNode text))
- throw new XamlIlLoadException("Property should be a text node", node);
+ throw new XamlX.XamlLoadException("Unable to find the parent scope for AvaloniaProperty lookup", node);
+ if (!(node is XamlAstTextNode text))
+ throw new XamlX.XamlLoadException("Property should be a text node", node);
result = XamlIlAvaloniaPropertyHelper.CreateNode(context, text.Text, scope.TargetType, text);
return true;
}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AddNameScopeRegistration.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AddNameScopeRegistration.cs
index 805b733feb..cb36851bab 100644
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AddNameScopeRegistration.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AddNameScopeRegistration.cs
@@ -1,139 +1,120 @@
using System;
using System.Linq;
-using XamlIl.Ast;
-using XamlIl.Transform;
-using XamlIl.TypeSystem;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Transform;
+using XamlX.TypeSystem;
+using XamlX.Emit;
+using XamlX.IL;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
- class AddNameScopeRegistration : IXamlIlAstTransformer
+ class AddNameScopeRegistration : IXamlAstTransformer
{
- public IXamlIlAstNode Transform(XamlIlAstTransformationContext context, IXamlIlAstNode node)
+ public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
- if (node is XamlIlPropertyAssignmentNode pa
- && pa.Property.Name == "Name"
- && pa.Property.DeclaringType.FullName == "Avalonia.StyledElement")
+ if (node is XamlPropertyAssignmentNode pa)
{
- if (context.ParentNodes().FirstOrDefault() is XamlIlManipulationGroupNode mg
- && mg.Children.OfType().Any())
- return node;
-
- IXamlIlAstValueNode value = null;
- for (var c = 0; c < pa.Values.Count; c++)
- if (pa.Values[c].Type.GetClrType().Equals(context.Configuration.WellKnownTypes.String))
- {
- value = pa.Values[c];
- if (!(value is XamlIlAstTextNode))
+ if (pa.Property.Name == "Name"
+ && pa.Property.DeclaringType.FullName == "Avalonia.StyledElement")
+ {
+ if (context.ParentNodes().FirstOrDefault() is XamlManipulationGroupNode mg
+ && mg.Children.OfType().Any())
+ return node;
+
+ IXamlAstValueNode value = null;
+ for (var c = 0; c < pa.Values.Count; c++)
+ if (pa.Values[c].Type.GetClrType().Equals(context.Configuration.WellKnownTypes.String))
{
- var local = new XamlIlAstCompilerLocalNode(value);
- // Wrap original in local initialization
- pa.Values[c] = new XamlIlAstLocalInitializationNodeEmitter(value, value, local);
- // Use local
- value = local;
- }
+ value = pa.Values[c];
+ if (!(value is XamlAstTextNode))
+ {
+ var local = new XamlAstCompilerLocalNode(value);
+ // Wrap original in local initialization
+ pa.Values[c] = new XamlAstLocalInitializationNodeEmitter(value, value, local);
+ // Use local
+ value = local;
+ }
- break;
- }
+ break;
+ }
- if (value != null)
- return new XamlIlManipulationGroupNode(pa)
+ if (value != null)
{
- Children =
+ var objectType = context.ParentNodes().OfType().FirstOrDefault()?.Type.GetClrType();
+ return new XamlManipulationGroupNode(pa)
{
- pa,
- new AvaloniaNameScopeRegistrationXamlIlNode(value, context.GetAvaloniaTypes())
- }
- };
+ Children =
+ {
+ pa,
+ new AvaloniaNameScopeRegistrationXamlIlNode(value, objectType)
+ }
+ };
+ }
+ }
+ else if (pa.Property.CustomAttributes.Select(attr => attr.Type).Intersect(context.Configuration.TypeMappings.DeferredContentPropertyAttributes).Any())
+ {
+ pa.Values[pa.Values.Count - 1] =
+ new NestedScopeMetadataNode(pa.Values[pa.Values.Count - 1]);
+ }
}
- if (!context.ParentNodes().Any()
- && node is XamlIlValueWithManipulationNode mnode)
- {
- mnode.Manipulation = new XamlIlManipulationGroupNode(mnode,
- new[]
- {
- mnode.Manipulation,
- new HandleRootObjectScopeNode(mnode, context.GetAvaloniaTypes())
- });
- }
return node;
}
+ }
- class HandleRootObjectScopeNode : XamlIlAstNode, IXamlIlAstManipulationNode, IXamlIlAstEmitableNode
+ class NestedScopeMetadataNode : XamlValueWithSideEffectNodeBase
+ {
+ public NestedScopeMetadataNode(IXamlAstValueNode value) : base(value, value)
{
- private readonly AvaloniaXamlIlWellKnownTypes _types;
-
- public HandleRootObjectScopeNode(IXamlIlLineInfo lineInfo,
- AvaloniaXamlIlWellKnownTypes types) : base(lineInfo)
- {
- _types = types;
- }
-
- public XamlIlNodeEmitResult Emit(XamlIlEmitContext context, IXamlIlEmitter codeGen)
- {
- var next = codeGen.DefineLabel();
- var scopeField = context.RuntimeContext.ContextType.Fields.First(f =>
- f.Name == AvaloniaXamlIlLanguage.ContextNameScopeFieldName);
- using (var local = codeGen.LocalsPool.GetLocal(_types.StyledElement))
- {
- codeGen
- .Isinst(_types.StyledElement)
- .Dup()
- .Stloc(local.Local)
- .Brfalse(next)
- .Ldloc(local.Local)
- .Ldloc(context.ContextLocal)
- .Ldfld(scopeField)
- .EmitCall(_types.NameScopeSetNameScope, true)
- .MarkLabel(next)
- .Ldloc(context.ContextLocal)
- .Ldfld(scopeField)
- .EmitCall(_types.INameScopeComplete, true);
- }
-
- return XamlIlNodeEmitResult.Void(1);
-
- }
}
}
- class AvaloniaNameScopeRegistrationXamlIlNode : XamlIlAstNode, IXamlIlAstManipulationNode, IXamlIlAstEmitableNode
+ class AvaloniaNameScopeRegistrationXamlIlNode : XamlAstNode, IXamlAstManipulationNode
{
- private readonly AvaloniaXamlIlWellKnownTypes _types;
- public IXamlIlAstValueNode Name { get; set; }
+ public IXamlAstValueNode Name { get; set; }
+ public IXamlType TargetType { get; }
- public AvaloniaNameScopeRegistrationXamlIlNode(IXamlIlAstValueNode name, AvaloniaXamlIlWellKnownTypes types) : base(name)
+ public AvaloniaNameScopeRegistrationXamlIlNode(IXamlAstValueNode name, IXamlType targetType) : base(name)
{
- _types = types;
+ TargetType = targetType;
Name = name;
}
- public override void VisitChildren(IXamlIlAstVisitor visitor)
- => Name = (IXamlIlAstValueNode)Name.Visit(visitor);
+ public override void VisitChildren(IXamlAstVisitor visitor)
+ => Name = (IXamlAstValueNode)Name.Visit(visitor);
+ }
- public XamlIlNodeEmitResult Emit(XamlIlEmitContext context, IXamlIlEmitter codeGen)
+ class AvaloniaNameScopeRegistrationXamlIlNodeEmitter : IXamlAstLocalsNodeEmitter
+ {
+ public XamlILNodeEmitResult Emit(IXamlAstNode node, XamlEmitContextWithLocals context, IXamlILEmitter codeGen)
{
- var scopeField = context.RuntimeContext.ContextType.Fields.First(f =>
- f.Name == AvaloniaXamlIlLanguage.ContextNameScopeFieldName);
-
- using (var targetLoc = context.GetLocal(context.Configuration.WellKnownTypes.Object))
+ if (node is AvaloniaNameScopeRegistrationXamlIlNode registration)
{
- codeGen
- // var target = {pop}
- .Stloc(targetLoc.Local)
- // _context.NameScope.Register(Name, target)
- .Ldloc(context.ContextLocal)
- .Ldfld(scopeField);
-
- context.Emit(Name, codeGen, Name.Type.GetClrType());
-
- codeGen
- .Ldloc(targetLoc.Local)
- .EmitCall(_types.INameScopeRegister, true);
- }
+ var scopeField = context.RuntimeContext.ContextType.Fields.First(f =>
+ f.Name == AvaloniaXamlIlLanguage.ContextNameScopeFieldName);
+
+ using (var targetLoc = context.GetLocalOfType(context.Configuration.WellKnownTypes.Object))
+ {
+
+ codeGen
+ // var target = {pop}
+ .Stloc(targetLoc.Local)
+ // _context.NameScope.Register(Name, target)
+ .Ldloc(context.ContextLocal)
+ .Ldfld(scopeField);
- return XamlIlNodeEmitResult.Void(1);
+ context.Emit(registration.Name, codeGen, registration.Name.Type.GetClrType());
+
+ codeGen
+ .Ldloc(targetLoc.Local)
+ .EmitCall(context.GetAvaloniaTypes().INameScopeRegister, true);
+ }
+
+ return XamlILNodeEmitResult.Void(1);
+ }
+ return default;
}
}
}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionHackTransformer.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionHackTransformer.cs
deleted file mode 100644
index c89106312f..0000000000
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionHackTransformer.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using XamlIl.Ast;
-using XamlIl.Transform;
-
-namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
-{
- class AvaloniaBindingExtensionHackTransformer : IXamlIlAstTransformer
- {
- public IXamlIlAstNode Transform(XamlIlAstTransformationContext context, IXamlIlAstNode node)
- {
- // Our code base expects XAML parser to prefer `FooExtension` to `Foo` even with `` syntax
- // This is the legacy of Portable.Xaml, so we emulate that behavior here
-
- if (node is XamlIlAstXmlTypeReference tref
- && tref.Name == "Binding"
- && tref.XmlNamespace == "https://github.com/avaloniaui")
- tref.IsMarkupExtension = true;
- return node;
- }
- }
-}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionTransformer.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionTransformer.cs
new file mode 100644
index 0000000000..de2c0eab96
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaBindingExtensionTransformer.cs
@@ -0,0 +1,75 @@
+using System.Linq;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Transform;
+
+
+using XamlParseException = XamlX.XamlParseException;
+
+namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
+{
+ class AvaloniaBindingExtensionTransformer : IXamlAstTransformer
+ {
+ public bool CompileBindingsByDefault { get; set; }
+
+ public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
+ {
+ if (context.ParentNodes().FirstOrDefault() is AvaloniaXamlIlCompileBindingsNode)
+ {
+ return node;
+ }
+
+ if (node is XamlAstObjectNode obj)
+ {
+ foreach (var item in obj.Children)
+ {
+ if (item is XamlAstXmlDirective directive)
+ {
+ if (directive.Namespace == XamlNamespaces.Xaml2006
+ && directive.Name == "CompileBindings"
+ && directive.Values.Count == 1)
+ {
+ if (!(directive.Values[0] is XamlAstTextNode text
+ && bool.TryParse(text.Text, out var compileBindings)))
+ {
+ throw new XamlParseException("The value of x:CompileBindings must be a literal boolean value.", directive.Values[0]);
+ }
+
+ obj.Children.Remove(directive);
+
+ return new AvaloniaXamlIlCompileBindingsNode(obj, compileBindings);
+ }
+ }
+ }
+ }
+
+ // Convert the tag to either a CompiledBinding or ReflectionBinding tag.
+
+ if (node is XamlAstXmlTypeReference tref
+ && tref.Name == "Binding"
+ && tref.XmlNamespace == "https://github.com/avaloniaui")
+ {
+ tref.IsMarkupExtension = true;
+
+ var compileBindings = context.ParentNodes()
+ .OfType()
+ .FirstOrDefault()
+ ?.CompileBindings ?? CompileBindingsByDefault;
+
+ tref.Name = compileBindings ? "CompiledBinding" : "ReflectionBinding";
+ }
+ return node;
+ }
+ }
+
+ internal class AvaloniaXamlIlCompileBindingsNode : XamlValueWithSideEffectNodeBase
+ {
+ public AvaloniaXamlIlCompileBindingsNode(IXamlAstValueNode value, bool compileBindings)
+ : base(value, value)
+ {
+ CompileBindings = compileBindings;
+ }
+
+ public bool CompileBindings { get; }
+ }
+}
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlAvaloniaPropertyResolver.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlAvaloniaPropertyResolver.cs
index 74f5c29f6a..9219a39ddc 100644
--- a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlAvaloniaPropertyResolver.cs
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlAvaloniaPropertyResolver.cs
@@ -1,14 +1,14 @@
using System.Linq;
-using XamlIl.Ast;
-using XamlIl.Transform;
+using XamlX.Ast;
+using XamlX.Transform;
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
- class AvaloniaXamlIlAvaloniaPropertyResolver : IXamlIlAstTransformer
+ class AvaloniaXamlIlAvaloniaPropertyResolver : IXamlAstTransformer
{
- public IXamlIlAstNode Transform(XamlIlAstTransformationContext context, IXamlIlAstNode node)
+ public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
- if (node is XamlIlAstClrProperty prop)
+ if (node is XamlAstClrProperty prop)
{
var n = prop.Name + "Property";
var field =
diff --git a/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlBindingPathParser.cs b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlBindingPathParser.cs
new file mode 100644
index 0000000000..7944d8b569
--- /dev/null
+++ b/src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlBindingPathParser.cs
@@ -0,0 +1,332 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Avalonia.Markup.Parsers;
+using Avalonia.Utilities;
+using XamlX;
+using XamlX.Ast;
+using XamlX.Transform;
+using XamlX.Transform.Transformers;
+using XamlX.TypeSystem;
+
+using XamlParseException = XamlX.XamlParseException;
+
+namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
+{
+ class AvaloniaXamlIlBindingPathParser : IXamlAstTransformer
+ {
+ public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
+ {
+ if (node is XamlAstObjectNode binding && binding.Type.GetClrType().Equals(context.GetAvaloniaTypes().CompiledBindingExtension))
+ {
+ var convertedNode = ConvertLongFormPropertiesToBindingExpressionNode(context, binding);
+
+ if (binding.Arguments.Count > 0 && binding.Arguments[0] is XamlAstTextNode bindingPathText)
+ {
+ var reader = new CharacterReader(bindingPathText.Text.AsSpan());
+ var (nodes, _) = BindingExpressionGrammar.Parse(ref reader);
+
+ if (convertedNode != null)
+ {
+ nodes.Insert(nodes.TakeWhile(x => x is BindingExpressionGrammar.ITransformNode).Count(), convertedNode);
+ }
+
+ binding.Arguments[0] = new ParsedBindingPathNode(bindingPathText, context.GetAvaloniaTypes().CompiledBindingPath, nodes);
+ }
+ else
+ {
+ var bindingPathAssignment = binding.Children.OfType()
+ .FirstOrDefault(v => v.Property.GetClrProperty().Name == "Path");
+
+ if (bindingPathAssignment != null && bindingPathAssignment.Values[0] is XamlAstTextNode pathValue)
+ {
+ var reader = new CharacterReader(pathValue.Text.AsSpan());
+ var (nodes, _) = BindingExpressionGrammar.Parse(ref reader);
+
+ if (convertedNode != null)
+ {
+ nodes.Insert(nodes.TakeWhile(x => x is BindingExpressionGrammar.ITransformNode).Count(), convertedNode);
+ }
+
+ bindingPathAssignment.Values[0] = new ParsedBindingPathNode(pathValue, context.GetAvaloniaTypes().CompiledBindingPath, nodes);
+ }
+ }
+ }
+
+ return node;
+ }
+
+ private static BindingExpressionGrammar.INode ConvertLongFormPropertiesToBindingExpressionNode(
+ AstTransformationContext context,
+ XamlAstObjectNode binding)
+ {
+ BindingExpressionGrammar.INode convertedNode = null;
+
+ var syntheticCompiledBindingProperties = binding.Children.OfType()
+ .Where(v => v.Property is AvaloniaSyntheticCompiledBindingProperty)
+ .ToList();
+
+ var elementNameProperty = syntheticCompiledBindingProperties
+ .FirstOrDefault(v =>
+ v.Property is AvaloniaSyntheticCompiledBindingProperty prop
+ && prop.Name == SyntheticCompiledBindingPropertyName.ElementName);
+
+ var sourceProperty = syntheticCompiledBindingProperties
+ .FirstOrDefault(v =>
+ v.Property is AvaloniaSyntheticCompiledBindingProperty prop
+ && prop.Name == SyntheticCompiledBindingPropertyName.Source);
+
+ var relativeSourceProperty = syntheticCompiledBindingProperties
+ .FirstOrDefault(v =>
+ v.Property is AvaloniaSyntheticCompiledBindingProperty prop
+ && prop.Name == SyntheticCompiledBindingPropertyName.RelativeSource);
+
+ if (elementNameProperty?.Values[0] is XamlAstTextNode elementName)
+ {
+ convertedNode = new BindingExpressionGrammar.NameNode { Name = elementName.Text };
+ }
+ else if (elementNameProperty != null)
+ {
+ throw new XamlParseException($"Invalid ElementName '{elementNameProperty.Values[0]}'.", elementNameProperty.Values[0]);
+ }
+
+ if (sourceProperty?.Values[0] != null)
+ {
+ if (convertedNode != null)
+ {
+ throw new XamlParseException("Only one of ElementName, Source, or RelativeSource specified as a binding source. Only one property is allowed.", binding);
+ }
+
+ convertedNode = new RawSourceBindingExpressionNode(sourceProperty?.Values[0]);
+ }
+
+ if (GetRelativeSourceObjectFromAssignment(
+ context,
+ relativeSourceProperty,
+ out var relativeSourceObject))
+ {
+ if (convertedNode != null)
+ {
+ throw new XamlParseException("Only one of ElementName, Source, or RelativeSource specified as a binding source. Only one property is allowed.", binding);
+ }
+
+ var mode = relativeSourceObject.Children
+ .OfType()
+ .FirstOrDefault(x => x.Property.GetClrProperty().Name == "Mode")
+ ?.Values[0] is XamlAstTextNode modeAssignedValue ? modeAssignedValue.Text : null;
+ if (relativeSourceObject.Arguments.Count == 0 && mode == null)
+ {
+ mode = "FindAncestor";
+ }
+
+ if (mode == "FindAncestor")
+ {
+ var ancestorLevel = relativeSourceObject.Children
+ .OfType()
+ .FirstOrDefault(x => x.Property.GetClrProperty().Name == "FindAncestor")
+ ?.Values[0] is XamlAstTextNode ancestorLevelText ? int.Parse(ancestorLevelText.Text) - 1 : 0;
+
+ var treeType = relativeSourceObject.Children
+ .OfType()
+ .FirstOrDefault(x => x.Property.GetClrProperty().Name == "Tree")
+ ?.Values[0] is XamlAstTextNode treeTypeValue ? treeTypeValue.Text : "Visual";
+
+ var ancestorTypeName = relativeSourceObject.Children
+ .OfType()
+ .FirstOrDefault(x => x.Property.GetClrProperty().Name == "AncestorType")
+ ?.Values[0] as XamlAstTextNode;
+
+ IXamlType ancestorType = null;
+ if (ancestorTypeName is null)
+ {
+ if (treeType == "Visual")
+ {
+ throw new XamlParseException("AncestorType must be set for RelativeSourceMode.FindAncestor when searching the visual tree.", relativeSourceObject);
+ }
+ else if (treeType == "Logical")
+ {
+ var styledElementType = context.GetAvaloniaTypes().StyledElement;
+ ancestorType = context
+ .ParentNodes()
+ .OfType()
+ .Where(x => styledElementType.IsAssignableFrom(x.Type.GetClrType()))
+ .ElementAtOrDefault(ancestorLevel)
+ ?.Type.GetClrType();
+
+ if (ancestorType is null)
+ {
+ throw new XamlX.XamlParseException("Unable to resolve implicit ancestor type based on XAML tree.", relativeSourceObject);
+ }
+ }
+ }
+ else
+ {
+ ancestorType = TypeReferenceResolver.ResolveType(
+ context,
+ ancestorTypeName.Text,
+ false,
+ ancestorTypeName,
+ true).GetClrType();
+ }
+
+ if (treeType == "Visual")
+ {
+ convertedNode = new VisualAncestorBindingExpressionNode
+ {
+ Type = ancestorType,
+ Level = ancestorLevel
+ };
+ }
+ else if (treeType == "Logical")
+ {
+ convertedNode = new LogicalAncestorBindingExpressionNode
+ {
+ Type = ancestorType,
+ Level = ancestorLevel
+ };
+ }
+ else
+ {
+ throw new XamlParseException($"Unknown tree type '{treeType}'.", binding);
+ }
+ }
+ else if (mode == "DataContext")
+ {
+ convertedNode = null;
+ }
+ else if (mode == "Self")
+ {
+ convertedNode = new BindingExpressionGrammar.SelfNode();
+ }
+ else if (mode == "TemplatedParent")
+ {
+ var parentType = context.ParentNodes().OfType()
+ .FirstOrDefault(x =>
+ x.ScopeType == AvaloniaXamlIlTargetTypeMetadataNode.ScopeTypes.ControlTemplate)
+ ?.TargetType.GetClrType();
+
+ if (parentType is null)
+ {
+ throw new XamlParseException("A binding with a TemplatedParent RelativeSource has to be in a ControlTemplate.", binding);
+ }
+
+ convertedNode = new TemplatedParentBindingExpressionNode { Type = parentType };
+ }
+ else
+ {
+ throw new XamlParseException($"Unknown RelativeSource mode '{mode}'.", binding);
+ }
+ }
+
+ if (elementNameProperty != null)
+ {
+ binding.Children.Remove(elementNameProperty);
+ }
+ if (sourceProperty != null)
+ {
+ binding.Children.Remove(sourceProperty);
+ }
+ if (relativeSourceProperty != null)
+ {
+ binding.Children.Remove(relativeSourceProperty);
+ }
+
+ return convertedNode;
+ }
+
+ private static bool GetRelativeSourceObjectFromAssignment(
+ AstTransformationContext context,
+ XamlAstXamlPropertyValueNode relativeSourceProperty,
+ out XamlAstObjectNode relativeSourceObject)
+ {
+ relativeSourceObject = null;
+ if (relativeSourceProperty is null)
+ {
+ return false;
+ }
+
+ if (relativeSourceProperty.Values[0] is XamlMarkupExtensionNode me)
+ {
+ if (me.Type.GetClrType() != context.GetAvaloniaTypes().RelativeSource)
+ {
+ throw new XamlParseException($"Expected an object of type 'Avalonia.Data.RelativeSource'. Found a object of type '{me.Type.GetClrType().GetFqn()}'", me);
+ }
+
+ relativeSourceObject = (XamlAstObjectNode)me.Value;
+ return true;
+ }
+
+ if (relativeSourceProperty.Values[0] is XamlAstObjectNode on)
+ {
+ if (on.Type.GetClrType() != context.GetAvaloniaTypes().RelativeSource)
+ {
+ throw new XamlParseException($"Expected an object of type 'Avalonia.Data.RelativeSource'. Found a object of type '{on.Type.GetClrType().GetFqn()}'", on);
+ }
+
+ relativeSourceObject = on;
+ return true;
+ }
+
+ return false;
+ }
+ }
+
+ class ParsedBindingPathNode : XamlAstNode, IXamlAstValueNode
+ {
+ public ParsedBindingPathNode(IXamlLineInfo lineInfo, IXamlType compiledBindingType, IList