public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
   if (editor == null) return;
   // final PsiFile psiFile =
   // PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
   final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
   if (psiFile == null) return;
   CommandProcessor.getInstance()
       .executeCommand(
           project,
           () -> {
             final CodeInsightActionHandler handler = getHandler();
             final Runnable action =
                 () -> {
                   if (!ApplicationManager.getApplication().isUnitTestMode()
                       && !editor.getContentComponent().isShowing()) return;
                   handler.invoke(project, editor, psiFile);
                 };
             if (handler.startInWriteAction()) {
               ApplicationManager.getApplication().runWriteAction(action);
             } else {
               action.run();
             }
           },
           getCommandName(),
           DocCommandGroupId.noneGroupId(editor.getDocument()));
 }
  @Override
  public void update(AnActionEvent e) {
    Presentation presentation = e.getPresentation();

    Project project = e.getProject();
    if (project == null) {
      presentation.setEnabled(false);
      return;
    }

    final DataContext dataContext = e.getDataContext();
    Editor editor = getEditor(dataContext, project, true);
    if (editor == null) {
      presentation.setEnabled(false);
      return;
    }

    final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file == null) {
      presentation.setEnabled(false);
      return;
    }

    update(presentation, project, editor, file, dataContext, e.getPlace());
  }
  private static boolean isEnabled(DataContext dataContext) {
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null
        || EditorGutter.KEY.getData(dataContext) != null
        || Boolean.TRUE.equals(dataContext.getData(CommonDataKeys.EDITOR_VIRTUAL_SPACE))) {
      return false;
    }

    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (editor == null) {
      UsageTarget[] target = UsageView.USAGE_TARGETS_KEY.getData(dataContext);
      return target != null && target.length > 0;
    } else {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null) {
        return false;
      }

      Language language = PsiUtilBase.getLanguageInEditor(editor, project);
      if (language == null) {
        language = file.getLanguage();
      }
      return !(LanguageFindUsages.INSTANCE.forLanguage(language)
          instanceof EmptyFindUsagesProvider);
    }
  }
  @Nullable
  private Commenter findCommenter(final int line) {
    final FileType fileType = myFile.getFileType();
    if (fileType instanceof AbstractFileType) {
      return ((AbstractFileType) fileType).getCommenter();
    }

    int lineStartOffset = myDocument.getLineStartOffset(line);
    int lineEndOffset = myDocument.getLineEndOffset(line) - 1;
    final CharSequence charSequence = myDocument.getCharsSequence();
    lineStartOffset = CharArrayUtil.shiftForward(charSequence, lineStartOffset, " \t");
    lineEndOffset =
        CharArrayUtil.shiftBackward(charSequence, lineEndOffset < 0 ? 0 : lineEndOffset, " \t");
    final Language lineStartLanguage = PsiUtilBase.getLanguageAtOffset(myFile, lineStartOffset);
    final Language lineEndLanguage = PsiUtilBase.getLanguageAtOffset(myFile, lineEndOffset);
    return CommentByBlockCommentHandler.getCommenter(
        myFile, myEditor, lineStartLanguage, lineEndLanguage);
  }
  @Nullable
  private static Commenter findCommenter(PsiFile file, Editor editor, Caret caret) {
    final FileType fileType = file.getFileType();
    if (fileType instanceof AbstractFileType) {
      return ((AbstractFileType) fileType).getCommenter();
    }

    Language lang = PsiUtilBase.getLanguageInEditor(caret, file.getProject());

    return getCommenter(file, editor, lang, lang);
  }
 @Nullable
 private static PsiElement[] convertToPsiElementsArray(final Object[] selectedElements) {
   if (selectedElements == null) return null;
   ArrayList<PsiElement> psiElements = new ArrayList<PsiElement>();
   for (Object selectedElement : selectedElements) {
     if (selectedElement instanceof PsiElement && ((PsiElement) selectedElement).isValid()) {
       psiElements.add((PsiElement) selectedElement);
     }
   }
   return PsiUtilBase.toPsiElementArray(psiElements);
 }
  @NotNull
  public FileHighlightingSetting getHighlightingSettingForRoot(@NotNull PsiElement root) {
    final PsiFile containingFile = root.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    FileHighlightingSetting[] fileHighlightingSettings = myHighlightSettings.get(virtualFile);
    final int index = PsiUtilBase.getRootIndex(root);

    if (fileHighlightingSettings == null || fileHighlightingSettings.length <= index) {
      return getDefaultHighlightingSetting(root.getProject(), virtualFile);
    }
    return fileHighlightingSettings[index];
  }
  public static boolean isInStringLiteral(PsiElement element) {
    ParserDefinition definition =
        LanguageParserDefinitions.INSTANCE.forLanguage(
            PsiUtilBase.findLanguageFromElement(element));
    if (definition == null) {
      return false;
    }

    return isStringLiteral(element, definition)
        || isStringLiteral(element.getParent(), definition)
        || isStringLiteralWithError(element, definition)
        || isStringLiteralWithError(element.getParent(), definition);
  }
  @NotNull
  private static PsiElement[] filterPsiElements(Object[] selectedElements) {
    if (selectedElements == null) {
      return PsiElement.EMPTY_ARRAY;
    }
    ArrayList<PsiElement> psiElements = new ArrayList<PsiElement>();

    for (Object selectedElement : selectedElements) {
      if (selectedElement instanceof PsiElement) {
        psiElements.add((PsiElement) selectedElement);
      }
    }
    return PsiUtilBase.toPsiElementArray(psiElements);
  }
  @Nullable
  public Runnable prepareTemplate(
      final Editor editor,
      char shortcutChar,
      @Nullable final PairProcessor<String, String> processor) {
    if (editor.getSelectionModel().hasSelection()) {
      return null;
    }

    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, myProject);
    if (file == null) return null;

    Map<TemplateImpl, String> template2argument =
        findMatchingTemplates(file, editor, shortcutChar, TemplateSettings.getInstance());

    List<CustomLiveTemplate> customCandidates =
        ContainerUtil.findAll(
            CustomLiveTemplate.EP_NAME.getExtensions(),
            customLiveTemplate ->
                shortcutChar == customLiveTemplate.getShortcut()
                    && (editor.getCaretModel().getCaretCount() <= 1
                        || supportsMultiCaretMode(customLiveTemplate)));
    if (!customCandidates.isEmpty()) {
      int caretOffset = editor.getCaretModel().getOffset();
      PsiFile fileCopy = insertDummyIdentifierIfNeeded(file, caretOffset, caretOffset, "");
      Document document = editor.getDocument();

      for (final CustomLiveTemplate customLiveTemplate : customCandidates) {
        if (isApplicable(customLiveTemplate, editor, fileCopy)) {
          final String key =
              customLiveTemplate.computeTemplateKey(new CustomTemplateCallback(editor, fileCopy));
          if (key != null) {
            int offsetBeforeKey = caretOffset - key.length();
            CharSequence text = document.getImmutableCharSequence();
            if (template2argument == null
                || !containsTemplateStartingBefore(
                    template2argument, offsetBeforeKey, caretOffset, text)) {
              return () -> customLiveTemplate.expand(key, new CustomTemplateCallback(editor, file));
            }
          }
        }
      }
    }

    return startNonCustomTemplates(template2argument, editor, processor);
  }
 @Nullable
 private static PsiFile getRoot(final PsiFile file, final Editor editor) {
   if (file == null) return null;
   int offset = editor.getCaretModel().getOffset();
   if (offset == editor.getDocument().getTextLength()) offset--;
   if (offset < 0) return null;
   PsiElement leafElement = file.findElementAt(offset);
   if (leafElement == null) return null;
   if (leafElement.getLanguage() instanceof DependentLanguage) {
     leafElement =
         file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage());
     if (leafElement == null) return null;
   }
   ASTNode node = leafElement.getNode();
   if (node == null) return null;
   return (PsiFile) PsiUtilBase.getRoot(node).getPsi();
 }
  private static boolean shouldFocusLookup(CompletionParameters parameters) {
    switch (CodeInsightSettings.getInstance().AUTOPOPUP_FOCUS_POLICY) {
      case CodeInsightSettings.ALWAYS:
        return true;
      case CodeInsightSettings.NEVER:
        return false;
    }

    final Language language =
        PsiUtilBase.getLanguageAtOffset(
            parameters.getPosition().getContainingFile(), parameters.getOffset());
    for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
      final ThreeState result = confidence.shouldFocusLookup(parameters);
      if (result != ThreeState.UNSURE) {
        return result == ThreeState.YES;
      }
    }
    return false;
  }
 public void setHighlightingSettingForRoot(
     @NotNull PsiElement root, @NotNull FileHighlightingSetting setting) {
   final PsiFile containingFile = root.getContainingFile();
   final VirtualFile virtualFile = containingFile.getVirtualFile();
   if (virtualFile == null) return;
   FileHighlightingSetting[] defaults = myHighlightSettings.get(virtualFile);
   int rootIndex = PsiUtilBase.getRootIndex(root);
   if (defaults != null && rootIndex >= defaults.length) defaults = null;
   if (defaults == null) defaults = getDefaults(containingFile);
   defaults[rootIndex] = setting;
   boolean toRemove = true;
   for (FileHighlightingSetting aDefault : defaults) {
     if (aDefault != FileHighlightingSetting.NONE) toRemove = false;
   }
   if (toRemove) {
     myHighlightSettings.remove(virtualFile);
   } else {
     myHighlightSettings.put(virtualFile, defaults);
   }
 }
 private static void addCompletionChar(
     Project project,
     CompletionAssertions.WatchingInsertionContext context,
     LookupElement item,
     Editor editor,
     CompletionProgressIndicator indicator,
     char completionChar) {
   int tailOffset = context.getTailOffset();
   if (tailOffset < 0) {
     LOG.info(
         "tailOffset<0 after inserting "
             + item
             + " of "
             + item.getClass()
             + "; invalidated at: "
             + context.invalidateTrace
             + "\n--------");
   } else {
     editor.getCaretModel().moveToOffset(tailOffset);
   }
   if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
     final Language language = PsiUtilBase.getLanguageInEditor(editor, project);
     if (language != null) {
       for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.forKey(language)) {
         if (processor.processAfterCompletion(editor, indicator.getParameters().getOriginalFile()))
           break;
       }
     }
   } else if (!editor
       .getCaretModel()
       .supportsMultipleCarets()) { // this will be done outside of runForEach caret context
     DataContext dataContext =
         DataManager.getInstance().getDataContext(editor.getContentComponent());
     EditorActionManager.getInstance()
         .getTypedAction()
         .getHandler()
         .execute(editor, completionChar, dataContext);
   }
 }
  private void invokeCompletion(final ExpressionContext context) {
    final Project project = context.getProject();
    final Editor editor = context.getEditor();

    final PsiFile psiFile = editor != null ? PsiUtilBase.getPsiFileInEditor(editor, project) : null;
    Runnable runnable =
        () -> {
          if (project.isDisposed()
              || editor == null
              || editor.isDisposed()
              || psiFile == null
              || !psiFile.isValid()) return;

          // it's invokeLater, so another completion could have started
          if (CompletionServiceImpl.getCompletionService().getCurrentCompletion() != null) return;

          CommandProcessor.getInstance()
              .executeCommand(
                  project,
                  () -> {
                    // if we're in some completion's insert handler, make sure our new completion
                    // isn't treated as the second invocation
                    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);

                    invokeCompletionHandler(project, editor);
                    Lookup lookup = LookupManager.getInstance(project).getActiveLookup();

                    if (lookup != null) {
                      lookup.addLookupListener(
                          new MyLookupListener(context, myCheckCompletionChar));
                    }
                  },
                  "",
                  null);
        };
    ApplicationManager.getApplication().invokeLater(runnable);
  }
