<commit_before>/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.copyright

import com.intellij.configurationStore.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentAdapter
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.project.isDirectoryBased
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.attribute
import com.intellij.util.element
import com.maddyhome.idea.copyright.CopyrightProfile
import com.maddyhome.idea.copyright.actions.UpdateCopyrightProcessor
import com.maddyhome.idea.copyright.options.LanguageOptions
import com.maddyhome.idea.copyright.options.Options
import com.maddyhome.idea.copyright.util.FileTypeUtil
import com.maddyhome.idea.copyright.util.NewFileTracker
import org.jdom.Element
import java.util.*
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Function

private const val DEFAULT = "default"
private const val MODULE2COPYRIGHT = "module2copyright"
private const val COPYRIGHT = "copyright"
private const val ELEMENT = "element"
private const val MODULE = "module"

private val LOG = Logger.getInstance(CopyrightManager::class.java)

@State(name = "CopyrightManager", storages = arrayOf(Storage(value = "copyright/profiles_settings.xml", exclusive = true)))
class CopyrightManager(private val project: Project, schemeManagerFactory: SchemeManagerFactory) : PersistentStateComponent<Element> {
  companion object {
    @JvmStatic
    fun getInstance(project: Project) = project.service<CopyrightManager>()
  }

  private var defaultCopyrightName: String? = null

  var defaultCopyright: CopyrightProfile?
    get() = defaultCopyrightName?.let { schemeManager.findSchemeByName(it)?.scheme }
    set(value) {
      defaultCopyrightName = value?.name
    }

  val scopeToCopyright = LinkedHashMap<String, String>()
  val options = Options()

  val schemeManager = schemeManagerFactory.create("copyright", object : LazySchemeProcessor<SchemeWrapper<CopyrightProfile>, SchemeWrapper<CopyrightProfile>>() {
    override fun createScheme(dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
                              name: String,
                              attributeProvider: Function<String, String?>): SchemeWrapper<CopyrightProfile> {
      return LazySchemeWrapper(name, dataHolder, schemeWriter)
    }

    override fun getState(scheme: SchemeWrapper<CopyrightProfile>) = scheme.schemeState

    override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml")
  }, isUseOldFileNameSanitize = true)

  init {
    val app = ApplicationManager.getApplication()
    if (project.isDirectoryBased || !app.isUnitTestMode) {
      schemeManager.loadSchemes()
    }
  }

  fun mapCopyright(scopeName: String, copyrightProfileName: String) {
    scopeToCopyright.put(scopeName, copyrightProfileName)
  }

  fun unmapCopyright(scopeName: String) {
    scopeToCopyright.remove(scopeName)
  }

  fun hasAnyCopyrights(): Boolean {
    return defaultCopyrightName != null || !scopeToCopyright.isEmpty()
  }

  override fun getState(): Element? {
    val result = Element("settings")
    try {
      if (!scopeToCopyright.isEmpty()) {
        val map = Element(MODULE2COPYRIGHT)
        for ((scopeName, profileName) in scopeToCopyright) {
          map.element(ELEMENT)
              .attribute(MODULE, scopeName)
              .attribute(COPYRIGHT, profileName)
        }
        result.addContent(map)
      }

      options.writeExternal(result)
    }
    catch (e: WriteExternalException) {
      LOG.error(e)
      return null
    }

    defaultCopyrightName?.let {
      result.setAttribute(DEFAULT, it)
    }

    return wrapState(result)
  }

