Pitfalls in Extension Development
This page collects behaviors that the API does not make obvious and that extension authors have run into. Where Beutl itself should change, the item links to the issue that tracks it. This page targets Beutl 2.0.0-preview.15; rebuild extensions against its SDK after migrating the APIs below.
Migrating from preview.14
Check these changes when you move an extension from preview.14. The decoders now belong to the host, as most other services did in preview.14: an extension that opens media itself, renders a scene, or implements one of the interfaces below has to change. Other extensions only need a rebuild, because many methods that open media gained an optional DecoderRegistry? decoders parameter. Removed APIs have no compatibility shims.
- Test projects: The target framework stays
net11.0, Avalonia stays at 12.1.6, and the file format floor stays at preview.11, so a project saved by preview.15 still opens in preview.11. See the version table. DecoderRegistry: No longer static. The host owns one, whichcontext.ServicesinLoadand the editor'sGetServiceprovide.Register,Unregister,EnumerateDecoder,GuessDecoder,OpenMediaFile,ProxyResolverandDecodersChangedare members of that instance,DecoderRegistry.Initialize(config)is now the constructornew DecoderRegistry(config), and what the staticDecoderFileExtensionsdid is now on itsFileExtensions.DecodingExtensionregisters its decoder in the registry of the context it loads in. See the decoder registry.- Opening media:
MediaReader.Opentakes the registry as its last argument. AVideoSourceorSoundSourcethat has a file throwsInvalidOperationExceptionwhen it is reconciled with aCompositionContextwhoseDecodersisnull, so pass the host's registry wherever an API takesDecoderRegistry? decoders, such asSceneRenderer,ExportRendererFactory.Create, andTryGetOriginalDurationofSourceSoundandSourceVideo. A test registers its decoders in a registry of its own. - Custom
IOriginalDurationProvider,IThumbnailsProviderandIProxyGeneratorFactory:TryGetOriginalDuration,GetThumbnailStripAsyncandGetWaveformChunksAsynctakeDecoderRegistry? decoders = nullas their last parameter, andIProxyGeneratorFactory.Createtakes theDecoderRegistryto open the source with. A class that implements them must add the parameter, and a package built for preview.14 that implements one of them does not load in preview.15. ASoundthat overridesGetClipLayoutadds the same last parameter. Open media with the registry they receive. - Custom
ITimeMappedSource:GetSourceDuration()is nowGetSourceDuration(DecoderRegistry? decoders = null). It has a default implementation, so a class that kept the parameterless method still compiles, but Beutl no longer calls it, and edits stop keepingOffsetPositionwithin the timeline's length. Add the parameter. See time-based content and splitting. - Custom
IGenerativeRunHost: The newDecodersproperty has no default implementation, so a class that implements the interface must add it.GenerativeGraphRunnerevaluates the graph and loads the nodes' previews with that registry. - Windows that your extension opens: Copy
ControlDecoders.Decodersfrom the opener as well. See windows that your extension opens. - Project fonts: Opening a project no longer loads its bundled fonts into the host's
FontManager. Each scene editor resolves them through aFontManagerof its own, which forks the host's, so the project's text drawn or measured with theFontManagerfromLoadfalls back to another font. Use the editor's. See drawing text and pixels. - Keyframes and expressions together: The editor no longer removes an expression when the user adds keyframes, nor the keyframes when the user sets an expression, because an expression can now read them as
Value. WhileHasExpressionistrue, the expression decides the value, even whenGetKeyFrameAnimation()returns keyframes. See keyframes and expressions. - Property editors: A value editor can stay editable while its property has an expression, and then edits the value under it.
IValueEditorContext<TEdit>has new members with default implementations, so an existing context still compiles and works as before. See editing under an expression. - Browser downloads:
BrowserDownloadOffernow tells the method of the request thatSourceanswered. An extension that requestsSourceitself checksCanRequestAgainfirst. See browser downloads. - Beutl's folder on Windows: A new installation goes to
%LOCALAPPDATA%\Programs\Beutlfor the current user by default, without administrator rights, and an update keeps the folder of the installation it replaces. Find Beutl's own files fromAppContext.BaseDirectoryrather than assumeProgram Files.
Migrating from preview.13
Check these changes when you move an extension from preview.13. Most of the global singletons that extensions used are gone: an extension takes the host's services from the context that Load receives. Every extension overrides Load, so every extension has to change and be rebuilt. Removed APIs have no compatibility shims.
- Test projects: The target framework stays
net11.0, Avalonia stays at 12.1.6, and the file format floor stays at preview.11, so a project saved by preview.14 still opens in preview.11. See the version table. Extension.Load()andUnload(): They are nowLoad(IExtensionContext context)andUnload(IExtensionContext context), andcontext.Servicesgives the host's services. A subclass ofThemeExtension,DecodingExtension,ProxyExtensionorTutorialExtensionthat overrides them passes the context on to the base method. A package built for preview.13 that overridesLoad()orUnload()does not load in preview.14. See services from the host.LibraryService.Current,ObjectTemplateService.Instance: Removed. ResolveLibraryServiceorObjectTemplateServicefromcontext.Services, or from the editor'sIEditorContext. See registering with the library.TutorialService: Removed with itsCurrent.TutorialExtensionregisters its tutorials with theITutorialServiceof the context, so code that calls itsLoaditself, such as a test, passes a context that provides one.GlobalConfiguration.Instance: Removed. ResolveGlobalConfigurationand read the section you need from it, such asEditorConfig. Its constructor is now public, so a test can make its own.RenderCacheOptions.CreateFromGlobalConfiguration()is nowCreateFromConfiguration(EditorConfig).Scene.AddChild,MoveChild,MoveChildren,CloseGapAfterandCloseAllGaps: They no longer read Settings → Editor → Automatically adjusts scene duration fromGlobalConfiguration.Instance, and takebool autoAdjustDurationinstead,trueby default. Without the argument, they lengthen the scene to reach the elements even when the user turned the setting off. To follow the setting, passEditorConfig.AutoAdjustSceneDuration.Valueof the host'sGlobalConfiguration.NotificationService: No longer static, andNotificationService.Handleris removed. ResolveINotificationServiceand callShow,ShowInformation,ShowSuccess,ShowWarningorShowError, extension methods inBeutl.Servicesthat take the same parameters as before.FontManager.Instance: Removed withFontManager.InitializeandFontFamily.Typefaces.FormattedText,TextElementsandTextElementsBuildertake theFontManagerto use, andfonts.GetTypefaces(family)lists the typefaces of a family. See drawing text and pixels.- Custom
IGenerativeRunHost: The newFontsproperty has no default implementation, so a class that implements the interface must add it.GenerativeGraphRunnerevaluates the graph with thatFontManagerwhen it captures a node's inputs. - Windows that your extension opens: The controls of
Beutl.Controlstake the user's settings and the host's fonts from attached properties that Beutl sets on its windows. See windows that your extension opens. - Render callbacks: Each raster that a callback reads describes its footprint with one
RenderPlacement. ReadPlacementonEffectTarget,RenderExecutionInput,MaterializedInputDescription,OpaqueRenderOutputandRenderCallbackCanvas, andOutputPlacementonGeometrySession,OpaqueRenderSessionandShaderExecutionContext, in place of their removedBounds,EffectiveScale,Scale,Density,WorkingScale,DeviceBounds,DeviceSize,DeviceGridOffset,LogicalOrigin,LogicalBounds,RasterBoundsandRequiredRegionmembers.EffectTarget.Boundsstays, and still moves the content.MaterializedInputDescription.FromRenderTargettakes aRenderPlacement. See processing the render target. GradingColorPicker:IsDraggingandStopDrag()are removed. Follow the edits throughColorChangedandColorConfirmed.- Beutl's UI fonts:
Beutl.Controlsno longer embeds them, so theavares://Beutl.Controls/Assets/Fonts/...resources are gone. UseUiFonts.DefaultFontFamilyorUiFonts.GetFontFamily(culture)inBeutl.Controls.Styling. - Async methods: The SDK compiles
asyncmethods that returnTaskorValueTaskwith .NET 11 runtime async. Such a method no longer carriesAsyncStateMachineAttribute, and the continuation of a task created withTaskCreationOptions.RunContinuationsAsynchronouslyreaches the UI thread through the thread pool, so it can run after work posted to the UI thread right after the task completed. See runtime async. - Browser downloads:
ClaimandImportAsyncofBrowserDownloadExtensionhave default implementations, and the newTryDownloadPageAsynchandles the browser's Download file command. See browser downloads. - Updates of your extension: Beutl now installs new releases of store extensions automatically by default. See target version and automatic updates.
Migrating from preview.12
Check these changes when you move an extension from preview.12. No public API was removed in preview.13.
- Test projects: The target framework stays
net11.0, Avalonia stays at 12.1.6, and the file format floor stays at preview.11, so a project saved by preview.13 still opens in preview.11. See the version table. - Custom
ILayerAttributeService: The newSetName(Scene scene, int zIndex, string name)has no default implementation, so a class that implements the interface must add it. It names the layer atzIndex, creating itsTimelineLayerwhen there is none, so that the name moves with the layer. An empty name clears the name and removes aTimelineLayerleft with only default values. It returnstrueand commits one history entry when the name changed. Code that only calls the service needs no change. - BT.709 video:
BitmapColorSpaceMapping.GetTransferFunctionmaps the BT.709 and BT.2020 SDR tags to the newBitmapColorSpaceTransferFn.CoreMedia709, so such video decodes with darker shadows and exports with brighter shadow codes. See decoders. - Property editors: With several elements selected, the property panel edits them together through a copy of one of them, and repeats each change to the copy on every element. See several selected elements.
- Code in string properties: Mark a property that holds a shader or a script with
[DataType(CustomDataTypes.Code)]for a monospace field that keeps its lines and takes Tab.DataType.MultilineTextfields now wrap long lines. See declaring properties.
Migrating from preview.11
Check these changes when you move an extension from preview.11. No public API was removed in preview.12.
- Target framework: The packages and
Beutl.Extensibility.Sdktargetnet11.0, so build with the .NET 11 SDK (Visual Studio 2026 18.12 or later). The SDK setsnet11.0for a project that names no framework; change a project or a test project that namesnet10.0. An extension built fornet10.0against preview.11 still loads in preview.12. See project setup. - Test projects: The file format floor stays at preview.11, so a project saved by preview.12 still opens in preview.11. A test project that pins Avalonia packages, such as
Avalonia.Headless, to Beutl's version moves to 12.1.6. See the version table. - Audio effects: When a source's sample rate differs from the project's, its effects run at the source's rate, and Beutl converts to the project's rate after them. Take the rate from
AudioProcessContext.SampleRateor the buffer, not from the project. See sample rates. - Times you show: The editor shows times as timecodes by default, and the user can switch to time or frame numbers. To match it, write a time with
TimeDisplayFormatter.Formatin the user'sEditorConfig.TimeDisplayFormat. See media time. - Effects in the library: The library and the effect picker show each effect as a moving thumbnail. Register a recipe for each of your effects; without one, its thumbnail plays at its defaults over a sample picture. See library thumbnails.
ColorBalancePad.DragStarted: Raised once a press has traveled 3 pixels instead of on the press, and the pointer lock starts then too. A click raises neitherDragStartednorDragCompleted.- Custom
IPreviewPlayer: The newCleanPreviewImagereturnsPreviewImageby default, andAcquireCleanPreview()a handle that does nothing. Override them in a player that draws over its frames, such as a selection outline: the library draws effect thumbnails on that frame.
Migrating from preview.10
Check these changes when you move an extension from preview.10. Removed APIs have no compatibility shims.
- Test projects: A project saved by preview.11 does not open in preview.10 or earlier. See the version table.
FAColorPicker,ColorPickerButton,ColorPickerFlyout: Removed fromBeutl.Controlswith the rest of its copy of the FluentAvalonia color picker inFluentAvalonia.UI.Controls:ColorButtonColorChangedEventArgs,ColorChangedEventArgs,ColorComponent,ColorPickerComponent,ColorRamp,ColorSpectrum,ColorSpectrumComponents,ColorSpectrumShape,ColorTextType, and the themesColorPickerStyles.axamlandColorPickerButtonStyles.axaml. UseSimpleColorPicker, orSimpleColorPickerButtonfor a color that is not a property of an object. See shared controls.ColorPaletteItem: Moved fromFluentAvalonia.UI.ControlstoBeutl.Controls.PropertyEditors. It raisesClickinstead of setting the color of theFAColorPickeraround it.Beutl.Controls.Behaviors.ColorPaletteItemBehaviorand theColorPaletteItemTemplateresource are removed.SimpleColorPicker.SetColor: Also sets the picker'sColor. It used to raise the events only.ColorGradingWheel:InputType,InputTypeProperty,ShowDetailsandShowDetailsPropertyare removed. Its template parts are nowPART_Layout,PART_Header,PART_Pad,PART_MasterWheel,PART_ComponentsandPART_ResetButtoninstead ofPART_GradingColorPicker, so a custom theme has to provide them. Set the newNeutralto the property's default when that is not zero;MaxChroma,MasterRangeandIsSideBySideare new as well.- Theme and app resources:
BeutlDarkBorder.axamlandBeutlDarkColors.axamlno longer define the keys only the FluentAvalonia picker read:ColorPickerBackground,ColorPickerComponentLabelBackground,ColorPickerTabsBackground,ColorPickerTabItemForeground,ColorPickerTabItemForegroundPointerOver,ColorPickerTabItemForegroundSelected,ColorPickerTabItemSelectionIndicatorColor,ColorPickerTabItemSelectionIndicatorPointerOver,ColorPickerColorTypeButtonBackground,ColorPickerMoreButtonForeground,ColorPickerMoreButtonForegroundPressedandColorPickerColorPaletteItemBorderBrushPointerOver. The app resourcePaletteColorsand the color grading tab'sMinimalNumberEditorandPropertiesVisibilityToggleButtonStyleare gone too. UIToneMappingOperator:Noneis now5instead of0, and0is the newAuto, which is alsodefault(UIToneMappingOperator). Rebuild an extension compiled against the old values, and nameNonewhere code relied ondefaultmeaning None.EditorConfig.ToneMappingModedefaults toAuto, a saved0reads asAuto, andUIToneMappingOperatorExtensions.Resolve(mode, showsHdr)gives the operator a preview applies.DynamicsNode.MapChannels: Removed. A node deriving fromDynamicsNodereads each channel withAudioBuffer.GetChannelData(channel).MessageStrings,Strings,TutorialStrings:MessageStrings.ConfirmInstall,UpdateCompletedLaunchConfirm,UpdateCompletedLaunchPrompt,ApplicationNotLaunched,ApplicationPathNotSpecified,Strings.CreateNewProjectOrScene,OpenAFileYouHaveAlreadyCreated,StartEditing,All,Projects,Files,Recently,NoFilesUsedRecently,PreviousandTutorialStrings.StartTutorialare gone. Provide your own strings.- Starting playback: Call
IPreviewPlayer.Play()instead of runningeditor.playPause, and time live input withGetPlaybackTime(). See the playhead during playback. - Encoders that write several files: List them in
EncodingController.OutputFilesinstead of moving them out of Beutl's staging folder yourself. See writing several files. - References to a library Beutl ships: Replace a
PackageReferencethat setsExcludeAssetsandPrivateAssets, or pins Beutl's version, withBeutlHostPackageReference. See libraries that Beutl already ships. - Drawables added through
IElementAdderorIElementObjectService: A new drawable whose transform group is still empty gets aTranslateTransform, aRotationTransformand aScaleTransform. Do not add your ownTranslateTransformto it afterwards, or it has two. See element sources. - State saved outside properties: An explicit save writes only the elements whose properties changed since the last one. See keep saved state in properties.
- Context menus on macOS: A
ContextMenuor a context flyout opens as a native menu by default. See context menus on macOS. - Custom
ISceneSettingsService: The newApplyoverload that takesmasterVolumehas a default implementation, which writesScene.MasterVolumeand calls the overload without it. Override it so that a change of the master volume alone is committed too. - Custom
INodeGraphMutationService: The newCanConnect(GraphModel, GraphNode, INodePort?, GraphNode, INodePort?)has a default implementation that answersfalsefor anullport. Override it if your service adds ports to dynamic-port nodes.
Migrating from preview.9
Check these changes when you move an extension from preview.9. Removed and moved APIs have no compatibility shims.
DrawableandFilterEffectoverrides: Move them onto the nestedResource. See drawing objects and effects.CustomEffectcallbacks: A callback run by the renderer can no longer launch another renderer. UseRenderDependency; see effects.- Code that reads a
MediaReader:ReadAudioreturnsAudioStreamInfo.ChannelLayoutchannels instead of always stereo, so handle any channel count. See decoders. ISampleProviderimplementations and encoders: DeclareChannelLayoutwhen a provider returns anything other than stereo, and take the encoder's channel count from it. See provider contracts.AudioEffectandAudioNodeimplementations: They receive the project's channel count in a 5.1 or 7.1 project. See channel layouts.StrokeEffect.Style,StrokeEffect.StrokeStyles: Removed. Where code setStyletoForeground, set the pen'sStrokeOrdertoStrokeOrder.BelowFill.Backgroundis the defaultAboveFill.NotifySplittedonSourceVideo,SourceSound,SceneSound,SceneDrawable: These types no longer declare it publicly. Call it throughISplittableorElement.NotifySplitted.FontFamilyPickerFlyout,FontFamilyPickerFlyoutViewModel: Renamed toSearchablePickerFlyout, which takes anISearchablePickerViewModel; the view model is now internal. See shared controls.- Custom
IElementAttributeService: ImplementSetTrackMatte(Element, MatteSourceKind, int?, MatteMode)andSetVisibleInOutput(Element, bool). - Custom
INodeGraphMutationService: ImplementCanConnect(GraphModel, INodePort, INodePort)andRewireListSlot(GraphModel, Connection, GraphNode, INodePort?). - Custom
ISceneSettingsService: ImplementApply(Scene, PixelSize, MediaTime, MediaTime, SpeakerLayout). ExtensionsStrings,Strings,GraphicsStrings:ExtensionsStrings.NoLogoImageAvailable,Free,Description,Package_Screenshots,Strings.LinkandGraphicsStrings.StrokeEffect_Styleare gone. Provide your own strings.WeakEvents,WeakEvent,WeakEvent<TSender, TEventArgs>,IWeakEventSubscriber<TEventArgs>: Removed fromBeutl.Utilities. Subscribe to the event directly and unsubscribe when done.- Test projects: A project saved by preview.10 does not open in preview.9 or earlier. See the version table.
Packaging and loading
Keep the source generator private
Since preview.9, the SDK marks Beutl.Engine.SourceGenerators as PrivateAssets="all", so the preview.8 workaround that disabled the automatic reference is no longer needed. Remove that workaround when upgrading; the SDK keeps the generator version aligned with $(BeutlPackagesVersion).
Check the .nuspec inside your .nupkg: the source generator must not appear as an install-time dependency.
Libraries that Beutl already ships
Each extension is loaded into its own AssemblyLoadContext, but when Beutl ships an assembly of the same name in the same or a newer version, the extension gets Beutl's copy. If your extension asks for a newer version, its copy is loaded separately, and its types do not match Beutl's. Without ExcludeAssets="runtime;native", native libraries that come in transitively, such as libSkiaSharp and HarfBuzz, also land in the runtimes folder of your output.
Since preview.11, reference such a library (FluentIcons, for example) with BeutlHostPackageReference and no version:
<ItemGroup>
<BeutlHostPackageReference Include="FluentIcons.Avalonia.Fluent" />
</ItemGroup>
The SDK turns it into a PackageReference at the version Beutl ships, with ExcludeAssets="runtime;native" and PrivateAssets="all". Your extension compiles against the library and runs on Beutl's copy, and nothing of the library goes into your output or package. The names it accepts are the packages in Beutl's Directory.Packages.props, without the build, test and packaging tools, and without the libraries that only the FFmpeg worker, or the Media Foundation extension on Windows x64, loads. A name Beutl does not ship stops the restore with an error: reference a library of your own with a normal PackageReference.
After a build, <AssemblyName>.deps.json in the output should list your own assembly and only the libraries that Beutl does not ship. The SDK also references Beutl.Controls; see project setup.
Libraries that load through the default context
Since preview.11, when a library asks AssemblyLoadContext.Default for an assembly that only your package holds, Beutl finds it in your package. The default context loads a copy of its own, which stays loaded until Beutl exits, and your extension's context uses that copy when it is new enough, so its types keep one identity. A library already loaded in your extension's context still cannot load, through the default context, an assembly that refers back to it (#3921).
Services from the host
Since preview.14, Beutl passes an IExtensionContext to Load and Unload. Its Services is the host's IServiceProvider, which provides LibraryService, ObjectTemplateService, GlobalConfiguration, FontManager, INotificationService and ITutorialService, and since preview.15 DecoderRegistry. It finds a service by its exact type, so ask for GlobalConfiguration and read a section such as EditorConfig from it. GetRequiredService<T>() is in Microsoft.Extensions.DependencyInjection, which the SDK's references bring.
using Beutl.Extensibility;
using Beutl.Graphics.Shapes;
using Beutl.Services;
using Microsoft.Extensions.DependencyInjection;
namespace MyExtension;
[Export]
public sealed class ShapesExtension : Extension
{
private INotificationService? _notifications;
public override void Load(IExtensionContext context)
{
context.Services.GetRequiredService<LibraryService>()
.RegisterGroup("My Shapes", group => group
.AddDrawable<RectShape>("My Rectangle"));
// Keep what later code needs, and let it go in Unload.
_notifications = context.Services.GetRequiredService<INotificationService>();
}
public override void Unload(IExtensionContext context)
{
_notifications = null;
}
public void ReportFailure(Exception exception)
=> _notifications?.ShowError("My Shapes", exception.Message);
}
- Beutl loads extensions one at a time: the built-in ones first, then installed packages by name, then side-loaded ones. It calls
Unloadafter a failedLoadas well, so writeUnloadto undo only whatLoadfinished, and to run more than once. - In a command, a tool tab or another factory, take services from the editor it serves, such as
execution.EditorContextor theIEditorContextthat a tool tab is created for: the scene editor provides the services above, and its own, throughGetService. One instance of an extension can serve more than one host, so prefer these over the services kept fromLoad. Since preview.15, the editor'sFontManageris a fork that resolves the fonts bundled with the scene's project ahead of the host's.
Loading is all or nothing
- Beutl looks for extensions among the public types of your assembly. An extension class must be
public, derive fromExtension, have the[Export]attribute and a parameterless constructor. - Beutl reads the public types strictly. If one of them refers to an assembly that cannot be loaded, such as a library you excluded that Beutl does not ship, the whole package fails to load.
- If
Loadof one extension throws, every extension in the same package is rolled back.
Sideloads
DebugApplication builds go to ~/.beutl/sideloads/<AssemblyName>. Beutl only picks up a folder that contains a DLL with the folder's own name (<name>/<name>.dll), so keep that naming if you copy files there yourself.
Version numbers and icons
- A stable version such as
0.1.0that depends on Beutl's preview packages makesdotnet packreport NU5104. Use a prerelease version, such as0.1.0-preview.1, while you target a preview of Beutl. PackageIconsets the icon inside the.nupkg. The icon on the store page is uploaded separately from the developer page (see Publishing Extensions). Use a square image without rounded corners: the store and Beutl round them when they display it.
Saving and editing
Collection converters belong on the value type
Since preview.9, a collection type's own [JsonConverter] is honored on both save and load. Without a converter, Beutl still writes collections item by item. ICoreSerializable and reference values follow Beutl's own serialization paths.
A [JsonConverter] placed on a property member is not read by the property system. Put it on the value type, or implement the appropriate Beutl serialization contract; do not rely on the member attribute.
Time-based content and splitting
When the user splits an element, Beutl copies it and calls ISplittable.NotifySplitted on the objects of both halves. An object that plays something on its own timeline, such as comments, lyrics or lip sync, should continue in the back half from where the front half stopped. Without that, the back half starts over from the beginning.
Implement ITimeMappedSource, the contract SourceVideo, SourceSound, SceneSound and SceneDrawable share. Only OffsetPosition and Speed are required: the default NotifySplitted moves the back half's OffsetPosition further into the timeline, and Split, Trim and Slip rewrite it through this contract. A Sound subclass already has both properties, so it only needs to add the interface.
using Beutl;
using Beutl.Engine;
using Beutl.Graphics;
public abstract partial class TimedDrawable : Drawable, ITimeMappedSource
{
protected TimedDrawable()
{
ScanProperties<TimedDrawable>();
}
public IExpressionProperty<MediaTime> OffsetPosition { get; } =
Property.CreateExpression(MediaTime.Zero);
// Null plays the timeline at 100%.
IExpressionProperty<float>? ITimeMappedSource.Speed => null;
}
At the element's local time t, the source plays its timeline at OffsetPosition plus the integral of Speed over [0, t], so draw from that position. GetSourceDuration(decoders) reports the timeline's length, which edits stay within; open a media file with the DecoderRegistry it receives. HasDynamicMapping defaults to OffsetPosition.HasExpression; override HasDynamicTimeline when an expression picks the timeline. Implement ISplittable directly only for an object without such a timeline.
Saved but not shown
HideProperties(...), a protected method of EngineObject, hides properties from the property panel. They are still saved, undone and copied, so use it for values that your own editor sets.
Keep saved state in properties
Since preview.11, an explicit save writes only the elements whose properties changed since the last save, keyframes and lists included. The first save after a scene opens, and a save that moves files or repairs media, still write every element. Keep what your object saves in its properties: a value that only a field holds, written by your own Serialize, reaches the file only when something else in its element changes. Hide such a property from the panel with HideProperties(...) when your own editor sets it.
One undo step for several changes
A property editor can obtain HistoryManager from the IServiceProvider visitor passed to IPropertyEditorContext.Accept. For an explicit edit, call BeginEdit, change properties inside edit.Enter(), then call Complete(). Disposing an unfinished session cancels its changes.
Only one edit session may be open. Call RunAfterEditAsync on the UI thread to queue an independent writer behind the active session. Do not hold an Enter() scope across await.
using Beutl;
using Beutl.Editor;
using Beutl.ProjectSystem;
public static class TimingEdits
{
public static Task SetTimingAsync(
HistoryManager history, Element element, MediaTime start, MediaTime length)
=> history.RunAfterEditAsync(() =>
{
using EditSession edit = history.BeginEdit("Change timing");
using (edit.Enter())
{
element.Start.Value = start;
element.Length.Value = length;
}
edit.Complete();
});
}
Editor integration
Register timeline-compatible library items
Since preview.9, AddDrawable<T>() and AddSound<T>() register the EngineObject format as well as their drawable or sound format. The preview.8 AddMultiple workaround is no longer necessary. BindDrawable<T>() and BindSound<T>() still register both formats when building a multiple-format item.
using Beutl.Graphics.Shapes;
using Beutl.Services;
public static class ShapeLibrary
{
// Call this from Load with the LibraryService of the context.
public static void Register(LibraryService library)
=> library.RegisterGroup("My Extension", group => group
.AddDrawable<RectShape>("My Rectangle"));
}
A test can register into a new LibraryService() and check that its GetTypesFromFormat(KnownLibraryItemFormats.EngineObject) contains your type.
The playhead during playback
During playback, IEditorClock.CurrentTime advances only when a rendered frame is shown. It moves in whole frames, and it falls behind the audio, or stops, when rendering is slow. To time live input during playback, read IPreviewPlayer.GetPlaybackTime() instead. It follows the audio the user hears, or the wall clock while nothing plays audio, and returns null while playback is stopped. While playback is starting, and during fast or reverse playback, which plays no audio, it returns the playhead.
IPreviewPlayer.Play() starts playback from the playhead at normal speed, and does nothing while playback is already running. Await IPreviewPlayer.Pause() before changing scene state that playback might still access. The scene editor provides the player as a service of its IEditorContext. Play() and GetPlaybackTime() have default implementations, so another IPreviewPlayer implementation still compiles; until it overrides them, Play() does nothing and GetPlaybackTime() returns null.
using Beutl;
using Beutl.Editor.Services;
using Beutl.Extensibility;
public sealed class TapRecorder(IPreviewPlayer player)
{
private readonly List<MediaTime> _taps = [];
public IReadOnlyList<MediaTime> Taps => _taps;
public static TapRecorder? Create(IEditorContext editor)
=> editor.GetService(typeof(IPreviewPlayer)) is IPreviewPlayer player
? new TapRecorder(player)
: null;
public void Start()
{
_taps.Clear();
player.Play();
}
// Call this from the key or pointer handler of each tap.
public void Tap()
{
if (player.GetPlaybackTime() is { } time)
_taps.Add(time);
}
public Task StopAsync() => player.Pause();
}
IEditorClock.CurrentTime is read-only and contains a MediaTime; seek with IEditorClock.Seek(time). Likewise, change the selected object with IEditorSelection.Select(obj), and use SelectedElements for the shared timeline selection. See editor integration for registering commands.
Tool tabs
ToolTabExtension.Headerlabels the tool picker; returningnullhides the tool there. Open tabs use the per-instanceIToolContext.Headerreactive property.OpenToolTabbrings an already-open context to the front. UseFindToolTab<T>()to reuse one.- Implement
IPinnableToolContextfor a tab that can remain on its target instead of following selection. KeepIsPinnedandHasTargetin sync with the target's lifetime. - Override
ReuseContentAcrossActivationonly when the same control should survive tab activation changes. It can still leave and re-enter the visual tree; a reusedIDisposablecontrol is disposed before its context when the tab closes. GetIcon()returns a FluentAvalonia 3FAIconSource. Return a new icon source for each call.
UI
Use the shared controls
Beutl.Controls is now a public package automatically referenced by the SDK. Use Beutl.Controls.ToolTabBar instead of rebuilding it from private theme resource keys. For built-in property editor integration, use the typed registrations in Beutl.Extensibility.
For a searchable, pinnable list like the font and codec pickers, derive from SearchablePickerViewModel<TSearchKey>, implement Search, and open it with SearchablePickerFlyout. Set PresenterThemeKey and NoResultsText for the look and wording.
Beutl.Controls.EmptyState tells that a view has nothing to show yet. Set Icon, Title and Description, and put an action, such as a button, in its content; a part that is not set takes no space. Beutl.Controls.StatusLabel shows the state of an item in a list or a row: Text is what it says, and Kind (Neutral, Accent, Success, Caution or Critical) picks its colors. Both pass AutomationProperties.LiveSetting on to the text they announce.
<StackPanel xmlns="https://github.com/avaloniaui"
xmlns:controls="using:Beutl.Controls"
xmlns:icons="using:FluentIcons.Avalonia.Fluent"
Spacing="8">
<controls:EmptyState Title="No markers"
Description="Markers you add to the timeline appear here.">
<controls:EmptyState.Icon>
<icons:SymbolIcon Symbol="Bookmark" />
</controls:EmptyState.Icon>
<Button Content="Add a marker" />
</controls:EmptyState>
<controls:StatusLabel Kind="Success" Text="Ready" />
</StackPanel>
For a color that is not a property of an object, such as one of your settings, use Beutl.Controls.PropertyEditors.SimpleColorPickerButton. It opens SimpleColorPicker with the palettes, applies the color when the user confirms it, and then raises ColorConfirmed. Set IsAlphaEnabled to false to keep the color opaque and hide the opacity.
Beutl.Controls.AnimatedThumbnail, new in preview.12, shows an IAnimatedThumbnailSource: its still at rest, and its frames, laid out in one sheet, in a loop while IsPlaying is true. It asks the source for the still only while it is on screen and for the frames only while it plays, so a long list loads only what is seen.
When adjusting a property's controls, check their spacing and label alignment under Beutl's theme. Headless rendering is useful for layout checks, but also check the result in Beutl before release.
Windows that your extension opens
Since preview.14, the controls of Beutl.Controls take the user's settings and the host's fonts from inherited attached properties, ControlConfiguration.Configuration and ControlFonts.Fonts, and ControlNotifications.Notifications carries the host's INotificationService to views the same way. Since preview.15, ControlDecoders.Decoders carries the host's DecoderRegistry, which the file pickers of video and sound properties read for the file types they offer. Beutl sets them on its windows, including floating tool tabs and the windows of a ToolWindowExtension, and a control in a tool tab, a flyout or a popup inherits them. A window that your extension creates and shows itself has none: native context menus on macOS and the pointer lock of property drags follow their defaults instead of the user's settings, a font picker makes a font manager of its own without the project's fonts, and ControlNotifications.GetNotifications and ControlDecoders.GetDecoders return null. Copy them from the control that opens the window:
using Avalonia.Controls;
using Beutl.Controls;
public static class ExtensionWindows
{
public static void CopyHostServices(Window window, Control opener)
{
ControlConfiguration.SetConfiguration(window, ControlConfiguration.GetConfiguration(opener));
ControlFonts.SetFonts(window, ControlFonts.GetFonts(opener));
ControlNotifications.SetNotifications(window, ControlNotifications.GetNotifications(opener));
ControlDecoders.SetDecoders(window, ControlDecoders.GetDecoders(opener));
}
}
The color pickers in such a window still show only the default palette and record no recent colors.
Context menus on macOS
Since preview.11, on macOS a ContextMenu, or a ContextFlyout that is a MenuFlyout, FAMenuFlyout or FACommandBarFlyout, opens as a native menu while Settings → View → Use native context menus is on, as it is by default. The Avalonia menu still opens, unseen, so its bindings, its Opening handlers and IsOpen keep working. A MenuItem shows its text, check mark and input gesture, but not its Icon; a FluentAvalonia item also shows its IconSource. A menu that holds anything else, such as a MenuItem whose header is not text, stays an Avalonia menu, and so does a flyout opened through Button.Flyout or ShowAt. Check your menus on macOS with the setting on and off.
Drawing text and pixels
- Since preview.14,
FormattedText,TextElementsandTextElementsBuildertake theFontManagerthat resolves their fonts. A resource takes it fromCompositionContext.Fontswhen it reconciles, asTextBlockdoes: while Beutl renders a scene, it is the font manager of the scene's editor. Outside rendering, take theFontManagerof the editor whose scene the text belongs to, or the host's for text outside a project. - Since preview.15, the editor's font manager is a fork.
FontManager.Fork()makes a manager that resolves the fonts thatLoadProjectFontsloads into it ahead of its parent's, and asks its parent for the rest. Those fonts never reach the parent, whileAddFontadds to the installed fonts that every fork shares. Beutl forks the host's fonts for the open project, and that fork again for each of its scene editors. A fork that you hand to controls withControlFonts.SetFontsis let go withControlFonts.Releaseonce they no longer show it. context.DrawText(text, fill, pen)draws an outline only whenFormattedText.Penis set. The pen argument alone draws no outline.FormattedText.Boundsincludes text advance and spacing;ActualBoundsincludes stroke ink andRasterBoundscovers rasterized glyph masks. None is a line height. Size lines withMetrics.Ascent, which is negative, andMetrics.Descent, and put the baseline attop - Ascent.- Choose a registered font that covers your text instead of assuming a platform-specific default. The font manager provides fallback families; measure with the actual typeface used for rendering.
TextElements.Linescaches the formatted result on first enumeration. If you change its input afterward, create a newTextElementsand dispose the old one.- The constructor of
Bgra8888takes(r, g, b, a), although the fields are stored in B, G, R, A order. - Check the alpha component when testing transparent pixels; RGB values alone do not establish transparency.
Source
Beutl.Extensibility.Sdk.csprojSdk.targetsandhost-libraries.mdPluginLoadContext.csExtension.csandIExtensionContext.csINotificationService.csandGlobalConfiguration.csJsonSerializationContext.Serialize.csJsonSerializationContext.Deserialize.csISplittable.csITimeMappedSource.csHistoryManager.EditSessions.csEditSession.csEditedElements.csLibraryServiceExtensions.csIPreviewPlayer.csSceneEditorExtension.Commands.csSceneEditorTabExtension.csIPinnableToolContext.csSearchablePickerFlyout.csSearchablePickerViewModel.csEmptyState.cs,StatusLabel.csandSimpleColorPickerButton.csAnimatedThumbnail.csandIAnimatedThumbnailSource.csColorBalancePad.csNativeContextMenus.csandContextMenuEntry.csControlConfiguration.cs,ControlFonts.cs,ControlNotifications.cs,ControlDecoders.csandUiFonts.csDecoderRegistry.cs,IOriginalLengthProvider.cs,IThumbnailsProvider.csandProxyGeneratorRegistry.csGenerativeGraphRunner.csScene.csandScene.Gaps.csRenderPlacement.csFontManager.csandCompositionContext.csFormattedText.csTextElements.csILayerAttributeService.cs