com.android.ide.common.res2.ResourceSet Java Examples

The following examples show how to use com.android.ide.common.res2.ResourceSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MergeAndroidResourceSourcesStep.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public StepExecutionResult execute(ExecutionContext context) {
  ResourceMerger merger = new ResourceMerger(1);
  try {
    for (Path resPath : getResPaths()) {
      ResourceSet set = new ResourceSet(resPath.toString(), true);
      set.setDontNormalizeQualifiers(true);
      set.addSource(resPath.toFile());
      set.loadFromFiles(new ResourcesSetLoadLogger(context.getBuckEventBus()));
      merger.addDataSet(set);
    }
    MergedResourceWriter writer =
        MergedResourceWriter.createWriterWithoutPngCruncher(
            getOutFolderPath().toFile(),
            null /*publicFile*/,
            null /*blameLogFolder*/,
            new NoOpResourcePreprocessor(),
            getTmpFolderPath().toFile());
    merger.mergeData(writer, /* cleanUp */ false);
  } catch (MergingException e) {
    LOG.error(e, "Failed merging resources.");
    return StepExecutionResults.ERROR;
  }
  return StepExecutionResults.SUCCESS;
}
 
Example #2
Source File: AARLibraries.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Merges the resources from all of the dependent AAR libraries into the main resource bundle for
 * the compiling app.
 *
 * @param outputDir the output directory to write the R.java files.
 * @param mainResDir the resource directory where the resource descriptors for the app reside.
 * @param cruncher configured PNG cruncher utility for reducing the size of PNG assets.
 * @return true if the merge was successful, otherwise false.
 */
public boolean mergeResources(File outputDir, File mainResDir, PngCruncher cruncher) {
  List<ResourceSet> resourceSets = getResourceSets();
  ResourceSet mainResSet = new ResourceSet("main");
  mainResSet.addSource(mainResDir);
  resourceSets.add(mainResSet);
  ResourceMerger merger = new ResourceMerger();

  try {
    for (ResourceSet resourceSet : resourceSets) {
      resourceSet.loadFromFiles(LOG);
      merger.addDataSet(resourceSet);
    }

    MergedResourceWriter writer = new MergedResourceWriter(outputDir, cruncher, false, false, null);
    writer.setInsertSourceMarkers(true);
    merger.mergeData(writer, false);
    return true;
  } catch(MergingException e) {
    e.printStackTrace();
    return false;
  }
}
 
Example #3
Source File: MergeResources.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
private List<ResourceSet> getConfiguredResourceSets() {
    List<ResourceSet> resourceSets = Lists.newArrayList(getInputResourceSets());
    List<ResourceSet> generatedSets = Lists.newArrayListWithCapacity(resourceSets.size());

    for (ResourceSet resourceSet : resourceSets) {
        resourceSet.setNormalizeResources(normalizeResources);
        resourceSet.setPreprocessor(preprocessor);
        ResourceSet generatedSet = new GeneratedResourceSet(resourceSet);
        resourceSet.setGeneratedSet(generatedSet);
        generatedSets.add(generatedSet);
    }

    // Put all generated sets at the start of the list.
    resourceSets.addAll(0, generatedSets);
    return resourceSets;
}
 
