summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt
blob: 5020acbd04de0e89e9e1a8ef92f4c4345cfad4bc (plain)
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.facet

import com.intellij.facet.ui.*
import com.intellij.ide.actions.ShowSettingsUtilImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.HoverHyperlinkLabel
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.ThreeStateCheckBox
import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.compiler.configuration.*
import org.jetbrains.kotlin.idea.core.util.onTextChange
import org.jetbrains.kotlin.idea.roots.invalidateProjectRoots
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.*
import javax.swing.border.EmptyBorder
import kotlin.reflect.full.findAnnotation

class KotlinFacetEditorGeneralTab(
    private val configuration: KotlinFacetConfiguration,
    private val editorContext: FacetEditorContext,
    private val validatorsManager: FacetValidatorsManager
) : FacetEditorTab() {

    //TODO(auskov): remove this hack as far as inconsistent equals in JdkPlatform is removed
    // what it actually does: if version of JVM target platform changed the TargetPlatform will
    // return true because equals in JvmPlatform is declared in the following way:
    // override fun equals(other: Any?): Boolean = other is JdkPlatform
    class TargetPlatformWrapper(val targetPlatform: TargetPlatform) {

        override fun equals(other: Any?): Boolean {
            if (other is TargetPlatformWrapper) {
                if (this.targetPlatform == other.targetPlatform) {
                    return if (this.targetPlatform.size == 1) {
                        this.targetPlatform.componentPlatforms.singleOrNull() === other.targetPlatform.componentPlatforms.singleOrNull()
                    } else {
                        true
                    }
                }
            }
            return false
        }
    }

    class EditorComponent(
        private val project: Project,
        private val configuration: KotlinFacetConfiguration?
    ) : JPanel(BorderLayout()) {
        private val isMultiEditor: Boolean
            get() = configuration == null

        private lateinit var editableCommonArguments: CommonCompilerArguments
        private lateinit var editableJvmArguments: K2JVMCompilerArguments
        private lateinit var editableJsArguments: K2JSCompilerArguments
        private lateinit var editableCompilerSettings: CompilerSettings

        lateinit var compilerConfigurable: KotlinCompilerConfigurableTab
            private set

        lateinit var useProjectSettingsCheckBox: ThreeStateCheckBox

        // UI components related to MPP target platforms
        lateinit var targetPlatformSelectSingleCombobox: ComboBox<TargetPlatformWrapper>
        lateinit var dependsOnLabel: JLabel
        lateinit var targetPlatformWrappers: List<TargetPlatformWrapper>
        lateinit var targetPlatformLabel: JLabel //JTextField?
        var targetPlatformsCurrentlySelected: TargetPlatform? = null

        private lateinit var projectSettingsLink: HoverHyperlinkLabel

        private fun FormBuilder.addTargetPlatformComponents(): FormBuilder {
            return if (configuration?.settings?.mppVersion?.isHmpp == true) {
                targetPlatformLabel.toolTipText =
                    KotlinBundle.message("facet.label.text.the.project.is.imported.from.external.build.system.and.could.not.be.edited")
                this.addLabeledComponent(
                    KotlinBundle.message("facet.label.text.selected.target.platforms"), targetPlatformLabel)
            } else {
                this.addLabeledComponent(
                    KotlinBundle.message("facet.label.text.target.platform"), targetPlatformSelectSingleCombobox)
            }
        }

        // Fixes sorting of JVM versions.
        // JVM 1.6, ... JVM 1.8 -> unchanged
        // JVM 9 -> JVM 1.9
        // JVM 11.. -> unchanged
        // As result JVM 1.8 < JVM 1.9 < JVM 11 in UI representation
        private fun unifyJvmVersion(version: String) = if (version.equals("JVM 9")) "JVM 1.9" else version

        // Returns maxRowsCount for combobox.
        // Try to show whole the list at one, but do not show more than 15 elements at once. 10 elements returned otherwise
        private fun targetPlatformsComboboxRowsCount(targetPlatforms: Int) =
            if (targetPlatforms <= 15) {
                targetPlatforms
            } else {
                10
            }

        fun initialize() {
            if (isMultiEditor) {
                editableCommonArguments = object : CommonCompilerArguments() {}
                editableJvmArguments = K2JVMCompilerArguments()
                editableJsArguments = K2JSCompilerArguments()
                editableCompilerSettings = CompilerSettings()
            } else {
                editableCommonArguments = configuration!!.settings.compilerArguments!!
                editableJvmArguments = editableCommonArguments as? K2JVMCompilerArguments
                    ?: Kotlin2JvmCompilerArgumentsHolder.getInstance(project).settings.unfrozen()
                editableJsArguments = editableCommonArguments as? K2JSCompilerArguments
                    ?: Kotlin2JsCompilerArgumentsHolder.getInstance(project).settings.unfrozen()
                editableCompilerSettings = configuration.settings.compilerSettings!!
            }

            compilerConfigurable = KotlinCompilerConfigurableTab(
                project,
                editableCommonArguments,
                editableJsArguments,
                editableJvmArguments,
                editableCompilerSettings,
                null,
                false,
                isMultiEditor
            )

            useProjectSettingsCheckBox = ThreeStateCheckBox(KotlinBundle.message("facet.checkbox.text.use.project.settings")).apply { isThirdStateEnabled = isMultiEditor }
            dependsOnLabel = JLabel()

            targetPlatformWrappers = CommonPlatforms.allDefaultTargetPlatforms.sortedBy { unifyJvmVersion(it.oldFashionedDescription) }
                .map { TargetPlatformWrapper(it) }
            targetPlatformLabel = JLabel() //JTextField()? targetPlatformLabel.isEditable = false
            targetPlatformSelectSingleCombobox =
                ComboBox(targetPlatformWrappers.toTypedArray()).apply {
                    setRenderer(object : DefaultListCellRenderer() {
                        override fun getListCellRendererComponent(
                            list: JList<*>?,
                            value: Any?,
                            index: Int,
                            isSelected: Boolean,
                            cellHasFocus: Boolean
                        ): Component {
                            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply {
                                text =
                                    (value as? TargetPlatformWrapper)?.targetPlatform?.componentPlatforms?.singleOrNull()
                                        ?.oldFashionedDescription
                                        ?: KotlinBundle.message("facet.text.multiplatform")
                            }
                        }
                    })
                }
            targetPlatformSelectSingleCombobox.maximumRowCount =
                targetPlatformsComboboxRowsCount(targetPlatformWrappers.size)
            projectSettingsLink = HoverHyperlinkLabel(KotlinBundle.message("facet.link.text.edit.project.settings")).apply {
                addHyperlinkListener {
                    ShowSettingsUtilImpl.showSettingsDialog(project, compilerConfigurable.id, "")
                    if (useProjectSettingsCheckBox.isSelected) {
                        updateCompilerConfigurable()
                    }
                }
            }

            val contentPanel = FormBuilder
                .createFormBuilder()
                .addComponent(JPanel(BorderLayout()).apply {
                    add(useProjectSettingsCheckBox, BorderLayout.WEST)
                    add(projectSettingsLink, BorderLayout.EAST)
                }).addTargetPlatformComponents()
                .addComponent(dependsOnLabel)
                .addComponent(compilerConfigurable.createComponent()!!.apply {
                    border = null
                })
                .panel
                .apply {
                    border = EmptyBorder(10, 10, 10, 10)
                }
            add(contentPanel, BorderLayout.NORTH)

            useProjectSettingsCheckBox.addActionListener {
                updateCompilerConfigurable()
            }
            targetPlatformSelectSingleCombobox.addActionListener {
                updateCompilerConfigurable()
            }
        }

        internal fun updateCompilerConfigurable() {
            val useProjectSettings = useProjectSettingsCheckBox.isSelected
            compilerConfigurable.setTargetPlatform(getChosenPlatform()?.idePlatformKind)
            compilerConfigurable.setEnabled(!useProjectSettings)
            if (useProjectSettings) {
                compilerConfigurable.commonCompilerArguments = KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.unfrozen()
                compilerConfigurable.k2jvmCompilerArguments = Kotlin2JvmCompilerArgumentsHolder.getInstance(project).settings.unfrozen()
                compilerConfigurable.k2jsCompilerArguments = Kotlin2JsCompilerArgumentsHolder.getInstance(project).settings.unfrozen()
                compilerConfigurable.compilerSettings = KotlinCompilerSettings.getInstance(project).settings.unfrozen()
            } else {
                compilerConfigurable.commonCompilerArguments = editableCommonArguments
                compilerConfigurable.k2jvmCompilerArguments = editableJvmArguments
                compilerConfigurable.k2jsCompilerArguments = editableJsArguments
                compilerConfigurable.compilerSettings = editableCompilerSettings
            }
            compilerConfigurable.reset()
        }

        fun getChosenPlatform(): TargetPlatform? {
            return if (configuration?.settings?.mppVersion?.isHmpp == true) {
                targetPlatformsCurrentlySelected
            } else {
                targetPlatformSelectSingleCombobox.selectedItemTyped?.targetPlatform
            }
        }
    }

    inner class ArgumentConsistencyValidator : FacetEditorValidator() {
        override fun check(): ValidationResult {
            val platform = editor.getChosenPlatform() ?: return ValidationResult(
                KotlinBundle.message("facet.error.text.at.least.one.target.platform.should.be.selected"))
            val primaryArguments = platform.createArguments {
                editor.compilerConfigurable.applyTo(
                    this,
                    this as? K2JVMCompilerArguments ?: K2JVMCompilerArguments(),
                    this as? K2JSCompilerArguments ?: K2JSCompilerArguments(),
                    CompilerSettings()
                )
            }
            val argumentClass = primaryArguments.javaClass
            val additionalArguments = argumentClass.newInstance().apply {
                parseCommandLineArguments(splitArgumentString(editor.compilerConfigurable.additionalArgsOptionsField.text), this)
                validateArguments(errors)?.let { message -> return ValidationResult(message) }
            }
            val emptyArguments = argumentClass.newInstance()
            val fieldNamesToCheck = when {
                platform.isJvm() -> jvmUIExposedFields
                platform.isJs() -> jsUIExposedFields
                platform.isCommon() -> metadataUIExposedFields
                else -> commonUIExposedFields
            }

            val propertiesToCheck = collectProperties(argumentClass.kotlin, false).filter { it.name in fieldNamesToCheck }
            val overridingArguments = ArrayList<String>()
            val redundantArguments = ArrayList<String>()
            for (property in propertiesToCheck) {
                val additionalValue = property.get(additionalArguments)
                if (additionalValue != property.get(emptyArguments)) {
                    val argumentInfo = property.findAnnotation<Argument>() ?: continue
                    val addTo = if (additionalValue != property.get(primaryArguments)) overridingArguments else redundantArguments
                    addTo += "<strong>" + argumentInfo.value.first() + "</strong>"
                }
            }
            if (overridingArguments.isNotEmpty() || redundantArguments.isNotEmpty()) {
                @NlsSafe
                val message = buildString {
                    if (overridingArguments.isNotEmpty()) {
                        append(
                            KotlinBundle.message(
                                "facet.text.following.arguments.override.facet.settings",
                                overridingArguments.joinToString()
                            )
                        )
                    }
                    if (redundantArguments.isNotEmpty()) {
                        if (isNotEmpty()) {
                            append("<br/>")
                        }
                        append(
                            KotlinBundle.message("facet.text.following.arguments.are.redundant", redundantArguments.joinToString()))
                    }
                }
                return ValidationResult(message)
            }

            return ValidationResult.OK
        }
    }

    private var isInitialized = false
    val editor by lazy { EditorComponent(editorContext.project, configuration) }

    private var enableValidation = false

    private fun onLanguageLevelChanged() {
        with(editor.compilerConfigurable) {
            onLanguageLevelChanged(selectedLanguageVersionView)
        }
    }

    private fun JTextField.validateOnChange() {
        onTextChange { doValidate() }
    }

    private fun AbstractButton.validateOnChange() {
        addChangeListener { doValidate() }
    }

    private fun JComboBox<*>.validateOnChange() {
        addActionListener { doValidate() }
    }

    private fun validateOnce(body: () -> Unit) {
        enableValidation = false
        body()
        enableValidation = true
        doValidate()
    }

    private fun doValidate() {
        if (enableValidation) {
            validatorsManager.validate()
        }
    }

    fun initializeIfNeeded() {
        if (isInitialized) return

        editor.initialize()

        for (creator in KotlinFacetValidatorCreator.EP_NAME.getExtensions()) {
            validatorsManager.registerValidator(creator.create(editor, validatorsManager, editorContext))
        }

        validatorsManager.registerValidator(ArgumentConsistencyValidator())

        with(editor.compilerConfigurable) {
            reportWarningsCheckBox.validateOnChange()
            additionalArgsOptionsField.textField.validateOnChange()
            generateSourceMapsCheckBox.validateOnChange()
            outputPrefixFile.textField.validateOnChange()
            outputPostfixFile.textField.validateOnChange()
            outputDirectory.textField.validateOnChange()
            copyRuntimeFilesCheckBox.validateOnChange()
            moduleKindComboBox.validateOnChange()
            languageVersionComboBox.addActionListener {
                onLanguageLevelChanged()
                doValidate()
            }
            apiVersionComboBox.validateOnChange()
        }
        editor.targetPlatformSelectSingleCombobox.validateOnChange()

        editor.updateCompilerConfigurable()
        isInitialized = true

        reset()
    }

    override fun onTabEntering() {
        initializeIfNeeded()
    }

    override fun isModified(): Boolean {
        if (!isInitialized) return false
        if (editor.useProjectSettingsCheckBox.isSelected != configuration.settings.useProjectSettings) return true
        val chosenPlatform = editor.getChosenPlatform()
        if (chosenPlatform != configuration.settings.targetPlatform) return true

        // work-around for hacked equals in JvmPlatform
        if (!configuration.settings.mppVersion.isHmpp) {
            if (configuration.settings.targetPlatform?.let { TargetPlatformWrapper(it) } != editor.targetPlatformSelectSingleCombobox
                    .selectedItemTyped) {
                return true
            }
        }
        val chosenSingle = chosenPlatform?.componentPlatforms?.singleOrNull()
        if (chosenSingle != null && chosenSingle == JvmPlatforms.defaultJvmPlatform) {
            if (chosenSingle !== configuration.settings.targetPlatform) {
                return true
            }
        }
        return !editor.useProjectSettingsCheckBox.isSelected && editor.compilerConfigurable.isModified
    }

    override fun reset() {
        if (!isInitialized) return
        validateOnce {
            editor.useProjectSettingsCheckBox.isSelected = configuration.settings.useProjectSettings
            editor.targetPlatformsCurrentlySelected = configuration.settings.targetPlatform
            editor.targetPlatformLabel.text =
                editor.targetPlatformsCurrentlySelected?.componentPlatforms?.map { it.oldFashionedDescription.trim() }?.joinToString(", ")
                    ?: "<none>"
            editor.dependsOnLabel.isVisible = configuration.settings.dependsOnModuleNames.isNotEmpty()
            editor.dependsOnLabel.text =
                KotlinBundle.message("facets.editor.general.tab.label.depends.on.0", configuration.settings.dependsOnModuleNames.joinToString())

            editor.targetPlatformSelectSingleCombobox.selectedItem = configuration.settings.targetPlatform?.let {
                val index = editor.targetPlatformWrappers.indexOf(TargetPlatformWrapper(it))
                if (index >= 0) {
                    editor.targetPlatformWrappers[index]
                } else {
                    null
                }
            }
            editor.compilerConfigurable.reset()
            editor.updateCompilerConfigurable()
        }
    }

    override fun apply() {
        initializeIfNeeded()
        validateOnce {
            editor.compilerConfigurable.apply()
            with(configuration.settings) {
                useProjectSettings = editor.useProjectSettingsCheckBox.isSelected
                editor.getChosenPlatform()?.let {
                    if (it != targetPlatform ||
                        isModified // work-around due to hacked equals
                    ) {
                        val platformArguments = when {
                            it.isJvm() -> editor.compilerConfigurable.k2jvmCompilerArguments
                            it.isJs() -> editor.compilerConfigurable.k2jsCompilerArguments
                            else -> null
                        }
                        compilerArguments = it.createArguments {
                            if (platformArguments != null) {
                                mergeBeans(platformArguments, this)
                            }
                            copyInheritedFields(compilerArguments!!, this)
                        }
                    }
                }
                configuration.settings.targetPlatform = editor.getChosenPlatform()
                updateMergedArguments()

                // Force code analysis with modified settings
                runWriteAction { editorContext.project.invalidateProjectRoots() }
            }
        }
    }

    override fun getDisplayName() = KotlinBundle.message("facet.name.general")

    override fun createComponent(): JComponent {
        return editor
    }

    override fun disposeUIResources() {
        if (isInitialized) {
            editor.compilerConfigurable.disposeUIResources()
        }
    }
}

@Suppress("UNCHECKED_CAST")
val <T> ComboBox<T>.selectedItemTyped: T?
    get() = selectedItem as T?