Skip to content

Direct Hook API ​

Use WorkshopApi.hookRegistrar to register method hooks or modify the UI. In Java, call WorkshopApi.hookRegistrar(). Hook API is available since 0.1.0-dev22 and is marked UnstableSpwWorkshopApi.

If you are creating a plugin, start with the Developer Quickstart and confirm that the target player provides the API version you need.

Get Started ​

Declare the permission in the plugin's spmod {} block and get the user's approval.

kotlin
import com.xuncorp.spw.workshop.gradle.PluginPermission

spmod {
    PluginPermissions = listOf(PluginPermission.CLASS_TRANSFORM)
}

Before registering, check WorkshopApi.manager.isPermissionGranted(PluginPermission.CLASS_TRANSFORM). See Plugin Permissions for declaration, authorization, and denial handling.

The com.myapp names below are examples. Substitute the actual classes and methods from the target host.

Obfuscated targets

Use identifying features to resolve obfuscated target methods at runtime. The same method may have different obfuscated names in the Windows and Linux builds.

Method Hooks ​

hookMethod supports three callbacks, which can be combined as needed.

  • before runs before the original method. It can read or modify arguments or return early
  • replace uses the callback's return value in place of the original result. Call invokeOriginal() to run the original method when needed
  • after runs when the method finishes. It can read or change the result and handle exceptions

This example targets calculate(Int): Int.

kotlin
override fun start() {
    WorkshopApi.hookRegistrar.hookMethod(
        className = "com.myapp.Calculator",
        methodName = "calculate",
        parameterTypes = listOf("int")
    ) {
        before { call ->
            call.args[0] = 100
        }
        replace { call ->
            call.invokeOriginal()
        }
        after { call ->
            println(call.result)
        }
    }
}

The order is before → replace or original method → after. If before calls setResult() or setThrowable(), both replacement and original execution are skipped. With no replacement, the original method runs by default.

In Java, implement MethodHook for before and after callbacks. Calling setResult() during before replaces the return value.

java
@Override
public void start() {
    WorkshopApi.hookRegistrar().hookMethod(
        "com.myapp.Calculator",
        "calculate",
        List.of("int"),
        new MethodHook() {
            @Override
            public void before(MethodHookParam call) throws Throwable {
                call.getArgs()[0] = 100;
                call.setResult(call.invokeOriginal());
            }

            @Override
            public void after(MethodHookParam call) {
                System.out.println(call.getResult());
            }
        }
    );
}

Read Arguments and Handle Results ​

Kotlin / JavaPurpose
method / getMethod()Metadata for the hooked method.
thisObject / getThisObject()Current receiver, or null for static methods.
args / getArgs()Arguments of the current call, with primitives boxed.
result / getResult()Current return value, which may be null.
throwable / getThrowable()Current exception, or null.
setResult(value)Use this return value and clear the current exception.
setThrowable(failure)Use this exception and clear the current return value.
invokeOriginal()Run the original method with the current arguments and return its result or throw its exception.

Changes to args in before reach the original method. In after, use setResult() or setThrowable() to change the final outcome. setResult(null) explicitly returns null. Use it for early return from a void method as well.

Arguments and return values must match the target types. MethodHookParam is valid only during the current callback. invokeOriginal() bypasses the hook at the current entry point and returns its result directly. Recursive invocations inside the original method may still trigger hooks. Hook callbacks run on the target method's thread.

Priorities and Exceptions ​

The default priority is 50. In Kotlin, set the priority parameter. In Java, use new MethodHook(priority). Before callbacks run from highest to lowest priority, in registration order when tied. After callbacks run in reverse order for the hooks whose before phase was reached. An early return stops subsequent before callbacks.

After callbacks can read exceptions from the replacement or original method. If a before or after callback itself throws unexpectedly, its argument and result changes are discarded. Changes inside referenced objects and other side effects may persist.

Select a Target ​

ParameterMeaning
classNameFully qualified name of the class that declares the target method.
methodNameTarget method's name.
parameterTypesFully qualified type names used to distinguish overloads.
inClassClass that contains the UI call. Changes apply only to calls to the target from that class.

parameterTypes defaults to null, which requires a unique target. An empty list means the target takes no application arguments. Use names such as java.lang.String, JVM primitive names such as int and long, and Class.getName() for arrays. For UI hooks, specify only the application's parameters.

UI hooks require a unique matching call in inClass. Target names and signatures can change between host versions. Specify which player versions your plugin supports.

Replace or Extend a Composable ​

replaceComposable replaces a selected component. afterComposable adds content after the selected component returns successfully.

kotlin
WorkshopApi.hookRegistrar.replaceComposable(
    className = "com.myapp.ui.PanelKt",
    methodName = "Panel",
    inClass = "com.myapp.ui.ScreenKt"
) { call ->
    PluginPanel(title = call.argument("title"))
}

In this example, PluginPanel is a @Composable function defined by the plugin.

Use a Compose effect for side effects after composition to avoid repeating them on recomposition.

