private static void doCollectResourceDirs(
      AndroidFacet facet,
      boolean collectResCacheDirs,
      List<String> result,
      CompileContext context) {
    final Module module = facet.getModule();

    if (collectResCacheDirs) {
      final AndroidPlatform platform = facet.getConfiguration().getAndroidPlatform();
      final int platformToolsRevision =
          platform != null ? platform.getSdk().getPlatformToolsRevision() : -1;

      if (platformToolsRevision < 0 || platformToolsRevision > 7) {
        // png cache is supported since platform-tools-r8
        final String resCacheDirOsPath = findResourcesCacheDirectory(module, false, context);
        if (resCacheDirOsPath != null) {
          result.add(resCacheDirOsPath);
        } else {
          LOG.info("PNG cache not found for module " + module.getName());
        }
      }
    }

    final VirtualFile resourcesDir = AndroidAptCompiler.getResourceDirForApkCompiler(module, facet);
    if (resourcesDir != null) {
      result.add(resourcesDir.getPath());
    }
  }
 public void rootsChanged(String listName) {
   FavoritesListener[] listeners =
       myListeners.toArray(new FavoritesListener[myListeners.size()]);
   for (FavoritesListener listener : listeners) {
     listener.rootsChanged(listName);
   }
 }
  private static Collection<? extends PackagingSourceItem> createClasspathItems(
      ArtifactEditorContext editorContext, Artifact artifact, @NotNull Module module) {
    final List<PackagingSourceItem> items = new ArrayList<PackagingSourceItem>();
    final ModuleRootModel rootModel = editorContext.getModulesProvider().getRootModel(module);
    List<Library> libraries = new ArrayList<Library>();
    for (OrderEntry orderEntry : rootModel.getOrderEntries()) {
      if (orderEntry instanceof LibraryOrderEntry) {
        final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
        final Library library = libraryEntry.getLibrary();
        final DependencyScope scope = libraryEntry.getScope();
        if (library != null && scope.isForProductionRuntime()) {
          libraries.add(library);
        }
      }
    }

    for (Module toAdd : getNotAddedModules(editorContext, artifact, module)) {
      items.add(new ModuleOutputSourceItem(toAdd));
    }

    for (Library library : getNotAddedLibraries(editorContext, artifact, libraries)) {
      items.add(new LibrarySourceItem(library));
    }
    return items;
  }
 private static List<? extends Library> getNotAddedLibraries(
     @NotNull final ArtifactEditorContext context,
     @NotNull Artifact artifact,
     List<Library> librariesList) {
   final Set<VirtualFile> roots = new HashSet<VirtualFile>();
   ArtifactUtil.processPackagingElements(
       artifact,
       PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE,
       new Processor<FileCopyPackagingElement>() {
         public boolean process(FileCopyPackagingElement fileCopyPackagingElement) {
           final VirtualFile root = fileCopyPackagingElement.getLibraryRoot();
           if (root != null) {
             roots.add(root);
           }
           return true;
         }
       },
       context,
       true);
   final List<Library> result = new ArrayList<Library>();
   for (Library library : librariesList) {
     if (!roots.containsAll(Arrays.asList(library.getFiles(OrderRootType.CLASSES)))) {
       result.add(library);
     }
   }
   return result;
 }
 public void listRemoved(String listName) {
   FavoritesListener[] listeners =
       myListeners.toArray(new FavoritesListener[myListeners.size()]);
   for (FavoritesListener listener : listeners) {
     listener.listRemoved(listName);
   }
 }
  private static void logStats(Collection<PsiFile> otherFiles, long start) {
    long time = System.currentTimeMillis() - start;

    final Multiset<String> stats = HashMultiset.create();
    for (PsiFile file : otherFiles) {
      stats.add(
          StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension())
              .toLowerCase());
    }

    List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
    Collections.sort(
        extensions,
        new Comparator<String>() {
          @Override
          public int compare(String o1, String o2) {
            return stats.count(o2) - stats.count(o1);
          }
        });

    String message =
        "Search in "
            + otherFiles.size()
            + " files with unknown types took "
            + time
            + "ms.\n"
            + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n"
            + "Most frequent non-indexed file extensions: ";
    for (int i = 0; i < Math.min(10, extensions.size()); i++) {
      String extension = extensions.get(i);
      message += extension + "(" + stats.count(extension) + ") ";
    }
    LOG.info(message);
  }
  private <T> boolean findListToRemoveFrom(
      @NotNull String name,
      @NotNull final List<T> elements,
      final Convertor<T, AbstractUrl> convertor) {
    Collection<TreeItem<Pair<AbstractUrl, String>>> list = getFavoritesListRootUrls(name);
    if (elements.size() > 1) {
      final List<T> sublist = elements.subList(0, elements.size() - 1);
      for (T obj : sublist) {
        AbstractUrl objUrl = convertor.convert(obj);
        final TreeItem<Pair<AbstractUrl, String>> item = findNextItem(objUrl, list);
        if (item == null || item.getChildren() == null) return false;
        list = item.getChildren();
      }
    }

    TreeItem<Pair<AbstractUrl, String>> found = null;
    AbstractUrl url = convertor.convert(elements.get(elements.size() - 1));
    if (url == null) return false;
    for (TreeItem<Pair<AbstractUrl, String>> pair : list) {
      if (url.equals(pair.getData().getFirst())) {
        found = pair;
        break;
      }
    }

    if (found != null) {
      list.remove(found);
      fireListeners.rootsChanged(name);
      return true;
    }
    return false;
  }
