private static OrderEntry[] calcOrderEntries(
      @NotNull RootInfo info,
      @NotNull MultiMap<VirtualFile, OrderEntry> depEntries,
      @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
      @NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries,
      @NotNull List<VirtualFile> hierarchy) {
    @Nullable VirtualFile libraryClassRoot = info.findLibraryRootInfo(hierarchy, false);
    @Nullable VirtualFile librarySourceRoot = info.findLibraryRootInfo(hierarchy, true);
    Set<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
    orderEntries.addAll(
        info.getLibraryOrderEntries(
            hierarchy,
            libraryClassRoot,
            librarySourceRoot,
            libClassRootEntries,
            libSourceRootEntries));
    for (VirtualFile root : hierarchy) {
      orderEntries.addAll(depEntries.get(root));
    }
    VirtualFile moduleContentRoot = info.findModuleRootInfo(hierarchy);
    if (moduleContentRoot != null) {
      ContainerUtil.addIfNotNull(
          orderEntries,
          info.getModuleSourceEntry(hierarchy, moduleContentRoot, libClassRootEntries));
    }
    if (orderEntries.isEmpty()) {
      return null;
    }

    OrderEntry[] array = orderEntries.toArray(new OrderEntry[orderEntries.size()]);
    Arrays.sort(array, BY_OWNER_MODULE);
    return array;
  }
Esempio n. 2
0
  protected DfaMemoryStateImpl(DfaMemoryStateImpl toCopy) {
    myFactory = toCopy.myFactory;
    myEphemeral = toCopy.myEphemeral;
    myDefaultVariableStates = toCopy.myDefaultVariableStates; // shared between all states

    myStack = new Stack<>(toCopy.myStack);
    myDistinctClasses = new TLongHashSet(toCopy.myDistinctClasses.toArray());
    myUnknownVariables = ContainerUtil.newLinkedHashSet(toCopy.myUnknownVariables);

    myEqClasses = ContainerUtil.newArrayList(toCopy.myEqClasses);
    myIdToEqClassesIndices = new MyIdMap(toCopy.myIdToEqClassesIndices.size());
    toCopy.myIdToEqClassesIndices.forEachEntry(
        new TIntObjectProcedure<int[]>() {
          @Override
          public boolean execute(int id, int[] set) {
            myIdToEqClassesIndices.put(id, set);
            return true;
          }
        });
    myVariableStates = ContainerUtil.newLinkedHashMap(toCopy.myVariableStates);

    myCachedDistinctClassPairs = toCopy.myCachedDistinctClassPairs;
    myCachedNonTrivialEqClasses = toCopy.myCachedNonTrivialEqClasses;
    myCachedHash = toCopy.myCachedHash;
  }
  @NotNull
  @Override
  public Runnable processFile(@NotNull PsiFile file) {
    if (!(file instanceof GoFile)) {
      return EmptyRunnable.getInstance();
    }
    MultiMap<String, GoImportSpec> importMap = ((GoFile) file).getImportMap();
    Set<PsiElement> importEntriesToDelete = ContainerUtil.newLinkedHashSet();
    Set<PsiElement> importIdentifiersToDelete = findRedundantImportIdentifiers(importMap);

    importEntriesToDelete.addAll(findDuplicatedEntries(importMap));
    importEntriesToDelete.addAll(filterUnusedImports(file, importMap).values());
    if (importEntriesToDelete.isEmpty() && importIdentifiersToDelete.isEmpty()) {
      return EmptyRunnable.getInstance();
    }

    return new CollectingInfoRunnable() {
      @Nullable
      @Override
      public String getUserNotificationInfo() {
        int entriesToDelete = importEntriesToDelete.size();
        int identifiersToDelete = importIdentifiersToDelete.size();
        String result = "";
        if (entriesToDelete > 0) {
          result = "Removed " + entriesToDelete + " import" + (entriesToDelete > 1 ? "s" : "");
        }
        if (identifiersToDelete > 0) {
          result += result.isEmpty() ? "Removed " : " and ";
          result += identifiersToDelete + " alias" + (identifiersToDelete > 1 ? "es" : "");
        }
        return StringUtil.nullize(result);
      }

      @Override
      public void run() {
        if (!importEntriesToDelete.isEmpty() || !importIdentifiersToDelete.isEmpty()) {
          PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
          Document document = manager.getDocument(file);
          if (document != null) {
            manager.commitDocument(document);
          }
        }

        for (PsiElement importEntry : importEntriesToDelete) {
          if (importEntry != null && importEntry.isValid()) {
            deleteImportSpec(getImportSpec(importEntry));
          }
        }

        for (PsiElement identifier : importIdentifiersToDelete) {
          if (identifier != null && identifier.isValid()) {
            identifier.delete();
          }
        }
      }
    };
  }
