diff --git a/README.md b/README.md index fa71387..c2ba5ce 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ Java Attach API でターゲット JVM にインスペクタエージェント - **シーングラフ探索** — Stage と表示中のポップアップを含む JavaFX ウィンドウ・ノードツリーを JSON で取得 - **ノード検索** — タイプ・CSS ID・テキスト・スタイルクラスからノードを検索 +- **祖先・表示状態** — 所属セルまでの祖先パス、実効表示状態と非表示の理由を取得 +- **ウィンドウ操作** — Stage の位置・サイズ・状態の取得と変更、終了要求、ポップアップを閉じる操作 +- **スクロール** — ListView・TableView・ScrollPane・VirtualFlow・Flowless をピクセル/項目インデックスで操作 - **プロパティ読み取り・変更** — テキスト・スタイル・表示状態などのプロパティを動的に操作 - **UI インタラクション** — クリック・フォーカス・キー入力を JavaFX イベントシステム経由で送信 - **ノードハイライト** — 対象ノードを視覚的なオーバーレイでハイライト表示 @@ -19,7 +22,7 @@ Java Attach API でターゲット JVM にインスペクタエージェント ``` MCP Client (AI / OpenCode) └─[STDIO]─► McpServerApplication (Spring Boot) - └─► FxgraphService (@Tool × 13 メソッド) + └─► FxgraphService (@Tool × 21 メソッド) └─► JavaFxAgent (Attach API + TCP socket) └─[TCP NDJSON]─► FxGraphInspectorAgent (注入済みエージェント) └─► SceneGraphInspector @@ -119,15 +122,21 @@ AI エージェントに `skills/fxgraph/SKILL.md` を読み込ませること | `connectApplication` | PID 指定でインスペクタエージェントを準備 | | `disconnectApplication` | PID 指定でインスペクタエージェントを停止 | | `getStages` | 表示中のウィンドウ(Stage・ContextMenu・Tooltip 等)の一覧・種類・サイズ・位置を取得 | +| `getWindowDetails` | Stage・ポップアップの詳細と Stage の最大化・最小化等の状態を取得 | +| `setWindowProperty` | Stage の位置・サイズ・公開プロパティを変更 | +| `closeWindow` | `WINDOW_CLOSE_REQUEST` を送信し、アプリ側のキャンセルを尊重 | +| `closePopup` | 指定した `PopupWindow` を閉じる | | `getScenegraph` | シーングラフのツリー構造を取得(深さ・プロパティ・バウンズ指定可) | -| `getNodeDetails` | 特定ノードの詳細プロパティを取得 | -| `findNodes` | タイプ・CSS ID・テキスト・スタイルクラスからノードを検索 | +| `getNodeDetails` | 特定ノードの詳細、実効表示状態、任意の祖先パスを取得 | +| `findNodes` | タイプ・CSS ID・テキスト・スタイルクラス・実効表示状態からノードを検索 | +| `scrollNode` | ピクセル指定または端へのスクロール | +| `scrollToIndex` | 仮想化コンテナの項目を0始まりのインデックスで表示 | | `setProperty` | ノードのプロパティ値を変更(text・style・visible 等) | | `selectNode` | ノードを視覚的にハイライト(赤枠オーバーレイ)。`nodeId=0` で解除 | | `clickNode` | ボタン・クリック回数を指定してクリック。右クリック・ダブルクリックに対応し、既定は合成入力 | | `activateNode` | `ButtonBase.fire()` でマウス入力なしにボタンを起動 | | `requestFocus` | ノードにキーボードフォーカスを要求 | -| `typeKey` | キー入力イベントを送信(`ENTER`・`TAB` 等のキーコード対応) | +| `typeKey` | 修飾キー付きのキー入力を送信。JavaFX 合成イベントで操作し、OS の入力権限に依存しない | | `takeScreenshot` | ノードまたはシーン全体のスクリーンショットを PNG 保存 | | `captureVideo` | ノードまたは任意のウィンドウシーンを最大30秒の MP4/H.264 で保存 | @@ -185,6 +194,16 @@ $CLI find-nodes --styleClass primary-action --stageId # ノードの詳細プロパティを取得(--filter 必須) $CLI node-details --filter text,visible,disable +$CLI node-details --filter text --ancestors +$CLI find-nodes --type Button --visible-only + +# ウィンドウ操作・仮想化リスト +$CLI window-details --stageId +$CLI set-window-property x 100 --type number +$CLI close-window +$CLI close-popup +$CLI scroll-to-index --index 10 +$CLI scroll-node --dy 500 # プロパティを変更 $CLI set-property text "Hello" @@ -195,16 +214,18 @@ $CLI select-node # クリック・論理起動・フォーカス・キー入力 $CLI click-node -$CLI click-node --mode robot +$CLI click-node --mode synthetic $CLI click-node --button secondary $CLI click-node --clickCount 2 $CLI right-click-node -$CLI double-click-node --mode robot +$CLI double-click-node $CLI activate-node $CLI focus $CLI type-key ENTER +$CLI type-key TAB --modifiers SHIFT +$CLI type-key W --modifiers META -# スクリーンショット +# スクリーンショット(既定は元の解像度、縮小時は scaled と元サイズを返す) $CLI screenshot ./result.png $CLI screenshot ./node.png --nodeId @@ -219,6 +240,8 @@ $CLI capture-video ./node.mp4 --nodeId --durationSeconds 10 > Stage とポップアップのどちらのウィンドウ ID にも使用できます。 CLI の完全なオプション仕様は `skills/fxgraph/references/` を参照してください。 +スクリーンショットの元画像は1辺8192px・総16777216pxまでです。`--no-limit` もこの安全上限内で動作します。 +スクロール後やポップアップを開くたびに `find-nodes` を再実行し、現在のノード ID を取得してください。 ## テスト実行 diff --git a/docs/tools-reference.md b/docs/tools-reference.md index 7b37118..33552c2 100644 --- a/docs/tools-reference.md +++ b/docs/tools-reference.md @@ -10,6 +10,8 @@ FXGraph MCP Serverは、JavaFXアプリケーションのシーングラフを - ノードプロパティの取得と変更 - ノードの選択とハイライト - ノードのクリック・フォーカス要求・キー入力(JavaFXイベントシステム) +- ウィンドウの状態取得・属性変更・閉じる要求とポップアップの終了 +- 仮想リストの画素スクロール・行指定と祖先・実効可視状態の取得 - ノード/シーングラフのスクリーンショット取得 - ノード/任意の JavaFX ウィンドウシーンの短時間 MP4 動画取得 @@ -239,6 +241,7 @@ PIDを指定してJavaFXアプリケーションを検査できる状態にし | pid | integer | はい | Process ID of the target JavaFX application | | nodeId | integer | はい | Node ID (identityHashCode of the JavaFX Node) | | propertyFilter | array | いいえ | List of property names to include (e.g., ["text", "value"]). Omit to get all properties. | +| includeAncestors | boolean | いいえ | `true` で直接の親からシーンルートまでの `ancestors` を追加。既定 `false` | **出力例**: ```json @@ -283,6 +286,10 @@ PIDを指定してJavaFXアプリケーションを検査できる状態にし } ``` +`node.parentId` は直接の包含親の ID です。シーンルートでは省略し、SubScene のルートでは +包含する SubScene の ID を返します。`includeAncestors=true` の `ancestors` は近い親から順に +`nodeId`、`type`、`id`(設定時)、`styleClass`、`bounds` を含みます。 + --- ### 7. findNodes @@ -300,6 +307,18 @@ PIDを指定してJavaFXアプリケーションを検査できる状態にし | text | string | いいえ | Text content to search for (case-sensitive contains match) | | styleClass | string | いいえ | Style class name to filter | | stageId | string | いいえ | Window ID from the stageId field; omit to search all showing windows | +| effectiveVisible | boolean | いいえ | `true` で実効可視ノード、`false` で実効不可視ノードに限定。省略時は両方 | + +`type` は JavaFX `Node` のクラス名(単純名または完全修飾名)と、その親クラスを照合します。 +FXML の非 Node コントローラや `MenuItem` 自体は対象外です。メニューを開いてから +`styleClass=menu-item` またはテキストで描画ノードを検索してください。 +ノード ID はメニューの再表示、アプリの再起動、仮想セルの再利用後に再取得してください。 + +`visible` はノード自身のフラグです。`inScene`、`effectiveVisible`、`clipped`、 +`visibilityReason` により祖先の非表示、透明、ゼロサイズ、クリップ、シーン外を区別します。 +部分クリップは `effectiveVisible=true, clipped=true` です。判定には矩形の境界を使い、 +兄弟や別ウィンドウによる遮蔽、非矩形クリップの穴、OS のヒットテストは判定しません。 +検索範囲は表示中のウィンドウに所属するノードで、切り離されたノードを検索するものではありません。 **出力例**: ```json @@ -414,14 +433,14 @@ PIDを指定してJavaFXアプリケーションを検査できる状態にし 指定したノードの中央へクリックジェスチャーを送ります。 -**説明**: 既定では `MOUSE_PRESSED`、`MOUSE_RELEASED`、`MOUSE_CLICKED` の完全な合成ジェスチャーを送り、システムポインターを移動せず、ウィンドウへのフォーカスも要求しません。`mode=robot` を明示すると JavaFX `Robot` がウィンドウへフォーカスを要求し、マウスをノード中央へ移動して指定したボタンで1回または2回クリックします。明示した `Robot` が利用できない場合は合成ジェスチャーへ自動的にフォールバックします。ノードまたは祖先が非表示の場合、disabled の場合、またはサイズがゼロの場合はエラーを返します。 +**説明**: JavaFX 内で `MOUSE_PRESSED`、`MOUSE_RELEASED`、`MOUSE_CLICKED` の完全な合成ジェスチャーを送り、システムポインターを移動せず、ウィンドウへのフォーカスも要求しません。OS の入力権限は不要です。ノードまたは祖先が非表示の場合、disabled の場合、またはサイズがゼロの場合はエラーを返します。 **入力パラメータ**: | パラメータ | 型 | 必須 | 説明 | |-----------|-----|------|------| | pid | integer | はい | Process ID of the target JavaFX application | | nodeId | integer | はい | Node ID | -| mode | string | いいえ | `synthetic`(既定)または `robot` | +| mode | string | いいえ | `synthetic` のみ。省略可 | | button | string | いいえ | `primary`(既定)、`secondary`(右)、`middle` | | clickCount | integer | いいえ | `1`(既定)または `2`(ダブルクリック) | @@ -438,7 +457,16 @@ PIDを指定してJavaFXアプリケーションを検査できる状態にし 合成ダブルクリックは回数1、2の完全なジェスチャーを順に送ります。右クリックは `CONTEXT_MENU_REQUESTED` も送り、標準コンテキストメニューを開きます。メニューやアプリのハンドラによってフォーカスが変わる場合があります。独自メニューを開く場合は context-menu request を consume して既定メニューの表示を抑制してください。 -Robot のダブルクリック認識は OS の時間・位置条件と直前のクリックに依存します。Robot から合成入力へフォールバックした場合は、`mode` が `synthetic` となり、`fallbackReason` が追加されます。ボタン・クリック回数は維持されます。 +標準サブメニューの描画ノードでは `MOUSE_ENTERED` も送り、サブメニューを開きます。 +マウスイベントの `isSynthesized` はタッチ由来を意味するため `false` です。 +クリックまたは起動ハンドラが `showAndWait()` のネストしたイベントループに入ると、 +`handlerPending=true` を返します。これは配送済みでハンドラが処理中であることを示します。 +表示されたダイアログや後続状態を再検索して確認し、同じ操作を繰り返さないでください。 + +旧 `mode=robot` を含む未対応モードは入力を送る前にエラーを返します。既存の呼び出しでは `mode` を省略するか、`synthetic` を指定してください。合成クリックは指定ノードへのイベント配送であり、OS のポインター移動やネイティブのヒットテストを再現しません。 + +旧 Robot モードにはポインター移動やウィンドウのフォーカス変更がありました。現在は削除済みです。 +旧環境の IMK/IMKCFRunLoopWakeUpReliable ログだけで入力の成否を判断せず、アプリの状態を確認してください。 メニュー項目の有効・無効は `getNodeDetails` の `node.disabled` で確認できます。無効時だけ `true` を出力し、省略時は `false` です。標準メニュー項目の状態は描画ノードの `disable` プロパティだけでは判断できないため、MenuItem の無効状態も反映します。 @@ -448,7 +476,7 @@ Robot のダブルクリック認識は OS の時間・位置条件と直前の 指定した `ButtonBase` をマウス入力なしに論理的に起動します。 -**説明**: `ButtonBase.fire()` を呼び出します。マウスハンドラやヒットテストを検証するときは `clickNode` を使用してください。 +**説明**: `ButtonBase.fire()` を呼び出します。マウスハンドラやヒットテストを検証するときは `clickNode` を使用してください。`showAndWait()` を開くハンドラでは `handlerPending=true` の意味は `clickNode` と同じです。 **入力パラメータ**: | パラメータ | 型 | 必須 | 説明 | @@ -490,25 +518,37 @@ Robot のダブルクリック認識は OS の時間・位置条件と直前の ### 13. typeKey -キー入力イベントを送信します。 +修飾キー付きの JavaFX 合成キー入力を送信します。OS の入力権限は不要です。 -**説明**: Type a key into a JavaFX node using JavaFX Event System. If nodeId is omitted, the currently focused node is used. +合成入力はキーの押下・解放と、文字入力時の `KEY_TYPED` を送信します。Control・Alt・Meta を含む +ショートカットでは文字を挿入しません。対象ノードに JavaFX 内のフォーカスを要求してから +イベントを送ります。ウィンドウを前面にする必要はありません。 **入力パラメータ**: | パラメータ | 型 | 必須 | 説明 | |-----------|-----|------|------| | pid | integer | はい | Process ID of the target JavaFX application | | key | string | はい | Key text or key code name (e.g. 'a', 'ENTER') | -| nodeId | integer | いいえ | Target node ID (optional, defaults to focused node) | +| nodeId | integer | いいえ | 対象ノード。省略時はフォーカスのあるシーン | +| modifiers | string[] | いいえ | `SHIFT`、`CTRL`/`CONTROL`、`ALT`、`CMD`/`META`。複数指定可、大文字小文字不問 | +| mode | string | いいえ | `synthetic` のみ。省略可 | **出力例**: ```json { "success": true, - "typed": true + "typed": true, + "mode": "synthetic" } ``` +単一文字は Unicode を含め指定した文字を送信できます。`CMD`/`META` は JavaFX イベントの +Meta フラグを設定します。Shift+Tab やアプリのイベントハンドラ・Scene accelerator は対象ですが、 +OS が処理する Cmd+Q/Cmd+W などのネイティブショートカットは送信しません。 +成功応答はイベント配送を示すため、ショートカットの実行結果は対象アプリで確認してください。 +アプリ側の処理で JVM が終了すると、応答前に接続が閉じる場合があります。 +旧 `mode=robot` を含む未対応モードは入力やフォーカス変更の前にエラーを返します。 + --- ### 14. takeScreenshot @@ -525,8 +565,8 @@ Robot のダブルクリック認識は OS の時間・位置条件と直前の | nodeId | integer | いいえ | Target node ID (optional; if omitted, captures full scene graph) | | stageId | string | いいえ | Window ID from the stageId field; first available Stage when omitted | | savePath | string | はい | Path to save the PNG screenshot | -| maxWidth | integer | いいえ | Maximum screenshot width (default: 1280) | -| maxHeight | integer | いいえ | Maximum screenshot height (default: 720) | +| maxWidth | integer | いいえ | 最大幅。省略または `0` は幅の制限なし。正の整数で縮小を指定 | +| maxHeight | integer | いいえ | 最大高さ。省略または `0` は高さの制限なし。正の整数で縮小を指定 | **出力例**: ```json @@ -536,6 +576,9 @@ Robot のダブルクリック認識は OS の時間・位置条件と直前の "savedPath": "/tmp/fxgraph/screenshot.png", "width": 800, "height": 600, + "sourceWidth": 1600, + "sourceHeight": 1200, + "scaled": true, "targetType": "scenegraph", "targetId": "123456789" } @@ -544,6 +587,13 @@ Robot のダブルクリック認識は OS の時間・位置条件と直前の `Scene.snapshot` は1ウィンドウ単位です。所有 Stage とポップアップを合成した画像が必要な場合は、 OS の画面キャプチャを使用してください。 +既定では元の画素サイズを保持します。縮小時も縦横比を保持し、拡大はしません。 +`sourceWidth` / `sourceHeight` は元画像、`width` / `height` は保存画像、`scaled` は縮小の有無です。 +負数や整数以外の上限は拒否します。元画像が一辺 8192px または総画素数 16,777,216 を超える場合は、 +画像を確保する前に拒否します。縮小指定でもこの安全上限は適用されるため、小さい対象ノードを選択してください。 +安全上限の計算には小数座標による画像境界の外向きの切り上げも含みます。 +CLI の `--no-limit` は両方の上限を `0` にし、`--maxWidth` / `--maxHeight` と併用できません。 + --- ### 15. captureVideo @@ -587,6 +637,95 @@ OS の画面キャプチャを使用してください。 --- +### 16. getWindowDetails + +`getStages` で取得したウィンドウの状態を取得します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| stageId | string | はい | ウィンドウ ID | + +`stageId`、`windowType`、`x`、`y`、`width`、`height`、`opacity`、`focused`、`showing`、 +`rootNodeId` を返します。Stage では `title`、`maximized`、`iconified`、`alwaysOnTop`、 +`resizable`、PopupWindow では `ownerWindowId` も返します。 + +### 17. setWindowProperty + +Stage のプロパティを変更します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| stageId | string | はい | Stage の ID | +| propertyName | string | はい | `x`、`y`、`width`、`height`、`opacity`、`title`、`maximized`、`iconified`、`alwaysOnTop`、`resizable` | +| value | string | はい | 設定値 | +| valueType | string | いいえ | `number`、`boolean`、`string`。省略時はプロパティから決定 | + +位置とサイズは有限数、サイズは正数、opacity は 0〜1、boolean は `true` / `false` のみです。 +不正値と未対応プロパティは変更前に拒否します。`oldValue` と `newValue` を返します。 +OS が状態を非同期に反映する場合があるため、最終状態は `getWindowDetails` で再確認してください。 + +### 18. closeWindow + +指定ウィンドウへ `WINDOW_CLOSE_REQUEST` を配送します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| stageId | string | はい | ウィンドウ ID | + +`closeRequested=true` と実際の `closed` を返します。閉じるハンドラがイベントを consume した場合は +`closed=false` です。確認ダイアログの `showAndWait()` が始まると `handlerPending=true` を返すので、 +ダイアログを操作してからウィンドウの有無を再確認してください。JVM が終了すると応答前に接続が閉じる場合があります。 +OS の Cmd+W を送らずに、JavaFX の閉じる要求とライフサイクルを扱えます。 + +### 19. closePopup + +指定した表示中の `PopupWindow` を `hide()` で閉じます。Stage は拒否します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| stageId | string | はい | ポップアップ ID | + +`closed` を返します。シーン内の独自オーバーレイはウィンドウではありません。 +例えば AtlantaFX `ModalPane` は `findNodes(type="ModalPane")` の後で `setProperty` に +`propertyName="display", value="false", valueType="boolean"` を指定する回避策が使えます。 +独自コンポーネントは `getNodeDetails` で writable な閉じるプロパティやボタンを確認してください。 + +### 20. scrollNode + +スクロール対象を画素差分または端へ移動します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| nodeId | integer | はい | スクロール対象の ID | +| dx | number | いいえ | 横方向の画素差分。正値は右 | +| dy | number | いいえ | 縦方向の画素差分。正値は下 | +| align | string | いいえ | `top`、`bottom`、`left`、`right`。dx/dy と併用不可 | + +dx/dy の少なくとも一方、または align が必要です。ListView、TableView、ScrollPane、JavaFX の +VirtualFlow、Flowless の VirtualFlow、およびそれを包む VirtualizedScrollPane を扱います。 +JavaFX VirtualFlow の端指定は向きに合うものだけを受け付けます。 + +### 21. scrollToIndex + +仮想化されたリストの行を表示範囲へ移動します。 + +| パラメータ | 型 | 必須 | 説明 | +|-----------|-----|------|------| +| pid | integer | はい | 対象 JVM の PID | +| nodeId | integer | はい | ListView、TableView、JavaFX/Flowless VirtualFlow、または Flowless VirtualizedScrollPane の ID | +| index | integer | はい | 0 から始まる行番号。範囲外は拒否 | + +両スクロールコマンドは `scrolled=true, refreshRequired=true` を返します。 +仮想セルは再利用されるので、操作後に `findNodes` で対象行と ID を取り直してください。 +Flowless は対象アプリの公開 API を使い、Agent の本番依存には追加していません。 + +--- + ## データモデル ### JavaFxApplication @@ -623,7 +762,10 @@ OS の画面キャプチャを使用してください。 ```json { "nodeId": 987654321, - "type": "Button" + "type": "Button", + "inScene": true, + "effectiveVisible": true, + "clipped": false } ``` @@ -633,6 +775,11 @@ OS の画面キャプチャを使用してください。 > - `styleClass`: 空でない場合のみ出力 > - `bounds`: `includeBounds=true` の場合のみ出力 > - `children`: 子ノードがある場合のみ出力 +> - `parentId`: 包含親がある場合のみ出力 +> - `inScene`、`effectiveVisible`、`clipped`: 実効可視状態を出力 +> - `visibilityReason`: 実効不可視の理由がある場合のみ出力 + +以下の例は各オプションに関係するフィールドのみを抜粋しています。 **CSS IDが設定されたノード:** ```json diff --git a/fxgraph-agent/README.md b/fxgraph-agent/README.md index e42bad6..c978226 100644 --- a/fxgraph-agent/README.md +++ b/fxgraph-agent/README.md @@ -30,6 +30,10 @@ Java Instrumentation API を使用してターゲット JVM に対してアタ | `agent.inspector` | `FxGraphInspectorAgent` | Java Instrumentation API エントリポイント。TCP サーバーを起動しコマンドを受け付ける | | `agent.inspector` | `SceneGraphInspector` | シーングラフのノード取得・プロパティ操作・スクリーンショット・短時間動画等の実装 | | `agent.inspector` | `NodeHierarchy` | 公開 JavaFX API から直接の子ノードを不変スナップショットとして取得するユーティリティ | +| `agent.inspector` | `NodeVisibility` | 祖先・透明度・クリップ・シーン範囲から実効表示状態を判定 | +| `agent.inspector` | `WindowOperations` | 公開 Stage プロパティの検証と読み書き | +| `agent.inspector` | `ScrollOperations` | 標準コントロールと Flowless の公開 API によるスクロール | +| `agent.inspector` | `KeyInput` | キーコード・修飾キーの検証とJavaFX 合成入力の実装 | | `agent.protocol` | `AgentCommand` / `AgentResponse` | エージェント独立の JSON 通信プロトコル定義 (fxgraph-core とは別コピー) | > **注記:** `agent.protocol` は `fxgraph-core` サブプロジェクトのプロトコル定義と同一内容の独立コピーです。 @@ -74,3 +78,4 @@ Can-Redefine-Classes: true | `javafx-controls/graphics/base` | compileOnly | ターゲット JVM が既に持つ JavaFX API | | `testfx-junit5` | testImplementation | JavaFX UI テスト | | `openjfx-monocle` | testImplementation | ヘッドレステスト用レンダリング | +| `flowless` | testImplementation | 対象側の Flowless と VirtualizedScrollPane の実動作検証。Agent JAR には同梱しない | diff --git a/fxgraph-agent/build.gradle b/fxgraph-agent/build.gradle index f2d8896..07cfaa6 100644 --- a/fxgraph-agent/build.gradle +++ b/fxgraph-agent/build.gradle @@ -32,6 +32,7 @@ dependencies { // Test dependencies testImplementation libs.assertj.core + testImplementation libs.flowless testImplementation 'org.testfx:testfx-junit5:4.0.18' testImplementation 'org.testfx:openjfx-monocle:21.0.2' testImplementation "org.openjfx:javafx-controls:${libs.versions.javafx.get()}:${javafxPlatform}" diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/FxGraphInspectorAgent.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/FxGraphInspectorAgent.java index f5262ca..f355a96 100644 --- a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/FxGraphInspectorAgent.java +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/FxGraphInspectorAgent.java @@ -117,6 +117,10 @@ private static AgentResponse processCommand(AgentCommand command, SceneGraphInsp return switch (command.getCommand()) { case PING -> AgentResponse.success("pong"); case GET_STAGES -> inspector.getStages(); + case GET_WINDOW_DETAILS -> inspector.getWindowDetails(command.getParams()); + case SET_WINDOW_PROPERTY -> inspector.setWindowProperty(command.getParams()); + case CLOSE_WINDOW -> inspector.closeWindow(command.getParams()); + case CLOSE_POPUP -> inspector.closePopup(command.getParams()); case GET_SCENEGRAPH -> inspector.getScenegraph(command.getParams()); case GET_NODE_DETAILS -> inspector.getNodeDetails(command.getParams()); case FIND_NODES -> inspector.findNodes(command.getParams()); @@ -126,6 +130,8 @@ private static AgentResponse processCommand(AgentCommand command, SceneGraphInsp case ACTIVATE_NODE -> inspector.activateNode(command.getParams()); case REQUEST_FOCUS -> inspector.requestFocus(command.getParams()); case TYPE_KEY -> inspector.typeKey(command.getParams()); + case SCROLL_NODE -> inspector.scrollNode(command.getParams()); + case SCROLL_TO_INDEX -> inspector.scrollToIndex(command.getParams()); case TAKE_SCREENSHOT -> inspector.takeScreenshot(command.getParams()); case CAPTURE_VIDEO -> inspector.captureVideo(command.getParams()); case SHUTDOWN -> { diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/KeyInput.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/KeyInput.java new file mode 100644 index 0000000..24401b6 --- /dev/null +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/KeyInput.java @@ -0,0 +1,114 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.scene.Node; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyEvent; + +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** Parses and dispatches JavaFX key gestures. */ +final class KeyInput { + private KeyInput() {} + + record Stroke(KeyCode code, String character, List modifiers) { + boolean has(KeyCode modifier) { + return modifiers.contains(modifier); + } + + KeyEvent event(javafx.event.EventType type) { + return new KeyEvent(type, type == KeyEvent.KEY_TYPED ? character : KeyEvent.CHAR_UNDEFINED, + type == KeyEvent.KEY_TYPED ? "" : code.getName(), code, + has(KeyCode.SHIFT), has(KeyCode.CONTROL), has(KeyCode.ALT), has(KeyCode.META)); + } + } + + static Stroke parse(Map params) { + if (!(params.get("key") instanceof String key) || key.isEmpty()) { + throw new IllegalArgumentException("key is required"); + } + var modifiers = EnumSet.noneOf(KeyCode.class); + if (params.get("modifiers") != null) { + if (!(params.get("modifiers") instanceof List values)) { + throw new IllegalArgumentException("modifiers must be an array"); + } + for (var value : values) { + var modifier = switch (String.valueOf(value).trim().toUpperCase(Locale.ROOT)) { + case "SHIFT" -> KeyCode.SHIFT; + case "CTRL", "CONTROL" -> KeyCode.CONTROL; + case "ALT" -> KeyCode.ALT; + case "CMD", "META" -> KeyCode.META; + default -> throw new IllegalArgumentException("Unsupported modifier: " + value + ". Expected SHIFT, CTRL/CONTROL, ALT, or CMD/META"); + }; + modifiers.add(modifier); + } + } + var code = keyCode(key); + if (code == KeyCode.UNDEFINED && key.codePointCount(0, key.length()) != 1) { + throw new IllegalArgumentException("Unsupported key: " + key); + } + var character = key.codePointCount(0, key.length()) == 1 ? key : character(code); + if (modifiers.contains(KeyCode.SHIFT)) { + character = character.toUpperCase(Locale.ROOT); + } + if (modifiers.contains(KeyCode.CONTROL) || modifiers.contains(KeyCode.ALT) || modifiers.contains(KeyCode.META)) { + character = ""; + } + return new Stroke(code, character, List.copyOf(modifiers)); + } + + private static KeyCode keyCode(String key) { + try { + return KeyCode.valueOf(key.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException ignored) { + if (key.codePointCount(0, key.length()) != 1) { + throw new IllegalArgumentException("Unsupported key: " + key); + } + var code = KeyCode.getKeyCode(key); + return code != null ? code : switch (key) { + case " " -> KeyCode.SPACE; + case "," -> KeyCode.COMMA; + case "." -> KeyCode.PERIOD; + case "/" -> KeyCode.SLASH; + case ";" -> KeyCode.SEMICOLON; + case "=" -> KeyCode.EQUALS; + case "-" -> KeyCode.MINUS; + case "[" -> KeyCode.OPEN_BRACKET; + case "]" -> KeyCode.CLOSE_BRACKET; + case "\\" -> KeyCode.BACK_SLASH; + case "'" -> KeyCode.QUOTE; + case "`" -> KeyCode.BACK_QUOTE; + default -> KeyCode.UNDEFINED; + }; + } + } + + private static String character(KeyCode code) { + if (code.isLetterKey()) return code.getName().toLowerCase(Locale.ROOT); + if (code.isDigitKey()) return code.name().substring(code.name().length() - 1); + return switch (code) { + case SPACE -> " "; + case COMMA -> ","; + case PERIOD -> "."; + case SLASH -> "/"; + case SEMICOLON -> ";"; + case EQUALS -> "="; + case MINUS -> "-"; + case OPEN_BRACKET -> "["; + case CLOSE_BRACKET -> "]"; + case BACK_SLASH -> "\\"; + case QUOTE -> "'"; + case BACK_QUOTE -> "`"; + default -> ""; + }; + } + + static void synthetic(Node target, Stroke stroke) { + target.fireEvent(stroke.event(KeyEvent.KEY_PRESSED)); + if (!stroke.character().isEmpty()) target.fireEvent(stroke.event(KeyEvent.KEY_TYPED)); + target.fireEvent(stroke.event(KeyEvent.KEY_RELEASED)); + } + +} diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeHierarchy.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeHierarchy.java index 0b10fb3..182f2dd 100644 --- a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeHierarchy.java +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeHierarchy.java @@ -5,6 +5,7 @@ import javafx.scene.SubScene; import java.util.List; +import java.util.ArrayList; /** * Describes direct containment relationships in a JavaFX scene graph. @@ -33,4 +34,29 @@ static List directChildren(Node node) { default -> List.of(); }; } + + /** Returns the containment path from root to target, including SubScene boundaries. */ + static List pathTo(Node root, Node target) { + var path = new ArrayList(); + return collectPath(root, target, path) ? List.copyOf(path) : List.of(); + } + + /** Returns the containing node, including the SubScene that owns a nested root. */ + static Node parentOf(Node node) { + if (node.getParent() != null) return node.getParent(); + var scene = node.getScene(); + if (scene == null || scene.getRoot() == node) return null; + var path = pathTo(scene.getRoot(), node); + return path.size() > 1 ? path.get(path.size() - 2) : null; + } + + private static boolean collectPath(Node node, Node target, List path) { + path.add(node); + if (node == target) return true; + for (var child : directChildren(node)) { + if (collectPath(child, target, path)) return true; + } + path.removeLast(); + return false; + } } diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeVisibility.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeVisibility.java new file mode 100644 index 0000000..9fe3256 --- /dev/null +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeVisibility.java @@ -0,0 +1,75 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.geometry.BoundingBox; +import javafx.geometry.Bounds; +import javafx.scene.Node; +import javafx.scene.SubScene; +import javafx.scene.layout.Region; +import javafx.stage.Stage; + +import java.util.Map; + +/** Estimates visibility from scene membership, ancestor state, and bounding-box clipping. */ +final class NodeVisibility { + private NodeVisibility() {} + + record State(boolean inScene, boolean effectiveVisible, boolean clipped, String reason) { + void addTo(Map result) { + result.put("inScene", inScene); + result.put("effectiveVisible", effectiveVisible); + result.put("clipped", clipped); + if (reason != null) result.put("visibilityReason", reason); + } + } + + static State evaluate(Node node) { + var scene = node.getScene(); + if (scene == null) return new State(false, false, false, "not in scene"); + var window = scene.getWindow(); + if (window == null || !window.isShowing()) { + return new State(true, false, false, "window not showing"); + } + if (window.getOpacity() <= 0) return new State(true, false, false, "window transparent"); + if (window instanceof Stage stage && stage.isIconified()) return new State(true, false, false, "window iconified"); + for (var current = node; current != null; current = NodeHierarchy.parentOf(current)) { + if (!current.isVisible()) { + return new State(true, false, false, current == node ? "node invisible" : "ancestor invisible"); + } + if (current.getOpacity() <= 0) { + return new State(true, false, false, current == node ? "node transparent" : "ancestor transparent"); + } + } + var bounds = node.getBoundsInLocal(); + if (bounds.getWidth() <= 0 || bounds.getHeight() <= 0 + || node instanceof Region region && (region.getWidth() <= 0 || region.getHeight() <= 0)) { + return new State(true, false, false, "zero-size"); + } + var visibleBounds = node.localToScreen(bounds); + if (visibleBounds == null) return new State(true, false, false, "not attached to showing window"); + var original = visibleBounds; + for (var current = node; current != null; current = NodeHierarchy.parentOf(current)) { + if (current.getClip() != null) { + visibleBounds = intersect(visibleBounds, current.localToScreen(current.getClip().getBoundsInParent())); + } + if (current instanceof SubScene) { + visibleBounds = intersect(visibleBounds, current.localToScreen(current.getLayoutBounds())); + } + if (visibleBounds == null) return new State(true, false, true, "clipped"); + } + var viewport = new BoundingBox(window.getX() + scene.getX(), window.getY() + scene.getY(), + scene.getWidth(), scene.getHeight()); + visibleBounds = intersect(visibleBounds, viewport); + if (visibleBounds == null) return new State(true, false, true, "outside scene viewport"); + var clipped = visibleBounds.getWidth() < original.getWidth() || visibleBounds.getHeight() < original.getHeight(); + return new State(true, true, clipped, null); + } + + private static Bounds intersect(Bounds first, Bounds second) { + if (first == null || second == null) return null; + var x = Math.max(first.getMinX(), second.getMinX()); + var y = Math.max(first.getMinY(), second.getMinY()); + var width = Math.min(first.getMaxX(), second.getMaxX()) - x; + var height = Math.min(first.getMaxY(), second.getMaxY()) - y; + return width > 0 && height > 0 ? new BoundingBox(x, y, width, height) : null; + } +} diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspector.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspector.java index 38d7687..e2b1380 100644 --- a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspector.java +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspector.java @@ -6,6 +6,7 @@ import javafx.beans.value.WritableValue; import javafx.collections.ObservableList; import javafx.event.EventType; +import javafx.event.Event; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.Node; @@ -14,22 +15,22 @@ import javafx.scene.SnapshotParameters; import javafx.scene.control.ButtonBase; import javafx.scene.control.MenuItem; +import javafx.scene.control.Menu; import javafx.scene.image.PixelReader; import javafx.scene.image.WritableImage; import javafx.scene.image.WritablePixelFormat; import javafx.scene.input.ContextMenuEvent; -import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.PickResult; import javafx.scene.layout.Region; import javafx.scene.paint.Color; -import javafx.scene.robot.Robot; import javafx.scene.shape.Rectangle; import javafx.scene.shape.StrokeType; import javafx.stage.PopupWindow; import javafx.stage.Stage; import javafx.stage.Window; +import javafx.stage.WindowEvent; import org.jcodec.api.awt.AWTSequenceEncoder; import javax.imageio.ImageIO; @@ -55,8 +56,10 @@ public class SceneGraphInspector { private static final String SPACE_CHAR = " "; - private static final int DEFAULT_SCREENSHOT_MAX_WIDTH = 1280; - private static final int DEFAULT_SCREENSHOT_MAX_HEIGHT = 720; + private static final int DEFAULT_VIDEO_MAX_WIDTH = 1280; + private static final int DEFAULT_VIDEO_MAX_HEIGHT = 720; + private static final int MAX_SNAPSHOT_DIMENSION = 8192; + private static final long MAX_SNAPSHOT_PIXELS = 16_777_216; private static final int DEFAULT_VIDEO_DURATION_SECONDS = 5; private static final int MAX_VIDEO_DURATION_SECONDS = 30; private static final int DEFAULT_VIDEO_FRAMES_PER_SECOND = 10; @@ -65,21 +68,6 @@ public class SceneGraphInspector { /** Tracks highlighted overlay nodes so they can be removed. */ private Node currentHighlight; private Parent currentHighlightParent; - private final RobotClicker robotClicker; - - public SceneGraphInspector() { - this((point, button, clickCount) -> { - var robot = new Robot(); - robot.mouseMove(point); - for (var count = 0; count < clickCount; count++) { - robot.mouseClick(button); - } - }); - } - - SceneGraphInspector(RobotClicker robotClicker) { - this.robotClicker = Objects.requireNonNull(robotClicker); - } // ============================================= // GET_STAGES @@ -94,6 +82,81 @@ public AgentResponse getStages() { } } + /** Returns geometry and public state of a showing Stage or PopupWindow identified by stageId. */ + public AgentResponse getWindowDetails(Map params) { + try { + return AgentResponse.success(runOnFxThread(() -> WindowOperations.details(WindowOperations.requireWindow(params)))); + } catch (Exception e) { + return AgentResponse.error("Failed to get window details: " + describeFailure(e)); + } + } + + /** Sets a supported Stage property after validating its type and numeric range. */ + public AgentResponse setWindowProperty(Map params) { + try { + return AgentResponse.success(runOnFxThread(() -> WindowOperations.setProperty(params))); + } catch (Exception e) { + return AgentResponse.error("Failed to set window property: " + describeFailure(e)); + } + } + + /** Fires WINDOW_CLOSE_REQUEST. A consumed request leaves the window open. */ + public AgentResponse closeWindow(Map params) { + try { + var window = runOnFxThread(() -> WindowOperations.requireWindow(params)); + var closed = new java.util.concurrent.atomic.AtomicBoolean(); + var outcome = runInteraction(() -> { + Event.fireEvent(window, new WindowEvent(window, WindowEvent.WINDOW_CLOSE_REQUEST)); + closed.set(!window.isShowing()); + return null; + }); + return AgentResponse.success(Map.of("stageId", windowId(window), "closeRequested", true, + "closed", closed.get(), "handlerPending", outcome.handlerPending())); + } catch (Exception e) { + return AgentResponse.error("Failed to close window: " + describeFailure(e)); + } + } + + /** Hides the selected PopupWindow, rejecting ordinary Stages. Embedded overlays are not windows. */ + public AgentResponse closePopup(Map params) { + try { + return runOnFxThread(() -> { + var window = WindowOperations.requireWindow(params); + if (!(window instanceof PopupWindow popup)) return AgentResponse.error("Window is not a PopupWindow: " + windowId(window)); + popup.hide(); + return AgentResponse.success(Map.of("stageId", windowId(window), "closed", !popup.isShowing())); + }); + } catch (Exception e) { + return AgentResponse.error("Failed to close popup: " + describeFailure(e)); + } + } + + /** Scrolls a supported container by pixels or to an edge; positive deltas move down/right. */ + public AgentResponse scrollNode(Map params) { + return scroll(params, false); + } + + /** Reveals a zero-based item in a ListView, TableView, or supported VirtualFlow. */ + public AgentResponse scrollToIndex(Map params) { + return scroll(params, true); + } + + private AgentResponse scroll(Map params, boolean byIndex) { + try { + if (params == null || !(params.get("nodeId") instanceof Number id)) return AgentResponse.error("nodeId is required"); + return runOnFxThread(() -> { + var node = findNodeById(id.intValue()); + if (node == null) return AgentResponse.error("Node not found: " + id); + var visibility = NodeVisibility.evaluate(node); + if (!visibility.effectiveVisible()) return AgentResponse.error("Node is not effectively visible: " + id + " (" + visibility.reason() + ")"); + if (node.isDisabled()) return AgentResponse.error("Node is disabled: " + id); + return AgentResponse.success(byIndex ? ScrollOperations.scrollToIndex(node, params) : ScrollOperations.scroll(node, params)); + }); + } catch (Exception e) { + return AgentResponse.error("Failed to scroll node: " + describeFailure(e)); + } + } + // ============================================= // FIND_NODES // ============================================= @@ -109,6 +172,9 @@ public AgentResponse findNodes(Map params) { List> results = runOnFxThread(() -> searchNodes(typeFilter, idFilter, textFilter, styleClassFilter, stageIdFilter)); + if (params != null && params.get("effectiveVisible") instanceof Boolean visible) { + results = results.stream().filter(info -> visible.equals(info.get("effectiveVisible"))).toList(); + } return AgentResponse.success(results); } catch (Exception e) { return AgentResponse.error("Failed to find nodes: " + e.getMessage()); @@ -170,6 +236,9 @@ private void searchNodeRecursive(Node node, String typeFilter, String idFilter, String text = getTextContent(node); if (text != null) info.put("text", text); info.put("visible", node.isVisible()); + NodeVisibility.evaluate(node).addTo(info); + var parent = NodeHierarchy.parentOf(node); + if (parent != null) info.put("parentId", System.identityHashCode(parent)); results.add(info); } @@ -298,7 +367,8 @@ public AgentResponse getNodeDetails(Map params) { List propertyFilter = params.get("propertyFilter") != null ? (List) params.get("propertyFilter") : null; - Map result = runOnFxThread(() -> collectNodeDetails(nodeId, propertyFilter)); + var includeAncestors = Boolean.TRUE.equals(params.get("includeAncestors")); + Map result = runOnFxThread(() -> collectNodeDetails(nodeId, propertyFilter, includeAncestors)); if (result == null) { return AgentResponse.error("Node not found: " + nodeId); } @@ -308,7 +378,7 @@ public AgentResponse getNodeDetails(Map params) { } } - private Map collectNodeDetails(int nodeId, List propertyFilter) { + private Map collectNodeDetails(int nodeId, List propertyFilter, boolean includeAncestors) { Node node = findNodeById(nodeId); if (node == null) return null; @@ -334,6 +404,17 @@ private Map collectNodeDetails(int nodeId, List property } result.put("children", childrenSummary); + if (includeAncestors) { + var path = NodeHierarchy.pathTo(node.getScene().getRoot(), node); + var ancestors = new ArrayList>(); + for (var index = path.size() - 2; index >= 0; index--) { + ancestors.add(serializeNodeLightweight(path.get(index), 0, 0, + false, null, false, true, + index > 0 ? System.identityHashCode(path.get(index - 1)) : null)); + } + result.put("ancestors", ancestors); + } + return result; } @@ -468,17 +549,14 @@ private Boolean doSelectNode(int nodeId, boolean showBounds) { // ============================================= /** - * Clicks a node through JavaFX Robot or a complete synthetic mouse gesture. + * Clicks a node through a complete JavaFX synthetic mouse gesture. * - *