Example #4
Source File: BaseVariantData.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Discover all sub-folders of all the {@link ResourceSet#getSourceFiles()} which names are
 * starting with one of the provided prefixes.
 *
 * @param resourceSets the list of sources {@link ResourceSet}
 * @param prefixes     the list of prefixes to look for folders.
 * @return a possibly empty list of folders.
 */
@NonNull
private static List<String> getAllFilters(List<ResourceSet> resourceSets, String... prefixes) {
    List<String> providedResFolders = new ArrayList<String>();
    for (ResourceSet resourceSet : resourceSets) {
        for (File resFolder : resourceSet.getSourceFiles()) {
            File[] subResFolders = resFolder.listFiles();
            if (subResFolders != null) {
                for (File subResFolder : subResFolders) {
                    for (String prefix : prefixes) {
                        if (subResFolder.getName().startsWith(prefix)) {
                            providedResFolders
                                    .add(subResFolder.getName().substring(prefix.length()));
                        }
                    }
                }
            }
        }
    }
    return providedResFolders;
}
 
Example #5
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<ResourceSet> getConfiguredResourceSets(ResourcePreprocessor preprocessor) {
    // it is possible that this get called twice in case the incremental run fails and reverts
    // back to full task run. Because the cached ResourceList is modified we don't want
    // to recompute this twice (plus, why recompute it twice anyway?)
    if (processedInputs == null) {
        processedInputs = computeResourceSetList();
        List<ResourceSet> generatedSets = Lists.newArrayListWithCapacity(processedInputs.size());

        for (ResourceSet resourceSet : processedInputs) {
            resourceSet.setPreprocessor(preprocessor);
            ResourceSet generatedSet = new GeneratedResourceSet(resourceSet);
            resourceSet.setGeneratedSet(generatedSet);
            generatedSets.add(generatedSet);
        }

        // We want to keep the order of the inputs. Given inputs:
        // (A, B, C, D)
        // We want to get:
        // (A-generated, A, B-generated, B, C-generated, C, D-generated, D).
        // Therefore, when later in {@link DataMerger} we look for sources going through the
        // list backwards, B-generated will take priority over A (but not B).
        // A real life use-case would be if an app module generated resource overrode a library
        // module generated resource (existing not in generated but bundled dir at this stage):
        // (lib, app debug, app main)
        // We will get:
        // (lib generated, lib, app debug generated, app debug, app main generated, app main)
        for (int i = 0; i < generatedSets.size(); ++i) {
            processedInputs.add(2 * i, generatedSets.get(i));
        }
    }

    return processedInputs;
}
 
Example #6
Source File: AARLibraries.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a list of resource sets loaded from the AAR libraries in the collection. Note that this
 * is computed on every call (results are not cached), so it is recommended that the caller only
 * call this after all AAR libraries of interest have been added.
 * @return  the list of all resource sets available across the AAR libraries.
 */
private List<ResourceSet> getResourceSets() {
  List<ResourceSet> resourceSets = new ArrayList<>();
  for (AARLibrary library : this) {
    if (library.getResDirectory() != null) {
      ResourceSet resourceSet = new ResourceSet(library.getDirectory().getName());
      resourceSet.addSource(library.getResDirectory());
      resourceSets.add(resourceSet);
    }
  }
  return resourceSets;
}
 
Example #7
Source File: MergeResources.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doFullTaskAction() throws IOException {
    // this is full run, clean the previous output
    File destinationDir = getOutputDir();
    FileUtils.emptyFolder(destinationDir);

    List<ResourceSet> resourceSets = getConfiguredResourceSets();

    // create a new merger and populate it with the sets.
    ResourceMerger merger = new ResourceMerger();

    try {
        for (ResourceSet resourceSet : resourceSets) {
            resourceSet.loadFromFiles(getILogger());
            merger.addDataSet(resourceSet);
        }

        // get the merged set and write it down.
        MergedResourceWriter writer = new MergedResourceWriter(
                destinationDir, getCruncher(),
                getCrunchPng(), getProcess9Patch(), getPublicFile(), preprocessor);
        writer.setInsertSourceMarkers(getInsertSourceMarkers());

        merger.mergeData(writer, false /*doCleanUp*/);

        // No exception? Write the known state.
        merger.writeBlobTo(getIncrementalFolder(), writer);
        throw new StopExecutionException("Stop for now.");
    } catch (MergingException e) {
        System.out.println(e.getMessage());
        merger.cleanBlob(getIncrementalFolder());
        throw new ResourceException(e.getMessage(), e);
    }
}
 
Example #8
Source File: BaseVariantData.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public List<String> discoverListOfResourceConfigs() {
    List<String> resFoldersOnDisk = new ArrayList<String>();
    List<ResourceSet> resourceSets = variantConfiguration.getResourceSets(
            getGeneratedResFolders(), false /* no libraries resources */);
    resFoldersOnDisk.addAll(getAllFilters(
            resourceSets,
            DiscoverableFilterType.LANGUAGE.folderPrefix,
            DiscoverableFilterType.DENSITY.folderPrefix));
    return resFoldersOnDisk;
}
 
Example #9
Source File: BaseVariantData.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the list of filter values for a filter type either from the user specified build.gradle
 * settings or through a discovery mechanism using folders names.
 *
 * @param resourceSets the list of source folders to discover from.
 * @param filterType   the filter type
 * @param splits       the variant's configuration for splits.
 * @return a possibly empty list of filter value for this filter type.
 */
@NonNull
private static Set<String> getFilters(
        @NonNull List<ResourceSet> resourceSets,
        @NonNull DiscoverableFilterType filterType,
        @NonNull Splits splits) {

    Set<String> filtersList = new HashSet<String>();
    if (filterType.isAuto(splits)) {
        filtersList.addAll(getAllFilters(resourceSets, filterType.folderPrefix));
    } else {
        filtersList.addAll(filterType.getConfiguredFilters(splits));
    }
    return filtersList;
}
 
Example #10
Source File: MergeResources.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public void setInputResourceSets(
        List<ResourceSet> inputResourceSets) {
    this.inputResourceSets = inputResourceSets;
}
 
Example #11
Source File: MergeResources.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(MergeResources mergeResourcesTask) {
    final BaseVariantData<? extends BaseVariantOutputData> variantData =
            scope.getVariantData();
    final AndroidConfig extension = scope.getGlobalScope().getExtension();

    mergeResourcesTask.setAndroidBuilder(scope.getGlobalScope().getAndroidBuilder());
    mergeResourcesTask.setVariantName(scope.getVariantConfiguration().getFullName());
    mergeResourcesTask.setIncrementalFolder(new File(
            scope.getGlobalScope().getBuildDir() + "/" + AndroidProject.FD_INTERMEDIATES +
                    "/incremental/" + taskNamePrefix + "Resources/" +
                    variantData.getVariantConfiguration().getDirName()));

    mergeResourcesTask.process9Patch = process9Patch;
    mergeResourcesTask.crunchPng = extension.getAaptOptions()
            .getCruncherEnabled();
    mergeResourcesTask.normalizeResources =
            extension.getBuildToolsRevision()
                    .compareTo(NORMALIZE_RESOURCES_BUILD_TOOLS) < 0;

    // Only one pre-processor for now. The code will need slight changes when we add more.
    mergeResourcesTask.preprocessor = new VectorDrawableRenderer(
            scope.getGeneratedPngsOutputDir(),
            extension.getPreprocessingOptions().getTypedDensities(),
            mergeResourcesTask.getILogger());

    ConventionMappingHelper.map(mergeResourcesTask, "useNewCruncher",
            new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return extension.getAaptOptions()
                            .getUseNewCruncher();
                }
            });

    ConventionMappingHelper.map(mergeResourcesTask, "inputResourceSets",
            new Callable<List<ResourceSet>>() {
                @Override
                public List<ResourceSet> call() throws Exception {
                    List<File> generatedResFolders = Lists.newArrayList(
                            scope.getGeneratedResOutputDir());
                    if (variantData.getExtraGeneratedResFolders() != null) {
                        generatedResFolders.addAll(
                                variantData.getExtraGeneratedResFolders());
                    }
                    return variantData.getVariantConfiguration()
                            .getResourceSets(generatedResFolders, includeDependencies);
                }
            });
    ConventionMappingHelper.map(mergeResourcesTask, "outputDir", new Callable<File>() {
        @Override
        public File call() throws Exception {
            return outputLocation != null ? outputLocation
                    : scope.getDefaultMergeResourcesOutputDir();
        }
    });

    variantData.mergeResourcesTask = mergeResourcesTask;
}
 