Beispiel #8
0
 public void assertProjectLibraries(String... expectedNames) {
   List<String> actualNames = new ArrayList<String>();
   for (Library each : ProjectLibraryTable.getInstance(myProject).getLibraries()) {
     String name = each.getName();
     actualNames.add(name == null ? "<unnamed>" : name);
   }
   assertUnorderedElementsAreEqual(actualNames, expectedNames);
 }
Beispiel #9
0
 protected void readProjects(VirtualFile... files) {
   List<MavenProject> projects = new ArrayList<MavenProject>();
   for (VirtualFile each : files) {
     projects.add(myProjectsManager.findProject(each));
   }
   myProjectsManager.forceUpdateProjects(projects);
   waitForReadingCompletion();
 }
 private static void buildPythonPath(
     Project project, GeneralCommandLine commandLine, PythonRunParams config) {
   Sdk pythonSdk = PythonSdkType.findSdkByPath(config.getSdkHome());
   if (pythonSdk != null) {
     List<String> pathList = Lists.newArrayList(getAddedPaths(pythonSdk));
     pathList.addAll(collectPythonPath(project, config));
     initPythonPath(commandLine, config.isPassParentEnvs(), pathList, config.getSdkHome());
   }
 }
Beispiel #11
0
  private List<String> collectModuleDepsNames(String moduleName, Class clazz) {
    List<String> actual = new ArrayList<String>();

    for (OrderEntry e : getRootManager(moduleName).getOrderEntries()) {
      if (clazz.isInstance(e)) {
        actual.add(e.getPresentableName());
      }
    }
    return actual;
  }
Beispiel #12
0
  protected void assertModules(String... expectedNames) {
    Module[] actual = ModuleManager.getInstance(myProject).getModules();
    List<String> actualNames = new ArrayList<String>();

    for (Module m : actual) {
      actualNames.add(m.getName());
    }

    assertUnorderedElementsAreEqual(actualNames, expectedNames);
  }
  public ExecutionResult execute(Executor executor, CommandLinePatcher... patchers)
      throws ExecutionException {
    final ProcessHandler processHandler = startProcess(patchers);
    final ConsoleView console =
        createAndAttachConsole(myConfig.getProject(), processHandler, executor);

    List<AnAction> actions = Lists.newArrayList(createActions(console, processHandler));

    return new DefaultExecutionResult(
        console, processHandler, actions.toArray(new AnAction[actions.size()]));
  }
