private static PsiDirectory[] suggestMostAppropriateDirectories(PsiPackage psiPackage) {
    final Project project = psiPackage.getProject();
    PsiDirectory[] directories = null;
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null) {
      final Document document = editor.getDocument();
      final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
      if (psiFile != null) {
        final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
        if (module != null) {
          directories =
              psiPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
        } else {
          directories =
              psiPackage.getDirectories(
                  GlobalSearchScope.notScope(GlobalSearchScope.projectScope(project)));
        }
      }
    }

    if (directories == null || directories.length == 0) {
      directories = psiPackage.getDirectories();
    }
    return directories;
  }
  @NotNull
  public static Collection<PsiFileSystemItem> getAbsoluteTopLevelDirLocations(
      final @NotNull PsiFile file) {

    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) {
      return Collections.emptyList();
    }
    final Project project = file.getProject();
    PsiDirectory parent = file.getParent();
    final Module module = ModuleUtil.findModuleForPsiElement(parent == null ? file : parent);
    if (module == null) {
      return Collections.emptyList();
    }
    final FileReferenceHelper[] helpers = FileReferenceHelperRegistrar.getHelpers();
    final ArrayList<PsiFileSystemItem> list = new ArrayList<PsiFileSystemItem>();
    for (FileReferenceHelper helper : helpers) {
      if (helper.isMine(project, virtualFile)) {
        final Collection<PsiFileSystemItem> roots = helper.getRoots(module);
        for (PsiFileSystemItem root : roots) {
          LOG.assertTrue(root != null, "Helper " + helper + " produced a null root for " + file);
        }
        list.addAll(roots);
      }
    }

    if (list.size() == 0) {
      list.addAll(FileReferenceHelperRegistrar.getNotNullHelper(file).getRoots(module));
    }
    return list;
  }
  @NotNull
  public List<? extends LocalQuickFix> registerFixes(final FileReference reference) {
    final PsiElement element = reference.getElement();
    if (!(reference instanceof JSFlexFileReference)
        || !(element instanceof JSAttributeNameValuePair)) return Collections.emptyList();

    final PsiElement parent = element.getParent();
    if (!(parent instanceof JSAttribute)
        || !FlexAnnotationNames.EMBED.equals(((JSAttribute) parent).getName())) {
      return Collections.emptyList();
    }

    final String value = ((JSAttributeNameValuePair) element).getSimpleValue();
    if (value.startsWith("/")) return Collections.emptyList();

    final Module module = ModuleUtil.findModuleForPsiElement(element);
    if (module == null) return Collections.emptyList();

    final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
    final VirtualFile virtualFile = element.getContainingFile().getVirtualFile();
    final boolean testSourceRoot =
        virtualFile != null && rootManager.getFileIndex().isInTestSourceContent(virtualFile);

    for (VirtualFile sourceRoot : rootManager.getSourceRoots(testSourceRoot)) {
      if (sourceRoot.findFileByRelativePath(value) != null) {
        return Collections.singletonList(
            new AddLeadingSlashFix((JSAttributeNameValuePair) element));
      }
    }

    return Collections.emptyList();
  }
  @NotNull
  @Override
  public Collection<AbstractTreeNode> modify(
      @NotNull final AbstractTreeNode node,
      @NotNull Collection<AbstractTreeNode> collection,
      ViewSettings settings) {
    final Project project = node.getProject();
    if (node instanceof PsiDirectoryNode && project != null) {
      final Module module =
          ModuleUtil.findModuleForPsiElement(((PsiDirectoryNode) node).getValue());
      final Optional<String> buildPath =
          module != null
              ? PantsUtil.getPathFromAddress(
                  module, ExternalSystemConstants.LINKED_PROJECT_PATH_KEY)
              : Optional.empty();
      if (buildPath.isPresent()) {
        final Optional<VirtualFile> buildFile =
            PantsUtil.findFileRelativeToBuildRoot(project, buildPath.get());

        boolean isModuleRoot =
            ArrayUtil.indexOf(
                    ModuleRootManager.getInstance(module).getContentRoots(),
                    ((PsiDirectoryNode) node).getVirtualFile())
                >= 0;
        if (buildFile.isPresent() && isModuleRoot) {
          // Check if there's already a BUILD file in the directory; if so, we don't add another
          final AbstractTreeNode existingBuildFile =
              ContainerUtil.find(
                  collection.iterator(),
                  new Condition<AbstractTreeNode>() {
                    @Override
                    public boolean value(AbstractTreeNode node) {
                      return node instanceof PsiFileNode
                          && buildFile.get().equals(((PsiFileNode) node).getVirtualFile());
                    }
                  });
          if (existingBuildFile == null) {
            final PsiFile buildPsiFile = PsiManager.getInstance(project).findFile(buildFile.get());
            final PsiFileNode buildNode =
                new PsiFileNode(project, buildPsiFile, settings) {
                  @Override
                  protected void updateImpl(PresentationData data) {
                    super.updateImpl(data);
                    data.setIcon(PantsIcons.Icon);
                  }
                };
            final List<AbstractTreeNode> modifiedCollection =
                new ArrayList<AbstractTreeNode>(collection);
            modifiedCollection.add(buildNode);
            return modifiedCollection;
          }
        }
      }
    }
    return collection;
  }
 private static PsiDirectory getWritableModuleDirectory(
     @NotNull Query<VirtualFile> vFiles, @NotNull Module module, PsiManager manager) {
   for (VirtualFile vFile : vFiles) {
     if (ModuleUtil.findModuleForFile(vFile, module.getProject()) != module) continue;
     PsiDirectory directory = manager.findDirectory(vFile);
     if (directory != null && directory.isValid() && directory.isWritable()) {
       return directory;
     }
   }
   return null;
 }
 private GlobalSearchScope getScope() {
   final GlobalSearchScope scope = myJavaClassReferenceSet.getProvider().getScope();
   if (scope == null) {
     final Module module = ModuleUtil.findModuleForPsiElement(getElement());
     if (module != null) {
       return module.getModuleWithDependenciesAndLibrariesScope(true);
     }
     return GlobalSearchScope.allScope(getElement().getProject());
   }
   return scope;
 }
 public static boolean isAccessible(
     final Project project, final VirtualFile virtualFile, final VirtualFile targetVirtualFile) {
   final boolean inTestSourceContent =
       ProjectRootManager.getInstance(project).getFileIndex().isInTestSourceContent(virtualFile);
   final Module module = ModuleUtil.findModuleForFile(virtualFile, project);
   if (targetVirtualFile != null
       && module != null
       && !GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, inTestSourceContent)
           .contains(targetVirtualFile)) {
     return false;
   }
   return true;
 }
 @Override
 protected void notifyByBalloon(
     JUnitRunningModel model, boolean started, final JUnitConsoleProperties consoleProperties) {
   if (myFoundTests) {
     super.notifyByBalloon(model, started, consoleProperties);
   } else {
     final String packageName = myConfiguration.getPackage();
     if (packageName == null) return;
     final Project project = myConfiguration.getProject();
     final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
     if (aPackage == null) return;
     final Module module = myConfiguration.getConfigurationModule().getModule();
     if (module == null) return;
     final Set<Module> modulesWithPackage = new HashSet<Module>();
     final PsiDirectory[] directories = aPackage.getDirectories();
     for (PsiDirectory directory : directories) {
       final Module currentModule =
           ModuleUtil.findModuleForFile(directory.getVirtualFile(), project);
       if (module != currentModule && currentModule != null) {
         modulesWithPackage.add(currentModule);
       }
     }
     if (!modulesWithPackage.isEmpty()) {
       final String testRunDebugId =
           consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN;
       final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
       final Function<Module, String> moduleNameRef =
           new Function<Module, String>() {
             @Override
             public String fun(Module module) {
               final String moduleName = module.getName();
               return "<a href=\"" + moduleName + "\">" + moduleName + "</a>";
             }
           };
       String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use ";
       if (modulesWithPackage.size() == 1) {
         message += "module \"" + moduleNameRef.fun(modulesWithPackage.iterator().next()) + "\" ";
       } else {
         message += "one of\n" + StringUtil.join(modulesWithPackage, moduleNameRef, "\n") + "\n";
       }
       message += "instead";
       toolWindowManager.notifyByBalloon(
           testRunDebugId,
           MessageType.WARNING,
           message,
           null,
           new ResetConfigurationModuleAdapter(
               project, consoleProperties, toolWindowManager, testRunDebugId));
     }
   }
 }
    public void beforeChildMovement(@NotNull final PsiTreeChangeEvent event) {
      final PsiElement oldParent = event.getOldParent();
      final PsiElement newParent = event.getNewParent();
      final PsiElement child = event.getChild();
      if (newParent instanceof PsiDirectory) {
        final Module module = ModuleUtil.findModuleForPsiElement(newParent);
        if (module == null) return;
        AbstractUrl childUrl = null;
        if (child instanceof PsiFile) {
          childUrl =
              new PsiFileUrl(
                  ((PsiDirectory) newParent).getVirtualFile().getUrl()
                      + "/"
                      + ((PsiFile) child).getName());
        } else if (child instanceof PsiDirectory) {
          childUrl =
              new DirectoryUrl(
                  ((PsiDirectory) newParent).getVirtualFile().getUrl()
                      + "/"
                      + ((PsiDirectory) child).getName(),
                  module.getName());
        }

        for (String listName : myName2FavoritesRoots.keySet()) {
          final List<TreeItem<Pair<AbstractUrl, String>>> roots =
              myName2FavoritesRoots.get(listName);
          final AbstractUrl finalChildUrl = childUrl;
          iterateTreeItems(
              roots,
              new Consumer<TreeItem<Pair<AbstractUrl, String>>>() {
                @Override
                public void consume(TreeItem<Pair<AbstractUrl, String>> item) {
                  final Pair<AbstractUrl, String> root = item.getData();
                  final Object[] path = root.first.createPath(myProject);
                  if (path == null || path.length < 1 || path[0] == null) {
                    return;
                  }
                  final Object element = path[path.length - 1];
                  if (element == child && finalChildUrl != null) {
                    item.setData(Pair.create(finalChildUrl, root.second));
                  } else {
                    if (element == oldParent) {
                      item.setData(
                          Pair.create(root.first.createUrlByElement(newParent), root.second));
                    }
                  }
                }
              });
        }
      }
    }
  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(
      @NotNull final ProblemsHolder holder,
      final boolean isOnTheFly,
      final LocalInspectionToolSession session) {
    final PsiFile file = session.getFile();
    Module module = ModuleUtil.findModuleForPsiElement(file);
    if (module == null) return super.buildVisitor(holder, isOnTheFly, session);
    final GlobalSearchScope searchScope = GlobalSearchScope.moduleWithDependentsScope(module);
    final PsiSearchHelper searchHelper = file.getManager().getSearchHelper();
    return new PsiElementVisitor() {
      @Override
      public void visitElement(PsiElement element) {
        if (!(element instanceof Property)) return;
        Property property = (Property) element;

        final ProgressIndicator original = ProgressManager.getInstance().getProgressIndicator();
        if (original != null) {
          if (original.isCanceled()) return;
          original.setText(
              PropertiesBundle.message(
                  "searching.for.property.key.progress.text", property.getUnescapedKey()));
        }

        String name = property.getName();
        if (name == null) return;
        PsiSearchHelper.SearchCostResult cheapEnough =
            searchHelper.isCheapEnoughToSearch(name, searchScope, file, original);
        if (cheapEnough == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return;

        final PsiReference usage =
            cheapEnough == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES
                ? null
                : ReferencesSearch.search(property, searchScope, false).findFirst();
        if (usage != null) return;
        final ASTNode propertyNode = property.getNode();
        assert propertyNode != null;

        ASTNode[] nodes = propertyNode.getChildren(null);
        PsiElement key = nodes.length == 0 ? property : nodes[0].getPsi();
        String description = PropertiesBundle.message("unused.property.problem.descriptor.name");

        holder.registerProblem(
            key,
            description,
            ProblemHighlightType.LIKE_UNUSED_SYMBOL,
            RemovePropertyLocalFix.INSTANCE);
      }
    };
  }
  @Override
  public ProblemDescriptor[] checkClass(
      @NotNull PsiClass aClass, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Project project = aClass.getProject();
    final PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
    final Module module = ModuleUtil.findModuleForPsiElement(aClass);

    if (nameIdentifier == null || module == null || !PsiUtil.isInstanciatable(aClass)) return null;

    final PsiClass base =
        JavaPsiFacade.getInstance(project)
            .findClass(INTENTION, GlobalSearchScope.allScope(project));

    if (base == null || !aClass.isInheritor(base, true)) return null;

    String descriptionDir = getDescriptionDirName(aClass);
    if (StringUtil.isEmptyOrSpaces(descriptionDir)) {
      return null;
    }

    for (PsiDirectory description : getIntentionDescriptionsDirs(module)) {
      PsiDirectory dir = description.findSubdirectory(descriptionDir);
      if (dir == null) continue;
      final PsiFile descr = dir.findFile("description.html");
      if (descr != null) {
        if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) {
          PsiElement problem = aClass.getNameIdentifier();
          ProblemDescriptor problemDescriptor =
              manager.createProblemDescriptor(
                  problem == null ? nameIdentifier : problem,
                  "Intention must have 'before.*.template' and 'after.*.template' beside 'description.html'",
                  isOnTheFly,
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
          return new ProblemDescriptor[] {problemDescriptor};
        }

        return null;
      }
    }

    final PsiElement problem = aClass.getNameIdentifier();
    final ProblemDescriptor problemDescriptor =
        manager.createProblemDescriptor(
            problem == null ? nameIdentifier : problem,
            "Intention does not have a description",
            isOnTheFly,
            new LocalQuickFix[] {new CreateHtmlDescriptionFix(descriptionDir, module, true)},
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    return new ProblemDescriptor[] {problemDescriptor};
  }
 @Nullable
 private XmlNSDescriptor getImplicitNamespaceDescriptor(String ns) {
   PsiFile file = getContainingFile();
   if (file == null) return null;
   Module module = ModuleUtil.findModuleForPsiElement(file);
   if (module != null) {
     for (ImplicitNamespaceDescriptorProvider provider :
         Extensions.getExtensions(ImplicitNamespaceDescriptorProvider.EP_NAME)) {
       XmlNSDescriptor nsDescriptor = provider.getNamespaceDescriptor(module, ns, file);
       if (nsDescriptor != null) return nsDescriptor;
     }
   }
   return null;
 }
  private MavenRunnerParameters createBuildParameters(Location l) {
    final PsiElement element = l.getPsiElement();
    final Project project = l.getProject();

    final Module module = ModuleUtil.findModuleForPsiElement(element);
    if (module == null) return null;

    final MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
    final MavenProject mavenProject = mavenProjectsManager.findProject(module);

    if (mavenProject == null) return null;

    // todo: check this code
    final List<MavenArtifact> dependencies = mavenProject.getDependencies();
    MavenArtifact artifact = null;
    for (MavenArtifact dependence : dependencies) {
      if (dependence.getArtifactId().equals(GROUP_ID_LIFT)) {
        artifact = dependence;
        break;
      } else if (dependence.getArtifactId().equals(ARTIFACT_ID_LIFT)) {
        artifact = dependence;
        break;
      }
    }
    // final MavenArtifact artifact = mavenProjectModel.findDependency(GROUP_ID_LIFT,
    // ARTIFACT_ID_LIFT);

    if (artifact == null) return null;

    mySourceElement = element;

    MavenExplicitProfiles profiles =
        MavenProjectsManager.getInstance(project).getExplicitProfiles();
    List<String> goals = new ArrayList<String>();

    goals.add(JETTY_RUN);

    final VirtualFile file = module.getModuleFile();
    if (file == null) return null;

    final VirtualFile parent = file.getParent();
    if (parent == null) return null;

    return new MavenRunnerParameters(true, parent.getPath(), goals, profiles);
  }
  public static Collection<JSQualifiedNamedElement> getCandidates(
      final Editor editor, final PsiFile file, final String name) {
    final Module module = ModuleUtil.findModuleForPsiElement(file);
    if (module != null) {
      GlobalSearchScope searchScope;
      VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile instanceof VirtualFileWindow)
        virtualFile = ((VirtualFileWindow) virtualFile).getDelegate();

      if (GlobalSearchScopes.projectProductionScope(file.getProject())
          .contains(virtualFile)) { // skip tests suggestions
        searchScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false);
      } else {
        searchScope = JSResolveUtil.getResolveScope(file);
      }
      return JSResolveUtil.findElementsByName(name, editor.getProject(), searchScope);
    } else {
      return Collections.emptyList();
    }
  }
    public void beforePropertyChange(@NotNull final PsiTreeChangeEvent event) {
      if (event.getPropertyName().equals(PsiTreeChangeEvent.PROP_FILE_NAME)
          || event.getPropertyName().equals(PsiTreeChangeEvent.PROP_DIRECTORY_NAME)) {
        final PsiElement psiElement = event.getChild();
        if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
          final Module module = ModuleUtil.findModuleForPsiElement(psiElement);
          if (module == null) return;
          final String url =
              ((PsiDirectory) psiElement.getParent()).getVirtualFile().getUrl()
                  + "/"
                  + event.getNewValue();
          final AbstractUrl childUrl =
              psiElement instanceof PsiFile
                  ? new PsiFileUrl(url)
                  : new DirectoryUrl(url, module.getName());

          for (String listName : myName2FavoritesRoots.keySet()) {
            final List<TreeItem<Pair<AbstractUrl, String>>> roots =
                myName2FavoritesRoots.get(listName);
            iterateTreeItems(
                roots,
                new Consumer<TreeItem<Pair<AbstractUrl, String>>>() {
                  @Override
                  public void consume(TreeItem<Pair<AbstractUrl, String>> item) {
                    final Pair<AbstractUrl, String> root = item.getData();
                    final Object[] path = root.first.createPath(myProject);
                    if (path == null || path.length < 1 || path[0] == null) {
                      return;
                    }
                    final Object element = path[path.length - 1];
                    if (element == psiElement && psiElement instanceof PsiFile) {
                      item.setData(Pair.create(childUrl, root.second));
                    } else {
                      item.setData(root);
                    }
                  }
                });
          }
        }
      }
    }