Example #12
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void doFullTaskAction() throws IOException {
    ResourcePreprocessor preprocessor = getPreprocessor();

    // this is full run, clean the previous output
    File destinationDir = getOutputDir();
    FileUtils.cleanOutputDir(destinationDir);

    List<ResourceSet> resourceSets = getConfiguredResourceSets(preprocessor);

    // create a new merger and populate it with the sets.
    ResourceMerger merger = new ResourceMerger(minSdk);
    MergingLog mergingLog =
            getBlameLogFolder() != null ? new MergingLog(getBlameLogFolder()) : null;

    try (QueueableResourceCompiler resourceCompiler =
                 processResources
                         ? makeAapt(
                         buildToolInfo.get(),
                         aaptGeneration,
                         getBuilder(),
                         crunchPng,
                         mergingLog)
                         : QueueableResourceCompiler.NONE) {

        for (ResourceSet resourceSet : resourceSets) {
            resourceSet.loadFromFiles(getILogger());
            merger.addDataSet(resourceSet);
        }

        MergedResourceWriter writer =
                new MergedResourceWriter(
                        workerExecutorFacade,
                        destinationDir,
                        getPublicFile(),
                        mergingLog,
                        preprocessor,
                        resourceCompiler,
                        getIncrementalFolder(),
                        null,
                        null,
                        false,
                        getCrunchPng());

        merger.mergeData(writer, false /*doCleanUp*/);

        // No exception? Write the known state.
        merger.writeBlobTo(getIncrementalFolder(), writer, false);
    } catch (MergingException e) {
        System.out.println(e.getMessage());
        merger.cleanBlob(getIncrementalFolder());
        throw new ResourceException(e.getMessage(), e);
    } finally {
        cleanup();
    }
}
 
