feat: 添加可手动运行的 ScreenMatch 尺寸生成工具
This commit is contained in:
1 parent
0b111f61f8
commit
5e749c18fc
5 files changed
+260
No files matched your search
@@ -1,5 +1,6 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
apply from: "config.gradle"
|
||||
apply from: "gradle/screenmatch.gradle"
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '2.4.21'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Independent build-time utility; deliberately not attached to preBuild/assemble.
|
||||
def screenMatchConfig = providers.gradleProperty('screenMatchConfig')
|
||||
.getOrElse('tools/screenmatch/screenmatch.properties')
|
||||
|
||||
tasks.register('screenMatch', Exec) {
|
||||
group = 'screen match'
|
||||
description = 'Manually regenerate dimension resources from values/dimens.xml.'
|
||||
workingDir rootDir
|
||||
commandLine new File(System.getProperty('java.home'), 'bin/java').absolutePath,
|
||||
'-Dfile.encoding=UTF-8', file('tools/screenmatch/ScreenMatch.java').absolutePath,
|
||||
rootDir.absolutePath, file(screenMatchConfig).absolutePath
|
||||
}
|
||||
|
||||
tasks.register('screenMatchPreview', Exec) {
|
||||
group = 'screen match'
|
||||
description = 'Generate a preview under build/screenmatch-preview without changing app resources.'
|
||||
workingDir rootDir
|
||||
commandLine new File(System.getProperty('java.home'), 'bin/java').absolutePath,
|
||||
'-Dfile.encoding=UTF-8', file('tools/screenmatch/ScreenMatch.java').absolutePath,
|
||||
rootDir.absolutePath, file(screenMatchConfig).absolutePath,
|
||||
layout.buildDirectory.dir('screenmatch-preview/res').get().asFile.absolutePath
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# ScreenMatch 尺寸资源生成工具
|
||||
|
||||
仅在开发电脑上运行,不打包进 APK,不修改 density。需要 JDK 11+;项目 Gradle 应继续使用其兼容的 JDK。
|
||||
|
||||
在 ElderlyDialer 根目录运行:
|
||||
|
||||
```powershell
|
||||
# 预览:仅写入 build/screenmatch-preview/res
|
||||
.\gradlew.bat screenMatchPreview
|
||||
|
||||
# 正式生成:覆盖/新增 app/src/main/res/values-swNNNdp/dimens.xml
|
||||
.\gradlew.bat screenMatch
|
||||
```
|
||||
|
||||
Android Studio 的 Gradle 面板中也可从 `screen match` 分组手动运行。普通构建不会触发生成。
|
||||
|
||||
配置文件为 `tools/screenmatch/screenmatch.properties`,不是根目录旧 IDE 插件的 `screenMatch.properties`。请勿交替使用旧插件生成同一批资源。
|
||||
|
||||
| 配置 | 默认值 | 作用 |
|
||||
|---|---|---|
|
||||
| base_dp | 360 | 默认 values/dimens.xml 的设计基准宽度 |
|
||||
| min_dp / max_dp / step_dp | 240 / 600 / 2 | 手机尺寸范围及步长,可设为 1dp |
|
||||
| extra_dp | 393,411 | 额外整数档位,逗号分隔 |
|
||||
| qualifier | sw | 与当前项目保持一致,可选 w,但必须先迁移旧 sw 资源 |
|
||||
| scale_sp | true | 是否同步缩放字体,系统字体设置仍然生效 |
|
||||
| include_existing | true | 将已有相同限定符档位纳入生成,修复旧资源不同步 |
|
||||
| exclude_names | 空 | 保持原尺寸的资源名称,逗号分隔 |
|
||||
| res_dir | app/src/main/res | 输入及正式输出资源目录 |
|
||||
|
||||
以默认 `values/dimens.xml` 为唯一来源,数值乘以 `目标宽度 / base_dp`,保留四位小数。支持 dp/dip/sp、负数、小数、零;引用及其他单位保持原样,XML 属性和注释保留。正式写入前会检查所有目标文件,不允许悄悄覆盖仅存在于目标档位的自定义尺寸;需先将其合并到默认文件。文件内容相同时不重写。工具不删除任何过期文件;缩小范围或改变配置后需检查旧目录是否仍会被选中。
|
||||
|
||||
例如:400dp 档位下 `24sp -> 26.6667sp`,`64dp -> 71.1111dp`。
|
||||
|
||||
默认沿用 sw 是为了兼容现有项目:横屏时仍按最小宽度匹配。若改为按当前窗口宽度匹配,应统一迁移为 w,不能直接叠加旧 sw 文件。Android 选择不超过可用宽度的合适档位,不做插值;2dp 步长在 240~600dp 范围内宽度比例的档位误差小于约 0.84%(不含像素取整)。范围之外不保证该误差。
|
||||
|
||||
`include_existing=true` 会继续按原比例更新旧的平板档位,**不代表已经完成平板布局适配**。平板需要独立布局及设计基准;本工具只生成尺寸,不能解决长宽比、系统栏、大字体造成的布局空间不足。
|
||||
|
||||
可指定另一配置文件:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat screenMatchPreview -PscreenMatchConfig=tools/screenmatch/custom.properties
|
||||
```
|
||||
|
||||
也可绕过 Gradle,直接用 JDK 运行(第三个参数为预览输出目录,省略则写回正式资源):
|
||||
|
||||
```powershell
|
||||
java tools/screenmatch/ScreenMatch.java . tools/screenmatch/screenmatch.properties build/screenmatch-preview/res
|
||||
```
|
||||
@@ -0,0 +1,174 @@
|
||||
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 <projectRoot> <config> [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<String> excluded = new HashSet<>(Arrays.asList(config.getProperty("exclude_names", "").split(",")));
|
||||
Set<String> trimmedExcluded = new HashSet<>();
|
||||
for (String name : excluded) trimmedExcluded.add(name.trim());
|
||||
TreeSet<Integer> 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<Path> 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<Path> 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<String> 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<Path, String> 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<Path, String> 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<String> names(Document doc) {
|
||||
if (!doc.getDocumentElement().getTagName().equals("resources")) {
|
||||
throw new IllegalArgumentException("Expected resources root");
|
||||
}
|
||||
Set<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# Standalone generator config, unrelated to the old IDE ScreenMatch plugin.
|
||||
base_dp=360
|
||||
res_dir=app/src/main/res
|
||||
# sw preserves the project's existing qualifier strategy. w requires migrating old sw resources first.
|
||||
qualifier=sw
|
||||
min_dp=240
|
||||
max_dp=600
|
||||
step_dp=2
|
||||
# Extra integer widths, for example 393,411,433.
|
||||
extra_dp=393,411
|
||||
scale_sp=true
|
||||
# Also refresh existing values-swNNNdp/dimens.xml, including legacy tablet sizes.
|
||||
include_existing=true
|
||||
# Resource names to keep at their original sizes, comma separated.
|
||||
exclude_names=
|
||||
Reference in new issue
Block a user