Exemple #16
0
  @NotNull
  @Override
  public List<SearchScope> getPredefinedScopes(
      @NotNull final Project project,
      @Nullable final DataContext dataContext,
      boolean suggestSearchInLibs,
      boolean prevSearchFiles,
      boolean currentSelection,
      boolean usageView,
      boolean showEmptyScopes) {
    Collection<SearchScope> result = ContainerUtil.newLinkedHashSet();
    result.add(GlobalSearchScope.projectScope(project));
    if (suggestSearchInLibs) {
      result.add(GlobalSearchScope.allScope(project));
    }

    if (ModuleUtil.isSupportedRootType(project, JavaSourceRootType.TEST_SOURCE)) {
      result.add(GlobalSearchScopesCore.projectProductionScope(project));
      result.add(GlobalSearchScopesCore.projectTestScope(project));
    }

    final GlobalSearchScope openFilesScope = GlobalSearchScopes.openFilesScope(project);
    if (openFilesScope != GlobalSearchScope.EMPTY_SCOPE) {
      result.add(openFilesScope);
    } else if (showEmptyScopes) {
      result.add(
          new LocalSearchScope(PsiElement.EMPTY_ARRAY, IdeBundle.message("scope.open.files")));
    }

    final Editor selectedTextEditor =
        ApplicationManager.getApplication().isDispatchThread()
            ? FileEditorManager.getInstance(project).getSelectedTextEditor()
            : null;
    final PsiFile psiFile =
        (selectedTextEditor != null)
            ? PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument())
            : null;
    PsiFile currentFile = psiFile;

    if (dataContext != null) {
      PsiElement dataContextElement = CommonDataKeys.PSI_FILE.getData(dataContext);
      if (dataContextElement == null) {
        dataContextElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      }

      if (dataContextElement == null && psiFile != null) {
        dataContextElement = psiFile;
      }

      if (dataContextElement != null) {
        if (!PlatformUtils.isCidr()) { // TODO: have an API to disable module scopes.
          Module module = ModuleUtilCore.findModuleForPsiElement(dataContextElement);
          if (module == null) {
            module = LangDataKeys.MODULE.getData(dataContext);
          }
          if (module != null && !(ModuleType.get(module) instanceof InternalModuleType)) {
            result.add(module.getModuleScope());
          }
        }
        if (currentFile == null) {
          currentFile = dataContextElement.getContainingFile();
        }
      }
    }

    if (currentFile != null || showEmptyScopes) {
      PsiElement[] scope =
          currentFile != null ? new PsiElement[] {currentFile} : PsiElement.EMPTY_ARRAY;
      result.add(new LocalSearchScope(scope, IdeBundle.message("scope.current.file")));
    }

    if (currentSelection && selectedTextEditor != null && psiFile != null) {
      SelectionModel selectionModel = selectedTextEditor.getSelectionModel();
      if (selectionModel.hasSelection()) {
        int start = selectionModel.getSelectionStart();
        final PsiElement startElement = psiFile.findElementAt(start);
        if (startElement != null) {
          int end = selectionModel.getSelectionEnd();
          final PsiElement endElement = psiFile.findElementAt(end);
          if (endElement != null) {
            final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
            if (parent != null) {
              final List<PsiElement> elements = new ArrayList<PsiElement>();
              final PsiElement[] children = parent.getChildren();
              TextRange selection = new TextRange(start, end);
              for (PsiElement child : children) {
                if (!(child instanceof PsiWhiteSpace)
                    && child.getContainingFile() != null
                    && selection.contains(child.getTextOffset())) {
                  elements.add(child);
                }
              }
              if (!elements.isEmpty()) {
                SearchScope local =
                    new LocalSearchScope(
                        PsiUtilCore.toPsiElementArray(elements),
                        IdeBundle.message("scope.selection"));
                result.add(local);
              }
            }
          }
        }
      }
    }

    if (usageView) {
      addHierarchyScope(project, result);
      UsageView selectedUsageView = UsageViewManager.getInstance(project).getSelectedUsageView();
      if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
        final Set<Usage> usages = ContainerUtil.newTroveSet(selectedUsageView.getUsages());
        usages.removeAll(selectedUsageView.getExcludedUsages());
        final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());

        if (prevSearchFiles) {
          final Set<VirtualFile> files = collectFiles(usages, true);
          if (!files.isEmpty()) {
            GlobalSearchScope prev =
                new GlobalSearchScope(project) {
                  private Set<VirtualFile> myFiles = null;

                  @NotNull
                  @Override
                  public String getDisplayName() {
                    return IdeBundle.message("scope.files.in.previous.search.result");
                  }

                  @Override
                  public synchronized boolean contains(@NotNull VirtualFile file) {
                    if (myFiles == null) {
                      myFiles = collectFiles(usages, false);
                    }
                    return myFiles.contains(file);
                  }

                  @Override
                  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
                    return 0;
                  }

                  @Override
                  public boolean isSearchInModuleContent(@NotNull Module aModule) {
                    return true;
                  }

                  @Override
                  public boolean isSearchInLibraries() {
                    return true;
                  }
                };
            result.add(prev);
          }
        } else {
          for (Usage usage : usages) {
            if (usage instanceof PsiElementUsage) {
              final PsiElement element = ((PsiElementUsage) usage).getElement();
              if (element != null && element.isValid() && element.getContainingFile() != null) {
                results.add(element);
              }
            }
          }

          if (!results.isEmpty()) {
            result.add(
                new LocalSearchScope(
                    PsiUtilCore.toPsiElementArray(results),
                    IdeBundle.message("scope.previous.search.results")));
          }
        }
      }
    }

    final FavoritesManager favoritesManager = FavoritesManager.getInstance(project);
    if (favoritesManager != null) {
      for (final String favorite : favoritesManager.getAvailableFavoritesListNames()) {
        final Collection<TreeItem<Pair<AbstractUrl, String>>> rootUrls =
            favoritesManager.getFavoritesListRootUrls(favorite);
        if (rootUrls.isEmpty()) continue; // ignore unused root
        result.add(
            new GlobalSearchScope(project) {
              @NotNull
              @Override
              public String getDisplayName() {
                return "Favorite \'" + favorite + "\'";
              }

              @Override
              public boolean contains(@NotNull final VirtualFile file) {
                return ApplicationManager.getApplication()
                    .runReadAction(
                        (Computable<Boolean>) () -> favoritesManager.contains(favorite, file));
              }

              @Override
              public int compare(
                  @NotNull final VirtualFile file1, @NotNull final VirtualFile file2) {
                return 0;
              }

              @Override
              public boolean isSearchInModuleContent(@NotNull final Module aModule) {
                return true;
              }

              @Override
              public boolean isSearchInLibraries() {
                return true;
              }
            });
      }
    }

    ContainerUtil.addIfNotNull(result, getSelectedFilesScope(project, dataContext));

    return ContainerUtil.newArrayList(result);
  }
  /**
   * spring bean reference annotator
   *
   * @param psiElement psi element
   * @param holder annotation holder
   */
  public void annotate(PsiElement psiElement, AnnotationHolder holder) {
    if (!(psiElement instanceof PsiJavaFile)) {
      return;
    }

    // Get java classes
    for (PsiClass javaClass : ((PsiJavaFile) psiElement).getClasses()) {

      PsiClass superClass = javaClass.getSuperClass();
      PsiField[] superClassFields =
          superClass != null ? superClass.getAllFields() : new PsiField[] {};
      for (PsiField field : javaClass.getAllFields()) {
        // We don't need scan super class fields
        if (isContain(superClassFields, field)) {
          continue;
        }

        PsiModifierList modifierList = field.getModifierList();
        if (modifierList == null) {
          continue;
        }
        for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
          String qcName = psiAnnotation.getQualifiedName();
          if (qcName == null || !qcName.startsWith("org.unitils.spring.annotation.")) {
            continue;
          }

          SpringManager springManager = SpringManager.getInstance(psiElement.getProject());
          SpringModel springModel =
              springManager.getCombinedModel(ModuleUtil.findModuleForPsiElement(psiElement));
          if (springModel == null) {
            continue;
          }

          // by type
          if (qcName.endsWith("SpringBeanByType")) {
            final PsiType type = field.getType();
            if (!(type instanceof PsiClassType)) {
              continue;
            }
            final PsiClass typeClass = ((PsiClassType) type).resolve();
            if (typeClass == null) {
              continue;
            }
            List<SpringBaseBeanPointer> springBaseBeanPointerList =
                springModel.findBeansByPsiClass(typeClass);
            if (springBaseBeanPointerList.size() > 0) {
              List<PsiElement> elements = new ArrayList<PsiElement>();
              for (SpringBaseBeanPointer springBaseBeanPointer : springBaseBeanPointerList) {
                elements.add(springBaseBeanPointer.getPsiElement());
              }
              NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON)
                  .setTooltipText("Navigate to the spring bean declaration(s)")
                  .setTargets(elements)
                  .install(holder, field.getNameIdentifier());
            }
          }
          // by name
          else {
            String beanName = field.getName();
            if (qcName.endsWith("SpringBean")) {
              PsiAnnotationMemberValue attributeValue = psiAnnotation.findAttributeValue("value");
              if (attributeValue != null && attributeValue.getText() != null) {
                beanName = attributeValue.getText().replace("\"", "");
              }
            }
            if (beanName != null && StringUtil.isNotEmpty(beanName)) {
              SpringBeanPointer springBeanPointer = springModel.findBeanByName(beanName);
              if (springBeanPointer != null) {
                NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON)
                    .setTooltipText("Navigate to the spring bean declaration(s)")
                    .setTarget(springBeanPointer.getPsiElement())
                    .install(holder, field.getNameIdentifier());
              }
            }
          }
        }
      }
    }
  }