Example #13
Source File: MergeResources.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public List<ResourceSet> getInputResourceSets() {
    return inputResourceSets;
}
 
Example #14
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
        public void execute(MergeResources mergeResourcesTask) {
            final Project project = androidExtension.getProject();

            mergeResourcesTask.setMinSdk(Integer.parseInt(androidExtension.getMinSdkVersion()));
            mergeResourcesTask.buildToolInfo = () -> BuildToolInfo.fromStandardDirectoryLayout(
                    androidExtension.getBuildToolsRevision(), androidExtension.getBuildToolsDir());

            mergeResourcesTask.aaptGeneration = AaptGeneration.AAPT_V1;
            mergeResourcesTask.setAndroidBuilder(androidExtension.getAndroidBuilder());
            mergeResourcesTask.fileCache = androidExtension.getBuildCache();
            mergeResourcesTask.setVariantName("jfx");
            mergeResourcesTask.setIncrementalFolder(androidExtension.getIncrementalDirectory(getName()));
            // Libraries use this task twice, once for compilation (with dependencies),
            // where blame is useful, and once for packaging where it is not.
            if (includeDependencies) {
                mergeResourcesTask.setBlameLogFolder(androidExtension.getResourceBlameLogDirectory());
            }
            mergeResourcesTask.processResources = processResources;
            mergeResourcesTask.crunchPng = true;

            final boolean validateEnabled = true;

            mergeResourcesTask.setValidateEnabled(validateEnabled);

//            if (includeDependencies) {
//                mergeResourcesTask.libraries = scope.getArtifactCollection(
//                        RUNTIME_CLASSPATH, ALL, ANDROID_RES);
//            }

            mergeResourcesTask.resSetSupplier =
                    () -> {
                        ResourceSet mainResourceSet = new ResourceSet(BuilderConstants.MAIN, null, null, validateEnabled);
                        mainResourceSet.addSource(project.file(androidExtension.getResDirectory()));
                        return Collections.singletonList(mainResourceSet);
                    };
            mergeResourcesTask.sourceFolderInputs =
                    TaskInputHelper.bypassFileSupplier(
                            () -> Collections.singletonList(project.file(androidExtension.getResDirectory())));
            mergeResourcesTask.renderscriptResOutputDir = project.files(androidExtension.getRenderscriptResOutputDirectory());
            mergeResourcesTask.generatedResOutputDir = project.files(androidExtension.getGeneratedResOutputDirectory());

            mergeResourcesTask.setOutputDir(outputLocation);
            mergeResourcesTask.setGeneratedPngsOutputDir(androidExtension.getGeneratedPngsOutputDirectory());
        }
 
Example #15
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Compute the list of resource set to be used during execution based all the inputs.
 */
List<ResourceSet> computeResourceSetList() {
    List<ResourceSet> sourceFolderSets = resSetSupplier.get();
    int size = sourceFolderSets.size() + 4;
    if (libraries != null) {
        size += libraries.getArtifacts().size();
    }

    List<ResourceSet> resourceSetList = Lists.newArrayListWithExpectedSize(size);

    // add at the beginning since the libraries are less important than the folder based
    // resource sets.
    // get the dependencies first
    if (libraries != null) {
        Set<ResolvedArtifactResult> libArtifacts = libraries.getArtifacts();
        // the order of the artifact is descending order, so we need to reverse it.
        for (ResolvedArtifactResult artifact : libArtifacts) {
            ResourceSet resourceSet =
                    new ResourceSet(
                            MergeManifests.getArtifactName(artifact),
                            null,
                            null,
                            validateEnabled);
            resourceSet.setFromDependency(true);
            resourceSet.addSource(artifact.getFile());

            // add to 0 always, since we need to reverse the order.
            resourceSetList.add(0,resourceSet);
        }
    }

    // add the folder based next
    resourceSetList.addAll(sourceFolderSets);

    // We add the generated folders to the main set
    List<File> generatedResFolders = Lists.newArrayList();

    generatedResFolders.addAll(renderscriptResOutputDir.getFiles());
    generatedResFolders.addAll(generatedResOutputDir.getFiles());

    // add the generated files to the main set.
    final ResourceSet mainResourceSet = sourceFolderSets.get(0);
    assert mainResourceSet.getConfigName().equals(BuilderConstants.MAIN);
    mainResourceSet.addSources(generatedResFolders);

    return resourceSetList;
}
 
