file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
LayoutXmlParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/LayoutXmlParser.java
package com.tyron.xml.completion.repository.parser; import com.google.common.collect.ImmutableList; import com.tyron.builder.compiler.manifest.SdkConstants; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.xml.completion.repository.api.LayoutInfo; import com.tyron.xml.completion.repository.api.LayoutResourceValueImpl; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.ResourceValueImpl; import com.tyron.xml.completion.util.DOMUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import kotlin.io.FilesKt; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMNode; import org.eclipse.lemminx.dom.DOMParser; import org.eclipse.lemminx.dom.DOMProcessingInstruction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LayoutXmlParser implements ResourceParser { private static class Result { public LayoutInfo layoutInfo; public List<ResourceValue> additionalValues; } @Override public List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException { if (!"xml".equals(FilesKt.getExtension(file)) || contents == null) { return Collections.emptyList(); } DOMDocument document = DOMParser.getInstance().parse(contents, "", null); List<DOMNode> roots = document.getRoots(); for (DOMNode root : roots) { if (root instanceof DOMProcessingInstruction) { continue; } return parseRoot(file, root, namespace, libraryName); } return ImmutableList.of(); } private List<ResourceValue> parseRoot( File file, DOMNode root, ResourceNamespace namespace, String libraryName) { List<ResourceValue> values = new ArrayList<>(); Result result = parseLayout(root, namespace, libraryName); ResourceReference resourceReference = new ResourceReference( namespace, ResourceType.LAYOUT, FilesKt.getNameWithoutExtension(file)); LayoutResourceValueImpl layoutValue = new LayoutResourceValueImpl(resourceReference, null, libraryName, result.layoutInfo); values.add(layoutValue); if (result.additionalValues != null) { values.addAll(result.additionalValues); } return values; } private Result parseLayout(DOMNode root, ResourceNamespace namespace, String libraryName) { String tag = root.getLocalName(); if (tag == null) { tag = ""; } Result result = new Result(); LayoutInfo layoutInfo = new LayoutInfo(tag); result.layoutInfo = layoutInfo; result.additionalValues = new ArrayList<>(); parseAttributes(root, namespace, libraryName, result); List<DOMNode> children = root.getChildren(); if (children != null) { for (DOMNode child : children) { Result childResult = parseLayout(child, namespace, libraryName); if (childResult.layoutInfo != null) { layoutInfo.addChild(childResult.layoutInfo); } if (childResult.additionalValues != null) { result.additionalValues.addAll(childResult.additionalValues); } } } return result; } private void parseAttributes( DOMNode node, ResourceNamespace namespace, String libraryName, Result result) { ResourceNamespace.Resolver resolver = DOMUtils.getNamespaceResolver(node.getOwnerDocument()); String prefix = resolver.uriToPrefix(ResourceNamespace.ANDROID.getXmlNamespaceUri()); if (prefix != null) { DOMAttr idAttr = node.getAttributeNode(prefix, "id"); if (idAttr != null) { String value = idAttr.getValue(); ResourceValue resourceValue = parseIdValue(value, namespace, libraryName); if (resourceValue != null) { result.additionalValues.add(resourceValue); } } } List<DOMAttr> attributeNodes = node.getAttributeNodes(); if (attributeNodes != null) { for (DOMAttr attrNode : attributeNodes) { result.layoutInfo.addAttribute(attrNode.getName(), attrNode.getValue()); } } } private ResourceValue parseIdValue( String value, ResourceNamespace namespace, String libraryName) { if (value == null) { return null; } if (!value.startsWith(SdkConstants.NEW_ID_PREFIX)) { return null; } String name = value.substring(SdkConstants.NEW_ID_PREFIX.length()); if (name.isEmpty()) { return null; } try { ResourceReference reference = new ResourceReference(namespace, ResourceType.ID, name); return new ResourceValueImpl(reference, null, libraryName); } catch (IllegalArgumentException e) { return null; } } }
5,049
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TemporaryParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/TemporaryParser.java
package com.tyron.xml.completion.repository.parser; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.ResourceValueImpl; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import kotlin.io.FilesKt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** A parser used by temporary implementations to generate R.java fields */ public class TemporaryParser implements ResourceParser { private final ResourceType mType; public TemporaryParser(@NotNull ResourceType type) { mType = type; } @Override public List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException { // temporary parser so drawables would get generated to R.java ResourceReference reference = new ResourceReference(namespace, mType, FilesKt.getNameWithoutExtension(file)); ResourceValue value = new ResourceValueImpl(reference, null, libraryName); return Collections.singletonList(value); } }
1,376
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
MenuParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/MenuParser.java
package com.tyron.xml.completion.repository.parser; import com.tyron.builder.compiler.manifest.SdkConstants; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.ResourceValueImpl; import com.tyron.xml.completion.util.DOMUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import kotlin.io.FilesKt; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMParser; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class MenuParser implements ResourceParser { @Override public List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException { if (contents == null) { return Collections.emptyList(); } DOMDocument parsed = DOMParser.getInstance().parse(contents, file.toURI().toString(), null); if (parsed == null) { return Collections.emptyList(); } DOMElement rootElement = DOMUtils.getRootElement(parsed); if (rootElement == null) { return Collections.emptyList(); } if (!SdkConstants.TAG_MENU.equals(rootElement.getTagName())) { return Collections.emptyList(); } return parseMenu(file, rootElement, namespace, libraryName); } private List<ResourceValue> parseMenu( File file, DOMElement root, ResourceNamespace namespace, String libraryName) { String name = FilesKt.getNameWithoutExtension(file); ResourceReference resourceReference = new ResourceReference(namespace, ResourceType.MENU, name); ResourceValueImpl resourceValue = new ResourceValueImpl(resourceReference, null, libraryName); List<ResourceValue> resourceValues = new ArrayList<>(); resourceValues.add(resourceValue); ResourceNamespace.Resolver resolver = DOMUtils.getNamespaceResolver(root.getOwnerDocument()); String prefix = resolver.uriToPrefix(ResourceNamespace.ANDROID.getXmlNamespaceUri()); if (prefix != null) { List<DOMElement> items = DOMUtils.findElementsWithTagName(root, "item"); for (DOMElement item : items) { DOMAttr id = item.getAttributeNode(prefix, "id"); if (id != null) { ResourceValue idValue = parseIdValue(id.getValue(), namespace, libraryName); if (idValue != null) { resourceValues.add(idValue); } } } } return resourceValues; } private ResourceValue parseIdValue( String value, ResourceNamespace namespace, String libraryName) { if (value == null) { return null; } if (!value.startsWith(SdkConstants.NEW_ID_PREFIX)) { return null; } String name = value.substring(SdkConstants.NEW_ID_PREFIX.length()); if (name.isEmpty()) { return null; } try { ResourceReference reference = new ResourceReference(namespace, ResourceType.ID, name); return new ResourceValueImpl(reference, null, libraryName); } catch (IllegalArgumentException e) { return null; } } }
3,457
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DrawableXmlParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/DrawableXmlParser.java
package com.tyron.xml.completion.repository.parser; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceValue; import java.io.File; import java.io.IOException; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class DrawableXmlParser implements ResourceParser { @Override public List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException { return null; } }
635
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ValuesXmlParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/ValuesXmlParser.java
package com.tyron.xml.completion.repository.parser; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Ints; import com.tyron.builder.compiler.manifest.SdkConstants; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.AttrResourceValueImpl; import com.tyron.xml.completion.repository.api.AttributeFormat; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.ResourceValueImpl; import com.tyron.xml.completion.repository.api.StyleItemResourceValue; import com.tyron.xml.completion.repository.api.StyleItemResourceValueImpl; import com.tyron.xml.completion.repository.api.StyleResourceValueImpl; import com.tyron.xml.completion.repository.api.StyleableResourceValue; import com.tyron.xml.completion.repository.api.StyleableResourceValueImpl; import com.tyron.xml.completion.util.DOMUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import kotlin.io.FilesKt; import org.eclipse.lemminx.dom.DOMComment; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMNode; import org.eclipse.lemminx.dom.DOMParser; import org.eclipse.lemminx.dom.DOMProcessingInstruction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ValuesXmlParser implements ResourceParser { @Override public List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String name) throws IOException { if (!"xml".equals(FilesKt.getExtension(file)) || contents == null) { return Collections.emptyList(); } DOMDocument document = DOMParser.getInstance().parse(contents, file.toURI().toString(), null); DOMUtils.setNamespace(document, namespace); List<DOMNode> roots = document.getRoots(); for (DOMNode root : roots) { if (root instanceof DOMProcessingInstruction) { continue; } if (SdkConstants.TAG_RESOURCES.equals(root.getNodeName())) { return parseResourceTag(root, namespace, name); } } return Collections.emptyList(); } private List<ResourceValue> parseResourceTag( DOMNode root, ResourceNamespace namespace, String name) { List<DOMNode> children = root.getChildren(); if (children == null) { return Collections.emptyList(); } List<ResourceValue> resourceValues = new ArrayList<>(); for (DOMNode child : children) { ResourceType type = ResourceType.fromXmlTag(child); if (type == null) { continue; } ResourceValue value = parseType(type, child, namespace, name); if (value != null) { resourceValues.add(value); } } return resourceValues; } private ResourceValue parseType( ResourceType resourceType, DOMNode child, ResourceNamespace namespace, String name) { switch (resourceType) { case COLOR: return parseColor(child, namespace, name); case STRING: return parseString(child, namespace, name); case BOOL: return parseBoolean(child, namespace, name); case INTEGER: return parseInteger(child, namespace, name); case STYLE: return parseStyle(child, namespace, name); case STYLEABLE: return parseStyleable(child, namespace, name); case ATTR: return parseAttrResourceValue(child, namespace, name); case PUBLIC: return parsePublic(child, namespace, name); case ID: return parseId(child, namespace, name); default: return null; } } @Nullable private ResourceValue parseId(DOMNode child, ResourceNamespace namespace, String libraryName) { String name = child.getAttribute("name"); if (name == null) { return null; } ResourceReference resourceReference = new ResourceReference(namespace, ResourceType.ID, name); return new ResourceValueImpl(resourceReference, null, libraryName); } @Nullable private ResourceValue parsePublic( DOMNode child, ResourceNamespace namespace, String libraryName) { String type = child.getAttribute("type"); if (type == null) { return null; } ResourceType resourceType = ResourceType.fromXmlTagName(type); if (resourceType == null) { return null; } String name = child.getAttribute("name"); if (name == null) { return null; } ResourceReference resourceReference = new ResourceReference(namespace, ResourceType.PUBLIC, name); return new ResourceValueImpl(resourceReference, null, libraryName); } @Nullable private ResourceValue parseColor(DOMNode child, ResourceNamespace namespace, String libraryName) { String name = child.getAttribute("name"); if (name == null) { return null; } DOMNode firstChild = child.getFirstChild(); if (firstChild == null) { return null; } if (!firstChild.isText()) { return null; } String value = firstChild.getTextContent(); ResourceReference reference = new ResourceReference(namespace, ResourceType.COLOR, name); return new ResourceValueImpl(reference, value, libraryName); } @Nullable private ResourceValue parseString(DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } DOMNode firstChild = node.getFirstChild(); if (firstChild == null) { return null; } if (!firstChild.isText()) { return null; } String value = firstChild.getTextContent(); ResourceReference reference = new ResourceReference(namespace, ResourceType.STRING, name); return new ResourceValueImpl(reference, value, libraryName); } @Nullable private ResourceValue parseBoolean( DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } DOMNode firstChild = node.getFirstChild(); if (firstChild == null) { return null; } if (!firstChild.isText()) { return null; } String value = firstChild.getTextContent(); ResourceReference reference = new ResourceReference(namespace, ResourceType.BOOL, name); return new ResourceValueImpl(reference, value, libraryName); } @Nullable private ResourceValue parseInteger( DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } DOMNode firstChild = node.getFirstChild(); if (firstChild == null) { return null; } if (!firstChild.isText()) { return null; } String value = firstChild.getTextContent(); ResourceReference reference = new ResourceReference(namespace, ResourceType.INTEGER, name); return new ResourceValueImpl(reference, value, libraryName); } @Nullable private ResourceValue parseStyle(DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } String parent = node.getAttribute("parent"); StyleResourceValueImpl styleResource = new StyleResourceValueImpl(namespace, name, parent, libraryName); List<DOMNode> children = node.getChildren(); if (children == null) { return styleResource; } for (DOMNode child : children) { String nodeName = child.getNodeName(); if (!SdkConstants.TAG_ITEM.equals(nodeName)) { continue; } StyleItemResourceValue item = parseStyleItem(child, namespace, libraryName); if (item != null) { styleResource.addItem(item); } } return styleResource; } @Nullable private StyleItemResourceValue parseStyleItem( DOMNode node, ResourceNamespace namespace, String libraryName) { String attributeName = node.getAttribute("name"); if (attributeName == null) { return null; } DOMNode firstChild = node.getFirstChild(); if (firstChild == null || !firstChild.isText()) { return null; } String value = firstChild.getTextContent(); return new StyleItemResourceValueImpl(namespace, attributeName, value, libraryName); } @Nullable private StyleableResourceValue parseStyleable( DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } StyleableResourceValueImpl resourceValue = new StyleableResourceValueImpl(namespace, name, null, null); List<DOMNode> children = node.getChildren(); if (children == null) { return resourceValue; } for (DOMNode child : children) { ResourceType type = ResourceType.fromXmlTag(child); if (ResourceType.ATTR.equals(type)) { AttrResourceValue attr = parseAttrResourceValue(child, namespace, libraryName); if (attr != null) { resourceValue.addValue(attr); } } } return resourceValue; } @Nullable private AttrResourceValue parseAttrResourceValue( DOMNode node, ResourceNamespace namespace, String libraryName) { String name = node.getAttribute("name"); if (name == null) { return null; } AttrResourceValueImpl resourceValue = new AttrResourceValueImpl(namespace, name, libraryName); String format = node.getAttribute("format"); if (format != null) { Set<AttributeFormat> parse = AttributeFormat.parse(format); resourceValue.setFormats(parse); } List<DOMNode> children = node.getChildren(); boolean hasEnum = false; boolean hasFlag = false; if (children != null) { for (DOMNode child : children) { String nodeName = child.getNodeName(); if (nodeName == null) { continue; } if (SdkConstants.TAG_FLAG.equals(nodeName)) { hasFlag = true; } else if (SdkConstants.TAG_ENUM.equals(nodeName)) { hasEnum = true; } else { hasFlag = false; hasEnum = false; continue; } String attributeName = child.getAttribute("name"); if (attributeName == null) { continue; } String value = child.getAttribute("value"); if (value == null) { continue; } Integer integer = Ints.tryParse(value); String description = null; DOMNode previous = child.getPreviousSibling(); if (previous != null && previous.isComment()) { DOMComment comment = (DOMComment) previous; description = comment.getTextContent(); } resourceValue.addValue(attributeName, integer, description); } } if (hasEnum && !resourceValue.getFormats().contains(AttributeFormat.ENUM)) { ImmutableSet<AttributeFormat> build = ImmutableSet.<AttributeFormat>builder() .addAll(resourceValue.getFormats()) .add(AttributeFormat.ENUM) .build(); resourceValue.setFormats(build); } else if (hasFlag && !resourceValue.getFormats().contains(AttributeFormat.FLAGS)) { ImmutableSet<AttributeFormat> build = ImmutableSet.<AttributeFormat>builder() .addAll(resourceValue.getFormats()) .add(AttributeFormat.FLAGS) .build(); resourceValue.setFormats(build); } return resourceValue; } }
11,872
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/parser/ResourceParser.java
package com.tyron.xml.completion.repository.parser; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceValue; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.FileUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface ResourceParser { default List<ResourceValue> parse( @NotNull File file, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException { String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8); return parse(file, contents, namespace, libraryName); } List<ResourceValue> parse( @NotNull File file, @Nullable String contents, @NotNull ResourceNamespace namespace, @Nullable String libraryName) throws IOException; }
953
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TextResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/TextResourceValue.java
package com.tyron.xml.completion.repository.api; /** A {@link ResourceValue} intended for text nodes where we need access to the raw XML text. */ public interface TextResourceValue extends ResourceValue {}
207
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/LayoutResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LayoutResourceValueImpl extends ResourceValueImpl implements LayoutResourceValue { private final LayoutInfo mRoot; public LayoutResourceValueImpl( @NotNull ResourceReference reference, @Nullable String value, @Nullable String libraryName, @Nullable LayoutInfo root) { super(reference, value, libraryName); mRoot = root; } @Nullable @Override public LayoutInfo getRoot() { return mRoot; } }
593
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceNamespace.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ResourceNamespace.java
package com.tyron.xml.completion.repository.api; import com.google.common.base.Strings; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.tyron.builder.compiler.manifest.SdkConstants; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; import java.util.logging.Logger; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents a namespace used by aapt when processing resources. * * <p>In "traditional" projects, all resources from local sources and AARs live in the {@link * #RES_AUTO} namespace and are processed together by aapt. Framework resources belong in the * "android" package name / namespace. * * <p>In namespace-aware projects, every module and AAR contains resources in a separate namespace * that is read from the manifest and corresponds to the {@code package-name}. Framework resources * are treated as before. * * <p>The tools namespace is a special case and is only used by sample data, so it never reaches the * aapt stage. * * <p>This class is serializable to allow passing between Gradle workers. */ public class ResourceNamespace implements Comparable<ResourceNamespace>, Serializable { public static final ResourceNamespace ANDROID = new ResourceNamespace(SdkConstants.ANDROID_URI, SdkConstants.ANDROID_NS_NAME); public static final ResourceNamespace RES_AUTO = new ResAutoNamespace(); public static final ResourceNamespace TOOLS = new ToolsNamespace(); public static final ResourceNamespace AAPT = new AaptNamespace(); /** The namespace of the Androidx appcompat library when namespaces are used. */ public static final ResourceNamespace APPCOMPAT = fromPackageName("androidx.appcompat"); /** The namespace of the old appcompat library when namespaces are used. */ public static final ResourceNamespace APPCOMPAT_LEGACY = fromPackageName("android.support.v7.appcompat"); private static final Logger LOG = Logger.getLogger(ResourceNamespace.class.getSimpleName()); @SuppressWarnings("StaticNonFinalField") // Non-final to be able to set in code. public static boolean noncomplianceLogging = false; /** * Namespace used in code that needs to start keeping track of namespaces. For easy tracking of * parts of codebase that need fixing. */ @NotNull public static ResourceNamespace TODO() { if (noncomplianceLogging) { String trace = Arrays.stream(Thread.currentThread().getStackTrace()) .map(Object::toString) .collect(Collectors.joining("\n")); LOG.warning("This code does not support namespaces yet\n" + trace); } return RES_AUTO; } /** * Logic for looking up namespace prefixes defined in some context. * * @see ResourceNamespace#fromNamespacePrefix(String, ResourceNamespace, Resolver) */ public interface Resolver { /** Returns the full URI of an XML namespace for a given prefix, if defined. */ @Nullable String prefixToUri(@NotNull String namespacePrefix); @Nullable default String uriToPrefix(@NotNull String namespaceUri) { // TODO(namespaces): remove the default implementation once layoutlib provides one. return null; } Resolver EMPTY_RESOLVER = new Resolver() { @Nullable @Override public String uriToPrefix(@NotNull String namespaceUri) { return null; } @Nullable @Override public String prefixToUri(@NotNull String namespacePrefix) { return null; } }; /** * Contains a single mapping from "tools" to the tools URI. In the past we assumed the "tools:" * prefix is defined, we need to keep doing this for projects that don't care about namespaces. */ Resolver TOOLS_ONLY = fromBiMap(ImmutableBiMap.of(SdkConstants.TOOLS_NS_NAME, SdkConstants.TOOLS_URI)); /** * Creates a new {@link Resolver} which looks up prefix definitions in the given {@link BiMap}. * * @param prefixes a {@link BiMap} mapping prefix strings to full namespace URIs */ @NotNull static Resolver fromBiMap(@NotNull BiMap<String, String> prefixes) { return new Resolver() { @Nullable @Override public String uriToPrefix(@NotNull String namespaceUri) { return prefixes.inverse().get(namespaceUri); } @Nullable @Override public String prefixToUri(@NotNull String namespacePrefix) { return prefixes.get(namespacePrefix); } }; } } @NotNull private final String uri; @Nullable private final String packageName; /** * Constructs a {@link ResourceNamespace} for the given (fully qualified) aapt package name. Note * that this is not the string used in XML notation before the colon (at least not in the general * case), which can be an alias. * * <p>This factory method can be used when reading the build system model or for testing, other * code most likely needs to resolve the short namespace prefix against XML namespaces defined in * the given context. * * @see #fromNamespacePrefix(String, ResourceNamespace, Resolver) */ @NotNull public static ResourceNamespace fromPackageName(@NotNull String packageName) { assert !Strings.isNullOrEmpty(packageName); if (packageName.equals(SdkConstants.ANDROID_NS_NAME)) { // Make sure ANDROID is a singleton, so we can use object identity to check for it. return ANDROID; } else { return new ResourceNamespace(SdkConstants.URI_PREFIX + packageName, packageName); } } /** * Constructs a {@link ResourceNamespace} in code that does not keep track of namespaces yet, only * of the boolean `isFramework` flag. */ @NotNull @Deprecated public static ResourceNamespace fromBoolean(boolean isFramework) { return isFramework ? ANDROID : TODO(); } /** * Tries to build a {@link ResourceNamespace} from the first part of a {@link ResourceUrl}, given * the context in which the string was used. * * @param prefix the string to resolve * @param defaultNamespace namespace in which this prefix was used. If no prefix is used (it's * null), this is the namespace that will be returned. For example, if an XML file inside libA * (com.lib.a) references "@string/foo", it means the "foo" resource from libA, so the * "com.lib.a" namespace should be passed as the {@code defaultNamespace}. * @param resolver strategy for mapping short namespace prefixes to namespace URIs as used in XML * resource files. This should be provided by the XML parser used. For example, if the source * XML document contained snippet such as {@code * xmlns:foo="http://schemas.android.com/apk/res/com.foo"}, it should return {@code * "http://schemas.android.com/apk/res/com.foo"} when applied to argument {@code "foo"}. * @see ResourceUrl#namespace */ @Nullable public static ResourceNamespace fromNamespacePrefix( @Nullable String prefix, @NotNull ResourceNamespace defaultNamespace, @NotNull Resolver resolver) { if (Strings.isNullOrEmpty(prefix)) { return defaultNamespace; } String uri = resolver.prefixToUri(prefix); if (uri != null) { return fromNamespaceUri(uri); } else { // TODO(namespaces): What is considered a good package name by aapt? return fromPackageName(prefix); } } /** * Constructs a {@link ResourceNamespace} for the given URI, as used in XML resource files. * * <p>This methods returns null if we don't recognize the URI. */ @Nullable public static ResourceNamespace fromNamespaceUri(@NotNull String uri) { if (uri.equals(SdkConstants.ANDROID_URI)) { return ANDROID; } if (uri.equals(SdkConstants.AUTO_URI)) { return RES_AUTO; } if (uri.equals(SdkConstants.TOOLS_URI)) { return TOOLS; } if (uri.equals(SdkConstants.AAPT_URI)) { return AAPT; } if (uri.startsWith(SdkConstants.URI_PREFIX)) { // TODO(namespaces): What is considered a good package name by aapt? String packageName = uri.substring(SdkConstants.URI_PREFIX.length()); if (!packageName.isEmpty()) { return fromPackageName(packageName); } } // The prefix is mapped to a string/URL we don't understand. return null; } private ResourceNamespace(@NotNull String uri, @Nullable String packageName) { this.uri = uri; this.packageName = packageName; } /** * Returns the package associated with this namespace, or null in the case of {@link #RES_AUTO}. * * <p>The result value can be used as the namespace part of a {@link * com.android.resources.ResourceUrl}. */ @Nullable public String getPackageName() { return packageName; } @NotNull public String getXmlNamespaceUri() { return uri; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceNamespace that = (ResourceNamespace) o; return Objects.equals(packageName, that.packageName); } @NotNull public Object readResolve() { switch (uri) { case SdkConstants.ANDROID_URI: return ANDROID; case SdkConstants.AUTO_URI: return RES_AUTO; case SdkConstants.TOOLS_URI: return TOOLS; case SdkConstants.AAPT_URI: return AAPT; default: return this; } } @Override public int hashCode() { return uri.hashCode(); } @Override public String toString() { return uri.substring(SdkConstants.URI_DOMAIN_PREFIX.length()); } @Override public int compareTo(@NotNull ResourceNamespace other) { return uri.compareTo(other.uri); } private static class ResAutoNamespace extends ResourceNamespace { private ResAutoNamespace() { super(SdkConstants.AUTO_URI, null); } } private static class ToolsNamespace extends ResourceNamespace { private ToolsNamespace() { super(SdkConstants.TOOLS_URI, null); } } private static class AaptNamespace extends ResourceNamespace { private AaptNamespace() { super(SdkConstants.AAPT_URI, null); } } }
10,410
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceReference.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ResourceReference.java
package com.tyron.xml.completion.repository.api; import com.google.common.base.MoreObjects; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.io.Serializable; import java.util.Objects; import javax.annotation.concurrent.Immutable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A resource reference, contains the namespace, type and name. Can be used to look for resources in * a resource repository. * * <p>This is an immutable class. */ @Immutable public final class ResourceReference implements Comparable<ResourceReference>, Serializable { @NotNull private final ResourceType resourceType; @NotNull private final ResourceNamespace namespace; @NotNull private final String name; /** * Initializes a ResourceReference. * * @param namespace the namespace of the resource * @param resourceType the type of the resource * @param name the name of the resource, should not be qualified */ public ResourceReference( @NotNull ResourceNamespace namespace, @NotNull ResourceType resourceType, @NotNull String name) { assert resourceType == ResourceType.SAMPLE_DATA || name.indexOf(':') < 0 : "Qualified name is not allowed: " + name; this.namespace = namespace; this.resourceType = resourceType; this.name = name; } /** A shorthand for creating a {@link ResourceType#ATTR} resource reference. */ public static ResourceReference attr(@NotNull ResourceNamespace namespace, @NotNull String name) { return new ResourceReference(namespace, ResourceType.ATTR, name); } /** A shorthand for creating a {@link ResourceType#STYLE} resource reference. */ public static ResourceReference style( @NotNull ResourceNamespace namespace, @NotNull String name) { return new ResourceReference(namespace, ResourceType.STYLE, name); } /** A shorthand for creating a {@link ResourceType#STYLEABLE} resource reference. */ public static ResourceReference styleable( @NotNull ResourceNamespace namespace, @NotNull String name) { return new ResourceReference(namespace, ResourceType.STYLEABLE, name); } /** Returns the name of the resource, as defined in the XML. */ @NotNull public String getName() { return name; } /** * If the package name of the namespace is not null, returns the name of the resource prefixed by * the package name with a colon separator. Otherwise returns the name of the resource. */ public String getQualifiedName() { String packageName = namespace.getPackageName(); return packageName == null ? name : packageName + ':' + name; } @NotNull public ResourceType getResourceType() { return resourceType; } @NotNull public ResourceNamespace getNamespace() { return namespace; } /** * Returns whether the resource is a framework resource ({@code true}) or a project resource * ({@code false}). * * @deprecated all namespaces should be handled not just "android:". */ @Deprecated public final boolean isFramework() { return ResourceNamespace.ANDROID.equals(namespace); } @NotNull public ResourceUrl getResourceUrl() { return ResourceUrl.create(namespace.getPackageName(), resourceType, name); } /** * Returns a {@link ResourceUrl} that can be used to refer to this resource from the given * namespace. This means the namespace part of the {@link ResourceUrl} will be null if the context * namespace is the same as the namespace of this resource. * * <p>This method assumes no namespace prefixes (aliases) are defined, so the returned {@link * ResourceUrl} will use the full package name of the target namespace, if necessary. Most use * cases should attempt to call the overloaded method instead and provide a {@link * ResourceNamespace.Resolver} from the XML element where the {@link ResourceUrl} will be used. * * @see #getRelativeResourceUrl(ResourceNamespace, ResourceNamespace.Resolver) */ @NotNull public ResourceUrl getRelativeResourceUrl(@NotNull ResourceNamespace context) { return getRelativeResourceUrl(context, ResourceNamespace.Resolver.EMPTY_RESOLVER); } /** * Returns a {@link ResourceUrl} that can be used to refer to this resource from the given * namespace. This means the namespace part of the {@link ResourceUrl} will be null if the context * namespace is the same as the namespace of this resource. * * <p>This method uses the provided {@link ResourceNamespace.Resolver} to find the short prefix * that can be used to refer to the target namespace. If it is not found, the full package name is * used. */ @NotNull public ResourceUrl getRelativeResourceUrl( @NotNull ResourceNamespace context, @NotNull ResourceNamespace.Resolver resolver) { String namespaceString; if (namespace.equals(context)) { namespaceString = null; } else { String prefix = resolver.uriToPrefix(namespace.getXmlNamespaceUri()); if (prefix != null) { namespaceString = prefix; } else { namespaceString = namespace.getPackageName(); } } return ResourceUrl.create(namespaceString, resourceType, name); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; ResourceReference reference = (ResourceReference) obj; if (resourceType != reference.resourceType) return false; if (!namespace.equals(reference.namespace)) return false; if (!name.equals(reference.name)) return false; return true; } @Override public int hashCode() { return Objects.hash(resourceType, namespace, name); } @Override public int compareTo(@NotNull ResourceReference other) { int diff = resourceType.compareTo(other.resourceType); if (diff != 0) { return diff; } diff = namespace.compareTo(other.namespace); if (diff != 0) { return diff; } return name.compareTo(other.name); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("namespace", namespace) .add("type", resourceType) .add("name", name) .toString(); } }
6,276
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttrResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/AttrResourceValue.java
package com.tyron.xml.completion.repository.api; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A resource value representing an attr resource. * * <p>The {@link #getValue()} method of this class always returns null. To get the numeric values * associated with flags or enums use {@link #getAttributeValues()}. */ public interface AttrResourceValue extends ResourceValue { /** * Returns the enum or flag integer values keyed by the value names. Some of the values in the * returned map may be null. The returned map is guaranteed to contain the names of all declared * values, even the ones that don't have corresponding numeric values. * * @return the map of (name, integer) values */ @NotNull Map<String, Integer> getAttributeValues(); /** Returns the description of a enum/flag value with the given name. */ @Nullable String getValueDescription(@NotNull String valueName); /** * Returns the description of the attr resource obtained from an XML comment. * * @return the description, or null if there was no comment for this attr in XML */ @Nullable String getDescription(); /** * Returns the name of the attr group obtained from an XML comment. For example, the following XML * will produce "textAppearance" attr resource with the group name "Text styles": * * <pre> * &lt;!-- =========== --> * &lt;!-- Text styles --> * &lt;!-- =========== --> * &lt;eat-comment /&gt; * * &lt;!-- Default appearance of text: color, typeface, size, and style. --> * &lt;attr name="textAppearance" format="reference" /&gt; * </pre> * * <p>Attr grouping is available only for the framework resources. * * @return the group name, or null no grouping information is available */ @Nullable String getGroupName(); /** Returns the formats allowed for the values of the attribute. */ @NotNull Set<AttributeFormat> getFormats(); }
2,030
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TextResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/TextResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** A {@link ResourceValue} intended for text nodes where we need access to the raw XML text. */ public class TextResourceValueImpl extends ResourceValueImpl implements TextResourceValue { @Nullable private String rawXmlValue; public TextResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String name, @Nullable String textValue, @Nullable String rawXmlValue, @Nullable String libraryName) { super(namespace, ResourceType.STRING, name, textValue, libraryName); this.rawXmlValue = rawXmlValue; } public TextResourceValueImpl( @NotNull ResourceReference reference, @Nullable String textValue, @Nullable String rawXmlValue, @Nullable String libraryName) { super(reference, textValue, libraryName); this.rawXmlValue = rawXmlValue; assert reference.getResourceType() == ResourceType.STRING; } @Override @Nullable public String getRawXmlValue() { if (rawXmlValue != null) { return rawXmlValue; } return super.getValue(); } /** * Sets the raw XML text. * * @param value the text to set * @see #getRawXmlValue() */ public void setRawXmlValue(@Nullable String value) { rawXmlValue = value; } @Override public int hashCode() { return Objects.hash(super.hashCode(), rawXmlValue); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; TextResourceValueImpl other = (TextResourceValueImpl) obj; return Objects.equals(rawXmlValue, other.rawXmlValue); } }
1,830
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
RenderResources.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/RenderResources.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.SdkConstants; public class RenderResources { public static final String REFERENCE_NULL = SdkConstants.NULL_RESOURCE; public static final String REFERENCE_EMPTY = "@empty"; public static final String REFERENCE_UNDEFINED = "@undefined"; }
337
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttrResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/AttrResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** A resource value representing an attr resource. */ public class AttrResourceValueImpl extends ResourceValueImpl implements AttrResourceValue { /** The keys are enum or flag names, the values are corresponding numeric values. */ @Nullable private Map<String, Integer> valueMap; /** The keys are enum or flag names, the values are the value descriptions. */ @Nullable private Map<String, String> valueDescriptionMap; @Nullable private String description; @Nullable private String groupName; @NotNull private Set<AttributeFormat> formats = EnumSet.noneOf(AttributeFormat.class); public AttrResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String name, @Nullable String libraryName) { super(namespace, ResourceType.ATTR, name, null, libraryName); } public AttrResourceValueImpl(@NotNull ResourceReference reference, @Nullable String libraryName) { super(reference, null, libraryName); } @Override @NotNull public Map<String, Integer> getAttributeValues() { return valueMap == null ? Collections.emptyMap() : valueMap; } @Override @Nullable public String getValueDescription(@NotNull String valueName) { return valueDescriptionMap == null ? null : valueDescriptionMap.get(valueName); } @Override @Nullable public String getDescription() { return description; } @Override @Nullable public String getGroupName() { return groupName; } @Override @NotNull public Set<AttributeFormat> getFormats() { return formats; } /** * Adds a possible value of the flag or enum attribute. * * @param valueName the name of the value * @param numericValue the corresponding numeric value * @param valueName the description of the value */ public void addValue( @NotNull String valueName, @Nullable Integer numericValue, @Nullable String description) { if (valueMap == null) { valueMap = new LinkedHashMap<>(); } valueMap.put(valueName, numericValue); if (description != null) { if (valueDescriptionMap == null) { valueDescriptionMap = new HashMap<>(); } valueDescriptionMap.put(valueName, description); } } /** * Sets the description of the attr resource. * * @param description the description to set */ public void setDescription(@Nullable String description) { this.description = description; } /** * Sets the name of group the attr resource belongs to. * * @param groupName the name of the group to set */ public void setGroupName(@Nullable String groupName) { this.groupName = groupName; } /** * Sets the formats allowed for the attribute. * * @param formats the formats to set */ public void setFormats(@NotNull Collection<AttributeFormat> formats) { this.formats = EnumSet.copyOf(formats); } }
3,247
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleItemResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleItemResourceValue.java
package com.tyron.xml.completion.repository.api; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface StyleItemResourceValue extends ResourceValue { /** * Returns contents of the {@code name} XML attribute that defined this style item. This is * supposed to be a reference to an {@code attr} resource. */ @NotNull String getAttrName(); /** * Returns a {@link ResourceReference} to the {@code attr} resource this item is defined for, if * the name was specified using the correct syntax. */ @Nullable ResourceReference getAttr(); /** * Returns just the name part of the attribute being referenced, for backwards compatibility with * layoutlib. Don't call this method, the item may be in a different namespace than the attribute * and the value being referenced, use {@link #getAttr()} instead. * * @deprecated Use {@link #getAttr()} instead. */ @Deprecated @Override @NotNull String getName(); }
1,006
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ResourceValue.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.io.Serializable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** Represents an Android resource with a name and a string value. */ public interface ResourceValue extends Serializable { default boolean isPublic() { return true; } @NotNull ResourceType getResourceType(); @NotNull ResourceNamespace getNamespace(); @NotNull String getName(); /** * Returns the name of the library where this resource was found or null if it is not from a * library. */ @Nullable String getLibraryName(); /** Returns true if the resource is user defined. */ boolean isUserDefined(); boolean isFramework(); /** * Returns the value of the resource, as defined in the XML. This can be null, for example for * instances of {@link StyleResourceValue}. */ @Nullable String getValue(); @NotNull ResourceReference asReference(); @NotNull default ResourceUrl getResourceUrl() { return asReference().getResourceUrl(); } /** * If this {@link ResourceValue} references another one, returns a {@link ResourceReference} to * it, otherwise null. * * <p>This method should be called before inspecting the textual value ({@link #getValue}), as it * handles namespaces correctly. */ @Nullable default ResourceReference getReference() { String value = getValue(); if (value == null) { return null; } ResourceUrl url = ResourceUrl.parse(value); if (url == null) { return null; } return url.resolve(getNamespace(), getNamespaceResolver()); } /** * Similar to {@link #getValue}, but returns the raw XML value. This is <b>usually</b> the same as * {@link #getValue}, but with a few exceptions. For example, for markup strings, you can have * {@code <string name="markup">This is <b>bold</b></string>}. Here, {@link #getValue} will return * "{@code This is bold}" -- e.g. just the plain text flattened. However, this method will return * "{@code This is <b>bold</b>}", which preserves the XML markup elements. */ @Nullable default String getRawXmlValue() { return getValue(); } /** * Sets the value of the resource. * * @param value the new value */ void setValue(@Nullable String value); /** * Returns the namespace resolver that can be used to resolve any name prefixes in the string * values associated with this resource. */ @NotNull ResourceNamespace.Resolver getNamespaceResolver(); }
2,631
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutInfo.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/LayoutInfo.java
package com.tyron.xml.completion.repository.api; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import kotlin.Pair; import org.jetbrains.annotations.Nullable; public class LayoutInfo { private String mName; private List<Pair<String, String>> mAttributes; private List<LayoutInfo> mChildren; public LayoutInfo() {} public LayoutInfo(String tag) { mName = tag; } /** * Return the name of this layout, this name is the xml tag and will be used to load the view * class */ public String getName() { return mName; } public ImmutableList<Pair<String, String>> getAttributes() { return ImmutableList.copyOf(mAttributes); } /** Return the child layout infos of this view, may return null if the view is not a ViewGroup */ @Nullable public ImmutableList<LayoutInfo> getChildren() { return ImmutableList.copyOf(mChildren); } public void addAttribute(String name, String value) { if (mAttributes == null) { mAttributes = new ArrayList<>(); } mAttributes.add(new Pair<>(name, value)); } public void addChild(LayoutInfo child) { if (mChildren == null) { mChildren = new ArrayList<>(); } mChildren.add(child); } }
1,263
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleableResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleableResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** A resource value representing a declare-styleable resource. */ public class StyleableResourceValueImpl extends ResourceValueImpl implements StyleableResourceValue { @NotNull private final List<AttrResourceValue> attrs = new ArrayList<>(); public StyleableResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String name, @Nullable String value, @Nullable String libraryName) { super(namespace, ResourceType.STYLEABLE, name, value, libraryName); } public StyleableResourceValueImpl( @NotNull ResourceReference reference, @Nullable String value, @Nullable String libraryName) { super(reference, value, libraryName); assert reference.getResourceType() == ResourceType.STYLEABLE; } @Override @NotNull public List<AttrResourceValue> getAllAttributes() { return attrs; } public void addValue(@NotNull AttrResourceValue attr) { assert attr.isFramework() || !isFramework() : "Can't add non-framework attributes to framework resource."; attrs.add(attr); } }
1,312
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleableResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleableResourceValue.java
package com.tyron.xml.completion.repository.api; import java.util.List; import org.jetbrains.annotations.NotNull; /** * A resource value representing a declare-styleable resource. * * <p>{@link #getValue()} will return null, instead use {@link #getAllAttributes()} to get the list * of attributes defined in the declare-styleable. */ public interface StyleableResourceValue extends ResourceValue { @NotNull List<AttrResourceValue> getAllAttributes(); }
464
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.google.common.base.MoreObjects; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** Simple implementation of the {@link ResourceValue} interface. */ public class ResourceValueImpl implements ResourceValue { @NotNull private final ResourceType resourceType; @NotNull private final ResourceNamespace namespace; @NotNull private final String name; @Nullable private final String libraryName; @Nullable private String value; @NotNull protected transient ResourceNamespace.Resolver mNamespaceResolver = ResourceNamespace.Resolver.EMPTY_RESOLVER; public ResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull ResourceType type, @NotNull String name, @Nullable String value, @Nullable String libraryName) { this.namespace = namespace; this.resourceType = type; this.name = name; this.value = value; this.libraryName = libraryName; } public ResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull ResourceType type, @NotNull String name, @Nullable String value) { this(namespace, type, name, value, null); } public ResourceValueImpl( @NotNull ResourceReference reference, @Nullable String value, @Nullable String libraryName) { this( reference.getNamespace(), reference.getResourceType(), reference.getName(), value, libraryName); } public ResourceValueImpl(@NotNull ResourceReference reference, @Nullable String value) { this(reference, value, null); } @Override @NotNull public final ResourceType getResourceType() { return resourceType; } @Override @NotNull public final ResourceNamespace getNamespace() { return namespace; } @Override @NotNull public String getName() { return name; } @Override @Nullable public final String getLibraryName() { return libraryName; } @Override public boolean isUserDefined() { // TODO: namespaces return !isFramework() && libraryName == null; } @Override public boolean isFramework() { // When transferring this across the wire, the instance check won't be correct. return ResourceNamespace.ANDROID.equals(namespace); } @Override @Nullable public String getValue() { return value; } @Override @NotNull public ResourceReference asReference() { return new ResourceReference(namespace, resourceType, name); } /** * Sets the value of the resource. * * @param value the new value */ @Override public void setValue(@Nullable String value) { this.value = value; } /** * Sets the value from another resource. * * @param value the resource value */ public void replaceWith(@NotNull ResourceValue value) { this.value = value.getValue(); } @Override @NotNull public ResourceNamespace.Resolver getNamespaceResolver() { return mNamespaceResolver; } /** * Specifies logic used to resolve namespace aliases for values that come from XML files. * * <p>This method is meant to be called by the XML parser that created this {@link ResourceValue}. */ public void setNamespaceResolver(@NotNull ResourceNamespace.Resolver resolver) { this.mNamespaceResolver = resolver; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceValueImpl that = (ResourceValueImpl) o; return resourceType == that.getResourceType() && Objects.equals(namespace, that.namespace) && Objects.equals(name, that.name) && Objects.equals(libraryName, that.libraryName) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(resourceType, namespace, name, libraryName, value); } @Override @NotNull public String toString() { return MoreObjects.toStringHelper(this) .add("namespace", getNamespace()) .add("type", getResourceType()) .add("name", getName()) .add("value", getValue()) .toString(); } }
4,336
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DensityBasedResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/DensityBasedResourceValue.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.Density; import com.tyron.builder.compiler.manifest.resources.ResourceType; import org.jetbrains.annotations.NotNull; /** Represents an Android resource value associated with a particular screen density. */ public interface DensityBasedResourceValue extends ResourceValue { /** Returns the density for which this resource is configured. */ @NotNull Density getResourceDensity(); /** * Checks if resources of the given resource type should be created as density based when they * belong to a folder with a density qualifier. */ static boolean isDensityBasedResourceType(@NotNull ResourceType resourceType) { // It is not clear why only drawables and mipmaps are treated as density dependent. // This logic has been moved from ResourceMergerItem.getResourceValue. return resourceType == ResourceType.DRAWABLE || resourceType == ResourceType.MIPMAP; } }
989
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ArrayResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ArrayResourceValue.java
package com.tyron.xml.completion.repository.api; import org.jetbrains.annotations.NotNull; /** * Represents an Android array resource with a name and a list of children {@link ResourceValue} * items, one for array element. */ public interface ArrayResourceValue extends ResourceValue, Iterable<String> { /** * Returns the number of elements in this array. * * @return the element count */ int getElementCount(); /** * Returns the array element value at the given index position. * * @param index index, which must be in the range [0..getElementCount()]. * @return the corresponding element */ @NotNull String getElement(int index); }
677
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleResourceValue.java
package com.tyron.xml.completion.repository.api; import java.util.Collection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an Android style resource with a name and a list of children {@link ResourceValue}. */ public interface StyleResourceValue extends ResourceValue { /** * Returns value of the {@code parent} XML attribute of this style. Unlike {@link * #getParentStyle()}, does not try to determine the name of the parent style by removing the last * component of the name of this style. */ @Nullable String getParentStyleName(); /** * Returns a reference to the parent style, if it can be determined based on the explicit parent * reference in XML, or by using the part of the name of this style before the last dot. * * <p>Note that names of styles have more meaning than other resources: if the parent attribute is * not set, aapt looks for a dot in the style name and treats the string up to the last dot as the * name of a parent style. So {@code <style name="Foo.Bar.Baz">} has an implicit parent called * {@code Foo.Bar}. Setting the {@code parent} XML attribute disables this feature, even if it's * set to an empty string. See {@code ResourceParser::ParseStyle} in aapt for details. */ @Nullable default ResourceReference getParentStyle() { String parentStyleName = getParentStyleName(); if (parentStyleName != null) { ResourceUrl url = ResourceUrl.parseStyleParentReference(parentStyleName); if (url == null) { return null; } return url.resolve(getNamespace(), getNamespaceResolver()); } String styleName = getName(); int lastDot = styleName.lastIndexOf('.'); if (lastDot >= 0) { String parent = styleName.substring(0, lastDot); if (parent.isEmpty()) { return null; } return ResourceReference.style(getNamespace(), parent); } return null; } static boolean isDefaultParentStyleName( @NotNull String parentStyleName, @NotNull String styleName) { return styleName.lastIndexOf('.') == parentStyleName.length() && styleName.startsWith(parentStyleName); } /** * Finds the item for the given qualified attr name in this style (if it's defined in this style). */ @Nullable StyleItemResourceValue getItem(@NotNull ResourceNamespace namespace, @NotNull String name); /** Finds the item for the given attr in this style (if it's defined in this style). */ @Nullable StyleItemResourceValue getItem(@NotNull ResourceReference attr); /** * Returns a list of all items defined in this Style. This doesn't return items inherited from the * parent. */ @NotNull Collection<StyleItemResourceValue> getDefinedItems(); }
2,788
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DensityBasedResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/DensityBasedResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.Density; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class DensityBasedResourceValueImpl extends ResourceValueImpl implements DensityBasedResourceValue { @NotNull private final Density density; public DensityBasedResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull ResourceType type, @NotNull String name, @Nullable String value, @NotNull Density density, @Nullable String libraryName) { super(namespace, type, name, value, libraryName); this.density = density; } public DensityBasedResourceValueImpl( @NotNull ResourceReference reference, @Nullable String value, @NotNull Density density) { super(reference, value); this.density = density; } @Override @NotNull public final Density getResourceDensity() { return density; } @Override @NotNull public String toString() { return "DensityBasedResourceValue [" + getResourceType() + "/" + getName() + " = " + getValue() + " (density:" + density + ", framework:" + isFramework() + ")]"; } @Override public int hashCode() { return Objects.hash(super.hashCode(), density); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; DensityBasedResourceValueImpl other = (DensityBasedResourceValueImpl) obj; return Objects.equals(density, other.density); } }
1,793
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ArrayResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ArrayResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an Android array resource with a name and a list of children {@link ResourceValue} * items, one for array element. */ public class ArrayResourceValueImpl extends ResourceValueImpl implements ArrayResourceValue { @NotNull private final List<String> elements = new ArrayList<>(); public ArrayResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String name, @Nullable String libraryName) { super(namespace, ResourceType.ARRAY, name, null, libraryName); } public ArrayResourceValueImpl( @NotNull ResourceReference reference, @Nullable String libraryName) { super(reference, null, libraryName); assert reference.getResourceType() == ResourceType.ARRAY; } @Override public int getElementCount() { return elements.size(); } @Override @NotNull public String getElement(int index) { return elements.get(index); } /** Adds an element into the array. */ public void addElement(@NotNull String value) { elements.add(value); } @Override public Iterator<String> iterator() { return elements.iterator(); } /** * Returns the index of the element to pick by default if a client of layoutlib asks for the * {@link #getValue()} rather than the more specific {@linkplain ArrayResourceValue} iteration * methods */ protected int getDefaultIndex() { return 0; } @Override @Nullable public String getValue() { // Clients should normally not call this method on ArrayResourceValues; they should // pick the specific array element they want. However, for compatibility with older // layout libs, return the first array element's value instead. //noinspection VariableNotUsedInsideIf if (super.getValue() == null) { if (!elements.isEmpty()) { return elements.get(getDefaultIndex()); } } return super.getValue(); } }
2,169
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutResourceValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/LayoutResourceValue.java
package com.tyron.xml.completion.repository.api; import org.jetbrains.annotations.Nullable; public interface LayoutResourceValue extends ResourceValue { /** Return the root view of this layout, may return null. */ @Nullable LayoutInfo getRoot(); }
257
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttributeFormat.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/AttributeFormat.java
package com.tyron.xml.completion.repository.api; import com.google.common.base.Splitter; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** Formats of styleable attribute value. */ public enum AttributeFormat { BOOLEAN("boolean", EnumSet.of(ResourceType.BOOL)), COLOR("color", EnumSet.of(ResourceType.COLOR, ResourceType.DRAWABLE, ResourceType.MIPMAP)), DIMENSION("dimension", EnumSet.of(ResourceType.DIMEN)), ENUM("enum", Collections.emptySet()), FLAGS("flags", Collections.emptySet()), FLOAT("float", EnumSet.of(ResourceType.INTEGER)), FRACTION("fraction", EnumSet.of(ResourceType.FRACTION)), INTEGER("integer", EnumSet.of(ResourceType.INTEGER)), REFERENCE("reference", ResourceType.REFERENCEABLE_TYPES), STRING("string", EnumSet.of(ResourceType.STRING)); private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults(); private final String name; private final Set<ResourceType> matchingTypes; AttributeFormat(@NotNull String name, @NotNull Set<ResourceType> matchingTypes) { this.name = name; this.matchingTypes = matchingTypes; } AttributeFormat(@NotNull String name, @NotNull EnumSet<ResourceType> matchingTypes) { this(name, Collections.unmodifiableSet(matchingTypes)); } /** Returns the name used for the format in XML. */ @NotNull public String getName() { return name; } /** Returns the set of matching resource types. */ @NotNull public Set<ResourceType> getMatchingTypes() { return matchingTypes; } /** * Returns the format given its XML name. * * @param name the name used for the format in XML * @return the format, or null if the given name doesn't match any formats */ @Nullable public static AttributeFormat fromXmlName(@NotNull String name) { switch (name) { case "boolean": return BOOLEAN; case "color": return COLOR; case "dimension": return DIMENSION; case "enum": return ENUM; case "flags": return FLAGS; case "float": return FLOAT; case "fraction": return FRACTION; case "integer": return INTEGER; case "reference": return REFERENCE; case "string": return STRING; } return null; } /** Parses a pipe-separated format string to a set of formats. */ @NotNull public static Set<AttributeFormat> parse(@NotNull String formatString) { Set<AttributeFormat> result = EnumSet.noneOf(AttributeFormat.class); for (String formatName : PIPE_SPLITTER.split(formatString)) { AttributeFormat format = fromXmlName(formatName); if (format != null) { result.add(format); } } return result; } }
2,900
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleItemResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleItemResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.google.common.base.MoreObjects; import com.tyron.builder.compiler.manifest.resources.ResourceType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** A straightforward implementation of the {@link StyleItemResourceValue} interface. */ public class StyleItemResourceValueImpl extends ResourceValueImpl implements StyleItemResourceValue { @NotNull private final String attributeName; public StyleItemResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String attributeName, @Nullable String value, @Nullable String libraryName) { super(namespace, ResourceType.STYLE_ITEM, "<item>", value, libraryName); this.attributeName = attributeName; } /** * Returns contents of the {@code name} XML attribute that defined this style item. This is * supposed to be a reference to an {@code attr} resource. */ @Override @NotNull public String getAttrName() { return attributeName; } /** * Returns a {@link ResourceReference} to the {@code attr} resource this item is defined for, if * the name was specified using the correct syntax. */ @Override @Nullable public ResourceReference getAttr() { ResourceUrl url = ResourceUrl.parseAttrReference(attributeName); if (url == null) { return null; } return url.resolve(getNamespace(), mNamespaceResolver); } /** * Returns just the name part of the attribute being referenced, for backwards compatibility with * layoutlib. Don't call this method, the item may be in a different namespace than the attribute * and the value being referenced, use {@link #getAttr()} instead. * * @deprecated TODO(namespaces): Throw in this method, once layoutlib correctly calls {@link * #getAttr()} instead. */ @Deprecated @Override @NotNull public String getName() { ResourceUrl url = ResourceUrl.parseAttrReference(attributeName); if (url != null) { return url.name; } else { return attributeName; } } @Override @NotNull public String toString() { return MoreObjects.toStringHelper(this) .add("namespace", getNamespace()) .add("attribute", attributeName) .add("value", getValue()) .toString(); } }
2,344
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ResourceUrl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/ResourceUrl.java
package com.tyron.xml.completion.repository.api; import static com.tyron.xml.completion.repository.api.RenderResources.REFERENCE_EMPTY; import static com.tyron.xml.completion.repository.api.RenderResources.REFERENCE_NULL; import static com.tyron.xml.completion.repository.api.RenderResources.REFERENCE_UNDEFINED; import com.tyron.builder.compiler.manifest.SdkConstants; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.io.Serializable; import java.util.Objects; import javax.annotation.concurrent.Immutable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A {@linkplain ResourceUrl} represents a parsed resource url such as {@code @string/foo} or {@code * ?android:attr/bar} */ @Immutable public class ResourceUrl implements Serializable { /** Type of resource. */ @NotNull public final ResourceType type; /** Name of resource. */ @NotNull public final String name; /** The namespace, or null if it's in the project namespace. */ @Nullable public final String namespace; @NotNull public final UrlType urlType; /** The URL requests access to a private resource. */ public final boolean privateAccessOverride; /** If true, the resource is in the android: framework. */ public boolean isFramework() { return SdkConstants.ANDROID_NS_NAME.equals(namespace); } /** Whether an id resource is of the form {@code @+id} rather than just {@code @id}. */ public boolean isCreate() { return urlType == UrlType.CREATE; } /** Whether this is a theme resource reference. */ public boolean isTheme() { return urlType == UrlType.THEME; } /** Whether this is a theme resource reference. */ public boolean isPrivateAccessOverride() { return privateAccessOverride; } public enum UrlType { /** Reference of the form {@code @string/foo}. */ NORMAL, /** Reference of the form {@code @+id/foo}. */ CREATE, /** Reference of the form {@code ?android:textColor}. */ THEME, /** Reference of the form {@code android:textColor}. */ ATTR, } private ResourceUrl( @NotNull ResourceType type, @NotNull String name, @Nullable String namespace, @NotNull UrlType urlType, boolean privateAccessOverride) { this.type = type; this.name = name; this.namespace = namespace; this.urlType = urlType; this.privateAccessOverride = privateAccessOverride; } /** * Creates a new resource URL, representing "@type/name" or "@android:type/name". * * @see #parse(String) * @param type the resource type * @param name the name * @param framework whether it's a framework resource * @deprecated This factory method is used where we have no way of knowing the namespace. We need * to migrate every call site to the other factory method that takes a namespace. */ @Deprecated // TODO: namespaces public static ResourceUrl create( @NotNull ResourceType type, @NotNull String name, boolean framework) { return new ResourceUrl( type, name, framework ? SdkConstants.ANDROID_NS_NAME : null, UrlType.NORMAL, false); } /** * Creates a new resource URL, representing "@namespace:type/name". * * @see #parse(String) * @param namespace the resource namespace * @param type the resource type * @param name the name */ @NotNull public static ResourceUrl create( @Nullable String namespace, @NotNull ResourceType type, @NotNull String name) { return new ResourceUrl(type, name, namespace, UrlType.NORMAL, false); } /** * Creates a new resource URL, representing "?namespace:type/name". * * @see #parse(String) * @param namespace the resource namespace * @param type the resource type * @param name the name */ @NotNull public static ResourceUrl createThemeReference( @Nullable String namespace, @NotNull ResourceType type, @NotNull String name) { return new ResourceUrl(type, name, namespace, UrlType.THEME, false); } /** * Creates a new resource URL, representing "namespace:name". * * @see #parse(String) * @param namespace the resource namespace * @param name the name */ @NotNull public static ResourceUrl createAttrReference(@Nullable String namespace, @NotNull String name) { return new ResourceUrl(ResourceType.ATTR, name, namespace, UrlType.ATTR, false); } /** * Returns a {@linkplain ResourceUrl} representation of the given string, or null if it's not a * valid resource reference. This method works only for strings of type {@link UrlType#NORMAL}, * {@link UrlType#CREATE} and {@link UrlType#THEME}, see dedicated methods for parsing references * to style parents and to {@code attr} resources in the {@code name} XML attribute of style * items. * * @param url the resource url to be parsed * @return a pair of the resource type and the resource name */ @Nullable public static ResourceUrl parse(@NotNull String url) { return parse(url, false); } /** * Returns a {@linkplain ResourceUrl} representation of the given string, or null if it's not a * valid resource reference. This method works only for strings of type {@link UrlType#NORMAL}, * {@link UrlType#CREATE} and {@link UrlType#THEME}, see dedicated methods for parsing references * to style parents and to {@code attr} resources in the {@code name} XML attribute of style * items. * * @param url the resource url to be parsed * @param defaultToFramework defaults the returned value to be a framework resource if no * namespace is specified. * <p>TODO(namespaces): remove the defaultToFramework argument. */ @Nullable public static ResourceUrl parse(@NotNull String url, boolean defaultToFramework) { // Options: UrlType urlType = UrlType.NORMAL; // A prefix that ends with a '*' means that private access is overridden. boolean privateAccessOverride = false; // If the prefix is '?' the url points to a style. boolean isStyle = false; // Beginning of the parsing: int currentIndex = 0; int length = url.length(); if (currentIndex == length) { return null; } char currentChar = url.charAt(currentIndex); // The prefix could be one of @, @+, @+*, @*, ? char themePrefix = SdkConstants.PREFIX_THEME_REF.charAt(0); char resourcePrefix = SdkConstants.PREFIX_RESOURCE_REF.charAt(0); if (themePrefix == currentChar) { currentIndex++; urlType = UrlType.THEME; isStyle = true; } else if (resourcePrefix == currentChar) { currentIndex++; if (currentIndex == length) { return null; } currentChar = url.charAt(currentIndex); if (currentChar == '+') { currentIndex++; urlType = UrlType.CREATE; } } int prefixEnd = currentIndex; if (prefixEnd == 0) { return null; } // Private override: if (currentIndex == length) { return null; } currentChar = url.charAt(currentIndex); if (currentChar == '*') { privateAccessOverride = true; currentIndex++; } // The token is used to mark the start of a group in the url. // Once a piece of code has extracted the desired group, // the token is updated to the current position. int tokenStart = currentIndex; // Namespace or type: // The type can only be empty if the prefix is '?' and in that case will default to 'attr'. int typeStart = -1; int typeEnd = -1; // The namespace can be null but cannot be empty, it is always located before ':'. int namespaceStart = defaultToFramework ? 0 : -1; // Setting to 0 so we don't unnecessary look for it. int namespaceEnd = -1; // Let's try to find the type and namespace no matter their order // until we hit the end of the string. while ((typeStart == -1 || namespaceStart == -1) && currentIndex < length) { currentChar = url.charAt(currentIndex); switch (currentChar) { case '/': if (typeStart == -1) { // If the namespace or type were already found, we do not override them. typeStart = tokenStart; typeEnd = currentIndex; tokenStart = currentIndex + 1; } break; case ':': if (namespaceStart == -1) { namespaceStart = tokenStart; namespaceEnd = currentIndex; if (namespaceStart == namespaceEnd) { return null; } tokenStart = currentIndex + 1; } break; case '[': while (']' != currentChar && currentIndex < length - 1) { currentIndex++; currentChar = url.charAt(currentIndex); } break; } currentIndex++; } // Name: // The rest of the url can now be considered as the name. // The name cannot be empty. int nameStart = tokenStart; if (length <= nameStart) { return null; } // End of parsing, we know all the indices and we can start // extracting them. String name = url.substring(nameStart, length); // If no type is defined and the url is a style, // then the type defaults to attr. // But if it is not a style, then the url is invalid. ResourceType type; if (typeEnd > typeStart) { type = ResourceType.fromXmlValue(url.substring(typeStart, typeEnd)); if (type == null) { return null; } } else if (isStyle) { type = ResourceType.ATTR; } else { return null; } // If defaultToFramework is true and no namespace is set, // the namespace will be 'android'. String namespace; if (namespaceStart < namespaceEnd) { namespace = url.substring(namespaceStart, namespaceEnd); } else { namespace = defaultToFramework ? SdkConstants.ANDROID_NS_NAME : null; } return new ResourceUrl(type, name, namespace, urlType, privateAccessOverride); } /** * Returns a {@linkplain ResourceUrl} representation of the given reference to an {@code attr} * resources, most likely the contents of {@code <item name="..." >}. */ @Nullable public static ResourceUrl parseAttrReference(@NotNull String input) { if (input.isEmpty()) { return null; } if (input.charAt(0) == '@' || input.charAt(0) == '?') { return null; } boolean privateAccessOverride = false; int prefixEnd = 0; if (input.charAt(0) == '*') { prefixEnd = 1; privateAccessOverride = true; } if (input.indexOf('/', prefixEnd) >= 0) { return null; } String namespace = null; String name; int colon = input.indexOf(':', prefixEnd); if (colon < 0) { name = input.substring(prefixEnd); } else { namespace = input.substring(prefixEnd, colon); if (namespace.isEmpty()) { return null; } name = input.substring(colon + 1); } if (name.isEmpty()) { return null; } return new ResourceUrl(ResourceType.ATTR, name, namespace, UrlType.ATTR, privateAccessOverride); } /** * Returns a {@linkplain ResourceUrl} representation of the given reference to a style's parent. */ @Nullable public static ResourceUrl parseStyleParentReference(@NotNull String input) { if (input.isEmpty()) { return null; } boolean privateAccessOverride = false; int pos = 0; if (input.charAt(pos) == '@' || input.charAt(pos) == '?') { pos++; } if (input.startsWith("*", pos)) { pos += 1; privateAccessOverride = true; } String namespace = null; int colon = input.indexOf(':', pos); if (colon != -1) { namespace = input.substring(pos, colon); if (namespace.isEmpty()) { return null; } pos = colon + 1; } int slash = input.indexOf('/', pos); if (slash != -1) { if (!input.startsWith(SdkConstants.REFERENCE_STYLE, pos)) { // Wrong resource type used. return null; } pos = slash + 1; } String name = input.substring(pos); if (name.isEmpty()) { return null; } return new ResourceUrl( ResourceType.STYLE, name, namespace, UrlType.NORMAL, privateAccessOverride); } /** Returns if the resource url is @null, @empty or @undefined. */ public static boolean isNullOrEmpty(@NotNull String url) { return url.equals(REFERENCE_NULL) || url.equals(REFERENCE_EMPTY) || url.equals(REFERENCE_UNDEFINED); } /** * Checks whether this resource has a valid name. Used when parsing data that isn't necessarily * known to be a valid resource; for example, "?attr/hello world" */ public boolean hasValidName() { return isValidName(name, type); } public static boolean isValidName(@NotNull String input, @NotNull ResourceType type) { // TODO(namespaces): This (almost) duplicates ValueResourceNameValidator. // Make sure it looks like a resource name; if not, it could just be a string // which starts with a ?, etc. if (input.isEmpty()) { return false; } if (!Character.isJavaIdentifierStart(input.charAt(0))) { return false; } for (int i = 1, n = input.length(); i < n; i++) { char c = input.charAt(i); if (!Character.isJavaIdentifierPart(c) && c != '.') { // Sample data allows for extra characters if (type != ResourceType.SAMPLE_DATA || (c != '/' && c != '[' && c != ']' && c != ':')) { return false; } } } return true; } /** * Tries to resolve this {@linkplain ResourceUrl} into a valid {@link ResourceReference} by * expanding the namespace alias (or lack thereof) based on the context in which this {@linkplain * ResourceUrl} was used. * * @param contextNamespace aapt namespace of the module in which this URL was used * @param resolver logic for expanding namespaces aliases, most likely by walking up the XML tree. * @see ResourceNamespace#fromNamespacePrefix(String, ResourceNamespace, * ResourceNamespace.Resolver) */ @Nullable public ResourceReference resolve( @NotNull ResourceNamespace contextNamespace, @NotNull ResourceNamespace.Resolver resolver) { ResourceNamespace resolvedNamespace = ResourceNamespace.fromNamespacePrefix(this.namespace, contextNamespace, resolver); if (resolvedNamespace == null) { return null; } if (name.indexOf(':') >= 0 && type != ResourceType.SAMPLE_DATA) { return null; } return new ResourceReference(resolvedNamespace, type, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); switch (urlType) { case NORMAL: sb.append(SdkConstants.PREFIX_RESOURCE_REF); break; case CREATE: sb.append("@+"); break; case THEME: sb.append(SdkConstants.PREFIX_THEME_REF); break; case ATTR: // No prefix. break; } if (privateAccessOverride) { sb.append('*'); } if (namespace != null) { sb.append(namespace); sb.append(':'); } if (urlType != UrlType.ATTR) { sb.append(type.getName()); sb.append('/'); } sb.append(name); return sb.toString(); } /** * Returns a short string representation, which includes just the namespace (if defined in this * {@linkplain ResourceUrl} and name, separated by a colon. For example {@code * ResourceUrl.parse("@android:style/Theme").getQualifiedName()} returns {@code "android:Theme"} * and {@code ResourceUrl.parse("?myColor").getQualifiedName()} returns {@code "myColor"}. * * <p>This is used when the type is implicit, e.g. when specifying attribute for a style item or a * parent for a style. */ @NotNull public String getQualifiedName() { if (namespace == null) { return name; } else { return namespace + ':' + name; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceUrl that = (ResourceUrl) o; return urlType == that.urlType && type == that.type && Objects.equals(name, that.name) && Objects.equals(namespace, that.namespace); } @Override public int hashCode() { return Objects.hash(urlType, type, name, namespace); } }
16,509
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleResourceValueImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/repository/api/StyleResourceValueImpl.java
package com.tyron.xml.completion.repository.api; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.tyron.builder.compiler.manifest.resources.ResourceType; import java.util.Collection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Represents an Android style resource with a name and a list of children {@link ResourceValue}. */ public class StyleResourceValueImpl extends ResourceValueImpl implements StyleResourceValue { /** * Contents of the {@code parent} XML attribute. May be empty or null. * * @see #StyleResourceValueImpl(ResourceReference, String, String) */ @Nullable private String parentStyle; /** * Items defined in this style, indexed by the namespace and name of the attribute they define. */ @NotNull private final Table<ResourceNamespace, String, StyleItemResourceValue> styleItems = HashBasedTable.create(); /** * Creates a new {@link StyleResourceValueImpl}. * * <p>Note that names of styles have more meaning than other resources: if the parent attribute is * not set, aapt looks for a dot in the style name and treats the string up to the last dot as the * name of a parent style. So {@code <style name="Foo.Bar.Baz">} has an implicit parent called * {@code Foo.Bar}. Setting the {@code parent} XML attribute disables this feature, even if it's * set to an empty string. See {@code ResourceParser::ParseStyle} in aapt for details. */ public StyleResourceValueImpl( @NotNull ResourceNamespace namespace, @NotNull String name, @Nullable String parentStyle, @Nullable String libraryName) { super(namespace, ResourceType.STYLE, name, null, libraryName); this.parentStyle = parentStyle; } /** * Creates a new {@link StyleResourceValueImpl}. * * @see #StyleResourceValueImpl(ResourceNamespace, String, String, String) */ public StyleResourceValueImpl( @NotNull ResourceReference reference, @Nullable String parentStyle, @Nullable String libraryName) { super(reference, null, libraryName); assert reference.getResourceType() == ResourceType.STYLE; this.parentStyle = parentStyle; } /** Creates a copy of the given style. */ @NotNull public static StyleResourceValueImpl copyOf(@NotNull StyleResourceValue style) { StyleResourceValueImpl copy = new StyleResourceValueImpl( style.getNamespace(), style.getName(), style.getParentStyleName(), style.getLibraryName()); for (StyleItemResourceValue item : style.getDefinedItems()) { copy.addItem(item); } return copy; } @Override @Nullable public String getParentStyleName() { return parentStyle; } @Override @Nullable public StyleItemResourceValue getItem( @NotNull ResourceNamespace namespace, @NotNull String name) { return styleItems.get(namespace, name); } @Override @Nullable public StyleItemResourceValue getItem(@NotNull ResourceReference attr) { assert attr.getResourceType() == ResourceType.ATTR; return styleItems.get(attr.getNamespace(), attr.getName()); } @Override @NotNull public Collection<StyleItemResourceValue> getDefinedItems() { return styleItems.values(); } /** * Adds a style item to this style. * * @param item the style item to add */ public void addItem(@NotNull StyleItemResourceValue item) { ResourceReference attr = item.getAttr(); if (attr != null) { styleItems.put(attr.getNamespace(), attr.getName(), item); } } @Override public void replaceWith(@NotNull ResourceValue style) { assert style instanceof StyleResourceValueImpl : style.getClass() + " is not StyleResourceValue"; super.replaceWith(style); //noinspection ConstantConditions if (style instanceof StyleResourceValueImpl) { styleItems.clear(); styleItems.putAll(((StyleResourceValueImpl) style).styleItems); } } }
4,041
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DOMUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-repository/src/main/java/com/tyron/xml/completion/util/DOMUtils.java
package com.tyron.xml.completion.util; import com.tyron.xml.completion.repository.api.ResourceNamespace; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.stream.Collectors; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMNode; import org.eclipse.lemminx.dom.DOMProcessingInstruction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class DOMUtils { private static final String RESOLVER_KEY = "uriResolver"; private static final String NAMESPACE_KEY = "namespace"; private static final WeakHashMap<DOMNode, Map<String, Object>> sUserDataHolder = new WeakHashMap<>(); public static List<DOMElement> findElementsWithTagName(DOMElement element, String tagName) { List<DOMElement> elements = new ArrayList<>(); List<DOMNode> children = element.getChildren(); for (DOMNode child : children) { if (!(child instanceof DOMElement)) { continue; } if (tagName.equals(((DOMElement) child).getTagName())) { elements.add((DOMElement) child); } elements.addAll(findElementsWithTagName((DOMElement) child, tagName)); } return elements; } public static String lookupPrefix(DOMAttr attr) { return lookupPrefix(attr, getPrefix(attr)); } public static String lookupPrefix(DOMAttr attr, String prefix) { DOMElement element = attr.getOwnerElement(); while (element != null) { List<DOMAttr> nodes = element.getAttributeNodes(); if (nodes != null) { for (DOMAttr node : nodes) { if (!node.isXmlns()) { continue; } if (prefix.equals(node.getLocalName())) { return node.getValue(); } } } element = element.getParentElement(); } return prefix; } public static String getPrefix(@NotNull DOMAttr attr) { String name = attr.getName(); if (!name.contains(":")) { return name; } return name.substring(0, name.indexOf(':')); } @Nullable public static DOMElement getRootElement(@NotNull DOMDocument document) { List<DOMNode> roots = document.getRoots(); for (DOMNode root : roots) { if (root instanceof DOMElement) { return (DOMElement) root; } } return null; } @NotNull public static List<DOMNode> getRootElements(@NotNull DOMDocument document) { List<DOMNode> roots = document.getRoots(); return roots.stream() .filter(it -> !(it instanceof DOMProcessingInstruction)) .collect(Collectors.toList()); } public static ResourceNamespace.Resolver getNamespaceResolver(DOMDocument document) { DOMElement rootElement = getRootElement(document); if (rootElement == null) { return ResourceNamespace.Resolver.EMPTY_RESOLVER; } Object userData = getUserData(rootElement, RESOLVER_KEY); if (userData instanceof ResourceNamespace.Resolver) { return (ResourceNamespace.Resolver) userData; } ResourceNamespace.Resolver resolver = new ResourceNamespace.Resolver() { @Nullable @Override public String uriToPrefix(@NotNull String namespaceUri) { return rootElement.getPrefix(namespaceUri); } @Nullable @Override public String prefixToUri(@NotNull String namespacePrefix) { DOMAttr xmlns = rootElement.getAttributeNode("xmlns", namespacePrefix); if (xmlns != null) { return xmlns.getValue(); } return null; } }; putUserData(rootElement, RESOLVER_KEY, resolver); return resolver; } public static boolean isClosed(DOMNode nodeAt) { if (!nodeAt.isClosed()) { return false; } DOMElement parent = nodeAt.getParentElement(); if (parent != null && !parent.isClosed()) { if (nodeAt.getNodeName().equals(parent.getTagName())) { return false; } } return nodeAt.isClosed(); } public static Object getUserData(DOMNode node, String key) { final Map<String, Object> map = sUserDataHolder.get(node); if (map == null) { return null; } return map.get(key); } public static void putUserData(@NotNull DOMNode node, @NotNull String key, Object value) { sUserDataHolder.computeIfAbsent(node, it -> new HashMap<>()); Map<String, Object> map = sUserDataHolder.get(node); if (map != null) { map.put(key, value); } } public static void setNamespace(DOMDocument document, ResourceNamespace namespace) { putUserData(document, NAMESPACE_KEY, namespace); } @Nullable public static ResourceNamespace getNamespace(DOMDocument document) { final Object userData = getUserData(document, NAMESPACE_KEY); if (userData instanceof ResourceNamespace) { return ((ResourceNamespace) userData); } return null; } }
5,074
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Javap.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javac/src/main/java/com/sun/tools/javap/Javap.java
package com.sun.tools.javap; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class Javap { public static void main(String[] args) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); com.sun.tools.javap.JavapTask javapTask = new com.sun.tools.javap.JavapTask(); javapTask.handleOptions(args); javapTask.setLog(printStream); javapTask.run(); // Print the output System.out.println(outputStream.toString()); } catch (Exception e) { e.printStackTrace(); // Print the exception stack trace } } }
670
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DefaultValues.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/DefaultValues.java
package com.tyron.vectorparser; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; public class DefaultValues { public static String[] PATH_ATTRIBUTES = { "name", "fillAlpha", "fillColor", "fillType", "pathData", "strokeAlpha", "strokeColor", "strokeLineCap", "strokeLineJoin", "strokeMiterLimit", "strokeWidth" }; public static final int PATH_FILL_COLOR = Color.TRANSPARENT; public static final int PATH_STROKE_COLOR = Color.TRANSPARENT; public static final float PATH_STROKE_WIDTH = 1.0f; public static final float PATH_STROKE_ALPHA = 1.0f; public static final float PATH_FILL_ALPHA = 1.0f; public static final Paint.Cap PATH_STROKE_LINE_CAP = Paint.Cap.BUTT; public static final Paint.Join PATH_STROKE_LINE_JOIN = Paint.Join.MITER; public static final float PATH_STROKE_MITER_LIMIT = 4.0f; public static final float PATH_STROKE_RATIO = 1.0f; // WINDING fill type is equivalent to NON_ZERO public static final Path.FillType PATH_FILL_TYPE = Path.FillType.WINDING; public static final float PATH_TRIM_PATH_START = 0.0f; public static final float PATH_TRIM_PATH_END = 1.0f; public static final float PATH_TRIM_PATH_OFFSET = 0.0f; public static final float VECTOR_VIEWPORT_WIDTH = 0.0f; public static final float VECTOR_VIEWPORT_HEIGHT = 0.0f; public static final float VECTOR_WIDTH = 0.0f; public static final float VECTOR_HEIGHT = 0.0f; public static final float VECTOR_ALPHA = 1.0f; public static final float GROUP_ROTATION = 0.0f; public static final float GROUP_PIVOT_X = 0.0f; public static final float GROUP_PIVOT_Y = 0.0f; public static final float GROUP_SCALE_X = 1.0f; public static final float GROUP_SCALE_Y = 1.0f; public static final float GROUP_TRANSLATE_X = 0.0f; public static final float GROUP_TRANSLATE_Y = 0.0f; }
1,879
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DynamicVectorDrawable.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/DynamicVectorDrawable.java
package com.tyron.vectorparser; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.flipkart.android.proteus.ProteusContext; import com.tyron.vectorparser.model.ClipPathModel; import com.tyron.vectorparser.model.GroupModel; import com.tyron.vectorparser.model.PathModel; import com.tyron.vectorparser.model.VectorModel; import com.tyron.vectorparser.util.Utils; import java.io.IOException; import java.io.StringReader; import java.util.Stack; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; public class DynamicVectorDrawable extends Drawable { private XmlPullParser mParser; private VectorModel vectorModel; private Matrix scaleMatrix; private int tempSaveCount; private int height; private int width; private int left; private int top; private float offsetX; private float offsetY; private float scaleRatio; private float strokeRatio; private float scaleX = 1.0f; private float scaleY = 1.0f; private final ProteusContext mContext; public DynamicVectorDrawable(ProteusContext context) { mContext = context; } public void setContents(String contents) throws XmlPullParserException { mParser = XmlPullParserFactory.newInstance().newPullParser(); mParser.setInput(new StringReader(contents)); buildVectorModel(); } private void buildVectorModel() { int tempPosition; PathModel pathModel = new PathModel(); vectorModel = new VectorModel(); GroupModel groupModel = new GroupModel(); ClipPathModel clipPathModel = new ClipPathModel(); Stack<GroupModel> groupModelStack = new Stack<>(); try { int event = mParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name = mParser.getName(); switch (event) { case XmlPullParser.START_TAG: switch (name) { case "vector": tempPosition = getAttrPosition(mParser, "android:viewportWidth"); vectorModel.setViewportWidth( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_VIEWPORT_WIDTH); tempPosition = getAttrPosition(mParser, "android:viewportHeight"); vectorModel.setViewportHeight( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_VIEWPORT_HEIGHT); tempPosition = getAttrPosition(mParser, "android:alpha"); vectorModel.setAlpha( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.VECTOR_ALPHA); tempPosition = getAttrPosition(mParser, "android:name"); vectorModel.setName( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(mParser, "android:width"); vectorModel.setWidth( (tempPosition != -1) ? Utils.getFloatFromDimensionString( mParser.getAttributeValue(tempPosition), mContext) : DefaultValues.VECTOR_WIDTH); tempPosition = getAttrPosition(mParser, "android:height"); vectorModel.setHeight( (tempPosition != -1) ? Utils.getFloatFromDimensionString( mParser.getAttributeValue(tempPosition), mContext) : DefaultValues.VECTOR_HEIGHT); tempPosition = getAttrPosition(mParser, "android:tint"); vectorModel.setTint( (tempPosition != -1) ? Utils.getColorFromString( mParser.getAttributeValue(tempPosition), mContext) : 0); break; case "path": pathModel = new PathModel(); tempPosition = getAttrPosition(mParser, "android:name"); pathModel.setName( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(mParser, "android:fillAlpha"); pathModel.setFillAlpha( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_FILL_ALPHA); tempPosition = getAttrPosition(mParser, "android:fillColor"); pathModel.setFillColor( (tempPosition != -1) ? Utils.getColorFromString( mParser.getAttributeValue(tempPosition), mContext) : DefaultValues.PATH_FILL_COLOR); tempPosition = getAttrPosition(mParser, "android:fillType"); pathModel.setFillType( (tempPosition != -1) ? Utils.getFillTypeFromString(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_FILL_TYPE); tempPosition = getAttrPosition(mParser, "android:pathData"); pathModel.setPathData( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(mParser, "android:strokeAlpha"); pathModel.setStrokeAlpha( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_ALPHA); tempPosition = getAttrPosition(mParser, "android:strokeColor"); pathModel.setStrokeColor( (tempPosition != -1) ? Utils.getColorFromString( mParser.getAttributeValue(tempPosition), mContext) : DefaultValues.PATH_STROKE_COLOR); tempPosition = getAttrPosition(mParser, "android:strokeLineCap"); pathModel.setStrokeLineCap( (tempPosition != -1) ? Utils.getLineCapFromString(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_LINE_CAP); tempPosition = getAttrPosition(mParser, "android:strokeLineJoin"); pathModel.setStrokeLineJoin( (tempPosition != -1) ? Utils.getLineJoinFromString(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_LINE_JOIN); tempPosition = getAttrPosition(mParser, "android:strokeMiterLimit"); pathModel.setStrokeMiterLimit( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_MITER_LIMIT); tempPosition = getAttrPosition(mParser, "android:strokeWidth"); pathModel.setStrokeWidth( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_STROKE_WIDTH); tempPosition = getAttrPosition(mParser, "android:trimPathEnd"); pathModel.setTrimPathEnd( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_END); tempPosition = getAttrPosition(mParser, "android:trimPathOffset"); pathModel.setTrimPathOffset( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_OFFSET); tempPosition = getAttrPosition(mParser, "android:trimPathStart"); pathModel.setTrimPathStart( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.PATH_TRIM_PATH_START); pathModel.buildPath(false); break; case "group": groupModel = new GroupModel(); tempPosition = getAttrPosition(mParser, "android:name"); groupModel.setName( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(mParser, "android:pivotX"); groupModel.setPivotX( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_PIVOT_X); tempPosition = getAttrPosition(mParser, "android:pivotY"); groupModel.setPivotY( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_PIVOT_Y); tempPosition = getAttrPosition(mParser, "android:rotation"); groupModel.setRotation( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_ROTATION); tempPosition = getAttrPosition(mParser, "android:scaleX"); groupModel.setScaleX( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_SCALE_X); tempPosition = getAttrPosition(mParser, "android:scaleY"); groupModel.setScaleY( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_SCALE_Y); tempPosition = getAttrPosition(mParser, "android:translateX"); groupModel.setTranslateX( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_TRANSLATE_X); tempPosition = getAttrPosition(mParser, "android:translateY"); groupModel.setTranslateY( (tempPosition != -1) ? Float.parseFloat(mParser.getAttributeValue(tempPosition)) : DefaultValues.GROUP_TRANSLATE_Y); groupModelStack.push(groupModel); break; case "clip-path": clipPathModel = new ClipPathModel(); tempPosition = getAttrPosition(mParser, "android:name"); clipPathModel.setName( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); tempPosition = getAttrPosition(mParser, "android:pathData"); clipPathModel.setPathData( (tempPosition != -1) ? mParser.getAttributeValue(tempPosition) : null); clipPathModel.buildPath(false); break; } break; case XmlPullParser.END_TAG: if (name.equals("path")) { if (groupModelStack.size() == 0) { vectorModel.addPathModel(pathModel); } else { groupModelStack.peek().addPathModel(pathModel); } vectorModel.getFullpath().addPath(pathModel.getPath()); } else if (name.equals("clip-path")) { if (groupModelStack.size() == 0) { vectorModel.addClipPathModel(clipPathModel); } else { groupModelStack.peek().addClipPathModel(clipPathModel); } } else if (name.equals("group")) { GroupModel topGroupModel = groupModelStack.pop(); if (groupModelStack.size() == 0) { topGroupModel.setParent(null); vectorModel.addGroupModel(topGroupModel); } else { topGroupModel.setParent(groupModelStack.peek()); groupModelStack.peek().addGroupModel(topGroupModel); } } else if (name.equals("vector")) { vectorModel.buildTransformMatrices(); } break; } event = mParser.next(); } } catch (XmlPullParserException | IOException e) { e.printStackTrace(); } } @Override public void draw(@NonNull Canvas canvas) { if (vectorModel == null) { return; } if (scaleMatrix == null) { int temp1 = (int) vectorModel.getWidth(); int temp2 = (int) vectorModel.getHeight(); setBounds(0, 0, temp1, temp2); } setAlpha(Utils.getAlphaFromFloat(vectorModel.getAlpha())); if (left != 0 || top != 0) { tempSaveCount = canvas.save(); canvas.translate(left, top); vectorModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); canvas.restoreToCount(tempSaveCount); } else { vectorModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); } } @Override public void setAlpha(int alpha) {} @Override public void setColorFilter(@Nullable ColorFilter colorFilter) {} @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public int getIntrinsicWidth() { return Utils.dpToPx((int) vectorModel.getWidth()); } @Override public int getIntrinsicHeight() { return Utils.dpToPx((int) vectorModel.getHeight()); } private void buildScaleMatrix() { scaleMatrix = new Matrix(); scaleMatrix.postTranslate( width / 2f - vectorModel.getViewportWidth() / 2, height / 2f - vectorModel.getViewportHeight() / 2); float widthRatio = width / vectorModel.getViewportWidth(); float heightRatio = height / vectorModel.getViewportHeight(); float ratio = Math.min(widthRatio, heightRatio); scaleRatio = ratio; scaleMatrix.postScale(ratio, ratio, width / 2f, height / 2f); } private void scaleAllPaths() { vectorModel.scaleAllPaths(scaleMatrix); } private void scaleAllStrokes() { strokeRatio = Math.min(width / vectorModel.getWidth(), height / vectorModel.getHeight()); vectorModel.scaleAllStrokeWidth(strokeRatio); } private int getAttrPosition(XmlPullParser xpp, String attrName) { for (int i = 0; i < xpp.getAttributeCount(); i++) { if (xpp.getAttributeName(i).equals(attrName)) { return i; } } return -1; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); if (bounds.width() != 0 && bounds.height() != 0) { left = bounds.left; top = bounds.top; width = bounds.width(); height = bounds.height(); buildScaleMatrix(); scaleAllPaths(); scaleAllStrokes(); } } }
15,556
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
VectorValue.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/VectorValue.java
package com.tyron.vectorparser; import android.view.View; import com.flipkart.android.proteus.ProteusContext; import com.flipkart.android.proteus.ProteusLayoutInflater; import com.flipkart.android.proteus.value.DrawableValue; import org.xmlpull.v1.XmlPullParserException; public class VectorValue extends DrawableValue { private final String contents; public VectorValue(String contents) { this.contents = contents; } @Override public void apply( View view, ProteusContext context, ProteusLayoutInflater.ImageLoader loader, Callback callback) { DynamicVectorDrawable dynamicVectorDrawable = new DynamicVectorDrawable(context); try { dynamicVectorDrawable.setContents(contents); dynamicVectorDrawable.invalidateSelf(); callback.apply(dynamicVectorDrawable); } catch (XmlPullParserException e) { e.printStackTrace(); } } }
906
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
TintMode.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/enums/TintMode.java
package com.tyron.vectorparser.enums; /** Created by Harjot on 20-Jun-17. */ public enum TintMode { ADD, MULTIPLY, SCREEN, SRC_ATOP, SCR_IN, SRC_OVER }
165
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ParserHelper.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/util/ParserHelper.java
package com.tyron.vectorparser.util; /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Changes Copyright 2011 Google Inc. */ /** * Parses numbers from SVG text. Based on the Batik Number Parser (Apache 2 License). * * @author Apache Software Foundation, Larva Labs LLC */ class ParserHelper { private char current; private final CharSequence s; public int pos; private final int n; public ParserHelper(CharSequence s) { this.s = s; this.pos = 0; n = s.length(); current = s.charAt(pos); } private char read() { if (pos < n) { pos++; } if (pos == n) { return '\0'; } else { return s.charAt(pos); } } public void skipWhitespace() { while (pos < n) { if (Character.isWhitespace(s.charAt(pos))) { advance(); } else { break; } } } void skipNumberSeparator() { while (pos < n) { char c = s.charAt(pos); switch (c) { case ' ': case ',': case '\n': case '\t': advance(); break; default: return; } } } public void advance() { current = read(); } // Parses the content of the buffer and converts it to a float. float parseFloat() { int mant = 0; int mantDig = 0; boolean mantPos = true; boolean mantRead = false; int exp = 0; int expDig = 0; int expAdj = 0; boolean expPos = true; switch (current) { case '-': mantPos = false; // fallthrough case '+': current = read(); } m1: switch (current) { default: return Float.NaN; case '.': break; case '0': mantRead = true; l: for (; ; ) { current = read(); switch (current) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break l; case '.': case 'e': case 'E': break m1; default: return 0.0f; case '0': } } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': mantRead = true; l: for (; ; ) { if (mantDig < 9) { mantDig++; mant = mant * 10 + (current - '0'); } else { expAdj++; } current = read(); switch (current) { default: break l; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': } } } if (current == '.') { current = read(); m2: switch (current) { default: case 'e': case 'E': if (!mantRead) { reportUnexpectedCharacterError(current); return 0.0f; } break; case '0': if (mantDig == 0) { l: for (; ; ) { current = read(); expAdj--; switch (current) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break l; default: if (!mantRead) { return 0.0f; } break m2; case '0': } } } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': l: for (; ; ) { if (mantDig < 9) { mantDig++; mant = mant * 10 + (current - '0'); expAdj--; } current = read(); switch (current) { default: break l; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': } } } } switch (current) { case 'e': case 'E': current = read(); switch (current) { default: reportUnexpectedCharacterError(current); return 0f; case '-': expPos = false; case '+': current = read(); switch (current) { default: reportUnexpectedCharacterError(current); return 0f; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': } en: switch (current) { case '0': l: for (; ; ) { current = read(); switch (current) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break l; default: break en; case '0': } } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': l: for (; ; ) { if (expDig < 3) { expDig++; exp = exp * 10 + (current - '0'); } current = read(); switch (current) { default: break l; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': } } } default: } if (!expPos) { exp = -exp; } exp += expAdj; if (!mantPos) { mant = -mant; } return buildFloat(mant, exp); } private void reportUnexpectedCharacterError(char c) { throw new RuntimeException("Unexpected char '" + c + "'."); } // Computes a float from mantissa and exponent. private static float buildFloat(int mant, int exp) { if (exp < -125 || mant == 0) { return 0.0f; } if (exp >= 128) { return (mant > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; } if (exp == 0) { return mant; } if (mant >= (1 << 26)) { mant++; // round up trailing bits if they will be dropped. } return (float) ((exp > 0) ? mant * pow10[exp] : mant / pow10[-exp]); } /** Array of powers of ten. Using double instead of float gives a tiny bit more precision. */ private static final double[] pow10 = new double[128]; static { for (int i = 0; i < pow10.length; i++) { pow10[i] = Math.pow(10, i); } } public float nextFloat() { skipWhitespace(); float f = parseFloat(); skipNumberSeparator(); return f; } }
8,698
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
PathParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/util/PathParser.java
package com.tyron.vectorparser.util; import android.graphics.Path; import android.graphics.RectF; import android.util.Log; public class PathParser { private static final String TAG = "PATH_PARSER"; /* * This is where the hard-to-parse paths are handled. * Uppercase rules are absolute positions, lowercase are relative. * Types of path rules: * <p/> * <ol> * <li>M/m - (x y)+ - Move to (without drawing) * <li>Z/z - (no params) - Close path (back to starting point) * <li>L/l - (x y)+ - Line to * <li>H/h - x+ - Horizontal ine to * <li>V/v - y+ - Vertical line to * <li>C/c - (x1 y1 x2 y2 x y)+ - Cubic bezier to * <li>S/s - (x2 y2 x y)+ - Smooth cubic bezier to (shorthand that assumes the x2, y2 from previous C/S is the x1, y1 of this bezier) * <li>Q/q - (x1 y1 x y)+ - Quadratic bezier to * <li>T/t - (x y)+ - Smooth quadratic bezier to (assumes previous control point is "reflection" of last one w.r.t. to current point) * </ol> * <p/> * Numbers are separate by whitespace, comma or nothing at all (!) if they are self-delimiting, (ie. begin with a - sign) */ public static Path doPath(String s) { int n = s.length(); ParserHelper ph = new ParserHelper(s); ph.skipWhitespace(); Path p = new Path(); float lastX = 0; float lastY = 0; float lastX1 = 0; float lastY1 = 0; float contourInitialX = 0; float contourInitialY = 0; RectF r = new RectF(); char prevCmd = 'm'; char cmd = 'x'; while (ph.pos < n) { char next = s.charAt(ph.pos); if (!Character.isDigit(next) && !(next == '.') && !(next == '-')) { cmd = next; ph.advance(); } else if (cmd == 'M') { // implied command cmd = 'L'; } else if (cmd == 'm') { // implied command cmd = 'l'; } else { // implied command // ignore } p.computeBounds(r, true); // Log.d(TAG, " " + cmd + " " + r); // Util.debug("* Commands remaining: '" + path + "'."); boolean wasCurve = false; switch (cmd) { case 'M': case 'm': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'm') { p.rMoveTo(x, y); lastX += x; lastY += y; } else { p.moveTo(x, y); lastX = x; lastY = y; } contourInitialX = lastX; contourInitialY = lastY; break; } case 'Z': case 'z': { /// p.lineTo(contourInitialX, contourInitialY); p.close(); lastX = contourInitialX; lastY = contourInitialY; break; } case 'L': case 'l': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'l') { if ((prevCmd == 'M' || prevCmd == 'm') && x == 0 && y == 0) { p.addCircle(x, y, 1f, Path.Direction.CW); } else { p.rLineTo(x, y); lastX += x; lastY += y; } } else { if ((prevCmd == 'M' || prevCmd == 'm') && x == lastX && y == lastY) { p.addCircle(x, y, 1f, Path.Direction.CW); } else { p.lineTo(x, y); lastX = x; lastY = y; } } break; } case 'H': case 'h': { float x = ph.nextFloat(); if (cmd == 'h') { p.rLineTo(x, 0); lastX += x; } else { p.lineTo(x, lastY); lastX = x; } break; } case 'V': case 'v': { float y = ph.nextFloat(); if (cmd == 'v') { p.rLineTo(0, y); lastY += y; } else { p.lineTo(lastX, y); lastY = y; } break; } case 'C': case 'c': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'c') { x1 += lastX; x2 += lastX; x += lastX; y1 += lastY; y2 += lastY; y += lastY; } p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'S': case 's': { wasCurve = true; float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 's') { x2 += lastX; x += lastX; y2 += lastY; y += lastY; } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'A': case 'a': { float rx = ph.nextFloat(); float ry = ph.nextFloat(); float theta = ph.nextFloat(); int largeArc = (int) ph.nextFloat(); int sweepArc = (int) ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'a') { x += lastX; y += lastY; } drawArc(p, lastX, lastY, x, y, rx, ry, theta, largeArc == 1, sweepArc == 1); lastX = x; lastY = y; break; } case 'T': case 't': { wasCurve = true; float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 't') { x += lastX; y += lastY; } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo(lastX, lastY, x1, y1, x, y); lastX = x; lastY = y; lastX1 = x1; lastY1 = y1; break; } case 'Q': case 'q': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'q') { x += lastX; y += lastY; x1 += lastX; y1 += lastY; } p.cubicTo(lastX, lastY, x1, y1, x, y); lastX1 = x1; lastY1 = y1; lastX = x; lastY = y; break; } default: Log.w(TAG, "Invalid path command: " + cmd); ph.advance(); } prevCmd = cmd; if (!wasCurve) { lastX1 = lastX; lastY1 = lastY; } ph.skipWhitespace(); } return p; } /* * Elliptical arc implementation based on the SVG specification notes * Adapted from the Batik library (Apache-2 license) by SAU */ private static void drawArc( Path path, double x0, double y0, double x, double y, double rx, double ry, double angle, boolean largeArcFlag, boolean sweepFlag) { double dx2 = (x0 - x) / 2.0; double dy2 = (y0 - y) / 2.0; angle = Math.toRadians(angle % 360.0); double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle); double x1 = (cosAngle * dx2 + sinAngle * dy2); double y1 = (-sinAngle * dx2 + cosAngle * dy2); rx = Math.abs(rx); ry = Math.abs(ry); double Prx = rx * rx; double Pry = ry * ry; double Px1 = x1 * x1; double Py1 = y1 * y1; // check that radii are large enough double radiiCheck = Px1 / Prx + Py1 / Pry; if (radiiCheck > 1) { rx = Math.sqrt(radiiCheck) * rx; ry = Math.sqrt(radiiCheck) * ry; Prx = rx * rx; Pry = ry * ry; } // Step 2 : Compute (cx1, cy1) double sign = (largeArcFlag == sweepFlag) ? -1 : 1; double sq = ((Prx * Pry) - (Prx * Py1) - (Pry * Px1)) / ((Prx * Py1) + (Pry * Px1)); sq = (sq < 0) ? 0 : sq; double coef = (sign * Math.sqrt(sq)); double cx1 = coef * ((rx * y1) / ry); double cy1 = coef * -((ry * x1) / rx); double sx2 = (x0 + x) / 2.0; double sy2 = (y0 + y) / 2.0; double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) double ux = (x1 - cx1) / rx; double uy = (y1 - cy1) / ry; double vx = (-x1 - cx1) / rx; double vy = (-y1 - cy1) / ry; double p, n; // Compute the angle start n = Math.sqrt((ux * ux) + (uy * uy)); p = ux; // (1 * ux) + (0 * uy) sign = (uy < 0) ? -1.0 : 1.0; double angleStart = Math.toDegrees(sign * Math.acos(p / n)); // Compute the angle extent n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); p = ux * vx + uy * vy; sign = (ux * vy - uy * vx < 0) ? -1.0 : 1.0; double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); if (!sweepFlag && angleExtent > 0) { angleExtent -= 360f; } else if (sweepFlag && angleExtent < 0) { angleExtent += 360f; } angleExtent %= 360f; angleStart %= 360f; RectF oval = new RectF((float) (cx - rx), (float) (cy - ry), (float) (cx + rx), (float) (cy + ry)); path.addArc(oval, (float) angleStart, (float) angleExtent); } }
9,983
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Utils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/util/Utils.java
package com.tyron.vectorparser.util; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import com.flipkart.android.proteus.ProteusContext; import com.flipkart.android.proteus.processor.ColorResourceProcessor; import com.flipkart.android.proteus.processor.DimensionAttributeProcessor; import com.flipkart.android.proteus.value.Dimension; import com.flipkart.android.proteus.value.Primitive; import com.flipkart.android.proteus.value.Value; public class Utils { public static int getColor(Value value, ProteusContext context) { if (value == null) { return Color.WHITE; } if (value.isPrimitive()) { Value staticValue = ColorResourceProcessor.staticCompile(value, context); return getColor(staticValue, context); } if (value.isResource()) { com.flipkart.android.proteus.value.Color color = value.getAsResource().getColor(context); if (color != null) { return color.apply(context).color; } } if (value.isAttributeResource()) { Value v = value.getAsAttributeResource().resolve(null, null, context); return getColor(v, context); } if (value.isColor()) { return value.getAsColor().apply(context).color; } return com.flipkart.android.proteus.value.Color.Int.getDefaultColor().value; } public static int getColorFromString(String value, ProteusContext context) { Value staticValue = ColorResourceProcessor.staticCompile(new Primitive(value), context); return getColor(staticValue, context); } public static Path.FillType getFillTypeFromString(String value) { Path.FillType fillType = Path.FillType.WINDING; if (value.equals("1")) { fillType = Path.FillType.EVEN_ODD; } return fillType; } public static Paint.Cap getLineCapFromString(String value) { switch (value) { case "1": return Paint.Cap.ROUND; case "2": return Paint.Cap.SQUARE; default: return Paint.Cap.BUTT; } } public static Paint.Join getLineJoinFromString(String value) { switch (value) { case "0": return Paint.Join.MITER; case "1": return Paint.Join.ROUND; case "2": return Paint.Join.BEVEL; default: return Paint.Join.MITER; } } public static int getAlphaFromFloat(float value) { int newValue = (int) (255 * value); return Math.min(255, newValue); } public static float getAlphaFromInt(int value) { return (((float) value) / 255.0f); } public static int dpToPx(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } public static int pxToDp(int px) { return (int) (px / Resources.getSystem().getDisplayMetrics().density); } public static float getDimension(Value value, ProteusContext context) { if (value.isDimension()) { return value.getAsDimension().apply(context); } if (value.isPrimitive()) { Value value1 = DimensionAttributeProcessor.staticPreCompile( value, context, context.getFunctionManager()); if (value1 == null) { value1 = Dimension.valueOf(value.toString()); } return getDimension(value1, context); } if (value.isResource()) { Dimension dimension = value.getAsResource().getDimension(context); if (dimension != null) { return dimension.apply(context); } } if (value.isAttributeResource()) { Value resolve = value.getAsAttributeResource().resolve(null, null, context); if (resolve != null) { return getDimension(resolve, context); } } return 0; } public static float getFloatFromDimensionString(String value, ProteusContext context) { return getDimension(new Primitive(value), context); } public static boolean isEqual(Object a, Object b) { return a == null && b == null || !(a == null || b == null) && a.equals(b); } }
3,992
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
VectorModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/model/VectorModel.java
package com.tyron.vectorparser.model; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Path; import com.tyron.vectorparser.enums.TintMode; import java.util.ArrayList; public class VectorModel { private String name; private float width, height; private float alpha = 1.0f; private boolean autoMirrored = false; private int tint = Color.TRANSPARENT; private TintMode tintMode = TintMode.SCR_IN; private float viewportWidth, viewportHeight; private ArrayList<GroupModel> groupModels; private ArrayList<PathModel> pathModels; private ArrayList<ClipPathModel> clipPathModels; private Path fullpath; private Matrix scaleMatrix; public VectorModel() { groupModels = new ArrayList<>(); pathModels = new ArrayList<>(); clipPathModels = new ArrayList<>(); fullpath = new Path(); } public void drawPaths(Canvas canvas, float offsetX, float offsetY, float scaleX, float scaleY) { for (ClipPathModel clipPathModel : clipPathModels) { canvas.clipPath(clipPathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY)); } for (GroupModel groupModel : groupModels) { groupModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); } for (PathModel pathModel : pathModels) { if (pathModel.isFillAndStroke()) { pathModel.makeFillPaint(); canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); pathModel.makeStrokePaint(); canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); } else { canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); } } } public void drawPaths(Canvas canvas) { for (ClipPathModel clipPathModel : clipPathModels) { canvas.clipPath(clipPathModel.getPath()); } for (GroupModel groupModel : groupModels) { groupModel.drawPaths(canvas); } for (PathModel pathModel : pathModels) { if (pathModel.isFillAndStroke()) { pathModel.makeFillPaint(); canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); pathModel.makeStrokePaint(); canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); } else { canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); } } } public void scaleAllPaths(Matrix scaleMatrix) { this.scaleMatrix = scaleMatrix; for (GroupModel groupModel : groupModels) { groupModel.scaleAllPaths(scaleMatrix); } for (PathModel pathModel : pathModels) { pathModel.transform(scaleMatrix); } for (ClipPathModel clipPathModel : clipPathModels) { clipPathModel.transform(scaleMatrix); } } public void scaleAllStrokeWidth(float ratio) { for (GroupModel groupModel : groupModels) { groupModel.scaleAllStrokeWidth(ratio); } for (PathModel pathModel : pathModels) { pathModel.setStrokeRatio(ratio); } } public void buildTransformMatrices() { for (GroupModel groupModel : groupModels) { groupModel.buildTransformMatrix(); } } public void addGroupModel(GroupModel groupModel) { groupModels.add(groupModel); } public ArrayList<GroupModel> getGroupModels() { return groupModels; } public void addPathModel(PathModel pathModel) { pathModels.add(pathModel); } public ArrayList<PathModel> getPathModels() { return pathModels; } public void addClipPathModel(ClipPathModel clipPathModel) { clipPathModels.add(clipPathModel); } public ArrayList<ClipPathModel> getClipPathModels() { return clipPathModels; } public Path getFullpath() { return fullpath; } public void setFullpath(Path fullpath) { this.fullpath = fullpath; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getWidth() { return width; } public void setWidth(float width) { this.width = width; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getAlpha() { return alpha; } public void setAlpha(float alpha) { this.alpha = alpha; } public boolean isAutoMirrored() { return autoMirrored; } public void setAutoMirrored(boolean autoMirrored) { this.autoMirrored = autoMirrored; } public int getTint() { return tint; } public void setTint(int tint) { this.tint = tint; } public TintMode getTintMode() { return tintMode; } public void setTintMode(TintMode tintMode) { this.tintMode = tintMode; } public float getViewportWidth() { return viewportWidth; } public void setViewportWidth(float viewportWidth) { this.viewportWidth = viewportWidth; } public float getViewportHeight() { return viewportHeight; } public void setViewportHeight(float viewportHeight) { this.viewportHeight = viewportHeight; } }
5,211
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
GroupModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/model/GroupModel.java
package com.tyron.vectorparser.model; import android.graphics.Canvas; import android.graphics.Matrix; import com.tyron.vectorparser.DefaultValues; import com.tyron.vectorparser.util.Utils; import java.util.ArrayList; public class GroupModel { private String name; private float rotation; private float pivotX, pivotY; private float scaleX, scaleY; private float translateX, translateY; private Matrix scaleMatrix; private Matrix originalTransformMatrix; private Matrix finalTransformMatrix; private GroupModel parent; private ArrayList<GroupModel> groupModels; private ArrayList<PathModel> pathModels; private ArrayList<ClipPathModel> clipPathModels; public GroupModel() { rotation = DefaultValues.GROUP_ROTATION; pivotX = DefaultValues.GROUP_PIVOT_X; pivotY = DefaultValues.GROUP_PIVOT_Y; scaleX = DefaultValues.GROUP_SCALE_X; scaleY = DefaultValues.GROUP_SCALE_Y; translateX = DefaultValues.GROUP_TRANSLATE_X; translateY = DefaultValues.GROUP_TRANSLATE_Y; groupModels = new ArrayList<>(); pathModels = new ArrayList<>(); clipPathModels = new ArrayList<>(); } public void drawPaths(Canvas canvas, float offsetX, float offsetY, float scaleX, float scaleY) { for (ClipPathModel clipPathModel : clipPathModels) { canvas.clipPath(clipPathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY)); } for (GroupModel groupModel : groupModels) { groupModel.drawPaths(canvas, offsetX, offsetY, scaleX, scaleY); } for (PathModel pathModel : pathModels) { if (pathModel.isFillAndStroke()) { pathModel.makeFillPaint(); canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); pathModel.makeStrokePaint(); canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); } else { canvas.drawPath( pathModel.getScaledAndOffsetPath(offsetX, offsetY, scaleX, scaleY), pathModel.getPathPaint()); } } } public void drawPaths(Canvas canvas) { for (ClipPathModel clipPathModel : clipPathModels) { canvas.clipPath(clipPathModel.getPath()); } for (GroupModel groupModel : groupModels) { groupModel.drawPaths(canvas); } for (PathModel pathModel : pathModels) { if (pathModel.isFillAndStroke()) { pathModel.makeFillPaint(); canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); pathModel.makeStrokePaint(); canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); } else { canvas.drawPath(pathModel.getPath(), pathModel.getPathPaint()); } } } public void scaleAllPaths(Matrix scaleMatrix) { this.scaleMatrix = scaleMatrix; finalTransformMatrix = new Matrix(originalTransformMatrix); finalTransformMatrix.postConcat(scaleMatrix); for (GroupModel groupModel : groupModels) { groupModel.scaleAllPaths(scaleMatrix); } for (PathModel pathModel : pathModels) { pathModel.transform(finalTransformMatrix); } for (ClipPathModel clipPathModel : clipPathModels) { clipPathModel.transform(finalTransformMatrix); } } public void scaleAllStrokeWidth(float ratio) { for (GroupModel groupModel : groupModels) { groupModel.scaleAllStrokeWidth(ratio); } for (PathModel pathModel : pathModels) { pathModel.setStrokeRatio(ratio); } } public void buildTransformMatrix() { originalTransformMatrix = new Matrix(); originalTransformMatrix.postScale(scaleX, scaleY, pivotX, pivotY); originalTransformMatrix.postRotate(rotation, pivotX, pivotY); originalTransformMatrix.postTranslate(translateX, translateY); if (parent != null) { originalTransformMatrix.postConcat(parent.getOriginalTransformMatrix()); } for (GroupModel groupModel : groupModels) { groupModel.buildTransformMatrix(); } } public void updateAndScalePaths() { if (scaleMatrix != null) { buildTransformMatrix(); scaleAllPaths(scaleMatrix); } } public GroupModel getGroupModelByName(String name) { GroupModel grpModel = null; for (GroupModel groupModel : groupModels) { if (Utils.isEqual(groupModel.getName(), name)) { grpModel = groupModel; return grpModel; } else { grpModel = groupModel.getGroupModelByName(name); if (grpModel != null) return grpModel; } } return grpModel; } public PathModel getPathModelByName(String name) { PathModel pModel = null; for (PathModel pathModel : pathModels) { if (Utils.isEqual(pathModel.getName(), name)) { return pathModel; } } for (GroupModel groupModel : groupModels) { pModel = groupModel.getPathModelByName(name); if (pModel != null && Utils.isEqual(pModel.getName(), name)) return pModel; } return pModel; } public ClipPathModel getClipPathModelByName(String name) { ClipPathModel cModel = null; for (ClipPathModel clipPathModel : getClipPathModels()) { if (Utils.isEqual(clipPathModel.getName(), name)) { return clipPathModel; } } for (GroupModel groupModel : getGroupModels()) { cModel = groupModel.getClipPathModelByName(name); if (cModel != null && Utils.isEqual(cModel.getName(), name)) return cModel; } return cModel; } public Matrix getOriginalTransformMatrix() { return originalTransformMatrix; } public GroupModel getParent() { return parent; } public void setParent(GroupModel parent) { this.parent = parent; } public void addGroupModel(GroupModel groupModel) { groupModels.add(groupModel); } public ArrayList<GroupModel> getGroupModels() { return groupModels; } public void addPathModel(PathModel pathModel) { pathModels.add(pathModel); } public ArrayList<PathModel> getPathModels() { return pathModels; } public void addClipPathModel(ClipPathModel clipPathModel) { clipPathModels.add(clipPathModel); } public ArrayList<ClipPathModel> getClipPathModels() { return clipPathModels; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getRotation() { return rotation; } public void setRotation(float rotation) { this.rotation = rotation; updateAndScalePaths(); } public float getPivotX() { return pivotX; } public void setPivotX(float pivotX) { this.pivotX = pivotX; } public float getPivotY() { return pivotY; } public void setPivotY(float pivotY) { this.pivotY = pivotY; } public float getScaleX() { return scaleX; } public void setScaleX(float scaleX) { this.scaleX = scaleX; updateAndScalePaths(); } public float getScaleY() { return scaleY; } public void setScaleY(float scaleY) { this.scaleY = scaleY; updateAndScalePaths(); } public float getTranslateX() { return translateX; } public void setTranslateX(float translateX) { this.translateX = translateX; updateAndScalePaths(); } public float getTranslateY() { return translateY; } public void setTranslateY(float translateY) { this.translateY = translateY; updateAndScalePaths(); } }
7,444
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
PathModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/model/PathModel.java
package com.tyron.vectorparser.model; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.RectF; import com.tyron.vectorparser.DefaultValues; import com.tyron.vectorparser.util.PathParser; import com.tyron.vectorparser.util.Utils; public class PathModel { private String name; private float fillAlpha; private int fillColor; private Path.FillType fillType; private String pathData; private float trimPathStart, trimPathEnd, trimPathOffset; private float strokeAlpha; private int strokeColor; private Paint.Cap strokeLineCap; private Paint.Join strokeLineJoin; private float strokeMiterLimit; private float strokeWidth; private float strokeRatio; private boolean isFillAndStroke = false; // Support for trim-paths is not available private Path originalPath; private Path path; private Path trimmedPath; private Paint pathPaint; private Matrix scaleMatrix; public PathModel() { fillAlpha = DefaultValues.PATH_FILL_ALPHA; fillColor = DefaultValues.PATH_FILL_COLOR; fillType = DefaultValues.PATH_FILL_TYPE; trimPathStart = DefaultValues.PATH_TRIM_PATH_START; trimPathEnd = DefaultValues.PATH_TRIM_PATH_END; trimPathOffset = DefaultValues.PATH_TRIM_PATH_OFFSET; strokeAlpha = DefaultValues.PATH_STROKE_ALPHA; strokeColor = DefaultValues.PATH_STROKE_COLOR; strokeLineCap = DefaultValues.PATH_STROKE_LINE_CAP; strokeLineJoin = DefaultValues.PATH_STROKE_LINE_JOIN; strokeMiterLimit = DefaultValues.PATH_STROKE_MITER_LIMIT; strokeWidth = DefaultValues.PATH_STROKE_WIDTH; strokeRatio = DefaultValues.PATH_STROKE_RATIO; pathPaint = new Paint(); pathPaint.setAntiAlias(true); updatePaint(); } public void buildPath(boolean useLegacyParser) { originalPath = PathParser.doPath(pathData); if (originalPath != null) originalPath.setFillType(fillType); path = new Path(originalPath); } public void updatePaint() { pathPaint.setStrokeWidth(strokeWidth * strokeRatio); if (fillColor != Color.TRANSPARENT && strokeColor != Color.TRANSPARENT) { isFillAndStroke = true; } else if (fillColor != Color.TRANSPARENT) { pathPaint.setColor(fillColor); pathPaint.setAlpha(Utils.getAlphaFromFloat(fillAlpha)); pathPaint.setStyle(Paint.Style.FILL); isFillAndStroke = false; } else if (strokeColor != Color.TRANSPARENT) { pathPaint.setColor(strokeColor); pathPaint.setAlpha(Utils.getAlphaFromFloat(strokeAlpha)); pathPaint.setStyle(Paint.Style.STROKE); isFillAndStroke = false; } else { pathPaint.setColor(Color.TRANSPARENT); } pathPaint.setStrokeCap(strokeLineCap); pathPaint.setStrokeJoin(strokeLineJoin); pathPaint.setStrokeMiter(strokeMiterLimit); } public void makeStrokePaint() { pathPaint.setColor(strokeColor); pathPaint.setAlpha(Utils.getAlphaFromFloat(strokeAlpha)); pathPaint.setStyle(Paint.Style.STROKE); } public void makeFillPaint() { pathPaint.setColor(fillColor); pathPaint.setAlpha(Utils.getAlphaFromFloat(fillAlpha)); pathPaint.setStyle(Paint.Style.FILL); } public void transform(Matrix matrix) { scaleMatrix = matrix; trimPath(); } public void trimPath() { if (scaleMatrix != null) { if (trimPathStart == 0 && trimPathEnd == 1 && trimPathOffset == 0) { path = new Path(originalPath); path.transform(scaleMatrix); } else { PathMeasure pathMeasure = new PathMeasure(originalPath, false); float length = pathMeasure.getLength(); trimmedPath = new Path(); pathMeasure.getSegment( (trimPathStart + trimPathOffset) * length, (trimPathEnd + trimPathOffset) * length, trimmedPath, true); path = new Path(trimmedPath); path.transform(scaleMatrix); } } } public Path getTrimmedPath() { return trimmedPath; } public void setTrimmedPath(Path trimmedPath) { this.trimmedPath = trimmedPath; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Path getScaledAndOffsetPath(float offsetX, float offsetY, float scaleX, float scaleY) { Path newPath = new Path(path); newPath.offset(offsetX, offsetY); newPath.transform(getScaleMatrix(newPath, scaleX, scaleY)); return newPath; } public Matrix getScaleMatrix(Path srcPath, float scaleX, float scaleY) { Matrix scaleMatrix = new Matrix(); RectF rectF = new RectF(); srcPath.computeBounds(rectF, true); scaleMatrix.setScale(scaleX, scaleY, rectF.left, rectF.top); return scaleMatrix; } public Paint getPathPaint() { return pathPaint; } public void setPathPaint(Paint pathPaint) { this.pathPaint = pathPaint; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getFillAlpha() { return fillAlpha; } public void setFillAlpha(float fillAlpha) { this.fillAlpha = fillAlpha; updatePaint(); } public int getFillColor() { return fillColor; } public void setFillColor(int fillColor) { this.fillColor = fillColor; updatePaint(); } public Path.FillType getFillType() { return fillType; } public void setFillType(Path.FillType fillType) { this.fillType = fillType; if (originalPath != null) originalPath.setFillType(fillType); } public String getPathData() { return pathData; } public void setPathData(String pathData) { this.pathData = pathData; } public float getTrimPathStart() { return trimPathStart; } public void setTrimPathStart(float trimPathStart) { this.trimPathStart = trimPathStart; trimPath(); } public float getTrimPathEnd() { return trimPathEnd; } public void setTrimPathEnd(float trimPathEnd) { this.trimPathEnd = trimPathEnd; trimPath(); } public float getTrimPathOffset() { return trimPathOffset; } public void setTrimPathOffset(float trimPathOffset) { this.trimPathOffset = trimPathOffset; trimPath(); } public float getStrokeAlpha() { return strokeAlpha; } public void setStrokeAlpha(float strokeAlpha) { this.strokeAlpha = strokeAlpha; updatePaint(); } public int getStrokeColor() { return strokeColor; } public void setStrokeColor(int strokeColor) { this.strokeColor = strokeColor; updatePaint(); } public Paint.Cap getStrokeLineCap() { return strokeLineCap; } public void setStrokeLineCap(Paint.Cap strokeLineCap) { this.strokeLineCap = strokeLineCap; updatePaint(); } public Paint.Join getStrokeLineJoin() { return strokeLineJoin; } public void setStrokeLineJoin(Paint.Join strokeLineJoin) { this.strokeLineJoin = strokeLineJoin; updatePaint(); } public float getStrokeMiterLimit() { return strokeMiterLimit; } public void setStrokeMiterLimit(float strokeMiterLimit) { this.strokeMiterLimit = strokeMiterLimit; updatePaint(); } public float getStrokeWidth() { return strokeWidth; } public void setStrokeWidth(float strokeWidth) { this.strokeWidth = strokeWidth; updatePaint(); } public float getStrokeRatio() { return strokeRatio; } public void setStrokeRatio(float strokeRatio) { this.strokeRatio = strokeRatio; updatePaint(); } public boolean isFillAndStroke() { return isFillAndStroke; } }
7,629
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ClipPathModel.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/vector-parser/src/main/java/com/tyron/vectorparser/model/ClipPathModel.java
package com.tyron.vectorparser.model; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import com.tyron.vectorparser.util.PathParser; public class ClipPathModel { private String name; private String pathData; private Path originalPath; private Path path; private Paint clipPaint; public ClipPathModel() { path = new Path(); clipPaint = new Paint(); clipPaint.setAntiAlias(true); clipPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } public void buildPath(boolean useLegacyParser) { originalPath = PathParser.doPath(pathData); path = new Path(originalPath); } public void transform(Matrix matrix) { path = new Path(originalPath); path.transform(matrix); } public Paint getClipPaint() { return clipPaint; } public void setClipPaint(Paint clipPaint) { this.clipPaint = clipPaint; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPathData() { return pathData; } public void setPathData(String pathData) { this.pathData = pathData; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Path getScaledAndOffsetPath(float offsetX, float offsetY, float scaleX, float scaleY) { Path newPath = new Path(path); newPath.offset(offsetX, offsetY); newPath.transform(getScaleMatrix(newPath, scaleX, scaleY)); return newPath; } public Matrix getScaleMatrix(Path srcPath, float scaleX, float scaleY) { Matrix scaleMatrix = new Matrix(); RectF rectF = new RectF(); srcPath.computeBounds(rectF, true); scaleMatrix.setScale(scaleX, scaleY, rectF.left, rectF.top); return scaleMatrix; } }
1,935
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ConstraintLayoutModule.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/constraintlayout/src/main/java/com/tyron/layout/constraintlayout/ConstraintLayoutModule.java
package com.tyron.layout.constraintlayout; import com.flipkart.android.proteus.ProteusBuilder; import com.tyron.layout.constraintlayout.widget.ConstraintLayoutParser; public class ConstraintLayoutModule implements ProteusBuilder.Module { private ConstraintLayoutModule() {} public static ConstraintLayoutModule create() { return new ConstraintLayoutModule(); } @Override public void registerWith(ProteusBuilder builder) { builder.register(new ConstraintLayoutParser<>()); } }
501
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProteusConstraintLayout.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/constraintlayout/src/main/java/com/tyron/layout/constraintlayout/view/ProteusConstraintLayout.java
package com.tyron.layout.constraintlayout.view; import static com.flipkart.android.proteus.ProteusView.*; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import com.flipkart.android.proteus.ProteusView; public class ProteusConstraintLayout extends ConstraintLayout implements ProteusView { private Manager manager; public ProteusConstraintLayout(Context context) { super(context); } @Override public Manager getViewManager() { return manager; } @NonNull @Override public void setViewManager(@NonNull Manager manager) { this.manager = manager; } @NonNull @Override public View getAsView() { return this; } }
763
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ConstraintLayoutParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/constraintlayout/src/main/java/com/tyron/layout/constraintlayout/widget/ConstraintLayoutParser.java
package com.tyron.layout.constraintlayout.widget; import static androidx.constraintlayout.widget.ConstraintLayout.*; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import com.flipkart.android.proteus.ProteusContext; import com.flipkart.android.proteus.ProteusView; import com.flipkart.android.proteus.ViewTypeParser; import com.flipkart.android.proteus.parser.ParseHelper; import com.flipkart.android.proteus.processor.NumberAttributeProcessor; import com.flipkart.android.proteus.processor.StringAttributeProcessor; import com.flipkart.android.proteus.toolbox.ProteusHelper; import com.flipkart.android.proteus.value.Layout; import com.flipkart.android.proteus.value.ObjectValue; import com.tyron.layout.constraintlayout.view.ProteusConstraintLayout; public class ConstraintLayoutParser<T extends View> extends ViewTypeParser<T> { @NonNull @Override public String getType() { return "androidx.constraintlayout.widget.ConstraintLayout"; } @Nullable @Override public String getParentType() { return "android.view.ViewGroup"; } @NonNull @Override public ProteusView createView( @NonNull ProteusContext context, @NonNull Layout layout, @NonNull ObjectValue data, @Nullable ViewGroup parent, int dataIndex) { return new ProteusConstraintLayout(context); } @Override protected void addAttributeProcessors() { addLayoutParamsAttributeProcessor( "app:layout_constraintLeft_toLeftOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).leftToLeft = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintLeft_toRightOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).leftToRight = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintRight_toLeftOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).rightToLeft = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintRight_toRightOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).rightToRight = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintStart_toStartOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).startToStart = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintStart_toEndOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).startToEnd = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintEnd_toStartOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).endToStart = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintEnd_toEndOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).endToEnd = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); ; } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintBottom_toBottomOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).bottomToBottom = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintBottom_toTopOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).bottomToTop = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintTop_toBottomOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).topToBottom = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintTop_toTopOf", new StringAttributeProcessor<T>() { @Override public void setString(T view, String value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).topToTop = value.equals("parent") ? ConstraintLayout.LayoutParams.PARENT_ID : ProteusHelper.getProteusContext(view) .getInflater() .getUniqueViewId(ParseHelper.parseViewId(value)); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintVertical_bias", new NumberAttributeProcessor<T>() { @Override public void setNumber(T view, @NonNull Number value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).verticalBias = value.floatValue(); } } }); addLayoutParamsAttributeProcessor( "app:layout_constraintHorizontal_bias", new NumberAttributeProcessor<T>() { @Override public void setNumber(T view, @NonNull Number value) { if (view.getLayoutParams() instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) view.getLayoutParams()).horizontalBias = value.floatValue(); } } }); } }
10,813
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Editor.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/Editor.java
package com.tyron.editor; import com.tyron.builder.model.DiagnosticWrapper; import com.tyron.builder.project.Project; import java.io.File; import java.util.List; import org.jetbrains.annotations.Nullable; public interface Editor { /** * @return The project this editor is associated with */ @Nullable Project getProject(); /** * Returns a mutable list of diagnostics from this editor * * @return mutable list of diagnostics */ List<DiagnosticWrapper> getDiagnostics(); void setDiagnostics(List<DiagnosticWrapper> diagnostics); boolean isBackgroundAnalysisEnabled(); /** * Get the current file opened in the editor * * @return the file opened in the editor */ File getCurrentFile(); /** * Open the file for editing * * @param file The file, must not be null */ void openFile(File file); /** * Get the CharPosition object containing line and column information from an index * * @param index the index should be > 0 * @return the CharPosition object */ CharPosition getCharPosition(int index); /** * Get the index of the given line and column * * @param line 0-based line * @param column 0-based column * @return the index */ int getCharIndex(int line, int column); /** * @return Whether the editor uses tab instead of white spaces. */ boolean useTab(); int getTabCount(); /** * Inserts the text at the specified line and column * * @param line 0-based line * @param column 0-based column * @param string the text to insert */ void insert(int line, int column, String string); void insertMultilineString(int line, int column, String string); /** * Deletes the text from the start to end * * @param startLine 0-based start line * @param startColumn 0-based start column * @param endLine 0-based end line * @param endColumn 0-based end column */ void delete(int startLine, int startColumn, int endLine, int endColumn); /** * Deletes the text within the specified index * * @param startIndex the start index from the text * @param endIndex the end index from the text */ void delete(int startIndex, int endIndex); /** Replace the given range of line and column with the specified text */ void replace(int line, int column, int endLine, int endColumn, String string); /** * Format the the current text asynchronously * * @return whether the format has been successful. */ boolean formatCodeAsync(); /** * Format a specific range of text asynchronously * * @param startIndex the start index * @param endIndex the end index * @return whether the format has been successful. */ boolean formatCodeAsync(int startIndex, int endIndex); /** * Begin a batch edit where all of the edits made after this call will be registered as one single * action that can be undone */ void beginBatchEdit(); void endBatchEdit(); /** * Get the caret representing the position of the cursor in the editor * * @return the caret object */ Caret getCaret(); /** * @return The object representing the content of the editor */ Content getContent(); // --- CURSOR RELATED --- // /** * Set the cursor position on the specified line and column * * @param line 0-based line * @param column 0-based column */ void setSelection(int line, int column); /** Sets the caret to the specified range */ void setSelectionRegion(int line, int column, int endLine, int endColumn); void setSelectionRegion(int startIndex, int endIndex); void moveSelectionUp(); void moveSelectionDown(); void moveSelectionLeft(); void moveSelectionRight(); /** * Notify the editor to show a progress that it is analyzing in background * * @param analyzing whether to show the progress bar. */ void setAnalyzing(boolean analyzing); void requireCompletion(); }
3,944
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Caret.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/Caret.java
package com.tyron.editor; public interface Caret { int getStart(); int getEnd(); int getStartLine(); int getStartColumn(); int getEndLine(); int getEndColumn(); boolean isSelected(); }
207
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Content.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/Content.java
package com.tyron.editor; public interface Content extends CharSequence { /** * Checks if this content can be redone to the previous action * * @return whether this content can be redone */ boolean canRedo(); /** * Redo the previous action, always check if {@link #canRedo()} returns true before calling this * method. */ void redo(); /** * @return Whether this content can be reverted to the previous action */ boolean canUndo(); /** Revert to the previous action */ void undo(); int getLineCount(); String getLineString(int line); void insert(int line, int column, CharSequence text); void insert(int index, CharSequence text); void delete(int start, int end); void replace(int start, int end, CharSequence text); }
784
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CharPosition.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/CharPosition.java
package com.tyron.editor; public class CharPosition { private final int mLine; private final int mColumn; public CharPosition(int line, int column) { mLine = line; mColumn = column; } public int getLine() { return mLine; } public int getColumn() { return mColumn; } }
305
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Snippet.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/snippet/Snippet.java
package com.tyron.editor.snippet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** A snippet object that can be inserted on the editor */ public class Snippet { private String mName; private String[] mPrefix; private Body mBody; private String mDescription; public String getName() { return mName; } /** * The prefixes that will be used to show this snippet on the code completion list * * @return the array of snippet names */ public String[] getPrefix() { return mPrefix; } public Body getBody() { return mBody; } /** * Retrieve the description of this snippet * * @return The description */ public String getDescription() { return mDescription; } public Snippet copy() { Snippet snippet = new Snippet(); snippet.mName = this.mName; snippet.mBody = this.mBody.copy(); snippet.mDescription = this.mDescription; snippet.mPrefix = this.mPrefix; return snippet; } public interface Text { String getText(Body body); } public static class Body { private Map<String, Variable> mVariables; private List<Text> mInsertTexts; public Body(Map<String, Variable> variables, List<Text> insertTexts) { mVariables = variables; mInsertTexts = insertTexts; } public Variable getVariable(String name) { return mVariables.get(name); } public List<Text> getInsertTexts() { return mInsertTexts; } public Body copy() { return new Body(new HashMap<>(mVariables), new ArrayList<>(mInsertTexts)); } public Map<String, Variable> getVariables() { return mVariables; } } public static class NormalText implements Text { private final String mText; public NormalText(String text) { mText = text; } @Override public String getText(Body body) { return mText; } } public static final Snippet TEST; static { Snippet snippet = new Snippet(); snippet.mName = "Indexed for loop"; snippet.mDescription = "Indexed for loop"; snippet.mPrefix = new String[] {"fori"}; // for (int ${1:name}; ${name} < ${2:size}; ${name}++) { } Map<String, Variable> variableMap = new HashMap<>(); variableMap.put("name", new Variable(1, "name", "")); variableMap.put("size", new Variable(2, "name", "")); List<Text> texts = new ArrayList<>(); texts.add(new NormalText("for (int")); texts.add(variableMap.get("name")); texts.add(new NormalText("; ")); texts.add(variableMap.get("size")); texts.add(new NormalText(" < ")); texts.add(new Variable(-1, "name")); texts.add(new NormalText("++) { }")); snippet.mBody = new Body(variableMap, texts); TEST = snippet; } public static class Variable implements Text { private int mIndex; private String mName; private boolean mIsReference; private String mText; private int startLine; private int startColumn; public Variable(int index, String name) { mIndex = index; mName = name; mIsReference = true; mText = null; } public Variable(int index, String name, String text) { mIndex = index; mName = name; mIsReference = false; mText = text; } public int getStartLine() { return startLine; } public void setStartLine(int line) { this.startLine = line; } public int getStartColumn() { return this.startColumn; } public void setStartColumn(int column) { this.startColumn = column; } public int getIndex() { return mIndex; } private String getName() { return mName; } /** * @return Whether this variable references another variable defined in this Snippet */ public boolean isReference() { return mIsReference; } @Override public String getText(Body body) { if (isReference()) { Variable variable = body.getVariable(getName()); if (variable != null) { return variable.getText(body); } } return mText; } } }
4,156
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ExpandSelectionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/editor-api/src/main/java/com/tyron/editor/selection/ExpandSelectionProvider.java
package com.tyron.editor.selection; import com.google.common.collect.Range; import com.tyron.editor.Editor; import com.tyron.language.api.Language; import com.tyron.language.fileTypes.FileTypeManager; import com.tyron.language.fileTypes.LanguageFileType; import java.io.File; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class ExpandSelectionProvider { private static final Map<Language, ExpandSelectionProvider> sRegisteredProviders = new ConcurrentHashMap<>(); @Nullable public abstract Range<Integer> expandSelection(Editor editor); public static ExpandSelectionProvider forEditor(Editor editor) { File currentFile = editor.getCurrentFile(); if (currentFile == null) { return null; } LanguageFileType fileType = FileTypeManager.getInstance().findFileType(currentFile); if (fileType == null) { return null; } return sRegisteredProviders.get(fileType.getLanguage()); } public static boolean hasProvider(File file) { LanguageFileType fileType = FileTypeManager.getInstance().findFileType(file); if (fileType == null) { return false; } return sRegisteredProviders.get(fileType.getLanguage()) != null; } public static void registerProvider( @NotNull Language language, @NotNull ExpandSelectionProvider provider) { ExpandSelectionProvider previous = sRegisteredProviders.putIfAbsent(language, provider); if (previous != null) { throw new IllegalArgumentException( "ExpandSelectionProvider for " + language + " is already registered."); } } }
1,691
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlRepository.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/XmlRepository.java
package com.tyron.completion.xml; import android.view.View; import android.view.ViewGroup; import android.widget.AbsoluteLayout; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.ViewSwitcher; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.completion.index.CompilerService; import com.tyron.completion.xml.model.AttributeInfo; import com.tyron.completion.xml.model.DeclareStyleable; import com.tyron.completion.xml.model.Format; import com.tyron.completion.xml.util.StyleUtils; import com.tyron.xml.completion.repository.ResourceRepository; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; public class XmlRepository { private final Map<String, DeclareStyleable> mDeclareStyleables = new TreeMap<>(); private final Map<String, DeclareStyleable> mManifestAttrs = new TreeMap<>(); private final Map<String, AttributeInfo> mExtraAttributes = new TreeMap<>(); private final Map<String, JavaClass> mJavaViewClasses = new TreeMap<>(); private boolean mInitialized = false; private ResourceRepository mRepository; public XmlRepository() {} @Deprecated public Map<String, DeclareStyleable> getManifestAttrs() { return mManifestAttrs; } @Deprecated public Map<String, DeclareStyleable> getDeclareStyleables() { return mDeclareStyleables; } public Map<String, JavaClass> getJavaViewClasses() { return mJavaViewClasses; } @Deprecated public AttributeInfo getExtraAttribute(String name) { return mExtraAttributes.get(name); } public void initialize(AndroidModule module) throws IOException { if (mInitialized) { return; } BytecodeScanner.scanBootstrapIfNeeded(); mRepository = new ResourceRepository(module); mRepository.initialize(); for (File library : module.getLibraries()) { File parent = library.getParentFile(); if (parent == null) { continue; } File classesFile = new File(parent, "classes.jar"); if (classesFile.exists()) { try { BytecodeScanner.loadJar(classesFile); } catch (IOException ignored) { } } } for (File library : module.getLibraries()) { try { List<JavaClass> scan = BytecodeScanner.scan(library); for (JavaClass javaClass : scan) { StyleUtils.putStyles(javaClass); mJavaViewClasses.put(javaClass.getClassName(), javaClass); } } catch (IOException e) { e.printStackTrace(); } } addFrameworkViews(); Repository.clearCache(); mInitialized = true; } private void addFrameworkViews() { addFrameworkView(View.class); addFrameworkView(ViewGroup.class); addFrameworkView(FrameLayout.class); addFrameworkView(RelativeLayout.class); addFrameworkView(LinearLayout.class); addFrameworkView(AbsoluteLayout.class); addFrameworkView(ListView.class); addFrameworkView(EditText.class); addFrameworkView(Button.class); addFrameworkView(TextView.class); addFrameworkView(ImageView.class); addFrameworkView(ImageButton.class); addFrameworkView(ImageSwitcher.class); addFrameworkView(ViewFlipper.class); addFrameworkView(ViewSwitcher.class); addFrameworkView(ScrollView.class); addFrameworkView(HorizontalScrollView.class); addFrameworkView(CompoundButton.class); addFrameworkView(ProgressBar.class); addFrameworkView(CheckBox.class); } private void addFrameworkView(Class<? extends View> viewClass) { org.apache.bcel.util.Repository repository = Repository.getRepository(); try { JavaClass javaClass = repository.loadClass(viewClass); if (javaClass != null) { mJavaViewClasses.put(javaClass.getClassName(), javaClass); } } catch (ClassNotFoundException e) { // ignored } } private Map<String, DeclareStyleable> parse(Reader reader, String namespace) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(reader); Map<String, DeclareStyleable> declareStyleables = new TreeMap<>(); while (parser.next() != XmlPullParser.END_DOCUMENT) { String name = parser.getName(); if ("declare-styleable".equals(name)) { DeclareStyleable declareStyleable = parseDeclareStyleable(parser, namespace); declareStyleables.put(declareStyleable.getName(), declareStyleable); } else if ("attr".equals(name)) { AttributeInfo attributeInfo = parseAttributeInfo(parser); if (!attributeInfo.getName().contains(":")) { attributeInfo.setNamespace(namespace); } else { String ns = attributeInfo.getName(); String newName = ns.substring(ns.indexOf(':') + 1); ns = attributeInfo.getName().substring(0, ns.indexOf(':')); attributeInfo.setName(newName); attributeInfo.setNamespace(ns); } mExtraAttributes.put(attributeInfo.getName(), attributeInfo); } } return declareStyleables; } private Map<String, DeclareStyleable> parse(File file, String namespace) throws XmlPullParserException, IOException { try (FileReader reader = new FileReader(file)) { return parse(reader, namespace); } } private DeclareStyleable parseDeclareStyleable(XmlPullParser parser, String namespace) throws IOException, XmlPullParserException { String name = getAttributeValue(parser, "name", ""); String parent = getAttributeValue(parser, "parent", ""); Set<AttributeInfo> attributeInfos = new TreeSet<>(); final int depth = parser.getDepth(); int type; while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } String tag = parser.getName(); if ("attr".equals(tag)) { AttributeInfo attributeInfo = parseAttributeInfo(parser); if (!attributeInfo.getName().contains(":")) { attributeInfo.setNamespace(namespace); } else { String ns = attributeInfo.getName(); String newName = ns.substring(ns.indexOf(':') + 1); ns = attributeInfo.getName().substring(0, ns.indexOf(':')); attributeInfo.setName(newName); attributeInfo.setNamespace(ns); } attributeInfos.add(attributeInfo); } } return new DeclareStyleable(name, attributeInfos, parent); } private AttributeInfo parseAttributeInfo(XmlPullParser parser) throws IOException, XmlPullParserException { String name = getAttributeValue(parser, "name", ""); Set<Format> formats = new TreeSet<>(); List<String> values = new ArrayList<>(); String formatString = getAttributeValue(parser, "format", null); if (formatString != null) { formats.addAll(Format.fromString(formatString)); } final int depth = parser.getDepth(); int type; while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } String tag = parser.getName(); if ("enum".equals(tag)) { formats.add(Format.ENUM); String enumName = getAttributeValue(parser, "name", null); if (enumName != null) { values.add(enumName); } } else if ("flag".equals(tag)) { formats.add(Format.FLAG); String flagName = getAttributeValue(parser, "name", null); if (flagName != null) { values.add(flagName); } } else { skip(parser); } } if (formats.contains(Format.BOOLEAN)) { values.add("true"); values.add("false"); } return new AttributeInfo(name, formats, values); } public static String getAttributeValue(XmlPullParser parser, String name, String defaultValue) { int attributeCount = parser.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { String attributeName = parser.getAttributeName(i); String attributeValue = parser.getAttributeValue(i); if (name.equals(attributeName)) { return attributeValue; } } return defaultValue; } public static void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } public ResourceRepository getRepository() { return mRepository; } public static XmlRepository getRepository(Project project, AndroidModule module) throws IOException { XmlIndexProvider indexProvider = CompilerService.getInstance().getIndex(XmlIndexProvider.KEY); XmlRepository repository = indexProvider.get(project, module); repository.initialize(module); return repository; } }
10,169
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlIndexProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/XmlIndexProvider.java
package com.tyron.completion.xml; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.builder.project.api.Module; import com.tyron.completion.index.CompilerProvider; import com.tyron.completion.index.CompilerService; public class XmlIndexProvider extends CompilerProvider<XmlRepository> { @Nullable public static XmlRepository getRepository( @NonNull Project project, @NonNull AndroidModule module) { Object index = CompilerService.getInstance().getIndex(KEY); if (!(index instanceof XmlIndexProvider)) { return null; } XmlIndexProvider provider = ((XmlIndexProvider) index); return provider.get(project, module); } public static final String KEY = XmlIndexProvider.class.getSimpleName(); private XmlRepository mRepository; @Override public XmlRepository get(Project project, Module module) { if (mRepository == null) { mRepository = new XmlRepository(); } return mRepository; } public void clear() { mRepository = null; } }
1,139
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlCharacter.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/XmlCharacter.java
package com.tyron.completion.xml; import java.util.HashSet; import java.util.Set; public class XmlCharacter { public static final Set<Character> sNonXmlCharacters = new HashSet<>(); static { sNonXmlCharacters.add('\t'); sNonXmlCharacters.add('\n'); sNonXmlCharacters.add(' '); } public static boolean isNonXmlCharacterPart(char c) { return sNonXmlCharacters.contains(c); } }
406
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlCompletionModule.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/XmlCompletionModule.java
package com.tyron.completion.xml; import android.content.Context; import android.os.Handler; import android.os.Looper; import com.tyron.actions.ActionManager; import com.tyron.completion.xml.action.context.AndroidManifestAddPermissionsAction; public class XmlCompletionModule { private static Context sApplicationContext; private static final Handler sApplicationHandler = new Handler(Looper.getMainLooper()); public static void registerActions(ActionManager actionManager) { actionManager.registerAction( AndroidManifestAddPermissionsAction.ID, new AndroidManifestAddPermissionsAction()); } public static void initialize(Context context) { sApplicationContext = context.getApplicationContext(); } public static Context getContext() { return sApplicationContext; } public static void post(Runnable runnable) { sApplicationHandler.post(runnable); } }
901
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BytecodeScanner.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/BytecodeScanner.java
package com.tyron.completion.xml; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableSet; import com.tyron.builder.BuildModule; import com.tyron.completion.xml.util.PartialClassParser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; /** * Scans jar files and saves all the class files that extends {@link View} and has the appropriate * constructors to be inflated in XML. */ public class BytecodeScanner { private static final Predicate<String> CLASS_NAME_FILTER = s -> s.endsWith(".class"); private static final Set<String> sIgnoredPaths; static { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add("android"); builder.add("android/util"); builder.add("android/os"); builder.add("android/os/health"); builder.add("android/os/strictmode"); builder.add("android/os/storage"); builder.add("android/graphics"); builder.add("android/graphics/drawable"); builder.add("android/graphics/fonts"); builder.add("android/graphics/pdf"); builder.add("android/graphics/text"); builder.add("android/system"); builder.add("android/content"); builder.add("android/content/res"); builder.add("android/content/pm"); sIgnoredPaths = builder.build(); } public static void loadJar(File jar) throws IOException { try (JarFile jarFile = new JarFile(jar)) { iterateClasses( jarFile, element -> { PartialClassParser classParser = new PartialClassParser(jar.getAbsolutePath(), element.getName()); try { Repository.addClass(classParser.parse()); } catch (IOException e) { // ignored, keep parsing other classes } }); } } public static List<JavaClass> scan(File file) throws IOException { List<JavaClass> viewClasses = new ArrayList<>(); try (JarFile jarFile = new JarFile(file)) { iterateClasses( jarFile, element -> { String fqn = element .getName() .replace('/', '.') .substring(0, element.getName().length() - ".class".length()); try { JavaClass javaClass = Repository.lookupClass(fqn); if (isViewClass(javaClass)) { viewClasses.add(javaClass); } } catch (ClassNotFoundException e) { // should not happen, the class should already be loaded here. } }); } return viewClasses; } public static boolean isViewGroup(JavaClass javaClass) { JavaClass[] superClasses = getSuperClasses(javaClass); return Arrays.stream(superClasses) .anyMatch(it -> ViewGroup.class.getName().equals(it.getClassName())); } public static void scanBootstrapIfNeeded() { if (!needScanBootstrap()) { return; } File androidJar = BuildModule.getAndroidJar(); if (androidJar != null && androidJar.exists()) { try (JarFile jarFile = new JarFile(androidJar)) { iterateClasses( jarFile, element -> { String name = element.getName(); String packagePath = name.substring(0, name.lastIndexOf('/')); if (sIgnoredPaths.contains(packagePath)) { return; } if (packagePath.startsWith("java/")) { return; } PartialClassParser classParser = new PartialClassParser(androidJar.getAbsolutePath(), name); try { Repository.addClass(classParser.parse()); } catch (IOException e) { // ignored, keep parsing other classes } }); } catch (IOException e) { // ignored } } } private static boolean needScanBootstrap() { try { Repository.getRepository().loadClass(View.class); return false; } catch (ClassNotFoundException e) { return true; } } private static boolean isViewClass(JavaClass javaClass) { JavaClass[] superClasses = getSuperClasses(javaClass); return Arrays.stream(superClasses) .anyMatch(it -> View.class.getName().equals(it.getClassName())); } /** * Get the array of java classes even if the root class does not exist * * @param javaClass The java class * @return array of super classes */ public static JavaClass[] getSuperClasses(JavaClass javaClass) { List<JavaClass> superClasses = new ArrayList<>(); JavaClass current = javaClass; while (current != null && current.getSuperclassName() != null) { JavaClass lookupClass; try { lookupClass = Repository.lookupClass(current.getSuperclassName()); } catch (ClassNotFoundException e) { lookupClass = null; } if (lookupClass != null) { superClasses.add(lookupClass); } current = lookupClass; } return superClasses.toArray(new JavaClass[0]); } private static boolean containsViewConstructors(Method[] methods) { for (Method method : methods) { if (!"<init>".equals(method.getName())) { continue; } Type[] argumentTypes = method.getArgumentTypes(); if (argumentTypes.length == 2) { if (Context.class.getName().equals(argumentTypes[0].toString())) { if (AttributeSet.class.getName().equals(argumentTypes[1].toString())) { return true; } } } } return false; } public static void iterateClasses(JarFile jarFile, Consumer<JarEntry> consumer) { iterate(jarFile, CLASS_NAME_FILTER, consumer); } public static void iterate( JarFile jarFile, Predicate<String> nameFilter, Consumer<JarEntry> consumer) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (nameFilter.test(entry.getName())) { consumer.accept(entry); } } } }
6,580
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AddPermissions.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/rewrite/AddPermissions.java
package com.tyron.completion.xml.rewrite; import static com.tyron.completion.xml.util.XmlUtils.newPullParser; import com.tyron.builder.util.CharSequenceReader; import com.tyron.completion.java.CompilerProvider; import com.tyron.completion.java.rewrite.JavaRewrite; import com.tyron.completion.model.Position; import com.tyron.completion.model.Range; import com.tyron.completion.model.TextEdit; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class AddPermissions implements JavaRewrite { private static final String PERMISSION_TEMPLATE = "<uses-permission android:name=\"%s\" />"; private final Path androidManifest; private final CharSequence androidManifestContents; private final List<String> permissions; public AddPermissions( Path androidManifest, CharSequence androidManifestContents, List<String> permissions) { this.androidManifest = androidManifest; this.androidManifestContents = androidManifestContents; this.permissions = permissions; } @Override public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) { Range manifestClosingTag = findManifestClosingTag(); String permissionsStr = permissions.stream() .map(s -> "\t" + String.format(PERMISSION_TEMPLATE, s)) .collect(Collectors.joining("\n")); TextEdit textEdit = new TextEdit(manifestClosingTag, "\n" + permissionsStr); return Collections.singletonMap(androidManifest, new TextEdit[] {textEdit}); } private Range findManifestClosingTag() { try { XmlPullParser xpp = newPullParser(); xpp.setInput(new CharSequenceReader(androidManifestContents)); int event = xpp.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { if (event == XmlPullParser.START_TAG) { if ("manifest".equals(xpp.getName()) && xpp.getDepth() == 1) { Position position = new Position(xpp.getLineNumber() - 1, xpp.getColumnNumber() - 1); return new Range(position, position); } } event = xpp.next(); } } catch (IOException | XmlPullParserException ignored) { } return Range.NONE; } public static Set<String> getUsedPermissions(CharSequence androidManifestContents) { Set<String> usedPerms = new HashSet<>(); try { XmlPullParser xpp = newPullParser(); xpp.setInput(new CharSequenceReader(androidManifestContents)); int event = xpp.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { if (event == XmlPullParser.START_TAG) { if ("uses-permission".equals(xpp.getName())) { String name = xpp.getAttributeValue(null, "android:name"); if (name != null) { usedPerms.add(name); } } } event = xpp.next(); } } catch (IOException | XmlPullParserException ignored) { } return usedPerms; } }
3,157
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidManifestAddPermissionsAction.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/action/context/AndroidManifestAddPermissionsAction.java
package com.tyron.completion.xml.action.context; import static com.tyron.completion.xml.util.XmlUtils.newPullParser; import androidx.annotation.NonNull; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.tyron.actions.ActionPlaces; import com.tyron.actions.AnAction; import com.tyron.actions.AnActionEvent; import com.tyron.actions.CommonDataKeys; import com.tyron.actions.Presentation; import com.tyron.builder.util.CharSequenceReader; import com.tyron.common.ApplicationProvider; import com.tyron.common.util.Decompress; import com.tyron.completion.java.rewrite.JavaRewrite; import com.tyron.completion.util.RewriteUtil; import com.tyron.completion.xml.R; import com.tyron.completion.xml.XmlCompletionModule; import com.tyron.completion.xml.rewrite.AddPermissions; import com.tyron.completion.xml.util.XmlUtils; import com.tyron.editor.Editor; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class AndroidManifestAddPermissionsAction extends AnAction { public static final String ID = "androidManifestAddPermissionAction"; private static final String MANIFEST_FILE_NAME = "AndroidManifest.xml"; private static File getOrExtractPermissions() { File filesDir = XmlCompletionModule.getContext().getFilesDir(); File check = new File(filesDir, "sources/android-34/data/permissions.txt"); if (check.exists()) { return check; } File dest = new File(filesDir, "sources"); Decompress.unzipFromAssets( ApplicationProvider.getApplicationContext(), "android-xml.zip", dest.getAbsolutePath()); return check; } @Override public void update(@NonNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setVisible(false); if (!ActionPlaces.EDITOR.equals(event.getPlace())) { return; } File file = event.getData(CommonDataKeys.FILE); if (file == null || !MANIFEST_FILE_NAME.equals(file.getName())) { return; } Editor editor = event.getData(CommonDataKeys.EDITOR); if (editor == null) { return; } XmlPullParser parser; try { parser = newPullParser(); parser.setInput(new CharSequenceReader(editor.getContent())); } catch (XmlPullParserException e) { return; } int depth = XmlUtils.getDepthAtPosition(parser, editor.getCaret().getStartLine() - 1); if (depth != 1) { // depth = 1 means we're right under the <manifest> tag return; } presentation.setVisible(true); presentation.setText(event.getDataContext().getString(R.string.menu_quickfix_add_permissions)); } @Override public void actionPerformed(@NonNull AnActionEvent event) { Editor editor = event.getRequiredData(CommonDataKeys.EDITOR); File file = event.getRequiredData(CommonDataKeys.FILE); List<String> permissions; try { permissions = FileUtils.readLines(getOrExtractPermissions(), StandardCharsets.UTF_8); } catch (IOException e) { return; } for (String usedPerm : AddPermissions.getUsedPermissions(editor.getContent())) { permissions.remove(usedPerm); } boolean[] selectedPermissions = new boolean[permissions.size()]; new MaterialAlertDialogBuilder(event.getDataContext()) .setTitle(event.getDataContext().getString(R.string.menu_quickfix_add_permissions)) .setMultiChoiceItems( permissions.toArray(new String[0]), selectedPermissions, (dialog, which, isChecked) -> { selectedPermissions[which] = isChecked; }) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton( android.R.string.ok, (dialog, which) -> { List<String> selected = new ArrayList<>(); for (int i = 0; i < permissions.size(); i++) { if (selectedPermissions[i]) { selected.add(permissions.get(i)); } } JavaRewrite rewrite = new AddPermissions(file.toPath(), editor.getContent(), selected); RewriteUtil.performRewrite(editor, file, null, rewrite); }) .show(); } }
4,412
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
InjectResourcesTask.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/task/InjectResourcesTask.java
package com.tyron.completion.xml.task; import androidx.annotation.NonNull; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ListMultimap; import com.google.common.collect.Table; import com.tyron.builder.compiler.incremental.resource.IncrementalAapt2Task; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.builder.compiler.symbol.SymbolLoader; import com.tyron.builder.compiler.symbol.SymbolWriter; import com.tyron.builder.model.SourceFileObject; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.builder.project.api.FileManager; import com.tyron.completion.java.JavaCompilerProvider; import com.tyron.completion.java.compiler.JavaCompilerService; import com.tyron.completion.xml.XmlRepository; import com.tyron.xml.completion.repository.ResourceItem; import com.tyron.xml.completion.repository.ResourceRepository; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.StyleableResourceValue; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; /** * Used to create fake R.java files from the project resources for it to show up on code completion. * Files generated from this task should not be included in the compilation process as the values of * the fields are not accurate from what AAPT2 generates. */ public class InjectResourcesTask { public static void inject(@NonNull Project project) throws IOException { inject(project, (AndroidModule) project.getMainModule()); } public static void inject(@NonNull Project project, @NonNull AndroidModule module) throws IOException { JavaCompilerService service = JavaCompilerProvider.get(project, module); if (service == null) { return; } InjectResourcesTask task = new InjectResourcesTask(project, module); task.inject( resourceFile -> { if (project.isCompiling() || project.isIndexing()) { return; } SourceFileObject sourceFileObject = new SourceFileObject(resourceFile.toPath(), module, Instant.now()); service.compile(Collections.singletonList(sourceFileObject)); }); } private final AndroidModule mModule; private final Project mProject; public InjectResourcesTask(Project project, AndroidModule module) { mProject = project; mModule = module; } public void inject(Consumer<File> consumer) throws IOException { XmlRepository xmlRepository = XmlRepository.getRepository(mProject, mModule); updateSymbols(xmlRepository); String classContents = createSymbols(xmlRepository); File classFile = getOrCreateResourceClass(mModule); FileUtils.writeStringToFile(classFile, classContents, StandardCharsets.UTF_8); mModule.addInjectedClass(classFile); consumer.accept(classFile); } private void updateSymbols(XmlRepository xmlRepository) throws IOException { Map<String, List<File>> files = IncrementalAapt2Task.getFiles(mModule, IncrementalAapt2Task.getOutputDirectory(mModule)); List<File> allFiles = files.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); allFiles.forEach( it -> { ResourceRepository repository = xmlRepository.getRepository(); try { FileManager fileManager = mModule.getFileManager(); CharSequence contents = null; if (fileManager.isOpened(it)) { Optional<CharSequence> fileContent = fileManager.getFileContent(it); if (fileContent.isPresent()) { contents = fileContent.get(); } } else { contents = FileUtils.readFileToString(it, StandardCharsets.UTF_8); } repository.updateFile(it, contents.toString()); } catch (IOException e) { // ignored } }); } private String createSymbols(XmlRepository xmlRepository) throws IOException { ResourceRepository repository = xmlRepository.getRepository(); List<ResourceType> resourceTypes = repository.getResourceTypes(); int id = 0; Table<String, String, SymbolLoader.SymbolEntry> symbols = HashBasedTable.create(); for (ResourceType resourceType : resourceTypes) { if (!resourceType.getCanBeReferenced() && resourceType != ResourceType.STYLEABLE) { continue; } ListMultimap<String, ResourceItem> resources = repository.getResources(repository.getNamespace(), resourceType); if (resources.values().isEmpty()) { continue; } for (Map.Entry<String, ResourceItem> resourceItemEntry : resources.entries()) { addResource(id, repository.getNamespace(), symbols, resourceType, resourceItemEntry); id++; } } SymbolLoader loader = new SymbolLoader(symbols); SymbolWriter symbolWriter = new SymbolWriter(null, mModule.getNameSpace(), loader, null); symbolWriter.addSymbolsToWrite(loader); return symbolWriter.getString(); } private void addResource( int id, ResourceNamespace namespace, Table<String, String, SymbolLoader.SymbolEntry> symbols, ResourceType resourceType, Map.Entry<String, ResourceItem> resourceItemEntry) { if (resourceType == ResourceType.STYLEABLE) { addStyleableResource(id, namespace, symbols, resourceItemEntry); return; } ResourceItem value = resourceItemEntry.getValue(); String replacedName = convertName(value.getName()); SymbolLoader.SymbolEntry entry = new SymbolLoader.SymbolEntry(replacedName, getType(resourceType), String.valueOf(id)); symbols.put(resourceType.getName(), replacedName, entry); } private void addStyleableResource( int id, ResourceNamespace namespace, Table<String, String, SymbolLoader.SymbolEntry> symbols, Map.Entry<String, ResourceItem> resourceItemEntry) { ResourceItem value = resourceItemEntry.getValue(); if (!(value.getResourceValue() instanceof StyleableResourceValue)) { return; } StyleableResourceValue styleable = ((StyleableResourceValue) value.getResourceValue()); String valueItem = "new int[" + styleable.getAllAttributes().size() + "];"; String replacedName = convertName(value.getName()); SymbolLoader.SymbolEntry entry = new SymbolLoader.SymbolEntry(replacedName, "int[]", valueItem); symbols.put(ResourceType.STYLEABLE.getName(), replacedName, entry); for (AttrResourceValue attr : styleable.getAllAttributes()) { String name = attr.getName(); if (name.isEmpty()) { continue; } String replace = name.replace(':', '_'); String attrName = replacedName + (replace.isEmpty() ? "" : "_" + replace); SymbolLoader.SymbolEntry attrEntry = new SymbolLoader.SymbolEntry(attrName, "int", "0"); symbols.put(ResourceType.STYLEABLE.getName(), attrName, attrEntry); } } private static String getType(ResourceType type) { return "int"; } private static String convertName(String name) { if (!name.contains(".")) { return name; } return name.replace('.', '_'); } public static File getOrCreateResourceClass(AndroidModule module) throws IOException { File outputDirectory = new File(module.getBuildDirectory(), "injected/resource"); if (!outputDirectory.exists() && !outputDirectory.mkdirs()) { throw new IOException("Unable to create directory " + outputDirectory); } File classFile = new File(outputDirectory, "R.java"); if (!classFile.exists() && !classFile.createNewFile()) { throw new IOException("Unable to create " + classFile); } return classFile; } }
8,137
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidManifestCompletionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/providers/AndroidManifestCompletionProvider.java
package com.tyron.completion.xml.providers; import androidx.annotation.NonNull; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.completion.model.CompletionList; import com.tyron.completion.xml.XmlRepository; import com.tyron.completion.xml.model.XmlCompletionType; import com.tyron.completion.xml.util.AndroidAttributeUtils; import com.tyron.completion.xml.util.AndroidXmlTagUtils; import com.tyron.completion.xml.util.AttributeValueUtils; import com.tyron.xml.completion.repository.api.ResourceNamespace; import java.io.File; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; public class AndroidManifestCompletionProvider extends LayoutXmlCompletionProvider { public AndroidManifestCompletionProvider() {} @Override public boolean accept(File file) { return file.isFile() && "AndroidManifest.xml".equals(file.getName()); } @NonNull @Override protected CompletionList.Builder completeInternal( Project project, AndroidModule module, XmlRepository repository, DOMDocument parsed, String prefix, XmlCompletionType completionType, ResourceNamespace namespace, long index) { CompletionList.Builder builder = CompletionList.builder(prefix); switch (completionType) { case TAG: AndroidXmlTagUtils.addManifestTagItems(repository, prefix, builder); break; case ATTRIBUTE: AndroidAttributeUtils.addManifestAttributes( builder, repository.getRepository(), parsed.findNodeAt((int) index), namespace); break; case ATTRIBUTE_VALUE: DOMAttr attr = parsed.findAttrAt((int) index); AttributeValueUtils.addManifestValueItems( repository, prefix, (int) index, attr, namespace, builder); } return builder; } }
1,868
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
EmptyCompletionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/providers/EmptyCompletionProvider.java
package com.tyron.completion.xml.providers; import com.tyron.builder.project.api.AndroidModule; import com.tyron.completion.CompletionParameters; import com.tyron.completion.CompletionProvider; import com.tyron.completion.model.CompletionList; import com.tyron.completion.xml.XmlRepository; import java.io.File; import java.io.IOException; import kotlin.io.FilesKt; /** Only used to listen to updates to files. */ public class EmptyCompletionProvider extends CompletionProvider { @Override public boolean accept(File file) { return "xml".equals(FilesKt.getExtension(file)); } @Override public CompletionList complete(CompletionParameters parameters) { try { doRefresh(parameters); } catch (IOException e) { // ignored } return null; } private void doRefresh(CompletionParameters parameters) throws IOException { File file = parameters.getFile(); XmlRepository repository = XmlRepository.getRepository( parameters.getProject(), (AndroidModule) parameters.getModule()); repository.getRepository().updateFile(file, parameters.getContents()); } }
1,127
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutXmlCompletionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/providers/LayoutXmlCompletionProvider.java
package com.tyron.completion.xml.providers; import static com.tyron.completion.xml.util.XmlUtils.isIncrementalCompletion; import android.annotation.SuppressLint; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.completion.CompletionParameters; import com.tyron.completion.CompletionProvider; import com.tyron.completion.model.CachedCompletion; import com.tyron.completion.model.CompletionList; import com.tyron.completion.xml.XmlRepository; import com.tyron.completion.xml.model.XmlCompletionType; import com.tyron.completion.xml.util.AndroidAttributeUtils; import com.tyron.completion.xml.util.AndroidResourcesUtils; import com.tyron.completion.xml.util.AndroidXmlTagUtils; import com.tyron.completion.xml.util.AttributeValueUtils; import com.tyron.completion.xml.util.XmlUtils; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.util.DOMUtils; import java.io.File; import java.io.IOException; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMNode; import org.eclipse.lemminx.dom.DOMParser; import org.eclipse.lemminx.uriresolver.URIResolverExtensionManager; import org.openjdk.javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xmlpull.v1.XmlPullParserException; @SuppressLint("NewApi") public class LayoutXmlCompletionProvider extends CompletionProvider { private CachedCompletion mCachedCompletion; public LayoutXmlCompletionProvider() {} @Override public boolean accept(File file) { return file.isFile() && AndroidResourcesUtils.isLayoutXMLFile(file); } @Override public CompletionList complete(CompletionParameters params) { if (!(params.getModule() instanceof AndroidModule)) { return CompletionList.EMPTY; } try { XmlRepository repository = XmlRepository.getRepository(params.getProject(), (AndroidModule) params.getModule()); String contents = params.getContents(); ResourceNamespace namespace = ResourceNamespace.fromPackageName(((AndroidModule) params.getModule()).getNameSpace()); DOMDocument parsed = DOMParser.getInstance() .parse(contents, namespace.getXmlNamespaceUri(), new URIResolverExtensionManager()); DOMNode node = parsed.findNodeAt((int) params.getIndex()); XmlCompletionType completionType = XmlUtils.getCompletionType(parsed, params.getIndex()); if (completionType == XmlCompletionType.UNKNOWN) { return CompletionList.EMPTY; } String prefix = XmlUtils.getPrefix(parsed, params.getIndex(), completionType); if (prefix == null) { return CompletionList.EMPTY; } if (isIncrementalCompletion(mCachedCompletion, params)) { CompletionList completionList = mCachedCompletion.getCompletionList(); if (!completionList.items.isEmpty()) { return CompletionList.copy(completionList, prefix); } } CompletionList.Builder builder = completeInternal( params.getProject(), ((AndroidModule) params.getModule()), repository, parsed, prefix, completionType, namespace, params.getIndex()); CompletionList build = builder.build(); mCachedCompletion = new CachedCompletion( params.getFile(), params.getLine(), params.getColumn(), builder.getPrefix(), build); return build; } catch (XmlPullParserException | IOException | ParserConfigurationException | SAXException e) { e.printStackTrace(); } return CompletionList.EMPTY; } @NonNull @RequiresApi(api = Build.VERSION_CODES.N) protected CompletionList.Builder completeInternal( Project project, AndroidModule module, XmlRepository repository, DOMDocument parsed, String prefix, XmlCompletionType completionType, ResourceNamespace namespace, long index) throws XmlPullParserException, IOException, ParserConfigurationException, SAXException { CompletionList.Builder builder = CompletionList.builder(prefix); switch (completionType) { case TAG: AndroidXmlTagUtils.addTagItems(repository, prefix, builder); break; case ATTRIBUTE: AndroidAttributeUtils.addLayoutAttributes( builder, repository.getRepository(), parsed.findNodeAt((int) index), namespace); break; case ATTRIBUTE_VALUE: DOMAttr attr = parsed.findAttrAt((int) index); String uri = DOMUtils.lookupPrefix(attr); ResourceNamespace resourceNamespace = ResourceNamespace.fromNamespaceUri(uri); AttributeValueUtils.addValueItems( project, module, prefix, (int) index, repository, attr, resourceNamespace, namespace, builder); } return builder; } }
5,167
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttributeInsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/insert/AttributeInsertHandler.java
package com.tyron.completion.xml.insert; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.progress.ProgressManager; import com.tyron.editor.Caret; import com.tyron.editor.Editor; public class AttributeInsertHandler extends DefaultXmlInsertHandler { private final String mValueToInsert; public AttributeInsertHandler(CompletionItem item) { this(null, item); } public AttributeInsertHandler(String value, CompletionItem item) { super(item); mValueToInsert = value; } @Override protected void insert(String string, Editor editor, boolean calcSpace) { super.insert(string, editor, calcSpace); Caret caret = editor.getCaret(); int startLine = caret.getStartLine(); int startColumn = caret.getStartColumn(); String lineString = editor.getContent().getLineString(startLine); String substring = lineString.substring(startColumn); if (substring.startsWith("=\"\"")) { editor.setSelection(startLine, startColumn + 2); } else if (substring.startsWith("=\"")) { // set the selection after the quote editor.setSelection(startLine, startColumn + 2); // insert the missing quote super.insert("\"", editor, false); // move back the selection inside the quote editor.setSelection(caret.getStartLine(), caret.getStartColumn() - 1); } else if (substring.startsWith("=")) { super.insert("\"\"", editor, false); editor.setSelection(startLine, startColumn + 2); } else { super.insert("=\"\"", editor, false); editor.setSelection(startLine, startColumn + 2); } if (mValueToInsert != null) { super.insert(mValueToInsert, editor, false); editor.setSelection(caret.getStartLine(), caret.getStartColumn() + 1); } else { // show completion window for enum/flag values. // the delay must be greater than DirectAccessProps.cancelCompletionNs ProgressManager.getInstance().runLater(editor::requireCompletion, 120); } } }
2,008
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
LayoutTagInsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/insert/LayoutTagInsertHandler.java
package com.tyron.completion.xml.insert; import com.tyron.completion.model.CompletionItem; import com.tyron.editor.Editor; import org.apache.bcel.classfile.JavaClass; public class LayoutTagInsertHandler extends DefaultXmlInsertHandler { private final JavaClass clazz; public LayoutTagInsertHandler(JavaClass clazz, CompletionItem item) { super(item); this.clazz = clazz; } @Override protected void insert(String string, Editor editor, boolean calcSpace) { super.insert(string, editor, calcSpace); } }
530
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ValueInsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/insert/ValueInsertHandler.java
package com.tyron.completion.xml.insert; import com.tyron.completion.model.CompletionItem; import com.tyron.editor.Caret; import com.tyron.editor.Editor; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.AttributeFormat; public class ValueInsertHandler extends DefaultXmlInsertHandler { private final AttrResourceValue attributeInfo; public ValueInsertHandler(AttrResourceValue attributeInfo, CompletionItem item) { super(item); this.attributeInfo = attributeInfo; } @Override protected void insert(String string, Editor editor, boolean calcSpace) { super.insert(string, editor, calcSpace); Caret caret = editor.getCaret(); int line = caret.getStartLine(); int column = caret.getStartColumn(); if (!attributeInfo.getFormats().contains(AttributeFormat.FLAGS)) { String lineString = editor.getContent().getLineString(line); if (lineString.charAt(column) == '"') { editor.setSelection(line, column + 1); editor.insertMultilineString(line, column + 1, "\n"); } } } }
1,111
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DefaultXmlInsertHandler.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/insert/DefaultXmlInsertHandler.java
package com.tyron.completion.xml.insert; import com.tyron.completion.DefaultInsertHandler; import com.tyron.completion.model.CompletionItem; import com.tyron.editor.Caret; import com.tyron.editor.Editor; import java.util.function.Predicate; public class DefaultXmlInsertHandler extends DefaultInsertHandler { private static final Predicate<Character> DEFAULT_PREDICATE = ch -> Character.isJavaIdentifierPart(ch) || ch == '@' || ch == '<' || ch == '/' || ch == ':' || ch == '.'; public DefaultXmlInsertHandler(CompletionItem item) { super(DEFAULT_PREDICATE, item); } @Override protected void deletePrefix(Editor editor) { Caret caret = editor.getCaret(); String lineString = editor.getContent().getLineString(caret.getStartLine()); String prefix = getPrefix(lineString, getCharPosition(caret)); int length = prefix.length(); editor.delete( caret.getStartLine(), caret.getStartColumn() - length, caret.getStartLine(), caret.getStartColumn()); } }
1,104
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XMLLexer.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/lexer/XMLLexer.java
// Generated from // C:/Users/admin/StudioProjects/CodeAssist/app/src/main/java/com/tyron/code/ui/editor/language/xml\XMLLexer.g4 by ANTLR 4.9.1 package com.tyron.completion.xml.lexer; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class XMLLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.9.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int COMMENT = 1, CDATA = 2, DTD = 3, EntityRef = 4, CharRef = 5, SEA_WS = 6, OPEN = 7, XMLDeclOpen = 8, TEXT = 9, CLOSE = 10, SPECIAL_CLOSE = 11, SLASH_CLOSE = 12, SLASH = 13, EQUALS = 14, STRING = 15, Name = 16, S = 17, ATTRIBUTE = 18, PI = 19; public static final int INSIDE = 1, PROC_INSTR = 2; public static String[] channelNames = {"DEFAULT_TOKEN_CHANNEL", "HIDDEN"}; public static String[] modeNames = {"DEFAULT_MODE", "INSIDE", "PROC_INSTR"}; private static String[] makeRuleNames() { return new String[] { "COMMENT", "CDATA", "DTD", "EntityRef", "CharRef", "SEA_WS", "OPEN", "XMLDeclOpen", "SPECIAL_OPEN", "TEXT", "CLOSE", "SPECIAL_CLOSE", "SLASH_CLOSE", "SLASH", "EQUALS", "STRING", "Name", "S", "ATTRIBUTE", "HEXDIGIT", "DIGIT", "NameChar", "NameStartChar", "PI", "IGNORE" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, null, null, null, null, null, null, "'<'", null, null, "'>'", null, "'/>'", "'/'", "'='" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "COMMENT", "CDATA", "DTD", "EntityRef", "CharRef", "SEA_WS", "OPEN", "XMLDeclOpen", "TEXT", "CLOSE", "SPECIAL_CLOSE", "SLASH_CLOSE", "SLASH", "EQUALS", "STRING", "Name", "S", "ATTRIBUTE", "PI" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public XMLLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache); } @Override public String getGrammarFileName() { return "XMLLexer.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\25\u00f2\b\1\b\1" + "\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4" + "\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t" + "\21\4\22\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t" + "\30\4\31\t\31\4\32\t\32\3\2\3\2\3\2\3\2\3\2\3\2\7\2>\n\2\f\2\16\2A\13" + "\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\7\3R\n" + "\3\f\3\16\3U\13\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\7\4_\n\4\f\4\16\4b\13" + "\4\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6\6\6p\n\6\r\6\16\6q" + "\3\6\3\6\3\6\3\6\3\6\3\6\3\6\6\6{\n\6\r\6\16\6|\3\6\3\6\5\6\u0081\n\6" + "\3\7\3\7\5\7\u0085\n\7\3\7\6\7\u0088\n\7\r\7\16\7\u0089\3\b\3\b\3\b\3" + "\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3\n" + "\3\n\3\13\6\13\u00a3\n\13\r\13\16\13\u00a4\3\f\3\f\3\f\3\f\3\r\3\r\3\r" + "\3\r\3\r\3\16\3\16\3\16\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\7\21\u00bb" + "\n\21\f\21\16\21\u00be\13\21\3\21\3\21\3\21\7\21\u00c3\n\21\f\21\16\21" + "\u00c6\13\21\3\21\5\21\u00c9\n\21\3\22\3\22\7\22\u00cd\n\22\f\22\16\22" + "\u00d0\13\22\3\23\3\23\3\23\3\23\3\24\6\24\u00d7\n\24\r\24\16\24\u00d8" + "\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\27\3\27\5\27\u00e5\n\27\3\30" + "\5\30\u00e8\n\30\3\31\3\31\3\31\3\31\3\31\3\32\3\32\3\32\3\32\5?S`\2\33" + "\5\3\7\4\t\5\13\6\r\7\17\b\21\t\23\n\25\2\27\13\31\f\33\r\35\16\37\17" + "!\20#\21%\22\'\23)\24+\2-\2/\2\61\2\63\25\65\2\5\2\3\4\f\4\2\13\13\"\"" + "\4\2((>>\4\2$$>>\4\2))>>\5\2\13\f\17\17\"\"\5\2\62;CHch\3\2\62;\4\2/\60" + "aa\5\2\u00b9\u00b9\u0302\u0371\u2041\u2042\n\2<<C\\c|\u2072\u2191\u2c02" + "\u2ff1\u3003\ud801\uf902\ufdd1\ufdf2\uffff\2\u00fd\2\5\3\2\2\2\2\7\3\2" + "\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2" + "\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\3\31\3\2\2\2\3\33\3\2\2\2\3\35\3" + "\2\2\2\3\37\3\2\2\2\3!\3\2\2\2\3#\3\2\2\2\3%\3\2\2\2\3\'\3\2\2\2\3)\3" + "\2\2\2\4\63\3\2\2\2\4\65\3\2\2\2\5\67\3\2\2\2\7F\3\2\2\2\tZ\3\2\2\2\13" + "g\3\2\2\2\r\u0080\3\2\2\2\17\u0087\3\2\2\2\21\u008b\3\2\2\2\23\u008f\3" + "\2\2\2\25\u0099\3\2\2\2\27\u00a2\3\2\2\2\31\u00a6\3\2\2\2\33\u00aa\3\2" + "\2\2\35\u00af\3\2\2\2\37\u00b4\3\2\2\2!\u00b6\3\2\2\2#\u00c8\3\2\2\2%" + "\u00ca\3\2\2\2\'\u00d1\3\2\2\2)\u00d6\3\2\2\2+\u00dc\3\2\2\2-\u00de\3" + "\2\2\2/\u00e4\3\2\2\2\61\u00e7\3\2\2\2\63\u00e9\3\2\2\2\65\u00ee\3\2\2" + "\2\678\7>\2\289\7#\2\29:\7/\2\2:;\7/\2\2;?\3\2\2\2<>\13\2\2\2=<\3\2\2" + "\2>A\3\2\2\2?@\3\2\2\2?=\3\2\2\2@B\3\2\2\2A?\3\2\2\2BC\7/\2\2CD\7/\2\2" + "DE\7@\2\2E\6\3\2\2\2FG\7>\2\2GH\7#\2\2HI\7]\2\2IJ\7E\2\2JK\7F\2\2KL\7" + "C\2\2LM\7V\2\2MN\7C\2\2NO\7]\2\2OS\3\2\2\2PR\13\2\2\2QP\3\2\2\2RU\3\2" + "\2\2ST\3\2\2\2SQ\3\2\2\2TV\3\2\2\2US\3\2\2\2VW\7_\2\2WX\7_\2\2XY\7@\2" + "\2Y\b\3\2\2\2Z[\7>\2\2[\\\7#\2\2\\`\3\2\2\2]_\13\2\2\2^]\3\2\2\2_b\3\2" + "\2\2`a\3\2\2\2`^\3\2\2\2ac\3\2\2\2b`\3\2\2\2cd\7@\2\2de\3\2\2\2ef\b\4" + "\2\2f\n\3\2\2\2gh\7(\2\2hi\5%\22\2ij\7=\2\2j\f\3\2\2\2kl\7(\2\2lm\7%\2" + "\2mo\3\2\2\2np\5-\26\2on\3\2\2\2pq\3\2\2\2qo\3\2\2\2qr\3\2\2\2rs\3\2\2" + "\2st\7=\2\2t\u0081\3\2\2\2uv\7(\2\2vw\7%\2\2wx\7z\2\2xz\3\2\2\2y{\5+\25" + "\2zy\3\2\2\2{|\3\2\2\2|z\3\2\2\2|}\3\2\2\2}~\3\2\2\2~\177\7=\2\2\177\u0081" + "\3\2\2\2\u0080k\3\2\2\2\u0080u\3\2\2\2\u0081\16\3\2\2\2\u0082\u0088\t" + "\2\2\2\u0083\u0085\7\17\2\2\u0084\u0083\3\2\2\2\u0084\u0085\3\2\2\2\u0085" + "\u0086\3\2\2\2\u0086\u0088\7\f\2\2\u0087\u0082\3\2\2\2\u0087\u0084\3\2" + "\2\2\u0088\u0089\3\2\2\2\u0089\u0087\3\2\2\2\u0089\u008a\3\2\2\2\u008a" + "\20\3\2\2\2\u008b\u008c\7>\2\2\u008c\u008d\3\2\2\2\u008d\u008e\b\b\3\2" + "\u008e\22\3\2\2\2\u008f\u0090\7>\2\2\u0090\u0091\7A\2\2\u0091\u0092\7" + "z\2\2\u0092\u0093\7o\2\2\u0093\u0094\7n\2\2\u0094\u0095\3\2\2\2\u0095" + "\u0096\5\'\23\2\u0096\u0097\3\2\2\2\u0097\u0098\b\t\3\2\u0098\24\3\2\2" + "\2\u0099\u009a\7>\2\2\u009a\u009b\7A\2\2\u009b\u009c\3\2\2\2\u009c\u009d" + "\5%\22\2\u009d\u009e\3\2\2\2\u009e\u009f\b\n\4\2\u009f\u00a0\b\n\5\2\u00a0" + "\26\3\2\2\2\u00a1\u00a3\n\3\2\2\u00a2\u00a1\3\2\2\2\u00a3\u00a4\3\2\2" + "\2\u00a4\u00a2\3\2\2\2\u00a4\u00a5\3\2\2\2\u00a5\30\3\2\2\2\u00a6\u00a7" + "\7@\2\2\u00a7\u00a8\3\2\2\2\u00a8\u00a9\b\f\6\2\u00a9\32\3\2\2\2\u00aa" + "\u00ab\7A\2\2\u00ab\u00ac\7@\2\2\u00ac\u00ad\3\2\2\2\u00ad\u00ae\b\r\6" + "\2\u00ae\34\3\2\2\2\u00af\u00b0\7\61\2\2\u00b0\u00b1\7@\2\2\u00b1\u00b2" + "\3\2\2\2\u00b2\u00b3\b\16\6\2\u00b3\36\3\2\2\2\u00b4\u00b5\7\61\2\2\u00b5" + " \3\2\2\2\u00b6\u00b7\7?\2\2\u00b7\"\3\2\2\2\u00b8\u00bc\7$\2\2\u00b9" + "\u00bb\n\4\2\2\u00ba\u00b9\3\2\2\2\u00bb\u00be\3\2\2\2\u00bc\u00ba\3\2" + "\2\2\u00bc\u00bd\3\2\2\2\u00bd\u00bf\3\2\2\2\u00be\u00bc\3\2\2\2\u00bf" + "\u00c9\7$\2\2\u00c0\u00c4\7)\2\2\u00c1\u00c3\n\5\2\2\u00c2\u00c1\3\2\2" + "\2\u00c3\u00c6\3\2\2\2\u00c4\u00c2\3\2\2\2\u00c4\u00c5\3\2\2\2\u00c5\u00c7" + "\3\2\2\2\u00c6\u00c4\3\2\2\2\u00c7\u00c9\7)\2\2\u00c8\u00b8\3\2\2\2\u00c8" + "\u00c0\3\2\2\2\u00c9$\3\2\2\2\u00ca\u00ce\5\61\30\2\u00cb\u00cd\5/\27" + "\2\u00cc\u00cb\3\2\2\2\u00cd\u00d0\3\2\2\2\u00ce\u00cc\3\2\2\2\u00ce\u00cf" + "\3\2\2\2\u00cf&\3\2\2\2\u00d0\u00ce\3\2\2\2\u00d1\u00d2\t\6\2\2\u00d2" + "\u00d3\3\2\2\2\u00d3\u00d4\b\23\2\2\u00d4(\3\2\2\2\u00d5\u00d7\7<\2\2" + "\u00d6\u00d5\3\2\2\2\u00d7\u00d8\3\2\2\2\u00d8\u00d6\3\2\2\2\u00d8\u00d9" + "\3\2\2\2\u00d9\u00da\3\2\2\2\u00da\u00db\5%\22\2\u00db*\3\2\2\2\u00dc" + "\u00dd\t\7\2\2\u00dd,\3\2\2\2\u00de\u00df\t\b\2\2\u00df.\3\2\2\2\u00e0" + "\u00e5\5\61\30\2\u00e1\u00e5\t\t\2\2\u00e2\u00e5\5-\26\2\u00e3\u00e5\t" + "\n\2\2\u00e4\u00e0\3\2\2\2\u00e4\u00e1\3\2\2\2\u00e4\u00e2\3\2\2\2\u00e4" + "\u00e3\3\2\2\2\u00e5\60\3\2\2\2\u00e6\u00e8\t\13\2\2\u00e7\u00e6\3\2\2" + "\2\u00e8\62\3\2\2\2\u00e9\u00ea\7A\2\2\u00ea\u00eb\7@\2\2\u00eb\u00ec" + "\3\2\2\2\u00ec\u00ed\b\31\6\2\u00ed\64\3\2\2\2\u00ee\u00ef\13\2\2\2\u00ef" + "\u00f0\3\2\2\2\u00f0\u00f1\b\32\4\2\u00f1\66\3\2\2\2\26\2\3\4?S`q|\u0080" + "\u0084\u0087\u0089\u00a4\u00bc\u00c4\u00c8\u00ce\u00d8\u00e4\u00e7\7\b" + "\2\2\7\3\2\5\2\2\7\4\2\6\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
11,085
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidResourcesUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/AndroidResourcesUtils.java
package com.tyron.completion.xml.util; import androidx.annotation.NonNull; import java.io.File; public class AndroidResourcesUtils { public static boolean isResourceXMLDir(File dir) { if (dir == null) { return false; } File parent = dir.getParentFile(); if (parent != null) { return parent.getName().equals("res"); } return false; } public static boolean isResourceXMLFile(@NonNull File file) { if (!file.getName().endsWith(".xml")) { return false; } return isResourceXMLDir(file.getParentFile()); } public static boolean isLayoutXMLFile(@NonNull File file) { if (!file.getName().endsWith(".xml")) { return false; } if (file.getParentFile() != null) { File parent = file.getParentFile(); if (parent.isDirectory() && parent.getName().startsWith("layout")) { return isResourceXMLFile(file); } } return false; } }
936
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidAttributeUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/AndroidAttributeUtils.java
package com.tyron.completion.xml.util; import static com.tyron.completion.xml.util.AttributeProcessingUtil.*; import static com.tyron.completion.xml.util.AttributeProcessingUtil.getLayoutStyleablePrimary; import static com.tyron.completion.xml.util.AttributeProcessingUtil.getLayoutStyleableSecondary; import android.text.TextUtils; import androidx.annotation.NonNull; import com.google.common.collect.ImmutableSet; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.CompletionList; import com.tyron.completion.model.DrawableKind; import com.tyron.completion.xml.insert.AttributeInsertHandler; import com.tyron.xml.completion.repository.ResourceRepository; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.util.DOMUtils; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMNode; public class AndroidAttributeUtils { public static void addManifestAttributes( @NonNull CompletionList.Builder builder, @NonNull ResourceRepository repository, @NonNull DOMNode node, @NonNull ResourceNamespace namespace) { Function<String, Set<String>> provider = tag -> { String manifestStyleName = AndroidXmlTagUtils.getManifestStyleName(tag); if (manifestStyleName != null) { return ImmutableSet.of(manifestStyleName); } return ImmutableSet.of(tag); }; List<AttrResourceValue> tagAttributes = getTagAttributes(repository, node, namespace, provider, ImmutableSet::of); addAttributes(tagAttributes, node, builder); } public static void addLayoutAttributes( @NonNull CompletionList.Builder builder, @NonNull ResourceRepository repository, @NonNull DOMNode node, @NonNull ResourceNamespace namespace) { DOMDocument ownerDocument = node.getOwnerDocument(); DOMElement rootElement = DOMUtils.getRootElement(ownerDocument); if (node.equals(rootElement)) { ResourceNamespace.Resolver resolver = DOMUtils.getNamespaceResolver(ownerDocument); if (resolver != null) { addNamespaceAttributes(builder, rootElement, resolver); } } List<AttrResourceValue> tagAttributes = getTagAttributes(repository, node, namespace, ImmutableSet::of); DOMNode parentNode = node.getParentNode(); if (parentNode != null) { Function<String, Set<String>> provider = tag -> ImmutableSet.of( tag, getLayoutStyleablePrimary(tag), getLayoutStyleableSecondary(tag)); tagAttributes.addAll(getTagAttributes(repository, parentNode, namespace, provider)); } addAttributes(tagAttributes, node, builder); } private static void addNamespaceAttributes( CompletionList.Builder builder, DOMElement rootElement, ResourceNamespace.Resolver resolver) { if (resolver.uriToPrefix(ResourceNamespace.ANDROID.getXmlNamespaceUri()) == null) { CompletionItem completionItem = CompletionItem.create("androidNs", "Namespace", "xmlns:android", DrawableKind.Attribute); completionItem.addFilterText("android"); completionItem.setInsertHandler( new AttributeInsertHandler( ResourceNamespace.ANDROID.getXmlNamespaceUri(), completionItem)); builder.addItem(completionItem); } if (resolver.uriToPrefix(ResourceNamespace.RES_AUTO.getXmlNamespaceUri()) == null) { CompletionItem completionItem = CompletionItem.create("appNs", "Namespace", "xmlns:app", DrawableKind.Attribute); completionItem.addFilterText("app"); completionItem.setInsertHandler( new AttributeInsertHandler( ResourceNamespace.RES_AUTO.getXmlNamespaceUri(), completionItem)); builder.addItem(completionItem); } } private static void addAttributes( List<AttrResourceValue> tagAttributes, DOMNode node, CompletionList.Builder builder) { ResourceNamespace.Resolver resolver = DOMUtils.getNamespaceResolver(node.getOwnerDocument()); Set<String> uniques = new HashSet<>(); for (AttrResourceValue tagAttribute : tagAttributes) { String name = tagAttribute.getName(); ResourceReference reference; if (name.contains(":")) { String prefix = name.substring(0, name.indexOf(':')); String fixedName = name.substring(name.indexOf(':') + 1); ResourceNamespace namespace = ResourceNamespace.fromNamespacePrefix( prefix, tagAttribute.getNamespace(), tagAttribute.getNamespaceResolver()); reference = new ResourceReference(namespace, tagAttribute.getResourceType(), fixedName); } else { reference = tagAttribute.asReference(); } String prefix = resolver.uriToPrefix(reference.getNamespace().getXmlNamespaceUri()); if (TextUtils.isEmpty(prefix)) { if (tagAttribute.getLibraryName() != null) { // default to res-auto namespace, commonly prefixed as 'app' prefix = resolver.uriToPrefix(ResourceNamespace.RES_AUTO.getXmlNamespaceUri()); } } String commitText = TextUtils.isEmpty(prefix) ? reference.getName() : prefix + ":" + reference.getName(); if (uniques.contains(commitText)) { continue; } CompletionItem attribute = CompletionItem.create(commitText, "Attribute", commitText, DrawableKind.Attribute); attribute.addFilterText(commitText); attribute.addFilterText(reference.getName()); attribute.setInsertHandler(new AttributeInsertHandler(attribute)); builder.addItem(attribute); uniques.add(commitText); } } }
5,946
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidXmlTagUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/AndroidXmlTagUtils.java
package com.tyron.completion.xml.util; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.CompletionList; import com.tyron.completion.model.DrawableKind; import com.tyron.completion.xml.XmlRepository; import com.tyron.completion.xml.insert.LayoutTagInsertHandler; import java.util.HashMap; import java.util.Map; import org.apache.bcel.classfile.JavaClass; public class AndroidXmlTagUtils { private static final Map<String, String> sManifestTagMappings = new HashMap<>(); static { sManifestTagMappings.put("manifest", "AndroidManifest"); sManifestTagMappings.put("application", "AndroidManifestApplication"); sManifestTagMappings.put("permission", "AndroidManifestPermission"); sManifestTagMappings.put("permission-group", "AndroidManifestPermissionGroup"); sManifestTagMappings.put("permission-tree", "AndroidManifestPermissionTree"); sManifestTagMappings.put("uses-permission", "AndroidManifestUsesPermission"); sManifestTagMappings.put("required-feature", "AndroidManifestRequiredFeature"); sManifestTagMappings.put("required-not-feature", "AndroidManifestRequiredNotFeature"); sManifestTagMappings.put("uses-configuration", "AndroidManifestUsesConfiguration"); sManifestTagMappings.put("uses-feature", "AndroidManifestUsesFeature"); sManifestTagMappings.put("feature-group", "AndroidManifestFeatureGroup"); sManifestTagMappings.put("uses-sdk", "AndroidManifestUsesSdk"); sManifestTagMappings.put("extension-sdk", "AndroidManifestExtensionSdk"); sManifestTagMappings.put("library", "AndroidManifestLibrary"); sManifestTagMappings.put("static-library", "AndroidManifestStaticLibrary"); sManifestTagMappings.put("uses-libraries", "AndroidManifestUsesLibrary"); sManifestTagMappings.put("uses-native-library", "AndroidManifestUsesNativeLibrary"); sManifestTagMappings.put("uses-static-library", "AndroidManifestUsesStaticLibrary"); sManifestTagMappings.put("additional-certificate", "AndroidManifestAdditionalCertificate"); sManifestTagMappings.put("uses-package", "AndroidManifestUsesPackage"); sManifestTagMappings.put("supports-screens", "AndroidManifestSupportsScreens"); sManifestTagMappings.put("processes", "AndroidManifestProcesses"); sManifestTagMappings.put("process", "AndroidManifestProcess"); sManifestTagMappings.put("deny-permission", "AndroidManifestDenyPermission"); sManifestTagMappings.put("allow-permission", "AndroidManifestAllowPermission"); sManifestTagMappings.put("provider", "AndroidManifestProvider"); sManifestTagMappings.put("grant-uri-permission", "AndroidManifestGrantUriPermission"); sManifestTagMappings.put("path-permission", "AndroidManifestPathPermission"); sManifestTagMappings.put("service", "AndroidManifestService"); sManifestTagMappings.put("receiver", "AndroidManifestReceiver"); sManifestTagMappings.put("activity", "AndroidManifestActivity"); sManifestTagMappings.put("activity-alias", "AndroidManifestActivityAlias"); sManifestTagMappings.put("meta-data", "AndroidManifestMetaData"); sManifestTagMappings.put("property", "AndroidManifestProperty"); sManifestTagMappings.put("intent-filter", "AndroidManifestIntentFilter"); sManifestTagMappings.put("action", "AndroidManifestAction"); sManifestTagMappings.put("data", "AndroidManifestData"); sManifestTagMappings.put("category", "AndroidManifestCategory"); sManifestTagMappings.put("instrumentation", "AndroidManifestInstrumentation"); sManifestTagMappings.put("screen", "AndroidManifestCompatibleScreensScreen"); sManifestTagMappings.put("input-type", "AndroidManifestSupportsInputType"); sManifestTagMappings.put("layout", "AndroidManifestLayout"); sManifestTagMappings.put("restrict-update", "AndroidManifestRestrictUpdate"); sManifestTagMappings.put("uses-split", "AndroidManifestUsesSplit"); } @Nullable public static String getManifestStyleName(String tag) { return sManifestTagMappings.get(tag); } public static void addManifestTagItems( @NonNull XmlRepository repository, @NonNull String prefix, @NonNull CompletionList.Builder builder) { for (String tag : sManifestTagMappings.keySet()) { CompletionItem item = new CompletionItem(); String commitPrefix = "<"; if (prefix.startsWith("</")) { commitPrefix = "</"; } item.label = tag; item.detail = "TAG"; item.iconKind = DrawableKind.Class; item.commitText = commitPrefix + tag; item.cursorOffset = item.commitText.length(); item.setInsertHandler(new LayoutTagInsertHandler(null, item)); item.setSortText(""); item.addFilterText(tag); item.addFilterText("<" + tag); item.addFilterText("</" + tag); builder.addItem(item); } } public static void addTagItems( @NonNull XmlRepository repository, @NonNull String prefix, @NonNull CompletionList.Builder builder) { for (Map.Entry<String, JavaClass> entry : repository.getJavaViewClasses().entrySet()) { CompletionItem item = new CompletionItem(); String commitPrefix = "<"; if (prefix.startsWith("</")) { commitPrefix = "</"; } boolean useFqn = prefix.contains("."); if (!entry.getKey().startsWith("android.widget")) { useFqn = true; } String simpleName = StyleUtils.getSimpleName(entry.getKey()); item.label = simpleName; item.detail = entry.getValue().getPackageName(); item.iconKind = DrawableKind.Class; item.commitText = commitPrefix + (useFqn ? entry.getValue().getClassName() : StyleUtils.getSimpleName(entry.getValue().getClassName())); item.cursorOffset = item.commitText.length(); item.setInsertHandler(new LayoutTagInsertHandler(entry.getValue(), item)); item.setSortText(""); item.addFilterText(entry.getKey()); item.addFilterText("<" + entry.getKey()); item.addFilterText("</" + entry.getKey()); item.addFilterText(simpleName); item.addFilterText("<" + simpleName); item.addFilterText("</" + simpleName); builder.addItem(item); } } }
6,312
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
StyleUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/StyleUtils.java
package com.tyron.completion.xml.util; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsoluteLayout; import android.widget.Button; import android.widget.CalendarView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.GridLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TableLayout; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.ViewSwitcher; import android.widget.ZoomButton; import androidx.annotation.NonNull; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.tyron.completion.xml.BytecodeScanner; import com.tyron.completion.xml.model.DeclareStyleable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.bcel.classfile.JavaClass; public class StyleUtils { private static final Multimap<String, String> sViewStyleMap = ArrayListMultimap.create(); private static final Map<String, ImmutableSet<String>> sLayoutParamsMap = new HashMap<>(); static { putLayoutParams(ViewGroup.class); putLayoutParams(AbsoluteLayout.class); putLayoutParams(FrameLayout.class); putLayoutParams(RelativeLayout.class); putLayoutParams(LinearLayout.class); putLayoutParams(GridLayout.class); putLayoutParams(TableLayout.class); putStyle(View.class); putStyle(ViewGroup.class); ; sViewStyleMap.put(ViewGroup.class.getSimpleName(), "ViewGroup_MarginLayout"); putStyle(LinearLayout.class); putStyle(FrameLayout.class); putStyle(ListView.class); putStyle(RelativeLayout.class); putStyle(EditText.class); putStyle(TextView.class); putStyle(Button.class); putStyle(CompoundButton.class); putStyle(ImageButton.class); putStyle(CheckBox.class); putStyle(ProgressBar.class); putStyle(SeekBar.class); putStyle(TableLayout.class); putStyle(GridLayout.class); putStyle(CalendarView.class); putStyle(DatePicker.class); putStyle(ViewFlipper.class); putStyle(ViewSwitcher.class); putStyle(AbsoluteLayout.class); putStyle(ZoomButton.class); putStyle(WebView.class); } public static Set<String> getClasses(String... classNames) { Set<String> classes = new HashSet<>(); for (String className : classNames) { Collection<String> strings = sViewStyleMap.get(className); if (strings != null) { classes.addAll(strings); for (String string : strings) { if (ImmutableSet.copyOf(classNames).contains(string)) { continue; } classes.addAll(getClasses(string)); } } } return classes; } public static void putStyles(JavaClass javaClass) { JavaClass[] superClasses = BytecodeScanner.getSuperClasses(javaClass); String viewSimpleName = getSimpleName(javaClass.getClassName()); for (JavaClass superClass : superClasses) { if (Object.class.getName().equals(superClass.getClassName())) { continue; } String simpleName = getSimpleName(superClass.getClassName()); sViewStyleMap.put(viewSimpleName, simpleName); } sViewStyleMap.put(viewSimpleName, viewSimpleName); if (BytecodeScanner.isViewGroup(javaClass)) { putLayoutParams(javaClass); } } public static void putLayoutParams(JavaClass javaClass) { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); JavaClass[] superClasses = BytecodeScanner.getSuperClasses(javaClass); Arrays.stream(superClasses) .map(JavaClass::getClassName) .filter(it -> !Object.class.getName().equals(it)) .filter(it -> !View.class.getName().equals(it)) .forEach(it -> builder.add(getSimpleName(it) + "_Layout")); sLayoutParamsMap.put(getSimpleName(javaClass.getClassName()) + "_Layout", builder.build()); } public static void putLayoutParams(@NonNull Class<? extends ViewGroup> viewGroup) { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); Class<?> current = viewGroup; while (current != null) { if (Object.class.getName().equals(current.getName())) { break; } // no layout params for view if (View.class.getName().equals(current.getName())) { break; } builder.add(current.getSimpleName() + "_Layout"); if ("ViewGroup".equals(current.getSimpleName())) { builder.add("ViewGroup_MarginLayout"); } current = current.getSuperclass(); } sLayoutParamsMap.put(viewGroup.getSimpleName() + "_Layout", builder.build()); } private static void putStyle(@NonNull Class<? extends View> view) { Class<?> current = view; while (current != null) { if ("java.lang.Object".equals(current.getName())) { break; } sViewStyleMap.put(view.getSimpleName(), current.getSimpleName()); current = current.getSuperclass(); } } /** returns all the attributes available fro the current tag and its parent. */ public static Set<DeclareStyleable> getStyles( Map<String, DeclareStyleable> map, String tag, String parentTag) { Set<DeclareStyleable> styles = getStyles(map, tag); if (styles.isEmpty()) { styles.addAll(getStyles(map, View.class.getName())); } Set<DeclareStyleable> layoutParams = getLayoutParams(map, parentTag); if (layoutParams.isEmpty()) { // the layout params of the parent tag is unknown, just use a ViewGroup layoutParams.addAll(getLayoutParams(map, ViewGroup.class.getName())); } styles.addAll(layoutParams); return styles; } public static Set<DeclareStyleable> getStyles(Map<String, DeclareStyleable> map, String name) { Set<DeclareStyleable> styles = new TreeSet<>(); String simpleName = getSimpleName(name); if (map.containsKey(simpleName)) { styles.add(map.get(simpleName)); } Collection<String> strings = sViewStyleMap.get(simpleName); if (strings != null) { for (String string : strings) { if (name.equals(string)) { // already parsed continue; } styles.addAll(getStyles(map, string)); } } return styles; } public static Set<DeclareStyleable> getLayoutParams( Map<String, DeclareStyleable> map, String name) { Set<DeclareStyleable> params = new HashSet<>(); String simpleName = getSimpleName(name); if (!simpleName.endsWith("_Layout")) { simpleName += "_Layout"; ; } if (!map.containsKey(simpleName)) { return params; } params.add(map.get(simpleName)); params.add(map.get("ViewGroup_MarginLayout")); ImmutableSet<String> strings = sLayoutParamsMap.get(simpleName); if (strings != null) { for (String string : strings) { if (simpleName.equals(string)) { continue; } params.addAll(getLayoutParams(map, string)); } } return params; } public static String getSimpleName(String name) { if (name == null) { return ""; } if (name.contains(".")) { return name.substring(name.lastIndexOf('.') + 1); } return name; } }
7,629
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
PartialClassParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/PartialClassParser.java
package com.tyron.completion.xml.util; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.bcel.Const; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.ClassFormatException; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; public final class PartialClassParser { private DataInputStream dataInputStream; private final boolean fileOwned; private final String fileName; private String zipFile; private int classNameIndex; private int superclassNameIndex; private int major; // Compiler version private int minor; // Compiler version private int accessFlags; // Access rights of parsed class private int[] interfaces; // Names of implemented interfaces private ConstantPool constantPool; // collection of constants private Field[] fields; // class fields, i.e., its variables private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class private final boolean isZip; // Loaded from zip file private static final int BUFSIZE = 8192; /** * Parses class from the given stream. * * @param inputStream Input stream * @param fileName File name */ public PartialClassParser(final InputStream inputStream, final String fileName) { this.fileName = fileName; fileOwned = false; final String clazz = inputStream.getClass().getName(); // Not a very clean solution ... isZip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar."); if (inputStream instanceof DataInputStream) { this.dataInputStream = (DataInputStream) inputStream; } else { this.dataInputStream = new DataInputStream(new BufferedInputStream(inputStream, BUFSIZE)); } } /** * Parses class from given .class file. * * @param fileName file name */ public PartialClassParser(final String fileName) { isZip = false; this.fileName = fileName; fileOwned = true; } /** * Parses class from given .class file in a ZIP-archive * * @param zipFile zip file name * @param fileName file name */ public PartialClassParser(final String zipFile, final String fileName) { isZip = true; fileOwned = true; this.zipFile = zipFile; this.fileName = fileName; } /** * Parses the given Java class file and return an object that represents the contained data, i.e., * constants, methods, fields and commands. A <em>ClassFormatException</em> is raised, if the file * is not a valid .class file. (This does not include verification of the byte code as it is * performed by the java interpreter). * * @return Class object representing the parsed class file * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ public org.apache.bcel.classfile.JavaClass parse() throws IOException, org.apache.bcel.classfile.ClassFormatException { ZipFile zip = null; try { if (fileOwned) { if (isZip) { zip = new ZipFile(zipFile); final ZipEntry entry = zip.getEntry(fileName); if (entry == null) { throw new IOException("File " + fileName + " not found"); } dataInputStream = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } else { dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName), BUFSIZE)); } } /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces // readInterfaces(); // /****************** Read class fields and methods ***************/ // // Read class fields, i.e., the variables of the class // readFields(); // // Read class methods, i.e., the functions in the class // readMethods(); // // Read class attributes // readAttributes(); // Check for unknown variables // Unknown[] u = Unknown.getUnknownAttributes(); // for (int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(isZip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + fileName); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } } finally { // Read everything of interest, so close the file if (fileOwned) { try { if (dataInputStream != null) { dataInputStream.close(); } } catch (final IOException ioe) { // ignore close exceptions } } try { if (zip != null) { zip.close(); } } catch (final IOException ioe) { // ignore close exceptions } } // Return the information we have gathered in a new object return new org.apache.bcel.classfile.JavaClass( classNameIndex, superclassNameIndex, fileName, major, minor, accessFlags, constantPool, interfaces, fields, methods, attributes, isZip ? org.apache.bcel.classfile.JavaClass.ZIP : JavaClass.FILE); } /** * Reads information about the attributes of the class. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readAttributes() throws IOException, org.apache.bcel.classfile.ClassFormatException { final int attributes_count = dataInputStream.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(dataInputStream, constantPool); } } /** * Reads information about the class and its super class. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readClassInfo() throws IOException, org.apache.bcel.classfile.ClassFormatException { accessFlags = dataInputStream.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((accessFlags & Const.ACC_INTERFACE) != 0) { accessFlags |= Const.ACC_ABSTRACT; } if (((accessFlags & Const.ACC_ABSTRACT) != 0) && ((accessFlags & Const.ACC_FINAL) != 0)) { throw new org.apache.bcel.classfile.ClassFormatException( "Class " + fileName + " can't be both final and abstract"); } classNameIndex = dataInputStream.readUnsignedShort(); superclassNameIndex = dataInputStream.readUnsignedShort(); } /** * Reads constant pool entries. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readConstantPool() throws IOException, org.apache.bcel.classfile.ClassFormatException { constantPool = new ConstantPool(dataInputStream); } /******************** Private utility methods **********************/ /** * Checks whether the header of the file is ok. Of course, this has to be the first action on * successive file reads. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readID() throws IOException, org.apache.bcel.classfile.ClassFormatException { if (dataInputStream.readInt() != Const.JVM_CLASSFILE_MAGIC) { throw new org.apache.bcel.classfile.ClassFormatException( fileName + " is not a Java .class file"); } } /** * Reads information about the interfaces implemented by this class. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readInterfaces() throws IOException, org.apache.bcel.classfile.ClassFormatException { final int interfaces_count = dataInputStream.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = dataInputStream.readUnsignedShort(); } } /** * Reads major and minor version of compiler which created the file. * * @throws IOException * @throws org.apache.bcel.classfile.ClassFormatException */ private void readVersion() throws IOException, ClassFormatException { minor = dataInputStream.readUnsignedShort(); major = dataInputStream.readUnsignedShort(); } }
9,316
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttributeProcessingUtil.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/AttributeProcessingUtil.java
package com.tyron.completion.xml.util; import static com.tyron.builder.compiler.manifest.SdkConstants.TABLE_ROW; import static com.tyron.builder.compiler.manifest.SdkConstants.VIEW_GROUP; import androidx.annotation.NonNull; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import com.tyron.builder.compiler.manifest.configuration.FolderConfiguration; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.xml.completion.repository.NotFoundException; import com.tyron.xml.completion.repository.ResourceItem; import com.tyron.xml.completion.repository.ResourceRepository; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceReference; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.StyleableResourceValue; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMNode; public class AttributeProcessingUtil { private static final FolderConfiguration DEFAULT = FolderConfiguration.createDefault(); public static List<AttrResourceValue> getTagAttributes( @NonNull ResourceRepository repository, @NonNull DOMNode node, @NonNull ResourceNamespace namespace, @NonNull Function<String, Set<String>> provider) { return getTagAttributes( repository, node, namespace, it -> { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(it); builder.addAll(StyleUtils.getClasses(it)); return builder.build(); }, provider); } public static List<AttrResourceValue> getTagAttributes( @NonNull ResourceRepository repository, @NonNull DOMNode node, @NonNull ResourceNamespace namespace, @NonNull Function<String, Set<String>> styleProvider, @NonNull Function<String, Set<String>> provider) { String tagName = getSimpleName(node.getNodeName()); Set<String> classes = styleProvider.apply(tagName); return classes.stream() .flatMap(it -> getAttributes(repository, it, namespace, provider).stream()) .filter( it -> { ListMultimap<String, ResourceItem> resources = repository.getResources(it.getNamespace(), ResourceType.PUBLIC); if (!resources.isEmpty() && !it.getNamespace().equals(namespace)) { return resources.containsKey(it.getName()); } return true; }) .collect(Collectors.toList()); } public static List<AttrResourceValue> getAttributes( @NonNull ResourceRepository repository, @NonNull String tag, @NonNull ResourceNamespace namespace, @NonNull Function<String, Set<String>> provider) { String modified = tag; if (VIEW_GROUP.equals(modified)) { modified = "ViewGroup_Layout"; } Set<String> names = provider.apply(modified); return names.stream() .map(it -> getResourceValue(repository, it, namespace)) .filter(it -> it instanceof StyleableResourceValue) .flatMap(it -> ((StyleableResourceValue) it).getAllAttributes().stream()) .collect(Collectors.toList()); } public static AttrResourceValue getLayoutAttributeFromNode( @NonNull ResourceRepository repository, @NonNull DOMElement node, @NonNull String attributeName, @NonNull ResourceNamespace namespace) { String tagName = getSimpleName(node.getTagName()); Set<String> classes = StyleUtils.getClasses(tagName); // get all the attributes of the superclasses of the view for (String aClass : classes) { String modified = aClass; if (aClass.equals(VIEW_GROUP)) { modified = "ViewGroup_Layout"; } Set<String> names = ImmutableSet.of( modified, getLayoutStyleablePrimary(aClass), getLayoutStyleableSecondary(aClass)); for (String name : names) { ResourceValue resourceValue = getResourceValue(repository, name, namespace); if (resourceValue == null) { continue; } StyleableResourceValue styleable = (StyleableResourceValue) resourceValue; AttrResourceValue previous = null; for (AttrResourceValue attribute : styleable.getAllAttributes()) { if (attributeName.equals(attribute.getName())) { AttrResourceValue attributeResourceValue = getAttributeResourceValue(repository, attribute); if (attributeResourceValue != null) { return attributeResourceValue; } else { previous = attribute; } } } } } DOMElement parentElement = node.getParentElement(); if (parentElement == null) { return null; } tagName = parentElement.getTagName(); if (tagName == null) { return null; } tagName = getSimpleName(tagName); classes = StyleUtils.getClasses(tagName); // get all the attributes of the superclasses of the view for (String aClass : classes) { String modified = aClass; if (aClass.equals(VIEW_GROUP)) { modified = "ViewGroup_Layout"; } Set<String> names = ImmutableSet.of( modified, getLayoutStyleablePrimary(aClass), getLayoutStyleableSecondary(aClass)); for (String name : names) { ResourceValue resourceValue = getResourceValue(repository, name, namespace); if (resourceValue == null) { continue; } StyleableResourceValue styleable = (StyleableResourceValue) resourceValue; AttrResourceValue previous = null; for (AttrResourceValue attribute : styleable.getAllAttributes()) { if (attributeName.equals(attribute.getName())) { AttrResourceValue attributeResourceValue = getAttributeResourceValue(repository, attribute); if (attributeResourceValue != null) { return attributeResourceValue; } else { previous = attribute; } } } } } return null; } public static ResourceValue getResourceValue( @NonNull ResourceRepository repository, String name, ResourceNamespace namespace) { if (name == null || namespace == null) { return null; } ResourceValue value; try { value = repository.getValue(ResourceReference.styleable(ResourceNamespace.ANDROID, name)); return value; } catch (NotFoundException ignored) { } try { value = repository.getValue(ResourceReference.styleable(namespace, name)); return value; } catch (NotFoundException ignored) { } for (ResourceNamespace ns : repository.getNamespaces()) { try { value = repository.getValue(ResourceReference.styleable(ns, name)); return value; } catch (NotFoundException ignored) { } } return null; } public static AttrResourceValue getAttributeResourceValue( @NonNull ResourceRepository repository, @NonNull AttrResourceValue value) { if (value.getFormats().isEmpty() && value.getAttributeValues().isEmpty()) { try { return (AttrResourceValue) repository.getValue(ResourceReference.attr(value.getNamespace(), value.getName())); } catch (NotFoundException ignored) { return null; } } return value; } private static void registerAttributesForClassAndSuperclasses() {} public static void processXmlAttributes( @NonNull DOMElement element, @NonNull ResourceRepository repository) { String tagName = element.getTagName(); } /** Returns the expected styleable name for the layout attributes defined by the simple name */ public static String getLayoutStyleablePrimary(@NonNull String simpleName) { switch (simpleName) { case VIEW_GROUP: return "ViewGroup_MarginLayout"; case TABLE_ROW: return "TableRow_Cell"; default: return simpleName + "_Layout"; } } public static String getLayoutStyleableSecondary(@NonNull String simpleName) { return simpleName + "_LayoutParams"; } private static List<ResourceItem> getAttributesFromSuffixedStyleableForNamespace( @NonNull ResourceRepository repository, @NonNull DOMElement element, @NonNull ResourceNamespace namespace) { return repository.getResources( namespace, ResourceType.STYLEABLE, (item -> { String name = item.getName(); return name.endsWith("_Layout") || name.endsWith("_LayoutParams") || name.equals("ViewGroup_MarginLayout") || name.equals("TableRow_Cell"); })); } private static String getSimpleName(String qualifiedName) { int index = qualifiedName.lastIndexOf('.'); if (index == -1) { return qualifiedName; } return qualifiedName.substring(index + 1); } }
9,229
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/XmlUtils.java
package com.tyron.completion.xml.util; import android.annotation.SuppressLint; import android.text.TextUtils; import android.util.Pair; import androidx.annotation.Nullable; import com.tyron.completion.CompletionParameters; import com.tyron.completion.model.CachedCompletion; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.DrawableKind; import com.tyron.completion.progress.ProgressManager; import com.tyron.completion.xml.XmlCharacter; import com.tyron.completion.xml.XmlRepository; import com.tyron.completion.xml.lexer.XMLLexer; import com.tyron.completion.xml.model.AttributeInfo; import com.tyron.completion.xml.model.Format; import com.tyron.completion.xml.model.XmlCompletionType; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.stream.Collectors; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.Token; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMNode; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; public class XmlUtils { private static final XmlPullParserFactory sParserFactory; static { XmlPullParserFactory sParserFactory1; try { sParserFactory1 = XmlPullParserFactory.newInstance(); } catch (XmlPullParserException e) { sParserFactory1 = null; e.printStackTrace(); } sParserFactory = sParserFactory1; } public static XmlPullParser newPullParser() throws XmlPullParserException { return sParserFactory.newPullParser(); } public static String partialIdentifier(String contents, int end) { int start = end; while (start > 0 && !XmlCharacter.isNonXmlCharacterPart(contents.charAt(start - 1))) { start--; } return contents.substring(start, end); } public static String fullIdentifier(String contents, int start) { int end = start; while (end < contents.length() && !XmlCharacter.isNonXmlCharacterPart(contents.charAt(end - 1))) { end++; } return contents.substring(start, end); } public static String getAttributeValueFromPrefix(String prefix) { String attributeValue = prefix; if (attributeValue.contains("=")) { attributeValue = attributeValue.substring(attributeValue.indexOf('=') + 1); } if (attributeValue.startsWith("\"")) { attributeValue = attributeValue.substring(1); } if (attributeValue.endsWith("\"")) { attributeValue = attributeValue.substring(0, attributeValue.length() - 1); } return attributeValue; } public static String getAttributeNameFromPrefix(String prefix) { String attributeName = prefix; if (attributeName.contains("=")) { attributeName = prefix.substring(0, prefix.indexOf('=')); } if (prefix.contains(":")) { attributeName = attributeName.substring(attributeName.indexOf(':') + 1); } return attributeName; } /** * @return depth at the current position */ public static int getDepthAtPosition(XmlPullParser parser, int line) { while (parser.getLineNumber() < line) { try { parser.nextToken(); } catch (IOException | XmlPullParserException e) { // keep parsing } } return parser.getDepth(); } public static boolean isInAttribute(String contents, int line, int column) throws XmlPullParserException, IOException { XmlPullParser parser = newPullParser(); parser.setInput(new StringReader(contents)); return isInAttribute(parser, line, column); } public static boolean isInAttribute(XmlPullParser parser, int line, int column) throws IOException, XmlPullParserException { int tag = parser.next(); boolean isInStart = false; while (tag != XmlPullParser.END_DOCUMENT) { try { if (tag == XmlPullParser.START_TAG) { if (parser.getLineNumber() == line) { if (column >= parser.getColumnNumber()) { isInStart = true; } } else { isInStart = parser.getLineNumber() < line; } } else if (tag == XmlPullParser.END_TAG) { if (isInStart) { if (line < parser.getLineNumber()) { return true; } else if (line == parser.getLineNumber()) { return column <= parser.getColumnNumber(); } } isInStart = false; } tag = parser.next(); } catch (XmlPullParserException e) { // ignored, continue parsing } } return false; } /** * @return pair of the parent tag and the current tag at the current position */ public static Pair<String, String> getTagAtPosition(XmlPullParser parser, int line, int column) throws XmlPullParserException { String parentTag = null; int previousDepth = 0; int currentDepth = 0; String tag = null; do { ProgressManager.checkCanceled(); try { parser.next(); } catch (IOException | XmlPullParserException e) { System.out.println(e); // continue } int type = parser.getEventType(); if (type == XmlPullParser.END_DOCUMENT) { break; } if (parser.getLineNumber() >= line && type != XmlPullParser.TEXT) { currentDepth = parser.getDepth(); tag = parser.getName(); break; } if (type == XmlPullParser.START_TAG && parser.getDepth() > previousDepth) { parentTag = parser.getName(); } previousDepth = parser.getDepth(); } while (true); return Pair.create(parentTag, tag); } /** * Checks whether the index is at the attribute tag of the node * * @param node The xml nod * @param index The index of the cursor * @return whther the index is at the attribite tag of the node */ public static boolean isTag(DOMNode node, long index) { String name = node.getNodeName(); if (name == null) { name = ""; } return node.getStart() < index && index <= (node.getStart() + name.length() + 1); } public static boolean isEndTag(DOMNode node, long index) { if (!(node instanceof DOMElement)) { return false; } DOMElement element = (DOMElement) node; int endOpenOffset = element.getEndTagOpenOffset(); if (endOpenOffset == -1) { return false; } return index >= endOpenOffset; } /** * Return the owner element of an attribute node * * @param element The element * @return The owner element */ public static Element getElementNode(Node element) { if (element.getNodeType() == Node.ELEMENT_NODE) { return (Element) element; } if (element.getNodeType() == Node.ATTRIBUTE_NODE) { return ((Attr) element).getOwnerElement(); } return null; } /** * Uses jsoup to build a well formed xml from a broken one. Do not depend on the attribute * positions as it does not match the original source. * * @param contents The broken xml contents * @return Well formed xml */ public static String buildFixedXml(String contents) { Parser parser = Parser.xmlParser(); Document document = Jsoup.parse(contents, "", parser); Document.OutputSettings settings = document.outputSettings(); settings.prettyPrint(false); return document.toString(); } /** * @return whether the current index is inside an attribute value, e.g {@code attribute="CURSOR"} */ public static boolean isInAttributeValue(String contents, int index) { XMLLexer lexer = new XMLLexer(CharStreams.fromString(contents)); Token token; while ((token = lexer.nextToken()) != null) { int start = token.getStartIndex(); int end = token.getStopIndex(); if (token.getType() == Token.EOF) { break; } if (start <= index && index <= end) { return token.getType() == XMLLexer.STRING; } if (end > index) { break; } } return false; } public static boolean isIncrementalCompletion( CachedCompletion cachedCompletion, CompletionParameters parameters) { File file = parameters.getFile(); String prefix = parameters.getPrefix(); int line = parameters.getLine(); int column = parameters.getColumn(); prefix = partialIdentifier(prefix, prefix.length()); if (line == -1) { return false; } if (column == -1) { return false; } if (cachedCompletion == null) { return false; } if (!file.equals(cachedCompletion.getFile())) { return false; } if (prefix.endsWith(".")) { return false; } if (cachedCompletion.getLine() != line) { return false; } if (cachedCompletion.getColumn() > column) { return false; } if (!prefix.startsWith(cachedCompletion.getPrefix())) { return false; } return prefix.length() - cachedCompletion.getPrefix().length() == column - cachedCompletion.getColumn(); } @SuppressLint("NewApi") public static CompletionItem getAttributeItem( XmlRepository repository, AttributeInfo attributeInfo, boolean shouldShowNamespace, String fixedPrefix) { if (attributeInfo.getFormats() == null || attributeInfo.getFormats().isEmpty()) { AttributeInfo extraAttributeInfo = repository.getExtraAttribute(attributeInfo.getName()); if (extraAttributeInfo != null) { attributeInfo = extraAttributeInfo; } } String commitText = ""; commitText = (TextUtils.isEmpty(attributeInfo.getNamespace()) ? "" : attributeInfo.getNamespace() + ":"); commitText += attributeInfo.getName(); CompletionItem item = new CompletionItem(); item.action = CompletionItem.Kind.NORMAL; item.label = commitText; item.iconKind = DrawableKind.Attribute; item.detail = attributeInfo.getFormats().stream().map(Format::name).collect(Collectors.joining("|")); item.commitText = commitText; if (!fixedPrefix.contains("=")) { item.commitText += "=\"\""; item.cursorOffset = item.commitText.length() - 1; } else { item.cursorOffset = item.commitText.length() + 2; } return item; } public static boolean isFlagValue(DOMAttr attr, int index) { String text = attr.getOwnerDocument().getText(); String value = text.substring(attr.getNodeAttrValue().getStart() + 1, (int) index); return value.contains("|"); } @Nullable public static String getPrefix(DOMDocument parsed, long index, XmlCompletionType type) { String text = parsed.getText(); switch (type) { case TAG: DOMNode nodeAt = parsed.findNodeAt((int) index); if (nodeAt == null) { return null; } return text.substring(nodeAt.getStart(), (int) index); case ATTRIBUTE: DOMAttr attr = parsed.findAttrAt((int) index); if (attr == null) { return null; } return text.substring(attr.getStart(), (int) index); case ATTRIBUTE_VALUE: DOMAttr attrAt = parsed.findAttrAt((int) index); if (attrAt == null) { return null; } return getFlagValuePrefix( text.substring(attrAt.getNodeAttrValue().getStart() + 1, (int) index)); } return null; } private static String getFlagValuePrefix(String prefix) { if (prefix.contains("|")) { prefix = prefix.substring(prefix.lastIndexOf('|') + 1); } return prefix; } public static XmlCompletionType getCompletionType(DOMDocument parsed, long cursor) { DOMNode nodeAt = parsed.findNodeAt((int) cursor); if (nodeAt == null) { return XmlCompletionType.UNKNOWN; } if (isTag(nodeAt, cursor) || isEndTag(nodeAt, cursor)) { return XmlCompletionType.TAG; } if (isInAttributeValue(parsed.getTextDocument().getText(), (int) cursor)) { return XmlCompletionType.ATTRIBUTE_VALUE; } return XmlCompletionType.ATTRIBUTE; } }
12,275
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttributeValueUtils.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/util/AttributeValueUtils.java
package com.tyron.completion.xml.util; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.tyron.builder.compiler.manifest.configuration.Configurable; import com.tyron.builder.compiler.manifest.configuration.FolderConfiguration; import com.tyron.builder.compiler.manifest.resources.ResourceType; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.CompletionList; import com.tyron.completion.model.DrawableKind; import com.tyron.completion.xml.XmlRepository; import com.tyron.completion.xml.insert.ValueInsertHandler; import com.tyron.xml.completion.repository.Repository; import com.tyron.xml.completion.repository.ResourceItem; import com.tyron.xml.completion.repository.ResourceRepository; import com.tyron.xml.completion.repository.api.AttrResourceValue; import com.tyron.xml.completion.repository.api.AttributeFormat; import com.tyron.xml.completion.repository.api.ResourceNamespace; import com.tyron.xml.completion.repository.api.ResourceValue; import com.tyron.xml.completion.repository.api.StyleableResourceValue; import com.tyron.xml.completion.util.DOMUtils; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMElement; public class AttributeValueUtils { private static final FolderConfiguration DEFAULT = FolderConfiguration.createDefault(); public static void addManifestValueItems( @NonNull XmlRepository repository, @NonNull String prefix, int index, @NonNull DOMAttr attr, @NonNull ResourceNamespace appNamespace, CompletionList.Builder builder) { DOMElement ownerElement = attr.getOwnerElement(); if (ownerElement == null) { return; } String tagName = ownerElement.getTagName(); if (tagName == null) { return; } String manifestStyleName = AndroidXmlTagUtils.getManifestStyleName(tagName); if (manifestStyleName == null) { return; } String namespace = DOMUtils.lookupPrefix(attr); if (namespace == null) { return; } ResourceNamespace resourceNamespace = ResourceNamespace.fromNamespaceUri(namespace); if (resourceNamespace == null) { return; } ResourceValue resourceValue = AttributeProcessingUtil.getResourceValue( repository.getRepository(), manifestStyleName, resourceNamespace); if (!(resourceValue instanceof StyleableResourceValue)) { return; } String attributeName = attr.getLocalName(); StyleableResourceValue styleable = (StyleableResourceValue) resourceValue; for (AttrResourceValue attribute : styleable.getAllAttributes()) { if (attributeName.equals(attribute.getName())) { AttrResourceValue attributeResourceValue = AttributeProcessingUtil.getAttributeResourceValue( repository.getRepository(), attribute); if (attributeResourceValue != null) { addValues( attributeResourceValue, repository.getRepository(), attr, index, prefix, appNamespace, builder); } } } } public static void addValueItems( @NonNull Project project, @NonNull Module module, @NonNull String prefix, int index, @NonNull XmlRepository repo, @NonNull DOMAttr attr, @NonNull ResourceNamespace attrNamespace, @NonNull ResourceNamespace appNamespace, @NonNull CompletionList.Builder list) { ResourceRepository repository = repo.getRepository(); AttrResourceValue attribute = AttributeProcessingUtil.getLayoutAttributeFromNode( repository, attr.getOwnerElement(), attr.getLocalName(), attrNamespace); if (attribute == null) { // attribute is not found return; } addValues(attribute, repository, attr, index, prefix, appNamespace, list); } private static void addValues( AttrResourceValue attribute, Repository repository, DOMAttr attr, int index, String prefix, ResourceNamespace appNamespace, CompletionList.Builder list) { Set<AttributeFormat> formats = attribute.getFormats(); if (formats.contains(AttributeFormat.FLAGS) || formats.contains(AttributeFormat.ENUM)) { if (formats.contains(AttributeFormat.ENUM) && XmlUtils.isFlagValue(attr, index)) { return; } Map<String, Integer> attributeValues = attribute.getAttributeValues(); for (String flag : attributeValues.keySet()) { CompletionItem item = CompletionItem.create(flag, "Value", flag, DrawableKind.Snippet); item.setInsertHandler(new ValueInsertHandler(attribute, item)); item.addFilterText(flag); list.addItem(item); } } if (prefix.startsWith("@")) { String resourceType = getResourceType(prefix); if (resourceType == null) { return; } ResourceNamespace.Resolver resolver = DOMUtils.getNamespaceResolver(attr.getOwnerDocument()); ResourceNamespace namespace; if (resourceType.contains(":")) { int i = resourceType.indexOf(':'); String packagePrefix = resourceType.substring(0, i); resourceType = resourceType.substring(i + 1); namespace = ResourceNamespace.fromPackageName(packagePrefix); } else { namespace = appNamespace; } ResourceType fromTag = ResourceType.fromXmlTagName(resourceType); if (fromTag == null) { return; } List<ResourceValue> items = repository.getResources(namespace, fromTag).asMap().values().stream() .map(AttributeValueUtils::getApplicableValue) .map(it -> it != null ? it.getResourceValue() : null) .collect(Collectors.toList()); for (ResourceValue value : items) { if (value.getResourceType().getName().startsWith(resourceType)) { String label = value.asReference().getRelativeResourceUrl(appNamespace, resolver).toString(); CompletionItem item = CompletionItem.create(label, "Value", label); item.iconKind = DrawableKind.LocalVariable; item.setInsertHandler(new ValueInsertHandler(attribute, item)); item.addFilterText(value.asReference().getRelativeResourceUrl(appNamespace).toString()); item.addFilterText(value.getName()); list.addItem(item); } } } } @Nullable private static String getResourceType(String declaration) { if (!declaration.startsWith("@")) { return null; } if (declaration.contains("/")) { return declaration.substring(1, declaration.indexOf('/')); } return declaration.substring(1); } @Nullable public static ResourceItem getApplicableValue(Collection<ResourceItem> items) { Map<Configurable, ResourceItem> map = new HashMap<>(); for (ResourceItem item : items) { FolderConfiguration configuration = item.getConfiguration(); map.put(() -> configuration, item); } Configurable matching = DEFAULT.findMatchingConfigurable(map.keySet()); if (matching == null) { return null; } return map.get(matching); } private static List<ResourceType> getMatchingTypes(AttrResourceValue attrResourceValue) { return attrResourceValue.getFormats().stream() .flatMap(it -> it.getMatchingTypes().stream()) .collect(Collectors.toList()); } }
7,679
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlCachedCompletion.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/model/XmlCachedCompletion.java
package com.tyron.completion.xml.model; import android.annotation.SuppressLint; import com.tyron.completion.model.CachedCompletion; import com.tyron.completion.model.CompletionItem; import com.tyron.completion.model.CompletionList; import java.io.File; import java.util.ArrayList; import java.util.stream.Collectors; import kotlin.jvm.functions.Function2; public class XmlCachedCompletion extends CachedCompletion { public static final int TYPE_ATTRIBUTE = 0; public static final int TYPE_ATTRIBUTE_VALUE = 1; public static final int TYPE_TAG = 2; private Function2<CompletionItem, String, Boolean> mFilter; private String mFilterPrefix; private int mCompletionType; public XmlCachedCompletion( File file, int line, int column, String prefix, CompletionList completionList) { super(file, line, column, prefix, completionList); } public void setFilter(Function2<CompletionItem, String, Boolean> predicate) { mFilter = predicate; } public void setFilterPrefix(String prefix) { mFilterPrefix = prefix; } public void setCompletionType(int type) { mCompletionType = type; } public int getCompletionType() { return mCompletionType; } @SuppressLint("NewApi") public CompletionList getCompletionList() { CompletionList original = super.getCompletionList(); CompletionList completionList = new CompletionList(); completionList.isIncomplete = original.isIncomplete; completionList.items = new ArrayList<>(original.items); if (mFilter != null) { completionList.items = completionList.items.stream() .filter(it -> mFilter.invoke(it, mFilterPrefix)) .collect(Collectors.toList()); } return completionList; } public String getFilterPrefix() { return mFilterPrefix; } }
1,810
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
Format.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/model/Format.java
package com.tyron.completion.xml.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** A format type for an attribute */ public enum Format { /** A string attribute */ STRING, /** A boolean attribute may be {@code true} or {@code false} */ BOOLEAN, INTEGER, FRACTION, FLOAT, COLOR, /** An attribute that references another attribute such as {@code @color/purple} */ REFERENCE, /** A dimension attribute which is density independent */ DIMENSION, /** * An attribute that only supports values defined in an enum. Example of this is the {@code * android:visibility} attribute which only takes visible, gone and invisible */ ENUM, /** An attribute that can have multiple values separated by {@code |} */ FLAG; /** Parse the formats from a {@code format=""} declaration */ public static List<Format> fromString(String declaration) { String[] split = declaration.split("\\|"); if (split.length == 0) { return Collections.singletonList(fromSingleString(declaration)); } List<Format> formats = new ArrayList<>(); for (String s : split) { Format format = fromSingleString(s); if (format != null) { formats.add(format); } } return formats; } private static Format fromSingleString(String string) { switch (string.toLowerCase()) { case "string": return Format.STRING; case "boolean": return Format.BOOLEAN; case "dimension": return Format.DIMENSION; case "integer": return Format.INTEGER; case "float": return Format.FLOAT; case "fraction": return Format.FRACTION; case "enum": return Format.ENUM; case "color": return Format.COLOR; case "flag": case "flags": return Format.FLAG; case "reference": return Format.REFERENCE; } return null; } }
1,951
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AttributeInfo.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/model/AttributeInfo.java
package com.tyron.completion.xml.model; import java.util.List; import java.util.Objects; import java.util.Set; public class AttributeInfo implements Comparable<AttributeInfo> { private String name; private Set<Format> formats; private List<String> values; private String namespace; public AttributeInfo(String name, Set<Format> formats, List<String> values) { this.name = name; this.formats = formats; this.values = values; } @Override public int compareTo(AttributeInfo o) { return Objects.compare(this.name, o.name, String::compareTo); } public void setName(String name) { this.name = name; } public String getName() { return name; } public List<String> getValues() { return values; } public Set<Format> getFormats() { return formats; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getNamespace() { return namespace; } }
962
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
DeclareStyleable.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/model/DeclareStyleable.java
package com.tyron.completion.xml.model; import com.tyron.completion.xml.XmlRepository; import java.util.Objects; import java.util.Set; import java.util.TreeSet; public class DeclareStyleable implements Comparable<DeclareStyleable> { private final String parent; private String name; private Set<AttributeInfo> attributeInfos; public DeclareStyleable(String name, Set<AttributeInfo> attributeInfos) { this(name, attributeInfos, ""); } public DeclareStyleable(String name, Set<AttributeInfo> attributeInfos, String parent) { this.name = name; this.attributeInfos = attributeInfos; this.parent = parent; } public Set<AttributeInfo> getAttributeInfos() { return attributeInfos; } public Set<AttributeInfo> getAttributeInfosWithParents(XmlRepository repository) { Set<AttributeInfo> attributeInfos = new TreeSet<>(getAttributeInfos()); String[] parents = parent.split(" "); for (String parent : parents) { DeclareStyleable declareStyleable = repository.getDeclareStyleables().get(parent); if (declareStyleable == null) { declareStyleable = repository.getManifestAttrs().get(parent); } if (declareStyleable != null) { attributeInfos.addAll(declareStyleable.getAttributeInfosWithParents(repository)); } } return attributeInfos; } public String getName() { return name; } @Override public int compareTo(DeclareStyleable o) { return Objects.compare(this.name, o.name, String::compareTo); } public String getParent() { return parent; } }
1,573
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlCompletionType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/completion/xml/model/XmlCompletionType.java
package com.tyron.completion.xml.model; public enum XmlCompletionType { TAG, ATTRIBUTE, ATTRIBUTE_VALUE, UNKNOWN }
127
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlExpandSelectionProvider.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/selection/xml/XmlExpandSelectionProvider.java
package com.tyron.selection.xml; import android.util.Pair; import com.google.common.collect.Range; import com.tyron.editor.Caret; import com.tyron.editor.Editor; import com.tyron.editor.selection.ExpandSelectionProvider; import java.util.List; import org.eclipse.lemminx.dom.DOMAttr; import org.eclipse.lemminx.dom.DOMDocument; import org.eclipse.lemminx.dom.DOMElement; import org.eclipse.lemminx.dom.DOMNode; import org.eclipse.lemminx.dom.DOMParser; import org.jetbrains.annotations.Nullable; public class XmlExpandSelectionProvider extends ExpandSelectionProvider { @Override public @Nullable Range<Integer> expandSelection(Editor editor) { String contents = editor.getContent().toString(); DOMDocument parsed = DOMParser.getInstance().parse(contents, "", null); if (parsed == null) { return null; } Caret caret = editor.getCaret(); int cursorStart = caret.getStart(); int cursorEnd = caret.getEnd(); DOMNode node = findNode(parsed, 0, Pair.create(cursorStart, cursorEnd)); if (node == null) { return null; } if (node.getStart() == cursorStart && node.getEnd() == cursorEnd) { DOMNode parentNode = node.getParentNode(); if (parentNode.getStart() != -1 && parentNode.getEnd() != -1) { return Range.closed(parentNode.getStart(), parentNode.getEnd()); } } return Range.closed(node.getStart(), node.getEnd()); } private DOMNode findNode(DOMNode node, int level, Pair<Integer, Integer> cursor) { if (node instanceof DOMElement) { List<DOMAttr> attributeNodes = node.getAttributeNodes(); if (attributeNodes != null) { for (DOMAttr attr : attributeNodes) { if (isInside(attr, cursor)) { return attr; } } } } if (isInside(node, cursor)) { return node; } List<DOMNode> list = node.getChildren(); for (DOMNode domNode : list) { findNode(domNode, level + 1, cursor); } return null; } private boolean isInside(DOMNode node, Pair<Integer, Integer> cursor) { if (node.getStart() == -1 || node.getEnd() == -1) { return false; } return node.getStart() >= cursor.first && cursor.second >= node.getEnd(); } }
2,233
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlLanguage.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/language/xml/XmlLanguage.java
package com.tyron.language.xml; import com.tyron.language.api.Language; import org.jetbrains.annotations.NotNull; public class XmlLanguage extends Language { public static final XmlLanguage INSTANCE = new XmlLanguage("XML"); protected XmlLanguage(@NotNull String id) { super(id); } }
298
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
XmlFileType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/xml-completion/src/main/java/com/tyron/language/xml/XmlFileType.java
package com.tyron.language.xml; import android.graphics.drawable.Drawable; import com.tyron.language.api.Language; import com.tyron.language.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; public class XmlFileType extends LanguageFileType { public static final XmlFileType INSTANCE = new XmlFileType(); private XmlFileType() { this(XmlLanguage.INSTANCE); } protected XmlFileType(@NotNull Language instance) { super(instance); } @Override public @NotNull String getName() { return "XML"; } @Override public @NotNull String getDescription() { return "XML Language"; } @Override public @NotNull String getDefaultExtension() { return "xml"; } @Override public @NotNull Drawable getIcon() { return null; } }
792
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BuildModule.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/BuildModule.java
package com.tyron.builder; import android.content.Context; import com.tyron.common.util.Decompress; import java.io.File; public class BuildModule { private static Context sApplicationContext; private static File sAndroidJar; private static File sLambdaStubs; private static File sKotlincZip; private static File sJavacZip; public static void initialize(Context applicationContext) { sApplicationContext = applicationContext.getApplicationContext(); } public static Context getContext() { return sApplicationContext; } public static File getAndroidJar() { if (sAndroidJar == null) { Context context = BuildModule.getContext(); if (context == null) { return null; } sAndroidJar = new File(context.getFilesDir(), "rt.jar"); if (!sAndroidJar.exists()) { Decompress.unzipFromAssets( BuildModule.getContext(), "rt.zip", sAndroidJar.getParentFile().getAbsolutePath()); } } return sAndroidJar; } public static File getLambdaStubs() { if (sLambdaStubs == null) { sLambdaStubs = new File(BuildModule.getContext().getFilesDir(), "core-lambda-stubs.jar"); if (!sLambdaStubs.exists()) { Decompress.unzipFromAssets( BuildModule.getContext(), "lambda-stubs.zip", sLambdaStubs.getParentFile().getAbsolutePath()); } } return sLambdaStubs; } public static File getKotlinc() { if (sKotlincZip == null) { sKotlincZip = new File(BuildModule.getContext().getFilesDir(), "kotlinc.jar"); if (!sKotlincZip.exists()) { Decompress.unzipFromAssets( BuildModule.getContext(), "kotlinc.zip", sKotlincZip.getParentFile().getAbsolutePath()); } } return sKotlincZip; } public static File getJavac() { if (sJavacZip == null) { sJavacZip = new File(BuildModule.getContext().getFilesDir(), "javac.jar"); if (!sJavacZip.exists()) { Decompress.unzipFromAssets( BuildModule.getContext(), "javac.zip", sJavacZip.getParentFile().getAbsolutePath()); } } return sJavacZip; } }
2,140
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
FileManager.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/parser/FileManager.java
package com.tyron.builder.parser; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.tyron.builder.BuildModule; import com.tyron.builder.model.Project; import com.tyron.common.util.Cache; import com.tyron.common.util.StringSearch; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.FileUtils; /** Class responsible for caching java files for fast lookup later whenever we need to. */ public class FileManager { private static class OpenedFile { private final String text; private final File file; private OpenedFile(String text, File file) { this.text = text; this.file = file; } } private static FileManager INSTANCE = null; private final ExecutorService service = Executors.newFixedThreadPool(4); private Project mCurrentProject; /** * Cache of java class files, keys can contain Dex files, Java class files and the values are the * files corresponding to it */ private Cache<String, List<File>> classCache = new Cache<>(); private Cache<String, List<File>> mDexCache = new Cache<>(); private Cache<Void, Void> mSymbolCache = new Cache<>(); // Map of compiled (.class) files with their fully qualified name as key private final Map<String, File> classFiles = new HashMap<>(); private final Map<File, OpenedFile> mOpenedFiles = new HashMap<>(); public static FileManager getInstance() { if (INSTANCE == null) { INSTANCE = new FileManager(); } return INSTANCE; } @VisibleForTesting public static FileManager getInstance(File androidJar, File lambdaStubs) { if (INSTANCE == null) { INSTANCE = new FileManager(androidJar, lambdaStubs); } return INSTANCE; } @VisibleForTesting public FileManager(File androidJar, File lambdaStubs) { try { putJar(androidJar); } catch (IOException ignore) { } } public FileManager() {} public File getJavaFile(String className) { if (mCurrentProject == null) { return null; } return mCurrentProject.getJavaFiles().get(className); } public File getKotlinFile(String className) { if (mCurrentProject == null) { return null; } return mCurrentProject.getKotlinFiles().get(className); } public List<File> list(String packageName) { List<File> list = new ArrayList<>(); for (String file : mCurrentProject.getJavaFiles().keySet()) { String name = file; if (file.endsWith(".")) { name = file.substring(0, file.length() - 1); } if (name.substring(0, name.lastIndexOf(".")).equals(packageName) || name.equals(packageName)) { list.add(mCurrentProject.getJavaFiles().get(file)); } } if (mCurrentProject != null) { for (String file : mCurrentProject.getRJavaFiles().keySet()) { String name = file; if (file.endsWith(".")) { name = file.substring(0, file.length() - 1); } if (name.substring(0, name.lastIndexOf(".")).equals(packageName) || name.equals(packageName)) { list.add(mCurrentProject.getRJavaFiles().get(file)); } } } return list; } public Cache<String, List<File>> getClassCache() { return classCache; } public Cache<String, List<File>> getDexCache() { return mDexCache; } public Cache<Void, Void> getSymbolCache() { return mSymbolCache; } public void addJavaFile(File javaFile) { String packageName = StringSearch.packageName(javaFile); if (packageName != null) { String fileName = javaFile.getName(); if (fileName.lastIndexOf('.') != -1) { fileName = fileName.substring(0, fileName.lastIndexOf('.')); } packageName += "." + fileName; addJavaFile(javaFile, packageName); } } public void addJavaFile(File javaFile, String packageName) { mCurrentProject.getJavaFiles().put(packageName, javaFile); } /** * Removes a java file from the indices * * @param packageName fully qualified name of the class */ public void removeJavaFile(@NonNull String packageName) { mCurrentProject.getJavaFiles().remove(packageName); } /** * Removes all the java files from the directory on the index and deletes the file * * @param directory The directory to delete * @return The files that are deleted * @throws IOException if the directory cannot be deleted */ public List<File> deleteDirectory(File directory) throws IOException { List<File> javaFiles = rDelete(directory); FileUtils.deleteDirectory(directory); return javaFiles; } private List<File> rDelete(File directory) throws IOException { List<File> javaFiles = findFilesWithExtension(directory, ".java"); for (File file : javaFiles) { if (file.isDirectory()) { javaFiles.addAll(rDelete(file)); continue; } String packageName = StringSearch.packageName(file); if (packageName != null) { mCurrentProject.getJavaFiles().remove(packageName); FileUtils.delete(file); } } return javaFiles; } @VisibleForTesting public void setCurrentProject(Project project) { mCurrentProject = project; } public void openProject(@NonNull Project project) { if (!project.isValidProject()) { // TODO: throw exception return; } if (!project.equals(mCurrentProject)) { mCurrentProject = project; classCache = new Cache<>(); mDexCache = new Cache<>(); mSymbolCache = new Cache<>(); } try { putJar(BuildModule.getAndroidJar()); } catch (IOException ignore) { } for (File file : project.getLibraries()) { try { putJar(file); } catch (IOException ignore) { } } } public Project getCurrentProject() { return mCurrentProject; } public Set<File> getLibraries() { return mCurrentProject.getLibraries(); } public Set<String> classpath() { Set<String> classpath = new HashSet<>(); classpath.addAll(mCurrentProject.getJavaFiles().keySet()); classpath.addAll(mCurrentProject.getRJavaFiles().keySet()); classpath.addAll(Collections.emptySet()); return classpath; } public Set<File> fileClasspath() { if (mCurrentProject != null) { Set<File> classpath = new HashSet<>(mCurrentProject.getJavaFiles().values()); classpath.addAll(mCurrentProject.getLibraries()); classpath.addAll(mCurrentProject.getRJavaFiles().values()); return classpath; } return Collections.emptySet(); } public List<String> all() { List<String> files = new ArrayList<>(classFiles.keySet()); if (mCurrentProject != null) { files.addAll(mCurrentProject.getJavaFiles().keySet()); files.addAll(mCurrentProject.getRJavaFiles().keySet()); files.addAll(mCurrentProject.getKotlinFiles().keySet()); } return files; } public boolean containsClass(String fullyQualifiedName) { return classFiles.containsKey(fullyQualifiedName); } private void putJar(File file) throws IOException { if (file == null) { return; } try (JarFile jar = new JarFile(file)) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class")) { continue; } // We only want top level classes, if it contains $ then // its an inner class, we ignore it if (entry.getName().contains("$")) { continue; } String packageName = entry .getName() .replace("/", ".") .substring(0, entry.getName().length() - ".class".length()); classFiles.put(packageName, file); } } } public void save(final File file, final String contents) { service.submit( () -> { if (mOpenedFiles.get(file) != null) { updateFile(file, contents); } try { FileUtils.writeStringToFile(file, contents, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } }); } public synchronized String readFile(File file) { OpenedFile openedFile = mOpenedFiles.get(file); if (openedFile != null) { return openedFile.text; } else { String text; try { text = FileUtils.readFileToString(file, Charset.defaultCharset()); } catch (IOException e) { text = ""; } return text; } } public synchronized void updateFile(File file, String contents) { OpenedFile openedFile = new OpenedFile(contents, file); mOpenedFiles.put(file, openedFile); } public void openFile(File file) { String contents = readFile(file); updateFile(file, contents); } public void closeFile(File file, boolean save) { OpenedFile openedFile = mOpenedFiles.get(file); if (openedFile != null) { mOpenedFiles.remove(file); if (save) { save(file, openedFile.text); } } } public static BufferedReader bufferedReader(File file) { try { return new BufferedReader(new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e) { Log.e("FileManager", Log.getStackTraceString(e)); return new BufferedReader(new StringReader("")); } } public static List<File> findFilesWithExtension(File directory, String extension) { List<File> files = new ArrayList<>(); File[] children = directory.listFiles(); if (children != null) { for (File child : children) { if (child.isDirectory()) { files.addAll(findFilesWithExtension(child, extension)); } else { if (child.getName().endsWith(extension)) { files.add(child); } } } } return files; } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); if (children != null) { for (String child : children) { boolean success = deleteDir(new File(dir, child)); if (!success) { return false; } } } } return dir.delete(); } public static BufferedReader lines(File file) { return bufferedReader(file); } }
10,970
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ModuleParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/parser/ModuleParser.java
package com.tyron.builder.parser; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.json.JSONException; import org.json.JSONObject; public class ModuleParser { private final File root; public ModuleParser(File root) { this.root = root; } public String parse() throws IOException, JSONException { File module = new File(root, "module.json"); if (!module.exists()) { return "Unknown"; } String contents = FileUtils.readFileToString(module, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(contents); return jsonObject.getString("type"); } }
696
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JavaParser.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/parser/JavaParser.java
package com.tyron.builder.parser; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.JavacTask; import com.sun.tools.javac.util.Context; import com.tyron.builder.log.LogViewModel; import java.io.File; import java.util.Collections; import java.util.List; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; /** use JavaCompilerService instead */ @Deprecated public class JavaParser { public JavaParser(LogViewModel log) {} public CompilationUnitTree parse(File file, String src, int pos) { return null; } public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { return null; } public JavacTask getTask() { return null; } public Context getContext() { return null; } public List<String> packagePrivateTopLevelTypes(String packageName) { return Collections.emptyList(); } public List<String> publicTopLevelTypes() { return null; } private List<File> classpath() { return null; } }
996
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AssembleJar.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/internal/jar/AssembleJar.java
package com.tyron.builder.internal.jar; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; public class AssembleJar { private final boolean mVerbose; private File mOutputFile; private JarOptions mJarOptions; public AssembleJar(boolean verbose) { mVerbose = verbose; mJarOptions = new JarOptionsImpl(new Attributes()); } public void createJarArchive(List<File> inputFolders) throws IOException { Manifest manifest = setJarOptions(mJarOptions); try (FileOutputStream stream = new FileOutputStream(mOutputFile)) { try (JarOutputStream out = new JarOutputStream(stream, manifest)) { for (File folder : inputFolders) { addFolderToJar("", folder, out); } } } } private void addFolderToJar(String path, File folder, JarOutputStream out) throws IOException { File[] files = folder.listFiles(); if (files == null) { return; } for (File file : files) { if (file.isDirectory()) { addFolderToJar(path + file.getName() + "/", file, out); } else { JarEntry entry = new JarEntry(path + file.getName()); out.putNextEntry(entry); try (FileInputStream in = new FileInputStream(file)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } out.closeEntry(); } } } public void createJarArchive(File in) throws IOException { Manifest manifest = setJarOptions(mJarOptions); File classesFolder = new File(in.getAbsolutePath()); try (FileOutputStream stream = new FileOutputStream(mOutputFile)) { try (JarOutputStream out = new JarOutputStream(stream, manifest)) { File[] children = classesFolder.listFiles(); if (children != null) { for (File clazz : children) { add(classesFolder.getAbsolutePath(), clazz, out); } } } } } private void add(String parentPath, File source, JarOutputStream target) throws IOException { String name = source.getPath().substring(parentPath.length() + 1); if (source.isDirectory()) { if (!name.isEmpty()) { if (!name.endsWith("/")) { name += "/"; } JarEntry entry = new JarEntry(name); entry.setTime(source.lastModified()); target.putNextEntry(entry); target.closeEntry(); } File[] children = source.listFiles(); if (children != null) { for (File child : children) { add(parentPath, child, target); } } return; } JarEntry entry = new JarEntry(name); entry.setTime(source.lastModified()); target.putNextEntry(entry); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) { byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) { break; } target.write(buffer, 0, count); } target.closeEntry(); } } public Manifest setJarOptions(JarOptions options) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); if (options != null) { manifest.getMainAttributes().putAll(options.getAttributes()); } return manifest; } public void setOutputFile(File output) { mOutputFile = output; } }
3,722
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JarOptionsImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/internal/jar/JarOptionsImpl.java
package com.tyron.builder.internal.jar; import androidx.annotation.NonNull; import java.util.jar.Attributes; public class JarOptionsImpl implements JarOptions { private Attributes attributes; public JarOptionsImpl(Attributes attributes) { this.attributes = attributes; } @NonNull @Override public Attributes getAttributes() { return attributes; } @Override public void setAttributes(Attributes attributes) { this.attributes = attributes; } }
480
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
JarOptions.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/internal/jar/JarOptions.java
package com.tyron.builder.internal.jar; import androidx.annotation.NonNull; import java.util.jar.Attributes; public interface JarOptions { @NonNull Attributes getAttributes(); void setAttributes(Attributes attributes); }
231
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
CleanTask.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/CleanTask.java
package com.tyron.builder.compiler; import android.util.Log; import com.tyron.builder.compiler.incremental.dex.IncrementalD8Task; import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask; import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask; import com.tyron.builder.compiler.symbol.MergeSymbolsTask; import com.tyron.builder.exception.CompilationFailedException; import com.tyron.builder.log.ILogger; import com.tyron.builder.parser.FileManager; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.common.util.Cache; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; public class CleanTask extends Task<AndroidModule> { private static final String TAG = "clean"; private BuildType mBuildType; public CleanTask(Project project, AndroidModule module, ILogger logger) { super(project, module, logger); } @Override public String getName() { return TAG; } @Override public void prepare(BuildType type) throws IOException { mBuildType = type; } @Override public void run() throws IOException, CompilationFailedException { if (mBuildType == BuildType.RELEASE || mBuildType == BuildType.AAB) { cleanRelease(); } else if (mBuildType == BuildType.DEBUG) { cleanClasses(); cleanDexFiles(); } } private void cleanRelease() throws IOException { Log.i(TAG, "Release build, clearing intermediate cache"); File binDirectory = new File(getModule().getBuildDirectory(), "bin"); if (binDirectory.exists()) { FileUtils.deleteDirectory(binDirectory); } File genDirectory = new File(getModule().getBuildDirectory(), "gen"); if (genDirectory.exists()) { FileUtils.deleteDirectory(genDirectory); } File intermediateDirectory = new File(getModule().getBuildDirectory(), "intermediate"); if (intermediateDirectory.exists()) { FileUtils.deleteDirectory(intermediateDirectory); } getModule().getCache(IncrementalJavaTask.CACHE_KEY, new Cache<>()).clear(); getModule().getCache(IncrementalD8Task.CACHE_KEY, new Cache<>()).clear(); getModule().getCache(MergeSymbolsTask.CACHE_KEY, new Cache<>()).clear(); getModule().getCache(IncrementalAssembleLibraryTask.CACHE_KEY, new Cache<>()).clear(); } private void cleanClasses() { File output = new File(getModule().getBuildDirectory(), "bin/classes/"); List<File> classFiles = FileManager.findFilesWithExtension(output, ".class"); for (File file : classFiles) { String path = file.getAbsolutePath() .replace(output.getAbsolutePath(), "") .replace("/", ".") .substring(1) .replace(".class", ""); if (!classExists(path)) { if (file.delete()) { Log.d(TAG, "Deleted class file " + file.getName()); } ; } } } private void cleanDexFiles() { File output = new File(getModule().getBuildDirectory(), "intermediate/classes"); List<File> classFiles = FileManager.findFilesWithExtension(output, ".dex"); for (File file : classFiles) { String path = file.getAbsolutePath() .replace(output.getAbsolutePath(), "") .replace("/", ".") .substring(1) .replace(".dex", ""); String packageName = path; if (file.getName().startsWith("-$$")) { String name = file.getName().replace(".dex", ""); int start = name.indexOf('$', 3) + 1; int end = name.indexOf('$', start); if (start == -1 || end == -1) { Log.w(TAG, "Unrecognized dex file: " + file.getName()); continue; } else { String className = name.substring(start, end); path = path.substring(0, path.lastIndexOf('.')) + "." + className; } } else { if (path.contains("$")) { path = path.substring(0, path.indexOf("$")); } } if (!classExists(packageName)) { if (file.delete()) { Log.d(TAG, "Deleted dex file " + path); } } } } private boolean classExists(String fqn) { if (fqn.contains("$")) { fqn = fqn.substring(0, fqn.indexOf('$')); } return getModule().getJavaFiles().get(fqn) != null || getModule().getKotlinFiles().get(fqn) != null || getModule().getResourceClasses().containsKey(fqn); } }
4,517
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ApkBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/ApkBuilder.java
package com.tyron.builder.compiler; /** * Main entry point for building apk files, this class does all * the necessary operations for * building apk files such as compiling resources, * compiling java files, dexing and merging */ @Deprecated public class ApkBuilder { public interface OnResultListener { void onComplete(boolean success, String message); } public interface TaskListener { void onTaskStarted(String name, String message, int progress); } }
477
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BuilderImpl.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/BuilderImpl.java
package com.tyron.builder.compiler; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.tyron.builder.exception.CompilationFailedException; import com.tyron.builder.log.ILogger; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.Module; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public abstract class BuilderImpl<T extends Module> implements Builder<T> { private final Handler mMainHandler; private final Project mProject; private final T mModule; private final ILogger mLogger; private final List<Task<? super T>> mTasksRan; private TaskListener mTaskListener; private Instant now; public BuilderImpl(Project project, T module, ILogger logger) { mProject = project; mModule = module; mLogger = logger; mMainHandler = new Handler(Looper.getMainLooper()); mTasksRan = new ArrayList<>(); } @NonNull @Override public Project getProject() { return mProject; } @Override public void setTaskListener(TaskListener taskListener) { mTaskListener = taskListener; } @Override public T getModule() { return mModule; } protected void updateProgress(String name, String message, int progress) { if (mTaskListener != null) { mTaskListener.onTaskStarted(name, message, progress); } } @Override public final void build(BuildType type) throws CompilationFailedException, IOException { now = Instant.now(); mTasksRan.clear(); List<Task<? super T>> tasks = getTasks(type); for (int i = 0, tasksSize = tasks.size(); i < tasksSize; i++) { Task<? super T> task = tasks.get(i); final float current = i; getLogger().info("> Task :" + getModule().getRootFile().getName() + ":" + task.getName()); try { mMainHandler.post( () -> updateProgress( task.getName(), "Task started", (int) ((current / (float) tasks.size()) * 100f))); task.prepare(type); task.run(); } catch (Throwable e) { if (e instanceof OutOfMemoryError) { tasks.clear(); mTasksRan.clear(); throw new CompilationFailedException("Builder ran out of memory", e); } task.clean(); mTasksRan.forEach(Task::clean); throw e; } mTasksRan.add(task); } mTasksRan.forEach(Task::clean); long milliseconds = Duration.between(now, Instant.now()).toMillis(); long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds); if (seconds > 60) { long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); getLogger().debug("TIME TOOK " + minutes + "m"); } else { getLogger().debug("TIME TOOK " + seconds + "s"); } } public abstract List<Task<? super T>> getTasks(BuildType type); /** Used in tests to check the values of tasks that ran */ @VisibleForTesting public List<Task<? super T>> getTasksRan() { return mTasksRan; } @Override public ILogger getLogger() { return mLogger; } }
3,268
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidAppBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/AndroidAppBuilder.java
package com.tyron.builder.compiler; import com.tyron.builder.compiler.apk.PackageTask; import com.tyron.builder.compiler.apk.SignTask; import com.tyron.builder.compiler.apk.ZipAlignTask; import com.tyron.builder.compiler.buildconfig.GenerateDebugBuildConfigTask; import com.tyron.builder.compiler.buildconfig.GenerateReleaseBuildConfigTask; import com.tyron.builder.compiler.dex.R8Task; import com.tyron.builder.compiler.firebase.GenerateFirebaseConfigTask; import com.tyron.builder.compiler.incremental.dex.IncrementalD8Task; import com.tyron.builder.compiler.incremental.java.IncrementalJavaFormatTask; import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask; import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinCompiler; import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinFormatTask; import com.tyron.builder.compiler.incremental.resource.IncrementalAapt2Task; import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask; import com.tyron.builder.compiler.java.CheckLibrariesTask; import com.tyron.builder.compiler.log.InjectLoggerTask; import com.tyron.builder.compiler.manifest.ManifestMergeTask; import com.tyron.builder.compiler.symbol.MergeSymbolsTask; import com.tyron.builder.compiler.viewbinding.GenerateViewBindingTask; import com.tyron.builder.crashlytics.CrashlyticsTask; import com.tyron.builder.log.ILogger; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.json.JSONObject; public class AndroidAppBuilder extends BuilderImpl<AndroidModule> { public AndroidAppBuilder(Project project, AndroidModule module, ILogger logger) { super(project, module, logger); } @Override public List<Task<? super AndroidModule>> getTasks(BuildType type) { AndroidModule module = getModule(); ILogger logger = getLogger(); List<Task<? super AndroidModule>> tasks = new ArrayList<>(); tasks.add(new CleanTask(getProject(), module, logger)); tasks.add(new IncrementalKotlinFormatTask(getProject(), module, logger)); tasks.add(new IncrementalJavaFormatTask(getProject(), module, logger)); tasks.add(new CheckLibrariesTask(getProject(), module, logger)); try { File buildSettings = new File( getProject().getRootFile(), ".idea/" + getProject().getRootName() + "_compiler_settings.json"); String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath()))); JSONObject buildSettingsJson = new JSONObject(content); boolean isDexLibrariesOnPrebuild = Optional.ofNullable(buildSettingsJson.optJSONObject("dex")) .map(json -> json.optString("isDexLibrariesOnPrebuild", "false")) .map(Boolean::parseBoolean) .orElse(false); if (isDexLibrariesOnPrebuild) { tasks.add(new IncrementalD8Task(getProject(), module, logger)); } } catch (Exception e) { } tasks.add(new IncrementalAssembleLibraryTask(getProject(), module, logger)); tasks.add(new ManifestMergeTask(getProject(), module, logger)); if (type == BuildType.DEBUG) { tasks.add(new GenerateDebugBuildConfigTask(getProject(), module, logger)); } else { tasks.add(new GenerateReleaseBuildConfigTask(getProject(), module, logger)); } tasks.add(new GenerateFirebaseConfigTask(getProject(), module, logger)); if (type == BuildType.DEBUG) { tasks.add(new InjectLoggerTask(getProject(), module, logger)); } tasks.add(new CrashlyticsTask(getProject(), module, logger)); tasks.add(new IncrementalAapt2Task(getProject(), module, logger, false)); tasks.add(new GenerateViewBindingTask(getProject(), module, logger, true)); tasks.add(new MergeSymbolsTask(getProject(), module, logger)); tasks.add(new IncrementalKotlinCompiler(getProject(), module, logger)); tasks.add(new IncrementalJavaTask(getProject(), module, logger)); if (module.getMinifyEnabled() && type == BuildType.RELEASE) { tasks.add(new R8Task(getProject(), module, logger)); } else { tasks.add(new IncrementalD8Task(getProject(), module, logger)); } tasks.add(new PackageTask(getProject(), module, logger)); if (module.getZipAlignEnabled()) { tasks.add(new ZipAlignTask(getProject(), module, logger)); } tasks.add(new SignTask(getProject(), module, logger)); return tasks; } }
4,606
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BuildType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/BuildType.java
package com.tyron.builder.compiler; import java.io.IOException; public enum BuildType { RELEASE("RELEASE"), DEBUG("DEBUG"), AAB("AAB"); private final String stringValue; BuildType(String stringValue) { this.stringValue = stringValue; } public String getStringValue() { return stringValue; } public static BuildType fromStringValue(String stringValue) { for (BuildType buildType : BuildType.values()) { if (buildType.stringValue.equals(stringValue)) { return buildType; } } try { throw new IOException("Unknown build type string value: " + stringValue); } catch (IOException e) { } return null; } }
682
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ScopeType.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/ScopeType.java
package com.tyron.builder.compiler; import java.io.IOException; public enum ScopeType { API("api"), IMPLEMENTATION("implementation"), COMPILE_ONLY("compileOnly"), COMPILE_ONLY_API("compileOnlyApi"), RUNTIME_ONLY("runtimeOnly"), RUNTIME_ONLY_API("runtimeOnlyApi"), NATIVES("natives"); private final String stringValue; ScopeType(String stringValue) { this.stringValue = stringValue; } public String getStringValue() { return stringValue; } public static ScopeType fromStringValue(String stringValue) { for (ScopeType scopeType : ScopeType.values()) { if (scopeType.stringValue.equals(stringValue)) { return scopeType; } } try { throw new IOException("Unknown scope type string value: " + stringValue); } catch (IOException e) { } return null; } }
838
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
AndroidAppBundleBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/AndroidAppBundleBuilder.java
package com.tyron.builder.compiler; import com.tyron.builder.compiler.aab.AabTask; import com.tyron.builder.compiler.aab.ExtractApksTask; import com.tyron.builder.compiler.apk.SignTask; import com.tyron.builder.compiler.apk.ZipAlignTask; import com.tyron.builder.compiler.buildconfig.GenerateDebugBuildConfigTask; import com.tyron.builder.compiler.buildconfig.GenerateReleaseBuildConfigTask; import com.tyron.builder.compiler.dex.R8Task; import com.tyron.builder.compiler.firebase.GenerateFirebaseConfigTask; import com.tyron.builder.compiler.incremental.dex.IncrementalD8Task; import com.tyron.builder.compiler.incremental.java.IncrementalJavaFormatTask; import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask; import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinCompiler; import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinFormatTask; import com.tyron.builder.compiler.incremental.resource.IncrementalAapt2Task; import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask; import com.tyron.builder.compiler.java.CheckLibrariesTask; import com.tyron.builder.compiler.log.InjectLoggerTask; import com.tyron.builder.compiler.manifest.ManifestMergeTask; import com.tyron.builder.compiler.symbol.MergeSymbolsTask; import com.tyron.builder.compiler.viewbinding.GenerateViewBindingTask; import com.tyron.builder.crashlytics.CrashlyticsTask; import com.tyron.builder.log.ILogger; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.json.JSONObject; public class AndroidAppBundleBuilder extends BuilderImpl<AndroidModule> { public AndroidAppBundleBuilder(Project project, AndroidModule module, ILogger logger) { super(project, module, logger); } @Override public List<Task<? super AndroidModule>> getTasks(BuildType type) { List<Task<? super AndroidModule>> tasks = new ArrayList<>(); tasks.add(new CleanTask(getProject(), getModule(), getLogger())); tasks.add(new IncrementalKotlinFormatTask(getProject(), getModule(), getLogger())); tasks.add(new IncrementalJavaFormatTask(getProject(), getModule(), getLogger())); tasks.add(new CheckLibrariesTask(getProject(), getModule(), getLogger())); try { File buildSettings = new File( getProject().getRootFile(), ".idea/" + getProject().getRootName() + "_compiler_settings.json"); String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath()))); JSONObject buildSettingsJson = new JSONObject(content); boolean isDexLibrariesOnPrebuild = Optional.ofNullable(buildSettingsJson.optJSONObject("dex")) .map(json -> json.optString("isDexLibrariesOnPrebuild", "false")) .map(Boolean::parseBoolean) .orElse(false); if (isDexLibrariesOnPrebuild) { tasks.add(new IncrementalD8Task(getProject(), getModule(), getLogger())); } } catch (Exception e) { } tasks.add(new IncrementalAssembleLibraryTask(getProject(), getModule(), getLogger())); tasks.add(new ManifestMergeTask(getProject(), getModule(), getLogger())); if (type == BuildType.DEBUG) { tasks.add(new GenerateDebugBuildConfigTask(getProject(), getModule(), getLogger())); } else { tasks.add(new GenerateReleaseBuildConfigTask(getProject(), getModule(), getLogger())); } tasks.add(new GenerateFirebaseConfigTask(getProject(), getModule(), getLogger())); if (type == BuildType.DEBUG) { tasks.add(new InjectLoggerTask(getProject(), getModule(), getLogger())); } tasks.add(new CrashlyticsTask(getProject(), getModule(), getLogger())); tasks.add(new IncrementalAapt2Task(getProject(), getModule(), getLogger(), true)); tasks.add(new GenerateViewBindingTask(getProject(), getModule(), getLogger(), true)); tasks.add(new MergeSymbolsTask(getProject(), getModule(), getLogger())); tasks.add(new IncrementalKotlinCompiler(getProject(), getModule(), getLogger())); tasks.add(new IncrementalJavaTask(getProject(), getModule(), getLogger())); if (getModule().getMinifyEnabled() && type == BuildType.RELEASE) { tasks.add(new R8Task(getProject(), getModule(), getLogger())); } else { tasks.add(new IncrementalD8Task(getProject(), getModule(), getLogger())); } tasks.add(new AabTask(getProject(), getModule(), getLogger())); if (getModule().getZipAlignEnabled()) { tasks.add(new ZipAlignTask(getProject(), getModule(), getLogger())); } tasks.add(new SignTask(getProject(), getModule(), getLogger())); tasks.add(new ExtractApksTask(getProject(), getModule(), getLogger())); return tasks; } }
4,894
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
BundleTool.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/BundleTool.java
package com.tyron.builder.compiler; import com.android.tools.build.bundletool.BundleToolMain; import com.android.tools.build.bundletool.commands.AddTransparencyCommand; import com.android.tools.build.bundletool.commands.BuildApksCommand; import com.android.tools.build.bundletool.commands.BuildBundleCommand; import com.android.tools.build.bundletool.commands.CheckTransparencyCommand; import com.android.tools.build.bundletool.commands.DumpCommand; import com.android.tools.build.bundletool.commands.ExtractApksCommand; import com.android.tools.build.bundletool.commands.GetDeviceSpecCommand; import com.android.tools.build.bundletool.commands.GetSizeCommand; import com.android.tools.build.bundletool.commands.InstallApksCommand; import com.android.tools.build.bundletool.commands.InstallMultiApksCommand; import com.android.tools.build.bundletool.commands.ValidateBundleCommand; import com.android.tools.build.bundletool.commands.VersionCommand; import com.android.tools.build.bundletool.device.AdbServer; import com.android.tools.build.bundletool.device.DdmlibAdbServer; import com.android.tools.build.bundletool.flags.FlagParser; import com.android.tools.build.bundletool.flags.ParsedFlags; import com.android.tools.build.bundletool.model.version.BundleToolVersion; import com.tyron.builder.BuildModule; import com.tyron.builder.exception.CompilationFailedException; import java.util.ArrayList; import java.util.Optional; /** * A wrapper around {@link BundleToolMain}. * * <p>Used to access bundle tool without it calling {@link System#exit(int)} */ public class BundleTool { private final ArrayList<String> commands; private final String mApkInputPath; private final String mApkOutputPath; public BundleTool(String inputPath, String outputPath) { commands = new ArrayList<>(); mApkInputPath = inputPath; mApkOutputPath = outputPath; } public void aab(boolean uncompressed) throws Exception { commands.add("build-bundle"); commands.add("--modules=" + mApkInputPath); commands.add("--output=" + mApkOutputPath); commands.add("--uncompressed=" + String.valueOf(uncompressed)); main(commands.toArray(new String[0])); } public void apk() throws Exception { commands.add("build-apks"); commands.add("--bundle=" + mApkInputPath); commands.add("--output=" + mApkOutputPath); commands.add("--mode=universal"); commands.add( "--aapt2=" + BuildModule.getContext().getApplicationInfo().nativeLibraryDir + "/libaapt2.so"); main(commands.toArray(new String[0])); } public static void main(String[] args) throws CompilationFailedException { final ParsedFlags flags; try { flags = new FlagParser().parse(args); } catch (FlagParser.FlagParseException e) { throw new CompilationFailedException("Error while parsing the flags: " + e.getMessage()); } Optional<String> command = flags.getMainCommand(); if (!command.isPresent()) { BundleToolMain.help(); throw new CompilationFailedException("You need to specify a command."); } try { switch (command.get()) { case BuildBundleCommand.COMMAND_NAME: BuildBundleCommand.fromFlags(flags).execute(); break; case BuildApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { BuildApksCommand.fromFlags(flags, adbServer).execute(); } break; case ExtractApksCommand.COMMAND_NAME: ExtractApksCommand.fromFlags(flags).execute(); break; case GetDeviceSpecCommand.COMMAND_NAME: // We have to destroy ddmlib resources at the end of the command. try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { GetDeviceSpecCommand.fromFlags(flags, adbServer).execute(); } break; case InstallApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { InstallApksCommand.fromFlags(flags, adbServer).execute(); } break; case InstallMultiApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { InstallMultiApksCommand.fromFlags(flags, adbServer).execute(); } break; case ValidateBundleCommand.COMMAND_NAME: ValidateBundleCommand.fromFlags(flags).execute(); break; case DumpCommand.COMMAND_NAME: DumpCommand.fromFlags(flags).execute(); break; case GetSizeCommand.COMMAND_NAME: GetSizeCommand.fromFlags(flags).execute(); break; case VersionCommand.COMMAND_NAME: VersionCommand.fromFlags(flags, System.out).execute(); break; case AddTransparencyCommand.COMMAND_NAME: AddTransparencyCommand.fromFlags(flags).execute(); break; case CheckTransparencyCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { CheckTransparencyCommand.fromFlags(flags, adbServer).execute(); } break; default: throw new CompilationFailedException( String.format("Error: Unrecognized command '%s'.%n%n%n", command.get())); } } catch (Exception e) { throw new CompilationFailedException( "[BT:" + BundleToolVersion.getCurrentVersion() + "] Error: " + e.getMessage()); } } }
5,471
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z
ProjectBuilder.java
/FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/ProjectBuilder.java
package com.tyron.builder.compiler; import androidx.annotation.NonNull; import com.tyron.builder.compiler.builder.AndroidLibraryBuilder; import com.tyron.builder.compiler.builder.JavaApplicationBuilder; import com.tyron.builder.compiler.builder.JavaLibraryBuilder; import com.tyron.builder.exception.CompilationFailedException; import com.tyron.builder.log.ILogger; import com.tyron.builder.project.Project; import com.tyron.builder.project.api.AndroidModule; import com.tyron.builder.project.api.Module; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProjectBuilder { private final List<Module> mModules; private final Project mProject; private final ILogger mLogger; private Builder.TaskListener mTaskListener; public ProjectBuilder(Project project, ILogger logger) throws IOException { mProject = project; mLogger = logger; mModules = project.getBuildOrder(); } public void setTaskListener(@NonNull Builder.TaskListener listener) { mTaskListener = listener; } public void build(BuildType type) throws IOException, CompilationFailedException { for (Module module : mModules) { module.clear(); module.open(); module.index(); Builder<? extends Module> builder = null; AndroidModule androidModule = (AndroidModule) module; List<String> plugins = new ArrayList<>(); for (String plugin : module.getPlugins()) { if (plugin.equals("java-library") || plugin.equals("com.android.library") || plugin.equals("com.android.application") || plugin.equals("kotlin") || plugin.equals("application") || plugin.equals("kotlin-android")) { plugins.add(plugin); } } String moduleType = plugins.toString(); if (moduleType.equals("[java-library]")) { builder = new JavaLibraryBuilder(mProject, androidModule, mLogger); } else if (moduleType.equals("[java-library, kotlin]") || moduleType.equals("[kotlin, java-library]")) { builder = new JavaLibraryBuilder(mProject, androidModule, mLogger); } else if (moduleType.equals("[com.android.library]")) { builder = new AndroidLibraryBuilder(mProject, androidModule, mLogger); } else if (moduleType.equals("[com.android.library, kotlin]") || moduleType.equals("[kotlin, com.android.library]")) { builder = new AndroidLibraryBuilder(mProject, androidModule, mLogger); } else if (moduleType.equals("[com.android.application]")) { if (type == BuildType.AAB) { builder = new AndroidAppBundleBuilder(mProject, androidModule, mLogger); } else { builder = new AndroidAppBuilder(mProject, androidModule, mLogger); } } else if (moduleType.equals("[application]")) { builder = new JavaApplicationBuilder(mProject, androidModule, mLogger); } else if (moduleType.equals("[com.android.application, kotlin-android]") || moduleType.equals("[kotlin-android, com.android.application]")) { if (type == BuildType.AAB) { builder = new AndroidAppBundleBuilder(mProject, androidModule, mLogger); } else { builder = new AndroidAppBuilder(mProject, androidModule, mLogger); } } else { throw new CompilationFailedException( "Unable to find any plugins in " + mProject.getRootFile().getName() + "/build.gradle, check project's gradle plugins and build again."); } builder.setTaskListener(mTaskListener); builder.build(type); } } }
3,644
Java
.java
Deenu488/CodeAssist-Unofficial
122
27
2
2022-12-13T08:34:02Z
2024-05-08T01:27:41Z