Skip to content

[Spec] Slim Renderer Architecture #28

Closed

Description

@StephaneDelcroix

WARNING: this spec is still a WIP, we're still experimenting with this concept

Description

Slim renderers architecture benefits from multi-targetting and single-project features.

Example

EntryRenderer.cs

public partial class EntryRenderer {
   public static PropertyMapper<IView> ViewMapper = new PropertyMapper<IView> {
	
     // Add your own method to map to any property         
     [nameof(IView.BackgroundColor)] = MapBackgroundColor

   };
}

EntryRenderer.iOS.cs

// You don’t need to register a new renderer.
public partial class EntryRenderer
{
     // You know what method to call because you named it!
   public static void MapBackgroundColor (IViewRenderer renderer, IView view)
     {
        // You don’t need to call any base methods here or worry about order.
   
        // Every renderer is consistent; you know where the native view is.
          var nativeView = (NativeView)renderer.NativeView;
          var color = view.BackgroundColor;

          if (color != null) {

            // Phew! That was easy!	        
            nativeView.BackgroundColor = UIColor.FromRGB (204, 153, 255);
          }
     }
}

Standardization of renderers

All the default renderers will be ported to this architecture, for all platforms

Registration of renderers

The rendererRegistrar will exists on the dependency service and be accessed by serviceCollection.Get<IRendererRegistrar>(), allowing control to which renderer is associated to which control

Interfaces on renderers

Mapper concept

The property mapper is responsible for triggering actions in response property changes. A slim renderer itself does not subscribe to the property changes, but some declared actions are executed in response to changes.

The property mapper property of a control is public static and can be extended by user code.

The property mapper plays no role in the feedback loop (button clicked, text entered)

TODO: discuss what to use for mapper key. string or object ? It'd be nice to avoid string comparison in case when we can compare references (in case of BindableProperties)

How to use legacy custom renderers

How to use third-party controls depending on old renderers

How to complement existing renderers

The new extensibility model for this architecture is based on the property mapper. When you want to add support for a new property, it only requires mapping the new property. For the property to exists, subclassing the control is necessary, but subclassing the renderer is not.

Backward Compatibility

Wether we want to keep backward compatibility with existing custom renderers, or subclasses of old renderers will influence the architecture of this

Difficulty : very high