Example #16
Source File: MergeResources.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void doIncrementalTaskAction(Map<File, FileStatus> changedInputs)
        throws IOException {
    ResourcePreprocessor preprocessor = getPreprocessor();

    // create a merger and load the known state.
    ResourceMerger merger = new ResourceMerger(minSdk);
    try {
        if (!merger.loadFromBlob(getIncrementalFolder(), true /*incrementalState*/)) {
            doFullTaskAction();
            return;
        }

        for (ResourceSet resourceSet : merger.getDataSets()) {
            resourceSet.setPreprocessor(preprocessor);
        }

        List<ResourceSet> resourceSets = getConfiguredResourceSets(preprocessor);

        // compare the known state to the current sets to detect incompatibility.
        // This is in case there's a change that's too hard to do incrementally. In this case
        // we'll simply revert to full build.
        if (!merger.checkValidUpdate(resourceSets)) {
            getLogger().info("Changed Resource sets: full task run!");
            doFullTaskAction();
            return;
        }

        // The incremental process is the following:
        // Loop on all the changed files, find which ResourceSet it belongs to, then ask
        // the resource set to update itself with the new file.
        for (Map.Entry<File, FileStatus> entry : changedInputs.entrySet()) {
            File changedFile = entry.getKey();

            merger.findDataSetContaining(changedFile, fileValidity);
            if (fileValidity.getStatus() == FileValidity.FileStatus.UNKNOWN_FILE) {
                doFullTaskAction();
                return;
            } else if (fileValidity.getStatus() == FileValidity.FileStatus.VALID_FILE) {
                if (!fileValidity.getDataSet().updateWith(
                        fileValidity.getSourceFile(), changedFile, entry.getValue(),
                        getILogger())) {
                    getLogger().info(
                            String.format("Failed to process %s event! Full task run",
                                    entry.getValue()));
                    doFullTaskAction();
                    return;
                }
            }
        }

        MergingLog mergingLog =
                getBlameLogFolder() != null ? new MergingLog(getBlameLogFolder()) : null;

        try (QueueableResourceCompiler resourceCompiler =
                     processResources
                             ? makeAapt(
                             buildToolInfo.get(),
                             aaptGeneration,
                             getBuilder(),
                             crunchPng,
                             mergingLog)
                             : QueueableResourceCompiler.NONE) {

            MergedResourceWriter writer =
                    new MergedResourceWriter(
                            workerExecutorFacade,
                            getOutputDir(),
                            getPublicFile(),
                            mergingLog,
                            preprocessor,
                            resourceCompiler,
                            getIncrementalFolder(),
                            null,
                            null,
                            false,
                            getCrunchPng());

            merger.mergeData(writer, false /*doCleanUp*/);

            // No exception? Write the known state.
            merger.writeBlobTo(getIncrementalFolder(), writer, false);
        }
    } catch (MergingException e) {
        merger.cleanBlob(getIncrementalFolder());
        throw new ResourceException(e.getMessage(), e);
    } finally {
        cleanup();
    }
}
 
Example #17
Source File: BaseVariantData.java    From javaide with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Calculates the filters for this variant. The filters can either be manually specified by
 * the user within the build.gradle or can be automatically discovered using the variant
 * specific folders.
 * <p>
 * This method must be called before {@link #getFilters(OutputFile.FilterType)}.
 *
 * @param splits the splits configuration from the build.gradle.
 */
public void calculateFilters(Splits splits) {

    List<ResourceSet> resourceSets = variantConfiguration
            .getResourceSets(getGeneratedResFolders(), false);
    densityFilters = getFilters(resourceSets, DiscoverableFilterType.DENSITY, splits);
    languageFilters = getFilters(resourceSets, DiscoverableFilterType.LANGUAGE, splits);
}