The optional {@code mode} parameter accepts {@code synthetic} or {@code robot} and - * defaults to {@code synthetic}, which does not move the system pointer or request window focus. - * Explicit Robot failures automatically fall back to synthetic input, with the effective mode - * and failure reason included in the successful response. + *

The optional {@code mode} parameter accepts only {@code synthetic}, which does not move + * the system pointer or request window focus. Other modes are rejected before sending input. * *

{@code button} accepts {@code primary} (default), {@code secondary}, or {@code middle}. * {@code clickCount} accepts 1 (default) or 2. Synthetic double clicks send two complete gestures * with increasing counts. Secondary synthetic clicks also request a context menu. - * Robot click counts depend on native multi-click recognition. * * @param params command parameters with {@code nodeId}, optional {@code mode}, {@code button}, * and integer {@code clickCount} @@ -490,29 +568,22 @@ public AgentResponse clickNode(Map params) { return AgentResponse.error("nodeId is required"); } var nodeId = ((Number) params.get("nodeId")).intValue(); - var mode = ClickMode.from(params.get("mode")); + requireSyntheticMode(params); var options = ClickOptions.from(params); - var outcome = runOnFxThread(() -> doClickNode(nodeId, mode, options)); + var outcome = runInteraction(() -> doClickNode(nodeId, options)); if (outcome.error() != null) { return AgentResponse.error(outcome.error()); } - if (outcome.mode() == ClickMode.ROBOT) { - // Robot posts platform input asynchronously; this barrier lets queued events run - // before the command reports success to a client that may immediately inspect state. - runOnFxThread(() -> null); - } var data = new LinkedHashMap(); data.put("clicked", true); - data.put("mode", outcome.mode().value()); + data.put("mode", "synthetic"); data.put("button", options.button().name().toLowerCase(Locale.ROOT)); data.put("clickCount", options.clickCount()); - if (outcome.fallbackReason() != null) { - data.put("fallbackReason", outcome.fallbackReason()); - } + if (outcome.handlerPending()) data.put("handlerPending", true); return AgentResponse.success(data); } catch (Exception e) { - return AgentResponse.error("Failed to click node: " + e.getMessage()); + return AgentResponse.error("Failed to click node: " + describeFailure(e)); } } @@ -532,13 +603,13 @@ public AgentResponse activateNode(Map params) { } var nodeId = ((Number) params.get("nodeId")).intValue(); - var error = runOnFxThread(() -> doActivateNode(nodeId)); - if (error != null) { - return AgentResponse.error(error); + var outcome = runInteraction(() -> doActivateNode(nodeId)); + if (outcome.error() != null) { + return AgentResponse.error(outcome.error()); } - return AgentResponse.success(Map.of("activated", true)); + return AgentResponse.success(Map.of("activated", true, "handlerPending", outcome.handlerPending())); } catch (Exception e) { - return AgentResponse.error("Failed to activate node: " + e.getMessage()); + return AgentResponse.error("Failed to activate node: " + describeFailure(e)); } } @@ -559,19 +630,40 @@ public AgentResponse requestFocus(Map params) { } } + /** + * Sends a key gesture to the selected node or focused scene. + * Input is dispatched inside JavaFX without native input or OS permission requirements. + * + * @param params key, optional nodeId, modifier array, and optional synthetic mode + * @return input submission result; successful submission does not guarantee shortcut execution + */ public AgentResponse typeKey(Map params) { try { if (params == null || params.get("key") == null) { return AgentResponse.error("key is required"); } - String key = String.valueOf(params.get("key")); + requireSyntheticMode(params); + var stroke = KeyInput.parse(params); Integer nodeId = params.get("nodeId") != null ? ((Number) params.get("nodeId")).intValue() : null; - - String error = runOnFxThread(() -> doTypeKey(nodeId, key)); - if (error != null) { - return AgentResponse.error(error); + var target = runOnFxThread(() -> nodeId != null ? findNodeById(nodeId) : findFocusedNode()); + if (target == null) { + return AgentResponse.error(nodeId != null ? "Node not found: " + nodeId : "No focused node found"); } - return AgentResponse.success(Map.of("typed", true)); + var error = runOnFxThread(() -> { + var visibility = NodeVisibility.evaluate(target); + if (!visibility.effectiveVisible()) return "Node is not effectively visible: " + nodeId + " (" + visibility.reason() + ")"; + if (target.isDisabled()) return "Node is disabled: " + nodeId; + target.requestFocus(); + KeyInput.synthetic(target, stroke); + return null; + }); + if (error != null) return AgentResponse.error(error); + return AgentResponse.success(Map.of("typed", true, "mode", "synthetic")); + } catch (IllegalArgumentException e) { + return AgentResponse.error(e.getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return AgentResponse.error("Key input was interrupted"); } catch (Exception e) { return AgentResponse.error("Failed to type key: " + e.getMessage()); } @@ -586,8 +678,8 @@ public AgentResponse takeScreenshot(Map params) { return AgentResponse.error("savePath is required"); } - int maxWidth = extractMaxDimension(params, "maxWidth", DEFAULT_SCREENSHOT_MAX_WIDTH); - int maxHeight = extractMaxDimension(params, "maxHeight", DEFAULT_SCREENSHOT_MAX_HEIGHT); + int maxWidth = screenshotDimension(params, "maxWidth"); + int maxHeight = screenshotDimension(params, "maxHeight"); Map screenshot = runOnFxThread(() -> doTakeScreenshot(nodeId, stageId, savePath, maxWidth, maxHeight)); if (screenshot == null) { @@ -598,7 +690,7 @@ public AgentResponse takeScreenshot(Map params) { } return AgentResponse.success(screenshot); } catch (Exception e) { - return AgentResponse.error("Failed to take screenshot: " + e.getMessage()); + return AgentResponse.error("Failed to take screenshot: " + describeFailure(e)); } } @@ -639,13 +731,13 @@ public AgentResponse captureVideo(Map params) { var maxWidth = extractBoundedInteger( params, "maxWidth", - DEFAULT_SCREENSHOT_MAX_WIDTH, + DEFAULT_VIDEO_MAX_WIDTH, 2, Integer.MAX_VALUE); var maxHeight = extractBoundedInteger( params, "maxHeight", - DEFAULT_SCREENSHOT_MAX_HEIGHT, + DEFAULT_VIDEO_MAX_HEIGHT, 2, Integer.MAX_VALUE); @@ -689,59 +781,44 @@ private int extractBoundedInteger( return value; } - private int extractMaxDimension(Map params, String key, int defaultValue) { - if (params == null || params.get(key) == null) { - return defaultValue; + private int screenshotDimension(Map params, String key) { + if (params == null || params.get(key) == null) return 0; + var value = params.get(key); + if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue()) + || number.doubleValue() != number.intValue() || number.intValue() < 0) { + throw new IllegalArgumentException(key + " must be a non-negative integer (0 means no resize limit)"); } - return ((Number) params.get(key)).intValue(); + return number.intValue(); } - private ClickOutcome doClickNode(int nodeId, ClickMode mode, ClickOptions options) { + private String doClickNode(int nodeId, ClickOptions options) { var node = findNodeById(nodeId); - if (node == null) return ClickOutcome.failure("Node not found: " + nodeId); - if (!isEffectivelyVisible(node)) { - return ClickOutcome.failure("Node is not visible: " + nodeId); - } - if (isInteractionDisabled(node)) return ClickOutcome.failure("Node is disabled: " + nodeId); + if (node == null) return "Node not found: " + nodeId; + var visibility = NodeVisibility.evaluate(node); + if (!visibility.effectiveVisible()) return "Node is not effectively visible: " + nodeId + " (" + visibility.reason() + ")"; + if (isInteractionDisabled(node)) return "Node is disabled: " + nodeId; var bounds = node.getBoundsInLocal(); if (hasZeroSize(node, bounds)) { - return ClickOutcome.failure("Node is not visible or has zero size: " + nodeId); + return "Node is not visible or has zero size: " + nodeId; } double localX = bounds.getMinX() + (bounds.getWidth() / 2.0); double localY = bounds.getMinY() + (bounds.getHeight() / 2.0); var screenCoordinates = node.localToScreen(localX, localY); if (screenCoordinates == null) { - return ClickOutcome.failure("Node is not attached to a showing window: " + nodeId); - } - - if (mode == ClickMode.SYNTHETIC) { - fireSyntheticClick(node, localX, localY, screenCoordinates.getX(), screenCoordinates.getY(), options); - return ClickOutcome.success(mode); + return "Node is not attached to a showing window: " + nodeId; } - var window = node.getScene() != null ? node.getScene().getWindow() : null; - if (window != null) { - window.requestFocus(); - } - - try { - robotClicker.click(screenCoordinates, options.button(), options.clickCount()); - return ClickOutcome.success(mode); - } catch (RuntimeException exception) { - fireSyntheticClick(node, localX, localY, screenCoordinates.getX(), screenCoordinates.getY(), options); - var reason = exception.getMessage() != null - ? exception.getMessage() - : exception.getClass().getSimpleName(); - return ClickOutcome.fallback(reason); - } + fireSyntheticClick(node, localX, localY, screenCoordinates.getX(), screenCoordinates.getY(), options); + return null; } private String doActivateNode(int nodeId) { var node = findNodeById(nodeId); if (node == null) return "Node not found: " + nodeId; - if (!isEffectivelyVisible(node)) return "Node is not visible: " + nodeId; + var visibility = NodeVisibility.evaluate(node); + if (!visibility.effectiveVisible()) return "Node is not effectively visible: " + nodeId + " (" + visibility.reason() + ")"; if (node.isDisabled()) return "Node is disabled: " + nodeId; var bounds = node.getBoundsInLocal(); @@ -765,6 +842,17 @@ private void fireSyntheticClick( ClickOptions options) { var sceneCoordinates = node.localToScene(localX, localY); + if (options.button() == MouseButton.PRIMARY) { + for (var current = node; current != null; current = current.getParent()) { + if (current.hasProperties() && current.getProperties().get(MenuItem.class) instanceof Menu) { + // Standard submenu skins select their parent menu on MOUSE_ENTERED. + current.fireEvent(createSyntheticMouseEvent(current, MouseEvent.MOUSE_ENTERED, + sceneCoordinates, screenX, screenY, options.button(), 0)); + break; + } + } + } + // Control skins may implement activation on press or release rather than MOUSE_CLICKED. for (var count = 1; count <= options.clickCount(); count++) { node.fireEvent(createSyntheticMouseEvent( @@ -803,7 +891,7 @@ private MouseEvent createSyntheticMouseEvent( pressed && button == MouseButton.PRIMARY, pressed && button == MouseButton.MIDDLE, pressed && button == MouseButton.SECONDARY, - true, button == MouseButton.SECONDARY && eventType == MouseEvent.MOUSE_RELEASED, true, + false, button == MouseButton.SECONDARY && eventType == MouseEvent.MOUSE_RELEASED, true, new PickResult(node, sceneCoordinates.getX(), sceneCoordinates.getY()) ); } @@ -832,52 +920,14 @@ private static ClickOptions from(Map params) { } } - private enum ClickMode { - ROBOT("robot"), - SYNTHETIC("synthetic"); - - private final String value; - - ClickMode(String value) { - this.value = value; - } - - private String value() { - return value; - } - - private static ClickMode from(Object value) { - if (value == null) { - return SYNTHETIC; - } - return switch (String.valueOf(value).toLowerCase(Locale.ROOT)) { - case "robot" -> ROBOT; - case "synthetic" -> SYNTHETIC; - default -> throw new IllegalArgumentException( - "Unsupported click mode: " + value + ". Expected robot or synthetic"); - }; - } - } - - private record ClickOutcome(String error, ClickMode mode, String fallbackReason) { - private static ClickOutcome success(ClickMode mode) { - return new ClickOutcome(null, mode, null); - } - - private static ClickOutcome fallback(String reason) { - return new ClickOutcome(null, ClickMode.SYNTHETIC, reason); - } - - private static ClickOutcome failure(String error) { - return new ClickOutcome(error, null, null); + private static void requireSyntheticMode(Map params) { + var mode = params.get("mode"); + if (mode != null && !"synthetic".equalsIgnoreCase(String.valueOf(mode))) { + throw new IllegalArgumentException( + "Unsupported input mode: " + mode + ". Only synthetic input is supported"); } } - @FunctionalInterface - interface RobotClicker { - void click(Point2D point, MouseButton button, int clickCount); - } - private boolean isInteractionDisabled(Node node) { if (node.isDisabled()) return true; for (var current = node; current != null; current = current.getParent()) { @@ -899,15 +949,6 @@ private boolean hasZeroSize(Node node, Bounds bounds) { && (region.getWidth() == 0 || region.getHeight() == 0); } - private boolean isEffectivelyVisible(Node node) { - for (var current = node; current != null; current = current.getParent()) { - if (!current.isVisible()) { - return false; - } - } - return true; - } - private Boolean doRequestFocus(int nodeId) { Node node = findNodeById(nodeId); if (node == null) return false; @@ -915,25 +956,6 @@ private Boolean doRequestFocus(int nodeId) { return true; } - private String doTypeKey(Integer nodeId, String key) { - if (key == null || key.isEmpty()) return "key is required"; - - Node target = nodeId != null ? findNodeById(nodeId) : findFocusedNode(); - if (target == null) return nodeId != null ? "Node not found: " + nodeId : "No focused node found"; - - target.requestFocus(); - - KeyEvent keyTyped = new KeyEvent( - KeyEvent.KEY_TYPED, - "", - "", - null, - false, false, false, false - ); - target.fireEvent(keyTyped); - return null; - } - private Map doTakeScreenshot(Integer nodeId, String stageId, String savePath, int maxWidth, int maxHeight) { WritableImage image; String targetType; @@ -942,17 +964,26 @@ private Map doTakeScreenshot(Integer nodeId, String stageId, Str if (nodeId != null) { Node node = findNodeById(nodeId); if (node == null) return null; + node.getScene().getRoot().applyCss(); + node.getScene().getRoot().layout(); + var bounds = node.getBoundsInParent(); + verifySnapshotSize(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight()); image = node.snapshot(new SnapshotParameters(), null); targetType = "node"; targetId = String.valueOf(nodeId); } else { Window window = findWindow(stageId); if (window == null || window.getScene() == null) return null; + window.getScene().getRoot().applyCss(); + window.getScene().getRoot().layout(); + verifySnapshotSize(0, 0, window.getScene().getWidth(), window.getScene().getHeight()); image = window.getScene().snapshot(null); targetType = "scenegraph"; targetId = windowId(window); } + var sourceWidth = (int) image.getWidth(); + var sourceHeight = (int) image.getHeight(); image = scaleImage(image, maxWidth, maxHeight); String savedPath = savePng(image, Paths.get(savePath)); @@ -961,11 +992,28 @@ private Map doTakeScreenshot(Integer nodeId, String stageId, Str result.put("savedPath", savedPath); result.put("width", (int) image.getWidth()); result.put("height", (int) image.getHeight()); + result.put("sourceWidth", sourceWidth); + result.put("sourceHeight", sourceHeight); + result.put("scaled", sourceWidth != (int) image.getWidth() || sourceHeight != (int) image.getHeight()); result.put("targetType", targetType); result.put("targetId", targetId); return result; } + private static void verifySnapshotSize(double x, double y, double width, double height) { + if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(width) || !Double.isFinite(height) + || width <= 0 || height <= 0) { + throw new IllegalArgumentException("Snapshot requires positive, finite source dimensions"); + } + // JavaFX snapshots round both edges outward, which can add a pixel at fractional coordinates. + var pixelsWide = Math.ceil(x + width) - Math.floor(x); + var pixelsHigh = Math.ceil(y + height) - Math.floor(y); + if (pixelsWide > MAX_SNAPSHOT_DIMENSION || pixelsHigh > MAX_SNAPSHOT_DIMENSION + || pixelsWide * pixelsHigh > MAX_SNAPSHOT_PIXELS) { + throw new IllegalArgumentException("Source exceeds snapshot safety limit: 8192 pixels per dimension and 16777216 pixels total. Capture a smaller node or window"); + } + } + private Map doCaptureVideo( CaptureTarget target, Path requestedOutput, @@ -1133,11 +1181,12 @@ private Window findWindow(String stageId) { private WritableImage scaleImage(WritableImage image, int maxWidth, int maxHeight) { int width = (int) image.getWidth(); int height = (int) image.getHeight(); - double scale = Math.min(Math.min(maxWidth / (double) width, maxHeight / (double) height), 1.0); + double scale = Math.min(Math.min(maxWidth > 0 ? maxWidth / (double) width : 1.0, + maxHeight > 0 ? maxHeight / (double) height : 1.0), 1.0); if (scale >= 1.0) return image; - int newWidth = (int) (width * scale); - int newHeight = (int) (height * scale); + int newWidth = Math.max(1, (int) (width * scale)); + int newHeight = Math.max(1, (int) (height * scale)); BufferedImage src = toBufferedImage(image); BufferedImage dst = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); @@ -1198,6 +1247,12 @@ private String savePng(WritableImage image, Path outputPath) { private Node findFocusedNode() { ObservableList windows = Window.getWindows(); + for (var window : windows) { + if (window.isFocused() && window.getScene() != null) { + var scene = window.getScene(); + return scene.getFocusOwner() != null ? scene.getFocusOwner() : scene.getRoot(); + } + } for (Window window : windows) { if (window.getScene() == null) continue; Node focusOwner = window.getScene().getFocusOwner(); @@ -1238,6 +1293,13 @@ private Map serializeNodeLightweight(Node node, int currentDepth Map result = new LinkedHashMap<>(); result.put("nodeId", System.identityHashCode(node)); + if (parentId != null) { + result.put("parentId", parentId); + } else if (NodeHierarchy.parentOf(node) != null) { + result.put("parentId", System.identityHashCode(NodeHierarchy.parentOf(node))); + } + NodeVisibility.evaluate(node).addTo(result); + // CSS id: only emit when set String fxId = node.getId(); if (fxId != null) { @@ -1593,4 +1655,33 @@ private T runOnFxThread(java.util.function.Supplier task) throws Exceptio }); return future.get(10, TimeUnit.SECONDS); } + + private record InteractionOutcome(String error, boolean handlerPending) {} + + private InteractionOutcome runInteraction(java.util.function.Supplier task) throws Exception { + if (Platform.isFxApplicationThread()) return new InteractionOutcome(task.get(), false); + var future = new CompletableFuture(); + Platform.runLater(() -> { + // showAndWait starts a nested loop while the action handler is still on the stack. + // A queued acknowledgement lets clients inspect and dismiss that dialog. + Platform.runLater(() -> { + if (!future.isDone() && Platform.isNestedLoopRunning()) { + future.complete(new InteractionOutcome(null, true)); + } + }); + try { + future.complete(new InteractionOutcome(task.get(), false)); + } catch (Exception e) { + future.completeExceptionally(e); + } + }); + return future.get(10, TimeUnit.SECONDS); + } + + private static String describeFailure(Throwable failure) { + while (failure.getCause() != null && failure.getCause() != failure) failure = failure.getCause(); + if (failure instanceof java.util.concurrent.TimeoutException) return "Timed out waiting for the JavaFX thread"; + return failure.getMessage() == null || failure.getMessage().isBlank() + ? failure.getClass().getSimpleName() : failure.getMessage(); + } } diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperations.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperations.java new file mode 100644 index 0000000..44a26bb --- /dev/null +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperations.java @@ -0,0 +1,191 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.scene.Node; +import javafx.scene.Parent; +import javafx.scene.control.ListView; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TableView; +import javafx.scene.control.skin.VirtualFlow; +import javafx.scene.input.PickResult; +import javafx.scene.input.ScrollEvent; + +import java.lang.reflect.InvocationTargetException; +import java.util.Map; + +/** Uses public control APIs; Flowless remains an optional dependency of the target application. */ +final class ScrollOperations { + private ScrollOperations() {} + + static Map scroll(Node node, Map params) { + var dx = delta(params, "dx"); + var dy = delta(params, "dy"); + var align = params.get("align"); + if (align != null && (params.containsKey("dx") || params.containsKey("dy"))) { + throw new IllegalArgumentException("align cannot be combined with dx or dy"); + } + if (align == null && !params.containsKey("dx") && !params.containsKey("dy")) { + throw new IllegalArgumentException("dx, dy or align is required"); + } + if (align != null && !(align instanceof String edge && java.util.Set.of("top", "bottom", "left", "right").contains(edge))) { + throw new IllegalArgumentException("align must be top, bottom, left or right"); + } + layout(node); + var target = unwrap(node); + if (target instanceof ScrollPane pane) { + scrollPane(pane, dx, dy, (String) align); + } else if (isFlowless(target)) { + if (align == null) { + call(target, "scrollXBy", double.class, dx); + call(target, "scrollYBy", double.class, dy); + } else { + var horizontal = align.equals("left") || align.equals("right"); + var last = align.equals("bottom") || align.equals("right"); + call(target, horizontal ? "scrollXToPixel" : "scrollYToPixel", double.class, last ? Double.MAX_VALUE : 0.0); + } + } else { + var flow = standardFlow(target); + if (align != null) { + var verticalEdge = align.equals("top") || align.equals("bottom"); + if (verticalEdge != flow.isVertical()) throw new IllegalArgumentException("align does not match the flow orientation"); + flow.setPosition(align.equals("bottom") || align.equals("right") ? 1 : 0); + } else { + flow.scrollPixels(flow.isVertical() ? dy : dx); + var crossAxis = flow.isVertical() ? dx : dy; + if (crossAxis != 0) fireScroll(flow, flow.isVertical() ? dx : 0, flow.isVertical() ? 0 : dy); + } + } + layout(node); + return Map.of("nodeId", System.identityHashCode(node), "scrolled", true, "refreshRequired", true); + } + + static Map scrollToIndex(Node node, Map params) { + var value = params.get("index"); + if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue()) + || number.doubleValue() != number.intValue() || number.intValue() < 0) { + throw new IllegalArgumentException("index must be a non-negative integer"); + } + var index = number.intValue(); + layout(node); + var target = unwrap(node); + if (target instanceof ListView list) { + checkIndex(index, list.getItems().size()); + list.scrollTo(index); + } else if (target instanceof TableView table) { + checkIndex(index, table.getItems().size()); + table.scrollTo(index); + } else if (target instanceof VirtualFlow flow) { + checkIndex(index, flow.getCellCount()); + flow.scrollTo(index); + } else if (isFlowless(target)) { + // getCell validates against the item list without accessing Flowless private fields. + call(target, "getCell", int.class, index); + call(target, "show", int.class, index); + } else { + throw unsupported(target); + } + layout(node); + return Map.of("nodeId", System.identityHashCode(node), "scrolled", true, "index", index, "refreshRequired", true); + } + + private static void scrollPane(ScrollPane pane, double dx, double dy, String align) { + var content = pane.getContent(); + if (content == null) throw new IllegalArgumentException("ScrollPane has no content"); + if (align != null) { + switch (align) { + case "top" -> pane.setVvalue(pane.getVmin()); + case "bottom" -> pane.setVvalue(pane.getVmax()); + case "left" -> pane.setHvalue(pane.getHmin()); + case "right" -> pane.setHvalue(pane.getHmax()); + default -> throw new IllegalArgumentException("Unsupported align: " + align); + } + } else { + pane.setHvalue(offset(pane.getHvalue(), dx, content.getBoundsInParent().getWidth() - pane.getViewportBounds().getWidth(), + pane.getHmin(), pane.getHmax())); + pane.setVvalue(offset(pane.getVvalue(), dy, content.getBoundsInParent().getHeight() - pane.getViewportBounds().getHeight(), + pane.getVmin(), pane.getVmax())); + } + } + + private static double offset(double value, double delta, double pixels, double min, double max) { + return pixels > 0 ? Math.max(min, Math.min(max, value + delta / pixels * (max - min))) : min; + } + + private static double delta(Map params, String name) { + if (!params.containsKey(name)) return 0; + if (!(params.get(name) instanceof Number value) || !Double.isFinite(value.doubleValue())) { + throw new IllegalArgumentException(name + " must be a finite number"); + } + return value.doubleValue(); + } + + private static void checkIndex(int index, int size) { + if (index >= size) throw new IllegalArgumentException("index out of range: " + index + " (item count: " + size + ")"); + } + + private static Node unwrap(Node node) { + if (hasType(node, "org.fxmisc.flowless.VirtualizedScrollPane")) { + var content = call(node, "getContent"); + if (content instanceof Node child) return child; + throw unsupported(node); + } + return node; + } + + private static boolean isFlowless(Node node) { + return hasType(node, "org.fxmisc.flowless.VirtualFlow"); + } + + private static boolean hasType(Node node, String name) { + for (Class type = node.getClass(); type != null; type = type.getSuperclass()) { + if (type.getName().equals(name)) return true; + } + return false; + } + + private static VirtualFlow standardFlow(Node target) { + if (target instanceof VirtualFlow flow) return flow; + if ((target instanceof ListView || target instanceof TableView) && target.lookup(".virtual-flow") instanceof VirtualFlow flow) { + return flow; + } + throw unsupported(target); + } + + private static IllegalArgumentException unsupported(Node target) { + return new IllegalArgumentException("Unsupported scroll target: " + target.getClass().getName()); + } + + private static Object call(Node target, String name, Class parameterType, Object value) { + return call(target, name, new Class[]{parameterType}, new Object[]{value}); + } + + private static Object call(Node target, String name) { + return call(target, name, new Class[0], new Object[0]); + } + + private static Object call(Node target, String name, Class[] types, Object[] values) { + try { + return target.getClass().getMethod(name, types).invoke(target, values); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(name + " failed: " + e.getCause(), e.getCause()); + } catch (ReflectiveOperationException e) { + throw new IllegalArgumentException("Public scroll API unavailable: " + name, e); + } + } + + private static void layout(Node node) { + if (node.getScene() != null) { + node.getScene().getRoot().applyCss(); + node.getScene().getRoot().layout(); + } + if (node instanceof Parent parent) parent.layout(); + } + + private static void fireScroll(Node node, double dx, double dy) { + var point = node.localToScene(node.getBoundsInLocal().getCenterX(), node.getBoundsInLocal().getCenterY()); + var screen = node.localToScreen(node.getBoundsInLocal().getCenterX(), node.getBoundsInLocal().getCenterY()); + node.fireEvent(new ScrollEvent(ScrollEvent.SCROLL, point.getX(), point.getY(), screen.getX(), screen.getY(), + false, false, false, false, false, false, -dx, -dy, -dx, -dy, + ScrollEvent.HorizontalTextScrollUnits.NONE, 0, ScrollEvent.VerticalTextScrollUnits.NONE, 0, + 0, new PickResult(node, point.getX(), point.getY()))); + } +} diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperations.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperations.java new file mode 100644 index 0000000..362b46d --- /dev/null +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperations.java @@ -0,0 +1,118 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.stage.PopupWindow; +import javafx.stage.Stage; +import javafx.stage.Window; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** Window operations use public JavaFX APIs and must run on the FX thread. */ +final class WindowOperations { + private WindowOperations() {} + + static Window requireWindow(Map params) { + var id = params == null ? null : params.get("stageId"); + if (!(id instanceof String stageId) || stageId.isBlank()) { + throw new IllegalArgumentException("stageId is required"); + } + return Window.getWindows().stream() + .filter(window -> stageId.equals(String.valueOf(System.identityHashCode(window)))) + .findFirst().orElseThrow(() -> new IllegalArgumentException("Window not found: " + stageId)); + } + + static Map details(Window window) { + var result = new LinkedHashMap(); + result.put("stageId", String.valueOf(System.identityHashCode(window))); + result.put("windowType", window.getClass().getSimpleName()); + result.put("x", window.getX()); + result.put("y", window.getY()); + result.put("width", window.getWidth()); + result.put("height", window.getHeight()); + result.put("opacity", window.getOpacity()); + result.put("focused", window.isFocused()); + result.put("showing", window.isShowing()); + if (window.getScene() != null && window.getScene().getRoot() != null) { + result.put("rootNodeId", System.identityHashCode(window.getScene().getRoot())); + } + if (window instanceof Stage stage) { + result.put("title", stage.getTitle()); + result.put("maximized", stage.isMaximized()); + result.put("iconified", stage.isIconified()); + result.put("alwaysOnTop", stage.isAlwaysOnTop()); + result.put("resizable", stage.isResizable()); + } + if (window instanceof PopupWindow popup && popup.getOwnerWindow() != null) { + result.put("ownerWindowId", String.valueOf(System.identityHashCode(popup.getOwnerWindow()))); + } + return result; + } + + static Map setProperty(Map params) { + var window = requireWindow(params); + if (!(window instanceof Stage stage)) throw new IllegalArgumentException("Window properties require a Stage"); + var property = params.get("propertyName"); + if (!(property instanceof String name) || name.isBlank()) { + throw new IllegalArgumentException("propertyName is required"); + } + var type = switch (name) { + case "x", "y", "width", "height", "opacity" -> "number"; + case "maximized", "iconified", "alwaysOnTop", "resizable" -> "boolean"; + case "title" -> "string"; + default -> throw new IllegalArgumentException("Unsupported window property: " + name); + }; + if (params.get("valueType") != null && !type.equals(params.get("valueType"))) { + throw new IllegalArgumentException(name + " requires type " + type); + } + var value = params.get("value"); + if (value == null) throw new IllegalArgumentException("value is required"); + var converted = switch (type) { + case "number" -> finiteNumber(value, name); + case "boolean" -> strictBoolean(value); + default -> value.toString(); + }; + var before = details(stage).get(name); + var after = switch (name) { + case "x" -> { stage.setX((Double) converted); yield stage.getX(); } + case "y" -> { stage.setY((Double) converted); yield stage.getY(); } + case "width" -> { stage.setWidth((Double) converted); yield stage.getWidth(); } + case "height" -> { stage.setHeight((Double) converted); yield stage.getHeight(); } + case "opacity" -> { stage.setOpacity((Double) converted); yield stage.getOpacity(); } + case "maximized" -> { stage.setMaximized((Boolean) converted); yield stage.isMaximized(); } + case "iconified" -> { stage.setIconified((Boolean) converted); yield stage.isIconified(); } + case "alwaysOnTop" -> { stage.setAlwaysOnTop((Boolean) converted); yield stage.isAlwaysOnTop(); } + case "resizable" -> { stage.setResizable((Boolean) converted); yield stage.isResizable(); } + case "title" -> { stage.setTitle((String) converted); yield stage.getTitle(); } + default -> throw new IllegalArgumentException("Unsupported window property: " + name); + }; + var result = new LinkedHashMap(); + result.put("stageId", String.valueOf(System.identityHashCode(stage))); + result.put("propertyName", name); + result.put("oldValue", before); + result.put("newValue", after); + return result; + } + + private static double finiteNumber(Object value, String name) { + final double number; + try { + number = Double.parseDouble(value.toString()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(name + " requires a finite number"); + } + if (!Double.isFinite(number)) throw new IllegalArgumentException(name + " requires a finite number"); + if ((name.equals("width") || name.equals("height")) && number <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + if (name.equals("opacity") && (number < 0 || number > 1)) { + throw new IllegalArgumentException("opacity must be between 0 and 1"); + } + return number; + } + + private static boolean strictBoolean(Object value) { + if ("true".equalsIgnoreCase(value.toString())) return true; + if ("false".equalsIgnoreCase(value.toString())) return false; + throw new IllegalArgumentException("Boolean value must be true or false"); + } +} diff --git a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java index 876f638..7ec87e9 100644 --- a/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java +++ b/fxgraph-agent/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java @@ -12,6 +12,10 @@ public class AgentCommand { public enum CommandType { GET_STAGES, + GET_WINDOW_DETAILS, + SET_WINDOW_PROPERTY, + CLOSE_WINDOW, + CLOSE_POPUP, GET_SCENEGRAPH, GET_NODE_DETAILS, FIND_NODES, @@ -21,6 +25,8 @@ public enum CommandType { ACTIVATE_NODE, REQUEST_FOCUS, TYPE_KEY, + SCROLL_NODE, + SCROLL_TO_INDEX, TAKE_SCREENSHOT, CAPTURE_VIDEO, PING, diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ClickNodeGestureTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ClickNodeGestureTest.java index 081634d..2c5f071 100644 --- a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ClickNodeGestureTest.java +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ClickNodeGestureTest.java @@ -6,6 +6,12 @@ import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; +import javafx.scene.control.Menu; +import javafx.scene.control.MenuButton; +import javafx.scene.control.Dialog; +import javafx.scene.control.ButtonType; +import javafx.animation.PauseTransition; +import javafx.util.Duration; import javafx.scene.control.TextField; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseButton; @@ -28,6 +34,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; @@ -92,6 +99,85 @@ void doubleClickSendsTwoCompleteGesturesWithIncreasingCounts() { assertThat(events).extracting(MouseEvent::getClickCount).containsExactly(1, 1, 1, 2, 2, 2); } + @Test + void syntheticClickIsAcceptedByHandlersThatIgnoreTouchInput() { + var rectangle = new Rectangle(40, 40); + var accepted = new AtomicInteger(); + rectangle.setOnMouseClicked(event -> { + if (!event.isSynthesized()) accepted.incrementAndGet(); + }); + show(rectangle); + + var response = inspector.clickNode(Map.of("nodeId", System.identityHashCode(rectangle))); + + assertThat(response.isSuccess()).isTrue(); + assertThat(accepted).hasValue(1); + } + + @Test + void syntheticClickOpensSubmenu() { + var submenu = new Menu("Submenu", null, new MenuItem("Nested action")); + var button = new MenuButton("Options", null, submenu); + show(button); + var container = new AtomicReference(); + onFx(() -> { + button.show(); + var popup = (ContextMenu) javafx.stage.Window.getWindows().stream() + .filter(w -> w instanceof ContextMenu && w.isShowing()).findFirst().orElseThrow(); + menus.add(popup); + popup.getScene().getRoot().applyCss(); + popup.getScene().getRoot().layout(); + container.set(popup.getScene().getRoot().lookupAll(".menu-item").stream() + .filter(n -> n.getProperties().get(MenuItem.class) == submenu).findFirst().orElseThrow()); + }); + + var response = inspector.clickNode(Map.of("nodeId", System.identityHashCode(container.get()))); + + assertThat(response.isSuccess()).isTrue(); + onFx(() -> assertThat(submenu.isShowing()).isTrue()); + } + + @Test + void menuActionOpeningModalDialogReturnsBeforeDialogIsDismissed() { + var dialog = new AtomicReference>(); + var actions = new AtomicInteger(); + var item = new MenuItem("Open dialog"); + item.setOnAction(event -> { + actions.incrementAndGet(); + var modal = new Dialog(); + modal.initOwner(stage); + modal.getDialogPane().getButtonTypes().add(ButtonType.CLOSE); + dialog.set(modal); + var timeout = new PauseTransition(Duration.seconds(12)); + timeout.setOnFinished(e -> modal.close()); + timeout.play(); + modal.showAndWait(); + timeout.stop(); + }); + var anchor = new Button("Menu"); + var menu = new ContextMenu(item); + menus.add(menu); + anchor.setContextMenu(menu); + show(anchor); + var container = new AtomicReference(); + onFx(() -> { + menu.show(anchor, javafx.geometry.Side.BOTTOM, 0, 0); + menu.getScene().getRoot().applyCss(); + menu.getScene().getRoot().layout(); + container.set(menu.getScene().getRoot().lookup(".menu-item")); + }); + + try { + var response = inspector.clickNode(Map.of("nodeId", System.identityHashCode(container.get()))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(actions).hasValue(1); + onFx(() -> assertThat(dialog.get().isShowing()).isTrue()); + } finally { + onFx(() -> { if (dialog.get() != null) dialog.get().close(); }); + } + } + @Test void doubleClickStartsNameEditing() { var name = new TextField("Original name"); @@ -182,39 +268,20 @@ void secondaryClickRequestsContextMenuOnce() { } @ParameterizedTest - @ValueSource(strings = {"secondary", "middle"}) - void robotClickDeliversRequestedButton(String button) { - var rectangle = new Rectangle(40, 40); - var events = new ArrayList(); - rectangle.setOnMouseClicked(events::add); - show(rectangle); - - var response = inspector.clickNode(Map.of( - "nodeId", System.identityHashCode(rectangle), "mode", "robot", "button", button)); - WaitForAsyncUtils.waitForFxEvents(); - - assertThat(response.isSuccess()).isTrue(); - assertThat(response.getData()).isInstanceOf(Map.class); - assertThat(((Map) response.getData()).get("mode")).isEqualTo("robot"); - assertThat(events).hasSize(1); - assertThat(events.getFirst().getButton().name()).isEqualToIgnoringCase(button); - assertThat(events.getFirst().isSynthesized()).isFalse(); - } - - @Test - void robotDoubleClickDeliversCountTwo() { + @ValueSource(strings = {"robot", "native"}) + void unsupportedModeDoesNotDispatchEvents(String mode) { var rectangle = new Rectangle(40, 40); var events = new ArrayList(); - rectangle.setOnMouseClicked(events::add); + rectangle.addEventFilter(MouseEvent.ANY, events::add); show(rectangle); var response = inspector.clickNode(Map.of( - "nodeId", System.identityHashCode(rectangle), "mode", "robot", "clickCount", 2)); + "nodeId", System.identityHashCode(rectangle), "mode", mode, "clickCount", 2)); WaitForAsyncUtils.waitForFxEvents(); - assertThat(response.isSuccess()).isTrue(); - assertThat(((Map) response.getData()).get("mode")).isEqualTo("robot"); - assertThat(events).extracting(MouseEvent::getClickCount).containsExactly(1, 2); + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("Only synthetic input is supported"); + assertThat(events).isEmpty(); } @Test @@ -239,25 +306,22 @@ void invalidClickParametersDoNotDispatchEvents() { } @Test - void robotFallbackPreservesButtonAndDoubleClick() { - var fallbackInspector = new SceneGraphInspector((point, button, count) -> { - throw new UnsupportedOperationException("Robot unavailable"); - }); + void rejectedRobotModeDoesNotOpenContextMenu() { + var menuRequests = new AtomicInteger(); var rectangle = new Rectangle(40, 40); var events = new ArrayList(); rectangle.setOnMouseClicked(events::add); + rectangle.setOnContextMenuRequested(event -> menuRequests.incrementAndGet()); show(rectangle); - var response = fallbackInspector.clickNode(Map.of( + var response = inspector.clickNode(Map.of( "nodeId", System.identityHashCode(rectangle), "mode", "robot", "button", "secondary", "clickCount", 2)); - assertThat(response.isSuccess()).isTrue(); - var data = (Map) response.getData(); - assertThat(data.get("mode")).isEqualTo("synthetic"); - assertThat(data.get("fallbackReason")).isEqualTo("Robot unavailable"); - assertThat(events).extracting(MouseEvent::getClickCount).containsExactly(1, 2); - assertThat(events).allMatch(event -> event.getButton() == MouseButton.SECONDARY); + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("Only synthetic input is supported"); + assertThat(events).isEmpty(); + assertThat(menuRequests).hasValue(0); } @Test diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeInspectionTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeInspectionTest.java new file mode 100644 index 0000000..fa5dba9 --- /dev/null +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/NodeInspectionTest.java @@ -0,0 +1,207 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.SubScene; +import javafx.scene.control.Button; +import javafx.scene.control.TitledPane; +import javafx.scene.canvas.Canvas; +import javafx.scene.layout.Pane; +import javafx.scene.layout.StackPane; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.testfx.framework.junit5.ApplicationExtension; +import org.testfx.framework.junit5.Start; +import org.testfx.util.WaitForAsyncUtils; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(ApplicationExtension.class) +class NodeInspectionTest { + private final SceneGraphInspector inspector = new SceneGraphInspector(); + private StackPane root; + private Stage stage; + + @Start + void start(Stage stage) { + this.stage = stage; + root = new StackPane(); + root.setId("root"); + stage.setScene(new Scene(root, 400, 300)); + stage.show(); + } + + @Test + @SuppressWarnings("unchecked") + void ancestorsDescribeContainingPaneThroughRoot() { + var button = new Button("Action"); + var pane = new StackPane(button); + pane.setId("cell"); + pane.getStyleClass().add("cell-container"); + show(pane); + + var response = inspector.getNodeDetails(Map.of( + "nodeId", System.identityHashCode(button), "includeAncestors", true)); + + assertThat(response.isSuccess()).isTrue(); + var data = (Map) response.getData(); + var ancestors = (List>) data.get("ancestors"); + assertThat(ancestors).extracting(a -> a.get("nodeId")).containsExactly( + System.identityHashCode(pane), System.identityHashCode(root)); + assertThat(ancestors.getFirst()).containsEntry("id", "cell") + .containsEntry("type", "StackPane") + .containsEntry("styleClass", List.of("cell-container")) + .containsKey("bounds"); + var node = (Map) data.get("node"); + assertThat(node).containsEntry("parentId", System.identityHashCode(pane)); + } + + @Test + @SuppressWarnings("unchecked") + void ancestorsCrossSubSceneBoundary() { + var button = new Button("Nested"); + var nestedRoot = new StackPane(button); + var subScene = new SubScene(nestedRoot, 200, 150); + show(subScene); + + var response = inspector.getNodeDetails(Map.of( + "nodeId", System.identityHashCode(button), "includeAncestors", true)); + + assertThat(response.isSuccess()).isTrue(); + var ancestors = (List>) ((Map) response.getData()).get("ancestors"); + assertThat(ancestors).extracting(a -> a.get("nodeId")).containsExactly( + System.identityHashCode(nestedRoot), System.identityHashCode(subScene), System.identityHashCode(root)); + } + + @Test + @SuppressWarnings("unchecked") + void scenegraphReportsParentIdForSubSceneRoot() { + var nestedRoot = new StackPane(new Button("Nested")); + var subScene = new SubScene(nestedRoot, 200, 150); + show(subScene); + + var response = inspector.getScenegraph(Map.of("depth", 3)); + + assertThat(response.isSuccess()).isTrue(); + var roots = (List>) ((Map) response.getData()).get("rootNodes"); + var tree = roots.stream().filter(n -> n.get("nodeId").equals(System.identityHashCode(root))) + .findFirst().orElseThrow(); + var child = ((List>) tree.get("children")).getFirst(); + var nested = ((List>) child.get("children")).getFirst(); + assertThat(nested).containsEntry("parentId", System.identityHashCode(subScene)); + } + + private void show(Node node) { + onFx(() -> { + root.getChildren().setAll(node); + root.applyCss(); + root.layout(); + }); + } + + @Test + void invisibleAncestorIsReportedAndExcludedFromVisibleSearch() { + var button = new Button("Hidden action"); + var pane = new StackPane(button); + pane.setVisible(false); + show(pane); + + assertThat(details(button)).containsEntry("inScene", true) + .containsEntry("effectiveVisible", false).containsEntry("visibilityReason", "ancestor invisible"); + assertThat(inspector.findNodes(Map.of("text", "Hidden action", "effectiveVisible", true)).getData()) + .isEqualTo(List.of()); + var response = inspector.activateNode(Map.of("nodeId", System.identityHashCode(button))); + assertThat(response.getError()).contains("ancestor invisible"); + } + + @Test + void clippingAncestorExplainsInvisibleButton() { + var button = new Button("Clipped"); + button.relocate(100, 100); + var pane = new Pane(button); + pane.setClip(new Rectangle(20, 20)); + show(pane); + + assertThat(details(button)).containsEntry("effectiveVisible", false) + .containsEntry("clipped", true).containsEntry("visibilityReason", "clipped"); + assertThat(inspector.clickNode(Map.of("nodeId", System.identityHashCode(button))).getError()) + .contains("clipped"); + } + + @Test + void collapsedTitledPaneContentIsNotEffectivelyVisible() { + var button = new Button("Collapsed action"); + var pane = new TitledPane("Section", button); + pane.setAnimated(false); + pane.setExpanded(false); + show(pane); + + assertThat(details(button)).containsEntry("effectiveVisible", false); + assertThat(inspector.activateNode(Map.of("nodeId", System.identityHashCode(button))).isSuccess()).isFalse(); + } + + @Test + void invisibleSubSceneIsIncludedInVisibilityCheck() { + var button = new Button("Nested hidden"); + var subScene = new SubScene(new StackPane(button), 200, 150); + subScene.setVisible(false); + show(subScene); + + assertThat(details(button)).containsEntry("effectiveVisible", false) + .containsEntry("visibilityReason", "ancestor invisible"); + } + + @Test + void zeroSizeNodeHasSpecificReason() { + var canvas = new Canvas(0, 0); + show(canvas); + + assertThat(details(canvas)).containsEntry("effectiveVisible", false) + .containsEntry("visibilityReason", "zero-size"); + } + + @Test + void transparentAncestorHasSpecificReason() { + var button = new Button("Transparent action"); + var pane = new StackPane(button); + pane.setOpacity(0); + show(pane); + + assertThat(details(button)).containsEntry("effectiveVisible", false) + .containsEntry("visibilityReason", "ancestor transparent"); + } + + @Test + void transparentWindowHasSpecificReason() { + var button = new Button("Window transparent"); + show(button); + onFx(() -> stage.setOpacity(0)); + try { + assertThat(details(button)).containsEntry("effectiveVisible", false) + .containsEntry("visibilityReason", "window transparent"); + } finally { + onFx(() -> stage.setOpacity(1)); + } + } + + @SuppressWarnings("unchecked") + private Map details(Node node) { + var response = inspector.getNodeDetails(Map.of("nodeId", System.identityHashCode(node))); + assertThat(response.isSuccess()).isTrue(); + return (Map) ((Map) response.getData()).get("node"); + } + + private void onFx(Runnable action) { + try { + WaitForAsyncUtils.asyncFx(action).get(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new AssertionError(e); + } + } +} diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspectorTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspectorTest.java index 070dd8c..9974cff 100644 --- a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspectorTest.java +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/SceneGraphInspectorTest.java @@ -506,7 +506,7 @@ void clickNode_returnsErrorWhenAncestorIsInvisible() { var response = inspector.clickNode(Map.of("nodeId", nodeId)); assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Node is not visible: " + nodeId); + assertThat(response.getError()).isEqualTo("Node is not effectively visible: " + nodeId + " (ancestor invisible)"); assertThat(actions).hasValue(0); } @@ -526,10 +526,9 @@ void clickNode_firesMouseEventForNode() { } @Test - @DisplayName("Should default to a synthetic gesture without using Robot") - void shouldDefaultToSyntheticGestureWithoutUsingRobot() { - var robotClicks = new AtomicInteger(); - var inspector = new SceneGraphInspector((point, button, count) -> robotClicks.incrementAndGet()); + @DisplayName("Should default to a synthetic gesture") + void shouldDefaultToSyntheticGesture() { + var inspector = createInspector(); var rectangle = new Rectangle(20, 20); var mouseClicks = new AtomicInteger(); rectangle.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> mouseClicks.incrementAndGet()); @@ -541,7 +540,6 @@ void shouldDefaultToSyntheticGestureWithoutUsingRobot() { assertThat(response.isSuccess()).isTrue(); assertThat(castMap(response.getData())).containsEntry("mode", "synthetic"); - assertThat(robotClicks).hasValue(0); assertThat(mouseClicks).hasValue(1); } @@ -595,35 +593,12 @@ void shouldSendCompleteSyntheticClickGestureWhenRequested() { MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED, MouseEvent.MOUSE_CLICKED); - assertThat(events).allMatch(MouseEvent::isSynthesized); + assertThat(events).allMatch(event -> !event.isSynthesized()); assertThat(events.getFirst().isPrimaryButtonDown()).isTrue(); assertThat(events.get(1).isPrimaryButtonDown()).isFalse(); assertThat(events.getLast().isPrimaryButtonDown()).isFalse(); } - @Test - @DisplayName("Should fall back to a synthetic gesture when Robot is unavailable") - void shouldFallBackToSyntheticGestureWhenRobotIsUnavailable() { - var inspector = new SceneGraphInspector((point, button, count) -> { - throw new UnsupportedOperationException("Robot is unavailable"); - }); - var rectangle = new Rectangle(20, 20); - var clicks = new AtomicInteger(); - rectangle.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> clicks.incrementAndGet()); - runOnFxThread(() -> root.getChildren().setAll(rectangle)); - - var response = inspector.clickNode(Map.of( - "nodeId", System.identityHashCode(rectangle), - "mode", "robot" - )); - - assertThat(response.isSuccess()).isTrue(); - assertThat(castMap(response.getData())) - .containsEntry("mode", "synthetic") - .containsEntry("fallbackReason", "Robot is unavailable"); - assertThat(clicks).hasValue(1); - } - @Test void clickNode_createsConsistentMouseEvent() { var inspector = createInspector(); @@ -642,12 +617,12 @@ void clickNode_createsConsistentMouseEvent() { var response = inspector.clickNode(Map.of( "nodeId", System.identityHashCode(rectangle), - "mode", "robot" + "mode", "synthetic" )); var event = clickedEvent.get(); assertThat(response.isSuccess()).isTrue(); - assertThat(castMap(response.getData())).containsEntry("mode", "robot"); + assertThat(castMap(response.getData())).containsEntry("mode", "synthetic"); assertThat(event).isNotNull(); assertThat(event.getSource()).isSameAs(rectangle); assertThat(event.getTarget()).isSameAs(rectangle); @@ -685,7 +660,7 @@ void clickNode_returnsErrorForZeroSize() { AgentResponse response = inspector.clickNode(Map.of("nodeId", nodeId)); assertFalse(response.isSuccess()); - assertEquals("Node is not visible or has zero size: " + nodeId, response.getError()); + assertEquals("Node is not effectively visible: " + nodeId + " (zero-size)", response.getError()); } @Test @@ -705,7 +680,7 @@ void clickNode_returnsErrorForZeroSizeButton() { assertThat(response.isSuccess()).isFalse(); assertThat(response.getError()).isEqualTo( - "Node is not visible or has zero size: " + nodeId + "Node is not effectively visible: " + nodeId + " (zero-size)" ); assertThat(actions).hasValue(0); } @@ -1173,7 +1148,7 @@ void takeScreenshot_preservesAspectRatio() { } @Test - void takeScreenshot_usesDefaultHdLimits() { + void takeScreenshot_preservesSourceDimensionsByDefault() { SceneGraphInspector inspector = createInspector(); Canvas canvas = new Canvas(1920, 1080); runOnFxThread(() -> { @@ -1183,7 +1158,7 @@ void takeScreenshot_usesDefaultHdLimits() { root.getChildren().setAll(canvas); }); int nodeId = System.identityHashCode(canvas); - Path output = tempPngPath("default-hd"); + Path output = tempPngPath("default-source"); AgentResponse response = inspector.takeScreenshot(Map.of( "nodeId", nodeId, "savePath", output.toString() @@ -1193,12 +1168,12 @@ void takeScreenshot_usesDefaultHdLimits() { Map data = castMap(response.getData()); int width = ((Number) data.get("width")).intValue(); int height = ((Number) data.get("height")).intValue(); - assertTrue(width <= 1280, "width should be <= 1280 but was " + width); - assertTrue(height <= 720, "height should be <= 720 but was " + height); + assertThat(width).isEqualTo(1920); + assertThat(height).isEqualTo(1080); } @Test - void takeScreenshot_scalesStageWhenExceedsHd() { + void takeScreenshot_scalesStageWithExplicitHdLimits() { SceneGraphInspector inspector = createInspector(); Stage testStage = createStage(new Group(), "TestStage"); String sid = stageId(testStage); @@ -1210,7 +1185,8 @@ void takeScreenshot_scalesStageWhenExceedsHd() { Path output = tempPngPath("stage-scale"); AgentResponse response = inspector.takeScreenshot(Map.of( "stageId", sid, - "savePath", output.toString() + "savePath", output.toString(), + "maxWidth", 1280, "maxHeight", 720 )); assertTrue(response.isSuccess()); diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScreenshotOptionsTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScreenshotOptionsTest.java new file mode 100644 index 0000000..0e69058 --- /dev/null +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScreenshotOptionsTest.java @@ -0,0 +1,125 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.scene.Scene; +import javafx.scene.layout.StackPane; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.testfx.framework.junit5.ApplicationExtension; +import org.testfx.framework.junit5.Start; +import org.testfx.util.WaitForAsyncUtils; + +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(ApplicationExtension.class) +class ScreenshotOptionsTest { + private final SceneGraphInspector inspector = new SceneGraphInspector(); + private StackPane root; + @TempDir Path directory; + + @Start + void start(Stage stage) { + root = new StackPane(); + stage.setScene(new Scene(root, 400, 300)); + stage.show(); + } + + @Test + @SuppressWarnings("unchecked") + void defaultPreservesLargeWindowResolution() { + var rectangle = show(2026, 1203); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", directory.resolve("original.png").toString())); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat((Map) response.getData()).containsEntry("width", 2026) + .containsEntry("height", 1203).containsEntry("sourceWidth", 2026) + .containsEntry("sourceHeight", 1203).containsEntry("scaled", false); + } + + @Test + @SuppressWarnings("unchecked") + void explicitLimitReportsScalingAndSourceDimensions() { + var rectangle = show(2000, 1000); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", directory.resolve("scaled.png").toString(), "maxWidth", 800, "maxHeight", 800)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat((Map) response.getData()).containsEntry("width", 800) + .containsEntry("height", 400).containsEntry("sourceWidth", 2000) + .containsEntry("sourceHeight", 1000).containsEntry("scaled", true); + } + + @Test + void zeroDisablesRequestedResizeLimits() { + var rectangle = show(2000, 1000); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", directory.resolve("zero.png").toString(), "maxWidth", 0, "maxHeight", 0)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(((Map) response.getData()).get("width")).isEqualTo(2000); + } + + @Test + void negativeLimitIsRejectedBeforeFileCreation() { + var rectangle = show(50, 50); + var path = directory.resolve("invalid.png"); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", path.toString(), "maxWidth", -1)); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("maxWidth", "non-negative"); + assertThat(path).doesNotExist(); + } + + @Test + void oversizedSourceIsRejectedBeforeSnapshotAllocation() { + var rectangle = show(10000, 2); + var path = directory.resolve("oversized.png"); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", path.toString())); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("snapshot safety limit"); + assertThat(path).doesNotExist(); + } + + @Test + void fractionalBoundsIncludeTheExtraSnapshotPixelInSafetyLimit() throws Exception { + var rectangle = show(8192, 2); + WaitForAsyncUtils.asyncFx(() -> rectangle.setTranslateX(0.5)).get(5, TimeUnit.SECONDS); + var path = directory.resolve("fractional.png"); + + var response = inspector.takeScreenshot(Map.of("nodeId", System.identityHashCode(rectangle), + "savePath", path.toString())); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("snapshot safety limit"); + assertThat(path).doesNotExist(); + } + + private Rectangle show(double width, double height) { + var rectangle = new Rectangle(width, height); + try { + WaitForAsyncUtils.asyncFx(() -> { + root.getChildren().setAll(rectangle); + root.applyCss(); + root.layout(); + }).get(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new AssertionError(e); + } + return rectangle; + } +} diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperationsTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperationsTest.java new file mode 100644 index 0000000..1c75b06 --- /dev/null +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/ScrollOperationsTest.java @@ -0,0 +1,210 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import io.github.k7t3.fxgraph.mcp.agent.protocol.AgentResponse; +import javafx.beans.property.SimpleStringProperty; +import javafx.collections.FXCollections; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.control.Label; +import javafx.scene.control.ListView; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableView; +import javafx.scene.layout.StackPane; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; +import org.fxmisc.flowless.Cell; +import org.fxmisc.flowless.VirtualFlow; +import org.fxmisc.flowless.VirtualizedScrollPane; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.testfx.framework.junit5.ApplicationExtension; +import org.testfx.framework.junit5.Start; +import org.testfx.util.WaitForAsyncUtils; + +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(ApplicationExtension.class) +class ScrollOperationsTest { + private final SceneGraphInspector inspector = new SceneGraphInspector(); + private StackPane root; + + @Start + void start(Stage stage) { + root = new StackPane(); + stage.setScene(new Scene(root, 400, 240)); + stage.show(); + } + + @Test + void listScrollToIndexMakesOffscreenItemDiscoverable() { + var list = new ListView<>(FXCollections.observableArrayList(items())); + show(list); + assertThat(inspector.findNodes(Map.of("text", "Row 80", "effectiveVisible", true)).getData()).isEqualTo(java.util.List.of()); + + var response = invoke("scrollToIndex", params(list, "index", 80)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertVisible("Row 80"); + } + + @Test + void tableScrollToIndexMakesOffscreenRowDiscoverable() { + var table = new TableView<>(FXCollections.observableArrayList(items())); + var column = new TableColumn("Name"); + column.setCellValueFactory(cell -> new SimpleStringProperty(cell.getValue())); + table.getColumns().add(column); + show(table); + + var response = invoke("scrollToIndex", params(table, "index", 70)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertVisible("Row 70"); + } + + @Test + void listPixelScrollMovesVisibleCells() { + var list = new ListView<>(FXCollections.observableArrayList(items())); + show(list); + + var response = invoke("scrollNode", params(list, "dy", 500)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> { + var flow = (javafx.scene.control.skin.VirtualFlow) list.lookup(".virtual-flow"); + assertThat(flow.getFirstVisibleCell().getIndex()).isPositive(); + }); + } + + @Test + void listBottomAlignmentShowsFinalItem() { + var list = new ListView<>(FXCollections.observableArrayList(items())); + show(list); + + var response = invoke("scrollNode", params(list, "align", "bottom")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertVisible("Row 99"); + } + + @Test + void scrollPanePixelAndEdgeOperationsChangeOffsets() { + var pane = new ScrollPane(new Rectangle(2000, 2000)); + show(pane); + + var response = invoke("scrollNode", params(pane, "dy", 500)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> assertThat(pane.getVvalue()).isBetween(0.1, 0.5)); + assertThat(invoke("scrollNode", params(pane, "align", "bottom")).isSuccess()).isTrue(); + onFx(() -> assertThat(pane.getVvalue()).isEqualTo(pane.getVmax())); + assertThat(invoke("scrollNode", params(pane, "align", "top")).isSuccess()).isTrue(); + onFx(() -> assertThat(pane.getVvalue()).isEqualTo(pane.getVmin())); + } + + @Test + void flowlessIndexNavigationCreatesNewCells() { + var flow = flowless(); + show(flow); + try { + var response = invoke("scrollToIndex", params(flow, "index", 80)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> assertThat(flow.getCellIfVisible(80)).isPresent()); + assertVisible("Row 80"); + } finally { + onFx(flow::dispose); + } + } + + @Test + void flowlessScrollPaneSupportsPixelsAndBottomAlignment() { + var flow = flowless(); + var pane = new VirtualizedScrollPane<>(flow); + show(pane); + try { + assertThat(invoke("scrollNode", params(pane, "dy", 500)).isSuccess()).isTrue(); + onFx(() -> assertThat(flow.getFirstVisibleIndex()).isPositive()); + assertThat(invoke("scrollNode", params(pane, "align", "bottom")).isSuccess()).isTrue(); + onFx(() -> assertThat(flow.getCellIfVisible(99)).isPresent()); + assertThat(invoke("scrollToIndex", params(pane, "index", 10)).isSuccess()).isTrue(); + onFx(() -> assertThat(flow.getCellIfVisible(10)).isPresent()); + } finally { + onFx(flow::dispose); + } + } + + @Test + void invalidIndexIsRejectedWithoutScrolling() { + var list = new ListView<>(FXCollections.observableArrayList(items())); + show(list); + + var response = invoke("scrollToIndex", params(list, "index", 100)); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("index"); + onFx(() -> assertThat(((javafx.scene.control.skin.VirtualFlow) list.lookup(".virtual-flow")) + .getFirstVisibleCell().getIndex()).isZero()); + } + + @Test + void unknownTargetIsRejectedWithReason() { + var rectangle = new Rectangle(50, 50); + show(rectangle); + + var response = invoke("scrollNode", params(rectangle, "dy", 500)); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("Unsupported scroll target"); + } + + private VirtualFlow> flowless() { + return VirtualFlow.createVertical(FXCollections.observableArrayList(items()), item -> { + var label = new Label(item); + label.setPrefHeight(30); + return Cell.wrapNode(label); + }); + } + + private java.util.List items() { + return IntStream.range(0, 100).mapToObj(i -> "Row " + i).toList(); + } + + private Map params(Node node, String name, Object value) { + return Map.of("nodeId", System.identityHashCode(node), name, value); + } + + private void assertVisible(String text) { + var response = inspector.findNodes(Map.of("text", text, "effectiveVisible", true)); + assertThat(response.isSuccess()).isTrue(); + assertThat((java.util.List) response.getData()).isNotEmpty(); + } + + private AgentResponse invoke(String method, Map params) { + return switch (method) { + case "scrollNode" -> inspector.scrollNode(params); + case "scrollToIndex" -> inspector.scrollToIndex(params); + default -> throw new IllegalArgumentException(method); + }; + } + + private void show(Node node) { + onFx(() -> { + root.getChildren().setAll(node); + root.applyCss(); + root.layout(); + }); + } + + private void onFx(Runnable action) { + try { + WaitForAsyncUtils.asyncFx(action).get(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new AssertionError(e); + } + } +} diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/TypeKeyGestureTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/TypeKeyGestureTest.java new file mode 100644 index 0000000..28cab2d --- /dev/null +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/TypeKeyGestureTest.java @@ -0,0 +1,283 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import javafx.application.Platform; +import javafx.scene.Node; +import javafx.scene.Scene; +import javafx.scene.control.TextField; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyCodeCombination; +import javafx.scene.input.KeyCombination; +import javafx.scene.input.KeyEvent; +import javafx.scene.layout.VBox; +import javafx.scene.shape.Rectangle; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.testfx.framework.junit5.ApplicationExtension; +import org.testfx.framework.junit5.Start; +import org.testfx.util.WaitForAsyncUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(ApplicationExtension.class) +class TypeKeyGestureTest { + private final SceneGraphInspector inspector = new SceneGraphInspector(); + private VBox root; + private Stage stage; + private final List additionalStages = new ArrayList<>(); + + @Start + void start(Stage stage) { + this.stage = stage; + root = new VBox(); + stage.setScene(new Scene(root, 400, 300)); + stage.show(); + } + + @AfterEach + void hideAdditionalStages() { + onFx(() -> additionalStages.forEach(Stage::hide)); + } + + @ParameterizedTest + @ValueSource(strings = {"a", "A", "1", "@", "あ"}) + void syntheticInputInsertsRequestedCharacter(String character) { + var field = new TextField(); + show(field); + + var response = inspector.typeKey(Map.of("nodeId", id(field), "key", character)); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> assertThat(field.getText()).isEqualTo(character)); + } + + @Test + void shiftProducesUppercaseCharacter() { + var field = new TextField(); + show(field); + + var response = inspector.typeKey(Map.of("nodeId", id(field), "key", "a", "modifiers", List.of("SHIFT"))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> assertThat(field.getText()).isEqualTo("A")); + } + + @Test + void namedKeySendsPressedAndReleasedEvents() { + var target = new Rectangle(40, 40); + var events = recordEvents(target); + show(target); + + var response = inspector.typeKey(Map.of("nodeId", id(target), "key", "ENTER")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(events).extracting(KeyEvent::getEventType).containsExactly(KeyEvent.KEY_PRESSED, KeyEvent.KEY_RELEASED); + assertThat(events).extracting(KeyEvent::getCode).containsOnly(KeyCode.ENTER); + } + + @Test + void enterFiresTextFieldAction() { + var field = new TextField(); + var actions = new AtomicInteger(); + field.setOnAction(event -> actions.incrementAndGet()); + show(field); + + var response = inspector.typeKey(Map.of("nodeId", id(field), "key", "ENTER")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(actions).hasValue(1); + } + + @Test + void shiftTabMovesFocusToPreviousControl() { + var first = new TextField(); + var second = new TextField(); + show(first, second); + onFx(second::requestFocus); + + var response = inspector.typeKey(Map.of("nodeId", id(second), "key", "TAB", + "modifiers", List.of("SHIFT"), "mode", "synthetic")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + onFx(() -> assertThat(stage.getScene().getFocusOwner()).isSameAs(first)); + } + + @ParameterizedTest + @CsvSource({"SHIFT,true,false,false,false", "CTRL,false,true,false,false", "CONTROL,false,true,false,false", + "ALT,false,false,true,false", "META,false,false,false,true", "CMD,false,false,false,true"}) + void modifiersAndAliasesSetEventFlags(String modifier, boolean shift, boolean control, boolean alt, boolean meta) { + var target = new Rectangle(40, 40); + var events = recordEvents(target); + show(target); + + var response = inspector.typeKey(Map.of("nodeId", id(target), "key", "Q", "modifiers", List.of(modifier.toLowerCase()))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + var pressed = events.stream().filter(event -> event.getEventType() == KeyEvent.KEY_PRESSED).findFirst().orElseThrow(); + assertThat(pressed.getCode()).isEqualTo(KeyCode.Q); + assertThat(pressed.isShiftDown()).isEqualTo(shift); + assertThat(pressed.isControlDown()).isEqualTo(control); + assertThat(pressed.isAltDown()).isEqualTo(alt); + assertThat(pressed.isMetaDown()).isEqualTo(meta); + } + + @Test + void combinedModifiersDoNotInsertShortcutCharacter() { + var target = new Rectangle(40, 40); + var events = recordEvents(target); + show(target); + + var response = inspector.typeKey(Map.of("nodeId", id(target), "key", "Q", "modifiers", List.of("META", "SHIFT"))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(events).extracting(KeyEvent::getEventType).containsExactly(KeyEvent.KEY_PRESSED, KeyEvent.KEY_RELEASED); + assertThat(events).allMatch(event -> event.isMetaDown() && event.isShiftDown()); + } + + @Test + void shortcutInvokesSceneAccelerator() { + var target = new Rectangle(40, 40); + var actions = new AtomicInteger(); + show(target); + onFx(() -> stage.getScene().getAccelerators().put( + new KeyCodeCombination(KeyCode.K, KeyCombination.CONTROL_DOWN), actions::incrementAndGet)); + + var response = inspector.typeKey(Map.of("nodeId", id(target), "key", "K", "modifiers", List.of("CTRL"))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(actions).hasValue(1); + } + + @Test + void metaWClosesWindowAndRunsHidingHandler() { + var target = new TextField(); + var hiding = new AtomicInteger(); + var window = new CompletableFuture(); + onFx(() -> { + var secondary = new Stage(); + additionalStages.add(secondary); + secondary.setScene(new Scene(new VBox(target), 200, 100)); + secondary.addEventHandler(WindowEvent.WINDOW_HIDING, event -> hiding.incrementAndGet()); + secondary.getScene().getAccelerators().put( + new KeyCodeCombination(KeyCode.W, KeyCombination.META_DOWN), secondary::close); + secondary.show(); + window.complete(secondary); + }); + + var response = inspector.typeKey(Map.of("nodeId", id(target), "key", "W", "modifiers", List.of("CMD"))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(hiding).hasValue(1); + onFx(() -> assertThat(window.join().isShowing()).isFalse()); + } + + @Test + void invalidKeyDoesNotDispatchEvents() { + assertRejected(Map.of("key", "NOT_A_KEY"), "Unsupported key"); + } + + @Test + void invalidModifierDoesNotDispatchEvents() { + assertRejected(Map.of("key", "Q", "modifiers", List.of("SUPER")), "Unsupported modifier"); + } + + @Test + void modifiersMustBeAnArray() { + assertRejected(Map.of("key", "Q", "modifiers", "META,SHIFT"), "modifiers must be an array"); + } + + @Test + void invalidModeDoesNotDispatchEvents() { + assertRejected(Map.of("key", "Q", "mode", "native"), "Only synthetic input is supported"); + } + + @Test + void robotModeDoesNotDispatchEvents() { + assertRejected(Map.of("key", "Q", "mode", "robot"), "Only synthetic input is supported"); + } + + @Test + void undefinedKeyCodeIsRejected() { + assertRejected(Map.of("key", "UNDEFINED"), "Unsupported key"); + } + + @Test + void rejectedRobotModePreservesFocusAndText() { + var first = new TextField("first"); + var second = new TextField("second"); + show(first, second); + onFx(first::requestFocus); + + var response = inspector.typeKey(Map.of("nodeId", id(second), "key", "a", "mode", "robot")); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("Only synthetic input is supported"); + onFx(() -> { + assertThat(stage.getScene().getFocusOwner()).isSameAs(first); + assertThat(first.getText()).isEqualTo("first"); + assertThat(second.getText()).isEqualTo("second"); + }); + } + + private void assertRejected(Map options, String error) { + var target = new Rectangle(40, 40); + var events = recordEvents(target); + show(target); + var params = new java.util.HashMap<>(options); + params.put("nodeId", id(target)); + + var response = inspector.typeKey(params); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains(error); + assertThat(events).isEmpty(); + } + + private List recordEvents(Node target) { + var events = new ArrayList(); + target.addEventFilter(KeyEvent.ANY, events::add); + return events; + } + + private void show(Node... nodes) { + onFx(() -> { + root.getChildren().setAll(nodes); + stage.requestFocus(); + nodes[0].requestFocus(); + }); + } + + private static int id(Node node) { + return System.identityHashCode(node); + } + + private static void onFx(Runnable action) { + var completion = new CompletableFuture(); + Platform.runLater(() -> { + try { + action.run(); + completion.complete(null); + } catch (Throwable error) { + completion.completeExceptionally(error); + } + }); + try { + completion.get(5, TimeUnit.SECONDS); + } catch (Exception error) { + throw new AssertionError(error); + } + WaitForAsyncUtils.waitForFxEvents(); + } +} diff --git a/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperationsTest.java b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperationsTest.java new file mode 100644 index 0000000..826694f --- /dev/null +++ b/fxgraph-agent/src/test/java/io/github/k7t3/fxgraph/mcp/agent/inspector/WindowOperationsTest.java @@ -0,0 +1,161 @@ +package io.github.k7t3.fxgraph.mcp.agent.inspector; + +import io.github.k7t3.fxgraph.mcp.agent.protocol.AgentResponse; +import javafx.scene.Scene; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Button; +import javafx.scene.control.MenuItem; +import javafx.scene.layout.StackPane; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.testfx.framework.junit5.ApplicationExtension; +import org.testfx.framework.junit5.Start; +import org.testfx.util.WaitForAsyncUtils; + +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(ApplicationExtension.class) +class WindowOperationsTest { + private final SceneGraphInspector inspector = new SceneGraphInspector(); + private Stage stage; + private Button button; + + @Start + void start(Stage stage) { + this.stage = stage; + button = new Button("Anchor"); + stage.setTitle("Window properties"); + stage.setScene(new Scene(new StackPane(button), 400, 300)); + stage.show(); + } + + @Test + @SuppressWarnings("unchecked") + void detailsReportStageState() { + var response = invoke("getWindowDetails", Map.of("stageId", id(stage))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat((Map) response.getData()).containsKeys("x", "y", "width", "height", "opacity", + "focused", "maximized", "iconified", "alwaysOnTop", "showing"); + } + + @Test + void propertyChangesAreReflectedInDetails() { + var response = invoke("setWindowProperty", Map.of( + "stageId", id(stage), "propertyName", "x", "value", "123", "valueType", "number")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(((Map) invoke("getWindowDetails", Map.of("stageId", id(stage))).getData()).get("x")) + .isEqualTo(123.0); + } + + @Test + void invalidWindowPropertyIsRejectedWithoutChangingState() { + var before = stage.getOpacity(); + var response = invoke("setWindowProperty", Map.of( + "stageId", id(stage), "propertyName", "opacity", "value", "NaN")); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("finite"); + assertThat(stage.getOpacity()).isEqualTo(before); + } + + @Test + void nullPreviousTitleDoesNotTurnAppliedChangeIntoFailure() { + onFx(() -> stage.setTitle(null)); + + var response = invoke("setWindowProperty", Map.of("stageId", id(stage), + "propertyName", "title", "value", "New title")); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(((Map) response.getData()).get("oldValue")).isNull(); + assertThat(stage.getTitle()).isEqualTo("New title"); + } + + @Test + void consumedCloseRequestKeepsWindowShowing() { + var requests = new AtomicInteger(); + onFx(() -> stage.setOnCloseRequest(event -> { + requests.incrementAndGet(); + event.consume(); + })); + + var response = invoke("closeWindow", Map.of("stageId", id(stage))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(requests).hasValue(1); + assertThat(((Map) response.getData()).get("closed")).isEqualTo(false); + assertThat(stage.isShowing()).isTrue(); + onFx(() -> stage.setOnCloseRequest(null)); + } + + @Test + void closeRequestRunsWindowHidingHandler() { + var requests = new AtomicInteger(); + var hiding = new AtomicInteger(); + onFx(() -> { + stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, event -> requests.incrementAndGet()); + stage.addEventHandler(WindowEvent.WINDOW_HIDING, event -> hiding.incrementAndGet()); + }); + + var response = invoke("closeWindow", Map.of("stageId", id(stage))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(requests).hasValue(1); + assertThat(hiding).hasValue(1); + assertThat(((Map) response.getData()).get("closed")).isEqualTo(true); + assertThat(stage.isShowing()).isFalse(); + } + + @Test + void closePopupHidesOnlySelectedPopup() { + var popup = new ContextMenu(new MenuItem("Popup action")); + onFx(() -> popup.show(button, javafx.geometry.Side.BOTTOM, 0, 0)); + try { + var response = invoke("closePopup", Map.of("stageId", id(popup))); + + assertThat(response.isSuccess()).as(response.getError()).isTrue(); + assertThat(popup.isShowing()).isFalse(); + assertThat(stage.isShowing()).isTrue(); + } finally { + onFx(popup::hide); + } + } + + @Test + void closePopupRejectsNormalStage() { + var response = invoke("closePopup", Map.of("stageId", id(stage))); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getError()).contains("PopupWindow"); + assertThat(stage.isShowing()).isTrue(); + } + + private AgentResponse invoke(String method, Map params) { + return switch (method) { + case "getWindowDetails" -> inspector.getWindowDetails(params); + case "setWindowProperty" -> inspector.setWindowProperty(params); + case "closeWindow" -> inspector.closeWindow(params); + case "closePopup" -> inspector.closePopup(params); + default -> throw new IllegalArgumentException(method); + }; + } + + private String id(javafx.stage.Window window) { + return String.valueOf(System.identityHashCode(window)); + } + + private void onFx(Runnable action) { + try { + WaitForAsyncUtils.asyncFx(action).get(5, TimeUnit.SECONDS); + } catch (Exception e) { + throw new AssertionError(e); + } + } +} diff --git a/fxgraph-cli/README.md b/fxgraph-cli/README.md index b838de9..2c587b8 100644 --- a/fxgraph-cli/README.md +++ b/fxgraph-cli/README.md @@ -37,7 +37,7 @@ java -jar fxgraph-cli.jar discover ### アプリへの接続・コマンド実行 ```bash -java -jar fxgraph-cli.jar [params-json] +java -jar fxgraph-cli.jar [arguments/options] ``` ### コマンド一覧 @@ -46,17 +46,23 @@ java -jar fxgraph-cli.jar [params-json] |---------|------|-----------| | `stages` | Stage(ウィンドウ)一覧を取得 | — | | `scenegraph` | シーングラフツリーを取得 | `--depth N`, `--bounds`, `--props`, `--filter`, `--stageId` | -| `node-details` | 指定ノードの詳細プロパティを取得 | ``, `--filter` | -| `find-nodes` | タイプ・ID・テキスト・スタイルクラスからノードを検索 | `--type`, `--id`, `--text`, `--styleClass`, `--stageId` | +| `window-details` | ウィンドウの位置・サイズ・状態を取得 | `` または `--stageId ID` | +| `set-window-property` | Stage の公開プロパティを変更 | ` `, `--type` | +| `close-window` | 終了要求を送り、アプリのキャンセルを尊重 | `` または `--stageId ID` | +| `close-popup` | 指定ポップアップを閉じる | `` または `--stageId ID` | +| `node-details` | 指定ノードの詳細プロパティ・実効表示状態・祖先を取得 | ``, `--filter`, `--ancestors` | +| `find-nodes` | タイプ・ID・テキスト・スタイルクラスからノードを検索 | `--type`, `--id`, `--text`, `--styleClass`, `--stageId`, `--visible-only` | +| `scroll-node` | ピクセル指定または端へのスクロール | ``, `--dx`, `--dy` または `--align` | +| `scroll-to-index` | 仮想化コンテナの項目を表示 | ` --index N` | | `set-property` | ノードのプロパティを変更 | ` `, `--type` | | `select-node` | ノードをハイライト表示 | ``, `--no-bounds` | -| `click-node` | ボタン・クリック回数を指定してクリック | ``, `--mode synthetic|robot`, `--button primary|secondary|middle`, `--clickCount 1|2` | +| `click-node` | ボタン・クリック回数を指定してクリック | ``, `--mode synthetic`, `--button primary|secondary|middle`, `--clickCount 1|2` | | `right-click-node` | `click-node --button secondary` のショートカット | ``, `--mode` | | `double-click-node` | `click-node --clickCount 2` のショートカット | ``, `--mode`, `--button` | | `activate-node` | マウス入力なしに `ButtonBase` を起動 | `` | | `focus` | ノードにフォーカスを当てる | `` | -| `type-key` | キー入力を送信 | ``, `--nodeId` | -| `screenshot` | スクリーンショットを保存 | ``, `--nodeId`, `--stageId`, `--maxWidth`, `--maxHeight` | +| `type-key` | 修飾キー付きのキー入力を送信 | ``, `--nodeId`, `--modifiers META,SHIFT`, `--mode synthetic` | +| `screenshot` | 元の解像度で PNG を保存。縮小時は元サイズ・scaled を返す | ``, `--nodeId`, `--stageId`, `--maxWidth`, `--maxHeight`, `--no-limit` | | `capture-video` | MP4 動画クリップを保存 | ``, `--nodeId`, `--stageId`, `--durationSeconds`, `--framesPerSecond`, `--maxWidth`, `--maxHeight` | ### 使用例 @@ -89,14 +95,16 @@ java -jar fxgraph-cli.jar $PID select-node $NODE_ID # クリック・論理起動・フォーカス・キー入力 java -jar fxgraph-cli.jar $PID click-node $NODE_ID -java -jar fxgraph-cli.jar $PID click-node $NODE_ID --mode robot +java -jar fxgraph-cli.jar $PID click-node $NODE_ID --mode synthetic java -jar fxgraph-cli.jar $PID click-node $NODE_ID --button secondary java -jar fxgraph-cli.jar $PID click-node $NODE_ID --clickCount 2 java -jar fxgraph-cli.jar $PID right-click-node $NODE_ID -java -jar fxgraph-cli.jar $PID double-click-node $NODE_ID --mode robot +java -jar fxgraph-cli.jar $PID double-click-node $NODE_ID java -jar fxgraph-cli.jar $PID activate-node $BUTTON_NODE_ID java -jar fxgraph-cli.jar $PID focus $NODE_ID java -jar fxgraph-cli.jar $PID type-key ENTER +java -jar fxgraph-cli.jar $PID type-key TAB --modifiers SHIFT +java -jar fxgraph-cli.jar $PID type-key W --modifiers META # スクリーンショット java -jar fxgraph-cli.jar $PID screenshot ./result.png @@ -110,12 +118,15 @@ java -jar fxgraph-cli.jar $PID capture-video ./node.mp4 --nodeId $NODE_ID --dura ## 出力形式 成功時はコマンドの結果を JSON オブジェクト/配列として標準出力に書き込みます。 -エラー時は以下の形式で標準出力に書き込まれます(終了コード 1): +エラーは標準エラー出力に書き込まれます(終了コード 1)。空のオプション値・値の欠落は、オプション名と使用法を示します: -```json -{ "error": "エラーメッセージ" } +```text +Error: Command failed: --stageId requires a non-empty value +Usage: fxgraph find-nodes [options] ``` +操作の詳細、検索対象、モーダルの回避策は [CLI リファレンス](../skills/fxgraph/references/interact-commands.md) を参照してください。 + ## 依存関係 | ライブラリ | スコープ | 用途 | diff --git a/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcher.java b/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcher.java index 861985a..7f0672a 100644 --- a/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcher.java +++ b/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcher.java @@ -57,7 +57,8 @@ public int dispatch(String[] args) { "No command specified after PID " + pid + ". Available commands: stages, scenegraph, node-details, find-nodes, set-property," + " select-node, click-node, right-click-node, double-click-node, activate-node," - + " focus, type-key, screenshot, capture-video"); + + " focus, type-key, window-details, set-window-property, close-window, close-popup," + + " scroll-node, scroll-to-index, screenshot, capture-video"); } return runWithAgent(pid, Arrays.copyOfRange(args, 1, args.length)); @@ -98,6 +99,10 @@ private static int dispatchAgentCommand(JavaFxAgent agent, String[] args) { try { return switch (command) { case "stages" -> cmdStages(agent); + case "window-details" -> cmdWindow(agent, args, AgentCommand.CommandType.GET_WINDOW_DETAILS); + case "set-window-property" -> cmdSetWindowProperty(agent, args); + case "close-window" -> cmdWindow(agent, args, AgentCommand.CommandType.CLOSE_WINDOW); + case "close-popup" -> cmdWindow(agent, args, AgentCommand.CommandType.CLOSE_POPUP); case "scenegraph" -> cmdScenegraph(agent, args); case "node-details" -> cmdNodeDetails(agent, args); case "find-nodes" -> cmdFindNodes(agent, args); @@ -107,10 +112,14 @@ private static int dispatchAgentCommand(JavaFxAgent agent, String[] args) { case "activate-node" -> cmdActivateNode(agent, args); case "focus" -> cmdFocus(agent, args); case "type-key" -> cmdTypeKey(agent, args); + case "scroll-node", "scroll-to-index" -> cmdScroll(agent, args); case "screenshot" -> cmdScreenshot(agent, args); case "capture-video" -> cmdCaptureVideo(agent, args); default -> CliJsonOutput.failure("Unknown command: " + command); }; + } catch (IllegalArgumentException e) { + return CliJsonOutput.failure("Command failed: " + e.getMessage() + + "\nUsage: fxgraph " + command + " [options]"); } catch (Exception e) { return CliJsonOutput.failure("Command failed: " + e.getMessage()); } @@ -126,6 +135,36 @@ private static int cmdStages(JavaFxAgent agent) throws Exception { return outputResponse(resp); } + private static int cmdWindow(JavaFxAgent agent, String[] args, AgentCommand.CommandType type) throws Exception { + var params = new LinkedHashMap(); + var start = 1; + if (args.length > 1 && !args[1].startsWith("--")) { + if (args[1].isBlank()) throw new IllegalArgumentException("stageId requires a non-empty value"); + params.put("stageId", args[1]); + start = 2; + } + for (var i = start; i < args.length; i++) { + if ("--stageId".equals(args[i])) params.put("stageId", requireNext(args, ++i, "--stageId")); + else throw new IllegalArgumentException(unknownOptionMessage(args[i])); + } + if (!params.containsKey("stageId")) throw new IllegalArgumentException(args[0] + " requires or --stageId "); + return outputResponse(agent.sendCommand(new AgentCommand(type, params))); + } + + private static int cmdSetWindowProperty(JavaFxAgent agent, String[] args) throws Exception { + if (args.length < 4) throw new IllegalArgumentException("set-window-property requires [--type TYPE]"); + if (args[1].isBlank()) throw new IllegalArgumentException("stageId requires a non-empty value"); + var params = new LinkedHashMap(); + params.put("stageId", args[1]); + params.put("propertyName", args[2]); + params.put("value", args[3]); + for (var i = 4; i < args.length; i++) { + if ("--type".equals(args[i])) params.put("valueType", requireNext(args, ++i, "--type")); + else throw new IllegalArgumentException(unknownOptionMessage(args[i])); + } + return outputResponse(agent.sendCommand(new AgentCommand(AgentCommand.CommandType.SET_WINDOW_PROPERTY, params))); + } + private static int cmdScenegraph(JavaFxAgent agent, String[] args) throws Exception { Map params = new LinkedHashMap<>(); for (int i = 1; i < args.length; i++) { @@ -157,6 +196,8 @@ private static int cmdNodeDetails(JavaFxAgent agent, String[] args) throws Excep if ("--filter".equals(args[i])) { params.put("propertyFilter", Arrays.asList(requireNext(args, ++i, "--filter").split(","))); + } else if ("--ancestors".equals(args[i])) { + params.put("includeAncestors", true); } else if ("--props".equals(args[i])) { throw new IllegalArgumentException( "--props is not valid for node-details. " + @@ -180,6 +221,7 @@ private static int cmdFindNodes(JavaFxAgent agent, String[] args) throws Excepti case "--text" -> params.put("text", requireNext(args, ++i, "--text")); case "--styleClass"-> params.put("styleClass", requireNext(args, ++i, "--styleClass")); case "--stageId" -> params.put("stageId", requireNext(args, ++i, "--stageId")); + case "--visible-only" -> params.put("effectiveVisible", true); default -> throw new IllegalArgumentException(unknownOptionMessage(args[i])); } } @@ -293,10 +335,11 @@ private static int cmdTypeKey(JavaFxAgent agent, String[] args) throws Exception Map params = new LinkedHashMap<>(); params.put("key", key); for (int i = 2; i < args.length; i++) { - if ("--nodeId".equals(args[i])) { - params.put("nodeId", Integer.parseInt(requireNext(args, ++i, "--nodeId"))); - } else { - throw new IllegalArgumentException(unknownOptionMessage(args[i])); + switch (args[i]) { + case "--nodeId" -> params.put("nodeId", Integer.parseInt(requireNext(args, ++i, "--nodeId"))); + case "--modifiers" -> params.put("modifiers", Arrays.asList(requireNext(args, ++i, "--modifiers").split(",", -1))); + case "--mode" -> params.put("mode", requireNext(args, ++i, "--mode")); + default -> throw new IllegalArgumentException(unknownOptionMessage(args[i])); } } AgentResponse resp = agent.sendCommand( @@ -311,6 +354,7 @@ private static int cmdScreenshot(JavaFxAgent agent, String[] args) throws Except String savePath = args[1]; Map params = new LinkedHashMap<>(); params.put("savePath", savePath); + var noLimit = false; for (int i = 2; i < args.length; i++) { switch (args[i]) { case "--nodeId" -> params.put("nodeId", @@ -320,14 +364,42 @@ private static int cmdScreenshot(JavaFxAgent agent, String[] args) throws Except Integer.parseInt(requireNext(args, ++i, "--maxWidth"))); case "--maxHeight" -> params.put("maxHeight", Integer.parseInt(requireNext(args, ++i, "--maxHeight"))); + case "--no-limit" -> noLimit = true; default -> throw new IllegalArgumentException(unknownOptionMessage(args[i])); } } + if (noLimit) { + if (params.containsKey("maxWidth") || params.containsKey("maxHeight")) { + throw new IllegalArgumentException("--no-limit cannot be combined with --maxWidth or --maxHeight"); + } + params.put("maxWidth", 0); + params.put("maxHeight", 0); + } AgentResponse resp = agent.sendCommand( new AgentCommand(AgentCommand.CommandType.TAKE_SCREENSHOT, params)); return outputResponse(resp); } + private static int cmdScroll(JavaFxAgent agent, String[] args) throws Exception { + if (args.length < 2) throw new IllegalArgumentException(args[0] + " requires a argument"); + var params = new LinkedHashMap(); + params.put("nodeId", parseNodeId(args[1])); + var byIndex = "scroll-to-index".equals(args[0]); + for (var i = 2; i < args.length; i++) { + var flag = args[i]; + if (byIndex && flag.equals("--index")) { + params.put("index", Integer.parseInt(requireNext(args, ++i, flag))); + } else if (!byIndex && (flag.equals("--dx") || flag.equals("--dy"))) { + params.put(flag.substring(2), Double.parseDouble(requireNext(args, ++i, flag))); + } else if (!byIndex && flag.equals("--align")) { + params.put("align", requireNext(args, ++i, flag)); + } else throw new IllegalArgumentException(unknownOptionMessage(flag)); + } + if (byIndex && !params.containsKey("index")) throw new IllegalArgumentException("--index is required"); + return outputResponse(agent.sendCommand(new AgentCommand( + byIndex ? AgentCommand.CommandType.SCROLL_TO_INDEX : AgentCommand.CommandType.SCROLL_NODE, params))); + } + private static int cmdCaptureVideo(JavaFxAgent agent, String[] args) throws Exception { if (args.length < 2) { return CliJsonOutput.failure("capture-video requires an argument"); @@ -393,8 +465,8 @@ private static int parseNodeId(String s) { } private static String requireNext(String[] args, int i, String flag) { - if (i >= args.length) { - throw new IllegalArgumentException(flag + " requires a value"); + if (i >= args.length || args[i].isBlank() || args[i].startsWith("--")) { + throw new IllegalArgumentException(flag + " requires a non-empty value"); } return args[i]; } diff --git a/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/FxgraphApplication.java b/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/FxgraphApplication.java index aa036b2..96b026a 100644 --- a/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/FxgraphApplication.java +++ b/fxgraph-cli/src/main/java/io/github/k7t3/fxgraph/mcp/cli/FxgraphApplication.java @@ -8,15 +8,21 @@ * fxgraph discover * fxgraph <pid> stages * fxgraph <pid> scenegraph [--stageId S] [--depth N] [--bounds] [--props] [--transforms] [--filter p1,p2] - * fxgraph <pid> node-details <nodeId> [--filter p1,p2] + * fxgraph <pid> node-details <nodeId> [--filter p1,p2] [--ancestors] + * fxgraph <pid> window-details --stageId S + * fxgraph <pid> set-window-property <stageId> <property> <value> [--type TYPE] + * fxgraph <pid> close-window <stageId> + * fxgraph <pid> close-popup <stageId> + * fxgraph <pid> scroll-node <nodeId> [--dx N] [--dy N] [--align top|bottom|left|right] + * fxgraph <pid> scroll-to-index <nodeId> --index N * fxgraph <pid> set-property <nodeId> <property> <value> [--type TYPE] * fxgraph <pid> select-node <nodeId> [--no-bounds] - * fxgraph <pid> click-node <nodeId> [--mode synthetic|robot] [--button primary|secondary|middle] [--clickCount 1|2] - * fxgraph <pid> right-click-node <nodeId> [--mode synthetic|robot] - * fxgraph <pid> double-click-node <nodeId> [--mode synthetic|robot] + * fxgraph <pid> click-node <nodeId> [--mode synthetic] [--button primary|secondary|middle] [--clickCount 1|2] + * fxgraph <pid> right-click-node <nodeId> [--mode synthetic] + * fxgraph <pid> double-click-node <nodeId> [--mode synthetic] * fxgraph <pid> activate-node <nodeId> * fxgraph <pid> focus <nodeId> - * fxgraph <pid> type-key <key> [--nodeId N] + * fxgraph <pid> type-key <key> [--nodeId N] [--modifiers META,SHIFT] [--mode synthetic] * fxgraph <pid> screenshot <outputPath> [--nodeId N] [--stageId S] * fxgraph <pid> capture-video <outputPath> [--nodeId N] [--stageId S] [--durationSeconds N] * @@ -44,6 +50,18 @@ static void printHelp() { System.err.println(" fxgraph stages"); System.err.println(" List showing windows (Stages and PopupWindows) in the application."); System.err.println(); + System.err.println(" fxgraph window-details (or --stageId )"); + System.err.println(" Read window geometry, state and Stage flags."); + System.err.println(" fxgraph set-window-property [--type TYPE]"); + System.err.println(" Set x/y/width/height/opacity/title/maximized/iconified/alwaysOnTop/resizable."); + System.err.println(" fxgraph close-window (or --stageId )"); + System.err.println(" Request close; the application can consume WINDOW_CLOSE_REQUEST."); + System.err.println(" fxgraph close-popup (or --stageId )"); + System.err.println(" Hide only the selected PopupWindow."); + System.err.println(); + System.err.println(" fxgraph find-nodes [--type T] [--id ID] [--text TEXT] [--styleClass C] [--stageId S] [--visible-only]"); + System.err.println(" Match Node classes, including subclasses; effective visibility includes ancestor state and clipping."); + System.err.println(); System.err.println(" fxgraph scenegraph [options]"); System.err.println(" Get the scene graph tree."); System.err.println(" --stageId Target a window (legacy option name)"); @@ -56,6 +74,7 @@ static void printHelp() { System.err.println(" fxgraph node-details [options]"); System.err.println(" Get detailed information about a specific node."); System.err.println(" --filter Comma-separated property filter"); + System.err.println(" --ancestors Include containing nodes through the scene root"); System.err.println(); System.err.println(" fxgraph set-property [--type TYPE]"); System.err.println(" Set a property on a node. Types: string, number, boolean, color"); @@ -63,10 +82,10 @@ static void printHelp() { System.err.println(" fxgraph select-node [--no-bounds]"); System.err.println(" Highlight a node with a red border overlay."); System.err.println(); - System.err.println(" fxgraph click-node [--mode synthetic|robot] [--button primary|secondary|middle] [--clickCount 1|2]"); - System.err.println(" fxgraph right-click-node [--mode synthetic|robot]"); - System.err.println(" fxgraph double-click-node [--mode synthetic|robot]"); - System.err.println(" Click with a synthetic gesture by default; use Robot explicitly for native input."); + System.err.println(" fxgraph click-node [--mode synthetic] [--button primary|secondary|middle] [--clickCount 1|2]"); + System.err.println(" fxgraph right-click-node [--mode synthetic]"); + System.err.println(" fxgraph double-click-node [--mode synthetic]"); + System.err.println(" Click with a synthetic JavaFX gesture without OS input permissions."); System.err.println(); System.err.println(" fxgraph activate-node "); System.err.println(" Fire a ButtonBase action without mouse input."); @@ -74,11 +93,17 @@ static void printHelp() { System.err.println(" fxgraph focus "); System.err.println(" Request keyboard focus for a node."); System.err.println(); - System.err.println(" fxgraph type-key [--nodeId N]"); - System.err.println(" Type a key (e.g. 'a', 'ENTER') into a node or the focused node."); + System.err.println(" fxgraph type-key [--nodeId N] [--modifiers META,SHIFT] [--mode synthetic]"); + System.err.println(" Send a key gesture into a node or the focused scene (default: synthetic)."); + System.err.println(" Modifiers: SHIFT, CTRL/CONTROL, ALT, CMD/META. Only synthetic JavaFX input is supported."); + System.err.println(); + System.err.println(" fxgraph scroll-node [--dx N] [--dy N] [--align top|bottom|left|right]"); + System.err.println(" fxgraph scroll-to-index --index N"); + System.err.println(" Scroll supported containers; positive pixels move right/down. Re-run find-nodes afterwards."); System.err.println(); - System.err.println(" fxgraph screenshot [--nodeId N] [--stageId S] [--maxWidth W] [--maxHeight H]"); - System.err.println(" Save a PNG screenshot of a node or one window scene. Default max size: 1280x720."); + System.err.println(" fxgraph screenshot [--nodeId N] [--stageId S] [--maxWidth W] [--maxHeight H] [--no-limit]"); + System.err.println(" Save PNG at source resolution by default; 0 disables an axis resize limit."); + System.err.println(" Source safety limits: 8192 pixels per dimension, 16777216 pixels total (also with --no-limit)."); System.err.println(" --stageId Target Stage or popup scene (legacy option name)"); System.err.println(); System.err.println(" fxgraph capture-video [options]"); diff --git a/fxgraph-cli/src/test/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcherTest.java b/fxgraph-cli/src/test/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcherTest.java index fa071df..f7a4ea9 100644 --- a/fxgraph-cli/src/test/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcherTest.java +++ b/fxgraph-cli/src/test/java/io/github/k7t3/fxgraph/mcp/cli/CliCommandDispatcherTest.java @@ -10,6 +10,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -18,6 +20,7 @@ import java.io.PrintStream; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @@ -82,6 +85,38 @@ void unknownCommandReturnsFailure() throws Exception { assertTrue(errContent.toString().contains("Error:")); } + @ParameterizedTest + @ValueSource(strings = {"", " ", "--text"}) + void findNodesRejectsEmptyOrMissingOptionValue(String value) throws Exception { + var code = dispatcher.dispatch(new String[]{ + "12345", "find-nodes", "--stageId", value, "--text", "閉じる"}); + + assertThat(code).isEqualTo(1); + assertThat(errContent.toString()).contains("--stageId requires a non-empty value", + "Usage: fxgraph find-nodes [options]"); + verify(mockAgent, never()).sendCommand(any()); + } + + @Test + void trailingOptionReportsUsage() throws Exception { + var code = dispatcher.dispatch(new String[]{"12345", "find-nodes", "--stageId"}); + + assertThat(code).isEqualTo(1); + assertThat(errContent.toString()).contains("--stageId requires a non-empty value", + "Usage: fxgraph find-nodes [options]"); + verify(mockAgent, never()).sendCommand(any()); + } + + @Test + void setPropertyPreservesEmptyStringValue() throws Exception { + successResponse(); + + var code = dispatcher.dispatch(new String[]{"12345", "set-property", "123", "text", ""}); + + assertThat(code).isZero(); + assertThat(captureCommand().getParams()).containsEntry("value", ""); + } + @Test void connectFailureReturnsFailure() throws Exception { doThrow(new RuntimeException("attach failed")).when(mockAgent).connect(); @@ -230,6 +265,48 @@ void nodeDetailsInvalidNodeIdReturnsFailure() throws Exception { assertEquals(1, code); } + @Test + void nodeDetailsRequestsAncestors() throws Exception { + successResponse(); + + var code = dispatcher.dispatch(new String[]{"12345", "node-details", "123", "--ancestors"}); + + assertThat(code).isZero(); + assertThat(captureCommand().getParams()).containsEntry("includeAncestors", true); + } + + @ParameterizedTest + @MethodSource("issueCommands") + void issueCommandsForwardParameters(String[] args, String command, Map params) throws Exception { + successResponse(); + + var code = dispatcher.dispatch(args); + + assertThat(code).as(errContent.toString()).isZero(); + var sent = captureCommand(); + assertThat(sent.getCommand().name()).isEqualTo(command); + assertThat(sent.getParams()).containsExactlyInAnyOrderEntriesOf(params); + } + + static Stream issueCommands() { + return Stream.of( + Arguments.of(new String[]{"12345", "window-details", "--stageId", "s"}, "GET_WINDOW_DETAILS", Map.of("stageId", "s")), + Arguments.of(new String[]{"12345", "set-window-property", "s", "x", "100", "--type", "number"}, "SET_WINDOW_PROPERTY", + Map.of("stageId", "s", "propertyName", "x", "value", "100", "valueType", "number")), + Arguments.of(new String[]{"12345", "close-window", "s"}, "CLOSE_WINDOW", Map.of("stageId", "s")), + Arguments.of(new String[]{"12345", "close-popup", "--stageId", "p"}, "CLOSE_POPUP", Map.of("stageId", "p")), + Arguments.of(new String[]{"12345", "scroll-node", "42", "--dy", "500", "--dx", "-20"}, "SCROLL_NODE", + Map.of("nodeId", 42, "dy", 500.0, "dx", -20.0)), + Arguments.of(new String[]{"12345", "scroll-node", "42", "--align", "bottom"}, "SCROLL_NODE", + Map.of("nodeId", 42, "align", "bottom")), + Arguments.of(new String[]{"12345", "scroll-to-index", "42", "--index", "10"}, "SCROLL_TO_INDEX", + Map.of("nodeId", 42, "index", 10)), + Arguments.of(new String[]{"12345", "find-nodes", "--visible-only"}, "FIND_NODES", Map.of("effectiveVisible", true)), + Arguments.of(new String[]{"12345", "screenshot", "/tmp/image.png", "--no-limit"}, "TAKE_SCREENSHOT", + Map.of("savePath", "/tmp/image.png", "maxWidth", 0, "maxHeight", 0)) + ); + } + @Test void nodeDetailsWithPropsHintsAtFilter() throws Exception { int code = dispatcher.dispatch(new String[]{"12345", "node-details", "123", "--props"}); @@ -415,24 +492,24 @@ void clickNodeSendsRequestedMode() throws Exception { void clickNodeSendsButtonAndClickCount() throws Exception { successResponse(); var code = dispatcher.dispatch(new String[]{ - "12345", "click-node", "42", "--button", "secondary", "--clickCount", "2", "--mode", "robot" + "12345", "click-node", "42", "--button", "secondary", "--clickCount", "2", "--mode", "synthetic" }); assertThat(code).isZero(); assertThat(captureCommand().getParams()).containsEntry("button", "secondary") - .containsEntry("clickCount", 2).containsEntry("mode", "robot"); + .containsEntry("clickCount", 2).containsEntry("mode", "synthetic"); } @ParameterizedTest @CsvSource({"right-click-node, button, secondary", "double-click-node, clickCount, 2"}) void clickShortcutSendsPresetWithRequestedMode(String shortcut, String key, String value) throws Exception { successResponse(); - var code = dispatcher.dispatch(new String[]{"12345", shortcut, "42", "--mode", "robot"}); + var code = dispatcher.dispatch(new String[]{"12345", shortcut, "42", "--mode", "synthetic"}); assertThat(code).isZero(); var command = captureCommand(); assertThat(command.getCommand()).isEqualTo(AgentCommand.CommandType.CLICK_NODE); - assertThat(command.getParams()).containsEntry("nodeId", 42).containsEntry("mode", "robot"); + assertThat(command.getParams()).containsEntry("nodeId", 42).containsEntry("mode", "synthetic"); assertThat(command.getParams().get(key).toString()).isEqualTo(value); } @@ -517,6 +594,26 @@ void typeKeyWithNodeId() throws Exception { assertEquals(123, cmd.getParams().get("nodeId")); } + @Test + void typeKeySendsModifiersAndMode() throws Exception { + successResponse(); + + var code = dispatcher.dispatch(new String[]{"12345", "type-key", "Q", "--modifiers", "META,SHIFT", "--mode", "synthetic"}); + + assertThat(code).isZero(); + assertThat(captureCommand().getParams()).containsEntry("modifiers", List.of("META", "SHIFT")) + .containsEntry("mode", "synthetic"); + } + + @Test + void typeKeyRejectsMissingModifiersValue() throws Exception { + var code = dispatcher.dispatch(new String[]{"12345", "type-key", "Q", "--modifiers"}); + + assertThat(code).isEqualTo(1); + assertThat(errContent.toString()).contains("--modifiers requires a non-empty value"); + verify(mockAgent, never()).sendCommand(any()); + } + // =================================================== // screenshot // =================================================== diff --git a/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java b/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java index 5db4a22..4d5da37 100644 --- a/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java +++ b/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/agent/protocol/AgentCommand.java @@ -12,6 +12,10 @@ public class AgentCommand { public enum CommandType { GET_STAGES, + GET_WINDOW_DETAILS, + SET_WINDOW_PROPERTY, + CLOSE_WINDOW, + CLOSE_POPUP, GET_SCENEGRAPH, GET_NODE_DETAILS, FIND_NODES, @@ -21,6 +25,8 @@ public enum CommandType { ACTIVATE_NODE, REQUEST_FOCUS, TYPE_KEY, + SCROLL_NODE, + SCROLL_TO_INDEX, TAKE_SCREENSHOT, CAPTURE_VIDEO, PING, diff --git a/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/model/SceneGraphNode.java b/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/model/SceneGraphNode.java index 08dc09f..cac200e 100644 --- a/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/model/SceneGraphNode.java +++ b/fxgraph-core/src/main/java/io/github/k7t3/fxgraph/mcp/model/SceneGraphNode.java @@ -11,6 +11,11 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class SceneGraphNode { private int nodeId; + private Integer parentId; + private Boolean inScene; + private Boolean effectiveVisible; + private Boolean clipped; + private String visibilityReason; private String id; private String type; private List children; @@ -29,6 +34,21 @@ public SceneGraphNode() {} public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } + public Integer getParentId() { return parentId; } + public void setParentId(Integer parentId) { this.parentId = parentId; } + + public Boolean getInScene() { return inScene; } + public void setInScene(Boolean inScene) { this.inScene = inScene; } + + public Boolean getEffectiveVisible() { return effectiveVisible; } + public void setEffectiveVisible(Boolean effectiveVisible) { this.effectiveVisible = effectiveVisible; } + + public Boolean getClipped() { return clipped; } + public void setClipped(Boolean clipped) { this.clipped = clipped; } + + public String getVisibilityReason() { return visibilityReason; } + public void setVisibilityReason(String visibilityReason) { this.visibilityReason = visibilityReason; } + public String getId() { return id; } public void setId(String id) { this.id = id; } diff --git a/fxgraph-mcp-server/README.md b/fxgraph-mcp-server/README.md index 5fca075..698cd0e 100644 --- a/fxgraph-mcp-server/README.md +++ b/fxgraph-mcp-server/README.md @@ -45,14 +45,21 @@ AI から JavaFX アプリケーションを Scenic View のように検査・ | `connectApplication` | 指定 PID のアプリにインスペクタエージェントを準備する | | `disconnectApplication` | 指定 PID のインスペクタエージェントを停止する | | `getStages` | Stage(ウィンドウ)一覧を取得する | +| `getWindowDetails` | Stage・ポップアップの位置・サイズ・状態を取得する | +| `setWindowProperty` | Stage の位置・サイズ・公開プロパティを変更する | +| `closeWindow` | 終了要求を送り、アプリ側のキャンセルを尊重する | +| `closePopup` | 指定 `PopupWindow` を閉じる | | `getScenegraph` | シーングラフツリーを取得する | -| `getNodeDetails` | 指定ノードのプロパティ詳細を取得する | +| `getNodeDetails` | 指定ノードの詳細・実効表示状態・任意の祖先パスを取得する | +| `findNodes` | Node クラス・ID・テキスト等で検索し、実効表示状態で絞り込む | +| `scrollNode` | ピクセル指定または端へのスクロール | +| `scrollToIndex` | 仮想化コンテナの項目を0始まりのインデックスで表示する | | `setProperty` | ノードのプロパティ値を変更する | | `selectNode` | ノードをハイライト表示する | | `clickNode` | ボタン・クリック回数を指定してクリック。右クリック・ダブルクリックに対応し、既定は合成入力 | | `activateNode` | マウス入力なしに `ButtonBase` を起動する | | `requestFocus` | ノードにフォーカスを当てる | -| `typeKey` | キー入力を送信する | +| `typeKey` | 修飾キー付きの JavaFX 合成キー入力を送信する | | `takeScreenshot` | スクリーンショットを PNG で保存する | | `captureVideo` | 最大30秒の MP4/H.264 動画クリップを保存する | diff --git a/fxgraph-mcp-server/src/main/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphService.java b/fxgraph-mcp-server/src/main/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphService.java index 2618a64..0d46646 100644 --- a/fxgraph-mcp-server/src/main/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphService.java +++ b/fxgraph-mcp-server/src/main/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphService.java @@ -117,6 +117,46 @@ public Map getStages( return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.GET_STAGES)); } + /** Reads public geometry and state from the selected showing window. */ + @Tool(description = "Get geometry and state of a showing Stage or PopupWindow: x, y, width, height, opacity, focused, showing, and Stage-specific maximized, iconified, alwaysOnTop, resizable, title.") + public Map getWindowDetails( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Window ID from stages.stageId") String stageId) { + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.GET_WINDOW_DETAILS, Map.of("stageId", stageId))); + } + + /** Sets a validated public Stage property and returns the previous and current values. */ + @Tool(description = "Set a Stage property: x, y, width, height, opacity, title, maximized, iconified, alwaysOnTop, or resizable. Numbers must be finite; dimensions positive; opacity 0 through 1. Returns oldValue and newValue. Window-manager changes may be asynchronous; re-read window details.") + public Map setWindowProperty( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Stage ID from stages.stageId") String stageId, + @ToolParam(description = "Supported Stage property name") String propertyName, + @ToolParam(description = "New value as string") String value, + @ToolParam(description = "Type hint: number, boolean or string; inferred when omitted", required = false) String valueType) { + var params = new LinkedHashMap(); + params.put("stageId", stageId); + params.put("propertyName", propertyName); + params.put("value", value); + if (valueType != null) params.put("valueType", valueType); + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.SET_WINDOW_PROPERTY, params)); + } + + /** Requests close through the application's normal window event handlers. */ + @Tool(description = "Fire WINDOW_CLOSE_REQUEST for the selected window. The application may consume the request. closeRequested means delivered; closed reports the window being hidden; handlerPending means a modal handler is still waiting. Does not force close or synthesize OS shortcuts.") + public Map closeWindow( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Window ID from stages.stageId") String stageId) { + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.CLOSE_WINDOW, Map.of("stageId", stageId))); + } + + /** Hides a selected popup without dismissing ordinary Stage windows. */ + @Tool(description = "Hide the selected PopupWindow, such as ContextMenu or Tooltip. Rejects ordinary Stages. Embedded overlays such as AtlantaFX ModalPane require their own close action or documented display-property workaround.") + public Map closePopup( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Popup ID from stages.stageId") String stageId) { + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.CLOSE_POPUP, Map.of("stageId", stageId))); + } + @Tool(description = "Get scene graph trees for showing JavaFX Stage and PopupWindow scenes. Returns compact hierarchical trees by default. Use depth to limit tree depth, includeBounds to include node bounding boxes, includeProperties to get property details, propertyFilter to limit which properties, and includeTransforms for transform details.") public Map getScenegraph( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @@ -139,28 +179,36 @@ public Map getScenegraph( new AgentCommand(AgentCommand.CommandType.GET_SCENEGRAPH, params)); } - @Tool(description = "Get detailed information about a specific node including all its properties, children summary, bounds, style classes, and more. Use the nodeId obtained from getScenegraph. Optionally filter properties with propertyFilter.") + @Tool(description = "Get a node's properties, children, bounds, style classes, parentId and effective visibility. Use a current nodeId from getScenegraph/findNodes. propertyFilter selects properties; includeAncestors adds the nearest-first containment path to the scene root, including SubScene boundaries.") public Map getNodeDetails( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "Node ID (identityHashCode of the JavaFX Node)") int nodeId, - @ToolParam(description = "List of property names to include (e.g., ['text', 'value']). Omit to get all properties.", required = false) List propertyFilter) { + @ToolParam(description = "List of property names to include (e.g., ['text', 'value']). Omit to get all properties.", required = false) List propertyFilter, + @ToolParam(description = "Include ancestors from immediate container to scene root, crossing SubScene boundaries", required = false) Boolean includeAncestors) { Map params = new LinkedHashMap<>(); params.put("nodeId", nodeId); if (propertyFilter != null) params.put("propertyFilter", propertyFilter); + if (includeAncestors != null) params.put("includeAncestors", includeAncestors); return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.GET_NODE_DETAILS, params)); } - @Tool(description = "Search showing JavaFX Stage and PopupWindow scene graphs by type, CSS id, text content, or style class. Returns matching nodes with their nodeId, type, id, and text. Use stageId to limit search to a specific window.") + /** Preserves the Java caller overload without ancestor information. */ + public Map getNodeDetails(int pid, int nodeId, List propertyFilter) { + return getNodeDetails(pid, nodeId, propertyFilter, null); + } + + @Tool(description = "Search showing Stage and PopupWindow scenes by Node class/superclass, CSS id, text or style class. Non-Node FXML controllers and MenuItem objects cannot match; search open menus' rendering nodes instead. Returns node IDs, parentId and effective visibility. stageId selects a window; effectiveVisible filters visibility. Reacquire IDs after reopening popups or recycling virtualized cells.") public Map findNodes( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "JavaFX class name to filter (e.g., 'Button', 'TextField'). Omit to match all types.", required = false) String type, @ToolParam(description = "CSS id (fx:id) to match exactly. Omit to match all ids.", required = false) String id, @ToolParam(description = "Text content to search for (case-sensitive contains match). Omit to match all text.", required = false) String text, @ToolParam(description = "Style class name to filter. Omit to match all style classes.", required = false) String styleClass, - @ToolParam(description = "Window ID from the stageId field. Omit to search all showing Stage and PopupWindow scenes.", required = false) String stageId) { + @ToolParam(description = "Window ID from the stageId field. Omit to search all showing Stage and PopupWindow scenes.", required = false) String stageId, + @ToolParam(description = "Filter by effective visibility, accounting for ancestors, opacity, clipping and scene viewport; does not detect occlusion by other nodes/windows", required = false) Boolean effectiveVisible) { Map params = new LinkedHashMap<>(); if (type != null) params.put("type", type); @@ -168,11 +216,42 @@ public Map findNodes( if (text != null) params.put("text", text); if (styleClass != null) params.put("styleClass", styleClass); if (stageId != null) params.put("stageId", stageId); + if (effectiveVisible != null) params.put("effectiveVisible", effectiveVisible); return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.FIND_NODES, params)); } + /** Preserves the Java caller overload without a visibility filter. */ + public Map findNodes(int pid, String type, String id, String text, String styleClass, String stageId) { + return findNodes(pid, type, id, text, styleClass, stageId, null); + } + + /** Scrolls supported containers and lays out the new visible cells before responding. */ + @Tool(description = "Scroll a ListView, TableView, ScrollPane, JavaFX VirtualFlow, Flowless VirtualFlow or VirtualizedScrollPane. Use dx/dy pixels (positive right/down) or align (top/bottom/left/right), exclusively. Re-run findNodes afterwards because virtualized cell IDs may change.") + public Map scrollNode( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Scrollable container node ID") int nodeId, + @ToolParam(description = "Horizontal pixel delta, positive right", required = false) Double dx, + @ToolParam(description = "Vertical pixel delta, positive down", required = false) Double dy, + @ToolParam(description = "Edge: top, bottom, left or right. Cannot be combined with dx/dy", required = false) String align) { + var params = new LinkedHashMap(); + params.put("nodeId", nodeId); + if (dx != null) params.put("dx", dx); + if (dy != null) params.put("dy", dy); + if (align != null) params.put("align", align); + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.SCROLL_NODE, params)); + } + + /** Reveals a zero-based item in a supported virtualized container. */ + @Tool(description = "Reveal a zero-based index in a ListView, TableView, JavaFX VirtualFlow or Flowless VirtualFlow (including a VirtualizedScrollPane wrapping one). Rejects indices outside the item list. Re-run findNodes afterwards to obtain current cell IDs.") + public Map scrollToIndex( + @ToolParam(description = "Process ID of the target JavaFX application") int pid, + @ToolParam(description = "Virtualized container node ID") int nodeId, + @ToolParam(description = "Zero-based item index") int index) { + return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.SCROLL_TO_INDEX, Map.of("nodeId", nodeId, "index", index))); + } + // =================================================== // Node Manipulation // =================================================== @@ -214,16 +293,16 @@ public Map selectNode( * * @param pid process ID of the target JavaFX application * @param nodeId node ID in the current target JVM session - * @param mode synthetic (default) or robot; null selects the default + * @param mode synthetic only; null selects the default * @param button primary (default), secondary or middle; null selects the default * @param clickCount 1 (default) or 2; null selects the default - * @return agent response with the effective mode, button, click count and any fallback reason + * @return agent response with the synthetic mode, button and click count */ - @Tool(description = "Click a JavaFX node by nodeId with primary, secondary (right), or middle button and one or two clicks. Uses synthetic gestures by default without moving the system pointer or requesting focus. Secondary clicks request a context menu. Robot input is available explicitly; native multi-click recognition depends on the OS.") + @Tool(description = "Click a node with primary, secondary or middle button and one or two clicks. Dispatches JavaFX gestures without OS pointer movement or window focus. Secondary clicks request a context menu; standard submenus receive mouse-enter. Only synthetic input is supported. handlerPending=true means a dispatched action is waiting in a modal handler: inspect its dialog and verify the eventual result, without repeating the action.") public Map clickNode( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "Node ID") int nodeId, - @ToolParam(description = "Click mode: synthetic (default) or robot", required = false) + @ToolParam(description = "Click mode: synthetic only (default)", required = false) String mode, @ToolParam(description = "Mouse button: primary (default), secondary (right), or middle", required = false) String button, @@ -251,7 +330,7 @@ public Map clickNode( * * @param pid target process ID * @param nodeId node ID in the current target JVM session - * @param mode synthetic (default) or robot; null selects the default + * @param mode synthetic only; null selects the default * @return agent response describing the delivered click */ public Map clickNode(int pid, int nodeId, String mode) { @@ -276,7 +355,7 @@ public Map clickNode(int pid, int nodeId) { * @param nodeId button node ID in the current target JVM session * @return agent response describing whether activation succeeded */ - @Tool(description = "Activate a JavaFX ButtonBase by nodeId through its semantic fire action without emitting mouse events.") + @Tool(description = "Activate a ButtonBase through fire() without mouse events. handlerPending=true means a dispatched action is waiting in a modal handler: inspect its dialog and verify the eventual result, without repeating the action.") public Map activateNode( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "ButtonBase node ID") int nodeId) { @@ -299,28 +378,54 @@ public Map requestFocus( new AgentCommand(AgentCommand.CommandType.REQUEST_FOCUS, params)); } - @Tool(description = "Type a key into a JavaFX node using JavaFX Event System. If nodeId is omitted, the currently focused node is used.") + /** + * Submits a synthetic JavaFX key gesture with optional modifiers. + * + * @param pid target JVM process ID + * @param key key code name or exact single character + * @param nodeId target node, or null for the focused scene + * @param modifiers modifier names, or null for none + * @param mode synthetic only; null selects the default + * @return agent input submission result, not a guarantee that a shortcut completed + */ + @Tool(description = "Send a synthetic JavaFX key gesture to a node or the focused scene. Supports SHIFT, CTRL/CONTROL, ALT, CMD/META modifiers and exact single characters. Only synthetic input is supported; no OS input permissions are required. Application event handlers and scene accelerators may handle shortcuts; native OS shortcuts are not sent. Termination may close the connection before a response.") public Map typeKey( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "Key text or key code name (e.g. 'a', 'ENTER')") String key, - @ToolParam(description = "Target node ID (optional, defaults to focused node)", required = false) Integer nodeId) { + @ToolParam(description = "Target node ID (optional, defaults to focused scene)", required = false) Integer nodeId, + @ToolParam(description = "Modifier names: SHIFT, CTRL/CONTROL, ALT, CMD/META (e.g. ['META', 'SHIFT'])", required = false) List modifiers, + @ToolParam(description = "Input mode: synthetic only (default)", required = false) String mode) { Map params = new LinkedHashMap<>(); params.put("key", key); if (nodeId != null) params.put("nodeId", nodeId); + if (modifiers != null) params.put("modifiers", modifiers); + if (mode != null) params.put("mode", mode); return sendAgentCommand(pid, new AgentCommand(AgentCommand.CommandType.TYPE_KEY, params)); } - @Tool(description = "Take a screenshot of a specific node or one JavaFX window scene, including an individually selected popup scene. Saves PNG to the specified path.") + /** + * Sends a synthetic key gesture without modifiers. + * + * @param pid target JVM process ID + * @param key key code name or single character + * @param nodeId target node, or null for the focused scene + * @return agent input submission result + */ + public Map typeKey(int pid, String key, Integer nodeId) { + return typeKey(pid, key, nodeId, null, null); + } + + @Tool(description = "Save a node or single window scene as PNG, including a selected popup scene. Preserves original dimensions by default; optional maxWidth/maxHeight shrink while preserving aspect ratio, with zero unlimited. Returns sourceWidth/sourceHeight and scaled. Rejects source images over 8192 pixels per axis or 16777216 pixels total before allocation.") public Map takeScreenshot( @ToolParam(description = "Process ID of the target JavaFX application") int pid, @ToolParam(description = "Target node ID (optional; if omitted, captures full scene graph)", required = false) Integer nodeId, @ToolParam(description = "Window ID from the stageId field for scene capture (optional; defaults to the first Stage)", required = false) String stageId, @ToolParam(description = "Path to save the PNG screenshot") String savePath, - @ToolParam(description = "Maximum width for the screenshot (default: 1280)", required = false) Integer maxWidth, - @ToolParam(description = "Maximum height for the screenshot (default: 720)", required = false) Integer maxHeight) { + @ToolParam(description = "Resize limit for screenshot width; omitted or 0 preserves source resolution. Sources are limited to 8192 per dimension and 16777216 pixels total", required = false) Integer maxWidth, + @ToolParam(description = "Resize limit for screenshot height; omitted or 0 preserves source resolution", required = false) Integer maxHeight) { Map params = new LinkedHashMap<>(); if (nodeId != null) params.put("nodeId", nodeId); diff --git a/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/server/McpServerStdioIntegrationTest.java b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/server/McpServerStdioIntegrationTest.java index a9b234e..34374fe 100644 --- a/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/server/McpServerStdioIntegrationTest.java +++ b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/server/McpServerStdioIntegrationTest.java @@ -155,14 +155,21 @@ void listToolsReturnsAllExpectedTools() { "connectApplication", "disconnectApplication", "getStages", + "getWindowDetails", + "setWindowProperty", + "closeWindow", + "closePopup", "getScenegraph", "getNodeDetails", + "findNodes", "setProperty", "selectNode", "clickNode", "activateNode", "requestFocus", "typeKey", + "scrollNode", + "scrollToIndex", "takeScreenshot", "captureVideo" ); @@ -171,6 +178,7 @@ void listToolsReturnsAllExpectedTools() { assertTrue(toolNames.contains(expected), "Tool '" + expected + "' should be registered. Found tools: " + toolNames); } + assertThat(toolNames).containsExactlyInAnyOrderElementsOf(expectedTools); } @Test @@ -226,6 +234,29 @@ void clickNodeExposesOptionalButtonAndClickCount() { assertThat(tool.inputSchema().required()).doesNotContain("button", "clickCount"); } + @Test + void typeKeyExposesOptionalModifiersAndMode() { + client.initialize(); + var tool = client.listTools().tools().stream() + .filter(candidate -> "typeKey".equals(candidate.name())).findFirst().orElseThrow(); + + assertThat(tool.inputSchema().properties()).containsKeys("modifiers", "mode"); + assertThat(tool.inputSchema().required()).doesNotContain("modifiers", "mode"); + } + + @Test + void inspectionToolsExposeOptionalAncestorsAndVisibilityFilter() { + client.initialize(); + var tools = client.listTools().tools(); + var details = tools.stream().filter(t -> t.name().equals("getNodeDetails")).findFirst().orElseThrow(); + var find = tools.stream().filter(t -> t.name().equals("findNodes")).findFirst().orElseThrow(); + + assertThat(details.inputSchema().properties()).containsKey("includeAncestors"); + assertThat(details.inputSchema().required()).doesNotContain("includeAncestors"); + assertThat(find.inputSchema().properties()).containsKey("effectiveVisible"); + assertThat(find.inputSchema().required()).doesNotContain("effectiveVisible"); + } + // ===== Tool Invocation ===== @Test diff --git a/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphServiceTest.java b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphServiceTest.java index 384dac6..02399d5 100644 --- a/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphServiceTest.java +++ b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/FxgraphServiceTest.java @@ -333,10 +333,10 @@ void clickNodeSendsOptionalMode() throws Exception { void clickNodeSendsButtonAndClickCount() throws Exception { stubSuccessfulMapResponse(); - service.clickNode(PID, 42, "robot", "secondary", 2); + service.clickNode(PID, 42, "synthetic", "secondary", 2); assertThat(capturedCommand().getParams()).containsEntry("nodeId", 42) - .containsEntry("mode", "robot").containsEntry("button", "secondary") + .containsEntry("mode", "synthetic").containsEntry("button", "secondary") .containsEntry("clickCount", 2); } @@ -394,6 +394,16 @@ void typeKeyOmitsNodeIdWhenAbsent() throws Exception { assertFalse(command.getParams().containsKey("nodeId")); } + @Test + void typeKeySendsModifiersAndMode() throws Exception { + stubSuccessfulMapResponse(); + + service.typeKey(PID, "Q", null, List.of("META", "SHIFT"), "synthetic"); + + assertThat(capturedCommand().getParams()).containsEntry("modifiers", List.of("META", "SHIFT")) + .containsEntry("mode", "synthetic").doesNotContainKey("nodeId"); + } + @Test void takeScreenshotSendsNodeTargetAndDimensions() throws Exception { stubSuccessfulMapResponse(); diff --git a/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/IssueToolsTest.java b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/IssueToolsTest.java new file mode 100644 index 0000000..7eeeb40 --- /dev/null +++ b/fxgraph-mcp-server/src/test/java/io/github/k7t3/fxgraph/mcp/tools/IssueToolsTest.java @@ -0,0 +1,60 @@ +package io.github.k7t3.fxgraph.mcp.tools; + +import io.github.k7t3.fxgraph.mcp.agent.JavaFxAgent; +import io.github.k7t3.fxgraph.mcp.agent.protocol.AgentCommand; +import io.github.k7t3.fxgraph.mcp.agent.protocol.AgentResponse; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.springframework.ai.tool.annotation.Tool; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class IssueToolsTest { + @ParameterizedTest(name = "{0}") + @MethodSource("commands") + void toolsForwardParametersAndCloseTransientConnection(String method, Object[] args, + String command, Map params) throws Exception { + var agent = mock(JavaFxAgent.class); + when(agent.sendCommand(any())).thenReturn(AgentResponse.success(Map.of("accepted", true))); + var service = new FxgraphService(pid -> agent); + + var tool = Arrays.stream(FxgraphService.class.getMethods()).filter(m -> m.getName().equals(method) + && m.getParameterCount() == args.length && m.isAnnotationPresent(Tool.class)).findFirst(); + var result = tool.isPresent() ? (Map) tool.get().invoke(service, args) + : Map.of("success", false, "error", "MCP tool unavailable: " + method); + + assertThat(result.get("success")).as(method).isEqualTo(true); + var captured = ArgumentCaptor.forClass(AgentCommand.class); + verify(agent).sendCommand(captured.capture()); + assertThat(captured.getValue().getCommand().name()).isEqualTo(command); + assertThat(captured.getValue().getParams()).containsExactlyInAnyOrderEntriesOf(params); + verify(agent).connect(); + verify(agent).disconnectWithoutShutdown(); + } + + static Stream commands() { + return Stream.of( + Arguments.of("getWindowDetails", new Object[]{12345, "s"}, "GET_WINDOW_DETAILS", Map.of("stageId", "s")), + Arguments.of("setWindowProperty", new Object[]{12345, "s", "x", "100", "number"}, "SET_WINDOW_PROPERTY", + Map.of("stageId", "s", "propertyName", "x", "value", "100", "valueType", "number")), + Arguments.of("closeWindow", new Object[]{12345, "s"}, "CLOSE_WINDOW", Map.of("stageId", "s")), + Arguments.of("closePopup", new Object[]{12345, "p"}, "CLOSE_POPUP", Map.of("stageId", "p")), + Arguments.of("scrollNode", new Object[]{12345, 42, -20.0, 500.0, null}, "SCROLL_NODE", + Map.of("nodeId", 42, "dx", -20.0, "dy", 500.0)), + Arguments.of("scrollToIndex", new Object[]{12345, 42, 10}, "SCROLL_TO_INDEX", Map.of("nodeId", 42, "index", 10)), + Arguments.of("getNodeDetails", new Object[]{12345, 42, List.of("text"), true}, "GET_NODE_DETAILS", + Map.of("nodeId", 42, "propertyFilter", List.of("text"), "includeAncestors", true)), + Arguments.of("findNodes", new Object[]{12345, "Button", null, null, null, "s", true}, "FIND_NODES", + Map.of("type", "Button", "stageId", "s", "effectiveVisible", true)) + ); + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1abb5ae..ef79a0c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,6 +2,7 @@ assertj = "3.27.7" jackson = "2.18.3" jcodec = "0.2.5" +flowless = "0.7.4" junit = "5.10.0" mockito = "5.23.0" javafx = "21" @@ -17,6 +18,7 @@ assertj-core = { module = "org.assertj:assertj-core", jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } jcodec-core = { module = "org.jcodec:jcodec", version.ref = "jcodec" } jcodec-javase = { module = "org.jcodec:jcodec-javase", version.ref = "jcodec" } +flowless = { module = "org.fxmisc.flowless:flowless", version.ref = "flowless" } junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" } diff --git a/skills/fxgraph/SKILL.md b/skills/fxgraph/SKILL.md index cb9416c..3546ae9 100644 --- a/skills/fxgraph/SKILL.md +++ b/skills/fxgraph/SKILL.md @@ -39,11 +39,14 @@ fxgraph repository root. Do not rebuild an installed skill unless its repository |---|---|---| | Nodes in a JavaFX `Stage` scene | Inspect and interact | — | | Additional windows implemented as `Stage` | Inspect with `stages` and `--stageId` | — | +| Stage geometry/state and close requests | `window-details`, `set-window-property`, `close-window` | Native OS shortcuts are not sent | | Showing `PopupWindow`, `ContextMenu`, `MenuButton` popup contents, tooltips | Inspect and interact with the popup's `stageId` | Open the popup before inspection | +| Close a showing popup | `close-popup` using the current popup ID | Embedded overlays require their own close action or documented property workaround | +| Virtualized items outside the viewport | `scroll-to-index` or `scroll-node`, then search again | Inspect the container's supported API | | Node or individual window scene image | `screenshot` | — | | Node or individual window scene motion (up to 30 seconds) | `capture-video` | — | | One image containing separately composited popups or OS decorations | Not captured by scene snapshots | Native OS/compositor screenshot | -| JavaFX click behavior without moving the system pointer | `click-node` uses a complete synthetic gesture by default | Use `--mode robot` only when native pointer input is required | +| JavaFX click behavior without moving the system pointer | `click-node` uses a complete synthetic gesture | Native pointer input is not supported | | Exact OS-specific mouse and keyboard behavior | Not guaranteed | TestFX or approved native UI automation | For a popup workflow, open the popup first, then rerun `stages`. Popup entries expose `windowType` @@ -129,14 +132,22 @@ If direct lookup is insufficient: ``` Use `select-node` before a risky change when visual confirmation helps. Prefer `set-property` for -deterministic text entry. `click-node` sends a complete synthetic gesture by default without moving -the pointer or requesting window focus; use `--mode robot` only when native pointer input is material. +deterministic text entry. `click-node` sends a complete synthetic JavaFX gesture without moving +the pointer or requesting window focus. Input commands do not require OS input permissions. Use `--button secondary` for a right click and `--clickCount 2` for a double click. The shortcuts -`right-click-node` and `double-click-node` accept `--mode robot` too. Context menus may take focus. +`right-click-node` and `double-click-node` use the same synthetic input. Context menus may take focus. For menu items, inspect `node.disabled` in `node-details`; omitted means false, while the rendered Node's `disable` property alone may not reflect the MenuItem state. Use `activate-node` for a deterministic `ButtonBase.fire()` action without mouse input. `type-key` -remains synthetic. +sends synthetic JavaFX key gestures; use `--modifiers SHIFT` for Shift+Tab or `--modifiers META` +for application shortcuts handled inside JavaFX. Native OS shortcuts are not sent. +Omit `--mode` or use `--mode synthetic`; the removed `robot` mode returns an error before input. +Verify the application effect; termination may close the connection before a response. +Use `node-details --ancestors` to identify a containing cell, and `--visible-only` on `find-nodes` +to exclude hidden/clipped nodes. These visibility diagnostics do not detect sibling/OS occlusion. +Rerun `stages` and `find-nodes` after every popup opening, and `find-nodes` after scrolling. +`handlerPending: true` indicates a dispatched action waiting in a modal handler: inspect and +dismiss the dialog, then verify the final application state rather than repeating the action. ## Apply command invariants @@ -146,7 +157,7 @@ remains synthetic. - `properties` is an array of `{name, value, type, writable, category}`, not a flat object. - Treat IDs as valid only for the current JVM session. After restart, rerun `discover`, `stages`, and `find-nodes`; do not reuse PID, window IDs from `stageId`, or node IDs. -- Inspect JSON error output and exit status before continuing. +- Inspect stderr and exit status before continuing; errors are plain text, not success JSON. - Verify changes through application state, a focused property query, a suitable screenshot, or a combination of them. - Use `capture-video` when motion over time is material; use `screenshot` for a single visual state. @@ -154,9 +165,10 @@ remains synthetic. ## Load command references only as needed - Read [inspect-commands.md](references/inspect-commands.md) for exhaustive options and schemas for - `discover`, `stages`, `find-nodes`, `scenegraph`, and `node-details`. + `discover`, `stages`, `window-details`, `find-nodes`, `scenegraph`, and `node-details`. - Read [interact-commands.md](references/interact-commands.md) for `set-property`, `select-node`, `click-node`, `right-click-node`, `double-click-node`, `activate-node`, `focus`, `type-key`, - `screenshot`, and `capture-video`. + `set-window-property`, `close-window`, `close-popup`, overlay workarounds, `scroll-node`, + `scroll-to-index`, `screenshot`, and `capture-video`. - Read [troubleshooting.md](references/troubleshooting.md) for decision trees covering empty discovery, attach failures, stale IDs, popup controls, and composite screenshots. diff --git a/skills/fxgraph/references/inspect-commands.md b/skills/fxgraph/references/inspect-commands.md index 3507929..0aee020 100644 --- a/skills/fxgraph/references/inspect-commands.md +++ b/skills/fxgraph/references/inspect-commands.md @@ -112,11 +112,12 @@ $CLI $PID find-nodes [OPTIONS] | Option | Description | |---|---| -| `--type TYPE` | Match the JavaFX class simple name, such as `Button` | +| `--type TYPE` | Match a Node class simple name, such as `Button`, or a superclass name | | `--id ID` | Match the node CSS ID | | `--text TEXT` | Match text contained by `Labeled` or `TextInputControl` nodes | | `--styleClass CLASS` | Match one style-class entry | | `--stageId ID` | Limit the search to one window; the option name is retained for compatibility | +| `--visible-only` | Return only effectively visible nodes | Combine filters to reduce ambiguity: @@ -126,10 +127,46 @@ $CLI $PID find-nodes --id submitBtn --stageId "$STAGE_ID" ``` Output is a JSON array of compact matches containing `nodeId`, `type`, and, when present, `id`, -`text`, and `visible`. +`text`, `visible`, `parentId`, `inScene`, `effectiveVisible`, and `clipped`. +When a node is not effectively visible, `visibilityReason` explains the cause. + +`--type` searches actual `Node` classes, including application-defined subclasses. FXML controllers +and view classes that do not extend `Node` are not searchable; locate their root node by its class, +CSS ID, or style class. `MenuItem` / `CheckMenuItem` are not Nodes either: search their currently +rendered `MenuItemContainer` skin nodes after opening the menu. + +`visible` describes only the node's own flag. `effectiveVisible` also checks ancestors (including +SubScene boundaries), window state/opacity, zero-size bounds, clips, and the scene viewport. +`clipped: true` can also indicate a partially visible node. This is a bounding-box estimate; +it does not detect coverage by sibling nodes, overlays, other windows, or holes in shaped clips. +Detached nodes and nodes in hidden windows are outside the searchable graph; stale IDs return +`Node not found`. For popup content, open the popup, obtain its ID from `stages`, and pass that ID to `--stageId`. Without the option, the search includes all currently showing Stage and popup windows. +Popup scenes and skin nodes may be recreated every time a popup opens. Rerun `stages` and then +`find-nodes --stageId "$POPUP_ID"` on every opening, even when the owner window is unchanged. + +An empty option value or a missing value is rejected with the option name and usage. Check that +shell variables are populated before invoking commands; `--stageId "" --text "Close"` reports +`--stageId requires a non-empty value` and does not consume `--text` as its value. + +--- + +## window-details + +Read the selected showing Stage or PopupWindow's public state: + +```bash +$CLI $PID window-details --stageId "$STAGE_ID" +# Positional form is also supported +$CLI $PID window-details "$STAGE_ID" +``` + +The result includes `stageId`, `windowType`, `x`, `y`, `width`, `height`, `opacity`, `focused`, +`showing`, and `rootNodeId` when there is a scene. Stage entries also include `title`, `maximized`, +`iconified`, `alwaysOnTop`, and `resizable`. Popup entries may include `ownerWindowId`. +Window-manager changes may be asynchronous; read details again after changing a property. --- @@ -158,12 +195,19 @@ $CLI $PID scenegraph [OPTIONS] ```json { "nodeId": 987654321, - "type": "Button" + "type": "Button", + "parentId": 123456789, + "inScene": true, + "effectiveVisible": true, + "clipped": false } ``` Field presence rules: - `id` — only when a CSS ID is set +- `parentId` — containing node ID; omitted for the scene root. A SubScene root points to its SubScene. +- `inScene`, `effectiveVisible`, `clipped` — always included +- `visibilityReason` — included when not effectively visible - `visible` — only when `false` (default is `true`) - `styleClass` — only when non-empty - `bounds` — only with `--bounds` @@ -217,6 +261,7 @@ $CLI $PID node-details $NODE_ID --filter text,visible,disable $CLI $PID node-details $NODE_ID --filter items # list/table item count $CLI $PID node-details $NODE_ID --filter text,style # label/button content $CLI $PID node-details $NODE_ID --filter focused,disabled,managed +$CLI $PID node-details $NODE_ID --filter text --ancestors # Full dump (only when you need everything — output is very large) $CLI $PID node-details $NODE_ID @@ -247,6 +292,11 @@ $CLI $PID node-details $NODE_ID **Property categories:** `layout`, `style`, `visual`, `content`, `interaction`, `properties`. +`--ancestors` adds an `ancestors` array, ordered from the immediate container to the scene root. +Each entry has `nodeId`, `type`, optional `id` / `styleClass`, and `bounds` in its parent's +coordinates. Paths cross SubScene boundaries. The normal `node` object also includes `parentId` +and visibility diagnostics, independently of `--filter`. + --- ## jq Pipeline Patterns diff --git a/skills/fxgraph/references/interact-commands.md b/skills/fxgraph/references/interact-commands.md index cbcb743..4b64884 100644 --- a/skills/fxgraph/references/interact-commands.md +++ b/skills/fxgraph/references/interact-commands.md @@ -32,7 +32,7 @@ $CLI $PID set-property $NODE_ID textFill "#FF0000" --type color **Output:** ```json -{ "success": true, "oldValue": "Previous Text", "newValue": "Hello World" } +{ "oldValue": "Previous Text", "newValue": "Hello World" } ``` - Property name must match the JavaFX bean property (e.g. `text`, `style`, `visible`, `disable`, `opacity`, `prefWidth`, `prefHeight`). @@ -52,7 +52,7 @@ $CLI $PID select-node 0 # clear highlight **Output:** ```json -{ "success": true, "highlighted": true } +{ "highlighted": true } ``` Use this to visually confirm you have the right node before modifying it. @@ -62,17 +62,16 @@ Use this to visually confirm you have the right node before modifying it. ## click-node Click the center of a node with synthetic `MOUSE_PRESSED`, `MOUSE_RELEASED`, and `MOUSE_CLICKED` -events by default. This mode does not move the system pointer or request window focus. Use -`--mode robot` when normal platform hit testing and native pointer input are required. If explicitly -requested Robot input is unavailable, fxgraph automatically falls back to the synthetic gesture. +events inside JavaFX. This does not move the system pointer or request window focus, and requires +no OS input permissions. Native pointer hit testing is not reproduced. ```bash $CLI $PID click-node $NODE_ID $CLI $PID click-node $NODE_ID --button secondary $CLI $PID click-node $NODE_ID --clickCount 2 -$CLI $PID click-node $NODE_ID --button middle --mode robot +$CLI $PID click-node $NODE_ID --button middle $CLI $PID right-click-node $NODE_ID -$CLI $PID double-click-node $NODE_ID --mode robot +$CLI $PID double-click-node $NODE_ID ``` - `--button`: `primary` (default), `secondary` (right), or `middle`. @@ -84,19 +83,27 @@ $CLI $PID double-click-node $NODE_ID --mode robot Custom context-menu handlers should consume that request when replacing the default menu. - The application must be running and the node and its ancestors must be visible. - Disabled and zero-size nodes are rejected, including disabled menu items and their children. -- `--mode robot` requests window focus and moves the system pointer to the node center. Double-click - recognition depends on the OS timing and position thresholds and prior native clicks. +- `--mode` is optional and accepts only `synthetic`. Other values, including the removed `robot` + mode, return an error before input is dispatched. - A menu or an application event handler may change focus even with synthetic input. - Inspect menu item state using `node-details`: `node.disabled: true` means disabled; omitted means false. A standard menu item's rendered Node `disable` property may differ from the MenuItem state. +- Standard `Menu` submenu containers receive an enter gesture so they can open without native input. +- If an action opens a blocking modal dialog, the response includes `handlerPending: true`. + It confirms dispatch while the handler is waiting; inspect/dismiss the dialog and verify the + application's resulting state. Do not repeat the action merely because it has not returned yet. +- Synthetic gestures use `MouseEvent.isSynthesized() == false`; that JavaFX flag identifies + touch-derived input, rather than programmatically created mouse events. + +Older Robot builds moved the system pointer and could change window focus. That mode is now removed. +Legacy macOS IMK/IMKCFRunLoopWakeUpReliable log messages alone do not establish input success or failure; +verify the application's resulting state when diagnosing an older installation. **Output:** ```json { "clicked": true, "mode": "synthetic", "button": "primary", "clickCount": 1 } ``` -Robot fallback returns `mode: "synthetic"` plus `fallbackReason`, preserving the button and click count. - --- ## activate-node @@ -109,7 +116,7 @@ $CLI $PID activate-node $BUTTON_NODE_ID **Output:** ```json -{ "success": true, "activated": true } +{ "activated": true, "handlerPending": false } ``` Use this for deterministic action invocation when pointer hit testing and mouse handlers are not @@ -127,7 +134,7 @@ $CLI $PID focus $NODE_ID **Output:** ```json -{ "success": true, "focused": true } +{ "focused": true } ``` Call this before `type-key` when targeting a specific input field. @@ -136,12 +143,17 @@ Call this before `type-key` when targeting a specific input field. ## type-key -Send a synthetic JavaFX key event to the focused node (or a specific node). +Send a synthetic JavaFX key gesture to the focused scene (or a specific node). +It dispatches `KEY_PRESSED` and `KEY_RELEASED`, plus `KEY_TYPED` for printable input without +Control, Alt, or Meta. Named keys such as `ENTER` and `TAB` are sent as key codes. ```bash $CLI $PID type-key ENTER $CLI $PID type-key a $CLI $PID type-key TAB --nodeId $NODE_ID +$CLI $PID type-key TAB --modifiers SHIFT +$CLI $PID type-key Q --modifiers META,SHIFT +$CLI $PID type-key W --modifiers CMD ``` | Argument | Format | @@ -150,16 +162,102 @@ $CLI $PID type-key TAB --nodeId $NODE_ID | Single character | `a`, `1`, `@`, etc. | `--nodeId` — optional; send to a specific node instead of the focused node. +`--modifiers` — comma-separated `SHIFT`, `CTRL`/`CONTROL`, `ALT`, `CMD`/`META`, case-insensitive. +Multiple names and aliases can be combined; duplicates are normalized to one event flag. +`CMD`/`META` sets the JavaFX event's Meta flag. +`--mode` — optional, accepts only `synthetic`. The removed `robot` mode returns an error before +input or focus changes. **Output:** ```json -{ "success": true, "typed": true } +{ "typed": true, "mode": "synthetic" } +``` + +Input is dispatched inside JavaFX after requesting node focus. No OS input permissions or foreground +window are required. Exact single characters, including Unicode, are supported. + +Successful output confirms input submission. Verify focus movement, shortcut actions, and window +lifecycle events in the application. Shift+Tab and JavaFX event handlers or scene accelerators can +handle gestures. Native OS shortcuts are not sent; Cmd+W/Cmd+Q require application-side handling. +Cmd+Q may terminate the JVM before the agent replies, producing a connection error; that error alone +does not establish whether the shortcut succeeded. For text fields, prefer `set-property ... text` +for deterministic replacement; for button activation, prefer `activate-node`. +To test a window's normal close-request/hiding handlers directly, use `close-window` instead of +relying on a native Cmd+W/Cmd+Q shortcut. + +--- + +## set-window-property / close-window + +```bash +$CLI $PID set-window-property "$STAGE_ID" x 100 --type number +$CLI $PID set-window-property "$STAGE_ID" width 1200 --type number +$CLI $PID set-window-property "$STAGE_ID" maximized true --type boolean +$CLI $PID close-window "$STAGE_ID" +# close-window also accepts --stageId "$STAGE_ID" ``` -This is not native keyboard input. Treat it as best-effort and verify the application effect. For -text fields, prefer `set-property ... text`; for deterministic button activation, prefer -`activate-node`. Use `click-node` when pointer behavior is material. Use TestFX or native automation -when exact key-code or input-method behavior matters. +Writable Stage properties: `x`, `y`, `width`, `height`, `opacity`, `title`, `maximized`, +`iconified`, `alwaysOnTop`, and `resizable`. `--type` may be `number`, `boolean`, or `string`; +it is inferred if omitted. Numeric values must be finite, dimensions positive, and opacity within +0 through 1. Boolean values must be `true` or `false`. Read `window-details` again to confirm the +window manager applied a change. + +`close-window` sends `WINDOW_CLOSE_REQUEST`, allowing application handlers to save state, prompt, +or cancel closing. The result has `closeRequested`, `closed`, and `handlerPending`. A consumed +request succeeds with `closed: false`; a modal confirmation reports `handlerPending: true`. +Closing the last window or exiting from a handler may terminate the JVM before it replies. +Verify lifecycle effects in the application's state/logs; a lost connection alone does not prove +either success or failure. + +--- + +## close-popup / embedded overlays + +```bash +# Obtain the popup ID after opening it; use its current stageId from stages +$CLI $PID close-popup --stageId "$POPUP_ID" +``` + +This hides only the specified `PopupWindow` (for example, `ContextMenu` or `Tooltip`) and rejects +normal Stages. It does not generically dismiss embedded application overlays. + +For AtlantaFX `ModalPane`, prefer its close control or the application's configured background +click / Escape handler. If those are unavailable, inspect the actual node's `display` property +before using the fallback: + +```bash +MODAL_ID=$($CLI $PID find-nodes --type ModalPane --visible-only \ + | jq -er 'if length == 1 then .[0].nodeId else error("ModalPane is not unique") end') +$CLI $PID node-details "$MODAL_ID" --filter display +$CLI $PID set-property "$MODAL_ID" display false --type boolean +$CLI $PID node-details "$MODAL_ID" --filter display +``` + +Direct property changes can bypass application close callbacks. Verify the overlay and underlying +view state afterwards. Other overlay libraries may expose different properties; inspect them +before modifying anything. + +--- + +## scroll-node / scroll-to-index + +```bash +$CLI $PID scroll-node "$LIST_NODE_ID" --dy 500 +$CLI $PID scroll-to-index "$LIST_NODE_ID" --index 10 +$CLI $PID scroll-node "$LIST_NODE_ID" --align bottom +$CLI $PID find-nodes --stageId "$STAGE_ID" --visible-only --text "Target item" +``` + +Supported containers: standard `ListView`, `TableView`, `ScrollPane`, JavaFX `VirtualFlow`, +Flowless `VirtualFlow`, and Flowless `VirtualizedScrollPane` wrapping one. Flowless must be present +in the target; the agent does not install it. Positive `--dx` / `--dy` move right/down; negative +values move left/up. `--align` accepts `top`, `bottom`, `left`, or `right` and cannot be combined +with pixel deltas. For standard virtual flows, the edge must match their scrolling orientation. + +`--index` is zero-based and must refer to an existing item. `ScrollPane` has no index navigation. +Scrolling lays out newly visible cells; rerun `find-nodes` afterwards, because recycled or newly +created cells can change their node IDs. `refreshRequired: true` also marks this in the response. --- @@ -169,7 +267,7 @@ Capture a PNG of a node or one specific window scene. A window can be a Stage or popup. ```bash -# Full scene of the primary window (default max: 1280x720) +# Full scene of the primary window (source resolution by default) $CLI $PID screenshot ./screenshot.png # Specific node @@ -184,15 +282,20 @@ $CLI $PID screenshot ./popup.png --stageId $POPUP_ID # Custom maximum dimensions (scales proportionally if exceeded) $CLI $PID screenshot ./hd.png --maxWidth 1920 --maxHeight 1080 $CLI $PID screenshot ./small.png --maxWidth 640 --maxHeight 480 +$CLI $PID screenshot ./original.png --no-limit +# 0 disables one axis's resize limit +$CLI $PID screenshot ./wide.png --maxWidth 0 --maxHeight 1080 ``` **Output:** ```json { - "success": true, - "savedPath": "./screenshot.png", + "savedPath": "/tmp/fxgraph/screenshot.png", "width": 1280, "height": 720, + "sourceWidth": 1920, + "sourceHeight": 1080, + "scaled": true, "mimeType": "image/png", "targetType": "scenegraph", "targetId": "123456" @@ -200,9 +303,14 @@ $CLI $PID screenshot ./small.png --maxWidth 640 --maxHeight 480 ``` - Output format is always PNG. -- The path is relative to the working directory of the CLI process. -- **Default max size is 1280x720 (HD).** Images exceeding these limits are scaled down proportionally. -- `--maxWidth` and `--maxHeight` are optional. Set both to override the default HD limit. +- Prefer an absolute path; relative paths resolve from the target JVM's working directory. +- The default preserves the JavaFX snapshot's source resolution. Explicit positive `--maxWidth` + / `--maxHeight` resize proportionally when exceeded; omitted or `0` means no limit for that axis. +- `--no-limit` explicitly disables both resize limits and cannot be combined with dimension flags. +- The source safety limit is **8192px per dimension and 16777216 pixels total**, including when + `--no-limit` is used. Oversized sources are rejected before snapshot allocation; capture a smaller + node or window. Dimension flags resize the output and do not bypass source limits. +- `sourceWidth`, `sourceHeight`, and `scaled` show whether the saved image was resized. - Aspect ratio is always preserved during scaling. - Window screenshots use `Scene.snapshot`; node screenshots use `Node.snapshot`. - A popup ID captures that popup scene by itself. A Stage snapshot does not composite separately @@ -242,7 +350,6 @@ $CLI $PID capture-video /tmp/popup.mp4 --stageId $POPUP_ID --durationSeconds 5 **Output:** ```json { - "success": true, "savedPath": "/tmp/clip.mp4", "width": 1280, "height": 720, @@ -287,7 +394,7 @@ NODE_ID=$($CLI $PID find-nodes --type TextField \ $CLI $PID select-node $NODE_ID # PowerShell: & $CLI $PID select-node $NODE_ID -# 4. Take a before screenshot (auto-scaled to HD by default) +# 4. Take a before screenshot at source resolution $CLI $PID screenshot ./before.png # 5. Set property directly @@ -318,8 +425,8 @@ $CLI $PID select-node 0 - Always verify changes with a screenshot or `node-details` query. - `select-node` before and after changes provides a quick visual confirmation. -- `click-node` uses synthetic input by default without moving the system pointer or requesting focus. -- Use `click-node --mode robot` only when native pointer behavior is part of the verification. +- `click-node` uses synthetic input without moving the system pointer or requesting window focus. +- Input commands require no OS input permissions and do not send native OS shortcuts. - Use `activate-node` when only a `ButtonBase` action needs verification. - For text input fields, prefer `set-property text "..."` for reliability over `type-key` character-by-character. - Prefer locating and clicking the submit control over relying on synthetic Enter behavior. diff --git a/skills/fxgraph/references/troubleshooting.md b/skills/fxgraph/references/troubleshooting.md index e21fd46..ec193f7 100644 --- a/skills/fxgraph/references/troubleshooting.md +++ b/skills/fxgraph/references/troubleshooting.md @@ -68,6 +68,56 @@ For popup verification, retain both forms of evidence when useful: - a property or in-process test assertion proving behavior; - a native composite screenshot proving final appearance. +## A node exists but cannot be clicked + +Read `effectiveVisible` and `visibilityReason`, not only the node's own `visible` flag. +An invisible or transparent ancestor, collapsed container, zero-size node, or clipping can make +the node unavailable. Use `node-details --ancestors` to locate the containing component, +then expand it or scroll it into view. `find-nodes --visible-only` excludes these unavailable nodes. +This geometry check does not detect sibling or other-window occlusion. + +`type` searches JavaFX Node classes and their superclasses. It cannot find a non-Node FXML +controller or MenuItem itself. Search an open menu's `.menu-item` rendering nodes or text. +Reacquire popup and cell node IDs after reopening a menu or scrolling virtualized content. + +## A menu action returns `handlerPending=true` + +The action was dispatched and its handler entered a nested JavaFX event loop, often `showAndWait()`. +Locate the dialog with `stages`, inspect its nodes, and continue there. After closing it, verify +the resulting application state. Do not repeat the original action while its handler is pending. + +For standard submenus, click the visible submenu rendering node. The command also dispatches +the mouse-enter event needed by the standard menu skin; it does not move the OS pointer. + +## A modal or popup must be closed + +Use `close-window ` for a Stage: it sends the close-request event and respects cancellation. +Use `close-popup ` to hide a PopupWindow. A component embedded inside a Scene is neither. +For AtlantaFX ModalPane, inspect the `display` property and set it to false: + +```bash +$CLI $PID find-nodes --type ModalPane +$CLI $PID node-details "$NODE_ID" --filter display +$CLI $PID set-property "$NODE_ID" display false --type boolean +``` + +For other embedded components, inspect writable properties or activate their close button. +JavaFX synthetic keys do not invoke OS-native Cmd+W or Cmd+Q; use the window command for a close request. + +## A screenshot is too small or exceeds the safety limit + +The screenshot default preserves source dimensions. Remove explicit `--maxWidth` / `--maxHeight`, +or use `--no-limit` (cannot be combined with those flags). Zero means unlimited on that axis. +Check `sourceWidth`, `sourceHeight`, and `scaled` in the result. +Source dimensions over 8192px on either axis or 16,777,216 pixels total are rejected before allocation, +even with a resize limit. Capture a smaller node in that case. Video defaults remain 1280×720. + +## A CLI option reports a missing value + +Options require a nonempty value and cannot consume the following `--option` as that value. +For example, `--stageId "" --depth 2` reports a stageId value error with usage. Retrieve the ID again. +The positional property value in `set-property text ""` can still intentionally clear text. + ## A command produces excessive or malformed output - Remove `--json`; JSON is always enabled.