Пример #1
0
 private static UsageTarget[] getTargetsForSQLReference(
     PsiElement psiElement, SQLRefReference sqlRefReferenceForID) {
   final List<PsiElement> primaryElementList = Lists.newArrayList();
   final List<PsiElement> secondaryElementList = Lists.newArrayList();
   if (psiElement.getLanguage() instanceof JavaLanguage) {
     for (final SmartPsiElementPointer<PsiElement> elementPointer :
         sqlRefReferenceForID.getXmlSmartPointersElements()) {
       primaryElementList.add(elementPointer.getElement());
     }
   } else if (psiElement.getLanguage() instanceof XMLLanguage) {
     for (final SmartPsiElementPointer<PsiElement> elementPointer :
         sqlRefReferenceForID.getClassSmartPointersElements()) {
       primaryElementList.add(elementPointer.getElement());
     }
     for (final SmartPsiElementPointer<PsiElement> elementPointer :
         sqlRefReferenceForID.getUtilClassSmartPointersElements().values()) {
       secondaryElementList.add(elementPointer.getElement());
     }
   }
   PsiElement[] primeElements = new PsiElement[primaryElementList.size()];
   PsiElement[] secondaryElements = new PsiElement[secondaryElementList.size()];
   primaryElementList.toArray(primeElements);
   secondaryElementList.toArray(secondaryElements);
   //		return new UsageTarget[]{new PsiElement2UsageTargetAdapter(primeElements[0])};
   //		return new UsageTarget[new PsiElement2UsageTargetAdapter(primeElements[0],new
   // FindUsagesOptions(psiElement.getProject())};
   return new UsageTarget[] {
     new PsiElement2UsageTargetComposite(
         primeElements, secondaryElements, new FindUsagesOptions(psiElement.getProject()))
   };
 }
 @Override
 public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
   return PsiUtil.isLanguageLevel5OrHigher(file)
       && myMethodCall.getElement() != null
       && myMethodCall.getElement().isValid()
       && myMethodCall.getElement().getMethodExpression().getQualifierExpression() == null
       && file.getManager().isInProject(file)
       && !(candidates == null ? candidates = getMethodsToImport() : candidates).isEmpty();
 }
 private static boolean doCreate(
     Project project,
     Editor editor,
     PsiParameter[] parameters,
     SmartPsiElementPointer constructorPointer,
     ParameterInfoImpl[] parameterInfos,
     HashMap<PsiField, String> fields) {
   PsiMethod constructor = (PsiMethod) constructorPointer.getElement();
   assert constructor != null;
   PsiParameter[] newParameters = constructor.getParameterList().getParameters();
   if (newParameters == parameters) return false; // user must have canceled dialog
   boolean created = false;
   // do not introduce assignment in chanined constructor
   if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
     for (PsiField field : fields.keySet()) {
       final String defaultParamName = fields.get(field);
       PsiParameter parameter =
           findParamByName(defaultParamName, field.getType(), newParameters, parameterInfos);
       if (parameter == null) {
         continue;
       }
       notNull(project, field, parameter);
       AssignFieldFromParameterAction.addFieldAssignmentStatement(
           project, field, parameter, editor);
       created = true;
     }
   }
   return created;
 }
  void doRefresh(boolean currentBuilderOnly) {
    if (currentBuilderOnly) LOG.assertTrue(myCurrentViewType != null);

    if (!isValidBase()) return;

    if (getCurrentBuilder() == null) return; // seems like we are in the middle of refresh already

    final Ref<Pair<List<Object>, List<Object>>> storedInfo =
        new Ref<Pair<List<Object>, List<Object>>>();
    if (myCurrentViewType != null) {
      final HierarchyTreeBuilder builder = getCurrentBuilder();
      storedInfo.set(builder.storeExpandedAndSelectedInfo());
    }

    final PsiElement element = mySmartPsiElementPointer.getElement();
    if (element == null || !isApplicableElement(element)) {
      return;
    }
    final String currentViewType = myCurrentViewType;

    if (currentBuilderOnly) {
      Disposer.dispose(getCurrentBuilder());
    } else {
      disposeBuilders();
    }
    setHierarchyBase(element);
    validate();
    ApplicationManager.getApplication()
        .invokeLater(
            () -> {
              changeView(currentViewType);
              final HierarchyTreeBuilder builder = getCurrentBuilder();
              builder.restoreExpandedAndSelectedInfo(storedInfo.get());
            });
  }
  final boolean isValidBase() {
    if (PsiDocumentManager.getInstance(myProject).getUncommittedDocuments().length > 0) {
      return myCachedIsValidBase;
    }

    final PsiElement element = mySmartPsiElementPointer.getElement();
    myCachedIsValidBase = element != null && isApplicableElement(element) && element.isValid();
    return myCachedIsValidBase;
  }
    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor)
        throws IncorrectOperationException {
      final PsiElement element = descriptor.getPsiElement();

      PsiExpression exp = expression.getElement();
      if (exp == null) return;
      element.replace(exp);
    }
