Search in sources :

Example 46 with Nullable

use of com.android.annotations.Nullable in project atlas by alibaba.

the class ProcessAwbAndroidResources method doFullTaskAction.

@Override
protected void doFullTaskAction() throws IOException {
    // we have to clean the source folder output in case the package name changed.
    File srcOut = getSourceOutputDir();
    if (srcOut != null) {
        //            FileUtils.emptyFolder(srcOut);
        srcOut.delete();
        srcOut.mkdirs();
    }
    @Nullable File resOutBaseNameFile = getPackageOutputFile();
    // If are in instant run mode and we have an instant run enabled manifest
    File instantRunManifest = getInstantRunManifestFile();
    File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null && instantRunManifest.exists() ? instantRunManifest : getManifestFile();
    //增加awb模块编译所需要的额外参数
    addAaptOptions();
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage, getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir()).setLibraries(getLibraries()).setPackageForR(getPackageForR()).setSourceOutputDir(absolutePath(srcOut)).setSymbolOutputDir(absolutePath(getTextSymbolOutputDir())).setResPackageOutput(absolutePath(resOutBaseNameFile)).setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType()).setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled()).setResourceConfigs(getResourceConfigs()).setSplits(getSplits()).setPreferredDensity(getPreferredDensity());
    @NonNull AtlasBuilder builder = (AtlasBuilder) getBuilder();
    //        MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder());
    //
    //        ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(
    //                new ToolOutputParser(new AaptOutputParser(), getILogger()),
    //                 builder.getErrorReporter());
    ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger());
    try {
        builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(), processOutputHandler, getMainSymbolFile());
        if (resOutBaseNameFile != null) {
            if (instantRunBuildContext.isInInstantRunMode()) {
                instantRunBuildContext.addChangedFile(InstantRunBuildContext.FileType.RESOURCES, resOutBaseNameFile);
                // get the new manifest file CRC
                JarFile jarFile = new JarFile(resOutBaseNameFile);
                String currentIterationCRC = null;
                try {
                    ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML);
                    if (entry != null) {
                        currentIterationCRC = String.valueOf(entry.getCrc());
                    }
                } finally {
                    jarFile.close();
                }
                // check the manifest file binary format.
                File crcFile = new File(instantRunSupportDir, "manifest.crc");
                if (crcFile.exists() && currentIterationCRC != null) {
                    // compare its content with the new binary file crc.
                    String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8);
                    if (!currentIterationCRC.equals(previousIterationCRC)) {
                        instantRunBuildContext.close();
                        instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus.BINARY_MANIFEST_FILE_CHANGE);
                    }
                }
                // write the new manifest file CRC.
                Files.createParentDirs(crcFile);
                Files.write(currentIterationCRC, crcFile, Charsets.UTF_8);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GradleException("process res exception", e);
    }
}
Also used : LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) ProcessOutputHandler(com.android.ide.common.process.ProcessOutputHandler) AaptPackageProcessBuilder(com.android.builder.core.AaptPackageProcessBuilder) NonNull(com.android.annotations.NonNull) ZipEntry(java.util.zip.ZipEntry) GradleException(org.gradle.api.GradleException) AtlasBuilder(com.android.builder.core.AtlasBuilder) LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) JarFile(java.util.jar.JarFile) JarFile(java.util.jar.JarFile) OutputFile(org.gradle.api.tasks.OutputFile) File(java.io.File) InputFile(org.gradle.api.tasks.InputFile) Nullable(com.android.annotations.Nullable) StopExecutionException(org.gradle.api.tasks.StopExecutionException) IOException(java.io.IOException) GradleException(org.gradle.api.GradleException)

Example 47 with Nullable

use of com.android.annotations.Nullable in project android by JetBrains.

the class DomPullParser method createNewDocumentBuilder.

/**
   * Creates an empty new document builder.
   * <p>
   * The new documents will not validate, will ignore comments, and will
   * support namespaces.
   *
   * @return the new document builder
   */
@Nullable
public static DocumentBuilder createNewDocumentBuilder() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    factory.setIgnoringComments(true);
    try {
        return factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        Logger.getInstance(DomPullParser.class).error(e);
    }
    return null;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Nullable(com.android.annotations.Nullable)