Beispiel #14
0
  protected void assertContentRoots(String moduleName, String... expectedRoots) {
    List<String> actual = new ArrayList<String>();
    for (ContentEntry e : getContentRoots(moduleName)) {
      actual.add(e.getUrl());
    }

    for (int i = 0; i < expectedRoots.length; i++) {
      expectedRoots[i] = VfsUtil.pathToUrl(expectedRoots[i]);
    }

    assertUnorderedPathsAreEqual(actual, Arrays.asList(expectedRoots));
  }
Beispiel #15
0
  private ContentEntry getContentRoot(String moduleName) {
    ContentEntry[] ee = getContentRoots(moduleName);
    List<String> roots = new ArrayList<String>();
    for (ContentEntry e : ee) {
      roots.add(e.getUrl());
    }

    String message = "Several content roots found: [" + StringUtil.join(roots, ", ") + "]";
    assertEquals(message, 1, ee.length);

    return ee[0];
  }
 public void removeRootByIndexes(String name, List<Integer> elementsIndexes) {
   List<TreeItem<Pair<AbstractUrl, String>>> list = getFavoritesListRootUrls(name);
   assert list != null;
   for (Integer index : elementsIndexes.subList(0, elementsIndexes.size() - 1)) {
     assert index >= 0 && index < list.size();
     final TreeItem<Pair<AbstractUrl, String>> item = list.get(index);
     list = item.getChildren();
   }
   assert list != null && !list.isEmpty();
   list.remove(elementsIndexes.get(elementsIndexes.size() - 1).intValue());
   fireListeners.rootsChanged(name);
 }
 public static void addMessages(
     @NotNull Map<CompilerMessageCategory, List<String>> messages,
     @NotNull Map<CompilerMessageCategory, List<String>> toAdd) {
   for (Map.Entry<CompilerMessageCategory, List<String>> entry : toAdd.entrySet()) {
     List<String> list = messages.get(entry.getKey());
     if (list == null) {
       list = new ArrayList<String>();
       messages.put(entry.getKey(), list);
     }
     list.addAll(entry.getValue());
   }
 }
    private void addPackage(@NotNull final String packageName, @NotNull final String packagePath) {
      myLibRootUrls.add(VfsUtilCore.pathToUrl(packagePath));

      List<String> paths = myPackagesMap.get((packageName));
      if (paths == null) {
        paths = new SmartList<String>();
        myPackagesMap.put(packageName, paths);
      }

      if (!paths.contains(packagePath)) {
        paths.add(packagePath);
      }
    }
Beispiel #19
0
 protected void assertGeneratedSources(String moduleName, String... expectedSources) {
   ContentEntry contentRoot = getContentRoot(moduleName);
   List<ContentFolder> folders = new ArrayList<ContentFolder>();
   for (SourceFolder folder : contentRoot.getSourceFolders(JavaSourceRootType.SOURCE)) {
     JavaSourceRootProperties properties =
         folder.getJpsElement().getProperties(JavaSourceRootType.SOURCE);
     assertNotNull(properties);
     if (properties.isForGeneratedSources()) {
       folders.add(folder);
     }
   }
   doAssertContentFolders(contentRoot, folders, expectedSources);
 }
Beispiel #20
0
 private static void removeModuleOutput(Module module, List<VirtualFile> from) {
   CompilerPathsManager compilerPathsManager =
       CompilerPathsManager.getInstance(module.getProject());
   for (ContentFolderType contentFolderType : ContentFolderType.ALL_SOURCE_ROOTS) {
     from.remove(compilerPathsManager.getCompilerOutput(module, contentFolderType));
   }
 }