Пример #7
0
 @Override
 public boolean isAvailable(
     @NotNull Project project,
     @NotNull PsiFile file,
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement) {
   final PsiModifierList myModifierList = (PsiModifierList) startElement;
   PsiVariable variable = myVariable == null ? null : myVariable.getElement();
   return myModifierList.isValid()
       && myModifierList.getManager().isInProject(myModifierList)
       && myModifierList.hasExplicitModifier(myModifier) != myShouldHave
       && (variable == null || variable.isValid());
 }
Пример #8
0
  public static void change(UsageInfo[] usages, TypeMigrationLabeler labeler, Project project) {
    final List<SmartPsiElementPointer<PsiNewExpression>> newExpressionsToCheckDiamonds =
        new SmartList<>();
    final TypeMigrationLabeler.MigrationProducer producer = labeler.createMigratorFor(usages);

    final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(project);
    List<UsageInfo> nonCodeUsages = new ArrayList<>();
    for (UsageInfo usage : usages) {
      if (((TypeMigrationUsageInfo) usage).isExcluded()) continue;
      final PsiElement element = usage.getElement();
      if (element instanceof PsiVariable
          || element instanceof PsiMember
          || element instanceof PsiExpression
          || element instanceof PsiReferenceParameterList) {
        producer.change(
            (TypeMigrationUsageInfo) usage,
            expression ->
                newExpressionsToCheckDiamonds.add(
                    smartPointerManager.createSmartPsiElementPointer(expression)));
      } else {
        nonCodeUsages.add(usage);
      }
    }

    for (SmartPsiElementPointer<PsiNewExpression> newExpressionPointer :
        newExpressionsToCheckDiamonds) {
      final PsiNewExpression newExpression = newExpressionPointer.getElement();
      if (newExpression != null) {
        labeler.postProcessNewExpression(newExpression);
      }
    }

    for (UsageInfo usageInfo : nonCodeUsages) {
      final PsiElement element = usageInfo.getElement();
      if (element != null) {
        final PsiReference reference = element.getReference();
        if (reference != null) {
          final Object target = producer.getConversion(usageInfo);
          if (target instanceof PsiMember) {
            try {
              reference.bindToElement((PsiElement) target);
            } catch (IncorrectOperationException ignored) {
            }
          }
        }
      }
    }

    producer.flush();
  }
 private void doImport(final String qName) {
   ApplicationManager.getApplication()
       .runWriteAction(
           () -> {
             final PsiElement element = myReference.getElement();
             SmartPsiElementPointer<PsiElement> pointer =
                 SmartPointerManager.getInstance(element.getProject())
                     .createSmartPsiElementPointer(element);
             ImportUtils.doImport(element, qName, true);
             PsiElement newElement = pointer.getElement();
             if (newElement != null) {
               ImportUtils.insertUseNamespaceIfNeeded(qName, newElement);
             }
           });
 }
 @Override
 public void run() {
   PsiDocumentManager.getInstance(myProject).commitAllDocuments();
   myUsageView.close();
   ArrayList<PsiElement> elements = new ArrayList<PsiElement>();
   for (SmartPsiElementPointer pointer : myPointers) {
     final PsiElement element = pointer.getElement();
     if (element != null) {
       elements.add(element);
     }
   }
   if (!elements.isEmpty()) {
     SafeDeleteHandler.invoke(myProject, PsiUtilCore.toPsiElementArray(elements), true);
   }
 }
  public final void changeView(@NotNull final String typeName) {
    myCurrentViewType = typeName;

    final PsiElement element = mySmartPsiElementPointer.getElement();
    if (element == null || !isApplicableElement(element)) {
      return;
    }

    if (myContent != null) {
      final String displayName = getContentDisplayName(typeName, element);
      if (displayName != null) {
        myContent.setDisplayName(displayName);
      }
    }

    myCardLayout.show(myTreePanel, typeName);

    if (!myBuilders.containsKey(typeName)) {
      try {
        setWaitCursor();
        // create builder
        final JTree tree = myType2TreeMap.get(typeName);
        final DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode(""));
        tree.setModel(model);

        final HierarchyTreeStructure structure = createHierarchyTreeStructure(typeName, element);
        if (structure == null) {
          return;
        }
        final Comparator<NodeDescriptor> comparator = getComparator();
        final HierarchyTreeBuilder builder =
            new HierarchyTreeBuilder(myProject, tree, model, structure, comparator);

        myBuilders.put(typeName, builder);
        Disposer.register(this, builder);
        Disposer.register(builder, () -> myBuilders.remove(typeName));

        final HierarchyNodeDescriptor descriptor = structure.getBaseDescriptor();
        builder.select(descriptor, () -> builder.expand(descriptor, null));
      } finally {
        restoreCursor();
      }
    }

    getCurrentTree().requestFocus();
  }
 @NotNull
 @Override
 protected List<PsiField> getMembersToImport(boolean applicableOnly) {
   final Project project = myRef.getProject();
   PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
   final PsiJavaCodeReferenceElement element = myRef.getElement();
   String name = element != null ? element.getReferenceName() : null;
   if (name == null) return Collections.emptyList();
   final StaticMembersProcessor<PsiField> processor =
       new StaticMembersProcessor<PsiField>(element) {
         @Override
         protected boolean isApplicable(PsiField field, PsiElement place) {
           final PsiType expectedType = getExpectedType();
           return expectedType == null
               || TypeConversionUtil.isAssignable(expectedType, field.getType());
         }
       };
   cache.processFieldsWithName(name, processor, element.getResolveScope(), null);
   return processor.getMembersToImport(applicableOnly);
 }
  // returns null if cannot find, empty Pair if all elements have been changed
  @Nullable
  private PsiElement[] restorePsiElements(SearchData searchData, final boolean showErrorMessage) {
    if (searchData == null) return null;
    SmartPsiElementPointer[] lastSearchElements = searchData.myElements;
    if (lastSearchElements == null) return null;
    List<PsiElement> elements = new ArrayList<PsiElement>();
    for (SmartPsiElementPointer pointer : lastSearchElements) {
      PsiElement element = pointer.getElement();
      if (element != null) elements.add(element);
    }
    if (elements.isEmpty() && showErrorMessage) {
      Messages.showMessageDialog(
          myProject,
          FindBundle.message("find.searched.elements.have.been.changed.error"),
          FindBundle.message("cannot.search.for.usages.title"),
          Messages.getInformationIcon());
      // SCR #10022
      // clearFindingNextUsageInFile();
      return PsiElement.EMPTY_ARRAY;
    }

    return PsiUtilCore.toPsiElementArray(elements);
  }
  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    if (myPsiElements.isEmpty() && myRangeMarkers.isEmpty() && mySerializedElements.isEmpty()) {
      throw new WriteExternalException();
    }

    if (mySerializedElements.isEmpty()) {
      for (SmartPsiElementPointer<PsiElement> ptr : myPsiElements) {
        PsiElement psiElement = ptr.getElement();
        if (psiElement == null || !psiElement.isValid()) {
          continue;
        }
        FoldingInfo fi = psiElement.getUserData(FOLDING_INFO_KEY);
        boolean state = fi != null && fi.expanded;
        String signature = FoldingPolicy.getSignature(psiElement);
        if (signature == null) {
          continue;
        }

        PsiFile containingFile = psiElement.getContainingFile();
        PsiElement restoredElement = FoldingPolicy.restoreBySignature(containingFile, signature);
        if (!psiElement.equals(restoredElement)) {
          StringBuilder trace = new StringBuilder();
          PsiElement restoredAgain =
              FoldingPolicy.restoreBySignature(containingFile, signature, trace);
          LOG.error(
              "element: "
                  + psiElement
                  + "("
                  + psiElement.getText()
                  + "); restoredElement: "
                  + restoredElement
                  + "; signature: '"
                  + signature
                  + "'; file: "
                  + containingFile
                  + "; injected: "
                  + InjectedLanguageManager.getInstance(myProject)
                      .isInjectedFragment(containingFile)
                  + "; languages: "
                  + containingFile.getViewProvider().getLanguages()
                  + "; restored again: "
                  + restoredAgain
                  + "; restore produces same results: "
                  + (restoredAgain == restoredElement)
                  + "; trace:\n"
                  + trace);
        }

        Element e = new Element(ELEMENT_TAG);
        e.setAttribute(SIGNATURE_ATT, signature);
        e.setAttribute(EXPANDED_ATT, Boolean.toString(state));
        element.addContent(e);
      }
    } else {
      // get back postponed state (before folding initialization)
      for (SerializedPsiElement entry : mySerializedElements) {
        Element e = new Element(ELEMENT_TAG);
        e.setAttribute(SIGNATURE_ATT, entry.mySerializedElement);
        e.setAttribute(EXPANDED_ATT, Boolean.toString(entry.myFoldingInfo.getExpanded()));
        element.addContent(e);
      }
    }
    String date = null;
    for (RangeMarker marker : myRangeMarkers) {
      FoldingInfo fi = marker.getUserData(FOLDING_INFO_KEY);
      boolean state = fi != null && fi.expanded;

      Element e = new Element(MARKER_TAG);
      if (date == null) {
        date = getTimeStamp();
      }
      if (date.isEmpty()) {
        continue;
      }

      e.setAttribute(DATE_ATT, date);
      e.setAttribute(EXPANDED_ATT, Boolean.toString(state));
      String signature =
          Integer.valueOf(marker.getStartOffset()) + ":" + Integer.valueOf(marker.getEndOffset());
      e.setAttribute(SIGNATURE_ATT, signature);
      String placeHolderText = fi == null ? DEFAULT_PLACEHOLDER : fi.placeHolder;
      e.setAttribute(PLACEHOLDER_ATT, placeHolderText);
      element.addContent(e);
    }
  }
 @NotNull
 private List<PsiMethod> getMethodsToImport() {
   PsiShortNamesCache cache = PsiShortNamesCache.getInstance(myMethodCall.getProject());
   PsiMethodCallExpression element = myMethodCall.getElement();
   PsiReferenceExpression reference = element.getMethodExpression();
   PsiExpressionList argumentList = element.getArgumentList();
   String name = reference.getReferenceName();
   List<PsiMethod> list = new ArrayList<PsiMethod>();
   if (name == null) return list;
   GlobalSearchScope scope = element.getResolveScope();
   PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(name, scope, 20);
   List<PsiMethod> applicableList = new ArrayList<PsiMethod>();
   final PsiResolveHelper resolveHelper =
       JavaPsiFacade.getInstance(element.getProject()).getResolveHelper();
   for (PsiMethod method : methods) {
     ProgressManager.checkCanceled();
     if (JavaCompletionUtil.isInExcludedPackage(method)) continue;
     if (!method.hasModifierProperty(PsiModifier.STATIC)) continue;
     PsiFile file = method.getContainingFile();
     if (file instanceof PsiJavaFile
         // do not show methods from default package
         && ((PsiJavaFile) file).getPackageName().length() != 0
         && PsiUtil.isAccessible(method, element, method.getContainingClass())) {
       list.add(method);
       PsiSubstitutor substitutorForMethod =
           resolveHelper.inferTypeArguments(
               method.getTypeParameters(),
               method.getParameterList().getParameters(),
               argumentList.getExpressions(),
               PsiSubstitutor.EMPTY,
               element.getParent(),
               DefaultParameterTypeInferencePolicy.INSTANCE);
       if (PsiUtil.isApplicable(method, substitutorForMethod, argumentList)) {
         applicableList.add(method);
       }
     }
   }
   List<PsiMethod> result = applicableList.isEmpty() ? list : applicableList;
   for (int i = result.size() - 1; i >= 0; i--) {
     ProgressManager.checkCanceled();
     PsiMethod method = result.get(i);
     PsiClass containingClass = method.getContainingClass();
     for (int j = i + 1; j < result.size(); j++) {
       PsiMethod exMethod = result.get(j);
       if (!Comparing.strEqual(exMethod.getName(), method.getName())) continue;
       PsiClass exContainingClass = exMethod.getContainingClass();
       if (containingClass != null
           && exContainingClass != null
           && !Comparing.equal(
               containingClass.getQualifiedName(), exContainingClass.getQualifiedName())) continue;
       // same named methods, drop one
       result.remove(i);
       break;
     }
     // check for manually excluded
     if (isExcluded(method)) {
       result.remove(i);
     }
   }
   Collections.sort(result, new PsiProximityComparator(argumentList));
   return result;
 }
 @Nullable
 @Override
 protected PsiElement getQualifierExpression() {
   final PsiJavaCodeReferenceElement element = myRef.getElement();
   return element != null ? element.getQualifier() : null;
 }
 public PsiElement getEndElement() {
   return myEndSmartPointer == null ? getStartElement() : myEndSmartPointer.getElement();
 }
 public PsiElement getStartElement() {
   return myStartSmartPointer.getElement();
 }
 private PsiClass getPsiClass() {
   return (PsiClass) myClassPointer.getElement();
 }
 E getEnd() {
   return myEnd.getElement();
 }
 E getStart() {
   return myStart.getElement();
 }
  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file)
      throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    PsiMethod[] constructors = myClass.getConstructors();
    if (constructors.length == 0) {
      final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(myClass);
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  defaultConstructorFix.invoke(project, editor, file);
                }
              });
      constructors = myClass.getConstructors();
    }
    Arrays.sort(
        constructors,
        new Comparator<PsiMethod>() {
          @Override
          public int compare(PsiMethod c1, PsiMethod c2) {
            final PsiMethod cc1 = RefactoringUtil.getChainedConstructor(c1);
            final PsiMethod cc2 = RefactoringUtil.getChainedConstructor(c2);
            if (cc1 == c2) return 1;
            if (cc2 == c1) return -1;
            if (cc1 == null) {
              return cc2 == null ? 0 : compare(c1, cc2);
            } else {
              return cc2 == null ? compare(cc1, c2) : compare(cc1, cc2);
            }
          }
        });
    final ArrayList<PsiMethod> constrs =
        filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
    if (constrs.size() > 1) {
      final PsiMethodMember[] members = new PsiMethodMember[constrs.size()];
      int i = 0;
      for (PsiMethod constructor : constrs) {
        members[i++] = new PsiMethodMember(constructor);
      }
      final List<PsiMethodMember> elements;
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        elements = Arrays.asList(members);
      } else {
        final MemberChooser<PsiMethodMember> chooser =
            new MemberChooser<PsiMethodMember>(members, false, true, project);
        chooser.setTitle("Choose constructors to add parameter to");
        chooser.show();
        elements = chooser.getSelectedElements();
        if (elements == null) return;
      }

      for (PsiMethodMember member : elements) {
        if (!addParameterToConstructor(
            project, file, editor, member.getElement(), new PsiField[] {getField()})) break;
      }

    } else if (!constrs.isEmpty()) {
      final Collection<SmartPsiElementPointer<PsiField>> fieldsToFix = getFieldsToFix();
      try {
        final PsiMethod constructor = constrs.get(0);
        final LinkedHashSet<PsiField> fields = new LinkedHashSet<PsiField>();
        getFieldsToFix().add(myField);
        for (SmartPsiElementPointer<PsiField> elementPointer : fieldsToFix) {
          final PsiField field = elementPointer.getElement();
          if (field != null
              && isAvailable(field)
              && filterConstructorsIfFieldAlreadyAssigned(new PsiMethod[] {constructor}, field)
                  .contains(constructor)) {
            fields.add(field);
          }
        }
        if (constrs.size() == constructors.length
            && fields.size() > 1
            && !ApplicationManager.getApplication().isUnitTestMode()) {
          PsiFieldMember[] members = new PsiFieldMember[fields.size()];
          int i = 0;
          for (PsiField field : fields) {
            members[i++] = new PsiFieldMember(field);
          }
          MemberChooser<PsiElementClassMember> chooser =
              new MemberChooser<PsiElementClassMember>(members, false, true, project);
          chooser.setTitle("Choose Fields to Generate Constructor Parameters for");
          chooser.show();
          if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
          final List<PsiElementClassMember> selectedElements = chooser.getSelectedElements();
          if (selectedElements == null) return;
          fields.clear();
          for (PsiElementClassMember member : selectedElements) {
            fields.add((PsiField) member.getElement());
          }
        }

        addParameterToConstructor(
            project,
            file,
            editor,
            constructor,
            constrs.size() == constructors.length
                ? fields.toArray(new PsiField[fields.size()])
                : new PsiField[] {getField()});
      } finally {
        fieldsToFix.clear();
      }
    }
  }
 private PsiField getField() {
   return myField.getElement();
 }
Пример #24
0
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      @Nullable("is null when called from inspection") Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiModifierList myModifierList = (PsiModifierList) startElement;
    final PsiVariable variable = myVariable == null ? null : myVariable.getElement();
    if (!CodeInsightUtilBase.preparePsiElementForWrite(myModifierList)) return;
    final List<PsiModifierList> modifierLists = new ArrayList<PsiModifierList>();
    final PsiFile containingFile = myModifierList.getContainingFile();
    final PsiModifierList modifierList;
    if (variable != null && variable.isValid()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                public void run() {
                  try {
                    variable.normalizeDeclaration();
                  } catch (IncorrectOperationException e) {
                    LOG.error(e);
                  }
                }
              });
      modifierList = variable.getModifierList();
      assert modifierList != null;
    } else {
      modifierList = myModifierList;
    }
    PsiElement owner = modifierList.getParent();
    if (owner instanceof PsiMethod) {
      PsiModifierList copy = (PsiModifierList) myModifierList.copy();
      changeModifierList(copy);
      final int accessLevel = PsiUtil.getAccessLevel(copy);

      OverridingMethodsSearch.search((PsiMethod) owner, owner.getResolveScope(), true)
          .forEach(
              new PsiElementProcessorAdapter<PsiMethod>(
                  new PsiElementProcessor<PsiMethod>() {
                    public boolean execute(@NotNull PsiMethod inheritor) {
                      PsiModifierList list = inheritor.getModifierList();
                      if (inheritor.getManager().isInProject(inheritor)
                          && PsiUtil.getAccessLevel(list) < accessLevel) {
                        modifierLists.add(list);
                      }
                      return true;
                    }
                  }));
    }

    if (!CodeInsightUtilBase.prepareFileForWrite(containingFile)) return;

    if (!modifierLists.isEmpty()) {
      if (Messages.showYesNoDialog(
              project,
              QuickFixBundle.message("change.inheritors.visibility.warning.text"),
              QuickFixBundle.message("change.inheritors.visibility.warning.title"),
              Messages.getQuestionIcon())
          == DialogWrapper.OK_EXIT_CODE) {
        ApplicationManager.getApplication()
            .runWriteAction(
                new Runnable() {
                  public void run() {
                    if (!CodeInsightUtilBase.preparePsiElementsForWrite(modifierLists)) {
                      return;
                    }

                    for (final PsiModifierList modifierList : modifierLists) {
                      changeModifierList(modifierList);
                    }
                  }
                });
      }
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                changeModifierList(modifierList);
                UndoUtil.markPsiFileForUndo(containingFile);
              }
            });
  }
 @Nullable
 public XmlElement getContextElement() {
   return myContextElement.getElement();
 }
 @Nullable
 @Override
 protected PsiElement getElement() {
   return myRef.getElement();
 }
  @Override
  public void setToEditor(@NotNull final Editor editor) {
    assertDispatchThread();
    final PsiManager psiManager = PsiManager.getInstance(myProject);
    if (psiManager.isDisposed()) return;

    if (!myFile.isValid()) return;
    final PsiFile psiFile = psiManager.findFile(myFile);
    if (psiFile == null) return;

    if (!mySerializedElements.isEmpty()) {
      // Restore postponed state
      assert myPsiElements.isEmpty() : "Sequential deserialization";
      for (SerializedPsiElement entry : mySerializedElements) {
        PsiElement restoredElement =
            FoldingPolicy.restoreBySignature(psiFile, entry.mySerializedElement);
        if (restoredElement != null && restoredElement.isValid()) {
          myPsiElements.add(
              SmartPointerManager.getInstance(myProject)
                  .createSmartPsiElementPointer(restoredElement));
          restoredElement.putUserData(FOLDING_INFO_KEY, entry.myFoldingInfo);
        }
      }
      mySerializedElements.clear();
    }

    Map<PsiElement, FoldingDescriptor> ranges = null;
    for (SmartPsiElementPointer<PsiElement> ptr : myPsiElements) {
      PsiElement element = ptr.getElement();
      if (element == null || !element.isValid()) {
        continue;
      }

      if (ranges == null) {
        ranges = buildRanges(editor, psiFile);
      }
      FoldingDescriptor descriptor = ranges.get(element);
      if (descriptor == null) {
        continue;
      }

      TextRange range = descriptor.getRange();
      FoldRegion region =
          FoldingUtil.findFoldRegion(editor, range.getStartOffset(), range.getEndOffset());
      if (region != null) {
        FoldingInfo fi = element.getUserData(FOLDING_INFO_KEY);
        boolean state = fi != null && fi.expanded;
        region.setExpanded(state);
      }
    }
    for (RangeMarker marker : myRangeMarkers) {
      if (!marker.isValid()) {
        continue;
      }
      FoldRegion region =
          FoldingUtil.findFoldRegion(editor, marker.getStartOffset(), marker.getEndOffset());
      FoldingInfo info = marker.getUserData(FOLDING_INFO_KEY);
      if (region == null) {
        if (info != null) {
          region =
              editor
                  .getFoldingModel()
                  .addFoldRegion(marker.getStartOffset(), marker.getEndOffset(), info.placeHolder);
        }
        if (region == null) {
          return;
        }
      }

      boolean state = info != null && info.expanded;
      region.setExpanded(state);
    }
  }
 @Nullable
 private static XmlTag getTagByInjectedFile(final PsiFile file) {
   final SmartPsiElementPointer pointer = file.getUserData(FileContextUtil.INJECTED_IN_ELEMENT);
   final PsiElement element = pointer == null ? null : pointer.getElement();
   return element instanceof XmlText ? ((XmlText) element).getParentTag() : null;
 }