BorrowedTorch.UIDPGenerator
2.0.0
Prefix Reserved
See the version list below for details.
dotnet add package BorrowedTorch.UIDPGenerator --version 2.0.0
NuGet\Install-Package BorrowedTorch.UIDPGenerator -Version 2.0.0
<PackageReference Include="BorrowedTorch.UIDPGenerator" Version="2.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="BorrowedTorch.UIDPGenerator" Version="2.0.0" />
<PackageReference Include="BorrowedTorch.UIDPGenerator"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add BorrowedTorch.UIDPGenerator --version 2.0.0
#r "nuget: BorrowedTorch.UIDPGenerator, 2.0.0"
#:package BorrowedTorch.UIDPGenerator@2.0.0
#addin nuget:?package=BorrowedTorch.UIDPGenerator&version=2.0.0
#tool nuget:?package=BorrowedTorch.UIDPGenerator&version=2.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 dependency property fields, 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.
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="2.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. 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. name defaults to <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. |
<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.
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<ButtonStyle>
{
#region Dependency properties
public DependencyProperty<int> WidthDP;
public DependencyProperty<string> TextDP;
public DependencyProperty<bool> IsPressedDP;
#endregion
#region Wrapping properties
public virtual int Width { get => WidthDP.Value; set => WidthDP.SetValue(value, true); }
public virtual string Text { get => TextDP.Value; set => TextDP.SetValue(value, false); }
public virtual bool IsPressed { get => IsPressedDP.Value; set => IsPressedDP.SetValue(value, true); }
#endregion
#region Dependency properties initialization
private void InitializeDependencyProperties()
{
WidthDP = new DependencyProperty<int>(this);
TextDP = new DependencyProperty<string>(this);
IsPressedDP = new DependencyProperty<bool>(this);
}
#endregion
#region Dependency properties disposal
internal override void DisposeDependencyProperties()
{
base.DisposeDependencyProperties();
WidthDP?.Dispose();
TextDP?.Dispose();
IsPressedDP?.Dispose();
}
#endregion
#region Common initialization
private void Initialize(Action preActions = null, Action postActions = null, Action initSubscriptions = null, Action additionalInstructions = null)
{
InitializeDependencyProperties();
preActions?.Invoke();
postActions?.Invoke();
initSubscriptions?.Invoke();
additionalInstructions?.Invoke();
ApplyGeneralStyle();
this.ApplyMouseCursorsOnState();
}
#endregion
}
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
internal override void ApplyValues(BaseElement element, ValueSources valueSource, BaseStyle defaults)
{
base.ApplyValues(element, valueSource, defaults);
var e = (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.WidthDP.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.TextDP.ClearValue(valueSource);
}
internal override void ClearValues(BaseElement element, ValueSources valueSource)
{
base.ClearValues(element, valueSource);
var e = (Button)element;
e.WidthDP.ClearValue(valueSource);
e.TextDP.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 of the consuming project, which BorrowedTorchUI has:
DependencyProperty<T>withValue,SetValue(T, bool),SetValue(T, bool, bool, ValueSources),ClearValue(ValueSources)andDispose(), 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.
Two names are special:
- An element named
BaseElementderives fromDisposableBaseinstead ofGenericStyleAndMouseCursorsData<…Style>, itsInitializedoes not callApplyGeneralStyle(), and it declaresDisposeDependencyPropertiesasvirtual, which the other elements override. - A style named
BaseStyleimplementsICloneableinstead of deriving fromBaseStyle, and declares the style members above asvirtual, 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.