Activity

  1. yasmoradi commented on May 19, 2020

    @yasmoradi
    Contributor

    Xamarin forms wpf renderers and some of android renderers such as ButtonRenderer are fast, and we know what does "fast" mean here.
    Are these renderers will be fast or not?
    Thanks in advance.

  2. samhouts commented on May 19, 2020

    @samhouts
    Contributor

    @ysmoradi Yep! These new renderers will follow the fast renderer pattern (i.e., no wrapper view around the main view). We plan to do this for all platforms, not just Android and WPF.

  3. MichaelRumpler commented on May 19, 2020

    @MichaelRumpler
    Contributor

    Please don't try to stay backwards compatible at all costs. This is something new. It does not have to be compatible with XF. You can make something better.

  4. ugnivs commented on May 19, 2020

    @ugnivs

    Why not to make UI framework with own set of controls without any kind of mappings and behavioral logic fully written on c# that would be rendered with Skia graphics library? As people use strongly customized design there is no need in trying to match platform design guidelines. The only need is possibility of flexible customizations. Please correct me if i'm missing something, but i don't understand why benefit is over Renderer architecture.

  5. pranshu-aggarwal commented on May 19, 2020

    @pranshu-aggarwal

    With this approach, is it possible to write a cross-platform renderer instead of the platform-specific renderer? Like mapping Button control with skia-sharp control .

  6. h82258652 commented on May 20, 2020

    @h82258652

    Platform renderer is a bad design. As you see, there are lots of xamarin control libs that don't support UWP due to the platform limit.
    Take an example, the shadow in UWP. You can't get a corner shadow from a corner button (of course, you can change the button template to do this, but that's another thing).

    I know it is very difficult to build a cross platform render. But flutter told us this is feasible. In the long term, a cross-platform renderer is the best solution.

  7. Soul-Master commented on May 20, 2020

    @Soul-Master

    I think render entire app as custom 2d canvas might work seamlessly for mobile app.

    But it might not work for desktop app or complex app because there are so many user actions that need to be re-implemented like drag-drop, text selection, keyboard shortcut to manipulate text and so on.

    Why not to make UI framework with own set of controls without any kind of mappings and behavioral logic fully written on c# that would be rendered with Skia graphics library? As people use strongly customized design there is no need in trying to match platform design guidelines. The only need is possibility of flexible customizations. Please correct me if i'm missing something, but i don't understand why benefit is over Renderer architecture.

  8. ugnivs commented on May 20, 2020

    @ugnivs

    I think render entire app as custom 2d canvas might work seamlessly for mobile app.

    But it might not work for desktop app or complex app because there are so many user actions that need to be re-implemented like drag-drop, text selection, keyboard shortcut to manipulate text and so on.

    Why not to make UI framework with own set of controls without any kind of mappings and behavioral logic fully written on c# that would be rendered with Skia graphics library? As people use strongly customized design there is no need in trying to match platform design guidelines. The only need is possibility of flexible customizations. Please correct me if i'm missing something, but i don't understand why benefit is over Renderer architecture.

    You're absolutely right about all of this stuff, but the team is not forced to choose the only one approach. I think this all about lack of time. I mean they just need to release a "brand new" fully crossplatform ui framework in a year together with .net 6. And and it's much less risky to take good old time-tested framework as the basis. It's ok and it should be. But i believe that in long time run custom 2d canvas rendering have much more benefits and really deserves to be called "cross platform". Xamarin forms is really good thing and it has a huge progress for today. But it's time to move on. Microsoft and xamarin teams have very clever engineers and they probably considering such an approach or maybe even have some connections with http://avaloniaui.net/ as a trump card

  9. filipoff2 commented on May 20, 2020

    @filipoff2

    Why not to make UI framework with own set of controls without any kind of mappings and behavioral logic fully written on c# that would be rendered with Skia graphics library? As people use strongly customized design there is no need in trying to match platform design guidelines. The only need is possibility of flexible customizations. Please correct me if i'm missing something, but i don't understand why benefit is over Renderer architecture.

    It could be cool to have 4-th render default grey one for Skia developers will 100% change it for sure to deliver rich design,
    For back combability would leave those 3 as they are but add " draw it yourself dear developer"_skia_render and take 90% responsibility for it developer.

  10. velocitysystems commented on May 20, 2020

    @velocitysystems

    If the concept of renderers is to be maintained, can thought be given to eliminating the bridge between shared UI code and renderers via INotifyPropertyChanged and event handlers? i.e.

    • Instead of setting a property on the shared control and a PropertyChanged event being propagated, can the property be mapped and set directly on the platform renderer?
    • Instead of calling a method on the shared control and an event being fired and handled by the renderer, can the method be mapped and involved directly on the platform renderer?

    INotifyPropertyChanged is great for MVVM design and loosely-couple view models, but has always felt clunky as a bridge mechanism between the shared UI code and platform renderers. This in turn would lead to better performance, less 'chattiness' between the shared UI and renderer layer and a better developer experience.

  11. freever commented on May 20, 2020

    @freever

    This is long but worth watching for some "inside baseball" on Maui.
    https://www.youtube.com/watch?v=_MGh3xipWm4

    It sounds like the architecture of Maui will support both platform-rendered controls and canvas-drawn controls, and furthermore that the noble @Clancey will be continuing to work on a skia-based render set for Maui which will not only work in the MVU flavour of Maui but also for the MVVM pattern.

    At first glance Maui seemed like a rebranding of Forms, but on closer inspection it is a restructuring of the Forms architecture to make its layers more loosely coupled and thereby support many of the things we are asking about in this thread. Fun times ahead.

  12. GalaxiaGuy commented on May 20, 2020

    @GalaxiaGuy
    Contributor

    This is slightly off topic, but is something I've wanted to ask just because of its relevance to this exact thing:

    How does memory work with SKCanvasView (or Skia in general)? Does each one always take up memory proportional to its size? Does this change if it overlaps others?

    If, for example I had a gradient control (renderer written in Skia) and over the top of that I had a semi transparent button (renderer written in Skia) would that take up twice as much memory, or is the graphics context somehow shared? How about if Skia controls overlapped non-Skia controls?

    I've considered implementing some fancy graphics controls in Forms using Skia before, but not understanding how the memory works has always caused enough concern that I haven't.

  13. h82258652 commented on May 20, 2020

    @h82258652

    @GalaxiaGuy I think using a skia control overlapped on a non-skia control, just like a winform control hosted on a wpf control. You can do this, but not the best.
    If you have two controls rendered by SKCanvasView, the graphics context will not be shared. The best way is to composite the two rendered and draw it on a single canvas.
    In my test, the SkiaSharp performance is not so bad if you just do some static things. And I try to do some animations, the CPU usage is a little high on my laptop.

  14. legistek commented on May 20, 2020

    @legistek
    Contributor

    Why are so many people obsessed with Skia? A good rendering spec would be agnostic to the rendering engine used at the low level. If a particular platform renderer wants to use Skia (or Direct2D or OpenGL or whatever) that shouldn't be something the application layer should have to worry about.

  15. 66 remaining items

  16. Charuwaka commented on May 17, 2021

    @Charuwaka

    I have built several apps in xamarin forms, recently I switched to the flutter, what I instantly noticed is, ease of writing UI. I built a simple dashboard UI (refer below) within 1.5 days, if it is xamarin forms it would take me at least 3-4 days(as per my experience). Hot reload works like a charm in flutter(but most of the time it sucks in xamarin forms especially if your writing a custom renderer for a button, you cant see preview).

    Screenshot 2021-05-17 at 1 52 53 PM

    I don't want to write a custom renderer for even simple things(Shadows, Elevations, etc), which is a tedious task, please find a way to avoid custom renderers as much as possible. Writing animations also very simple which is not the case in xamarin forms.

    From a backend perspective C# is pretty solid in terms of (MVVM, DI, Design patterns) hands down!

  17. programming98 commented on May 19, 2021

    @programming98

    I've been developing with Xamarin.Forms since its inception. Every client I've worked for has wanted as close to an identical UI as possible on all target platforms. Clients do not want or need native controls/widgets/views to be rendered typically. It is a rare edge case. All clients I've worked for have adopted Xamarin because existing .NET developers could use C#/.NET to build mobile apps, while being able to consume existing libraries without reinventing the wheel. Clients and developers I've spoken to want Microsoft to ditch the native UI approach, and to emulate the Flutter and UNO approach of rendering controls independently of the constraints of the platform. The majority of development time is spent trying to tweak the UI to make it look identical on both platforms for current Xamarin developers. With the release of Flutter 2.2, it is becoming increasingly difficult to rationalize further investment in MAUI until this becomes THE primary architecture for the platform. Mimicking the Flutter/UNO approach highly simplifies the development process on your end, and working prototypes are already alive and well that should be used to accelerate development. This is where developers want MS and the MAUI/Xamarin team to invest in. The holy grail for developers is for MS to emulate Flutter's architecture while giving we developers the massive advantage of being able to continue to use .NET and C# so we don't have to reinvent the wheel by rewriting libraries in an immature language like Dart. Finally, Microsoft is investing in working with Google to allow Flutter to target Windows.. MS should instead be investing in competing directly with Google by building MAUI the way its veteran developers want. If MAUI goes native UI first at launch, it will be obsolete the day it is released. If this happens, after seven years of using Xamarin/.NET to develop mobile apps, I will move on and invest in Flutter instead, because at least Google has its head on straight enough to build the tools we want and need.

  18. nickrandolph commented on May 20, 2021

    @nickrandolph
    Contributor

    @brencode there's room in the market for different solutions and different approaches. I agree that for the most part Flutter is dominating this space as Google seems to be investing heavily in marketing (they see this as a loss leader for their cloud platform). I see that Maui and Uno are attempting to solve same issue but coming from different directions. If you want 100% consistency of layout etc, then Uno is the answer. If you want a framework for rapidly scaffolding an application, the Maui with pieces like Shell will give you that jump start - it also is the way to go if your company/customer is fixated on not using third party frameworks (I don't understand this but it does exist with some orgs)

  19. giuseppenovielli commented on May 20, 2021

    @giuseppenovielli

    @brencode but MAUI will be implement also with draw controls by https://github.com/dotnet/Microsoft.Maui.Graphics.Controls

  20. Charuwaka commented on May 20, 2021

    @Charuwaka

    Xamarin is very good from a backend perspective, I can quickly build enterprise architecture patterns with ease, but when it comes to UI, I need to spend a lot of time to match UI pixel perfectly with a mockup. Please focus on the UI part that's all we want. why don't you guys use Skia Sharp to draw controls on canvas which can eliminate all UI renderers. let me show a simple example, I want to create a simple round corner Entry like below. see how much code I need to write for xamarin vs flutter.

    6wSSE

    Flutter way

    TextField(
     decoration: new InputDecoration(
         border: new OutlineInputBorder(
           borderRadius: const BorderRadius.all(
             const Radius.circular(10.0),
           ),
         ),
         filled: true,
         hintStyle: new TextStyle(color: Colors.grey[800]),
         hintText: "Type in your text",
         fillColor: Colors.white70),
    )
    

    Xamarin Way

    //UI
    < controls: CustomEntry IsPassword = "True"
    x: Name = "txtEmail"
    Style = "{StaticResource EntryStyle}" > </controls:CustomEntry>
    
    / / Custom Entry
    public class CustomEntry: Entry {}
    
    //Android Shape
    
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" > 
        <stroke android:width="1dp" android:color="#e7e7e7" /> 
        <solid android:color="#fafafa" /> 
        <padding android:left="1dp" android:right="1dp" android:top="1dp" /> 
        <corners android:radius="5dp" />
    </shape>
    
    //Android Renderer
    public class CustomEntryRenderer: EntryRenderer {
    	public CustomEntryRenderer(Context context) : base(context) {
    		AutoPackage = false;
    	}
    	protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) 
            { 
                base.OnElementChanged(e);
                if (Control != null) 
                { 
                    Control.Background = Android.App.Application.Context.GetDrawable(Resource.Drawable.rounded_corners); 
                    Control.Gravity = GravityFlags.CenterVertical; 
                    Control.SetPadding(10, 0, 0, 0); } 
                }
            }
    }
    
    //iOS Renderer
    public class CustomEntryRenderer: EntryRenderer {
    	protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
    		base.OnElementPropertyChanged(sender, e);
    		Control.Layer.BorderWidth = 0;
    		Control.BorderStyle = UITextBorderStyle.None;
    	}
    }
    

    see how much code it took to show a simple round corner text field in xamarin forms vs flutter? , this is where lot of people going away from xamarin.

  21. saint4eva commented on May 21, 2021

    @saint4eva

    Xamarin is very good from a backend perspective, I can quickly build enterprise architecture patterns with ease, but when it comes to UI, I need to spend a lot of time to match UI pixel perfectly with a mockup. Please focus on the UI part that's all we want. why don't you guys use Skia Sharp to draw controls on canvas which can eliminate all UI renderers. let me show a simple example, I want to create a simple round corner Entry like below. see how much code I need to write for xamarin vs flutter.

    6wSSE

    Flutter way

    TextField(
     decoration: new InputDecoration(
         border: new OutlineInputBorder(
           borderRadius: const BorderRadius.all(
             const Radius.circular(10.0),
           ),
         ),
         filled: true,
         hintStyle: new TextStyle(color: Colors.grey[800]),
         hintText: "Type in your text",
         fillColor: Colors.white70),
    )
    

    Xamarin Way

    //UI
    < controls: CustomEntry IsPassword = "True"
    x: Name = "txtEmail"
    Style = "{StaticResource EntryStyle}" > </controls:CustomEntry>
    
    / / Custom Entry
    public class CustomEntry: Entry {}
    
    //Android Shape
    
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" > 
        <stroke android:width="1dp" android:color="#e7e7e7" /> 
        <solid android:color="#fafafa" /> 
        <padding android:left="1dp" android:right="1dp" android:top="1dp" /> 
        <corners android:radius="5dp" />
    </shape>
    
    //Android Renderer
    public class CustomEntryRenderer: EntryRenderer {
    	public CustomEntryRenderer(Context context) : base(context) {
    		AutoPackage = false;
    	}
    	protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) 
            { 
                base.OnElementChanged(e);
                if (Control != null) 
                { 
                    Control.Background = Android.App.Application.Context.GetDrawable(Resource.Drawable.rounded_corners); 
                    Control.Gravity = GravityFlags.CenterVertical; 
                    Control.SetPadding(10, 0, 0, 0); } 
                }
            }
    }
    
    //iOS Renderer
    public class CustomEntryRenderer: EntryRenderer {
    	protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
    		base.OnElementPropertyChanged(sender, e);
    		Control.Layer.BorderWidth = 0;
    		Control.BorderStyle = UITextBorderStyle.None;
    	}
    }
    

    see how much code it took to show a simple round corner text field in xamarin forms vs flutter? , this is where lot of people going away from xamarin.

    Try the .NET Maui C# MVU - Comet

    https://github.com/dotnet/Comet

  22. saint4eva commented on May 21, 2021

    @saint4eva

    I've been developing with Xamarin.Forms since its inception. Every client I've worked for has wanted as close to an identical UI as possible on all target platforms. Clients do not want or need native controls/widgets/views to be rendered typically. It is a rare edge case. All clients I've worked for have adopted Xamarin because existing .NET developers could use C#/.NET to build mobile apps, while being able to consume existing libraries without reinventing the wheel. Clients and developers I've spoken to want Microsoft to ditch the native UI approach, and to emulate the Flutter and UNO approach of rendering controls independently of the constraints of the platform. The majority of development time is spent trying to tweak the UI to make it look identical on both platforms for current Xamarin developers. With the release of Flutter 2.2, it is becoming increasingly difficult to rationalize further investment in MAUI until this becomes THE primary architecture for the platform. Mimicking the Flutter/UNO approach highly simplifies the development process on your end, and working prototypes are already alive and well that should be used to accelerate development. This is where developers want MS and the MAUI/Xamarin team to invest in. The holy grail for developers is for MS to emulate Flutter's architecture while giving we developers the massive advantage of being able to continue to use .NET and C# so we don't have to reinvent the wheel by rewriting libraries in an immature language like Dart. Finally, Microsoft is investing in working with Google to allow Flutter to target Windows.. MS should instead be investing in competing directly with Google by building MAUI the way its veteran developers want. If MAUI goes native UI first at launch, it will be obsolete the day it is released. If this happens, after seven years of using Xamarin/.NET to develop mobile apps, I will move on and invest in Flutter instead, because at least Google has its head on straight enough to build the tools we want and need.

    MAUI C# MVU - Comet. Also, .NET Maui will have support for drawn UI using GraphicsControl

    https://github.com/dotnet/Comet

    https://github.com/dotnet/Microsoft.Maui.Graphics.Controls

    https://github.com/dotnet/Microsoft.Maui.Graphics

  23. GalaxiaGuy commented on May 21, 2021

    @GalaxiaGuy
    Contributor

    I've seen this conversation happening in a few places, and I thought I'd share my own experience (despite the fact the plural of "anecdote" is not "data").

    This does not match my experience with Xamarin. The clients I've worked with have mostly fallen into two categories:

    Those that don't care about the UI details. Pixel perfect UI is not interesting to them compared to delivering functionality. For them, sharing business logic between platforms (and sometimes with a C# server) that can be delivered quickly is number one priority.

    Those that want a native looking app. Most of these have avoided Forms (for example because they want to use native navigation patterns (Android supports a lot more patterns that are a challenge on iOS)). This has started to change now with some Forms embedding and the fact that I can use effects to apply some existing native styling code to Forms controls has made that much easier.

    A final note that is finally getting more attention is accessibility. I've just started to scratch the surface of advanced accessibility stuff iOS and Android support natively, and being able to get access to that (even in Forms) is important. Re-implementing controls would involve a lot of work on that front.

    (Bit of a cheap shot, but do your designers who care about the pixels being perfect for sighted users care about the screenreader announcements being perfect for blind users?)

  24. Jure-BB commented on May 21, 2021

    @Jure-BB

    A final note that is finally getting more attention is accessibility. I've just started to scratch the surface of advanced accessibility stuff iOS and Android support natively, and being able to get access to that (even in Forms) is important. Re-implementing controls would involve a lot of work on that front.

    (Bit of a cheap shot, but do your designers who care about the pixels being perfect for sighted users care about the screenreader announcements being perfect for blind users?)

    Yes, accessibility is important. Issue with current platform specific controls is that they are highly coupled by design. Single control can contain behavior logic, drawing logic, user input handling and accessibility all tied to a single platform APIs. Customizing just a single aspect of a control in a multiplatform application means re-implementing same thing multiple times with vastly different APIs.

    Providing unified abstractions over lower-level platform APIs and building controls on top, gives multiplatform developers ability to customize controls at much lower cost. Unified APIs enable developers to implement, for example, customized drawing or customized reactions to scroll input only once, instead of writing separate implementation for each platform.

    Even though the cost of developing framework like this is higher in the beginning, the cost in the long run is probably smaller, as creating and maintaining loosely coupled multiplatform controls is much more cost effective for framework developers too. Look how basic Xamarin.Forms controls still are after so many years and how quickly Flutter controls are evolving. Most of Xamarin.Forms controls implement only functionality that is common on all platforms and are often missing functionality that is provided just by a single vendor. For controls build on top of unified abstractions of low-level APIs, this becomes a non-issue. Every functionality implemented in a control is instantly avaliable on all platforms. Framework controls also don't need to lag behind platform specific controls anymore, as framework can provide even controls or functionality that is not avaliable in any platform's UI framework.

    If there is any issue with providing accessibility features for custom-drawn controls, it is up to platform vendors to provide better APIs for this kind of multiplatform frameworks.

  25. unpinned this issue on May 26, 2021
  26. deleted a comment from Rand-Random on Jan 16, 2022
  27. deleted a comment from Solaiman100 on Jan 16, 2022
  28. ghost locked as resolved and limited conversation to collaborators on Feb 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions