SDK API ガイド

現在の Turboism プラグイン SDK のエントリーポイント、サービス、オブジェクトモデル、ライフサイクル、機能境界。

Turboism SDK は plugin にとって唯一の public dependency です。Turboism は単一の public SDK 階層を公開し、source repository のレビュー済みバイナリ API ベースライン(現在は 0.67.4 の現行リリースゲートである v23。v2–v22 は過去の監査記録として保持)が compatibility gate です。利用可能性は、次の 4 つの事実に分かれます。

  1. SDK に API が存在する。
  2. plugin が必要な permission を宣言している。
  3. Runtime に対応する capability Provider がある。
  4. active Cubism version と object generation がサポートされている。

生成済み type と method の index については、SDK HTML API リファレンス を開いてください。

SDK API 範囲と incubating API

plugin は "turboismApi": "[0.67.0,1.0.0)" を宣言します。下限は plugin が必要とする最小のフレームワーク基底バージョンで、Runtime が API バージョンを算出する際は beta、nightly、SNAPSHOT のサフィックスを無視します。旧来の [0.1.0,0.2.0) plugin は拒否されます。後のリリースで追加された SDK メンバーを使う場合は、意図的に下限を引き上げてください。新しい SDK でコンパイルしても、その追加分が古い Runtime で動くわけではありません。たとえば公式 plugin の atlas-folder-layout、atlas-bitmask-nesting、atlas-dalsoo-polygon、psd-clip-mask-import は 0.67.4 を、external-psd-edit と atlas-maxrects-bssf は 0.67.2 を必要とします。

@Incubating(dev.turboism.sdk.Incubating)は、破壊的なシグネチャ変更を含め、変更または削除される可能性がある実験的 API を示します。厳密な互換性ベースラインからは除外され、型への付与はそのメンバー全体に及びます。incubating API への依存はビルドに使った SDK バージョンに固定されたものとして扱い、SDK を更新するたびに見直してください。最初の安定 SDK リリースまでは破壊的変更が許容されるため、アノテーションがないことは最初の安定 SDK リリースが行われた証拠にはなりません。

プラグインのライフサイクル

すべての entrypoint は TurboismPlugin または CubismPlugin などの subinterface を実装します。

public interface TurboismPlugin {
    default void init(PluginContext context) throws Exception {}
    default void enable() throws Exception {}
    default void disable() throws Exception {}
    default void shutdown() throws Exception {}
}
  • init: context を保持し、configuration schema を登録し、plugin-private state を作成する。
  • enable: action、event、UI、task、その他の active behavior を提供する。
  • disable: Runtime が plugin scope を閉じる前に active behavior を停止する。
  • shutdown: scope が所有していない plugin-private resource を解放する。

1 つの JAR に順序付きの複数 entrypoint を含めることができます。construct、initialization、enablement は manifest order に従います。disablement と shutdown は reverse order で実行されます。startup は JAR 全体で atomic です。

PluginContext

EntryPurpose
descriptor()現在の JAR-level PluginDescriptor
logger()plugin-scoped logging
paths()configuration、data、cache、state、log namespace
localization()locale、text lookup、formatting
tasks()bounded one-shot と fixed-delay task
hostReads()bounded asynchronous host read
storage()plugin-owned DATA、STATE、CACHE storage
userFiles()user-granted file handle
cubism()snapshot、unified object access、transaction compatibility entrypoint
selectionQuery()selection read と change subscription
modelHierarchyQuery()model-tree query
cubismRead()aggregated read capability family
eventBus()typed event の publish と subscribe
actions() と menus()action registration と menu contribution
services().require(MainToolbarRegistry.class)、services().require(PaletteToolbarRegistry.class)、services().require(ContextMenuRegistry.class)typed UI contribution registry
services().require(UiHostCapabilityService.class) と uiScheduler()toolkit-neutral UI capability と UI-thread scheduling
config()typed plugin configuration
diagnostics()現在の structured diagnostic
disposableScope()reverse-order lifecycle cleanup

一部の default service は UnsupportedOperationException を throw し、他は explicit unavailable implementation を返します。plugin は unavailable capability family を処理し、迂回してはいけません。

任意サービスの検出

型付きディレクトリで任意サービスを取得します。find はサービスがない場合の機能縮小に使い、require は PluginServiceUnavailableException を投げます。サービスが存在しても、権限、ホストバージョン、機能、オブジェクト世代の検査は操作ごとに行われます。

context.services().find(UiHostCapabilityService.class).ifPresent(ui -> {
    // Use the installed UI service with the required permissions.
});

ツールバー、コンテキストメニュー、UI ホスト、設定の追加にはこのディレクトリを使います。削除された PluginContext の簡易アクセサーは使用しません。

登録とクリーンアップ

多くの registry は Registration を返します。これは AutoCloseable handle です。

Registration registration = context.actions().register("example.refresh", action);
context.disposableScope().register(registration);

scope は registration を reverse order で閉じます。Runtime が plugin ClassLoader を安全に解放できるよう、action、menu、UI contribution、subscription、task handle、その他の closeable resource を scope に入れてください。

Cubism lifecycle hook は callback registration bus ではなく、entrypoint interface から検出されます。

アクション、メニュー、イベント

ActionRegistry.Action は ID、label、handler を提供します。ActionContext は typed UI action event または generation-bound context-menu selection を運べます。

MenuRegistry.MenuContribution は slash-delimited menu path を登録済み action ID と order に結び付けます。

汎用 event bus は型付きです。

record MyEvent(String value) implements dev.turboism.sdk.event.TurboismEvent {}

Registration subscription = context.eventBus().subscribe(
    MyEvent.class,
    event -> context.logger().info(event.value())
);
context.disposableScope().register(subscription);
context.eventBus().publish(new MyEvent("changed"));

Event は immutable な plugin- または SDK-owned value にしてください。raw host object、Swing widget、native handle、host ClassLoader を event に入れないでください。

スナップショットとクエリ API

CubismFacade は引き続き immutable runtime snapshot を提供します。

CubismRuntimeSnapshot runtime = context.cubism().runtime();
Optional<ProjectSnapshot> project = context.cubism().activeProject();
Optional<DocumentSnapshot> document = context.cubism().activeDocument();
Optional<ModelSnapshot> model = context.cubism().activeModel();
boolean hostPresent = context.cubism().isHostPresent();

狭い query service には次が含まれます。

  • パラメータ検索には context.cubism().model().active().parameters()、任意サービスの取得には context.services() を使用します。
  • current selection と selection-change subscription 用の SelectionQueryService。
  • model-tree traversal 用の ModelHierarchyQueryService。
  • project、document、model、selection、parameter、model-object、mesh、deformer、PSD、clip-mask、texture-atlas、render-status、workspace、theme-status の read family 用の CubismReadCapabilityService。

Snapshot と query value は immutable DTO であり、host object reference ではありません。

統合された Cubism オブジェクトグラフ

新しい plugin code では unified object API を優先してください。

CubismModel model = context.cubism().model().active();
Parameter parameter = model.parameters().find(new ParameterId("ParamAngleX"));

float value = parameter.getValue();
parameter.setValue(value + 1.0f);

CubismModel は Parameters、Parameter Groups、Parts、Drawables、Deformers、Warp and Rotation Deformers、Glue、Canvas、model update、default-keyform lock、parameter-binding operation を公開します。

Strong ID には ProjectId、DocumentId、ModelId、ModelObjectId、ParameterId、ParameterGroupId、PartId、ArtMeshId、DeformerId、GlueId、ParameterBindingPointId が含まれます。

model とその child は generation-bound です。document switch、reload、deletion、plugin disablement、Provider replacement、その他の invalidating lifecycle event の後は、reference が fail closed します。

操作ライフサイクルフック

CubismPlugin は Parameter、Part、Drawable、Deformer、Model hook family をまとめます。

public final class ClampPlugin implements CubismPlugin {
    @Override
    public float beforeSetParameterValue(Parameter parameter, float value) {
        return Math.min(value, parameter.getMaximumValue());
    }

    @Override
    public void onParameterValueChanged(
        Parameter parameter,
        float oldValue,
        float newValue
    ) {
        // 権威ある状態が変わった後にのみ実行されます。
    }

    @Override
    public void afterSetParameterValue(Parameter parameter, float value) {
        // 正常完了を観測します。二度目の変更は行わないでください。
    }
}
before -> 正規操作 -> 権威状態の確認 -> on(変更時のみ)-> after(正常完了時)
  • before は同期的かつ順序付きで、argument を書き換えられます。
  • on は observable change の場合だけ発行されます。
  • after は normal completion を観測します。
  • observe と intercept の permission は別々です。
  • plugin が bytecode transformer を直接登録することはできません。