kotlin
WorkshopApi.hookRegistrar.afterComposable(
    className = "com.myapp.ui.PanelKt",
    methodName = "Panel",
    inClass = "com.myapp.ui.ScreenKt"
) {
    LaunchedEffect(Unit) {
        WorkshopApi.ui.toast("Hook is active", WorkshopApi.Ui.ToastType.Success)
    }
}

Java can register a ComposableHook implemented in Kotlin.

kotlin
class PanelHook : ComposableHook() {
    @Composable
    override fun Content(call: UiHookCall) {
        PluginPanel(title = call.argument("title"))
    }
}
java
WorkshopApi.hookRegistrar().replaceComposable(
    "com.myapp.ui.PanelKt",
    "Panel",
    "com.myapp.ui.ScreenKt",
    new PanelHook()
);

Composable code must be written in Kotlin with the Compose compiler enabled. The default priority for UI hooks is 50. Set priority in Kotlin. In Java's full overload, pass parameterTypes and priority before the callback.

When several replacements match the same call site, the highest priority wins, with the earliest registration breaking ties. All added content from afterComposable runs in priority order. With no active replacement, the original component is displayed.

Append to Builder Content ​

Use appendContent to extend an ordinary builder callback, such as one that creates menu items. The scope type must match the target component's callback parameter.

If the target menu provides a MenuScope and the plugin defines PluginMenuItems.append(), the call looks like this.

kotlin
WorkshopApi.hookRegistrar.appendContent<MenuScope>(
    className = "com.myapp.ui.MenuKt",
    methodName = "Menu",
    inClass = "com.myapp.ui.ScreenKt",
    parameter = "content"
) { call ->
    PluginMenuItems.append(this, call)
}

In Java, provide the scope class explicitly.

java
WorkshopApi.hookRegistrar().appendContent(
    "com.myapp.ui.MenuKt",
    "Menu",
    "com.myapp.ui.ScreenKt",
    "content",
    MenuScope.class,
    (scope, call) -> PluginMenuItems.INSTANCE.append(scope, call)
);

The original builder runs first, followed by all added content in priority order. The builder is an ordinary callback. To draw a Composable, pass Composable content through the appropriate parameter on the builder scope. appendContent supports ordinary builders and cannot append directly to a Composable lambda.

UI Arguments and State ​

Read the current call's business arguments through UiHookCall. arguments is a read-only shallow copy. Primitive values are boxed. thisObject or getThisObject() gives the current receiver, or null for static calls.

Check parameter names, indices, and types before reading.

  1. Reading by name requires parameter names in the target. Use an index if they are unavailable. An index outside arguments throws IndexOutOfBoundsException
  2. Kotlin's argument<T>() validates the type. A missing or null argument for non-null T, or a type mismatch, throws IllegalArgumentException with the argument identifier. Use a nullable type to accept missing or null arguments
  3. Java's getArgument(index, type) and getArgument(name, type) validate the type and return null for missing or null values. Handle null in the caller. A type mismatch throws IllegalArgumentException
kotlin
val title = call.argument<String>("title")
val firstArgument = call.argument<Any?>(0)
java
String title = call.getArgument("title", String.class);
Object firstArgument = call.getArgument(0);

Arguments remain valid only during the current component or builder invocation. Follow Compose state and side-effect conventions. Use collectAsState() for flows, LaunchedEffect for asynchronous work, and DisposableEffect for resources that require cleanup. Exceptions thrown by UI callbacks propagate normally.

Default Arguments ​

  • replaceComposable replaces calls only when all application arguments are passed explicitly. Calls that rely on defaults keep the original component
  • When using afterComposable, read only arguments you know were passed explicitly. Omitted arguments may differ from the final default values
  • appendContent requires an explicit builder callback. It does not append when the callback is null or omitted

Unregister Hooks and Manage Their Lifecycle ​

Registration returns a HookHandle. To cancel it early, call unhook() or close(). Repeated calls are safe.

kotlin
val handle = WorkshopApi.hookRegistrar.hookMethod(
    className = "com.myapp.Calculator",
    methodName = "calculate"
) {
    after { call -> println(call.result) }
}

handle.unhook()

The host automatically unregisters hooks when a plugin is disabled or uninstalled, or when permission is revoked. Save handles when you need to unregister a hook early. In-flight callbacks may finish. Register the hooks again when the plugin is re-enabled.

Limitations and Errors ​

Method hooks do not support constructors, native, abstract, or suspend methods, or calls that have been inlined. Use compileOnly for Compose, Kotlin, Workshop API, and other host-provided dependencies. Match the host's Kotlin and Compose compiler versions when building UI plugins.

ErrorWhat to check
PluginPermissionDeniedExceptionConfirm that the plugin declares and has been granted CLASS_TRANSFORM, and that it registers the hook from plugin code.
IllegalArgumentExceptionCheck for a unique target and verify parameter types, names, and scope parameter types.
IllegalStateExceptionCheck the error details, hook installation, and host version.
Recent Update