/**
 * Implementation of {@link Properties} which has a defined order of elements. Properties will be
 * returned in the same order in which they are inserted.
 */
public class OrderedProperties extends Properties {
  private final Set<Object> myKeys = ContainerUtil.newLinkedHashSet();

  @NotNull
  public static OrderedProperties fromMap(@NotNull Map<String, String> map) {
    OrderedProperties result = new OrderedProperties();
    for (Map.Entry<String, String> entry : map.entrySet()) {
      result.setProperty(entry.getKey(), entry.getValue());
    }
    return result;
  }

  @NotNull
  public Map<String, String> toMap() {
    Map<String, String> result = new LinkedHashMap<String, String>(size());
    for (String name : stringPropertyNames()) {
      result.put(name, getProperty(name));
    }
    return result;
  }

  @Override
  public synchronized Enumeration<Object> keys() {
    return Collections.enumeration(myKeys);
  }

  @Override
  public Enumeration<?> propertyNames() {
    return Collections.enumeration(myKeys);
  }

  @SuppressWarnings("unchecked")
  @Override
  public Set<String> stringPropertyNames() {
    return (Set) Collections.unmodifiableSet(myKeys);
  }

  @SuppressWarnings("UseOfPropertiesAsHashtable")
  @Override
  public synchronized Object put(Object key, Object value) {
    myKeys.add(key);
    return super.put(key, value);
  }

  @Override
  public synchronized Object remove(Object key) {
    myKeys.remove(key);
    return super.remove(key);
  }

  @Override
  public synchronized void clear() {
    myKeys.clear();
    super.clear();
  }
}
Esempio n. 5
0
 protected DfaMemoryStateImpl(final DfaValueFactory factory) {
   myFactory = factory;
   myDefaultVariableStates = ContainerUtil.newTroveMap();
   myEqClasses = ContainerUtil.newArrayList();
   myUnknownVariables = ContainerUtil.newLinkedHashSet();
   myVariableStates = ContainerUtil.newLinkedHashMap();
   myDistinctClasses = new TLongHashSet();
   myStack = new Stack<>();
   myIdToEqClassesIndices = new MyIdMap(20);
 }
 @NotNull
 Set<VirtualFile> getAllRoots() {
   LinkedHashSet<VirtualFile> result = ContainerUtil.newLinkedHashSet();
   result.addAll(classAndSourceRoots);
   result.addAll(contentRootOf.keySet());
   result.addAll(excludedFromLibraries.keySet());
   result.addAll(excludedFromModule.keySet());
   result.addAll(excludedFromProject);
   return result;
 }
Esempio n. 7
0
  LinkedHashSet<EqClass> getNonTrivialEqClasses() {
    if (myCachedNonTrivialEqClasses != null) return myCachedNonTrivialEqClasses;

    LinkedHashSet<EqClass> result = ContainerUtil.newLinkedHashSet();
    for (EqClass eqClass : myEqClasses) {
      if (eqClass != null && eqClass.size() > 1) {
        result.add(eqClass);
      }
    }
    return myCachedNonTrivialEqClasses = result;
  }
Esempio n. 8
0
  LinkedHashSet<UnorderedPair<EqClass>> getDistinctClassPairs() {
    if (myCachedDistinctClassPairs != null) return myCachedDistinctClassPairs;

    LinkedHashSet<UnorderedPair<EqClass>> result = ContainerUtil.newLinkedHashSet();
    for (long encodedPair : myDistinctClasses.toArray()) {
      result.add(
          new UnorderedPair<>(
              myEqClasses.get(low(encodedPair)), myEqClasses.get(high(encodedPair))));
    }
    return myCachedDistinctClassPairs = result;
  }
 private String constructAmendedMessage() {
   Set<VirtualFile> selectedRoots = getVcsRoots(getSelectedFilePaths()); // get only selected files
   LinkedHashSet<String> messages = ContainerUtil.newLinkedHashSet();
   if (myMessagesForRoots != null) {
     for (VirtualFile root : selectedRoots) {
       String message = myMessagesForRoots.get(root);
       if (message != null) {
         messages.add(message);
       }
     }
   }
   return DvcsUtil.joinMessagesOrNull(messages);
 }