Exemplo n.º 16
0
  public static LookupElement objectToLookupItem(Object object) {
    if (object instanceof LookupElement) return (LookupElement) object;

    String s = null;
    TailType tailType = TailType.NONE;
    if (object instanceof PsiElement) {
      s = PsiUtilBase.getName((PsiElement) object);
    } else if (object instanceof PsiMetaData) {
      s = ((PsiMetaData) object).getName();
    } else if (object instanceof String) {
      s = (String) object;
    } else if (object instanceof Template) {
      s = ((Template) object).getKey();
    } else if (object instanceof PresentableLookupValue) {
      s = ((PresentableLookupValue) object).getPresentation();
    } else {
      LOG.assertTrue(
          false,
          "Null string for object: "
              + object
              + " of class "
              + (object != null ? object.getClass() : null));
    }

    LookupItem item = new LookupItem(object, s);

    if (object instanceof LookupValueWithUIHint && ((LookupValueWithUIHint) object).isBold()) {
      item.setBold();
    }
    if (object instanceof LookupValueWithTail) {
      item.setAttribute(
          LookupItem.TAIL_TEXT_ATTR, " " + ((LookupValueWithTail) object).getTailText());
    }
    item.setAttribute(CompletionUtil.TAIL_TYPE_ATTR, tailType);
    return item;
  }
  protected boolean handleBackspace(
      Editor editor, Caret caret, DataContext dataContext, boolean toWordStart) {
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) return false;

    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);

    if (file == null) return false;

    if (editor.getSelectionModel().hasSelection()) return false;

    int offset = editor.getCaretModel().getOffset() - 1;
    if (offset < 0) return false;
    CharSequence chars = editor.getDocument().getCharsSequence();
    char c = chars.charAt(offset);

    final Editor injectedEditor =
        TypedHandler.injectedEditorIfCharTypedIsSignificant(c, editor, file);
    final Editor originalEditor = editor;
    if (injectedEditor != editor) {
      int injectedOffset = injectedEditor.getCaretModel().getOffset();
      if (isOffsetInsideInjected(injectedEditor, injectedOffset)) {
        file = PsiDocumentManager.getInstance(project).getPsiFile(injectedEditor.getDocument());
        editor = injectedEditor;
        offset = injectedOffset - 1;
      }
    }

    final BackspaceHandlerDelegate[] delegates =
        Extensions.getExtensions(BackspaceHandlerDelegate.EP_NAME);
    if (!toWordStart) {
      for (BackspaceHandlerDelegate delegate : delegates) {
        delegate.beforeCharDeleted(c, file, editor);
      }
    }

    FileType fileType = file.getFileType();
    final QuoteHandler quoteHandler = TypedHandler.getQuoteHandler(file, editor);

    HighlighterIterator hiterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
    boolean wasClosingQuote =
        quoteHandler != null && quoteHandler.isClosingQuote(hiterator, offset);

    myOriginalHandler.execute(originalEditor, caret, dataContext);

    if (!toWordStart) {
      for (BackspaceHandlerDelegate delegate : delegates) {
        if (delegate.charDeleted(c, file, editor)) {
          return true;
        }
      }
    }

    if (offset >= editor.getDocument().getTextLength()) return true;

    chars = editor.getDocument().getCharsSequence();
    if ((c == '(' || c == '[' || c == '{')
        && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) {
      char c1 = chars.charAt(offset);
      if (c1 != getRightChar(c)) return true;

      HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
      BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
      if (!braceMatcher.isLBraceToken(iterator, chars, fileType)
          && !braceMatcher.isRBraceToken(iterator, chars, fileType)) {
        return true;
      }

      int rparenOffset =
          BraceMatchingUtil.findRightmostRParen(iterator, iterator.getTokenType(), chars, fileType);
      if (rparenOffset >= 0) {
        iterator = ((EditorEx) editor).getHighlighter().createIterator(rparenOffset);
        boolean matched = BraceMatchingUtil.matchBrace(chars, fileType, iterator, false);
        if (matched) return true;
      }

      editor.getDocument().deleteString(offset, offset + 1);
    } else if ((c == '"' || c == '\'' || c == '`')
        && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) {
      char c1 = chars.charAt(offset);
      if (c1 != c) return true;
      if (wasClosingQuote) return true;

      HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
      if (quoteHandler == null || !quoteHandler.isOpeningQuote(iterator, offset)) return true;

      editor.getDocument().deleteString(offset, offset + 1);
    }

    return true;
  }
 @Override
 @NotNull
 public PsiElement[] getSecondaryElements() {
   PsiElement element = getPsiElement();
   if (ApplicationManager.getApplication().isUnitTestMode()) return PsiElement.EMPTY_ARRAY;
   if (element instanceof PsiField) {
     final PsiField field = (PsiField) element;
     PsiClass containingClass = field.getContainingClass();
     if (containingClass != null) {
       String fieldName = field.getName();
       final String propertyName =
           JavaCodeStyleManager.getInstance(getProject())
               .variableNameToPropertyName(fieldName, VariableKind.FIELD);
       Set<PsiMethod> accessors = new THashSet<PsiMethod>();
       boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
       PsiMethod getter =
           PropertyUtil.findPropertyGetterWithType(
               propertyName,
               isStatic,
               field.getType(),
               ContainerUtil.iterate(containingClass.getMethods()));
       if (getter != null) accessors.add(getter);
       PsiMethod setter =
           PropertyUtil.findPropertySetterWithType(
               propertyName,
               isStatic,
               field.getType(),
               ContainerUtil.iterate(containingClass.getMethods()));
       if (setter != null) accessors.add(setter);
       accessors.addAll(PropertyUtil.getAccessors(containingClass, fieldName));
       if (!accessors.isEmpty()) {
         final boolean doSearch;
         boolean containsPhysical =
             ContainerUtil.find(
                     accessors,
                     new Condition<PsiMethod>() {
                       @Override
                       public boolean value(PsiMethod psiMethod) {
                         return psiMethod.isPhysical();
                       }
                     })
                 != null;
         if (!containsPhysical) {
           doSearch = true;
         } else {
           doSearch =
               Messages.showOkCancelDialog(
                       FindBundle.message("find.field.accessors.prompt", fieldName),
                       FindBundle.message("find.field.accessors.title"),
                       CommonBundle.getYesButtonText(),
                       CommonBundle.getNoButtonText(),
                       Messages.getQuestionIcon())
                   == DialogWrapper.OK_EXIT_CODE;
         }
         if (doSearch) {
           final Set<PsiElement> elements = new THashSet<PsiElement>();
           for (PsiMethod accessor : accessors) {
             ContainerUtil.addAll(
                 elements, SuperMethodWarningUtil.checkSuperMethods(accessor, ACTION_STRING));
           }
           return PsiUtilBase.toPsiElementArray(elements);
         }
       }
     }
   }
   return super.getSecondaryElements();
 }
  // currently only one level here..
  public boolean contains(@NotNull String name, @NotNull final VirtualFile vFile) {
    final ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(myProject).getFileIndex();
    final Set<Boolean> find = new HashSet<Boolean>();
    final ContentIterator contentIterator =
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir != null && fileOrDir.getPath().equals(vFile.getPath())) {
              find.add(Boolean.TRUE);
            }
            return true;
          }
        };

    Collection<TreeItem<Pair<AbstractUrl, String>>> urls = getFavoritesListRootUrls(name);
    for (TreeItem<Pair<AbstractUrl, String>> pair : urls) {
      AbstractUrl abstractUrl = pair.getData().getFirst();
      if (abstractUrl == null) {
        continue;
      }
      final Object[] path = abstractUrl.createPath(myProject);
      if (path == null || path.length < 1 || path[0] == null) {
        continue;
      }
      Object element = path[path.length - 1];
      if (element instanceof SmartPsiElementPointer) {
        final VirtualFile virtualFile =
            PsiUtilBase.getVirtualFile(((SmartPsiElementPointer) element).getElement());
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }

      if (element instanceof PsiElement) {
        final VirtualFile virtualFile = PsiUtilBase.getVirtualFile((PsiElement) element);
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }
      if (element instanceof Module) {
        ModuleRootManager.getInstance((Module) element)
            .getFileIndex()
            .iterateContent(contentIterator);
      }
      if (element instanceof LibraryGroupElement) {
        final boolean inLibrary =
            ModuleRootManager.getInstance(((LibraryGroupElement) element).getModule())
                    .getFileIndex()
                    .isInContent(vFile)
                && projectFileIndex.isInLibraryClasses(vFile);
        if (inLibrary) {
          return true;
        }
      }
      if (element instanceof NamedLibraryElement) {
        NamedLibraryElement namedLibraryElement = (NamedLibraryElement) element;
        final VirtualFile[] files =
            namedLibraryElement.getOrderEntry().getRootFiles(OrderRootType.CLASSES);
        if (files != null && ArrayUtil.find(files, vFile) > -1) {
          return true;
        }
      }
      if (element instanceof ModuleGroup) {
        ModuleGroup group = (ModuleGroup) element;
        final Collection<Module> modules = group.modulesInGroup(myProject, true);
        for (Module module : modules) {
          ModuleRootManager.getInstance(module).getFileIndex().iterateContent(contentIterator);
        }
      }

      for (FavoriteNodeProvider provider :
          Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, myProject)) {
        if (provider.elementContainsFile(element, vFile)) {
          return true;
        }
      }

      if (!find.isEmpty()) {
        return true;
      }
    }
    return false;
  }
  /**
   * Inspects all lines of the given document and wraps all of them that exceed {@link
   * CodeStyleSettings#RIGHT_MARGIN right margin}.
   *
   * <p>I.e. the algorithm is to do the following for every line:
   *
   * <p>
   *
   * <pre>
   * <ol>
   *   <li>
   *      Check if the line exceeds {@link CodeStyleSettings#RIGHT_MARGIN right margin}. Go to the next line in the case of
   *      negative answer;
   *   </li>
   *   <li>Determine line wrap position; </li>
   *   <li>
   *      Perform 'smart wrap', i.e. not only wrap the line but insert additional characters over than line feed if necessary.
   *      For example consider that we wrap a single-line comment - we need to insert comment symbols on a start of the wrapped
   *      part as well. Generally, we get the same behavior as during pressing 'Enter' at wrap position during editing document;
   *   </li>
   * </ol>
   * </pre>
   *
   * @param file file that holds parsed document tree
   * @param document target document
   * @param startOffset start offset of the first line to check for wrapping (inclusive)
   * @param endOffset end offset of the first line to check for wrapping (exclusive)
   */
  private void wrapLongLinesIfNecessary(
      @NotNull final PsiFile file,
      @Nullable final Document document,
      final int startOffset,
      final int endOffset) {
    if (!mySettings.getCommonSettings(file.getLanguage()).WRAP_LONG_LINES
        || PostprocessReformattingAspect.getInstance(file.getProject())
            .isViewProviderLocked(file.getViewProvider())
        || document == null) {
      return;
    }

    final VirtualFile vFile = FileDocumentManager.getInstance().getFile(document);
    if ((vFile == null || vFile instanceof LightVirtualFile)
        && !ApplicationManager.getApplication().isUnitTestMode()) {
      // we assume that control flow reaches this place when the document is backed by a "virtual"
      // file so any changes made by
      // a formatter affect only PSI and it is out of sync with a document text
      return;
    }

    Editor editor = PsiUtilBase.findEditor(file);
    EditorFactory editorFactory = null;
    if (editor == null) {
      if (!ApplicationManager.getApplication().isDispatchThread()) {
        return;
      }
      editorFactory = EditorFactory.getInstance();
      editor = editorFactory.createEditor(document, file.getProject());
    }
    try {
      final Editor editorToUse = editor;
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  final CaretModel caretModel = editorToUse.getCaretModel();
                  final int caretOffset = caretModel.getOffset();
                  final RangeMarker caretMarker =
                      editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset);
                  doWrapLongLinesIfNecessary(
                      editorToUse,
                      file.getProject(),
                      editorToUse.getDocument(),
                      startOffset,
                      endOffset);
                  if (caretMarker.isValid()
                      && caretModel.getOffset() != caretMarker.getStartOffset()) {
                    caretModel.moveToOffset(caretMarker.getStartOffset());
                  }
                }
              });
    } finally {
      PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
      if (documentManager.isUncommited(document)) documentManager.commitDocument(document);
      if (editorFactory != null) {
        editorFactory.releaseEditor(editor);
      }
    }
  }
  private void executeWriteActionInner(Editor editor, DataContext dataContext, Project project) {
    CodeInsightSettings settings = CodeInsightSettings.getInstance();
    if (project == null) {
      myOriginalHandler.execute(editor, dataContext);
      return;
    }
    final Document document = editor.getDocument();
    final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);

    if (file == null) {
      myOriginalHandler.execute(editor, dataContext);
      return;
    }

    CommandProcessor.getInstance()
        .setCurrentCommandName(CodeInsightBundle.message("command.name.typing"));

    EditorModificationUtil.deleteSelectedText(editor);

    int caretOffset = editor.getCaretModel().getOffset();
    CharSequence text = document.getCharsSequence();
    int length = document.getTextLength();
    if (caretOffset < length && text.charAt(caretOffset) != '\n') {
      int offset1 = CharArrayUtil.shiftBackward(text, caretOffset, " \t");
      if (offset1 < 0 || text.charAt(offset1) == '\n') {
        int offset2 = CharArrayUtil.shiftForward(text, offset1 + 1, " \t");
        boolean isEmptyLine = offset2 >= length || text.charAt(offset2) == '\n';
        if (!isEmptyLine) { // we are in leading spaces of a non-empty line
          myOriginalHandler.execute(editor, dataContext);
          return;
        }
      }
    }

    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitDocument(document);

    boolean forceIndent = false;
    boolean forceSkipIndent = false;
    Ref<Integer> caretOffsetRef = new Ref<Integer>(caretOffset);
    Ref<Integer> caretAdvanceRef = new Ref<Integer>(0);

    final EnterHandlerDelegate[] delegates = Extensions.getExtensions(EnterHandlerDelegate.EP_NAME);
    for (EnterHandlerDelegate delegate : delegates) {
      EnterHandlerDelegate.Result result =
          delegate.preprocessEnter(
              file, editor, caretOffsetRef, caretAdvanceRef, dataContext, myOriginalHandler);
      if (caretOffsetRef.get() > document.getTextLength()) {
        throw new AssertionError("Wrong caret offset change by " + delegate);
      }

      if (result == EnterHandlerDelegate.Result.Stop) {
        return;
      }
      if (result != EnterHandlerDelegate.Result.Continue) {
        if (result == EnterHandlerDelegate.Result.DefaultForceIndent) {
          forceIndent = true;
        } else if (result == EnterHandlerDelegate.Result.DefaultSkipIndent) {
          forceSkipIndent = true;
        }
        break;
      }
    }

    text = document.getCharsSequence(); // update after changes done in preprocessEnter()
    caretOffset = caretOffsetRef.get().intValue();
    boolean isFirstColumn = caretOffset == 0 || text.charAt(caretOffset - 1) == '\n';
    final boolean insertSpace =
        !isFirstColumn
            && !(caretOffset >= text.length()
                || text.charAt(caretOffset) == ' '
                || text.charAt(caretOffset) == '\t');
    editor.getCaretModel().moveToOffset(caretOffset);
    myOriginalHandler.execute(editor, dataContext);
    if (!editor.isInsertMode() || forceSkipIndent) {
      return;
    }

    if (settings.SMART_INDENT_ON_ENTER || forceIndent) {
      caretOffset += 1;
      caretOffset =
          CharArrayUtil.shiftForward(editor.getDocument().getCharsSequence(), caretOffset, " \t");
    } else {
      caretOffset = editor.getCaretModel().getOffset();
    }

    documentManager.commitAllDocuments();
    final DoEnterAction action =
        new DoEnterAction(
            file,
            editor,
            document,
            dataContext,
            caretOffset,
            !insertSpace,
            caretAdvanceRef.get(),
            project);
    action.setForceIndent(forceIndent);
    action.run();
    documentManager.commitDocument(document);
    for (EnterHandlerDelegate delegate : delegates) {
      if (delegate.postProcessEnter(file, editor, dataContext)
          == EnterHandlerDelegate.Result.Stop) {
        break;
      }
    }
    documentManager.commitDocument(document);
  }
  private void doComment() {
    myStartLine = myDocument.getLineNumber(myStartOffset);
    myEndLine = myDocument.getLineNumber(myEndOffset);

    if (myEndLine > myStartLine && myDocument.getLineStartOffset(myEndLine) == myEndOffset) {
      myEndLine--;
    }

    myStartOffsets = new int[myEndLine - myStartLine + 1];
    myEndOffsets = new int[myEndLine - myStartLine + 1];
    myCommenters = new Commenter[myEndLine - myStartLine + 1];
    myCommenterStateMap = new THashMap<SelfManagingCommenter, CommenterDataHolder>();
    CharSequence chars = myDocument.getCharsSequence();

    boolean singleline = myStartLine == myEndLine;
    int offset = myDocument.getLineStartOffset(myStartLine);
    offset = CharArrayUtil.shiftForward(myDocument.getCharsSequence(), offset, " \t");

    final Language languageSuitableForCompleteFragment =
        PsiUtilBase.reallyEvaluateLanguageInRange(
            offset,
            CharArrayUtil.shiftBackward(
                myDocument.getCharsSequence(), myDocument.getLineEndOffset(myEndLine), " \t\n"),
            myFile);

    Commenter blockSuitableCommenter =
        languageSuitableForCompleteFragment == null
            ? LanguageCommenters.INSTANCE.forLanguage(myFile.getLanguage())
            : null;
    if (blockSuitableCommenter == null && myFile.getFileType() instanceof AbstractFileType) {
      blockSuitableCommenter =
          new Commenter() {
            final SyntaxTable mySyntaxTable =
                ((AbstractFileType) myFile.getFileType()).getSyntaxTable();

            @Nullable
            public String getLineCommentPrefix() {
              return mySyntaxTable.getLineComment();
            }

            @Nullable
            public String getBlockCommentPrefix() {
              return mySyntaxTable.getStartComment();
            }

            @Nullable
            public String getBlockCommentSuffix() {
              return mySyntaxTable.getEndComment();
            }

            public String getCommentedBlockCommentPrefix() {
              return null;
            }

            public String getCommentedBlockCommentSuffix() {
              return null;
            }
          };
    }

    boolean allLineCommented = true;
    boolean commentWithIndent =
        !CodeStyleSettingsManager.getSettings(myProject).LINE_COMMENT_AT_FIRST_COLUMN;

    for (int line = myStartLine; line <= myEndLine; line++) {
      Commenter commenter =
          blockSuitableCommenter != null ? blockSuitableCommenter : findCommenter(line);
      if (commenter == null) return;
      if (commenter.getLineCommentPrefix() == null
          && (commenter.getBlockCommentPrefix() == null
              || commenter.getBlockCommentSuffix() == null)) {
        return;
      }

      if (commenter instanceof SelfManagingCommenter
          && myCommenterStateMap.get(commenter) == null) {
        final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter) commenter;
        CommenterDataHolder state =
            selfManagingCommenter.createLineCommentingState(
                myStartLine, myEndLine, myDocument, myFile);
        if (state == null) state = SelfManagingCommenter.EMPTY_STATE;
        myCommenterStateMap.put(selfManagingCommenter, state);
      }

      myCommenters[line - myStartLine] = commenter;
      if (!isLineCommented(line, chars, commenter) && (singleline || !isLineEmpty(line))) {
        allLineCommented = false;
        if (commenter instanceof IndentedCommenter) {
          final Boolean value = ((IndentedCommenter) commenter).forceIndentedLineComment();
          if (value != null) {
            commentWithIndent = value;
          }
        }
        break;
      }
    }

    if (!allLineCommented) {
      if (!commentWithIndent) {
        doDefaultCommenting(blockSuitableCommenter);
      } else {
        doIndentCommenting(blockSuitableCommenter);
      }
    } else {
      for (int line = myEndLine; line >= myStartLine; line--) {
        uncommentLine(line);
        // int offset1 = myStartOffsets[line - myStartLine];
        // int offset2 = myEndOffsets[line - myStartLine];
        // if (offset1 == offset2) continue;
        // Commenter commenter = myCommenters[line - myStartLine];
        // String prefix = commenter.getBlockCommentPrefix();
        // if (prefix == null || !myDocument.getText().substring(offset1,
        // myDocument.getTextLength()).startsWith(prefix)) {
        //  prefix = commenter.getLineCommentPrefix();
        // }
        //
        // String suffix = commenter.getBlockCommentSuffix();
        // if (suffix == null && prefix != null) suffix = "";
        //
        // if (prefix != null && suffix != null) {
        //  final int suffixLen = suffix.length();
        //  final int prefixLen = prefix.length();
        //  if (offset2 >= 0) {
        //    if (!CharArrayUtil.regionMatches(chars, offset1 + prefixLen, prefix)) {
        //      myDocument.deleteString(offset2 - suffixLen, offset2);
        //    }
        //  }
        //  if (offset1 >= 0) {
        //    for (int i = offset2 - suffixLen - 1; i > offset1 + prefixLen; --i) {
        //      if (CharArrayUtil.regionMatches(chars, i, suffix)) {
        //        myDocument.deleteString(i, i + suffixLen);
        //      }
        //      else if (CharArrayUtil.regionMatches(chars, i, prefix)) {
        //        myDocument.deleteString(i, i + prefixLen);
        //      }
        //    }
        //    myDocument.deleteString(offset1, offset1 + prefixLen);
        //  }
        // }
      }
    }
  }
  public static void deletePsiElement(
      final PsiElement[] elementsToDelete, final Project project, boolean needConfirmation) {
    if (elementsToDelete == null || elementsToDelete.length == 0) return;

    final PsiElement[] elements = PsiTreeUtil.filterAncestors(elementsToDelete);

    boolean safeDeleteApplicable = true;
    for (int i = 0; i < elements.length && safeDeleteApplicable; i++) {
      PsiElement element = elements[i];
      safeDeleteApplicable = SafeDeleteProcessor.validElement(element);
    }

    final boolean dumb = DumbService.getInstance(project).isDumb();
    if (safeDeleteApplicable && !dumb) {
      DeleteDialog dialog =
          new DeleteDialog(
              project,
              elements,
              new DeleteDialog.Callback() {
                public void run(final DeleteDialog dialog) {
                  if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(
                      project, Arrays.asList(elements), true)) return;
                  SafeDeleteProcessor.createInstance(
                          project,
                          new Runnable() {
                            public void run() {
                              dialog.close(DialogWrapper.CANCEL_EXIT_CODE);
                            }
                          },
                          elements,
                          dialog.isSearchInComments(),
                          dialog.isSearchInNonJava(),
                          true)
                      .run();
                }
              });
      if (needConfirmation) {
        dialog.show();
        if (!dialog.isOK()) return;
      }
    } else {
      @SuppressWarnings({"UnresolvedPropertyKey"})
      String warningMessage =
          DeleteUtil.generateWarningMessage(IdeBundle.message("prompt.delete.elements"), elements);

      boolean anyDirectories = false;
      String directoryName = null;
      for (PsiElement psiElement : elementsToDelete) {
        if (psiElement instanceof PsiDirectory
            && !PsiUtilBase.isSymLink((PsiDirectory) psiElement)) {
          anyDirectories = true;
          directoryName = ((PsiDirectory) psiElement).getName();
          break;
        }
      }
      if (anyDirectories) {
        if (elements.length == 1) {
          warningMessage +=
              IdeBundle.message("warning.delete.all.files.and.subdirectories", directoryName);
        } else {
          warningMessage +=
              IdeBundle.message(
                  "warning.delete.all.files.and.subdirectories.in.the.selected.directory");
        }
      }

      if (safeDeleteApplicable && dumb) {
        warningMessage +=
            "\n\nWarning:\n  Safe delete is not available while "
                + ApplicationNamesInfo.getInstance().getFullProductName()
                + " updates indices,\n  no usages will be checked.";
      }

      if (needConfirmation) {
        int result =
            Messages.showOkCancelDialog(
                project,
                warningMessage,
                IdeBundle.message("title.delete"),
                ApplicationBundle.message("button.delete"),
                CommonBundle.getCancelButtonText(),
                Messages.getQuestionIcon());
        if (result != 0) return;
      }
    }

    final FileTypeManager ftManager = FileTypeManager.getInstance();
    CommandProcessor.getInstance()
        .executeCommand(
            project,
            new Runnable() {
              public void run() {
                if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(
                    project, Arrays.asList(elements), false)) {
                  return;
                }

                // deleted from project view or something like that.
                if (PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext())
                    == null) {
                  CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
                }

                for (final PsiElement elementToDelete : elements) {
                  if (!elementToDelete.isValid()) continue; // was already deleted
                  if (elementToDelete instanceof PsiDirectory) {
                    VirtualFile virtualFile = ((PsiDirectory) elementToDelete).getVirtualFile();
                    if (virtualFile.isInLocalFileSystem() && !virtualFile.isSymLink()) {
                      ArrayList<VirtualFile> readOnlyFiles = new ArrayList<VirtualFile>();
                      getReadOnlyVirtualFiles(virtualFile, readOnlyFiles, ftManager);

                      if (!readOnlyFiles.isEmpty()) {
                        int _result =
                            Messages.showYesNoDialog(
                                project,
                                IdeBundle.message(
                                    "prompt.directory.contains.read.only.files",
                                    virtualFile.getPresentableUrl()),
                                IdeBundle.message("title.delete"),
                                Messages.getQuestionIcon());
                        if (_result != 0) continue;

                        boolean success = true;
                        for (VirtualFile file : readOnlyFiles) {
                          success = clearReadOnlyFlag(file, project);
                          if (!success) break;
                        }
                        if (!success) continue;
                      }
                    }
                  } else if (!elementToDelete.isWritable()
                      && !(elementToDelete instanceof PsiFileSystemItem
                          && PsiUtilBase.isSymLink((PsiFileSystemItem) elementToDelete))) {
                    final PsiFile file = elementToDelete.getContainingFile();
                    if (file != null) {
                      final VirtualFile virtualFile = file.getVirtualFile();
                      if (virtualFile.isInLocalFileSystem()) {
                        int _result =
                            MessagesEx.fileIsReadOnly(project, virtualFile)
                                .setTitle(IdeBundle.message("title.delete"))
                                .appendMessage(IdeBundle.message("prompt.delete.it.anyway"))
                                .askYesNo();
                        if (_result != 0) continue;

                        boolean success = clearReadOnlyFlag(virtualFile, project);
                        if (!success) continue;
                      }
                    }
                  }

                  try {
                    elementToDelete.checkDelete();
                  } catch (IncorrectOperationException ex) {
                    Messages.showMessageDialog(
                        project,
                        ex.getMessage(),
                        CommonBundle.getErrorTitle(),
                        Messages.getErrorIcon());
                    continue;
                  }

                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            public void run() {
                              try {
                                elementToDelete.delete();
                              } catch (final IncorrectOperationException ex) {
                                ApplicationManager.getApplication()
                                    .invokeLater(
                                        new Runnable() {
                                          public void run() {
                                            Messages.showMessageDialog(
                                                project,
                                                ex.getMessage(),
                                                CommonBundle.getErrorTitle(),
                                                Messages.getErrorIcon());
                                          }
                                        });
                              }
                            }
                          });
                }
              }
            },
            RefactoringBundle.message(
                "safe.delete.command",
                RefactoringUIUtil.calculatePsiElementDescriptionList(elements)),
            null);
  }
  public final void invokeCompletion(
      @NotNull final Project project,
      @NotNull final Editor editor,
      int time,
      boolean hasModifiers,
      boolean restarted) {
    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
    assert psiFile != null
        : "no PSI file: " + FileDocumentManager.getInstance().getFile(editor.getDocument());

    checkNoWriteAccess();

    CompletionAssertions.checkEditorValid(editor);

    if (editor.isViewer()) {
      editor.getDocument().fireReadOnlyModificationAttempt();
      return;
    }

    if (invokedExplicitly) {
      CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
    }

    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)
        || !FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
      return;
    }

    psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);

    CompletionPhase phase = CompletionServiceImpl.getCompletionPhase();
    boolean repeated =
        phase.indicator != null && phase.indicator.isRepeatedInvocation(myCompletionType, editor);
    /*
    if (repeated && isAutocompleteCommonPrefixOnInvocation() && phase.fillInCommonPrefix()) {
      return;
    }
    */

    int newTime = phase.newCompletionStarted(time, repeated);
    if (invokedExplicitly) {
      time = newTime;
    }
    if (CompletionServiceImpl.isPhase(CompletionPhase.InsertedSingleItem.class)) {
      CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
    }
    CompletionServiceImpl.assertPhase(
        CompletionPhase.NoCompletion.getClass(), CompletionPhase.CommittingDocuments.class);

    if (time > 1) {
      if (myCompletionType == CompletionType.BASIC) {
        FeatureUsageTracker.getInstance()
            .triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION);
      }
    }

    final CompletionInitializationContext[] initializationContext = {null};

    Runnable initCmd =
        new Runnable() {
          @Override
          public void run() {
            Runnable runnable =
                new Runnable() {
                  @Override
                  public void run() {
                    EditorUtil.fillVirtualSpaceUntilCaret(editor);
                    PsiDocumentManager.getInstance(project).commitAllDocuments();

                    CompletionAssertions.assertCommitSuccessful(editor, psiFile);
                    CompletionAssertions.checkEditorValid(editor);

                    initializationContext[0] = runContributorsBeforeCompletion(editor, psiFile);
                  }
                };
            ApplicationManager.getApplication().runWriteAction(runnable);
          }
        };
    if (autopopup) {
      CommandProcessor.getInstance().runUndoTransparentAction(initCmd);
      if (!restarted && shouldSkipAutoPopup(editor, psiFile)) {
        CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
        return;
      }
    } else {
      CommandProcessor.getInstance().executeCommand(project, initCmd, null, null);
    }

    insertDummyIdentifier(initializationContext[0], hasModifiers, time);
  }
 private void selectPsiElement(PsiElement element, boolean requestFocus) {
   VirtualFile virtualFile = PsiUtilBase.getVirtualFile(element);
   FavoritesTreeViewPanel.this.selectElement(element, virtualFile, requestFocus);
 }
  @Override
  protected void performRefactoring(UsageInfo[] usages) {
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);

    PsiType initializerType = mySettings.getSelectedType();

    // Changing external occurrences (the tricky part)

    IntroduceParameterUtil.processUsages(usages, this);

    final GrMethod toReplaceIn = (GrMethod) mySettings.getToReplaceIn();
    final PsiMethod toSearchFor = (PsiMethod) mySettings.getToSearchFor();

    final boolean methodsToProcessAreDifferent = toReplaceIn != toSearchFor;
    if (mySettings.generateDelegate()) {
      GroovyIntroduceParameterUtil.generateDelegate(toReplaceIn, myParameterInitializer, myProject);
      if (methodsToProcessAreDifferent) {
        final GrMethod method =
            GroovyIntroduceParameterUtil.generateDelegate(
                toSearchFor, myParameterInitializer, myProject);
        final PsiClass containingClass = method.getContainingClass();
        if (containingClass != null && containingClass.isInterface()) {
          final GrOpenBlock block = method.getBlock();
          if (block != null) {
            block.delete();
          }
        }
      }
    }

    // Changing signature of initial method
    // (signature of myMethodToReplaceIn will be either changed now or have already been changed)
    LOG.assertTrue(initializerType == null || initializerType.isValid());

    final FieldConflictsResolver fieldConflictsResolver =
        new FieldConflictsResolver(mySettings.getName(), toReplaceIn.getBlock());
    IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(
        new UsageInfo(toReplaceIn), usages, this);
    if (methodsToProcessAreDifferent) {
      IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(
          new UsageInfo(toSearchFor), usages, this);
    }

    // Replacing expression occurrences
    for (UsageInfo usage : usages) {
      if (usage instanceof ChangedMethodCallInfo) {
        PsiElement element = usage.getElement();

        GroovyIntroduceParameterUtil.processChangedMethodCall(element, mySettings, myProject);
      } else if (usage instanceof InternalUsageInfo) {
        PsiElement element = usage.getElement();
        if (element == null) continue;
        GrExpression newExpr = factory.createExpressionFromText(mySettings.getName());
        if (element instanceof GrExpression) {
          ((GrExpression) element).replaceWithExpression(newExpr, true);
        } else {
          element.replace(newExpr);
        }
      }
    }

    final StringPartInfo stringPartInfo = mySettings.getStringPartInfo();
    if (stringPartInfo != null) {
      final GrExpression expr =
          GrIntroduceHandlerBase.processLiteral(
              mySettings.getName(), mySettings.getStringPartInfo(), mySettings.getProject());
      final Editor editor = PsiUtilBase.findEditor(expr);
      if (editor != null) {
        editor.getSelectionModel().removeSelection();
        editor.getCaretModel().moveToOffset(expr.getTextRange().getEndOffset());
      }
    }

    final GrVariable var = mySettings.getVar();
    if (var != null && mySettings.removeLocalVariable()) {
      var.delete();
    }
    fieldConflictsResolver.fix();
  }
