Salt Desktop API — 0.1.6
Salt's Inventory Update hosts mod UIs as independent desktop windows. API version 6 supports menu-backed windows and client-only views. Salt remains an optional installation: your normal mod and UI run without it, while Salt discovers your integration providers when installed.
There are no adapters for the earlier public API. Build your integration for the exact Minecraft version, loader and mappings you support. The supported matrix is Fabric on 1.20.1, 1.21.1, 1.21.11, 26.1.2, 26.2 and 26.3; Forge on 1.20.1; NeoForge on the other five versions.
Core and the optional compatibility extension are independent JARs. The extension uses this same API as any other consumer. The separation guide documents recipe providers, native menu/session hooks, item-backed inventories, lifecycle callbacks and integration help pages. On legacy targets, the public graphics and input wrappers now live in api.client.gui and api.client.input; consumers must use these supported packages instead of the former implementation packages. Native Minecraft input/rendering types on newer targets remain unchanged.
On every supported version and loader, Core 0.1.6's additive native window template API can inherit automatic native artwork and controls, compose multiple regions/cutouts, and add ordinary API content. Its opt-in contracts, profiles and inspector preserve ordinary definitions' priority.
Mouse Tweaks input interoperability
Core supplies optional Mouse Tweaks input support on every supported version and loader. Install the matching upstream Mouse Tweaks JAR with Core; the Compatibility extension is not needed. Core uses Mouse Tweaks' published IMTModGuiContainer3Ex interface and its own gesture algorithms/configuration. Existing API 6 consumers need no Mouse Tweaks imports or additional registration.
For a menu-backed window, expose real slots with DesktopWindowDefinition.slotAt and DesktopSlotContext.menuSlotHit, using the same coordinates as rendering. Core resolves the topmost window and committed slot geometry, including custom layouts, and sends actions through its normal server-authorized inventory path. The player inventory remains an available wheel-transfer partner when its window is closed. Native result slots support output transfers; protected backing items remain protected.
Declare filter, phantom and other non-owning entries through DesktopMenuBindings.SlotAccess.isVirtualSlot. Core excludes them from Mouse Tweaks item transfers. Use the existing slot bindings for player-inventory ownership and physical source identity, so aliases are not offered twice. Client-only views and custom controls retain their ordinary input behavior; they do not become item inventories. Menu client click handlers should follow Minecraft's normal local-prediction contract.
No supported public API signature or protocol version changes are required by this bridge. Minecraft 1.20.1 negotiates a new optional click-sequence capability; install the updated Core on both sides to enable its desktop gestures. Core remains usable with Mouse Tweaks absent. Focused runtime and artifact checks are recorded in Mouse Tweaks validation.
Migrating to 0.1.5 / API 6
Minimize and ghost pins have been removed from implementation and API. Recompile integrations against API 6 and set apiVersion=6 in provider descriptors. API 5 descriptors are rejected during discovery instead of running against removed members.
DesktopWindowOptions now has five components (movable, pinnable, closable, lockable, managementMenu) and a three-argument convenience constructor. DesktopWindowState no longer has minimized or ghosted components. Window contexts no longer expose those states, definitions no longer have ghost/unghost callbacks, and server session contexts and handlers no longer expose ghost pin state or pin-change callbacks. The related actions, Restore action and Minimize control are gone. Normal pinning and Persistent Windows remain supported. Use a lifetime handle's focus() or workspace restoreWindow() to restore a hidden window.
Legacy config keys are discarded when settings load and save. Previously ghost-pinned saved positions load as ordinary pins. Hiding a retained native chest menu suspends its physical viewer; restoring it reopens that same menu, and final disposal cannot stop the same viewer twice.
Public API and 0.1.4 changes
All packages below begin with com.salts_inventory_update. The shared contracts have no native Minecraft dependency; the other contracts are compiled for each Minecraft target. Source links use 26.3 as the current reference. For an older target, read the same package under that version's fabric/src/main/java directory; Forge/NeoForge builds share those API sources.
| Package | Public entry points and purpose |
|---|---|
api.integration | DesktopIntegration, DesktopIntegrationContext, DesktopDiagnostics: optional discovery, phase selection and structured diagnostics. |
api.desktop | DesktopMenuBindings: common slot/source/gesture registration. DesktopPayloadCodecs: typed payload encoding/decoding on 1.21.1 and newer. |
api.server.desktop | DesktopServerApi, session/payload contexts and handlers, and recipe-transfer requests/decisions/validators. Safe to reference from the common provider. |
api.client.desktop | DesktopClientApi, DesktopMenuFactories, window definitions/contexts, native rendering, presentation regions, resizing and matcher contracts. Load through the client provider. |
api.client.desktop.widget | Text editing, buttons, grids, virtual items and scrollbar helpers. Shared DesktopScrollState supplies scrolling/virtualization calculations. |
| Shared window contracts | DesktopWindowHandle and DesktopWindowOptions: instance lifetime and permitted window controls. Keep their use inside the optional integration even though these two contracts have no native GUI dependency. |
The 0.1.4 public surface changes are:
- The combined
SaltsInventoryDesktopApiwas removed. Register common/server behavior withDesktopServerApiand client behavior withDesktopClientApi. DesktopWindowDefinition<T, S>now accepts any model type. Contexts exposemodel()in place ofmenu(), withinventoryAvailable()separating menu-backed windows from client-only views.- Former internal helpers are public contracts:
DesktopMenuBindings,DesktopMenuFactories,DesktopWindowPresentation,DesktopWindowRegionandDesktopNativeRenderContext. The old internal types were removed. - Use
sendPayloadin place ofsendCustomPayload. Matchers must declare their supported menu types for capture negotiation. Duplicate registration now fails; window replacement is explicit. - New optional discovery, client views/handles, keyboard ownership, modal routing, pointer capture/cancellation, overlay/external-region rendering, clips/transforms, free resizing and storage ownership hooks are described below. There are no old API aliases.
External workspace presentation
The API exposes DesktopWorkspace, DesktopWorkspaceHost and DesktopWorkspaceWindow across all twelve supported targets. An installed host receives normal workspace openings through DesktopClientApi.setWorkspaceHost. The host owns its screen and presentation; Core retains all window models, menus, authenticated sessions, shared cursor state and lifecycle callbacks. currentWorkspace and client tick callbacks provide access without importing Core implementation classes. isNativeScreenActive identifies an already visible native workspace, and openPlayerWorkspace opens the ordinary inventory lifetime through the installed host.
As of Core 0.1.5, registering an alternative workspace host also suppresses the automatic regular-window tutorial, even while that presentation is not currently active. Core does not mark the tutorial as seen when it skips the popup. Explicit help commands and configuration actions still open the guide normally. Passing null to setWorkspaceHost restores the default automatic onboarding policy; Core does not inspect any add-on's mod ID or implementation classes.
Use windows() to retain lifetime handles, ensureWindow for the built-in player inventory or Character, protectWindow to prevent removal while externally presented, and initialize to update the native rendering viewport. A presentation transforms renderWindow and translates mouse coordinates back before pointer, hoveredSlot or clickAt. containsPointer includes native popups and interactive external regions, so controls extending past a window's base rectangle remain reachable. An active modal owner also receives outside presses. Use dismissOutsidePointer with each displayed window's native coordinates for a press on empty workspace; this dismisses native popups without dispatching body input or world interaction. visibleSlots supplies native slot geometry for cursor snapping; transform those points using the same presentation coordinates. restoreWindow resumes a persistently hidden surface without replacing its model, state, handle or session, requesting focus, or saving layout preferences. Owner-hidden companions retain their normal visibility rules. renderCarried draws the shared cursor once. transferPair restricts quick-move to the other member of the displayed pair; destinations without storage reject the action. External presentations own window placement and management chrome; native content controls remain available. cancelInput ends local gestures and keyboard ownership before changing presentation. forceInventoryHud is an effective, presentation-scoped override and does not save the user's normal configuration. closeAllHoldMillis returns the existing Core hold duration, and closeClosableWindows disposes closable windows while preserving explicitly protected lifetimes. isValid detects owner/world/session replacement.
All calls run on the client thread. Returning to gameplay or replacing the presentation must preserve native ownership; the host must not call vanilla container-screen teardown when it merely hides its workspace. These new hooks require the rebuilt Core artifact from the same branch; they are not available in previously published 0.1.4 JARs.
Start with the examples
The example sources demonstrate:
SimpleMachineWindow: one original machine frame, zero host insets, custom real-slot artwork, computed gesture previews, synchronized progress, session-scoped buttons and a management menu.MachineTransferHandlerimplements server-authorized smelting recipe transfer.TerminalWindow: a stepped surface with transparent top corners, protruding tabs, a 10,000-row virtual catalog, search, independent scroll state, nested clips, custom slot previews, resizing, tooltips, selection dragging, an attached inspector and a declared modal popup. Virtual entries use a custom server action, rather than invented slots.ClientOnlyWindow: nativeEditBox/Buttonwidgets, instance-owned routing, Tab/Shift-Tab traversal, semantic labels, narration, inactive hover and capture cancellation.StyledPreferencesWindowreuses those widgets with custom manager-routed decoration.
The example backends contain no Salt references. Register their menu types through your usual loader setup and call ExampleMenus.bind(...) there. Keep your original screens registered. The provider classes supply the optional desktop presentation. The sample catalog selection demonstrates authenticated server actions; connect actual withdrawals to your own storage and permission checks.
Run ./gradlew verifyApiExamples to compile these integrations against all twelve actual loader/version classpaths. Generated sources under each loader's build/generated/api-examples account for native Minecraft name, graphics and input differences. They are excluded from the shipped mod jars. See the examples README for setup.
Compile against Salt without requiring it
Use Salt as a compile-only mod dependency. Do not bundle its jar, copy its API classes into your mod, or list it as a required runtime dependency. The full matching Salt jar provides the public API; there is no separate runtime API mod.
For a local build, use the matching artifact from build/release/0.1.6, or the matching project's development output. Keep Minecraft mappings consistent. Pre-26 Fabric consumers should let Loom remap the production mod dependency; ForgeGradle consumers should use their usual deobfuscated mod dependency configuration. Modern ModDev consumers must also use the appropriate development mappings. A plain unmapped production jar is not interchangeable with a development jar.
A Fabric project using Loom can use:
dependencies {
modCompileOnly(files("libs/salts_inventory_update-<minecraft>-Fabric-0.1.6.jar"))
// Add the same matching jar to a local runtime only when testing Salt-present behavior.
}
For a project using named development output, compileOnly(files(...)) can reference the matching loader, version-common and shared-common class directories. See this repository's compileApiExamples tasks for an executable example. The loader's remapping/deobfuscation configuration remains part of your own build; Salt does not publish an invented Maven coordinate.
Fabric
Leave Salt out of fabric.mod.json's depends. An optional suggests entry is allowed. Do not put the Salt providers in main or client entrypoints; those run even when Salt is absent. Salt reads the descriptor below from the owning ModContainer after your registries exist.
Forge 1.20.1
Leave Salt out of mandatory dependencies in META-INF/mods.toml. If you declare it for ordering/version information, use mandatory=false with modId="salts_inventory_update". Do not annotate the provider with @Mod or subscribe it as an ordinary automatic event subscriber. Salt scans the loaded mod files and runs common registration before server startup, or during client initialization.
NeoForge
Leave Salt out of required dependencies in META-INF/neoforge.mods.toml. Optional metadata can use type="optional" and modId="salts_inventory_update". Do not register the provider as a normal mod entrypoint/event subscriber. Salt reads each owning mod file's contents, using the supported NeoForge file SPI for that version. Client registration runs on the loader's queued client setup; dedicated servers select only the common provider.
Minecraft-specific types
The following native types differ between targets. CharacterEvent, KeyEvent and MouseButtonEvent use the package shown in the event column.
| Minecraft | Identifier type | nativeGraphics() | Event package | clickSlot action type | Payload codecs |
|---|---|---|---|---|---|
| 1.20.1 | ResourceLocation | GuiGraphics | com.salts_inventory_update.client.input | ClickType | Raw bytes |
| 1.21.1 | ResourceLocation | GuiGraphics | com.salts_inventory_update.client.input | ClickType | Raw bytes or StreamCodec |
| 1.21.11 | Identifier | GuiGraphics | net.minecraft.client.input | ClickType | Raw bytes or StreamCodec |
| 26.1.2 / 26.2 / 26.3 | Identifier | GuiGraphicsExtractor | net.minecraft.client.input | ContainerInput | Raw bytes or StreamCodec |
On 26.3, native mouse events and mouseButtonDown(...) use SDL mouse button ids, such as InputConstants.MOUSE_BUTTON_LEFT. clickSlot(...) retains container button conventions: for a pickup, primary is 0 and secondary is 1. Translate the event button before sending a slot click; do not forward the SDL id directly. Other container actions have their own button meanings. Earlier targets use their native pre-SDL mouse constants.
See the version adaptations in the example compilation tasks for native event construction and widget calls. These source differences require a build for each target.
Optional provider discovery
Ship a UTF-8 properties file at exactly:
# META-INF/salts_inventory_update.integration.properties
modId=my_mod
apiVersion=6
common=my.mod.salt.MyCommonIntegration
client=my.mod.salt.MyClientIntegration
# Optional prerequisites, evaluated before resolving either provider class:
# requires=another_mod,optional_ui_library
modId must match the descriptor's owning loader mod. common and client can be omitted independently. Each specified class implements DesktopIntegration, with an accessible no-argument constructor:
public final class MyCommonIntegration implements DesktopIntegration {
@Override
public void register(DesktopIntegrationContext context) {
DesktopServerApi.registerWindow(MyMenus.MACHINE, new MyMachineServerHandler());
}
}
The client provider registers DesktopClientApi definitions. Keep every Salt type reference inside these lazily discovered classes or classes they load. Your normal entrypoint must not instantiate the provider, store a Salt type in a field, inherit from a Salt class, or use a provider class literal. A client annotation alone does not make Salt optional.
The descriptor is the bridge: without Salt, nobody resolves the provider classes. The JVM can load your ordinary mod while their bytecode remains in its jar. On a dedicated server, Salt never resolves the client class. Put native GUI classes and client API imports exclusively in the client provider's dependency tree.
Common registration runs once per process, after mod registries exist, at client initialization or the first server-starting event. Client registration follows common registration. World restarts do not repeat registration. Providers run in deterministic mod-id order; use requires for prerequisites, not an assumed provider ordering. DesktopIntegrationContext.phase() identifies the selected phase and isModLoaded(...) can gate additional integrations.
Salt refuses an incompatible apiVersion, malformed/oversized descriptor, unknown descriptor key or absent prerequisite before class resolution. The descriptor is limited to 16 KiB and accepts only modId, apiVersion, common, client and requires. A failed common provider also prevents its client provider from running. Registered API entries are rolled back if the provider fails, including restoring deliberate window replacements. Keep other changes to your mod's hooks explicit: registration rollback covers Salt's registries, not arbitrary side effects in your code.
Open a client-only view
Client-only views use ordinary mod models and do not create a menu:
DesktopClientApi.registerView(PREFERENCES, PreferencesModel.class, new PreferencesWindow());
var handle = DesktopClientApi.openView(PREFERENCES, "main", model, Component.literal("Preferences"));
Different nonblank instance keys create independent windows. Reusing a key with the same model object focuses that instance, preserving its state. Reusing it with a different object is an error. A non-null model must match the class registered by registerView. openView returns an empty optional when no view is registered or the desktop is unavailable; your mod can open its original UI then. Install an ordinary mod-owned callback from the client provider, as ExampleUiHooks demonstrates, so normal code contains no Salt references.
The context exposes model(), state(), geometry and windowHandle(). The handle's UUID identifies this particular window lifetime. focus() restores an existing hidden instance when another modal does not own focus; close() disposes it permanently. Stale handles return false. Handles are invalidated before closed, preventing recursive close actions. Opening a replacement with the same key gives a new lifetime/UUID.
For client-only views, inventoryAvailable() is false, the session id is Integer.MIN_VALUE, slot lists are empty and the carried stack is empty. Menu buttons, rename, slot/quick-move actions and payload sends return false; typed payloads are denied before encoding. These views do not select an inventory transfer target.
Render intricate interfaces
DesktopRenderContext supplies text, fills, textures, sprites, item/virtual-item rendering, real slots, tooltips and entity previews. Sizes describe the complete surface, including its declared insets; contentX/Y/Width/Height derive from those insets. Salt's default presentation uses its frame. A mod-owned surface can use zero insets and draw the whole interface. Default callbacks use absolute scaled GUI coordinates. Region coordinates are window-relative.
Use explicit ARGB colors (0xAARRGGBB) for text and fills: 0xFFFFFFFF is opaque white and 0xFF404040 is opaque dark gray. A six-digit RGB text color has zero alpha and can become invisible on newer Minecraft renderers.
The surface overhaul is in progress. The implemented surface contracts are described here; resource-reload/accessibility hooks, complete gesture presentation, consumer examples and native acceptance are still tracked in the implementation record.
Override surface(context) to return a DesktopWindowSurface. DesktopWindowSurface.SALT supplies the normal appearance. modOwned(regions) supplies zero insets, explicit hit regions and preserved dimensions. Salt then adds no frame, backing fill, title, controls or resize decoration, and disables its native title/grip hit targets. Window title metadata remains available. Normal callback contexts expose the committed snapshot through surface().
prepareLayout(context) receives a candidate surface whose insets already apply to its content geometry. Position native widgets there. Salt then samples the final pure surface(...), advanced regions and decoration queries and commits their immutable results together. Queries may run in both layout stages; rendering/hit testing use the completed snapshot rather than rerunning those queries. Keep painting and input based on that prepared geometry.
Regions independently declare visual, interactive and placement participation. withRole(...) assigns CONTENT, MOVE, a directional resize role, SLOT, CONTROL or POPUP. Controls, slots and popups take priority over movement/resizing; background content has lower priority. Among declared regions of equal priority, the later region wins. Actual slots also prevent move/resize interception. An undeclared cutout can expose an underlying window; modality still blocks background interaction independently of shape. Image alpha alone never selects a hit target.
For styled Salt-managed chrome, return a DesktopWindowDecoration from decoration(context). Its metrics() defines title/control/grip geometry, and its render(context, controls) paints all chrome using your assets or draw calls. Each immutable DesktopControlState supplies its kind, bounds, hover/press/enable/selection state. Salt routes the controls using those same bounds and adds no default decoration when a renderer is supplied. Use DesktopChromeMetrics.contentInsets(padding) and DesktopInsets.surfaceSize(...) to keep surface and content sizes consistent.
Use nativeGraphics() to delegate appropriate parts of existing renderers and Minecraft/mod widgets. rawGraphics() exposes Salt's version bridge and context.gesture() supplies immutable computed slot/cursor presentation data. Native types differ by Minecraft version: GuiGraphics on 1.20.1/1.21.1/1.21.11 and GuiGraphicsExtractor on the 26.x targets. Compile against the matching target instead of assuming one native binary fits all versions.
withClip(x, y, width, height, draw) and withTransform(x, y, scale, draw) restore the parent scissor/pose in finally, including nested scopes. Clip dimensions must be nonnegative; transform positions must be finite and scale finite/positive. Clip coordinates follow the current native render pose. Apply the matching inverse transform in hit testing. DesktopScrollState provides bounded pixel scrolling, uniform-row virtualization, visible ranges/overscan and the corresponding row hit test. It does not own your model, variable-height layout or fetching policy. Existing helpers include text editing, buttons, slot/virtual grids and scrollbars; arbitrary trees, tabs and animations may use your own UI framework.
An optional DesktopWindowPresentation adds:
renderBehindFrame: attached decorations beneath the Salt frame.desiredWindowSize: native layout-driven size updates.externalRegions: visual, interactive and position-constraining areas independently. Transient popups can remain interactive without changing window placement bounds.updateTooltipState: hover activity notification, including inactive notifications for obscured native controls.cancelPointer: cancellation without a release/commit when capture is lost.
renderOverlay belongs to the main definition and runs above that window's content/frame, below windows later in the stack. External controls and popups must report their hit regions. Return real slots from slotAt only when the visible area represents those slots; arbitrary virtual hit targets stay in your own input callbacks. Avoid duplicate native and Salt slot-click handling.
Implement DesktopWindowPresentation alongside your DesktopWindowDefinition. Its externalRegions query must be side-effect free. DesktopWindowRegion accepts negative window-relative positions, nonnegative dimensions and independent visual, interactive and constrainsWindow flags. The visual, interactive and visualAndInteractive factories constrain placement; transientVisualAndInteractive creates a popup that does not. Use updateTooltipState(..., active) to clear native hover state when the window loses tooltip ownership.
Reuse your content/widgets, adapting position, focus, rendering and input ownership. Do not replace the game's active screen from a hosted render callback or blindly delegate a whole container screen that assumes player.containerMenu, one global cursor or native player-inventory placement. Per-version native behavior outside these hooks requires an explicit adapter. The examples and existing Tom's/Sophisticated integrations demonstrate supported patterns; they are evidence for those patterns, not proof that every UI framework can be hosted unchanged.
Geometry and viewport fallback
All surface/content sizes and regions use scaled GUI pixels, not framebuffer pixels. windowX/Y are screen-space origins; regions are relative to that origin. contentX/Y add the committed left/top insets. Content dimensions subtract both opposite insets and clamp at zero. DesktopInsets.ZERO imposes no padding. Mod-owned surfaces may deliberately declare their own insets. Default/minimum/maximum/snap sizes all describe the whole surface.
DesktopInsets.surfaceSize(contentWidth, contentHeight) adds insets with checked arithmetic. contentWidth(surfaceWidth) and contentHeight(surfaceHeight) subtract them and allow a zero-size interior. surfaceTransform() and contentTransform() provide translation/scale helpers: screenX/Y, exact localX/Y inverses and pixelX/Y rounded with Math.round. Native drawing uses its target's float transform; use integer translation and integral positive scale for crisp pixel art. Region rectangles are half-open on right/bottom. Negative region origins support attachments; negative dimensions and arithmetic overflow are rejected.
The surface's alpha, declared visual regions, pointer regions and placement constraints are independent. Salt does not sample image alpha. Declare a transparent cutout as absent from the visual/hit shape when clicks should reach another desktop window. A transparent visual corner may still have an interactive region when the owner must block input there. Shape never bypasses modal or world-input rules. Declaring a region does not draw or scissor it; your renderer owns its actual pixels.
CLAMP fits the surface to the viewport and requires your renderer to adapt to the resulting size; it may reduce below an author minimum when the viewport is smaller. PRESERVE retains unscaled dimensions and may overflow; it preserves access to the base window's top edge where possible. ADAPT also preserves pixels and calls surfaceUnavailable(context) once per unavailable surface/viewport size, including placement-constraining attachments. Select a compact internal layout, new desired size or another policy there. The default callback leaves the dimensions preserved. A newly fitting layout resets that notification. No policy scales textures automatically or silently hands a detached authenticated session to an unrelated native screen.
Use environmentChanged(context, environment) to react to GUI scale or viewport changes. Client-only ordinary UI hooks can choose their normal screen when openView is unavailable. For menu-backed content, implement a compact view or deliberate overflow in the same authenticated model. A fallback that opens a new native menu must follow your mod's normal server-authorized opening flow. Do not assign minecraft.screen or player.containerMenu to bypass it.
TerminalWindow demonstrates ADAPT: a small viewport reduces the virtual catalog's dimensions and hides the inspector attachment while retaining its state. It keeps a readable 160×120 minimum and reserves room for the protruding tabs. Below that minimum it deliberately retains unscaled dimensions. Its inventory/menu topology never changes when selecting the compact layout.
Author minimum sizes take precedence over an inconsistent author maximum; provide maxSize >= minSize to avoid that normalization. Salt applies author limits on initial/restored geometry, desired-size updates, handle resize, dragging and snapping. Preservation policies retain dimensions rather than shrinking to make attachments fit. FIXED disallows user resize; a provider may still update its desired size for an internal mode change.
Definition defaults and callback failures
A definition can override only the capabilities it needs. createState returns null by default; title returns originalTitle; defaultSize uses the setup context's dimensions; minSize is 64×48; maxSize, snapSize, decoration, createRecipeBook and slotAt return null. resizePolicy is FIXED, options enables all seven permissions, surface is Salt's normal surface, popups is empty and layoutRevision is an empty string. modal and wantsTextInput are false. Input, tooltip, traversal and dismissal callbacks return false; other notification/render/persistence callbacks do nothing. Default narration supplies the metadata title.
Setup defaults for a client-only view are a 240×160 surface and 256×192 nominal content hints. Return your own surface dimensions when those hints do not describe your UI. Setup hints are not mandatory padding or an author minimum. Menu-backed setup dimensions depend on the captured menu; choose explicit dimensions when preserving original artwork.
surface and custom decoration metrics must be non-null; null popup/attachment lists are treated as empty. Prefer the documented defaults rather than relying on defensive normalization of malformed queries. Definitions and their queries run on the client thread. Callback exceptions produce structured diagnostics; an initialization failure rejects that window, input failures are treated as unhandled and rendering failures skip that callback. A failure before a layout commits retains its previous surface/region snapshot; Salt cannot undo native widget changes made in prepareLayout. Salt does not roll back mutations you made in your model or server handler. Validate before mutation and handle operation-specific errors in your own UI. Closed lifetimes suppress subsequent rendering/input/model callbacks; closed is the final definition notification.
Computed inventory gesture presentation
DesktopGestureSnapshot contains id, phase (NONE, PENDING, DISTRIBUTING), native pointer button, container quickCraftType, nullable ownerInstanceId, immutable slots, computed carriedPreview, nullable carriedCountText, and pointerCaptured. It belongs to the current callback, not a mutable menu transaction. Stack accessors return copies. slot(sessionId, menuSlotId) resolves a preview by authenticated session and logical id; null means no affected preview for that slot.
Each DesktopSlotPreview contains sessionId, menuSlotId, a computed displayStack, nullable countText, eligible, selected and hovered. Distribution counts include current target contents, capacity, Salt's configured slot policies and global selected target count. Targets may belong to several windows/sessions. A non-participating window sees phase NONE; it must not paint another owner's targets as its own. Use the actual slot stack when no preview exists. OriginalSlotArtwork is the complete custom-rendering example; it never mutates a slot or the shared carried stack.
gestureChanged(context, DesktopGestureEvent) reports a stable gesture id and STARTED, UPDATED, COMPLETED or CANCELLED with a reason. A terminal callback observes cleared pending presentation. Completion means the pointer gesture ended; server authorization/reconciliation still determines the inventory result. Cancellation covers discarded pending clicks, invalid targets, owner disposal/hiding and surface-mode changes. Salt handles releases consumed by its inventory routing. Clear your own transient native previews from terminal callbacks or read the new snapshot; global mouse polling is unnecessary. Custom native widget capture is independently exposed by pointerCaptured() and the presentation's cancelPointer hook.
Keep the original menu slot topology and backing storage when omitting player inventory/hotbar visuals. Bind ownership through DesktopMenuBindings; hidden player-owned slots remain in the menu and are presented through Salt's shared inventory. A logical id need not equal a physical container index. Dynamic wrappers supply a current resolver and slot snapshot. Hidden real slots cannot be returned as clickable targets. Virtual entries have no real logical slot; use authenticated mod payloads with server-owned quantity and permission checks instead.
Native widgets, popups and accessibility
DesktopWidgetHost is an optional per-instance router for existing AbstractWidgets. add(id, widget, semanticLabel[, cancellation]) rejects duplicate/blank ids, reused widget instances and null arguments. Position widgets in prepareLayout; paint with host.render(context) and delegate mouse/key/character methods. focusNext(forward) cycles visible active widgets; wire it from the definition's focusNext callback, used for unconsumed Tab/Shift-Tab. Hidden or disabled widgets lose focus and captured input before routing/rendering/narration; cancellation is delivered once. clearFocus, nullable focusedId, hoverActive, cancelPointer and narrate(output) manage their corresponding local state. The cancellation hook must clear custom drag state without executing a release action. Cancel capture before replacing an internal widget set. Native widgets still own caret, selection, button actions and focus artwork.
Override narrate(context, NarrationElementOutput) to describe the hosted view and its focused controls. The default narrates title(context) even without visible host chrome. Salt delegates narration to the modal/keyboard owner. host.narrate preserves the native widget's title, role and value, then adds your semantic label as a hint. Supply meaningful titles/labels and visible focus cues for custom controls. ClientOnlyWindow demonstrates both keyboard routing and narration; mod-owned surfaces retain the same accessibility hooks.
popups(context) returns immutable descriptors in bottom-to-top order within this owner. DesktopPopup(id, regions, modal, dismissOnOutside, dismissOnEscape, dismissOnFocusLoss) rejects blank ids; duplicate ids in one layout are errors. Regions become transient POPUP roles and do not constrain window placement. The integration still paints and routes the popup's widgets in its owner group. context.popups() exposes the committed list. Popup modality is desktop-wide while its owner is active; hidden owners cannot block input.
dismissPopup(context, id, reason) receives OUTSIDE_PRESS, ESCAPE or FOCUS_LOST. Return true after removing it from the model and next paint; Salt cancels pointer capture and commits the new hit layout. A modal popup consumes an outside press even if dismissal is declined. A nonmodal dismissal lets normal routing continue. Escape checks the last declared popup first, before owner key input. Dismiss flags select requests, not forced mutation of your model. Close nested subview tasks/subscriptions yourself when dismissing them. Persistent panels use placement-constraining surface/external regions; popup descriptors are transient but remain owned by that window.
Before replacing an internal view, tab layout or set of real slot targets, call windowHandle().cancelInput() on the client thread. It cancels that owner's pointer capture, window drag/resize and any slot gesture involving it; other participating owners receive the same terminal cancellation. An unrelated owner's slot gesture remains intact. If called during a handled press, Salt does not capture the replacement view for that old press. It returns false for a closed lifetime and does not undo actions already sent to the server. Cancel or close the old subview's own asynchronous subscriptions separately.
Input, focus and window constraints
Mouse presses go to the topmost hovered window or modal owner. A handled API press captures subsequent drag/release events for that owner, even outside its rectangle. Mouse motion reaches the capture owner or hovered window. Capture is cancelled on hide, removal and modality changes; cancelPointer must clear pending gestures without committing them.
Keyboard and character input go to one active API keyboard owner. keyboardFocusChanged reports ownership transitions. keyboardFocused() differs from focused(): the latter is the selected inventory transfer target. Opening/clicking a client-only view does not redirect Shift-click transfers. A focused editor returning wantsTextInput=true suppresses desktop shortcuts and movement. Forward key press/release and character events to the appropriate native widget; it still owns its internal caret/selection. Release events clear movement key state.
modal(context) is a pure query. An active modal stays on top and blocks pointer, keyboard, hotbar/world and inventory interaction behind it. It also takes keyboard ownership. Hidden windows cannot hold modality. Consume Escape in your callback to dismiss an internal modal panel; otherwise Escape closes a closable modal owner.
Use DesktopWindowOptions to allow moving, pinning, user closing, locking and management menus independently. Unsupported controls are hidden. Constraints apply when restoring saved state and during desktop updates. An owner's permanent handle close and world/session teardown can dispose a view even if user closing is disabled.
DesktopResizePolicy.FIXED disables interactive resize, FREE permits arbitrary resizing and STORAGE_GRID uses grid-oriented resizing. Sizes describe the surface including its declared insets. Supply defaultSize, minSize, optional maxSize and snapSize for your layout. Defaults are a 64×48 minimum, no integration-specific maximum and all seven window options enabled. Your layout must honor these dimensions and update child geometry after moving/resizing; side-region placement may constrain what fits on a small desktop.
Core keeps ordinary frames within all four desktop edges, including the complete bottom/right bounds. Resolution and GUI-scale changes recover retained window bounds as well. If this changes an API window's size or position, its resized/moved callback receives the current viewport environment; update cached child geometry there. Native surfaces using PRESERVE or ADAPT retain their existing viewport-policy contract and should select a compact layout when the original surface cannot fit.
Handles expose state(), available(action), request(action), moveTo(x, y) and resizeTo(width, height). DesktopWindowAction supports focus, user close, pin/unpin, lock/unlock and MANAGEMENT_MENU. Focus restores a persistently hidden window. Right-click an explicit MOVE region to open the management menu, or call request(MANAGEMENT_MENU). Salt anchors it to an ellipsis control when present, otherwise to the surface's upper-right edge, and keeps it in the viewport. Escape dismisses the menu before reaching the owner's key callback. Parameterized movement/resizing use their own methods; request(MOVE) and request(RESIZE) return false. windowStateChanged(context, snapshot) observes changed state. User requests honor permissions, modality and lifetime; permanent owner close() remains separate from user-close permission.
Lifecycle, persistence and threads
Client render/input/tick/lifecycle callbacks and view handle operations run on the client main thread. Common provider registration runs on the selected client/server initialization thread. Server session/payload callbacks run on the server thread. Marshal asynchronous model results to the appropriate main thread before touching a menu, window or widget. Do not retain a callback context or native graphics object beyond that callback.
windowHandle().schedule(action) may be called from a background thread; it queues an update and suppresses it if the window has closed before execution. context.tasks() supplies a lifetime-owned DesktopWindowTasks scope. watch(stage, success, failure) observes shared work without cancelling the shared stage; closing the returned subscription suppresses its results. submit(executor, work, success, failure) owns its work and supplies a cooperative cancellation predicate. Completion callbacks run through the owner on the client thread. Disposal closes the scope and suppresses queued/late results. Do not capture a live callback context in a worker; capture your mod-owned model or immutable request data instead.
Start lifetime-scoped asynchronous observations in opened or later. Initial environment/preparation callbacks run before the window is open; updates scheduled for a not-yet-open lifetime may be suppressed. A subview replacement should close its own subscriptions while retaining the parent window's task scope.
createState runs for each instance; the initial environmentChanged notification precedes surface preparation; opened follows creation/restoration. moved, resized, transfer-focus and keyboard-focus callbacks track desktop changes. Tick/animation callbacks continue for visible windows. Persistent hiding retains the instance and state while disabling interaction. closed runs once on permanent disposal, including owner/world changes. The final closed-state notification precedes closed; preparation/render/input observers stop after disposal, including reentrant close from a callback. Release native resources and pending jobs there.
loadLocalState/saveLocalState use a per-window CompoundTag for UI preferences. Geometry/pins use Salt's existing window-state partitioning. Client view identity includes view id and instance key. Menu-backed source keys identify real sources; avoid assigning identical source keys to distinct containers. Persist filters, selected tabs and layout preferences, not authoritative stacks or server authorization tokens. Reopening the same retained instance preserves its state; reconstructing one creates new state then loads local preferences.
layoutRevision(context) defaults to the empty string and is limited to 256 characters. Change it when saved geometry/local preferences no longer fit your UI schema. Salt stores its revision separately from your preferences; mismatches discard the old local tag and reset to the instance's initial size before loading fresh preferences. Keep this revision per integration/layout, not tied to arbitrary runtime data.
DesktopWindowEnvironment(viewportWidth, viewportHeight, guiScale, resourceRevision) is delivered initially and when it changes. Resource reload increments resourceRevision and re-prepares retained windows on the client thread. Re-resolve your cached assets/styles when it changes; native texture ids use the reloaded resources. Salt cannot reconstruct arbitrary mod-specific cached renderer objects. Layout queries must be side-effect free except prepareLayout, and one completed layout supplies the surface, regions, popup descriptors and decoration metrics used by both paint and hit tests.
Within a window group the order is underlays, surface/chrome, content/slots/widgets and its overlay/attachments. Later window groups cover earlier groups. Native render strata separate groups. Desktop management popups, shared cursor and tooltips are final desktop stages; a per-window overlay does not paint over later owners. Render callbacks may not replace the active screen or retain native graphics beyond the callback.
Server actions and authority
Use context helpers rather than sending another window's vanilla container packet. Menu buttons, slot clicks and custom payloads include Salt's connection/session authorization, state and ordered mutation handling. Each same-type menu has its own session and state. Salt checks capabilities, menu validity, visibility, state freshness, player state and rate/size bounds before dispatching authorized custom actions.
Register a channel with DesktopServerApi.registerPayload and send using DesktopInputContext.sendPayload. Raw bytes work on every target. Newer targets also provide registry-aware typed codecs through DesktopPayloadCodecs; decoding rejects oversized/trailing input. Server payload contexts expose the authenticated player, menu, per-session state and source key, plus sendToClient and broadcastChanges.
Client replies arrive in the definition's customPayload(context, channel, data) callback for that session. Server window handlers have createState, opened, tick, closed and visibilityChanged callbacks. Recipe-browser transfers stay disabled for custom menus until validateTransfer returns an allowed DesktopTransferDecision based on the server-resolved recipe and real destination slots. The recipe-transfer reference gives signatures, request/session fields, construction rules, limits and a consumer pattern.
Initialize every field used by your menu's full synchronization before that first write. Server createState runs before the synchronizer is installed; opened follows installation and its initial full synchronization. Menu construction or createState can initialize those values. A first tick or opened callback is too late for values serialized during opening. This matters for native mod synchronization as well as Salt's slot/data snapshot.
Your handler must validate operation-specific permissions, indexes, quantities and storage state. Treat virtual-entry ids/counts as requests, never as authoritative stacks. Preserve backing inventory rules, mayPlace/mayPickup, source locks and cursor reconciliation. Use reject(reason) for a diagnostic on a mod-specific refusal, then return from your handler. Its reason is limited to 512 characters. It records a warning; it does not abort execution, undo mutations or send an error reply by itself. Send your own response if your UI needs one. If a native handler needs a temporary active-menu assumption, adapt it explicitly; a context does not make the player's global menu point at this detached session.
Transport and capture bounds
| Field | Limit |
|---|---|
| Opening data or custom payload body | 32 KiB |
| Client-advertised supported menu ids | 1,024 |
| Explicit force-enabled menu ids | 256 |
| Wire identifier text | 256 characters |
| Source text | 512 characters |
| Desktop container sessions | 16 |
| Items in an opening snapshot | 8,192 |
| Menu data values | 4,096 |
| Protocol envelope | 1 MiB |
The session/slot limits govern real menus, not the length of your virtual catalog. Keep large catalogs in your mod's model and use bounded paging/synchronization through your own actions. Salt's capability lists are separate from force overrides; do not use force capture as a substitute for registering a renderer.
Diagnostics and verification
DesktopDiagnostics.snapshot() returns an immutable list of recent structured events with level (INFO, WARNING, ERROR), owner, operation, message and optional cause. listen(...) subscribes and returns an AutoCloseable subscription; close it when your debug view closes. Listeners run on the reporting thread, so marshal updates before touching client UI. Salt also logs these events. History is bounded to 256 entries. Check discovery/API mismatch, registration conflicts, eligibility/opening-data failures, callback exceptions and action refusals when a window does not work.
Automated proof in this repository covers an external-style mod compiled against the API and run with Salt removed from its runtime classpath, Salt-present phased discovery, dedicated-server client-class resolution traps, registration rollback, client-only action denial, unique/stale handles, focus/modality, external regions, custom inventory ownership, capture negotiation and packet bounds. Existing sort, transfer, gesture and protocol tests remain part of verification.
Historical API5 companion acceptance gates are tracked in the companion verification record. The surface API verification record covers the earlier completed API4 work. Earlier API test totals and old screenshots are historical evidence. Compilation, assertions, clean process exit and visual fidelity are assessed separately. The public signature reference lists the current consumer declarations; this guide specifies behavior and ownership.
$env:CI = 'true' # supported NeoForge binary patch pipeline
./gradlew verifyApiExamples :common:test
./gradlew -I functional-tests/sort-tests.gradle :1.20.1:fabric:test :1.21.1:fabric:test :1.21.11:fabric:test :26.1.2:fabric:test :26.2:fabric:test :26.3:fabric:test
./gradlew -PincludeFunctionalTests=true functionalTestCompile
./gradlew build
Run your own mod with Salt absent and present, and on a dedicated server, before shipping. Test multiple instances, cursor/slot restrictions, persistence, resize, clips, modal input, native widgets and your mod's real permission/storage behavior. Headless tests establish routing and contract behavior; visual/native-framework behavior still needs an in-game pass for that integration.
HUD interoperability
Core API 6 also provides public detached-HUD layout providers for whole-layout movement, independent slot placement/scaling, visibility and interaction. Rendering and pointer targets use the same resolved geometry. See HUD interoperability for the contract, registration lifecycle, example and optional Raised adapter.
Built-in Character attachments (1.21.1)
These APIs are available in the 1.20.1 and 1.21.1 Core sources; the rebuilt Fabric pairs use them for Trinkets 3.7.2 and 3.10.0 respectively. The existing section anchor is retained. Core adds DesktopClientApi.registerBuiltinAttachment(id, Kind.CHARACTER, factory). Each factory creates one DesktopBuiltinAttachment per Character lifetime. Contributions compose with the built-in player preview, armor, offhand, crafting grid and recipe guide; they do not replace the workspace host or create a second player inventory. Other built-in kinds are rejected in this revision.
Callbacks receive the existing DesktopWindowContext<AbstractContainerMenu, Void> interfaces: model() is the real player menu, sessionId() is the authenticated player session, and contentX/Y() is the origin of the vanilla upper inventory layout. state() is null; store attachment state on the attachment instance. builtinSlotBounds(5..8) supplies visible armor anchors and builtinSlotBounds(45) supplies the offhand anchor when Core displays it. Override requestsBuiltinSlot(45) to keep Character's real offhand visible and interactive regardless of the hotbar layout. This is an additive visibility request; other views of that same native menu slot remain available and share the same stack. Character currently supports slot 45.
Use render, slotAt and occludes together. Return only real menu slot IDs; Core owns pickup, swap, drop, drag distribution, quick transfer, shared cursor and tooltips. An attachment hit wins over its owner's base slots. occludes owns blank popup pixels without making the whole desktop modal. regions supplies window-relative visual/input areas for z order and controller/Mouse Tweaks slot discovery. Hit queries must be pure: controller discovery samples many coordinates. placementBounds reserves window-relative room for expandable artwork without painting or blocking invisible regions. Core applies those bounds during placement, dragging and layout changes. opened, tick, suspended and closed manage native hover state; suspension may resume on the same instance. Core starts a fresh foreground stratum for each attachment, after the owner's preview and controls. Later windows and the open recipe guide still cover it. Restore native graphics state, and use rawGraphics().nextStratum() between native background and item passes when their depth conventions differ.
DesktopPlayerMenuApi.registerEquipment(id, Equipment) is a common-side registration for real player-menu equipment. Implement owns, a stable (group/type/instance) slotKey, and quickMoveTargets. Apply native quick-move predicates in addition to Slot.mayPlace; Core continues to check the native removal/insertion rules and authenticated session/state IDs. Owner UI visibility is not server permission. Existing MenuType bindings remain unchanged.
Bracket native slot reconstruction with beforeSlotRebuild(menu) and afterSlotRebuild(menu, player). Core removes only its own expanded slots and tracking entries, then appends them after the native rebuild. Logical identity and backing-storage changes invalidate old gestures and queued player-menu mutations; ordinary content updates preserve hover selection. Dynamic equipment snapshots use namespaced identities instead of assuming every index after 45 is expanded storage. The provider remains responsible for native slot materialization and inventory synchronization. See the 1.20.1 and 1.21.1 Trinkets adapters for complete consumer examples.
Built-in controls and joined menu windows
Core 0.1.5 on every supported mapping provides Character control contributions through DesktopClientApi.registerBuiltinAttachment(id, kind, factory). This revision supplies control rendering, mouseClicked, appendTooltip, window-local regions and lifetime callbacks (opened, tick, suspended, closed). Character contexts expose the player menu and the vanilla upper-inventory content origin. An attachment stores local state on its own instance. It does not grant access to slots from a different menu or install another item-click transport. The older Trinkets attachment contracts described above retain their existing signatures; the additional click and tooltip callbacks have default implementations.
A separate DesktopWindowDefinition can return a DesktopWindowAttachment from attachment(context). Supply the owner's window-handle UUID, preferred child body height, top protrusion (for example a cosmetic tab) and gap. Core places the child above the owner, matches its width, fits both to the desktop and reduces the child's height when necessary. The child must adapt its visible content to the committed windowHeight(); its definition can use normal mouseScrolled, pointer capture and controllerScrollRegions callbacks. The child keeps its own menu, authenticated session, slot IDs and public render/input context.
The owner and child are raised together. Closing/disposing or hiding the owner releases the child through the normal window/session lifecycle. One direct child is supported per owner; missing owners, multiple children, nested attachments and cycles are rejected. Decorations and external tabs still belong in surface(context).regions(). Keep layout queries pure and avoid independently moving/resizing a joined child. The owner controls movement and the combined bounds.
DesktopClientApi.isDesktopAvailable() lets a native mod retain its normal UI when desktop sessions are disabled or unavailable. DesktopMenuBindings.maxMenuSlots() publishes the menu slot bound, including hidden/cosmetic slots. The Curios adapters cover six native-loader releases using only these APIs and the existing menu/session registration contracts.
Native templates in Core 0.1.6
The native-template guide covers automatic window composition, retained native fragments, exterior panels, standard slot backgrounds, local profiles and the in-game inspector. These additive contracts are available across every supported version and loader; existing API window definitions retain priority.
DesktopSynchronization.isDesktopSynchronizer(ContainerSynchronizer) identifies a synchronizer owned by an authenticated desktop session. A native-menu adapter can pass that synchronizer to its upstream full-count setter when the upstream menu intentionally ignores the vanilla setter. The predicate exposes no implementation type and grants no inventory authority. Outside desktop ownership, retain the mod's original synchronization behavior.