Exemple #18
0
  protected void initialize() {
    myDefaultConstructor = null;

    final PsiClass psiClass = getElement();

    LOG.assertTrue(psiClass != null);

    PsiElement psiParent = psiClass.getParent();
    if (psiParent instanceof PsiFile) {
      if (isSyntheticJSP()) {
        final RefFileImpl refFile =
            (RefFileImpl) getRefManager().getReference(JspPsiUtil.getJspFile(psiClass));
        LOG.assertTrue(refFile != null);
        refFile.add(this);
      } else if (psiParent instanceof PsiJavaFile) {
        PsiJavaFile psiFile = (PsiJavaFile) psiParent;
        String packageName = psiFile.getPackageName();
        if (!"".equals(packageName)) {
          ((RefPackageImpl) getRefJavaManager().getPackage(packageName)).add(this);
        } else {
          ((RefPackageImpl) getRefJavaManager().getDefaultPackage()).add(this);
        }
      }
      final Module module = ModuleUtil.findModuleForPsiElement(psiClass);
      LOG.assertTrue(module != null);
      final RefModuleImpl refModule = ((RefModuleImpl) getRefManager().getRefModule(module));
      LOG.assertTrue(refModule != null);
      refModule.add(this);
    } else {
      while (!(psiParent instanceof PsiClass
          || psiParent instanceof PsiMethod
          || psiParent instanceof PsiField)) {
        psiParent = psiParent.getParent();
      }
      RefElement refParent = getRefManager().getReference(psiParent);
      LOG.assertTrue(refParent != null);
      ((RefElementImpl) refParent).add(this);
    }

    setAbstract(psiClass.hasModifierProperty(PsiModifier.ABSTRACT));

    setAnonymous(psiClass instanceof PsiAnonymousClass);
    setIsLocal(!(isAnonymous() || psiParent instanceof PsiClass || psiParent instanceof PsiFile));
    setInterface(psiClass.isInterface());

    initializeSuperReferences(psiClass);

    PsiMethod[] psiMethods = psiClass.getMethods();
    PsiField[] psiFields = psiClass.getFields();

    setUtilityClass(psiMethods.length > 0 || psiFields.length > 0);

    for (PsiField psiField : psiFields) {
      getRefManager().getReference(psiField);
    }

    if (!isApplet()) {
      final PsiClass servlet = getRefJavaManager().getServlet();
      setServlet(servlet != null && psiClass.isInheritor(servlet, true));
    }
    if (!isApplet() && !isServlet()) {
      setTestCase(TestUtil.isTestClass(psiClass));
      for (RefClass refBase : getBaseClasses()) {
        ((RefClassImpl) refBase).setTestCase(true);
      }
    }

    for (PsiMethod psiMethod : psiMethods) {
      RefMethod refMethod = (RefMethod) getRefManager().getReference(psiMethod);

      if (refMethod != null) {
        if (psiMethod.isConstructor()) {
          if (psiMethod.getParameterList().getParametersCount() > 0
              || !psiMethod.hasModifierProperty(PsiModifier.PRIVATE)) {
            setUtilityClass(false);
          }

          addConstructor(refMethod);
          if (psiMethod.getParameterList().getParametersCount() == 0) {
            setDefaultConstructor((RefMethodImpl) refMethod);
          }
        } else {
          if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
            setUtilityClass(false);
          }
        }
      }
    }

    if (getConstructors().size() == 0 && !isInterface() && !isAnonymous()) {
      RefImplicitConstructorImpl refImplicitConstructor = new RefImplicitConstructorImpl(this);
      setDefaultConstructor(refImplicitConstructor);
      addConstructor(refImplicitConstructor);
    }

    if (isInterface()) {
      for (int i = 0; i < psiFields.length && isUtilityClass(); i++) {
        PsiField psiField = psiFields[i];
        if (!psiField.hasModifierProperty(PsiModifier.STATIC)) {
          setUtilityClass(false);
        }
      }
    }

    final PsiClass applet = getRefJavaManager().getApplet();
    setApplet(applet != null && psiClass.isInheritor(applet, true));
    getRefManager().fireNodeInitialized(this);
  }
 @Nullable
 public static Pair<Module, FlexUnitSupport> getModuleAndSupport(@NotNull PsiElement context) {
   final Module module = ModuleUtil.findModuleForPsiElement(context);
   final FlexUnitSupport support = getSupport(module);
   return support != null ? Pair.create(module, support) : null;
 }
  private PsiClass buildClass() {
    if (existingClass != null) {
      return existingClass;
    }
    final ParameterObjectBuilder beanClassBuilder = new ParameterObjectBuilder();
    beanClassBuilder.setVisibility(myCreateInnerClass ? PsiModifier.PRIVATE : PsiModifier.PUBLIC);
    beanClassBuilder.setProject(myProject);
    beanClassBuilder.setTypeArguments(typeParams);
    beanClassBuilder.setClassName(className);
    beanClassBuilder.setPackageName(packageName);
    for (ParameterChunk parameterChunk : parameters) {
      final VariableData parameter = parameterChunk.parameter;
      final boolean setterRequired = paramsNeedingSetters.contains(parameter.variable);
      beanClassBuilder.addField(
          (PsiParameter) parameter.variable, parameter.name, parameter.type, setterRequired);
    }
    final String classString = beanClassBuilder.buildBeanClass();

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(method.getProject());
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, classString);
      if (myCreateInnerClass) {
        final PsiClass containingClass = method.getContainingClass();
        final PsiClass[] classes = newFile.getClasses();
        assert classes.length > 0 : classString;
        final PsiClass innerClass = (PsiClass) containingClass.add(classes[0]);
        PsiUtil.setModifierProperty(innerClass, PsiModifier.STATIC, true);
        return (PsiClass)
            JavaCodeStyleManager.getInstance(newFile.getProject())
                .shortenClassReferences(innerClass);
      } else {
        final PsiFile containingFile = method.getContainingFile();
        final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
        final PsiDirectory directory;
        if (myMoveDestination != null) {
          directory = myMoveDestination.getTargetDirectory(containingDirectory);
        } else {
          final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
          directory =
              PackageUtil.findOrCreateDirectoryForPackage(
                  module, packageName, containingDirectory, true, true);
        }

        if (directory != null) {

          final CodeStyleManager codeStyleManager =
              CodeStyleManager.getInstance(method.getManager().getProject());
          final PsiElement shortenedFile =
              JavaCodeStyleManager.getInstance(newFile.getProject())
                  .shortenClassReferences(newFile);
          final PsiElement reformattedFile = codeStyleManager.reformat(shortenedFile);
          return ((PsiJavaFile) directory.add(reformattedFile)).getClasses()[0];
        }
      }
    } catch (IncorrectOperationException e) {
      logger.info(e);
    }
    return null;
  }
  @Override
  public boolean execute(
      @NotNull final PsiElement queryParameters, @NotNull final Processor<PsiElement> consumer) {
    if (queryParameters instanceof XmlTagImpl) {
      final XmlTagImpl xml = (XmlTagImpl) queryParameters;
      if (isTypeElement(xml)) {
        final Collection<SchemaTypeInfo> infos =
            ApplicationManager.getApplication()
                .runReadAction(
                    new Computable<Collection<SchemaTypeInfo>>() {

                      @Override
                      public Collection<SchemaTypeInfo> compute() {
                        return gatherInheritors(xml);
                      }
                    });

        if (infos != null && !infos.isEmpty()) {
          final Project project = XmlUtil.getContainingFile(xml).getProject();
          final Module module = ModuleUtil.findModuleForPsiElement(queryParameters);
          // if (module == null) return false;

          final XmlFile file = XmlUtil.getContainingFile(xml);
          final VirtualFile vf = file.getVirtualFile();
          String thisNs = XmlNamespaceIndex.getNamespace(vf, project);
          thisNs = thisNs == null ? getDefaultNs(file) : thisNs;
          // so thisNs can be null
          if (thisNs == null) return false;
          final ArrayList<SchemaTypeInfo> infosLst = new ArrayList<SchemaTypeInfo>(infos);
          Collections.sort(infosLst);
          final Map<String, Set<XmlFile>> nsMap = new HashMap<String, Set<XmlFile>>();
          for (final SchemaTypeInfo info : infosLst) {
            Set<XmlFile> targetFiles = nsMap.get(info.getNamespaceUri());
            if (targetFiles == null) {
              targetFiles = new HashSet<XmlFile>();
              if (Comparing.equal(info.getNamespaceUri(), thisNs)) {
                targetFiles.add(file);
              }
              final Collection<XmlFile> files =
                  ApplicationManager.getApplication()
                      .runReadAction(
                          new Computable<Collection<XmlFile>>() {
                            @Override
                            public Collection<XmlFile> compute() {
                              return XmlUtil.findNSFilesByURI(
                                  info.getNamespaceUri(), project, module);
                            }
                          });
              if (files != null) {
                targetFiles.addAll(files);
              }
              nsMap.put(info.getNamespaceUri(), targetFiles);
            }
            if (!targetFiles.isEmpty()) {
              for (final XmlFile targetFile : targetFiles) {
                ApplicationManager.getApplication()
                    .runReadAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            final String prefixByURI =
                                XmlUtil.findNamespacePrefixByURI(
                                    targetFile, info.getNamespaceUri());
                            if (prefixByURI == null) return;
                            final PsiElementProcessor processor =
                                new PsiElementProcessor() {
                                  @Override
                                  public boolean execute(@NotNull PsiElement element) {
                                    if (element instanceof XmlTagImpl) {
                                      if (isCertainTypeElement(
                                              (XmlTagImpl) element, info.getTagName(), prefixByURI)
                                          || isElementWithEmbeddedType(
                                              (XmlTagImpl) element,
                                              info.getTagName(),
                                              prefixByURI)) {
                                        consumer.process(element);
                                        return false;
                                      }
                                    }
                                    return true;
                                  }
                                };
                            XmlUtil.processXmlElements(targetFile, processor, true);
                          }
                        });
              }
            }
          }
        }
      }
    }
    return true;
  }
  private PsiClass buildClass() {
    final PsiManager manager = sourceClass.getManager();
    final Project project = sourceClass.getProject();
    final ExtractedClassBuilder extractedClassBuilder = new ExtractedClassBuilder();
    extractedClassBuilder.setProject(myProject);
    extractedClassBuilder.setClassName(newClassName);
    extractedClassBuilder.setPackageName(newPackageName);
    extractedClassBuilder.setOriginalClassName(sourceClass.getQualifiedName());
    extractedClassBuilder.setRequiresBackPointer(requiresBackpointer);
    extractedClassBuilder.setExtractAsEnum(enumConstants);
    for (PsiField field : fields) {
      extractedClassBuilder.addField(field);
    }
    for (PsiMethod method : methods) {
      extractedClassBuilder.addMethod(method);
    }
    for (PsiClass innerClass : innerClasses) {
      extractedClassBuilder.addInnerClass(
          innerClass, innerClassesToMakePublic.contains(innerClass));
    }
    extractedClassBuilder.setTypeArguments(typeParams);
    final List<PsiClass> interfaces = calculateInterfacesSupported();
    extractedClassBuilder.setInterfaces(interfaces);

    if (myGenerateAccessors) {
      final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
      sourceClass.accept(visitor);
      extractedClassBuilder.setFieldsNeedingGetters(visitor.getFieldsNeedingGetter());
      extractedClassBuilder.setFieldsNeedingSetters(visitor.getFieldsNeedingSetter());
    }

    final String classString = extractedClassBuilder.buildBeanClass();
    if (extractInnerClass) {
      final PsiFileFactory factory = PsiFileFactory.getInstance(project);
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(
                  newClassName + ".java", JavaFileType.INSTANCE, classString);
      final PsiClass psiClass = newFile.getClasses()[0];
      if (!psiClass.isEnum()) {
        final PsiModifierList modifierList = psiClass.getModifierList();
        assert modifierList != null;
        modifierList.setModifierProperty(PsiModifier.STATIC, true);
      }
      final PsiElement addedClass = sourceClass.add(psiClass);
      return (PsiClass)
          CodeStyleManager.getInstance(manager)
              .reformat(
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClass));
    }

    try {
      final PsiFile containingFile = sourceClass.getContainingFile();
      final PsiDirectory directory;
      final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
      if (myMoveDestination != null) {
        directory = myMoveDestination.getTargetDirectory(containingDirectory);
      } else {
        final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
        assert module != null;
        directory =
            PackageUtil.findOrCreateDirectoryForPackage(
                module, newPackageName, containingDirectory, false, true);
      }
      if (directory != null) {
        final PsiFileFactory factory = PsiFileFactory.getInstance(project);
        final PsiFile newFile =
            factory.createFileFromText(newClassName + ".java", JavaFileType.INSTANCE, classString);
        final PsiElement addedFile = directory.add(newFile);
        final CodeStyleManager codeStyleManager =
            CodeStyleManager.getInstance(manager.getProject());
        final PsiElement shortenedFile =
            JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedFile);
        return ((PsiJavaFile) codeStyleManager.reformat(shortenedFile)).getClasses()[0];
      } else {
        return null;
      }
    } catch (IncorrectOperationException e) {
      return null;
    }
  }
 public static Module getCurrentModule() {
   final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
   VirtualFile file =
       PlatformDataKeys.VIRTUAL_FILE.getData(DataManager.getInstance().getDataContext(owner));
   return ModuleUtil.findModuleForFile(file, getCurrentProject());
 }
 /**
  * Gets the StrutsFacet for the module containing the given PsiElement.
  *
  * @param element Element to check.
  * @return Instance or <code>null</code> if none configured.
  */
 @Nullable
 public static OfbizFacet getInstance(@NotNull final PsiElement element) {
   final Module module = ModuleUtil.findModuleForPsiElement(element);
   return module != null ? getInstance(module) : null;
 }
  public static List<SearchScope> getPredefinedScopes(
      @NotNull final Project project,
      @Nullable final DataContext dataContext,
      boolean suggestSearchInLibs,
      boolean prevSearchFiles,
      boolean currentSelection,
      boolean usageView) {
    ArrayList<SearchScope> result = new ArrayList<SearchScope>();
    result.add(GlobalSearchScope.projectScope(project));
    if (suggestSearchInLibs) {
      result.add(GlobalSearchScope.allScope(project));
    }

    if (!PlatformUtils.isCidr()
        && ModuleUtil.isSupportedRootType(
            project, JavaSourceRootType.TEST_SOURCE)) { // TODO: fix these scopes in AppCode
      result.add(GlobalSearchScopes.projectProductionScope(project));
      result.add(GlobalSearchScopes.projectTestScope(project));
    }

    result.add(GlobalSearchScopes.openFilesScope(project));

    if (dataContext != null) {
      PsiElement dataContextElement = CommonDataKeys.PSI_FILE.getData(dataContext);
      if (dataContextElement == null) {
        dataContextElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      }
      if (dataContextElement != null) {
        if (!PlatformUtils.isCidr()) { // TODO: have an API to disable module scopes.
          Module module = ModuleUtilCore.findModuleForPsiElement(dataContextElement);
          if (module == null) {
            module = LangDataKeys.MODULE.getData(dataContext);
          }
          if (module != null) {
            result.add(module.getModuleScope());
          }
        }
        if (dataContextElement.getContainingFile() != null) {
          result.add(
              new LocalSearchScope(dataContextElement, IdeBundle.message("scope.current.file")));
        }
      }
    }

    if (currentSelection) {
      FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
      final Editor selectedTextEditor = fileEditorManager.getSelectedTextEditor();
      if (selectedTextEditor != null) {
        final PsiFile psiFile =
            PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument());
        if (psiFile != null) {
          if (selectedTextEditor.getSelectionModel().hasSelection()) {
            final PsiElement startElement =
                psiFile.findElementAt(selectedTextEditor.getSelectionModel().getSelectionStart());
            if (startElement != null) {
              final PsiElement endElement =
                  psiFile.findElementAt(selectedTextEditor.getSelectionModel().getSelectionEnd());
              if (endElement != null) {
                final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
                if (parent != null) {
                  final List<PsiElement> elements = new ArrayList<PsiElement>();
                  final PsiElement[] children = parent.getChildren();
                  for (PsiElement child : children) {
                    if (!(child instanceof PsiWhiteSpace) && child.getContainingFile() != null) {
                      elements.add(child);
                    }
                  }
                  if (!elements.isEmpty()) {
                    SearchScope local =
                        new LocalSearchScope(
                            PsiUtilCore.toPsiElementArray(elements),
                            IdeBundle.message("scope.selection"));
                    result.add(local);
                  }
                }
              }
            }
          }
        }
      }
    }

    if (usageView) {
      UsageView selectedUsageView = UsageViewManager.getInstance(project).getSelectedUsageView();
      if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
        final Set<Usage> usages = selectedUsageView.getUsages();
        final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());

        if (prevSearchFiles) {
          final Set<VirtualFile> files = new HashSet<VirtualFile>();
          for (Usage usage : usages) {
            if (usage instanceof PsiElementUsage) {
              PsiElement psiElement = ((PsiElementUsage) usage).getElement();
              if (psiElement != null && psiElement.isValid()) {
                PsiFile psiFile = psiElement.getContainingFile();
                if (psiFile != null) {
                  VirtualFile file = psiFile.getVirtualFile();
                  if (file != null) files.add(file);
                }
              }
            }
          }
          if (!files.isEmpty()) {
            GlobalSearchScope prev =
                new GlobalSearchScope(project) {
                  @Override
                  public String getDisplayName() {
                    return IdeBundle.message("scope.files.in.previous.search.result");
                  }

                  @Override
                  public boolean contains(@NotNull VirtualFile file) {
                    return files.contains(file);
                  }

                  @Override
                  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
                    return 0;
                  }

                  @Override
                  public boolean isSearchInModuleContent(@NotNull Module aModule) {
                    return true;
                  }

                  @Override
                  public boolean isSearchInLibraries() {
                    return true;
                  }
                };
            result.add(prev);
          }
        } else {
          for (Usage usage : usages) {
            if (usage instanceof PsiElementUsage) {
              final PsiElement element = ((PsiElementUsage) usage).getElement();
              if (element != null && element.isValid() && element.getContainingFile() != null) {
                results.add(element);
              }
            }
          }

          if (!results.isEmpty()) {
            result.add(
                new LocalSearchScope(
                    PsiUtilCore.toPsiElementArray(results),
                    IdeBundle.message("scope.previous.search.results")));
          }
        }
      }
    }

    final FavoritesManager favoritesManager = FavoritesManager.getInstance(project);
    if (favoritesManager != null) {
      for (final String favorite : favoritesManager.getAvailableFavoritesListNames()) {
        final Collection<TreeItem<Pair<AbstractUrl, String>>> rootUrls =
            favoritesManager.getFavoritesListRootUrls(favorite);
        if (rootUrls.isEmpty()) continue; // ignore unused root
        result.add(
            new GlobalSearchScope(project) {
              @Override
              public String getDisplayName() {
                return "Favorite \'" + favorite + "\'";
              }

              @Override
              public boolean contains(@NotNull final VirtualFile file) {
                return favoritesManager.contains(favorite, file);
              }

              @Override
              public int compare(
                  @NotNull final VirtualFile file1, @NotNull final VirtualFile file2) {
                return 0;
              }

              @Override
              public boolean isSearchInModuleContent(@NotNull final Module aModule) {
                return true;
              }

              @Override
              public boolean isSearchInLibraries() {
                return true;
              }
            });
      }
    }

    if (dataContext != null) {
      final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
      if (files != null) {
        final List<VirtualFile> openFiles = Arrays.asList(files);
        result.add(
            new DelegatingGlobalSearchScope(GlobalSearchScope.filesScope(project, openFiles)) {
              @Override
              public String getDisplayName() {
                return "Selected Files";
              }
            });
      }
    }

    return result;
  }
  /**
   * Here we check if a given file belongs to our plugin. We take this road because we need the
   * actual file and not a filename to check files without extension.
   *
   * <p>A file is checked according to the rules defined in the facet settings. A file can be set to
   * ignored, accepted or auto. Auto means that the content is checked.
   *
   * @param file The file to check
   * @return True if BashSupport wants to take that file
   */
  public boolean isMyFileType(VirtualFile file) {
    if (file == null) {
      return false;
    }

    if (file.isDirectory()) {
      return false;
    }

    if (extensionList.contains(file.getExtension())) {
      return true;
    } else if (!file.isInLocalFileSystem()) {
      return false;
    } else if (StringUtils.isEmpty(file.getExtension())) {
      BashFacet facet = null;
      try {
        // no extensions, special checks (looking at the content, etc)

        // guess project
        Project project = ProjectUtil.guessProjectForFile(file);
        if (project == null) {
          return false;
        }

        DumbServiceImpl dumbService = DumbServiceImpl.getInstance(project);
        if (dumbService == null || dumbService.isDumb()) {
          return false;
        }

        DirectoryIndex directoryIndex = DirectoryIndex.getInstance(project);
        if (directoryIndex == null || !directoryIndex.isInitialized()) {
          return false;
        }

        Module module = ModuleUtil.findModuleForFile(file, project);
        if (module == null) {
          return false;
        }

        facet = BashFacet.getInstance(module);
        if (facet == null) {
          return false;
        }

        BashFacetConfiguration config = facet.getConfiguration();
        FileMode mode = config.findMode(file);

        if (mode == FileMode.accept()) {
          return true;
        } else if (mode == FileMode.ignore()) {
          return false;
        } else if (mode == FileMode.auto()) {
          return BashContentUtil.isProbablyBashFile(
              VfsUtil.virtualToIoFile(file),
              MIN_FILE_PROBABILIY,
              ProjectUtil.guessProjectForFile(file));
        }
      } catch (Exception e) {
        // ignore this
        LOG.warn("Could not check the file type due to exception", e);
      }
    }

    return false;
  }
  /** Should be invoked in command and write action */
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static void generateDataBindingMethods(final WizardData data) throws MyException {
    if (data.myBindToNewBean) {
      data.myBeanClass = createBeanClass(data);
    } else {
      if (!CommonRefactoringUtil.checkReadOnlyStatus(
          data.myBeanClass.getProject(), data.myBeanClass)) {
        return;
      }
    }

    final HashMap<String, String> binding2beanGetter = new HashMap<String, String>();
    final HashMap<String, String> binding2beanSetter = new HashMap<String, String>();

    final FormProperty2BeanProperty[] bindings = data.myBindings;
    for (final FormProperty2BeanProperty form2bean : bindings) {
      if (form2bean == null || form2bean.myBeanProperty == null) {
        continue;
      }

      // check that bean contains the property, and if not, try to add the property to the bean
      {
        final String setterName = PropertyUtil.suggestSetterName(form2bean.myBeanProperty.myName);
        final PsiMethod[] methodsByName = data.myBeanClass.findMethodsByName(setterName, true);
        if (methodsByName.length < 1) {
          // bean does not contain this property
          // try to add...

          LOG.assertTrue(
              !data.myBindToNewBean); // just generated bean class should contain all necessary
                                      // properties

          if (!data.myBeanClass.isWritable()) {
            throw new MyException(
                "Cannot add property to non writable class " + data.myBeanClass.getQualifiedName());
          }

          final StringBuffer membersBuffer = new StringBuffer();
          final StringBuffer methodsBuffer = new StringBuffer();

          final Project project = data.myBeanClass.getProject();
          final CodeStyleManager formatter = CodeStyleManager.getInstance(project);
          final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(project);

          generateProperty(
              styler,
              form2bean.myBeanProperty.myName,
              form2bean.myBeanProperty.myType,
              membersBuffer,
              methodsBuffer);

          final PsiClass fakeClass;
          try {
            fakeClass =
                JavaPsiFacade.getInstance(data.myBeanClass.getProject())
                    .getElementFactory()
                    .createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null);

            final PsiField[] fields = fakeClass.getFields();
            {
              final PsiElement result = data.myBeanClass.add(fields[0]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }

            final PsiMethod[] methods = fakeClass.getMethods();
            {
              final PsiElement result = data.myBeanClass.add(methods[0]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }
            {
              final PsiElement result = data.myBeanClass.add(methods[1]);
              styler.shortenClassReferences(result);
              formatter.reformat(result);
            }
          } catch (IncorrectOperationException e) {
            throw new MyException(e.getMessage());
          }
        }
      }

      final PsiMethod propertySetter =
          PropertyUtil.findPropertySetter(
              data.myBeanClass, form2bean.myBeanProperty.myName, false, true);
      final PsiMethod propertyGetter =
          PropertyUtil.findPropertyGetter(
              data.myBeanClass, form2bean.myBeanProperty.myName, false, true);

      if (propertyGetter == null) {
        // todo
        continue;
      }
      if (propertySetter == null) {
        // todo
        continue;
      }

      final String binding = form2bean.myFormProperty.getLwComponent().getBinding();
      binding2beanGetter.put(binding, propertyGetter.getName());
      binding2beanSetter.put(binding, propertySetter.getName());
    }

    final String dataBeanClassName = data.myBeanClass.getQualifiedName();

    final LwRootContainer[] rootContainer = new LwRootContainer[1];
    final FormProperty[] formProperties =
        exposeForm(data.myProject, data.myFormFile, rootContainer);

    final StringBuffer getDataBody = new StringBuffer();
    final StringBuffer setDataBody = new StringBuffer();
    final StringBuffer isModifiedBody = new StringBuffer();

    // iterate exposed formproperties

    for (final FormProperty formProperty : formProperties) {
      final String binding = formProperty.getLwComponent().getBinding();
      if (!binding2beanGetter.containsKey(binding)) {
        continue;
      }

      getDataBody.append("data.");
      getDataBody.append(binding2beanSetter.get(binding));
      getDataBody.append("(");
      getDataBody.append(binding);
      getDataBody.append(".");
      getDataBody.append(formProperty.getComponentPropertyGetterName());
      getDataBody.append("());\n");

      setDataBody.append(binding);
      setDataBody.append(".");
      setDataBody.append(formProperty.getComponentPropertySetterName());
      setDataBody.append("(data.");
      setDataBody.append(binding2beanGetter.get(binding));
      setDataBody.append("());\n");

      final String propertyClassName = formProperty.getComponentPropertyClassName();
      if ("boolean".equals(propertyClassName)) {
        isModifiedBody.append("if (");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append("!= ");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        //
        isModifiedBody.append(") return true;\n");
      } else {
        isModifiedBody.append("if (");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append("!= null ? ");
        //
        isModifiedBody.append("!");
        //
        isModifiedBody.append(binding);
        isModifiedBody.append(".");
        isModifiedBody.append(formProperty.getComponentPropertyGetterName());
        isModifiedBody.append("()");
        //
        isModifiedBody.append(".equals(");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        isModifiedBody.append(") : ");
        //
        isModifiedBody.append("data.");
        isModifiedBody.append(binding2beanGetter.get(binding));
        isModifiedBody.append("()");
        isModifiedBody.append("!= null");
        //
        isModifiedBody.append(") return true;\n");
      }
    }
    isModifiedBody.append("return false;\n");

    final String textOfMethods =
        "public void setData("
            + dataBeanClassName
            + " data){\n"
            + setDataBody.toString()
            + "}\n"
            + "\n"
            + "public void getData("
            + dataBeanClassName
            + " data){\n"
            + getDataBody.toString()
            + "}\n"
            + "\n"
            + "public boolean isModified("
            + dataBeanClassName
            + " data){\n"
            + isModifiedBody.toString()
            + "}\n";

    // put them to the bound class

    final Module module = ModuleUtil.findModuleForFile(data.myFormFile, data.myProject);
    LOG.assertTrue(module != null);
    final PsiClass boundClass =
        FormEditingUtil.findClassToBind(module, rootContainer[0].getClassToBind());
    LOG.assertTrue(boundClass != null);

    if (!CommonRefactoringUtil.checkReadOnlyStatus(module.getProject(), boundClass)) {
      return;
    }

    // todo: check that this method does not exist yet

    final PsiClass fakeClass;
    try {
      fakeClass =
          JavaPsiFacade.getInstance(data.myProject)
              .getElementFactory()
              .createClassFromText(textOfMethods, null);

      final PsiMethod methodSetData = fakeClass.getMethods()[0];
      final PsiMethod methodGetData = fakeClass.getMethods()[1];
      final PsiMethod methodIsModified = fakeClass.getMethods()[2];

      final PsiMethod existing1 = boundClass.findMethodBySignature(methodSetData, false);
      final PsiMethod existing2 = boundClass.findMethodBySignature(methodGetData, false);
      final PsiMethod existing3 = boundClass.findMethodBySignature(methodIsModified, false);

      // warning already shown
      if (existing1 != null) {
        existing1.delete();
      }
      if (existing2 != null) {
        existing2.delete();
      }
      if (existing3 != null) {
        existing3.delete();
      }

      final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject());
      final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject());

      final PsiElement setData = boundClass.add(methodSetData);
      styler.shortenClassReferences(setData);
      formatter.reformat(setData);

      final PsiElement getData = boundClass.add(methodGetData);
      styler.shortenClassReferences(getData);
      formatter.reformat(getData);

      if (data.myGenerateIsModified) {
        final PsiElement isModified = boundClass.add(methodIsModified);
        styler.shortenClassReferences(isModified);
        formatter.reformat(isModified);
      }

      final OpenFileDescriptor descriptor =
          new OpenFileDescriptor(
              setData.getProject(),
              setData.getContainingFile().getVirtualFile(),
              setData.getTextOffset());
      FileEditorManager.getInstance(data.myProject).openTextEditor(descriptor, true);
    } catch (IncorrectOperationException e) {
      throw new MyException(e.getMessage());
    }
  }
  /** @param rootContainer output parameter; should be LwRootContainer[1] */
  public static FormProperty[] exposeForm(
      final Project project, final VirtualFile formFile, final LwRootContainer[] rootContainer)
      throws MyException {
    final Module module = ModuleUtil.findModuleForFile(formFile, project);
    LOG.assertTrue(module != null);

    final PsiPropertiesProvider propertiesProvider = new PsiPropertiesProvider(module);

    final Document doc = FileDocumentManager.getInstance().getDocument(formFile);
    final LwRootContainer _rootContainer;
    try {
      _rootContainer = Utils.getRootContainer(doc.getText(), propertiesProvider);
    } catch (AlienFormFileException e) {
      throw new MyException(e.getMessage());
    } catch (Exception e) {
      throw new MyException(UIDesignerBundle.message("error.cannot.process.form.file", e));
    }

    rootContainer[0] = _rootContainer;

    final String classToBind = _rootContainer.getClassToBind();
    if (classToBind == null) {
      throw new MyException(UIDesignerBundle.message("error.form.is.not.bound.to.a.class"));
    }

    final PsiClass boundClass = FormEditingUtil.findClassToBind(module, classToBind);
    if (boundClass == null) {
      throw new MyException(
          UIDesignerBundle.message("error.bound.class.does.not.exist", classToBind));
    }

    final ArrayList<FormProperty> result = new ArrayList<FormProperty>();
    final MyException[] exception = new MyException[1];

    FormEditingUtil.iterate(
        _rootContainer,
        new FormEditingUtil.ComponentVisitor<LwComponent>() {
          public boolean visit(final LwComponent component) {
            final String binding = component.getBinding();
            if (binding == null) {
              return true;
            }

            final PsiField[] fields = boundClass.getFields();
            PsiField field = null;
            for (int i = fields.length - 1; i >= 0; i--) {
              if (binding.equals(fields[i].getName())) {
                field = fields[i];
                break;
              }
            }
            if (field == null) {
              exception[0] =
                  new MyException(
                      UIDesignerBundle.message(
                          "error.field.not.found.in.class", binding, classToBind));
              return false;
            }

            final PsiClass fieldClass = getClassByType(field.getType());
            if (fieldClass == null) {
              exception[0] =
                  new MyException(
                      UIDesignerBundle.message(
                          "error.invalid.binding.field.type", binding, classToBind));
              return false;
            }

            if (instanceOf(fieldClass, JTextComponent.class.getName())) {
              result.add(new FormProperty(component, "getText", "setText", String.class.getName()));
            } else if (instanceOf(fieldClass, JCheckBox.class.getName())) {
              result.add(
                  new FormProperty(
                      component, "isSelected", "setSelected", boolean.class.getName()));
            }

            return true;
          }
        });

    if (exception[0] != null) {
      throw exception[0];
    }

    return result.toArray(new FormProperty[result.size()]);
  }
  public void annotate(
      @NotNull final PsiElement psiElement, @NotNull final AnnotationHolder holder) {
    if (!(psiElement instanceof XmlFile)) {
      return;
    }

    if (psiElement instanceof JspFile) {
      return;
    }

    final Module module = ModuleUtil.findModuleForPsiElement(psiElement);
    if (module == null) {
      return;
    }

    // do not run when facet not enabled
    if (StrutsFacet.getInstance(module) == null) {
      return;
    }

    final XmlFile xmlFile = (XmlFile) psiElement;
    final Project project = psiElement.getProject();

    final StrutsManager strutsManager = StrutsManager.getInstance(project);
    if (!strutsManager.isStruts2ConfigFile(xmlFile)) {
      return;
    }

    final VirtualFile currentVirtualFile = xmlFile.getVirtualFile();
    assert currentVirtualFile != null;

    final Set<StrutsFileSet> allConfigFileSets = strutsManager.getAllConfigFileSets(module);
    for (final StrutsFileSet configFileSet : allConfigFileSets) {
      if (configFileSet.hasFile(currentVirtualFile)) {
        return;
      }
    }

    final boolean fileSetAvailable = allConfigFileSets.size() != 0;
    final Annotation annotation =
        holder.createWarningAnnotation(
            xmlFile,
            fileSetAvailable
                ? StrutsBundle.message("annotators.fileset.file.not.registered")
                : StrutsBundle.message("annotators.fileset.no.file.sets"));
    annotation.setFileLevelAnnotation(true);

    if (fileSetAvailable) {
      final AddToFileSetFix addToFileSetFix = new AddToFileSetFix(xmlFile.getName());
      annotation.registerFix(addToFileSetFix);
    } else {
      annotation.registerFix(
          new IntentionAction() {
            @NotNull
            public String getText() {
              return StrutsBundle.message("annotators.fileset.edit.facet.settings");
            }

            @NotNull
            public String getFamilyName() {
              return StrutsBundle.message("intentions.family.name");
            }

            public boolean isAvailable(
                @NotNull final Project project, final Editor editor, final PsiFile psiFile) {
              return true;
            }

            public void invoke(
                @NotNull final Project project, final Editor editor, final PsiFile psiFile)
                throws IncorrectOperationException {
              final StrutsFacet strutsFacet = StrutsFacet.getInstance(module);
              assert strutsFacet != null;
              ModulesConfigurator.showFacetSettingsDialog(strutsFacet, null);
            }

            public boolean startInWriteAction() {
              return false;
            }
          });
    }
  }