Exemplo n.º 27
0
 public static PsiElement[] collect(final Matcher matcher) {
   if (matcher == null) return PsiElement.EMPTY_ARRAY;
   final List<PsiElement> found = process(matcher, false);
   return PsiUtilBase.toPsiElementArray(found);
 }
  @Override
  protected JComponent createCenterPanel() {
    myTitledSeparator.setText(myAnalysisNoon);

    // include test option
    myInspectTestSource.setSelected(myAnalysisOptions.ANALYZE_TEST_SOURCES);

    // module scope if applicable
    myModuleButton.setText(
        AnalysisScopeBundle.message("scope.option.module.with.mnemonic", myModuleName));
    boolean useModuleScope = false;
    if (myModuleName != null) {
      useModuleScope = myAnalysisOptions.SCOPE_TYPE == AnalysisScope.MODULE;
      myModuleButton.setSelected(myRememberScope && useModuleScope);
    }

    myModuleButton.setVisible(
        myModuleName != null && ModuleManager.getInstance(myProject).getModules().length > 1);

    boolean useUncommitedFiles = false;
    final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
    final boolean hasVCS = !changeListManager.getAffectedFiles().isEmpty();
    if (hasVCS) {
      useUncommitedFiles = myAnalysisOptions.SCOPE_TYPE == AnalysisScope.UNCOMMITTED_FILES;
      myUncommitedFilesButton.setSelected(myRememberScope && useUncommitedFiles);
    }
    myUncommitedFilesButton.setVisible(hasVCS);

    DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(ALL);
    final List<? extends ChangeList> changeLists = changeListManager.getChangeListsCopy();
    for (ChangeList changeList : changeLists) {
      model.addElement(changeList.getName());
    }
    myChangeLists.setModel(model);
    myChangeLists.setEnabled(myUncommitedFilesButton.isSelected());
    myChangeLists.setVisible(hasVCS);

    // file/package/directory/module scope
    if (myFileName != null) {
      myFileButton.setText(myFileName);
      myFileButton.setMnemonic(myFileName.charAt(getSelectedScopeMnemonic()));
    } else {
      myFileButton.setVisible(false);
    }

    VirtualFile file = PsiUtilBase.getVirtualFile(myContext);
    ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
    boolean searchInLib =
        file != null && (fileIndex.isInLibraryClasses(file) || fileIndex.isInLibrarySource(file));

    String preselect =
        StringUtil.isEmptyOrSpaces(myAnalysisOptions.CUSTOM_SCOPE_NAME)
            ? FindSettings.getInstance().getDefaultScopeName()
            : myAnalysisOptions.CUSTOM_SCOPE_NAME;
    if (searchInLib
        && GlobalSearchScope.projectScope(myProject).getDisplayName().equals(preselect)) {
      preselect = GlobalSearchScope.allScope(myProject).getDisplayName();
    }
    if (GlobalSearchScope.allScope(myProject).getDisplayName().equals(preselect)
        && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.CUSTOM) {
      myAnalysisOptions.CUSTOM_SCOPE_NAME = preselect;
      searchInLib = true;
    }

    // custom scope
    myCustomScopeButton.setSelected(
        myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.CUSTOM);

    myScopeCombo.init(myProject, searchInLib, true, preselect);

    // correct selection
    myProjectButton.setSelected(
        myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.PROJECT
            || myFileName == null);
    myFileButton.setSelected(
        myFileName != null
            && (!myRememberScope
                || myAnalysisOptions.SCOPE_TYPE != AnalysisScope.PROJECT
                    && !useModuleScope
                    && myAnalysisOptions.SCOPE_TYPE != AnalysisScope.CUSTOM
                    && !useUncommitedFiles));

    myScopeCombo.setEnabled(myCustomScopeButton.isSelected());

    final ActionListener radioButtonPressed =
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            onScopeRadioButtonPressed();
          }
        };
    final Enumeration<AbstractButton> enumeration = myGroup.getElements();
    while (enumeration.hasMoreElements()) {
      enumeration.nextElement().addActionListener(radioButtonPressed);
    }

    // additional panel - inspection profile chooser
    JPanel wholePanel = new JPanel(new BorderLayout());
    wholePanel.add(myPanel, BorderLayout.NORTH);
    final JComponent additionalPanel = getAdditionalActionSettings(myProject);
    if (additionalPanel != null) {
      wholePanel.add(additionalPanel, BorderLayout.CENTER);
    }
    new RadioUpDownListener(
        myProjectButton,
        myModuleButton,
        myUncommitedFilesButton,
        myFileButton,
        myCustomScopeButton);
    return wholePanel;
  }