BorrowedTorch.UIDPGenerator
4.0.0
Prefix Reserved
dotnet add package BorrowedTorch.UIDPGenerator --version 4.0.0
NuGet\Install-Package BorrowedTorch.UIDPGenerator -Version 4.0.0
<PackageReference Include="BorrowedTorch.UIDPGenerator" Version="4.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="BorrowedTorch.UIDPGenerator" Version="4.0.0" />
<PackageReference Include="BorrowedTorch.UIDPGenerator"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add BorrowedTorch.UIDPGenerator --version 4.0.0
#r "nuget: BorrowedTorch.UIDPGenerator, 4.0.0"
#:package BorrowedTorch.UIDPGenerator@4.0.0
#addin nuget:?package=BorrowedTorch.UIDPGenerator&version=4.0.0
#tool nuget:?package=BorrowedTorch.UIDPGenerator&version=4.0.0
BorrowedTorchUI Dependency Properties Generator
Generator of dependency properties for the BorrowedTorchUI framework.
It scans a project folder for XML .dpg files and generates, next to each one, a partial
element class with its dependency properties (created when first used, with their owner actions and
defaults shared by the class), wrapping properties and initialization code, plus an optional partial
style class.
It ships as a NuGet package that runs the generator before every build of the consuming project, and can also be run by hand from the command line. The consuming project is BorrowedTorch.UI itself, or a game or library of your own that references it and adds elements of its own (see Elements of your own project).
Version 4.0.0
The generated code compiles in a project outside BorrowedTorch.UI, so a game can generate the dependency properties and the style of an element of its own. This changes the generated contract:
DisposeDependencyPropertiesand the style'sApplyValuesandClearValuesareprotectedinstead ofinternal(BaseElementandBaseStyledeclare themprotected virtual, the others override them). BorrowedTorch.UI applies and clears a style through internal members of its ownBaseStyle.Initializecalls the protectedApplyMouseCursors()ofBaseElementinstead of an internal extension method.- An element derives from the style its
<Style name="…">names (it took<ElementName>Stylewhatever the name). - The element and its style refer to each other by their full names (
global::Game.Ui.Badge), so an element named like a type of BorrowedTorch.UI (Button) is not ambiguous with it.
It needs a BorrowedTorch.UI that has these members: the version that references the generator 4.0.0 or later. An older BorrowedTorch.UI compiles with the generator 3.0.0 only.
Version 3.0.0
The dependency properties are created when first used, so an element no longer allocates every property of its class up front. This changes the generated contract:
{Name}DPis a property instead of a field (source compatible for reading and calling it).- The owner actions are set once per class on the shared
{Name}DPActionsobjects (for example in a static constructor) instead of on every instance, andInitializeno longer takes the pre and post action methods. - A style applies or clears only the properties it touches; clearing does not create a property.
The consuming library must provide DependencyPropertyActions<T> with a public DefaultValue and a
DependencyProperty<T>(owner, actions) constructor (BorrowedTorch.UI does).
Requirements
- .NET 10 SDK. The project targets plain
net10.0, so it builds and runs on Windows, Linux and macOS. - The generated style classes use the C#
fieldkeyword, so the consuming project must compile with C# 14 or later.
NuGet package
Reference the package from the project that contains the .dpg files:
<ItemGroup>
<PackageReference Include="BorrowedTorch.UIDPGenerator" Version="4.0.0" />
</ItemGroup>
Every build then runs the generator over the project folder first and compiles the generated
.g.cs files, including on the very first build, when they did not exist yet. The package is a
development dependency (PrivateAssets="all"), so it does not flow to projects that reference yours.
| MSBuild property | Default | Description |
|---|---|---|
BorrowedTorchDpgIndentSize |
4 |
Spaces per indentation level in the generated code. |
BorrowedTorchDpgEnabled |
true |
Set to false to stop generating code during the build. |
<PropertyGroup>
<BorrowedTorchDpgIndentSize>2</BorrowedTorchDpgIndentSize>
</PropertyGroup>
How it behaves in the build:
- The generator runs out of process with the
dotnethost of the build, so it works the same fromdotnet build, Visual Studio and Rider. The machine needs a .NET 10 or later runtime, which the .NET 10 SDK already provides. [BUIDPG]warnings and errors are reported as MSBuild warnings and errors, so they show up in the IDE's error list. A.dpgfile that fails fails the build.- Unchanged output files are not rewritten, so their timestamps stay put and incremental builds are not
invalidated. Editing a
.dpgfile is enough for the Visual Studio fast up-to-date check to start a build. - Design-time builds (IntelliSense) do not run the generator.
- In a multi-targeting project (
<TargetFrameworks>) the generator runs once in the outer build, before the per-framework builds, which then find the files up to date and do not write them in parallel. - Generated files are only picked up from inside the project folder. A style
<Dir>that points outside of it needs its own<Compile Include="…" />.
Building the package
dotnet pack -c Release -o nupkg
The version comes from <Version> in BorrowedTorch.UIDependencyPropertiesGenerator.csproj. To consume the
package without publishing it, add the output folder as a package source in a nuget.config next to the
consuming solution:
<configuration>
<packageSources>
<add key="local" value="path\to\nupkg" />
</packageSources>
</configuration>
NuGet caches packages by id and version, so bump the version (or clear the cache with
dotnet nuget locals global-packages --clear) after repacking a version that was already restored.
Command line
dotnet run --project <path>\BorrowedTorch.UIDependencyPropertiesGenerator.csproj -- <projectDir> [<indentSize>]
| Argument | Description |
|---|---|
projectDir |
Folder that is scanned recursively for *.dpg files. Must exist. |
indentSize |
Spaces per indentation level in the generated code. Optional, default 4, must be >= 0. |
Exit code 0 means every .dpg file was processed. Exit code 1 means the arguments were
invalid or at least one file failed (malformed XML, missing <Element> root, I/O error).
A failing file is reported on stderr with the [BUIDPG] tag and does not stop the other files.
The tool can also be published as a single executable and run as
BorrowedTorch.UIDependencyPropertiesGenerator.exe <projectDir> [<indentSize>]:
dotnet publish -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true
The .dpg format
<Element name="Button">
<Using>System</Using>
<Using>BorrowedTorch.UI.Core</Using>
<Namespace>BorrowedTorch.UI.Elements</Namespace>
<DP type="int">Width</DP>
<DP type="string" checkEquality="false">Text</DP>
<DP type="bool" excludeFromStyle="true">IsPressed</DP>
<Style name="ButtonStyle">
<Using>BorrowedTorch.UI.Styles</Using>
<Namespace>BorrowedTorch.UI.Styles</Namespace>
<Dir>..\..\Styles</Dir>
</Style>
</Element>
| Node | Description |
|---|---|
<Element name="…"> |
Root. name is the element class name; default is the .dpg file name without extension. |
<Element>/<Using> |
One using directive each. BorrowedTorch.UI.Modules is always imported; outside BorrowedTorch.UI add BorrowedTorch.UI.Elements (the element's base class). Blank and duplicate entries are ignored. |
<Element>/<Namespace> |
File-scoped namespace of the element class. Omitted: global namespace. |
<DP type="T">Name</DP> |
One dependency property. type is required. checkEquality (default true) is passed to SetValue; excludeFromStyle (default false) leaves the property out of the style. |
<Style name="…"> |
Present: a style class is generated too, and the element takes it as its style. name defaults to <ElementName>Style. Absent: the element takes a hand-written <ElementName>Style. |
<Style>/<Using> |
Extra using directives of the style class, after BorrowedTorch.UI.Modules. Element usings and the element's namespace are merged in after them, duplicates removed. Outside BorrowedTorch.UI add BorrowedTorch.UI.Styles (the style's base class). |
<Style>/<Namespace> |
File-scoped namespace of the style class. Omitted: global namespace. |
<Style>/<Dir> |
Output folder of the style class. A relative path is resolved against the folder of the .dpg file. Default: ..\..\Styles. |
In BorrowedTorchUI every element has its own folder under Elements, and the default <Dir> puts the
style next to the other styles, beside the hand-written halves of the partial classes:
Elements/Button/Button.dpg -> Elements/Button/Button.g.cs (next to Button.cs)
-> Styles/ButtonStyle/ButtonStyle.g.cs (next to ButtonStyle.cs)
Rules and validation:
- Element and attribute names are case-sensitive; boolean attribute values are not (
true,True,TRUE). - Only direct children of
<Element>and<Style>are read. Values are trimmed. - Children may appear in any order.
<DP>entries keep their order in the generated members,<Using>entries keep their order in theusingdirectives. typeis copied into the C# code as is, so nullable (Color?), generic and array types work. The file is XML, so the<of a generic type must be written as<, and by convention>as>:<DP type="Func<string, string>">TextFilter</DP>.- The generated files are compiled with the project's global usings (
global using,ImplicitUsings), so<Using>is only needed for namespaces that are not imported globally. The element class'sInitializeusesAction, soSystemmust be imported one way or the other. - Use
/as the separator in<Dir>when the path must also work on Linux or macOS; Windows accepts\and/. - A
<DP>withouttype, without a name, or with a name already declared is skipped with a warning. - An invalid boolean attribute value is reported and the default is used.
- Warnings are printed on stderr with the line number of the offending node; they do not fail the run.
Elements of your own project
A game that references BorrowedTorch.UI (with the generator 4.0.0 or later) gives an element of its own dependency properties and a style the same way the library's elements get theirs. Reference the generator next to BorrowedTorch.UI:
<ItemGroup>
<PackageReference Include="BorrowedTorch.UI" Version="…" />
<PackageReference Include="BorrowedTorch.UIDPGenerator" Version="4.0.0" />
</ItemGroup>
Describe the element in a .dpg file, for example Ui/Badge/Badge.dpg:
<Element>
<Namespace>Game.Ui</Namespace>
<Using>BorrowedTorch.UI.Elements</Using>
<Using>Microsoft.Xna.Framework</Using>
<DP type="Color">GlowColor</DP>
<DP type="int">Pulse</DP>
<Style>
<Namespace>Game.Ui.Styles</Namespace>
<Using>BorrowedTorch.UI.Styles</Using>
<Dir>../../Styles</Dir>
</Style>
</Element>
The build then writes Ui/Badge/Badge.g.cs (the dependency properties GlowColorDP and PulseDP, their shared
…DPActions, the wrapping properties GlowColor and Pulse) and Styles/BadgeStyle/BadgeStyle.g.cs (the style with
GlowColor and Pulse). The element derives from GenericStyleAndMouseCursorsData<BadgeStyle>, so it has a general
style (Badge.GeneralStyle) and a StyleOverride like the library's elements.
Write the other half of each partial class next to the .dpg file and the generated style:
namespace Game.Ui;
public partial class Badge
{
// what the element does when a value changes: set once per class, in its static constructor
static Badge()
{
PulseDPActions.OwnerPostAction = static (owner, _) => owner.InvalidateMeasure();
}
public Badge(string name = null) : base(name)
{
// applies the general style and the cursors: call it at the end of every constructor
Initialize();
}
}
namespace Game.Ui.Styles;
public partial class BadgeStyle
{
// the framework defaults of the style, under the general style
protected override void SetDefaults()
{
base.SetDefaults();
Pulse = 3;
}
}
- An element class sets each
…DPActionsaction once: a second set throws, so the actions of the library's elements can't be replaced from outside.OwnerPreActioncan correct or reject a value before it is stored. - A style's
SetDefaultsisprotected internalin BorrowedTorch.UI; in a project of your own it is overridden asprotected override, and it calls the base first (HitTestandCropOutsideOfParentBorderare on by default). - The element and its layout are written as for any element derived from
BaseElement(MeasureContent,ArrangeContentand the handler overrides); the generator only adds the properties and the style.
Generated code
For the example above the element class goes to <dpg folder>\Button.g.cs:
// <auto-generated>
// Generated by BorrowedTorchUI Dependency Properties Generator from Button.dpg.
// Changes to this file will be lost when it is regenerated.
// </auto-generated>
using BorrowedTorch.UI.Modules;
using System;
using BorrowedTorch.UI.Core;
namespace BorrowedTorch.UI.Elements;
public partial class Button : GenericStyleAndMouseCursorsData<global::BorrowedTorch.UI.Styles.ButtonStyle>
{
#region Dependency properties
// the owner actions and the default of each property, shared by all the instances of the class
public static readonly DependencyPropertyActions<int> WidthDPActions = new();
public static readonly DependencyPropertyActions<string> TextDPActions = new();
public static readonly DependencyPropertyActions<bool> IsPressedDPActions = new();
// created when first used: an element pays only for the properties it uses
private DependencyProperty<int> _widthDP;
private DependencyProperty<string> _textDP;
private DependencyProperty<bool> _isPressedDP;
public DependencyProperty<int> WidthDP => _widthDP ??= new DependencyProperty<int>(this, WidthDPActions);
public DependencyProperty<string> TextDP => _textDP ??= new DependencyProperty<string>(this, TextDPActions);
public DependencyProperty<bool> IsPressedDP => _isPressedDP ??= new DependencyProperty<bool>(this, IsPressedDPActions);
// the property once it was used, null before (a style clears only the properties that exist)
internal DependencyProperty<int> WidthDPIfCreated => _widthDP;
internal DependencyProperty<string> TextDPIfCreated => _textDP;
internal DependencyProperty<bool> IsPressedDPIfCreated => _isPressedDP;
#endregion
#region Wrapping properties
public virtual int Width { get => _widthDP is { } dp ? dp.Value : WidthDPActions.DefaultValue; set => WidthDP.SetValue(value, true); }
public virtual string Text { get => _textDP is { } dp ? dp.Value : TextDPActions.DefaultValue; set => TextDP.SetValue(value, false); }
public virtual bool IsPressed { get => _isPressedDP is { } dp ? dp.Value : IsPressedDPActions.DefaultValue; set => IsPressedDP.SetValue(value, true); }
#endregion
#region Dependency properties disposal
protected override void DisposeDependencyProperties()
{
base.DisposeDependencyProperties();
_widthDP?.Dispose();
_textDP?.Dispose();
_isPressedDP?.Dispose();
}
#endregion
#region Common initialization
private void Initialize(Action initSubscriptions = null, Action additionalInstructions = null)
{
initSubscriptions?.Invoke();
additionalInstructions?.Invoke();
ApplyGeneralStyle();
ApplyMouseCursors();
}
#endregion
}
A dependency property object is created the first time it is used (set, cleared by a style that set it, bound,
subscribed to, or read through its …DP property); reading the wrapping property does not create it. An element
therefore pays only for the properties it uses. What the properties of one name share over all the elements of a
class lives in its …DPActions object: the owner's pre and post actions, which the element class sets once, in its
static constructor, and the default value.
The style class goes to <Dir>\<StyleName>\<StyleName>.g.cs, here
<dpg folder>\..\..\Styles\ButtonStyle\ButtonStyle.g.cs:
// <auto-generated>
// Generated by BorrowedTorchUI Dependency Properties Generator from Button.dpg.
// Changes to this file will be lost when it is regenerated.
// </auto-generated>
using BorrowedTorch.UI.Modules;
using BorrowedTorch.UI.Styles;
using System;
using BorrowedTorch.UI.Core;
using BorrowedTorch.UI.Elements;
namespace BorrowedTorch.UI.Styles;
public partial class ButtonStyle : BaseStyle
{
// a bit per property, set once the property was assigned: only assigned properties are applied
private ulong _assigned0;
public int Width { get; set => SetProperty(ref field, value, ref _assigned0, (1UL << 0)); }
public string Text { get; set => SetProperty(ref field, value, ref _assigned0, (1UL << 1)); }
#region Assigned properties
public override bool IsSet(string propertyName)
{
return propertyName switch
{
nameof(Width) => (_assigned0 & (1UL << 0)) != 0,
nameof(Text) => (_assigned0 & (1UL << 1)) != 0,
_ => base.IsSet(propertyName)
};
}
protected override bool UnsetProperty(string propertyName)
{
switch (propertyName)
{
case nameof(Width):
if ((_assigned0 & (1UL << 0)) == 0) return false;
Width = default;
_assigned0 &= ~(1UL << 0);
return true;
case nameof(Text):
if ((_assigned0 & (1UL << 1)) == 0) return false;
Text = default;
_assigned0 &= ~(1UL << 1);
return true;
default:
return base.UnsetProperty(propertyName);
}
}
protected override void CopyAssignedTo(BaseStyle target)
{
base.CopyAssignedTo(target);
var style = (ButtonStyle)target;
if ((_assigned0 & (1UL << 0)) != 0) style.Width = CloneValue(Width);
if ((_assigned0 & (1UL << 1)) != 0) style.Text = CloneValue(Text);
}
#endregion
#region Apply
protected override void ApplyValues(BaseElement element, ValueSources valueSource, BaseStyle defaults)
{
base.ApplyValues(element, valueSource, defaults);
var e = (global::BorrowedTorch.UI.Elements.Button)element;
var d = defaults as ButtonStyle;
if ((_assigned0 & (1UL << 0)) != 0)
e.WidthDP.SetValue(Width, true, true, valueSource);
else if (d != null && (d._assigned0 & (1UL << 0)) != 0)
e.WidthDP.SetValue(d.Width, true, true, valueSource);
else
e.WidthDPIfCreated?.ClearValue(valueSource);
if ((_assigned0 & (1UL << 1)) != 0)
e.TextDP.SetValue(Text, true, true, valueSource);
else if (d != null && (d._assigned0 & (1UL << 1)) != 0)
e.TextDP.SetValue(d.Text, true, true, valueSource);
else
e.TextDPIfCreated?.ClearValue(valueSource);
}
protected override void ClearValues(BaseElement element, ValueSources valueSource)
{
base.ClearValues(element, valueSource);
var e = (global::BorrowedTorch.UI.Elements.Button)element;
e.WidthDPIfCreated?.ClearValue(valueSource);
e.TextDPIfCreated?.ClearValue(valueSource);
}
#endregion
}
A style property counts as assigned once it is set, also when it is set to its default value. IsSet tells
whether it is, UnsetProperty takes it back out. ApplyValues sets the assigned properties in the element's
layer of the given value source, takes an unassigned property from defaults (a style of the same type) when
that has it assigned, and clears the others; ClearValues clears them all. CopyAssignedTo copies the assigned
properties to another style of the same type. Base classes go first: the base style's properties are applied
and copied before those of the derived style, and DisposeDependencyProperties disposes the base element's
dependency properties before the element's own.
The generated code builds on these members, which BorrowedTorch.UI has (public or protected, so they are reachable from a project of your own):
DependencyProperty<T>with the(owner, actions)constructor,Value,SetValue(T, bool),SetValue(T, bool, bool, ValueSources),ClearValue(ValueSources)andDispose(),DependencyPropertyActions<T>withDefaultValue, and theValueSourcesenum, inBorrowedTorch.UI.Modules.BaseStyle, the hand-written half, withSetProperty<T>(ref T field, T value, ref ulong assigned, ulong bit), which stores the value and sets the bit, andCloneValue<T>(T), which copies a value for a cloned style.BaseElement, the class every element derives from, with the protectedApplyMouseCursors(), andGenericStyleAndMouseCursorsData<TStyle>with the protectedApplyGeneralStyle().
Two names are special:
- An element named
BaseElementderives fromDisposableBaseinstead ofGenericStyleAndMouseCursorsData<…Style>, itsInitializedoes not callApplyGeneralStyle(), and it declaresDisposeDependencyPropertiesasprotected virtual, which the other elements override. - A style named
BaseStyleimplementsICloneableinstead of deriving fromBaseStyle, and declares the style members above asvirtual(ApplyValuesandClearValuesasprotected virtual), which the other styles override.
In BorrowedTorchUI both come from Elements/ElementCore/BaseElement.dpg, which names its style explicitly
with <Style name="BaseStyle">; the default would be BaseElementStyle.
Every generated file starts with an <auto-generated> header, so analyzers treat it as generated
code. *.g.cs files are listed in .gitignore; regenerate them instead of committing them.
Project layout
| File | Responsibility |
|---|---|
Program.cs |
Command line parsing, exit code. |
Generator.cs |
Finds .dpg files, resolves output paths, writes files only when changed. |
DpgParser.cs |
Turns the XML into ElementDefinition, StyleDefinition, DependencyPropertyInfo. |
SourceEmitter.cs |
Renders the C# text of the element and style classes. |
StyleMembers.cs |
Renders the members of a style class: assigned bits, properties, apply, clear, copy. |
build/*.targets |
Imported by NuGet into consuming projects: runs the generator before the build. |
buildMultiTargeting/*.targets |
Imports build/*.targets into the outer build of multi-targeting consuming projects. |
Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests |
xUnit tests for the parser, the emitter, the file generation, the CLI and the package. |
Tests
dotnet test Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests
PackageTests pack the generator into a temporary folder feed and build throw-away consuming projects
against it with the dotnet CLI, which takes a few tens of seconds. To run only the fast tests:
dotnet test Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests --filter "Category!=Package"
There is intentionally no solution file: dotnet build and dotnet run in the repository root
keep working on the generator project alone, and the test project references it directly.
License
MIT, see LICENSE.
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.