Beispiel #21
0
 private static void retainOnlyJarsAndDirectories(List<VirtualFile> woSdk) {
   for (Iterator<VirtualFile> iterator = woSdk.iterator(); iterator.hasNext(); ) {
     VirtualFile file = iterator.next();
     final VirtualFile local = ArchiveVfsUtil.getVirtualFileForJar(file);
     final boolean dir = file.isDirectory();
     final String name = file.getName();
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Considering: "
               + file.getPath()
               + "; local="
               + local
               + "; dir="
               + dir
               + "; name="
               + name);
     }
     if (dir || local != null) {
       continue;
     }
     if (name.endsWith(".jar")) {
       continue;
     }
     LOG.debug("Removing");
     iterator.remove();
   }
 }
  private static List<RootModelImpl> getSortedChangedModels(
      Collection<ModifiableRootModel> rootModels, ModifiableModuleModel moduleModel) {
    List<RootModelImpl> result = ContainerUtil.newArrayListWithCapacity(rootModels.size());

    for (ModifiableRootModel model : rootModels) {
      RootModelImpl rootModel = (RootModelImpl) model;
      if (rootModel.isChanged()) {
        result.add(rootModel);
      }
    }

    DFSTBuilder<RootModelImpl> builder = createDFSTBuilder(result, moduleModel);
    Collections.sort(result, builder.comparator());

    return result;
  }
 public synchronized boolean removeRoot(
     @NotNull String name, @NotNull List<AbstractTreeNode> elements) {
   final Convertor<AbstractTreeNode, AbstractUrl> convertor =
       new Convertor<AbstractTreeNode, AbstractUrl>() {
         @Override
         public AbstractUrl convert(AbstractTreeNode obj) {
           return createUrlByElement(obj.getValue(), myProject);
         }
       };
   boolean result = true;
   for (AbstractTreeNode element : elements) {
     final List<AbstractTreeNode> path =
         TaskDefaultFavoriteListProvider.getPathToUsualNode(element);
     result &= findListToRemoveFrom(name, path.subList(1, path.size()), convertor);
   }
   return result;
 }
  private static void readFavoritesOneLevel(
      Element list, Project project, Collection<TreeItem<Pair<AbstractUrl, String>>> result) {
    final List listChildren = list.getChildren(FAVORITES_ROOT);
    if (listChildren == null || listChildren.isEmpty()) return;

    for (Object favorite : listChildren) {
      final Element favoriteElement = (Element) favorite;
      final String className = favoriteElement.getAttributeValue(CLASS_NAME);
      final AbstractUrl abstractUrl = readUrlFromElement(favoriteElement, project);
      if (abstractUrl != null) {
        final TreeItem<Pair<AbstractUrl, String>> treeItem =
            new TreeItem<Pair<AbstractUrl, String>>(Pair.create(abstractUrl, className));
        result.add(treeItem);
        readFavoritesOneLevel(favoriteElement, project, treeItem.getChildren());
      }
    }
  }
 @Nullable("returns null only if dir is under ignored folder")
 private static List<VirtualFile> getHierarchy(
     VirtualFile dir, @NotNull Set<VirtualFile> allRoots, @NotNull RootInfo info) {
   List<VirtualFile> hierarchy = ContainerUtil.newArrayList();
   boolean hasContentRoots = false;
   while (dir != null) {
     hasContentRoots |= info.contentRootOf.get(dir) != null;
     if (!hasContentRoots && isIgnored(dir)) {
       return null;
     }
     if (allRoots.contains(dir)) {
       hierarchy.add(dir);
     }
     dir = dir.getParent();
   }
   return hierarchy;
 }
  public void compile() throws CompilerException, CacheCorruptedException {
    Application application = ApplicationManager.getApplication();
    try {
      if (!myFilesToCompile.isEmpty()) {
        if (application.isUnitTestMode()) {
          saveTestData();
        }
        compileModules(buildModuleToFilesMap(myFilesToCompile));
      }
    } catch (SecurityException e) {
      throw new CompilerException(
          CompilerBundle.message("error.compiler.process.not.started", e.getMessage()), e);
    } catch (IllegalArgumentException e) {
      throw new CompilerException(e.getMessage(), e);
    } finally {
      for (final VirtualFile file : myModuleToTempDirMap.values()) {
        if (file != null) {
          final File ioFile = new File(file.getPath());
          FileUtil.asyncDelete(ioFile);
        }
      }
      myModuleToTempDirMap.clear();
    }

    if (!myFilesToCompile.isEmpty()
        && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) {
      // package-info.java hack
      final List<TranslatingCompiler.OutputItem> outputs =
          new ArrayList<TranslatingCompiler.OutputItem>();
      ApplicationManager.getApplication()
          .runReadAction(
              new Runnable() {
                public void run() {
                  for (final VirtualFile file : myFilesToCompile) {
                    if (PACKAGE_ANNOTATION_FILE_NAME.equals(file.getName())
                        && !myProcessedPackageInfos.contains(file)) {
                      outputs.add(new OutputItemImpl(file));
                    }
                  }
                }
              });
      if (!outputs.isEmpty()) {
        mySink.add(null, outputs, VirtualFile.EMPTY_ARRAY);
      }
    }
  }
 public static void addLibrary(
     Module module, String libName, String libDir, String[] classRoots, String[] sourceRoots) {
   String proto =
       (classRoots.length > 0 ? classRoots[0] : sourceRoots[0]).endsWith(".jar!/")
           ? JarFileSystem.PROTOCOL
           : LocalFileSystem.PROTOCOL;
   String parentUrl = VirtualFileManager.constructUrl(proto, libDir);
   List<String> classesUrls = new ArrayList<>();
   List<String> sourceUrls = new ArrayList<>();
   for (String classRoot : classRoots) {
     classesUrls.add(parentUrl + classRoot);
   }
   for (String sourceRoot : sourceRoots) {
     sourceUrls.add(parentUrl + sourceRoot);
   }
   ModuleRootModificationUtil.addModuleLibrary(module, libName, classesUrls, sourceUrls);
 }