Esempio n. 10
0
 @Override
 public void flushFields() {
   Set<DfaVariableValue> vars = ContainerUtil.newLinkedHashSet(getChangedVariables());
   for (EqClass aClass : myEqClasses) {
     if (aClass != null) {
       vars.addAll(aClass.getVariables(true));
     }
   }
   for (DfaVariableValue value : vars) {
     if (value.isFlushableByCalls()) {
       doFlush(value, shouldMarkUnknown(value));
     }
   }
 }
 @NotNull
 public static Set<PsiElement> findRedundantImportIdentifiers(
     @NotNull MultiMap<String, GoImportSpec> importMap) {
   Set<PsiElement> importIdentifiersToDelete = ContainerUtil.newLinkedHashSet();
   for (PsiElement importEntry : importMap.values()) {
     GoImportSpec importSpec = getImportSpec(importEntry);
     if (importSpec != null) {
       String localPackageName = importSpec.getLocalPackageName();
       if (!StringUtil.isEmpty(localPackageName)) {
         if (Comparing.equal(importSpec.getAlias(), localPackageName)) {
           importIdentifiersToDelete.add(importSpec.getIdentifier());
         }
       }
     }
   }
   return importIdentifiersToDelete;
 }
 public static Set<String> getAllLookupStrings(@NotNull PsiMember member) {
   Set<String> allLookupStrings = ContainerUtil.newLinkedHashSet();
   String name = member.getName();
   allLookupStrings.add(name);
   PsiClass containingClass = member.getContainingClass();
   while (containingClass != null) {
     final String className = containingClass.getName();
     if (className == null) {
       break;
     }
     name = className + "." + name;
     allLookupStrings.add(name);
     final PsiElement parent = containingClass.getParent();
     if (!(parent instanceof PsiClass)) {
       break;
     }
     containingClass = (PsiClass) parent;
   }
   return allLookupStrings;
 }
 @NotNull
 public static List<GotoRelatedItem> collectRelatedItems(
     @NotNull PsiElement contextElement, @Nullable DataContext dataContext) {
   Set<GotoRelatedItem> items = ContainerUtil.newLinkedHashSet();
   for (GotoRelatedProvider provider : Extensions.getExtensions(GotoRelatedProvider.EP_NAME)) {
     items.addAll(provider.getItems(contextElement));
     if (dataContext != null) {
       items.addAll(provider.getItems(dataContext));
     }
   }
   GotoRelatedItem[] result = items.toArray(new GotoRelatedItem[items.size()]);
   Arrays.sort(
       result,
       (i1, i2) -> {
         String o1 = i1.getGroup();
         String o2 = i2.getGroup();
         return StringUtil.isEmpty(o1) ? 1 : StringUtil.isEmpty(o2) ? -1 : o1.compareTo(o2);
       });
   return Arrays.asList(result);
 }
  @NotNull
  private static Set<String> sortMatching(
      @NotNull PrefixMatcher matcher, @NotNull Collection<String> names, @NotNull GoFile file) {
    ProgressManager.checkCanceled();
    String prefix = matcher.getPrefix();
    if (prefix.isEmpty()) return ContainerUtil.newLinkedHashSet(names);

    Set<String> packagesWithAliases = ContainerUtil.newHashSet();
    for (Map.Entry<String, Collection<GoImportSpec>> entry : file.getImportMap().entrySet()) {
      for (GoImportSpec spec : entry.getValue()) {
        String alias = spec.getAlias();
        if (spec.isDot() || alias != null) {
          packagesWithAliases.add(entry.getKey());
          break;
        }
      }
    }

    List<String> sorted = ContainerUtil.newArrayList();
    for (String name : names) {
      if (matcher.prefixMatches(name) || packagesWithAliases.contains(substringBefore(name, '.'))) {
        sorted.add(name);
      }
    }

    ProgressManager.checkCanceled();
    Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
    ProgressManager.checkCanceled();

    LinkedHashSet<String> result = new LinkedHashSet<String>();
    for (String name : sorted) {
      if (matcher.isStartMatch(name)) {
        result.add(name);
      }
    }

    ProgressManager.checkCanceled();

    result.addAll(sorted);
    return result;
  }
  @NotNull
  public static Set<GoImportSpec> findDuplicatedEntries(
      @NotNull MultiMap<String, GoImportSpec> importMap) {
    Set<GoImportSpec> duplicatedEntries = ContainerUtil.newLinkedHashSet();
    for (Map.Entry<String, Collection<GoImportSpec>> imports : importMap.entrySet()) {
      Collection<GoImportSpec> importsWithSameName = imports.getValue();
      if (importsWithSameName.size() > 1) {
        MultiMap<String, GoImportSpec> importsWithSameString =
            collectImportsWithSameString(importsWithSameName);

        for (Map.Entry<String, Collection<GoImportSpec>> importWithSameString :
            importsWithSameString.entrySet()) {
          List<GoImportSpec> duplicates =
              ContainerUtil.newArrayList(importWithSameString.getValue());
          if (duplicates.size() > 1) {
            duplicatedEntries.addAll(duplicates.subList(1, duplicates.size()));
          }
        }
      }
    }
    return duplicatedEntries;
  }
 @NotNull
 private LinkedHashSet<OrderEntry> getLibraryOrderEntries(
     @NotNull List<VirtualFile> hierarchy,
     @Nullable VirtualFile libraryClassRoot,
     @Nullable VirtualFile librarySourceRoot,
     @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
     @NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries) {
   LinkedHashSet<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
   for (VirtualFile root : hierarchy) {
     if (root.equals(libraryClassRoot) && !sourceRootOf.containsKey(root)) {
       orderEntries.addAll(libClassRootEntries.get(root));
     }
     if (root.equals(librarySourceRoot) && libraryClassRoot == null) {
       orderEntries.addAll(libSourceRootEntries.get(root));
     }
     if (libClassRootEntries.containsKey(root)
         || sourceRootOf.containsKey(root) && librarySourceRoot == null) {
       break;
     }
   }
   return orderEntries;
 }
 @NotNull
 public List<VirtualFile> getAffectedFiles() {
   final Set<VirtualFile> result = ContainerUtil.newLinkedHashSet();
   for (LocalChangeList list : myMap.values()) {
     for (Change change : list.getChanges()) {
       final ContentRevision before = change.getBeforeRevision();
       final ContentRevision after = change.getAfterRevision();
       if (before != null) {
         final VirtualFile file = before.getFile().getVirtualFile();
         if (file != null) {
           result.add(file);
         }
       }
       if (after != null) {
         final VirtualFile file = after.getFile().getVirtualFile();
         if (file != null) {
           result.add(file);
         }
       }
     }
   }
   return new ArrayList<VirtualFile>(result);
 }
 @NotNull
 public static Set<PsiField> findConstantsUsedInSwitch(@Nullable PsiElement position) {
   if (IN_SWITCH_LABEL.accepts(position)) {
     Set<PsiField> used = ContainerUtil.newLinkedHashSet();
     PsiSwitchStatement sw = PsiTreeUtil.getParentOfType(position, PsiSwitchStatement.class);
     assert sw != null;
     final PsiCodeBlock body = sw.getBody();
     assert body != null;
     for (PsiStatement statement : body.getStatements()) {
       if (statement instanceof PsiSwitchLabelStatement) {
         final PsiExpression value = ((PsiSwitchLabelStatement) statement).getCaseValue();
         if (value instanceof PsiReferenceExpression) {
           final PsiElement target = ((PsiReferenceExpression) value).resolve();
           if (target instanceof PsiField) {
             used.add(CompletionUtil.getOriginalOrSelf((PsiField) target));
           }
         }
       }
     }
     return used;
   }
   return Collections.emptySet();
 }
  private static Set<ReadWriteVariableInstruction> collectUsedVariableWithoutInitialization(
      GrTypeDefinition typeDefinition) {
    final Set<ReadWriteVariableInstruction> vars = ContainerUtil.newLinkedHashSet();
    typeDefinition.acceptChildren(
        new GroovyRecursiveElementVisitor() {
          private void collectVars(Instruction[] flow) {
            ReadWriteVariableInstruction[] reads =
                ControlFlowBuilderUtil.getReadsWithoutPriorWrites(flow, false);
            Collections.addAll(vars, reads);
          }

          @Override
          public void visitField(GrField field) {
            GrExpression initializer = field.getInitializerGroovy();
            if (initializer != null) {
              Instruction[] flow =
                  new ControlFlowBuilder(field.getProject()).buildControlFlow(initializer);
              collectVars(flow);
            }
          }

          @Override
          public void visitMethod(GrMethod method) {
            GrOpenBlock block = method.getBlock();
            if (block != null) {
              collectVars(block.getControlFlow());
            }
          }

          @Override
          public void visitClassInitializer(GrClassInitializer initializer) {
            GrOpenBlock block = initializer.getBlock();
            collectVars(block.getControlFlow());
          }
        });
    return vars;
  }
  @Override
  public DfaInstructionState[] visitMethodCall(
      final MethodCallInstruction instruction,
      final DataFlowRunner runner,
      final DfaMemoryState memState) {
    DfaValue[] argValues = popCallArguments(instruction, runner, memState);
    final DfaValue qualifier = popQualifier(instruction, runner, memState);

    List<DfaMemoryState> currentStates = ContainerUtil.newArrayList(memState);
    Set<DfaMemoryState> finalStates = ContainerUtil.newLinkedHashSet();
    if (argValues != null) {
      for (MethodContract contract : instruction.getContracts()) {
        currentStates =
            addContractResults(
                argValues, contract, currentStates, instruction, runner.getFactory(), finalStates);
      }
    }
    for (DfaMemoryState state : currentStates) {
      state.push(getMethodResultValue(instruction, qualifier, runner.getFactory()));
      finalStates.add(state);
    }

    return ContainerUtil.map2Array(
        finalStates,
        DfaInstructionState.class,
        new Function<DfaMemoryState, DfaInstructionState>() {
          @Override
          public DfaInstructionState fun(DfaMemoryState state) {
            if (instruction.shouldFlushFields()) {
              state.flushFields();
            }
            return new DfaInstructionState(
                runner.getInstruction(instruction.getIndex() + 1), state);
          }
        });
  }
 @Nullable
 public String getDefaultMessageFor(FilePath[] filesToCheckin) {
   LinkedHashSet<String> messages = ContainerUtil.newLinkedHashSet();
   for (VirtualFile root : GitUtil.gitRoots(Arrays.asList(filesToCheckin))) {
     VirtualFile mergeMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_MERGE_MSG);
     VirtualFile squashMsg = root.findFileByRelativePath(GitRepositoryFiles.GIT_SQUASH_MSG);
     try {
       if (mergeMsg == null && squashMsg == null) {
         continue;
       }
       String encoding = GitConfigUtil.getCommitEncoding(myProject, root);
       if (mergeMsg != null) {
         messages.add(loadMessage(mergeMsg, encoding));
       } else {
         messages.add(loadMessage(squashMsg, encoding));
       }
     } catch (IOException e) {
       if (log.isDebugEnabled()) {
         log.debug("Unable to load merge message", e);
       }
     }
   }
   return DvcsUtil.joinMessagesOrNull(messages);
 }
  @Override
  public void importData(
      @NotNull final Collection<DataNode<BuildScriptClasspathData>> toImport,
      @NotNull final Project project,
      boolean synchronous) {
    if (toImport.isEmpty()) {
      return;
    }
    if (!project.isInitialized()) {
      return;
    }

    final GradleInstallationManager gradleInstallationManager =
        ServiceManager.getService(GradleInstallationManager.class);

    ExternalSystemManager<?, ?, ?, ?, ?> manager =
        ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
    assert manager != null;
    AbstractExternalSystemLocalSettings localSettings =
        manager.getLocalSettingsProvider().fun(project);

    //noinspection MismatchedQueryAndUpdateOfCollection
    Map<String /* externalProjectPath */, Set<String>> externalProjectGradleSdkLibs =
        new FactoryMap<String, Set<String>>() {
          @Nullable
          @Override
          protected Set<String> create(String externalProjectPath) {
            GradleProjectSettings settings =
                GradleSettings.getInstance(project).getLinkedProjectSettings(externalProjectPath);
            if (settings == null || settings.getDistributionType() == null) return null;

            final Set<String> gradleSdkLibraries = ContainerUtil.newLinkedHashSet();
            File gradleHome =
                gradleInstallationManager.getGradleHome(
                    settings.getDistributionType(), externalProjectPath, settings.getGradleHome());
            if (gradleHome != null && gradleHome.isDirectory()) {

              final Collection<File> libraries =
                  gradleInstallationManager.getClassRoots(project, externalProjectPath);
              if (libraries != null) {
                for (File library : libraries) {
                  gradleSdkLibraries.add(FileUtil.toCanonicalPath(library.getPath()));
                }
              }
            }
            return gradleSdkLibraries;
          }
        };

    for (final DataNode<BuildScriptClasspathData> node : toImport) {
      if (GradleConstants.SYSTEM_ID.equals(node.getData().getOwner())) {

        DataNode<ProjectData> projectDataNode =
            ExternalSystemApiUtil.findParent(node, ProjectKeys.PROJECT);
        assert projectDataNode != null;

        String linkedExternalProjectPath = projectDataNode.getData().getLinkedExternalProjectPath();
        DataNode<ModuleData> moduleDataNode =
            ExternalSystemApiUtil.findParent(node, ProjectKeys.MODULE);
        if (moduleDataNode == null) continue;

        String externalModulePath = moduleDataNode.getData().getLinkedExternalProjectPath();
        GradleProjectSettings settings =
            GradleSettings.getInstance(project).getLinkedProjectSettings(linkedExternalProjectPath);
        if (settings == null || settings.getDistributionType() == null) continue;

        final Set<String> buildClasspath = ContainerUtil.newLinkedHashSet();
        BuildScriptClasspathData buildScriptClasspathData = node.getData();
        for (BuildScriptClasspathData.ClasspathEntry classpathEntry :
            buildScriptClasspathData.getClasspathEntries()) {
          for (String path : classpathEntry.getSourcesFile()) {
            buildClasspath.add(FileUtil.toCanonicalPath(path));
          }

          for (String path : classpathEntry.getClassesFile()) {
            buildClasspath.add(FileUtil.toCanonicalPath(path));
          }
        }

        ExternalProjectBuildClasspathPojo projectBuildClasspathPojo =
            localSettings.getProjectBuildClasspath().get(linkedExternalProjectPath);
        if (projectBuildClasspathPojo == null) {
          projectBuildClasspathPojo =
              new ExternalProjectBuildClasspathPojo(
                  moduleDataNode.getData().getExternalName(),
                  ContainerUtil.<String>newArrayList(),
                  ContainerUtil.<String, ExternalModuleBuildClasspathPojo>newHashMap());
          localSettings
              .getProjectBuildClasspath()
              .put(linkedExternalProjectPath, projectBuildClasspathPojo);
        }

        List<String> projectBuildClasspath =
            ContainerUtil.newArrayList(externalProjectGradleSdkLibs.get(linkedExternalProjectPath));
        // add main java root of buildSrc project
        projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/java");
        // add main groovy root of buildSrc project
        projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/groovy");

        projectBuildClasspathPojo.setProjectBuildClasspath(projectBuildClasspath);
        projectBuildClasspathPojo
            .getModulesBuildClasspath()
            .put(
                externalModulePath,
                new ExternalModuleBuildClasspathPojo(
                    externalModulePath, ContainerUtil.newArrayList(buildClasspath)));
      }
    }

    GradleBuildClasspathManager.getInstance(project).reload();
  }
  /**
   * @param addClearListItem - used for detecting whether the "Clear List" action should be added to
   *     the end of the returned list of actions
   * @return
   */
  public AnAction[] getRecentProjectsActions(boolean addClearListItem) {
    validateRecentProjects();

    final Set<String> openedPaths = ContainerUtil.newHashSet();
    for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
      ContainerUtil.addIfNotNull(openedPaths, getProjectPath(openProject));
    }

    final LinkedHashSet<String> paths;
    synchronized (myStateLock) {
      paths = ContainerUtil.newLinkedHashSet(myState.recentPaths);
    }
    paths.remove(null);
    paths.removeAll(openedPaths);

    ArrayList<AnAction> actions = new ArrayList<AnAction>();
    Set<String> duplicates = getDuplicateProjectNames(openedPaths, paths);
    for (final String path : paths) {
      final String projectName = getProjectName(path);
      String displayName;
      synchronized (myStateLock) {
        displayName = myState.names.get(path);
      }
      if (StringUtil.isEmptyOrSpaces(displayName)) {
        displayName = duplicates.contains(path) ? path : projectName;
      }

      // It's better don't to remove non-existent projects. Sometimes projects stored
      // on USB-sticks or flash-cards, and it will be nice to have them in the list
      // when USB device or SD-card is mounted
      if (new File(path).exists()) {
        actions.add(new ReopenProjectAction(path, projectName, displayName));
      }
    }

    if (actions.isEmpty()) {
      return AnAction.EMPTY_ARRAY;
    }

    ArrayList<AnAction> list = new ArrayList<AnAction>();
    for (AnAction action : actions) {
      list.add(action);
    }
    if (addClearListItem) {
      AnAction clearListAction =
          new AnAction(IdeBundle.message("action.clear.list")) {
            public void actionPerformed(AnActionEvent e) {
              final int rc =
                  Messages.showOkCancelDialog(
                      e.getData(PlatformDataKeys.PROJECT),
                      "Would you like to clear the list of recent projects?",
                      "Clear Recent Projects List",
                      Messages.getQuestionIcon());

              if (rc == 0) {
                synchronized (myStateLock) {
                  myState.recentPaths.clear();
                }
                WelcomeFrame.clearRecents();
              }
            }
          };

      list.add(Separator.getInstance());
      list.add(clearListAction);
    }

    return list.toArray(new AnAction[list.size()]);
  }
 @NotNull
 private static Set<String> getIgnoredModules(@NotNull Project project) {
   String value =
       PropertiesComponent.getInstance(project).getValue(DONT_ASK_TO_CHANGE_MODULE_TYPE_KEY, "");
   return ContainerUtil.newLinkedHashSet(StringUtil.split(value, ","));
 }
