Wizard: save some setting values in UI

#KT-35585 fixed
This commit is contained in:
Ilya Kirillov
2020-02-20 18:42:44 +03:00
parent 9e47d0b33c
commit 05022109fc
20 changed files with 138 additions and 27 deletions
@@ -29,7 +29,9 @@ class IdeWizard(
private val allSettings = plugins.flatMap { it.declaredSettings }
init {
context.settingContext.initPluginSettings(allSettings)
with(valuesReadingContext) {
context.settingContext.apply { initPluginSettings(allSettings) }
}
}
var projectPath by setting(StructurePlugin::projectPath.reference)
@@ -65,6 +65,7 @@ class NewProjectWizardModuleBuilder : EmptyModuleBuilder() {
override fun isAvailable(): Boolean = ExperimentalFeatures.NewWizard.isEnabled
private var wizardContext: WizardContext? = null
private var pomValuesAreSet: Boolean = false
override fun getModuleType(): ModuleType<*> = NewProjectWizardModuleType()
override fun getParentGroup(): String = KotlinTemplatesFactory.KOTLIN_PARENT_GROUP_NAME
@@ -137,7 +138,7 @@ class NewProjectWizardModuleBuilder : EmptyModuleBuilder() {
}
private fun updateProjectNameAndPomDate(settingsStep: SettingsStep) {
if (wizard.artifactId != null || wizard.groupId != null) return
if (pomValuesAreSet) return
val suggestedProjectName = with(wizard.valuesReadingContext) {
ProjectTemplatesPlugin::template.settingValue.suggestedProjectName.decapitalize()
}
@@ -150,6 +151,7 @@ class NewProjectWizardModuleBuilder : EmptyModuleBuilder() {
wizard.artifactId = suggestedProjectName
wizard.groupId = suggestGroupId()
pomValuesAreSet = true
}
private fun suggestGroupId(): String {
@@ -0,0 +1,25 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard.wizard.service
import com.intellij.ide.util.PropertiesComponent
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService
class IdeaSettingSavingWizardService : SettingSavingWizardService, IdeaWizardService {
override fun saveSettingValue(settingPath: String, settingValue: String) = runWriteAction {
PropertiesComponent.getInstance().setValue(PATH_PREFIX + settingPath, settingValue)
}
override fun getSettingValue(settingPath: String): String? = runReadAction {
PropertiesComponent.getInstance().getValue(PATH_PREFIX + settingPath)
}
companion object {
private const val PATH_PREFIX = "NewKotlinWizard."
}
}
@@ -16,7 +16,8 @@ object IdeaServices {
val PROJECT_INDEPENDENT: List<IdeaWizardService> = listOf(
IdeaFileSystemWizardService(),
IdeaBuildSystemAvailabilityWizardService(),
IdeaKotlinVersionProviderService()
IdeaKotlinVersionProviderService(),
IdeaSettingSavingWizardService()
)
fun createScopeDependent(project: Project, model: ModifiableModuleModel) = listOf(
@@ -8,14 +8,13 @@ package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.openapi.Disposable
import org.jetbrains.kotlin.tools.projectWizard.core.ValuesReadingContext
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.DynamicComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.FocusableComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.label
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.panel
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ErrorAwareComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.IdeaBasedComponentValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator
import java.awt.BorderLayout
import javax.swing.JComponent
@@ -83,5 +82,7 @@ abstract class UIComponent<V : Any>(
}
}
fun <V : Any> UIComponent<V>.valueForSetting(setting: Setting<V, SettingType<V>>): V? =
setting.defaultValue ?: getUiValue()
fun <V : Any> ValuesReadingContext.valueForSetting(
uiComponent: UIComponent<V>,
setting: Setting<V, SettingType<V>>
): V? = setting.savedOrDefaultValue ?: uiComponent.getUiValue()
@@ -55,8 +55,10 @@ class TemplatesSubStep(valuesReadingContext: ValuesReadingContext) :
// TODO do not use settingContext directly
context.settingContext[setting] = value
}
allModules().forEach { module ->
module.initDefaultValuesForSettings(valuesReadingContext.context)
read {
allModules().forEach { module ->
module.apply { initDefaultValuesForSettings(valuesReadingContext.context) }
}
}
}
@@ -41,7 +41,7 @@ class ModulesEditorComponent(
}
)
private val model = TargetsModel(tree, ::value, valuesReadingContext.context, uiEditorUsagesStats)
private val model = TargetsModel(tree, ::value, valuesReadingContext, uiEditorUsagesStats)
override fun onInit() {
super.onInit()
@@ -2,6 +2,7 @@ package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.secondStep.modulesEdi
import org.jetbrains.kotlin.idea.projectWizard.UiEditorUsageStats
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.ValuesReadingContext
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@@ -12,7 +13,7 @@ import kotlin.reflect.KMutableProperty0
class TargetsModel(
private val tree: ModulesEditorTree,
private val value: KMutableProperty0<List<Module>?>,
private val context: Context,
private val valuesReadingContext: ValuesReadingContext,
private val uiEditorUsagesStats: UiEditorUsageStats
) {
private val root get() = tree.model.root as DefaultMutableTreeNode
@@ -64,7 +65,9 @@ class TargetsModel(
fun add(module: Module) {
uiEditorUsagesStats.modulesCreated++
module.initDefaultValuesForSettings(context)
with(valuesReadingContext) {
module.apply { initDefaultValuesForSettings(context) }
}
addToTheTree(module, modifyValue = true, parent = tree.selectedNode ?: root)
}
@@ -65,7 +65,7 @@ class VersionSettingComponent(
override fun onInit() {
super.onInit()
val values = setting.defaultValue?.let(::listOf).orEmpty()
val values = read { setting.savedOrDefaultValue }?.let(::listOf).orEmpty()
comboBox.model = DefaultComboBoxModel<Version>(values.toTypedArray())
if (values.isNotEmpty()) {
@@ -24,7 +24,7 @@ abstract class UIComponentDelegatingSettingComponent<V : Any, T : SettingType<V>
override fun onInit() {
super.onInit()
if (value == null) {
uiComponent.valueForSetting(setting)?.let { value = it }
read { valueForSetting(uiComponent, setting) }?.let { value = it }
}
value?.let(uiComponent::updateUiValue)
}
@@ -10,7 +10,11 @@ import kotlin.reflect.full.isSubclassOf
data class ParsingState(
val idToTemplate: Map<String, Template>,
val settingValues: Map<SettingReference<*, *>, Any>
) : ComputeContextState
) : ComputeContextState {
companion object {
val EMPTY = ParsingState(emptyMap(), emptyMap())
}
}
fun ParsingState.withSettings(newSettings: List<Pair<SettingReference<*, *>, Any>>) =
copy(settingValues = settingValues + newSettings)
@@ -3,6 +3,7 @@ package org.jetbrains.kotlin.tools.projectWizard.core
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager
import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
@@ -40,5 +41,14 @@ open class ValuesReadingContext(
val <V : Any, T : SettingType<V>> PluginSettingReference<V, T>.pluginSetting: Setting<V, T>
get() = context.settingContext.getPluginSetting(this)
fun <V : Any> Setting<V, SettingType<V>>.getSavedValueForSetting(): V? {
if (!isSavable || this !is PluginSetting<*, *>) return null
val serializer = type.serializer.safeAs<SerializerImpl<V>>() ?: return null
val savedValue = service<SettingSavingWizardService>()!!.getSettingValue(path) ?: return null
return serializer.fromString(savedValue)
}
val <V : Any> Setting<V, SettingType<V>>.savedOrDefaultValue: V?
get() = getSavedValueForSetting() ?: defaultValue
}
@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.templates.Template
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
@@ -130,9 +131,9 @@ class SettingContext(val onUpdated: (SettingReference<*, *>) -> Unit) {
onUpdated(reference)
}
fun initPluginSettings(settings: List<PluginSetting<*, *>>) {
fun ValuesReadingContext.initPluginSettings(settings: List<PluginSetting<*, *>>) {
for (setting in settings) {
setting.defaultValue?.let { values[setting.path] = it }
setting.savedOrDefaultValue?.let { values[setting.path] = it }
}
}
@@ -167,9 +168,9 @@ interface Setting<out V : Any, out T : SettingType<V>> : Entity, ActivityChecker
val title: String
val defaultValue: V?
val isRequired: Boolean
val isSavable: Boolean
var neededAtPhase: GenerationPhase
val type: T
}
data class InternalSetting<out V : Any, out T : SettingType<V>>(
@@ -178,6 +179,7 @@ data class InternalSetting<out V : Any, out T : SettingType<V>>(
override val defaultValue: V?,
override val activityChecker: Checker,
override val isRequired: Boolean,
override val isSavable: Boolean,
override var neededAtPhase: GenerationPhase,
override val validator: SettingValidator<@UnsafeVariance V>,
override val type: T
@@ -205,6 +207,7 @@ abstract class SettingBuilder<V : Any, T : SettingType<V>>(
) {
var checker: Checker = Checker.ALWAYS_AVAILABLE
var defaultValue: V? = null
var isSavable: Boolean = false
protected var validator = SettingValidator<V> { ValidationResult.OK }
@@ -225,6 +228,7 @@ abstract class SettingBuilder<V : Any, T : SettingType<V>>(
defaultValue = defaultValue,
activityChecker = checker,
isRequired = defaultValue == null,
isSavable = isSavable,
neededAtPhase = neededAtPhase,
validator = validator,
type = type
@@ -232,14 +236,26 @@ abstract class SettingBuilder<V : Any, T : SettingType<V>>(
}
sealed class SettingSerializer<out V : Any>()
object NonSerializable : SettingSerializer<Nothing>()
data class SerializerImpl<V : Any>(
val fromString: (String) -> V?,
val toString: (V) -> String = Any::toString
) : SettingSerializer<V>()
sealed class SettingType<out V : Any> {
abstract fun parse(context: ParsingContext, value: Any, name: String): TaskResult<V>
open val serializer: SettingSerializer<V> = NonSerializable
}
object StringSettingType : SettingType<String>() {
override fun parse(context: ParsingContext, value: Any, name: String) =
value.parseAs<String>(name)
override val serializer: SettingSerializer<String> = SerializerImpl(fromString = { it })
class Builder(
path: String,
private val title: String,
@@ -257,6 +273,8 @@ object BooleanSettingType : SettingType<Boolean>() {
override fun parse(context: ParsingContext, value: Any, name: String) =
value.parseAs<Boolean>(name)
override val serializer: SettingSerializer<Boolean> = SerializerImpl(fromString = { it.toBoolean() })
class Builder(
path: String,
title: String,
@@ -264,6 +282,7 @@ object BooleanSettingType : SettingType<Boolean>() {
) : SettingBuilder<Boolean, BooleanSettingType>(path, title, neededAtPhase) {
override val type = BooleanSettingType
}
}
class DropDownSettingType<V : DisplayableSettingItem>(
@@ -277,6 +296,12 @@ class DropDownSettingType<V : DisplayableSettingItem>(
}
}
override val serializer: SettingSerializer<V> = SerializerImpl(fromString = { value ->
ComputeContext.runInComputeContextWithState(ParsingState.EMPTY) {
parser.parse(this, value, "")
}.asNullable?.first
})
class Builder<V : DisplayableSettingItem>(
path: String,
title: String,
@@ -292,7 +317,8 @@ class DropDownSettingType<V : DisplayableSettingItem>(
}
}
typealias DropDownSettingTypeFilter<V> = ValuesReadingContext.(SettingReference<V, DropDownSettingType<V>>, V) -> Boolean
typealias DropDownSettingTypeFilter <V> =
ValuesReadingContext.(SettingReference<V, DropDownSettingType<V>>, V) -> Boolean
class ValueSettingType<V : Any>(
@@ -375,6 +401,8 @@ object PathSettingType : SettingType<Path>() {
}
}
override val serializer: SettingSerializer<Path> = SerializerImpl(fromString = { Paths.get(it) })
class Builder(
path: String,
private val title: String,
@@ -0,0 +1,16 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard.core.service
interface SettingSavingWizardService : WizardService {
fun saveSettingValue(settingPath: String, settingValue: String)
fun getSettingValue(settingPath: String): String?
}
class SettingSavingWizardServiceImpl : SettingSavingWizardService, IdeaIndependentWizardService {
override fun saveSettingValue(settingPath: String, settingValue: String) {}
override fun getSettingValue(settingPath: String): String? = null
}
@@ -11,7 +11,8 @@ object Services {
BuildSystemAvailabilityWizardServiceImpl(),
DummyFileFormattingService(),
KotlinVersionProviderServiceImpl(),
RunConfigurationsServiceImpl()
RunConfigurationsServiceImpl(),
SettingSavingWizardServiceImpl()
)
}
@@ -16,6 +16,7 @@ class StructurePlugin(context: Context) : Plugin(context) {
val name by stringSetting("Name", GenerationPhase.PROJECT_GENERATION)
val groupId by stringSetting("Group ID", GenerationPhase.PROJECT_GENERATION) {
isSavable = true
shouldNotBeBlank()
validate(StringValidators.shouldBeValidIdentifier("Group ID", setOf('.', '_')))
}
@@ -24,6 +24,7 @@ import java.nio.file.Path
abstract class BuildSystemPlugin(context: Context) : Plugin(context) {
val type by enumSetting<BuildSystemType>("Build System", GenerationPhase.FIRST_STEP) {
isSavable = true
filter = { _, type ->
val service = service<BuildSystemAvailabilityWizardService>()!!
service.isAvailable(type)
@@ -44,7 +44,7 @@ class Module(
is ModuleConfiguratorSetting<Any, SettingType<Any>> -> setting.reference.notRequiredSettingValue
else -> null
}
?: setting.defaultValue
?: setting.savedOrDefaultValue
?: return@map ValidationResult.ValidationError("${setting.title.capitalize()} should not be blank")
(setting.validator as SettingValidator<Any>).validate(this@settingValidator, value)
}.fold()
@@ -54,7 +54,7 @@ class Module(
org.jetbrains.kotlin.tools.projectWizard.templates.withSettingsOf(module) {
template.settings.map { setting ->
val value = setting.reference.notRequiredSettingValue
?: setting.defaultValue
?: setting.savedOrDefaultValue
?: return@map ValidationResult.ValidationError("${setting.title.capitalize()} should not be blank")
(setting.validator as SettingValidator<Any>).validate(this@settingValidator, value)
}.fold()
@@ -86,9 +86,9 @@ class Module(
else -> "Module"
}
fun initDefaultValuesForSettings(context: Context) {
configurator.safeAs<ModuleConfiguratorWithSettings>()?.initDefaultValuesFor(this, context)
template?.initDefaultValuesFor(this, context)
fun ValuesReadingContext.initDefaultValuesForSettings(context: Context) {
configurator.safeAs<ModuleConfiguratorWithSettings>()?.initDefaultValuesFor(this@Module, context)
template?.apply { initDefaultValuesFor(this@Module, context) }
}
companion object {
@@ -71,10 +71,10 @@ abstract class Template : SettingsOwner {
open val settings: List<TemplateSetting<*, *>> = emptyList()
open val interceptionPoints: List<InterceptionPoint<Any>> = emptyList()
fun initDefaultValuesFor(module: Module, context: Context) {
fun ValuesReadingContext.initDefaultValuesFor(module: Module, context: Context) {
withSettingsOf(module) {
settings.forEach { setting ->
val defaultValue = setting.defaultValue ?: return@forEach
val defaultValue = setting.savedOrDefaultValue ?: return@forEach
context.settingContext[setting.reference] = defaultValue
}
}
@@ -4,6 +4,7 @@ import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager
import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
abstract class Wizard(createPlugins: PluginsCreator, val servicesManager: ServicesManager, private val isUnitTestMode: Boolean) {
@@ -28,6 +29,18 @@ abstract class Wizard(createPlugins: PluginsCreator, val servicesManager: Servic
}
}.fold(ValidationResult.OK, ValidationResult::and).toResult()
private fun ValuesReadingContext.saveSettingValues(phases: Set<GenerationPhase>) {
for (setting in pluginSettings) {
if (setting.neededAtPhase !in phases) continue
if (!setting.isSavable) continue
val serializer = setting.type.serializer as? SerializerImpl<Any> ?: continue
service<SettingSavingWizardService>()!!.saveSettingValue(
setting.path,
serializer.toString(setting.reference.settingValue)
)
}
}
open fun apply(
services: List<WizardService>,
phases: Set<GenerationPhase>,
@@ -36,6 +49,7 @@ abstract class Wizard(createPlugins: PluginsCreator, val servicesManager: Servic
context.checkAllRequiredSettingPresent(phases).ensure()
val taskRunningContext = TaskRunningContext(context, servicesManager.withServices(services), isUnitTestMode)
taskRunningContext.validate(phases).ensure()
taskRunningContext.saveSettingValues(phases)
val (tasksSorted) = context.sortTasks().map { tasks ->
tasks.groupBy { it.phase }.toList().sortedBy { it.first }.flatMap { it.second }
}