Beispiel #28
0
  private static void doAssertContentFolders(
      ContentEntry e, final List<? extends ContentFolder> folders, String... expected) {
    List<String> actual = new ArrayList<String>();
    for (ContentFolder f : folders) {
      String rootUrl = e.getUrl();
      String folderUrl = f.getUrl();

      if (folderUrl.startsWith(rootUrl)) {
        int length = rootUrl.length() + 1;
        folderUrl = folderUrl.substring(Math.min(length, folderUrl.length()));
      }

      actual.add(folderUrl);
    }

    assertOrderedElementsAreEqual(actual, Arrays.asList(expected));
  }
 public static void addLibrary(
     Module module, ModifiableRootModel model, String libName, String libPath, String... jarArr) {
   List<VirtualFile> classesRoots = new ArrayList<>();
   for (String jar : jarArr) {
     if (!libPath.endsWith("/") && !jar.startsWith("/")) {
       jar = "/" + jar;
     }
     String path = libPath + jar;
     VirtualFile root;
     if (path.endsWith(".jar")) {
       root = JarFileSystem.getInstance().refreshAndFindFileByPath(path + "!/");
     } else {
       root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
     }
     assert root != null : "Library root folder not found: " + path + "!/";
     classesRoots.add(root);
   }
   addProjectLibrary(module, model, libName, classesRoots, Collections.emptyList());
 }
 private static VirtualFile[] getFilesToCheckReadonlyStatus(
     GeneratingCompiler.GenerationItem[] items) {
   List<VirtualFile> filesToCheck = new ArrayList<VirtualFile>();
   for (GeneratingCompiler.GenerationItem item : items) {
     if (item instanceof AndroidAptCompiler.AptGenerationItem) {
       final Set<File> generatedFiles =
           ((AndroidAptCompiler.AptGenerationItem) item).getGeneratedFiles().keySet();
       for (File generatedFile : generatedFiles) {
         if (generatedFile.exists()) {
           VirtualFile generatedVFile =
               LocalFileSystem.getInstance().findFileByIoFile(generatedFile);
           if (generatedVFile != null) {
             filesToCheck.add(generatedVFile);
           }
         }
       }
     }
   }
   return VfsUtil.toVirtualFileArray(filesToCheck);
 }