<commit_before>/*
 * Copyright 2000-2009 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.codeInsight.daemon.impl.analysis;

import com.intellij.application.options.XmlSettings;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.completion.ExtendedTagInsertHandler;
import com.intellij.codeInsight.daemon.XmlErrorMessages;
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass;
import com.intellij.codeInsight.daemon.impl.VisibleHighlightingPassFactory;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.HintAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.cache.impl.id.IdTableBuilding;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlToken;
import com.intellij.ui.components.JBList;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import com.intellij.xml.impl.schema.XmlNSDescriptorImpl;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Maxim.Mossienko
 */
public class CreateNSDeclarationIntentionFix implements HintAction, LocalQuickFix {

  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.analysis.CreateNSDeclarationIntentionFix");

  private final String myNamespacePrefix;
  private final PsiElement myElement;
  private final XmlFile myFile;
  private final XmlToken myToken;

  @Nullable
  public static CreateNSDeclarationIntentionFix createFix(@NotNull final PsiElement element, @NotNull final String namespacePrefix) {
    PsiFile file = element.getContainingFile();
    return file instanceof XmlFile ? new CreateNSDeclarationIntentionFix(element, namespacePrefix, (XmlFile)file) : null;
  }

  protected CreateNSDeclarationIntentionFix(@NotNull final PsiElement element,
                                            @NotNull final String namespacePrefix, XmlFile containingFile) {
    this(element, namespacePrefix, null, containingFile);
  }

  public CreateNSDeclarationIntentionFix(final PsiElement element,
                                         final String namespacePrefix,
                                         @Nullable final XmlToken token,
                                         XmlFile containingFile) {
    myNamespacePrefix = namespacePrefix;
    myElement = element;
    myFile = containingFile;
    myToken = token;
  }

  @NotNull
  public String getText() {
    final String alias = StringUtil.capitalize(XmlExtension.getExtension(myFile).getNamespaceAlias(myFile));
    return XmlErrorMessages.message("create.namespace.declaration.quickfix", alias);
  }

  @NotNull
  public String getName() {
    return getFamilyName();
  }

  @NotNull
  public String getFamilyName() {
    return getText();
  }

