Skip to content

Commit

Permalink
docs(ide-note): add instructions for dynamically attaching actions to…
Browse files Browse the repository at this point in the history
… ContextMenu

Adds explanation and code examples for two methods of attaching custom actions to the ContextMenu. The first method is a standard approach, while the second method demonstrates how to dynamically attach actions for plugins that do not expose such functionality directly, using SonarLint as a reference.
  • Loading branch information
phodal committed Nov 29, 2024
1 parent d1858c1 commit 99b426f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
39 changes: 39 additions & 0 deletions docs/development/ide-note.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ fun getCommitWorkflowUi(): CommitWorkflowUi? {

## 自定义 ContextMenu 位置


### 普通方式

参考:`ShireActionStartupActivity` 中的实现,如:`attachTerminalAction` 方法

```kotlin
Expand All @@ -120,3 +123,39 @@ private fun attachTerminalAction() {

1. 从 ActionManager 中获取目标 ActionGroup
2. 将自定义 Action 添加到目标 ActionGroup 中

### 动态方式

对于不对外提供的插件,可以尝试监听是否有对应的事件,诸如 Sonarlint 使用的是 Panel,因此可以监听 Panel 的事件,然后动态添加 Action。

```kotlin
private fun attachSonarLintAction(project: Project) {
project.messageBus.connect().subscribe(ToolWindowManagerListener.TOPIC, SonarLintToolWindowListener(project));
}
```

对应的 `SonarLintToolWindowListener` 实现如下:

```kotlin
class SonarLintToolWindowListener(private val project: Project) : ToolWindowManagerListener {
override fun toolWindowShown(toolWindow: ToolWindow) {
if (toolWindow.id != "SonarLint") return

val action = ActionManager.getInstance().getAction("ShireSonarLintAction")

val contentManager = toolWindow.contentManager
val content = contentManager.getContent(0) ?: return

val simpleToolWindowPanel = content.component as? SimpleToolWindowPanel
val actionToolbar = simpleToolWindowPanel?.toolbar?.components?.get(0) as? ActionToolbar ?: return
val actionGroup = actionToolbar.actionGroup as? DefaultActionGroup

if (actionGroup?.containsAction(action) == false) {
actionGroup.add(action)
}
}
}
```



Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ class ShireActionStartupActivity : ProjectActivity {
class SonarLintToolWindowListener(private val project: Project) : ToolWindowManagerListener {
override fun toolWindowShown(toolWindow: ToolWindow) {
if (toolWindow.id != "SonarLint") return

val action = ActionManager.getInstance().getAction("ShireSonarLintAction")

val contentManager = toolWindow.contentManager
Expand Down

0 comments on commit 99b426f

Please sign in to comment.