Esempio n. 25
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);
  }
 protected boolean addInapplicableCandidate(@NotNull GroovyResolveResult candidate) {
   if (myInapplicableCandidates == null) {
     myInapplicableCandidates = ContainerUtil.newLinkedHashSet();
   }
   return myInapplicableCandidates.add(candidate);
 }
  private static class RootInfo {
    // getDirectoriesByPackageName used to be in this order, some clients might rely on that
    @NotNull
    final LinkedHashSet<VirtualFile> classAndSourceRoots = ContainerUtil.newLinkedHashSet();

    @NotNull final Set<VirtualFile> libraryOrSdkSources = ContainerUtil.newHashSet();
    @NotNull final Set<VirtualFile> libraryOrSdkClasses = ContainerUtil.newHashSet();
    @NotNull final Map<VirtualFile, Module> contentRootOf = ContainerUtil.newHashMap();
    @NotNull final MultiMap<VirtualFile, Module> sourceRootOf = MultiMap.createSet();
    @NotNull final TObjectIntHashMap<VirtualFile> rootTypeId = new TObjectIntHashMap<VirtualFile>();
    @NotNull final MultiMap<VirtualFile, Library> excludedFromLibraries = MultiMap.createSmart();
    @NotNull final MultiMap<VirtualFile, Library> classOfLibraries = MultiMap.createSmart();
    @NotNull final MultiMap<VirtualFile, Library> sourceOfLibraries = MultiMap.createSmart();
    @NotNull final Set<VirtualFile> excludedFromProject = ContainerUtil.newHashSet();
    @NotNull final Map<VirtualFile, Module> excludedFromModule = ContainerUtil.newHashMap();
    @NotNull final Map<VirtualFile, String> packagePrefix = ContainerUtil.newHashMap();

    @NotNull
    Set<VirtualFile> getAllRoots() {
      LinkedHashSet<VirtualFile> result = ContainerUtil.newLinkedHashSet();
      result.addAll(classAndSourceRoots);
      result.addAll(contentRootOf.keySet());
      result.addAll(excludedFromLibraries.keySet());
      result.addAll(excludedFromModule.keySet());
      result.addAll(excludedFromProject);
      return result;
    }

    @Nullable
    private VirtualFile findModuleRootInfo(@NotNull List<VirtualFile> hierarchy) {
      for (VirtualFile root : hierarchy) {
        Module module = contentRootOf.get(root);
        Module excludedFrom = excludedFromModule.get(root);
        if (module != null && excludedFrom != module) {
          return root;
        }
        if (excludedFrom != null || excludedFromProject.contains(root)) {
          return null;
        }
      }
      return null;
    }

    @Nullable
    private VirtualFile findNearestContentRootForExcluded(@NotNull List<VirtualFile> hierarchy) {
      for (VirtualFile root : hierarchy) {
        if (contentRootOf.containsKey(root)) {
          return root;
        }
      }
      return null;
    }

    @Nullable
    private VirtualFile findLibraryRootInfo(@NotNull List<VirtualFile> hierarchy, boolean source) {
      Set<Library> librariesToIgnore = ContainerUtil.newHashSet();
      for (VirtualFile root : hierarchy) {
        librariesToIgnore.addAll(excludedFromLibraries.get(root));
        if (source
            && libraryOrSdkSources.contains(root)
            && (!sourceOfLibraries.containsKey(root)
                || !librariesToIgnore.containsAll(sourceOfLibraries.get(root)))) {
          return root;
        } else if (!source
            && libraryOrSdkClasses.contains(root)
            && (!classOfLibraries.containsKey(root)
                || !librariesToIgnore.containsAll(classOfLibraries.get(root)))) {
          return root;
        }
      }
      return null;
    }

    private String calcPackagePrefix(
        @NotNull VirtualFile root,
        @NotNull List<VirtualFile> hierarchy,
        VirtualFile moduleContentRoot,
        VirtualFile libraryClassRoot,
        VirtualFile librarySourceRoot) {
      VirtualFile packageRoot =
          findPackageRootInfo(hierarchy, moduleContentRoot, libraryClassRoot, librarySourceRoot);
      String prefix = packagePrefix.get(packageRoot);
      if (prefix != null && !root.equals(packageRoot)) {
        assert packageRoot != null;
        String relative = VfsUtilCore.getRelativePath(root, packageRoot, '.');
        prefix = StringUtil.isEmpty(prefix) ? relative : prefix + '.' + relative;
      }
      return prefix;
    }

    @Nullable
    private VirtualFile findPackageRootInfo(
        @NotNull List<VirtualFile> hierarchy,
        VirtualFile moduleContentRoot,
        VirtualFile libraryClassRoot,
        VirtualFile librarySourceRoot) {
      for (VirtualFile root : hierarchy) {
        if (moduleContentRoot != null
            && sourceRootOf.get(root).contains(contentRootOf.get(moduleContentRoot))
            && librarySourceRoot == null) {
          return root;
        }
        if (root.equals(libraryClassRoot) || root.equals(librarySourceRoot)) {
          return root;
        }
        if (root.equals(moduleContentRoot)
            && !sourceRootOf.containsKey(root)
            && librarySourceRoot == null
            && libraryClassRoot == null) {
          return null;
        }
      }
      return null;
    }

    @NotNull
    private LinkedHashSet<OrderEntry> getLibraryOrderEntries(
        @NotNull List<VirtualFile> hierarchy,
        @Nullable VirtualFile libraryClassRoot,
        @Nullable VirtualFile librarySourceRoot,
        @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
        @NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries) {
      LinkedHashSet<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
      for (VirtualFile root : hierarchy) {
        if (root.equals(libraryClassRoot) && !sourceRootOf.containsKey(root)) {
          orderEntries.addAll(libClassRootEntries.get(root));
        }
        if (root.equals(librarySourceRoot) && libraryClassRoot == null) {
          orderEntries.addAll(libSourceRootEntries.get(root));
        }
        if (libClassRootEntries.containsKey(root)
            || sourceRootOf.containsKey(root) && librarySourceRoot == null) {
          break;
        }
      }
      return orderEntries;
    }

    @Nullable
    private ModuleSourceOrderEntry getModuleSourceEntry(
        @NotNull List<VirtualFile> hierarchy,
        @NotNull VirtualFile moduleContentRoot,
        @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries) {
      Module module = contentRootOf.get(moduleContentRoot);
      for (VirtualFile root : hierarchy) {
        if (sourceRootOf.get(root).contains(module)) {
          return ContainerUtil.findInstance(
              ModuleRootManager.getInstance(module).getOrderEntries(),
              ModuleSourceOrderEntry.class);
        }
        if (libClassRootEntries.containsKey(root)) {
          return null;
        }
      }
      return null;
    }
  }