-
Notifications
You must be signed in to change notification settings - Fork 1
/
CreateElementAction.kt
198 lines (173 loc) · 8.53 KB
/
CreateElementAction.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*
* Copyright (c) 2010-2022 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
*/
package org.eclipse.scout.sdk.s2i.element
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil
import com.intellij.ide.ui.newItemPopup.NewItemPopupUtil
import com.intellij.ide.ui.newItemPopup.NewItemSimplePopupPanel
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.PackageIndex
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiNameHelper
import com.intellij.psi.util.PsiUtil
import com.intellij.util.concurrency.AppExecutorUtil
import org.eclipse.scout.sdk.core.log.SdkLog
import org.eclipse.scout.sdk.core.s.environment.IEnvironment
import org.eclipse.scout.sdk.core.s.environment.IProgress
import org.eclipse.scout.sdk.core.s.util.ITier
import org.eclipse.scout.sdk.core.s.util.ScoutTier
import org.eclipse.scout.sdk.core.util.Strings.capitalize
import org.eclipse.scout.sdk.s2i.EclipseScoutBundle
import org.eclipse.scout.sdk.s2i.environment.IdeaEnvironment
import org.eclipse.scout.sdk.s2i.util.SourceFolderHelper
import org.eclipse.scout.sdk.s2i.util.compat.CompatibilityMethodCaller
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.function.BiConsumer
abstract class CreateElementAction<OP : BiConsumer<IEnvironment, IProgress>>(val text: String, val description: String) : AnAction(text, description, null) {
override fun actionPerformed(e: AnActionEvent) {
val dataContext = e.dataContext
val view = LangDataKeys.IDE_VIEW.getData(dataContext) ?: return
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val dir = view.orChooseDirectory ?: return
createPopup(dir).showCenteredInCurrentWindow(project)
}
override fun update(e: AnActionEvent) {
super.update(e)
val dataContext = e.dataContext
val presentation = e.presentation
val file = LangDataKeys.VIRTUAL_FILE.getData(dataContext)
if (file == null || !file.isDirectory) {
presentation.isEnabledAndVisible = false
return
}
val project = CommonDataKeys.PROJECT.getData(dataContext)
if (project == null) {
presentation.isEnabledAndVisible = false
return
}
val fileIndex = ProjectFileIndex.getInstance(project)
val sourceFolder = fileIndex.getSourceFolder(file)
if (sourceFolder == null || sourceFolder.isTestSource) {
presentation.isEnabledAndVisible = false
return
}
presentation.isEnabledAndVisible = true
}
protected fun createPopup(dir: PsiDirectory): JBPopup {
val contentPanel = NewItemSimplePopupPanel()
val nameField = contentPanel.textField
val popup = NewItemPopupUtil.createNewItemPopup(text, contentPanel, nameField)
contentPanel.setApplyAction {
val name = nameField.text
val errorMessage = validateInput(dir, name)
if (errorMessage != null) {
contentPanel.setError(errorMessage)
} else {
createElement(name, dir)
popup.closeOk(it)
}
}
return popup
}
protected fun validateInput(dir: PsiDirectory, name: String): String? {
var errorMessage: String? = null
val psiNameHelper = PsiNameHelper.getInstance(dir.project)
val level = PsiUtil.getLanguageLevel(dir)
if (!psiNameHelper.isQualifiedName(name) || !psiNameHelper.isQualifiedName(name.lowercase(Locale.US)) || name.contains("$")) {
errorMessage = EclipseScoutBundle.message("invalid.java.qualified.name")
}
val shortName = StringUtil.getShortName(name)
if (HighlightClassUtil.isRestrictedIdentifier(shortName, level)) {
errorMessage = JavaErrorBundle.message("restricted.identifier", shortName)
}
return errorMessage
}
protected fun createElement(name: String, dir: PsiDirectory) {
IdeaEnvironment.callInIdeaEnvironment(dir.project, description) { env, progress ->
val project = env.project
val fileIndex = ProjectFileIndex.getInstance(project)
val sourceFolder = fileIndex.getSourceFolder(dir.virtualFile)
if (sourceFolder?.isTestSource == true) {
SdkLog.warning("No source folder could be determined for location '{}'", dir.virtualFile)
return@callInIdeaEnvironment null
}
val sourceFolderHelper = SourceFolderHelper(project, sourceFolder!!) { env.findClasspathEntry(it) }
if (!validateSourceFolderHelper(sourceFolderHelper, dir)) {
return@callInIdeaEnvironment null
}
var pkg = getPackageNameByDirectory(dir.virtualFile, fileIndex, project)
val lastIndexOf = name.lastIndexOf(".")
if (lastIndexOf > 0) pkg += "." + name.substring(0, lastIndexOf)
val elementName = capitalize(name.substring(lastIndexOf + 1, name.length)).toString()
if (pkg.isNullOrEmpty()) {
SdkLog.warning("No package provided")
return@callInIdeaEnvironment null
}
val op = sourceFolderHelper.classpathEntry()?.javaEnvironment()?.let {
EclipseScoutBundle.elementCreationManager()
.createOperation(operationClass(), elementName, pkg, sourceFolderHelper, it)
} ?: return@callInIdeaEnvironment null
op.accept(env, progress)
return@callInIdeaEnvironment psiClassToOpen(op)
}.thenAccept {
it.get()?.let { psiSupplier -> openPsiInEditorLater(dir.project, psiSupplier) }
}.exceptionally {
SdkLog.error("Error creating {}.", text, it)
null
}
}
protected fun getPackageNameByDirectory(dir: VirtualFile, fileIndex: ProjectFileIndex, project: Project): String? {
// can be removed as soon as IJ 2022.3 is the latest supported version
return CompatibilityMethodCaller<String?>()
.withCandidate(PackageIndex::class.java.name, "getPackageNameByDirectory", VirtualFile::class.java.name) {
// for IJ >= 2022.3: use PackageIndex
it.invoke(PackageIndex.getInstance(project), dir)
}
.withCandidate(ProjectFileIndex::class.java.name, "getPackageNameByDirectory", VirtualFile::class.java.name) {
// for IJ <= 2022.2 use ProjectFileIndex
it.invoke(fileIndex, dir)
}.invoke()
}
protected open fun openPsiInEditorLater(project: Project, psiSupplier: () -> PsiClass?) {
AppExecutorUtil.getAppScheduledExecutorService().schedule({
DumbService.getInstance(project).smartInvokeLater {
val psi = psiSupplier() ?: return@smartInvokeLater
EditorHelper.openInEditor(psi, true, true)
}
}, 400, TimeUnit.MILLISECONDS)
}
protected open fun validateSourceFolderHelper(sourceFolderHelper: SourceFolderHelper, dir: PsiDirectory): Boolean {
if (sourceFolderHelper.classpathEntry() == null) {
SdkLog.warning("No source folder could be determined for location '{}'", dir.virtualFile)
return false
}
if (!startTiers().contains(sourceFolderHelper.tier())) {
SdkLog.warning("Location '{}' is not a {} module", dir.virtualFile, startTiers().joinToString())
return false
}
return true
}
protected open fun startTiers(): Collection<ITier<*>> = listOf(ScoutTier.Client, ScoutTier.Shared, ScoutTier.Server)
protected abstract fun operationClass(): Class<OP>
protected abstract fun psiClassToOpen(op: OP): () -> PsiClass?
}