Example 48 with Nullable

use of com.android.annotations.Nullable in project android by JetBrains.

the class LayoutMetadata method getProperty.

/**
   * Returns the given property of the given DOM node, or null
   *
   * @param node the XML node to associate metadata with
   * @param name the name of the property to look up
   * @return the value stored with the given node and name, or null
   */
@Nullable
public static String getProperty(@NotNull Node node, @NotNull String name) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        String value = element.getAttributeNS(TOOLS_URI, name);
        if (value != null && value.isEmpty()) {
            value = null;
        }
        return value;
    }
    return null;
}
Also used : Element(org.w3c.dom.Element) Nullable(com.android.annotations.Nullable)

Example 49 with Nullable

use of com.android.annotations.Nullable in project android by JetBrains.

the class LayoutMetadata method setProperty.

/**
   * Sets the given property of the given DOM node to a given value, or if null clears
   * the property.
   */
public static void setProperty(@NotNull final Project project, @Nullable String title, @NotNull final XmlFile file, @NotNull final XmlTag element, @NotNull final String name, @Nullable final String namespace, @Nullable final String value) {
    String capitalizedName = StringUtil.capitalize(name);
    if (title == null) {
        title = String.format(value != null ? "Set %1$s" : "Clear %1$s", capitalizedName);
    }
    WriteCommandAction<Void> action = new WriteCommandAction<Void>(project, title, file) {

        @Override
        protected void run(@NotNull Result<Void> result) throws Throwable {
            if (value == null) {
                // Clear attribute
                XmlAttribute attribute;
                if (namespace != null) {
                    attribute = element.getAttribute(name, namespace);
                } else {
                    attribute = element.getAttribute(name);
                }
                if (attribute != null) {
                    attribute.delete();
                }
            } else {
                if (namespace != null) {
                    AndroidResourceUtil.ensureNamespaceImported(file, namespace, null);
                    element.setAttribute(name, namespace, value);
                } else {
                    element.setAttribute(name, value);
                }
            }
        }
    };
    action.execute();
    // Also set the values on the same elements in any resource variations
    // of the same layout
    // TODO: This should be done after a brief delay, say 50ms
    final List<XmlTag> list = ApplicationManager.getApplication().runReadAction(new Computable<List<XmlTag>>() {

        @Override
        @Nullable
        public List<XmlTag> compute() {
            // Look up the id of the element, if any
            String id = stripIdPrefix(element.getAttributeValue(ATTR_ID, ANDROID_URI));
            if (id.isEmpty()) {
                return null;
            }
            VirtualFile layoutFile = file.getVirtualFile();
            if (layoutFile != null) {
                final List<VirtualFile> variations = ResourceHelper.getResourceVariations(layoutFile, false);
                if (variations.isEmpty()) {
                    return null;
                }
                PsiManager manager = PsiManager.getInstance(project);
                List<XmlTag> list = Lists.newArrayList();
                for (VirtualFile file : variations) {
                    PsiFile psiFile = manager.findFile(file);
                    if (psiFile == null) {
                        continue;
                    }
                    for (XmlTag tag : PsiTreeUtil.findChildrenOfType(psiFile, XmlTag.class)) {
                        XmlAttribute attribute = tag.getAttribute(ATTR_ID, ANDROID_URI);
                        if (attribute == null || attribute.getValue() == null) {
                            continue;
                        }
                        if (attribute.getValue().endsWith(id) && id.equals(stripIdPrefix(attribute.getValue()))) {
                            list.add(tag);
                            break;
                        }
                    }
                }
                return list;
            }
            return null;
        }
    });
    if (list != null && !list.isEmpty()) {
        List<PsiFile> affectedFiles = Lists.newArrayList();
        for (XmlTag tag : list) {
            PsiFile psiFile = tag.getContainingFile();
            if (psiFile != null) {
                affectedFiles.add(psiFile);
            }
        }
        action = new WriteCommandAction<Void>(project, title, affectedFiles.toArray(new PsiFile[affectedFiles.size()])) {

            @Override
            protected void run(@NotNull Result<Void> result) throws Throwable {
                for (XmlTag tag : list) {
                    if (value == null) {
                        // Clear attribute
                        XmlAttribute attribute;
                        if (namespace != null) {
                            attribute = tag.getAttribute(name, namespace);
                        } else {
                            attribute = tag.getAttribute(name);
                        }
                        if (attribute != null) {
                            attribute.delete();
                        }
                    } else {
                        if (namespace != null) {
                            AndroidResourceUtil.ensureNamespaceImported(file, namespace, null);
                            tag.setAttribute(name, namespace, value);
                        } else {
                            tag.setAttribute(name, value);
                        }
                    }
                }
            }
        };
        action.execute();
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) VirtualFile(com.intellij.openapi.vfs.VirtualFile) XmlAttribute(com.intellij.psi.xml.XmlAttribute) PsiManager(com.intellij.psi.PsiManager) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) List(java.util.List) PsiFile(com.intellij.psi.PsiFile) Nullable(com.android.annotations.Nullable) XmlTag(com.intellij.psi.xml.XmlTag)