  override fun loadState(state: Element) {
    val data = state.getChild("settings")
    val moduleToCopyright = data.getChild(MODULE2COPYRIGHT)
    if (moduleToCopyright != null) {<commit_msg>scheme-based copyright manager — ipr<commit_after>/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.copyright

import com.intellij.configurationStore.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentAdapter
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.project.isDirectoryBased
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.attribute
import com.intellij.util.element
import com.maddyhome.idea.copyright.CopyrightProfile
import com.maddyhome.idea.copyright.actions.UpdateCopyrightProcessor
import com.maddyhome.idea.copyright.options.LanguageOptions
import com.maddyhome.idea.copyright.options.Options
import com.maddyhome.idea.copyright.util.FileTypeUtil
import com.maddyhome.idea.copyright.util.NewFileTracker
import org.jdom.Element
import java.util.*
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Function

private const val DEFAULT = "default"
private const val MODULE2COPYRIGHT = "module2copyright"
private const val COPYRIGHT = "copyright"
private const val ELEMENT = "element"
private const val MODULE = "module"

private val LOG = Logger.getInstance(CopyrightManager::class.java)

@State(name = "CopyrightManager", storages = arrayOf(Storage(value = "copyright/profiles_settings.xml", exclusive = true)))
class CopyrightManager(private val project: Project, schemeManagerFactory: SchemeManagerFactory) : PersistentStateComponent<Element> {
  companion object {
    @JvmStatic
    fun getInstance(project: Project) = project.service<CopyrightManager>()
  }

  private var defaultCopyrightName: String? = null

  var defaultCopyright: CopyrightProfile?
    get() = defaultCopyrightName?.let { schemeManager.findSchemeByName(it)?.scheme }
    set(value) {
      defaultCopyrightName = value?.name
    }

  val scopeToCopyright = LinkedHashMap<String, String>()
  val options = Options()

  private val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider()

  val schemeManager = schemeManagerFactory.create("copyright", object : LazySchemeProcessor<SchemeWrapper<CopyrightProfile>, SchemeWrapper<CopyrightProfile>>() {
    override fun createScheme(dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
                              name: String,
                              attributeProvider: Function<String, String?>): SchemeWrapper<CopyrightProfile> {
      return LazySchemeWrapper(name, dataHolder, schemeWriter)
    }

    override fun getState(scheme: SchemeWrapper<CopyrightProfile>) = scheme.schemeState

    override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml")
  }, isUseOldFileNameSanitize = true, streamProvider = schemeManagerIprProvider)

  init {
    val app = ApplicationManager.getApplication()
    if (project.isDirectoryBased || !app.isUnitTestMode) {
      schemeManager.loadSchemes()
    }
  }

  fun mapCopyright(scopeName: String, copyrightProfileName: String) {
    scopeToCopyright.put(scopeName, copyrightProfileName)
  }

  fun unmapCopyright(scopeName: String) {
    scopeToCopyright.remove(scopeName)
  }

  fun hasAnyCopyrights(): Boolean {
    return defaultCopyrightName != null || !scopeToCopyright.isEmpty()
  }

  override fun getState(): Element? {
    val result = Element("settings")
    try {
      schemeManagerIprProvider?.writeState(result)

      if (!scopeToCopyright.isEmpty()) {
        val map = Element(MODULE2COPYRIGHT)
        for ((scopeName, profileName) in scopeToCopyright) {
          map.element(ELEMENT)
              .attribute(MODULE, scopeName)
              .attribute(COPYRIGHT, profileName)
        }
        result.addContent(map)
      }

      options.writeExternal(result)
    }
    catch (e: WriteExternalException) {
      LOG.error(e)
      return null
    }

    defaultCopyrightName?.let {
      result.setAttribute(DEFAULT, it)
    }

    return wrapState(result)
  }

  override fun loadState(state: Element) {
    val data: Element? = state.getChild("settings")

    schemeManagerIprProvider?.let {
      it.load(data)
      schemeManager.reload()
    }

    if (data == null) {
      return
    }

    val moduleToCopyright = data.getChild(MODULE2COPYRIGHT)
    if (moduleToCopyright != null) {
{'fraction_non_alphanumeric': 0.08939635333687378, 'fraction_numerical': 0.0028323597096831295, 'mean_word_length': 4.576999012833169, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1071587', 'n_tokens_mistral': 3128, 'n_tokens_neox': 3065, 'n_words': 701}