設定

Typed configuration は schema、codec、sequential migration、asynchronous read、revision-based compare-and-set write をサポートします。

ConfigKey<Boolean> enabled = new ConfigKey<>(
    "example.settings",
    "enabled",
    true,
    ConfigCodecs.booleanValue()
);

ConfigSchema schema = new ConfigSchema(
    "example.settings",
    "settings.json",
    1,
    List.of(enabled)
);

context.config().registerSchema(schema, List.of());
context.config().read(enabled);
context.config().write(enabled, true, expectedRevision);

Runtime は plugin settings を config/<pluginId>/ に保存します。plugin は turboism.home の下に自分で path を構築してはいけません。

プラグインストレージとユーザーファイル

PluginStorage は 3 つの root の下で atomic read、write、copy、move、list、delete operation を提供します。

  • DATA は persistent business data 用。
  • STATE は rebuildable runtime state 用。
  • CACHE は rebuildable cached data 用。
StoragePath path = new StoragePath(StorageRoot.STATE, "manual-order.txt");
context.storage().writeUtf8Atomic(path, "a\nb\n");
context.storage().readUtf8(path, 256 * 1024);

path は normalized relative path でなければなりません。user-selected external file には UserFileAccessService と scoped UserFileHandle object を使います。user file は unrestricted filesystem capability ではありません。

タスクと非同期読み取り

管理されていない thread、executor、timer を所有する代わりに PluginTaskScheduler を使います。

TaskSubmission submission = context.tasks().submit(
    new PluginTaskRequest(
        new TaskId("refresh"),
        PluginTaskKind.COMPUTE,
        PluginTaskPriority.NORMAL,
        token -> token.checkCanceled()
    )
);

Task は typed な submission、cancellation、completion、timeout、rejection、backpressure、circuit-open outcome を公開します。

AsyncHostReadService は意図的に小さな intent set を持ちます。現在の SDK に存在する intent だけを使い、将来の parameter、mesh、PSD intent を仮定しないでください。

ユーザーインターフェース API

UI API は Swing/AWT や host widget ではなく SDK DTO を使います。現在の family には次が含まれます。

  • action と menu。
  • main と palette toolbar。
  • typed context menu と context selection。
  • overlay、dialog、status notification、canvas hint、file selection。
  • toolkit-neutral PanelView embedded panel。
  • UI-thread scheduling。
  • canvas-hint notification(turboism.ui.canvas.hint 権限)。
  • scene-table、appearance、control-appearance、selected Editor contribution。

各 UI family には独立した capability と Provider evidence があります。ある family が利用可能でも、他の family がすべて有効になるわけではありません。

権限、機能、操作

  • permission は risk boundary を越えることを認可します。
  • capability は現在の Provider と host version が feature family をサポートすることを示します。
  • operation は 1 つの具体的な invocation と diagnostic identity です。

permission は operation validation を迂回せず、欠けている Provider を作りません。

クロスプラグインイベント契約

schema 4 を使用する plugin descriptor は、自身が export および import する public event type を宣言できます。それぞれは contract version と event type の ABI digest に結び付きます。Runtime はそれらの contract を ClassLoader delegation なしで解決し、duplicate export を拒否し、provider contract が認定されていない import を拒否します。event contract を宣言しても host への write 権限は付与されず、plugin が所有する event type を他の plugin から利用できるようになるだけです。詳細はプラグインマニフェストとパッケージングを参照してください。

0.67.2 と 0.67.4 の SDK 追加内容