  public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiFile containingFile = descriptor.getPsiElement().getContainingFile();
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    final PsiFile file = editor != null ? PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()):null;
    if (file == null || file.getVirtualFile() != containingFile.getVirtualFile()) return;

    try { invoke(project, editor, containingFile); } catch (IncorrectOperationException ex) {
      LOG.error(ex);
    }
  }

  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return myElement.isValid();
  }

  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    if (!myElement.isValid() || !CodeInsightUtilBase.prepareFileForWrite(file)) return;

    final Set<String> set = XmlExtension.getExtension(file).guessUnboundNamespaces(myElement, (XmlFile)file);
    final String[] namespaces = ArrayUtil.toStringArray(set);
    Arrays.sort(namespaces);

    runActionOverSeveralAttributeValuesAfterLettingUserSelectTheNeededOne(
      namespaces,
      project,
      new StringToAttributeProcessor() {
        public void doSomethingWithGivenStringToProduceXmlAttributeNowPlease(@NotNull final String namespace) throws IncorrectOperationException {
          String prefix = myNamespacePrefix;
          if (StringUtil.isEmpty(prefix)) {
            final XmlExtension extension = XmlExtension.getExtension(myFile);
            final XmlFile xmlFile = extension.getContainingFile(myElement);
            prefix = ExtendedTagInsertHandler.getPrefixByNamespace(xmlFile, namespace);
            if (StringUtil.isNotEmpty(prefix)) {
              ExtendedTagInsertHandler.qualifyWithPrefix(prefix, myElement);
              return;
            } else {
              prefix = ExtendedTagInsertHandler.suggestPrefix(xmlFile, namespace);
              if (StringUtil.isEmpty(prefix)) {
                HintManager.getInstance().showInformationHint(editor, "Namespace not found");
                return;
              }
              ExtendedTagInsertHandler.qualifyWithPrefix(prefix, myElement);
              PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
            }
          }<commit_msg>test fixed<commit_after>/*
 * Copyright 2000-2009 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.codeInsight.daemon.impl.analysis;

import com.intellij.application.options.XmlSettings;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.completion.ExtendedTagInsertHandler;
import com.intellij.codeInsight.daemon.XmlErrorMessages;
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass;
import com.intellij.codeInsight.daemon.impl.VisibleHighlightingPassFactory;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.HintAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.cache.impl.id.IdTableBuilding;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlToken;
import com.intellij.ui.components.JBList;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import com.intellij.xml.impl.schema.XmlNSDescriptorImpl;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Maxim.Mossienko
 */
public class CreateNSDeclarationIntentionFix implements HintAction, LocalQuickFix {

  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.analysis.CreateNSDeclarationIntentionFix");

  private final String myNamespacePrefix;
  private final PsiElement myElement;
  private final XmlFile myFile;
  private final XmlToken myToken;

  @Nullable
  public static CreateNSDeclarationIntentionFix createFix(@NotNull final PsiElement element, @NotNull final String namespacePrefix) {
    PsiFile file = element.getContainingFile();
    return file instanceof XmlFile ? new CreateNSDeclarationIntentionFix(element, namespacePrefix, (XmlFile)file) : null;
  }

  protected CreateNSDeclarationIntentionFix(@NotNull final PsiElement element,
                                            @NotNull final String namespacePrefix, XmlFile containingFile) {
    this(element, namespacePrefix, null, containingFile);
  }

  public CreateNSDeclarationIntentionFix(final PsiElement element,
                                         final String namespacePrefix,
                                         @Nullable final XmlToken token,
                                         XmlFile containingFile) {
    myNamespacePrefix = namespacePrefix;
    myElement = element;
    myFile = containingFile;
    myToken = token;
  }

  @NotNull
  public String getText() {
    final String alias = StringUtil.capitalize(XmlExtension.getExtension(myFile).getNamespaceAlias(myFile));
    return XmlErrorMessages.message("create.namespace.declaration.quickfix", alias);
  }

  @NotNull
  public String getName() {
    return getFamilyName();
  }

  @NotNull
  public String getFamilyName() {
    return getText();
  }

  public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiFile containingFile = descriptor.getPsiElement().getContainingFile();
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    final PsiFile file = editor != null ? PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()):null;
    if (file == null || file.getVirtualFile() != containingFile.getVirtualFile()) return;

    try { invoke(project, editor, containingFile); } catch (IncorrectOperationException ex) {
      LOG.error(ex);
    }
  }

  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return myElement.isValid();
  }

  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    if (!myElement.isValid() || !CodeInsightUtilBase.prepareFileForWrite(file)) return;

    final Set<String> set = XmlExtension.getExtension(file).guessUnboundNamespaces(myElement, (XmlFile)file);
    final String[] namespaces = ArrayUtil.toStringArray(set);
    Arrays.sort(namespaces);

    runActionOverSeveralAttributeValuesAfterLettingUserSelectTheNeededOne(
      namespaces,
      project,
      new StringToAttributeProcessor() {
        public void doSomethingWithGivenStringToProduceXmlAttributeNowPlease(@NotNull final String namespace) throws IncorrectOperationException {
          String prefix = myNamespacePrefix;
          if (StringUtil.isEmpty(prefix)) {
            final XmlExtension extension = XmlExtension.getExtension(myFile);
            final XmlFile xmlFile = extension.getContainingFile(myElement);
            prefix = ExtendedTagInsertHandler.getPrefixByNamespace(xmlFile, namespace);
            if (StringUtil.isNotEmpty(prefix)) {
              ExtendedTagInsertHandler.qualifyWithPrefix(prefix, myElement);
              return;
            } else {
              prefix = ExtendedTagInsertHandler.suggestPrefix(xmlFile, namespace);
              if (StringUtil.isEmpty(prefix)) {
                if (!ApplicationManager.getApplication().isUnitTestMode()) {
                  HintManager.getInstance().showInformationHint(editor, "Namespace not found");
                }
                return;
              }
              ExtendedTagInsertHandler.qualifyWithPrefix(prefix, myElement);
              PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
            }
          }
{'fraction_non_alphanumeric': 0.08614676339285714, 'fraction_numerical': 0.0016741071428571428, 'mean_word_length': 4.240131578947368, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 24}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4337783', 'n_tokens_mistral': 3927, 'n_tokens_neox': 3831, 'n_words': 839}