Example 50 with Nullable

use of com.android.annotations.Nullable in project android by JetBrains.

the class LayoutPsiPullParser method createSnapshot.

@Nullable
private static TagSnapshot createSnapshot(@NotNull XmlTag tag) {
    // <include> tags can't be at the root level; handle <fragment> rewriting here such that we don't
    // need to handle it as a tag name rewrite (where it's harder to change the structure)
    // https://code.google.com/p/android/issues/detail?id=67910
    tag = getRootTag(tag);
    if (tag == null || (tag.isEmpty() && tag.getName().isEmpty())) {
        // Rely on code inspection to log errors in the layout but return something that layoutlib can paint.
        return EMPTY_LAYOUT;
    }
    String rootTag = tag.getName();
    switch(rootTag) {
        case VIEW_FRAGMENT:
            return createSnapshotForViewFragment(tag);
        case FRAME_LAYOUT:
            return createSnapshotForFrameLayout(tag);
        case VIEW_MERGE:
            return createSnapshotForMerge(tag);
        default:
            TagSnapshot root = TagSnapshot.createTagSnapshot(tag);
            // attribute binding to work. (Without this, a <ListView> at the root level will not show Item 1, Item 2, etc.
            if (rootTag.equals(LIST_VIEW) || rootTag.equals(EXPANDABLE_LIST_VIEW) || rootTag.equals(GRID_VIEW) || rootTag.equals(SPINNER)) {
                XmlAttribute id = tag.getAttribute(ATTR_ID, ANDROID_URI);
                if (id == null) {
                    String prefix = tag.getPrefixByNamespace(ANDROID_URI);
                    if (prefix != null) {
                        root.setAttribute(ATTR_ID, ANDROID_URI, prefix, "@+id/_dynamic");
                    }
                }
            }
            return root;
    }
}
Also used : XmlAttribute(com.intellij.psi.xml.XmlAttribute) Nullable(com.android.annotations.Nullable)

Aggregations

Nullable (com.android.annotations.Nullable)83 File (java.io.File)21 IOException (java.io.IOException)9 ResourceType (com.android.resources.ResourceType)8 PsiClass (com.intellij.psi.PsiClass)7 PsiElement (com.intellij.psi.PsiElement)7 PsiReferenceExpression (com.intellij.psi.PsiReferenceExpression)7 ResourceUrl (com.android.ide.common.resources.ResourceUrl)6 PsiAssignmentExpression (com.intellij.psi.PsiAssignmentExpression)6 PsiDeclarationStatement (com.intellij.psi.PsiDeclarationStatement)6 PsiExpression (com.intellij.psi.PsiExpression)6 PsiExpressionStatement (com.intellij.psi.PsiExpressionStatement)6 PsiMethod (com.intellij.psi.PsiMethod)6 PsiStatement (com.intellij.psi.PsiStatement)6 ArrayList (java.util.ArrayList)6 PsiField (com.intellij.psi.PsiField)5 PsiFile (com.intellij.psi.PsiFile)4 Node (lombok.ast.Node)4 UReferenceExpression (org.jetbrains.uast.UReferenceExpression)4 AbstractResourceRepository (com.android.ide.common.res2.AbstractResourceRepository)3