v22(0.67.2)と v23(0.67.4)のベースラインは API を追加するのみで、既存の公開型や呼び出し可能な JVM ディスクリプタは削除していません。

  • テクスチャアトラスのページ別サイズ: TextureAtlasPageSize と、ページごとに独立したサイズを持つ TextureAtlasLayoutPlan コンストラクタ。TextureAtlasLayoutPlanner.supportsCompleteAtlas() は default メソッドで、現在ページ専用のプランナーはこれをオーバーライドして false を返します。
  • パッキング失敗: プランナーは、入力が収まらないことを公開かつ拡張可能な TextureAtlasPackingException とその Reason(PAGE_BUDGET_EXHAUSTED、ITEM_DOES_NOT_FIT、INVALID_RESERVED_SIZE)で報告します。
  • ポリゴン輪郭とポリゴンページ(0.67.4): TextureAtlasLayoutItem に任意のソース outline(4 引数コンストラクタとアクセサ。3 引数コンストラクタは維持)、TextureAtlasLayoutPlan に polygonPages(8 引数コンストラクタとアクセサ)が追加され、TextureAtlasOutline は値の等価性、hashCode、toString を持つようになりました。TextureAtlasPolygonLayoutPlanner は @Incubating です。
  • PSD 編集: PsdEditFile.openInApplication(String) は default メソッドです。
  • SettingsControl.FilePath: SettingsControl は sealed interface のため、新しいバリアントは網羅的な switch にとってソースレベルの変更です。現在の SDK で再コンパイルする際は FilePath の case を追加してください。
  • TurboismProgressDialog(dev.turboism.sdk.ui.window、0.67.4): Cubism Editor の中央に表示される共有のモードレス進捗ウィンドウです。(title, message) コンストラクタと show、focus、setMessage、setProgress、close を持ち、AutoCloseable を実装します。

コンポーネントが追加された record では、リフレクション上の形、equals、hashCode、toString が変わり、維持された旧 canonical コンストラクタはパラメータ名メタデータを失います。これらの record をリフレクションで調べるコードは対応が必要です。

非契約の公開型

いくつかのクラスは、共有された内部ヘルパーが必要とするために public な SDK クラスとしてコンパイルされていますが、そのクラス自身のドキュメントは、安定プラグイン API 面に属さないと明記しています。現在の例は dev.turboism.sdk.cubism.ActiveReadProjections です。

これらの型を呼び出さず、そのシグネチャを互換性の約束として扱わないでください。生成されたリファレンスに掲載されているのは、それらがリリース済みバイトコードに存在するためであり、理由は 生成された API リファレンス に記載しています。

バージョンと準備状況に関する注意

  • 20 バージョンの網羅: レビュー済みの Cubism Editor バージョンマトリクスは 5.0.00 から 5.3.04 まで の全 20 バージョンをカバーしています。
  • バージョン制約: @CubismEditor は厳密な value 一覧、または両端を含む from/to 範囲と exclude をサポートします。空の宣言は下限を追加しません。権限、プロバイダー、機能、世代の検査は引き続き必要です。各バージョンの行を確認してください。全操作の可用性を保証するものではありません。
  • 0.67 で追加された主要機能群:
    • 統合モデルオブジェクトグラフ(CubismModel、Drawables、Deformers、Parts、Parameters)
    • メッシュモデリングおよびセッション(MeshEditService、MeshEditParticipation、MeshMirrorAxisService)
    • テクスチャアトラス配置および統計(TextureAtlasLayoutService、TextureAtlasEditorSession、TextureAtlasSummary、TextureAtlasLayoutPlanner、TextureAtlasPageSize、TextureAtlasPackingException、TextureAtlasOutline。TextureAtlasPolygonLayoutPlanner は @Incubating)
    • PSD およびクリップマスク操作(PsdClipMaskDocumentSnapshot、PsdEditFile。openInApplication を含む)
    • パラメータ一括転送・変形操作(ParameterBindingBatchOperations、ParameterBindingTransferPlan)
    • 3D モデルインポート連携(ModelObjectCreateRequest 等)
    • 専用プラグイン設定(SettingsRegistry、SettingsContribution、SettingsControl のバリアント Choice、Toggle、Text、FilePath、Note)
    • 進捗ウィンドウ(TurboismProgressDialog)
    • 描画領域ネイティブヒント通知(CanvasHintNotification、turboism.ui.canvas.hint)
  • 各バージョンの詳細な機能境界と差分は 互換性ドキュメント を参照してください。
  • History DTO(HistoryEntry、HistoryChange、HistoryEditContext、HistoryGroup、HistoryOrigin、HistoryTarget)は、範囲が限定された immutable な semantic projection です。host への write 権限を与えることはありません。
  • Fake と static test が証明するのは、それぞれが名指しした layer だけです。
  • Snapshot/query/transaction compatibility surface は現在、unified object graph と併存しています。