import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** Build-time only, runs on JDK 11+; never packaged into the Android app. */ public final class ScreenMatch { private static final Pattern VALUE = Pattern.compile("([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+))(dp|dip|sp)"); public static void main(String[] args) throws Exception { if (args.length < 2 || args.length > 3) { throw new IllegalArgumentException("Usage: java ScreenMatch.java [previewResDir]"); } Path root = Paths.get(args[0]).toAbsolutePath().normalize(); Properties config = new Properties(); try (java.io.Reader reader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.UTF_8)) { config.load(reader); } Path res = root.resolve(config.getProperty("res_dir", "app/src/main/res")).normalize(); Path output = args.length == 3 ? Paths.get(args[2]).toAbsolutePath().normalize() : res; Path source = res.resolve("values/dimens.xml"); BigDecimal base = new BigDecimal(config.getProperty("base_dp", "360")); int min = integer(config, "min_dp", 240); int max = integer(config, "max_dp", 600); int step = integer(config, "step_dp", 2); String qualifier = config.getProperty("qualifier", "sw").trim(); if (base.signum() <= 0 || min <= 0 || max < min || max > 10000 || step <= 0 || !(qualifier.equals("sw") || qualifier.equals("w"))) { throw new IllegalArgumentException("Invalid base/range/step/qualifier (maximum width: 10000dp)"); } boolean scaleSp = bool(config, "scale_sp", true); Set excluded = new HashSet<>(Arrays.asList(config.getProperty("exclude_names", "").split(","))); Set trimmedExcluded = new HashSet<>(); for (String name : excluded) trimmedExcluded.add(name.trim()); TreeSet widths = new TreeSet<>(); for (int width = min; width <= max; width += step) widths.add(width); widths.add(max); for (String value : config.getProperty("extra_dp", "").split(",")) { if (!value.trim().isEmpty()) widths.add(Integer.parseInt(value.trim())); } Pattern folderPattern = Pattern.compile("values-" + qualifier + "(\\d+)dp"); if (bool(config, "include_existing", true)) { try (Stream paths = Files.list(res)) { paths.filter(Files::isDirectory).forEach(path -> { Matcher match = folderPattern.matcher(path.getFileName().toString()); if (match.matches() && Files.exists(path.resolve("dimens.xml"))) { widths.add(Integer.parseInt(match.group(1))); } }); } } for (int width : widths) { if (width <= 0 || width > 10000) throw new IllegalArgumentException("Invalid width: " + width); } // Fail before writing if another qualifier family could shadow generated values. String other = qualifier.equals("sw") ? "w" : "sw"; try (Stream paths = Files.list(res)) { if (paths.anyMatch(path -> path.getFileName().toString().matches("values-" + other + "\\d+dp") && Files.exists(path.resolve("dimens.xml")))) { throw new IllegalStateException("Migrate existing values-" + other + "NNNdp/dimens.xml before switching qualifier families"); } } Document original = read(source); Set sourceNames = names(original); if (sourceNames.isEmpty()) throw new IllegalArgumentException("No dimensions found in " + source); // Render and validate all files first, so an invalid resource cannot cause partial generation. Map generated = new LinkedHashMap<>(); for (int width : widths) { Path target = output.resolve("values-" + qualifier + width + "dp/dimens.xml"); if (Files.exists(target) && !sourceNames.containsAll(names(read(target)))) { throw new IllegalStateException("Target contains custom dimensions absent from base; merge them first: " + target); } Document doc = (Document) original.cloneNode(true); NodeList dimensions = doc.getDocumentElement().getElementsByTagName("dimen"); for (int i = 0; i < dimensions.getLength(); i++) { Element dimension = (Element) dimensions.item(i); Matcher match = VALUE.matcher(dimension.getTextContent().trim()); if (!trimmedExcluded.contains(dimension.getAttribute("name")) && match.matches() && (scaleSp || !match.group(2).equals("sp"))) { BigDecimal value = new BigDecimal(match.group(1)).multiply(BigDecimal.valueOf(width)) .divide(base, 4, RoundingMode.HALF_UP).stripTrailingZeros(); dimension.setTextContent(value.toPlainString() + match.group(2)); } } doc.insertBefore(doc.createComment(" Generated by tools/screenmatch/ScreenMatch.java; edit values/dimens.xml instead. "), doc.getDocumentElement()); TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); generated.put(target, writer.toString().replace("\r\n", "\n")); } int changed = 0; for (Map.Entry entry : generated.entrySet()) { Path target = entry.getKey(); byte[] bytes = entry.getValue().getBytes(StandardCharsets.UTF_8); if (!Files.exists(target) || !Arrays.equals(Files.readAllBytes(target), bytes)) { Files.createDirectories(target.getParent()); Files.write(target, bytes); changed++; } } System.out.println("ScreenMatch: " + sourceNames.size() + " dimensions, " + widths.size() + " widths, " + changed + " files updated -> " + output); System.out.println("No density changes. Existing widths are retained; obsolete files are not deleted."); } private static int integer(Properties config, String key, int fallback) { return Integer.parseInt(config.getProperty(key, Integer.toString(fallback)).trim()); } private static boolean bool(Properties config, String key, boolean fallback) { String value = config.getProperty(key, Boolean.toString(fallback)).trim(); if (!value.equals("true") && !value.equals("false")) throw new IllegalArgumentException("Invalid boolean: " + key); return Boolean.parseBoolean(value); } private static Document read(Path path) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); try (InputStream input = Files.newInputStream(path)) { return factory.newDocumentBuilder().parse(input); } } private static Set names(Document doc) { if (!doc.getDocumentElement().getTagName().equals("resources")) { throw new IllegalArgumentException("Expected resources root"); } Set names = new HashSet<>(); NodeList children = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child instanceof Element) { Element element = (Element) child; if (!element.getTagName().equals("dimen") || element.getAttribute("name").isEmpty() || !names.add(element.getAttribute("name"))) { throw new IllegalArgumentException("Only uniquely named dimen resources are supported"); } } } return names; } }