NativeTemplateCommandBuilder.java 66.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
package com.foodlabel.nativeprinter.template;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.util.Base64;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class NativeTemplateCommandBuilder {
    private static final double DESIGN_DPI = 96.0;
    /**
     * 与 JS 光栅路径 clearTopRasterRows 等效:热敏头可印区相对模板顶边常有一小段空白,
     * 全部为 0 时顶部中文位图/TEXT 易被裁切;略下移与整页光栅观感一致。
     */
    private static final int LABEL_TOP_MARGIN_DOTS = 18;
    private static final int TEXT_PADDING_DOTS = 6;
    private static final int RIGHT_SAFE_MARGIN_DOTS = 8;
    /** 营养表数值列右对齐:比通用 TEXT 更贴右边框 */
    private static final int NUTRITION_VALUE_RIGHT_MARGIN_DOTS = 2;
    /** 条码条宽占模块比例(越小缝越宽) */
    private static final double BARCODE_MODULE_FILL_RATIO = 0.72;
    private static final int DEFAULT_THRESHOLD = 180;
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{\\s*([\\w.-]+)\\s*\\}\\}");
    private static final String[][] NUTRITION_FIXED_ITEMS = new String[][]{
            {"fat", "Total Fat"},
            {"saturatedFat", "Saturated Fat"},
            {"transFat", "Trans Fat"},
            {"cholesterol", "Cholesterol"},
            {"sodium", "Sodium"},
            {"carbs", "Total Carbohydrates"},
            {"dietaryFiber", "Dietary Fiber"},
            {"totalSugar", "Total Sugar"},
            {"protein", "Protein"},
            {"vitaminA", "Vitamin A"},
            {"vitaminC", "Vitamin C"},
            {"calcium", "Calcium"},
            {"iron", "Iron"}
    };

    private NativeTemplateCommandBuilder() {
    }

    public static byte[] build(String templateJson, String dataJson, int dpi, int printQty) throws Exception {
        JSONObject template = new JSONObject(templateJson);
        JSONObject data = (dataJson == null || dataJson.trim().isEmpty()) ? new JSONObject() : new JSONObject(dataJson);
        return buildWithStats(template, data, dpi, printQty).bytes;
    }

    public static byte[] build(JSONObject template, JSONObject data, int dpi, int printQty) throws Exception {
        return buildWithStats(template, data, dpi, printQty).bytes;
    }

    public static BuildResult buildWithStats(String templateJson, String dataJson, int dpi, int printQty) throws Exception {
        JSONObject template = new JSONObject(templateJson);
        JSONObject data = (dataJson == null || dataJson.trim().isEmpty()) ? new JSONObject() : new JSONObject(dataJson);
        return buildWithStats(template, data, dpi, printQty);
    }

    public static BuildResult buildWithStats(JSONObject template, JSONObject data, int dpi, int printQty) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int nativeTextCount = 0;
        int rasterTextCount = 0;
        int qrCodeCount = 0;
        int barcodeCount = 0;
        int imagePatchCount = 0;
        int lineCount = 0;
        String unit = getString(template, "unit", "inch");
        double widthMm = round1(toMillimeter(getDouble(template, "width", 0), unit));
        double heightMm = round1(toMillimeter(getDouble(template, "height", 0), unit));
        double pageWidthPx = widthMm / 25.4 * DESIGN_DPI;
        /** 标签可印宽度(点);BITMAP 超出时部分机型会把溢出列折到左侧,表现为「右边框印到最左边」 */
        int pageWidthDots = Math.max(8, pxToDots(pageWidthPx, dpi));

        addLine(out, "SIZE " + formatMm(widthMm) + " mm," + formatMm(heightMm) + " mm");
        addLine(out, "GAP 0 mm,0 mm");
        addLine(out, "CODEPAGE 1252");
        addLine(out, "DENSITY 14");
        addLine(out, "SPEED 5");
        addLine(out, "CLS");

        JSONArray elements = template.optJSONArray("elements");
        if (elements != null) {
            for (int i = 0; i < elements.length(); i++) {
                JSONObject element = elements.optJSONObject(i);
                if (element == null) continue;
                JSONObject config = element.optJSONObject("config");
                if (config == null) config = new JSONObject();
                String type = getString(element, "type", "").toUpperCase();

                if (type.startsWith("TEXT_")) {
                    String text = resolveElementText(type, config, data);
                    if (text.isEmpty()) continue;
                    String align = resolveElementAlign(element, config, pageWidthPx);
                    if (shouldRasterizeText(text, type, config)) {
                        rasterTextCount++;
                        BitmapPatch patch = createTextPatch(element, type, config, text, dpi, align);
                        writeBitmapPatch(out, patch, pageWidthDots);
                    } else {
                        nativeTextCount++;
                        int scale = resolveTextScale(getDouble(config, "fontSize", 14), dpi);
                        if ("TEXT_PRICE".equals(type)) {
                            // 价格行与普通文案保持接近视觉粗细,避免看起来偏“粗黑”。
                            scale = Math.max(1, scale - 1);
                        }
                        int x = resolveTextX(align, getDouble(element, "x", 0), getDouble(element, "width", 0), dpi, text, scale);
                        int y = yDots(getDouble(element, "y", 0), dpi);
                        int rotation = "vertical".equalsIgnoreCase(getString(element, "rotation", "horizontal")) ? 90 : 0;
                        String fontName = getString(config, "tscFont", "TSS24.BF2");
                        addLine(out, "TEXT " + x + "," + y + ",\"" + escapeTscString(fontName) + "\"," + rotation + "," + scale + "," + scale + ",\"" + escapeTscString(text) + "\"");
                    }
                    continue;
                }

                if ("QRCODE".equals(type)) {
                    String sourceLike = getString(
                            config,
                            "src",
                            getString(
                                    config,
                                    "Src",
                                    getString(
                                            config,
                                            "data",
                                            getString(config, "Data", getString(config, "url", getString(config, "Url", "")))
                                    )
                            )
                    );
                    if (isImageLikeSource(sourceLike)) {
                        BitmapPatch patch = createImagePatch(element, config, dpi, sourceLike);
                        if (patch != null) {
                            imagePatchCount++;
                            writeBitmapPatch(out, patch, pageWidthDots);
                        }
                        continue;
                    }
                    String value = resolveElementDataValue(type, config, data);
                    if (value.isEmpty()) continue;
                    if (isImageLikeSource(value)) {
                        BitmapPatch patch = createImagePatch(element, config, dpi, value);
                        if (patch != null) {
                            imagePatchCount++;
                            writeBitmapPatch(out, patch, pageWidthDots);
                        }
                        continue;
                    }
                    qrCodeCount++;
                    String level = normalizeQrLevel(getString(config, "errorLevel", "M"));
                    int x = pxToDots(getDouble(element, "x", 0), dpi);
                    int y = yDots(getDouble(element, "y", 0), dpi);
                    int size = resolveQrModuleSize(getDouble(element, "width", 0), getDouble(element, "height", 0), dpi, value, level);
                    addLine(out, "QRCODE " + x + "," + y + "," + level + "," + size + ",A,0,\"" + escapeTscString(value) + "\"");
                    continue;
                }

                if ("NUTRITION".equals(type)) {
                    nativeTextCount += emitNutritionNativeText(out, element, config, dpi);
                    continue;
                }

                if ("BARCODE".equals(type)) {
                    String symbology = normalizeBarcodeType(getString(config, "barcodeType", "CODE128"));
                    String value = formatBarcodeValueForTsc(symbology, resolveElementDataValue(type, config, data));
                    if (value.isEmpty()) continue;
                    barcodeCount++;
                    String orientation = getString(config, "orientation", getString(element, "rotation", "horizontal"));
                    boolean forceBitmap = getBoolean(config, "nativeBarcodeBitmap", false)
                            || getBoolean(config, "NativeBarcodeBitmap", false)
                            || "CODA".equals(symbology);
                    if ("vertical".equalsIgnoreCase(orientation)) {
                        BitmapPatch patch = createVerticalBarcodePatch(element, config, dpi, value);
                        if (patch != null) {
                            imagePatchCount++;
                            writeBitmapPatch(out, patch, pageWidthDots);
                        }
                        continue;
                    }
                    if (forceBitmap) {
                        BitmapPatch patch = createHorizontalBarcodePatch(element, config, dpi, value);
                        if (patch != null) {
                            imagePatchCount++;
                            writeBitmapPatch(out, patch, pageWidthDots);
                        }
                        continue;
                    }
                    int x = pxToDots(getDouble(element, "x", 0), dpi);
                    int y = yDots(getDouble(element, "y", 0), dpi);
                    int height = Math.max(20, pxToDots(getDouble(element, "height", 0), dpi));
                    int readable = getBoolean(config, "showText", true) ? 1 : 0;
                    int rotation = "vertical".equalsIgnoreCase(orientation) ? 90 : 0;
                    int barWidthDots = Math.max(48, pxToDots(getDouble(element, "width", 0), dpi));
                    int len = Math.max(1, value.length());
                    int narrow = clamp(barWidthDots / Math.max(48.0, len * 11.0), 2, 8);
                    int wide = clamp(barWidthDots / Math.max(28.0, len * 6.5), 3, 12);
                    if (wide <= narrow) wide = Math.min(12, narrow + 1);
                    addLine(out, "BARCODE " + x + "," + y + ",\"" + symbology + "\"," + height + "," + readable + "," + rotation + "," + narrow + "," + wide + ",\"" + escapeTscString(value) + "\"");
                    continue;
                }

                if ("IMAGE".equals(type)) {
                    BitmapPatch patch = createImagePatch(element, config, dpi);
                    if (patch != null) {
                        imagePatchCount++;
                        writeBitmapPatch(out, patch, pageWidthDots);
                    }
                    continue;
                }

                if ("BLANK".equals(type) && "line".equalsIgnoreCase(getString(element, "border", ""))) {
                    lineCount++;
                    int x = pxToDots(getDouble(element, "x", 0), dpi);
                    int y = yDots(getDouble(element, "y", 0), dpi);
                    int width = Math.max(1, pxToDots(getDouble(element, "width", 0), dpi));
                    int height = Math.max(1, pxToDots(getDouble(element, "height", 1), dpi));
                    addLine(out, "BAR " + x + "," + y + "," + width + "," + height);
                }
            }
        }

        addLine(out, "PRINT 1," + Math.max(1, printQty));
        return new BuildResult(
                out.toByteArray(),
                nativeTextCount,
                rasterTextCount,
                qrCodeCount,
                barcodeCount,
                imagePatchCount,
                lineCount,
                elements == null ? 0 : elements.length()
        );
    }

    private static String resolveElementText(String type, JSONObject config, JSONObject data) {
        String configText = getString(config, "text", "");
        boolean hasText = !configText.isEmpty();
        if ("TEXT_PRICE".equals(type)) {
            String bindingKey = resolveBindingKey(type, config);
            String boundValue = resolveTemplateValue(data, bindingKey);
            String raw = !boundValue.isEmpty() ? boundValue : (hasText ? applyTemplateData(configText, data) : "");
            if (raw.isEmpty()) return "";
            String prefix = getString(config, "prefix", "");
            String suffix = getString(config, "suffix", "");
            int decimal = (int) getDouble(config, "decimal", -1);
            if (decimal >= 0) {
                try {
                    double value = Double.parseDouble(raw);
                    raw = String.format(java.util.Locale.US, "%1$." + decimal + "f", value);
                } catch (Exception ignored) {
                }
            }
            raw = trimLeadingCurrencyIfPrefixed(raw, prefix);
            return normalizePriceCurrencySymbol(prefix + raw + suffix);
        }
        if (hasText && "TEXT_STATIC".equals(type)) {
            return applyTemplateData(configText, data);
        }
        if (hasText && configText.contains("{{")) {
            return applyTemplateData(configText, data);
        }
        String bindingKey = resolveBindingKey(type, config);
        String boundValue = resolveTemplateValue(data, bindingKey);
        if (!boundValue.isEmpty()) return boundValue;
        return hasText ? applyTemplateData(configText, data) : "";
    }

    private static String resolveElementDataValue(String type, JSONObject config, JSONObject data) {
        String raw = getString(
                config,
                "data",
                getString(
                        config,
                        "Data",
                        getString(
                                config,
                                "value",
                                getString(config, "Value", getString(config, "src", getString(config, "Src", getString(config, "url", getString(config, "Url", "")))))
                        )
                )
        );
        if (!raw.isEmpty()) return applyTemplateData(raw, data);
        return resolveTemplateValue(data, resolveBindingKey(type, config));
    }

    private static String resolveBindingKey(String type, JSONObject config) {
        String[] keys = new String[]{"dataKey", "field", "bindField", "key", "valueKey"};
        for (String key : keys) {
            String value = getString(config, key, "");
            if (!value.isEmpty()) return value;
        }
        switch (type) {
            case "TEXT_PRODUCT": return "productName";
            case "TEXT_LABEL_ID": return "labelId";
            case "TEXT_CATEGORY": return "category";
            case "TEXT_PRICE": return "price";
            case "TEXT_DATE": return "date";
            case "TEXT_TIME": return "time";
            case "QRCODE": return "qrCode";
            case "BARCODE": return "barcode";
            default:
                String pureType = type.replace("TEXT_", "").replace("FIELD_", "").replace("VALUE_", "");
                return pureType.isEmpty() ? "" : toCamelCase(pureType);
        }
    }

    private static String resolveTemplateValue(JSONObject data, String key) {
        if (key == null || key.isEmpty()) return "";
        String[] candidates;
        switch (key) {
            case "productName": candidates = new String[]{"productName", "product"}; break;
            case "product": candidates = new String[]{"product", "productName"}; break;
            case "qrCode": candidates = new String[]{"qrCode", "labelId", "barcode"}; break;
            case "barcode": candidates = new String[]{"barcode", "labelId", "qrCode"}; break;
            default: candidates = new String[]{key};
        }
        for (String candidate : candidates) {
            Object value = data.opt(candidate);
            if (value != null) return String.valueOf(value);
        }
        return "";
    }

    private static String applyTemplateData(String text, JSONObject data) {
        Matcher matcher = PLACEHOLDER_PATTERN.matcher(text == null ? "" : text);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            String key = matcher.group(1);
            Object value = data.opt(key);
            matcher.appendReplacement(buffer, Matcher.quoteReplacement(value == null ? "" : String.valueOf(value)));
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

    private static String toCamelCase(String value) {
        String[] parts = value.toLowerCase().split("[_\\s-]+");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            if (parts[i].isEmpty()) continue;
            if (builder.length() == 0) {
                builder.append(parts[i]);
            } else {
                builder.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
            }
        }
        return builder.toString();
    }

    private static String resolveElementAlign(JSONObject element, JSONObject config, double pageWidthPx) {
        String align = getString(config, "textAlign", "").toLowerCase();
        if ("left".equals(align) || "center".equals(align) || "right".equals(align)) return align;
        double centerX = getDouble(element, "x", 0) + getDouble(element, "width", 0) / 2.0;
        if (centerX <= pageWidthPx * 0.33) return "left";
        if (centerX >= pageWidthPx * 0.67) return "right";
        return "center";
    }

    private static boolean shouldRasterizeText(String text, String type, JSONObject config) {
        if (getBoolean(config, "invertColors", false) || getBoolean(config, "InvertColors", false)) {
            return true;
        }
        if (getBoolean(config, "forceRasterText", false)) {
            return true;
        }
        if (text == null || text.isEmpty()) return false;
        if ("TEXT_PRICE".equals(type) && isSimplePriceLikeText(text)) {
            // 价格行优先走原生 TEXT:避免位图二值化导致的糊边/左侧杂点。
            return false;
        }
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c < 32 || c > 126) {
                return true;
            }
        }
        CharsetEncoder encoder = getPrinterEncoder();
        if (encoder == null) return true;
        try {
            return !encoder.canEncode(text);
        } catch (Exception e) {
            return true;
        }
    }

    private static boolean isSimplePriceLikeText(String text) {
        String s = text == null ? "" : text.trim();
        if (s.isEmpty()) return false;
        // 允许货币符号 + 数字/小数点/逗号/空格,统一按原生字体输出。
        return s.matches("^[¥¥$€£]?\\s*[-+]?\\d+(?:[.,]\\d{1,2})?\\s*$");
    }

    private static String normalizePriceCurrencySymbol(String value) {
        if (value == null || value.isEmpty()) return "";
        return value.replace('¥', '¥');
    }

    private static String trimLeadingCurrencyIfPrefixed(String raw, String prefix) {
        if (raw == null || raw.isEmpty()) return "";
        String p = prefix == null ? "" : prefix.trim();
        if (p.isEmpty()) return raw;
        char c = p.charAt(0);
        if (c != '¥' && c != '¥' && c != '$' && c != '€' && c != '£') return raw;
        String s = raw.trim();
        while (!s.isEmpty()) {
            char ch = s.charAt(0);
            if (ch == '¥' || ch == '¥' || ch == '$' || ch == '€' || ch == '£') {
                s = s.substring(1).trim();
                continue;
            }
            break;
        }
        return s;
    }

    private static BitmapPatch createTextPatch(JSONObject element, String type, JSONObject config, String text, int dpi, String align) {
        String nativeSrc = text != null ? getString(config, "nativeSourceType", "") : "";
        boolean dateLikeTime =
                "DATE".equalsIgnoreCase(nativeSrc)
                        || "TIME".equalsIgnoreCase(nativeSrc)
                        || "DURATION".equalsIgnoreCase(nativeSrc);
        if (text != null && dateLikeTime) {
            /** 预览里日期与时间之间多空格,measure + 折行易把尾部数字挤到下一行;打印前压成单空格 */
            text = text.replaceAll("\\s{2,}", " ").trim();
        }
        int contentWidth = Math.max(8, pxToDots(getDouble(element, "width", 0), dpi));
        int elementHeightDots = Math.max(16, pxToDots(getDouble(element, "height", 0), dpi));
        boolean inverted = getBoolean(config, "invertColors", false) || getBoolean(config, "InvertColors", false);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setSubpixelText(true);
        paint.setColor(inverted ? Color.WHITE : Color.BLACK);
        int fontSizeDots = Math.max(14, pxToDots(getDouble(config, "fontSize", 14), dpi));
        paint.setTextSize(fontSizeDots);
        /** 不再对 TEXT_PRICE 强制加粗:fakeBold + 粗体会糊边、measureText 偏窄,右对齐时左侧易出现杂点 */
        boolean bold = "bold".equalsIgnoreCase(getString(config, "fontWeight", ""));
        paint.setFakeBoldText(bold);
        paint.setTypeface(bold ? Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) : Typeface.SANS_SERIF);

        java.util.List<String> lines;
        if (dateLikeTime && text != null && text.indexOf('\n') < 0) {
            /** 与画布单行日期/时间一致:禁止按字符宽度硬切,避免出现「12: 00 5」类残缺行 */
            int wNeed = (int) Math.ceil(paint.measureText(text)) + 24;
            contentWidth = Math.max(contentWidth, wNeed);
            lines = new java.util.ArrayList<>();
            lines.add(text);
        } else {
            if (text != null && text.indexOf('\n') < 0) {
                int singleLineWidth = (int) Math.ceil(paint.measureText(text)) + 8;
                contentWidth = Math.max(contentWidth, singleLineWidth);
            }
            lines = splitTextLines(text == null ? "" : text, paint, Math.max(8, contentWidth));
        }
        Paint.FontMetrics metrics = paint.getFontMetrics();
        int lineHeight = Math.max(fontSizeDots + 2, (int) Math.ceil(Math.abs(metrics.top) + Math.abs(metrics.bottom) + 2));
        int totalHeight = lines.size() * lineHeight;
        float maxLineWidth = 0;
        for (String line : lines) {
            maxLineWidth = Math.max(maxLineWidth, paint.measureText(line));
        }
        int horizontalPadding = TEXT_PADDING_DOTS * 2;
        int verticalPadding = TEXT_PADDING_DOTS * 2;
        int width = ensureMultipleOf8(Math.max(contentWidth + horizontalPadding * 2, (int) Math.ceil(maxLineWidth) + horizontalPadding * 2 + 4));
        int height = Math.max(16, Math.max(elementHeightDots + verticalPadding * 2, totalHeight + verticalPadding * 2 + 4));
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(inverted ? Color.BLACK : Color.WHITE);
        if (inverted && elementHeightDots > 0 && contentWidth > 0) {
            Paint fill = new Paint();
            fill.setColor(Color.BLACK);
            canvas.drawRect(0, 0, width, height, fill);
        }

        int topOffset = "TEXT_PRICE".equals(type)
                ? Math.max(verticalPadding, (height - totalHeight) / 2)
                : verticalPadding;
        int drawableWidth = width - horizontalPadding * 2;

        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            float lineWidth = paint.measureText(line);
            float drawX = horizontalPadding;
            float baseline = topOffset + i * lineHeight - metrics.top;
            if ("center".equals(align)) {
                String eid = getString(element, "id", "");
                /** 条码下方人读数字:用 CENTER 对齐条区中心,避免 measure 偏差导致「差一截才居中」 */
                if (eid.contains("barcode") && eid.endsWith("_label")) {
                    Align saved = paint.getTextAlign();
                    paint.setTextAlign(Align.CENTER);
                    float cx = horizontalPadding + drawableWidth / 2f;
                    canvas.drawText(line, cx, baseline, paint);
                    paint.setTextAlign(saved);
                    continue;
                }
                drawX = horizontalPadding + Math.max(0, (drawableWidth - lineWidth) / 2f);
            } else if ("right".equals(align)) {
                /** ¥ 等字符 measureText 常偏窄;日期时间含空格时末字符也易被裁,统一略加余量并留右内边距 */
                float w = lineWidth;
                if ("TEXT_PRICE".equals(type)) {
                    w += Math.max(2f, paint.getTextSize() * 0.12f);
                } else {
                    w += Math.max(3f, paint.getTextSize() * 0.14f);
                }
                float rightPad = 4f;
                drawX = horizontalPadding + Math.max(0, drawableWidth - w - rightPad);
            }
            canvas.drawText(line, drawX, baseline, paint);
        }

        BitmapPatch patch = new BitmapPatch(Math.max(0, pxToDots(getDouble(element, "x", 0), dpi) - horizontalPadding),
                Math.max(0, yDots(getDouble(element, "y", 0), dpi) - verticalPadding),
                bitmapToMonochrome(bitmap, DEFAULT_THRESHOLD));
        bitmap.recycle();
        return patch;
    }

    private static BitmapPatch createImagePatch(JSONObject element, JSONObject config, int dpi) {
        return createImagePatch(element, config, dpi, null);
    }

    /**
     * 与 APP drawBarcodeLikePreview 同源:模块来自人读数字(1234),条宽比例见 BARCODE_MODULE_FILL_RATIO;
     * 在打印点阵坐标直接绘制,避免缩放后细缝被二值化糊死。人读数字由 JS 追加 TEXT_STATIC 输出。
     */
    private static BitmapPatch createHorizontalBarcodePatch(JSONObject element, JSONObject config, int dpi, String encodedValue) {
        int designW = Math.max(40, (int) Math.round(getDouble(element, "width", 140)));
        int designH = Math.max(28, (int) Math.round(getDouble(element, "height", 56)));
        String displayValue = barcodeDisplayText(config, encodedValue);
        String moduleSource = displayValue.isEmpty()
                ? stripCodabarDisplay(encodedValue)
                : displayValue;

        int printW = ensureMultipleOf8(Math.max(8, pxToDots(designW, dpi)));
        int printH = Math.max(8, pxToDots(designH, dpi));
        float scaleX = (float) printW / (float) Math.max(1, designW);
        float scaleY = (float) printH / (float) Math.max(1, designH);
        int padDots = Math.max(2, Math.round(2f * scaleX));
        int barTop = padDots;
        int barBottom = printH - padDots;
        int barHeightDots = Math.max(8, barBottom - barTop);
        int innerWDots = Math.max(8, printW - padDots * 2);

        Bitmap outputBitmap = Bitmap.createBitmap(printW, printH, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outputBitmap);
        canvas.drawColor(Color.WHITE);

        int[] modules = barcodeModulesFromValue(moduleSource);
        Paint barPaint = new Paint();
        barPaint.setAntiAlias(false);
        barPaint.setColor(Color.BLACK);
        if (modules.length > 0) {
            double moduleWDots = (double) innerWDots / (double) modules.length;
            for (int i = 0; i < modules.length; i++) {
                if (modules[i] != 1) continue;
                int left = padDots + (int) Math.round(i * moduleWDots);
                int barWDots = Math.max(1, (int) Math.round(moduleWDots * BARCODE_MODULE_FILL_RATIO));
                int right = Math.min(printW - padDots, left + barWDots);
                if (right > left) {
                    canvas.drawRect(left, barTop, right, barTop + barHeightDots, barPaint);
                }
            }
        }

        MonochromeImage mono = bitmapToMonochrome(outputBitmap, 192);
        outputBitmap.recycle();
        if (mono == null) return null;
        return new BitmapPatch(
                pxToDots(getDouble(element, "x", 0), dpi),
                yDots(getDouble(element, "y", 0), dpi),
                mono
        );
    }

    private static String stripCodabarDisplay(String value) {
        if (value == null) return "";
        String raw = value.trim();
        if (raw.length() >= 2) {
            char first = Character.toUpperCase(raw.charAt(0));
            char last = raw.charAt(raw.length() - 1);
            if ("ABCD".indexOf(first) >= 0 && "TNE*".indexOf(last) >= 0) {
                return raw.substring(1, raw.length() - 1);
            }
        }
        return raw;
    }

    private static String barcodeDisplayText(JSONObject config, String encodedValue) {
        String display = getString(
                config,
                "barcodeDisplayText",
                getString(config, "BarcodeDisplayText", "")
        ).trim();
        if (!display.isEmpty()) return stripCodabarDisplay(display);
        return stripCodabarDisplay(encodedValue);
    }

    private static BitmapPatch createVerticalBarcodePatch(JSONObject element, JSONObject config, int dpi, String value) {
        int width = ensureMultipleOf8(Math.max(8, pxToDots(getDouble(element, "width", 0), dpi)));
        int height = Math.max(12, pxToDots(getDouble(element, "height", 0), dpi));
        Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outputBitmap);
        canvas.drawColor(Color.WHITE);

        int pad = 2;
        boolean showText = getBoolean(config, "showText", true);
        int textBandWidth = (showText && value != null && !value.isEmpty()) ? Math.max(10, (int) Math.round(width * 0.18)) : 0;
        int barAreaWidth = Math.max(8, width - textBandWidth - pad * 2);
        int innerHeight = Math.max(10, height - pad * 2);

        int[] modules = barcodeModulesFromValue(value);
        Paint barPaint = new Paint();
        barPaint.setAntiAlias(false);
        barPaint.setColor(Color.BLACK);
        if (modules.length > 0) {
            double moduleH = (double) innerHeight / (double) modules.length;
            double cursorY = pad;
            for (int i = 0; i < modules.length; i++) {
                if (modules[i] == 1) {
                    float top = (float) cursorY;
                    float bottom = (float) (cursorY + Math.max(0.7, moduleH * BARCODE_MODULE_FILL_RATIO));
                    canvas.drawRect(pad, top, pad + barAreaWidth, bottom, barPaint);
                }
                cursorY += moduleH;
            }
        }

        if (showText && value != null && !value.isEmpty() && textBandWidth > 0) {
            Paint txt = new Paint();
            txt.setAntiAlias(true);
            txt.setColor(Color.BLACK);
            int font = Math.max(9, Math.min(11, (int) Math.floor(textBandWidth * 0.75)));
            txt.setTextSize(font);
            txt.setTextAlign(Paint.Align.CENTER);
            float cx = width - textBandWidth / 2f;
            float cy = height / 2f;
            canvas.save();
            // 竖排文本按模板端习惯:从下到上
            canvas.rotate(-90f, cx, cy);
            Paint.FontMetrics fm = txt.getFontMetrics();
            float baseline = cy - (fm.ascent + fm.descent) / 2f;
            canvas.drawText(value, cx, baseline, txt);
            canvas.restore();
        }

        BitmapPatch patch = new BitmapPatch(
                pxToDots(getDouble(element, "x", 0), dpi),
                yDots(getDouble(element, "y", 0), dpi),
                bitmapToMonochrome(outputBitmap, (int) getDouble(config, "threshold", DEFAULT_THRESHOLD))
        );
        outputBitmap.recycle();
        return patch;
    }

    private static int[] barcodeModulesFromValue(String value) {
        String s = value == null ? "" : value.trim();
        if (s.isEmpty()) return new int[0];
        java.util.ArrayList<Integer> m = new java.util.ArrayList<>();
        // quiet + start
        int[] start = new int[]{1, 0, 1, 0, 1, 0, 1, 0};
        for (int v : start) m.add(v);
        for (int i = 0; i < s.length(); i++) {
            int code = s.charAt(i) & 0xFF;
            int key = (code ^ (i * 13) ^ (s.length() * 7)) & 0x1F;
            for (int b = 4; b >= 0; b--) {
                m.add((key >> b) & 1);
            }
            m.add(0);
        }
        int[] stop = new int[]{1, 0, 1, 1, 0, 1, 0, 1};
        for (int v : stop) m.add(v);
        int[] out = new int[m.size()];
        for (int i = 0; i < m.size(); i++) out[i] = m.get(i);
        return out;
    }

    /**
     * 营养表走 TSC TEXT + BOX,不走 BITMAP,避免机型把位图最右列折到 x=0(数值列出现在左侧)。
     * @return 发出的 TEXT 行数(供统计)
     */
    private static int emitNutritionNativeText(ByteArrayOutputStream out, JSONObject element, JSONObject config, int dpi) {
        int designW = Math.max(40, (int) Math.round(getDouble(element, "width", 0)));
        int designH = (int) Math.round(getDouble(config, "nativePrintHeight",
                getDouble(config, "NativePrintHeight", getDouble(element, "height", 72))));
        if (designH < 40) designH = 40;
        double elX = getDouble(element, "x", 0);
        double elY = getDouble(element, "y", 0);
        int padDesign = 3;
        int patchX = pxToDots(elX, dpi);
        int patchY = yDots(elY, dpi);
        int boxWDots = Math.max(8, pxToDots(designW, dpi));
        int boxHDots = Math.max(8, pxToDots(designH, dpi));
        int boxR = patchX + boxWDots - 1;
        int boxB = patchY + boxHDots - 1;
        addLine(out, "BOX " + patchX + "," + patchY + "," + boxR + "," + boxB + ",1");

        int titleSize = clamp((int) Math.round(getDouble(config, "nutritionTitleFontSize", 16)), 11, 22);
        int bodySize = clamp(Math.round(titleSize * 0.72f), 8, 14);
        int titleScale = resolveTextScale(titleSize, dpi);
        int bodyScale = resolveTextScale(bodySize, dpi);
        int titleLineHDots = titleScale * 24 + 4;
        int bodyLineHDots = bodyScale * 24 + 2;
        int padDots = Math.max(2, pxToDots(padDesign, dpi));
        int textCount = 0;

        int cursorY = patchY + padDots;
        textCount += addNativeTextLine(out, pxToDots(elX + padDesign, dpi), cursorY, titleScale, "Nutrition Facts");
        cursorY += titleLineHDots;

        int barX = patchX + padDots;
        int barW = Math.max(8, boxWDots - padDots * 2);
        addLine(out, "BAR " + barX + "," + cursorY + "," + barW + ",1");
        cursorY += 4;

        double innerX = elX + padDesign;
        double innerW = Math.max(8, designW - padDesign * 2.0);

        String calories = getString(config, "calories", getString(config, "Calories",
                getNutritionFixedField(config, "calories", "value")));
        if (!calories.trim().isEmpty()) {
            textCount += emitNutritionRow(out, innerX, innerW, cursorY, dpi, bodyScale,
                    "Calories", nutritionDisplayValue(calories, ""));
            cursorY += bodyLineHDots;
        }

        String servingsPerContainer = getString(config, "servingsPerContainer", getString(config, "ServingsPerContainer", ""));
        if (!servingsPerContainer.trim().isEmpty()) {
            textCount += emitNutritionRow(out, innerX, innerW, cursorY, dpi, bodyScale,
                    "Servings Per Container", servingsPerContainer);
            cursorY += bodyLineHDots;
        }

        String servingSize = getString(config, "servingSize", getString(config, "ServingSize", ""));
        if (!servingSize.trim().isEmpty()) {
            textCount += emitNutritionRow(out, innerX, innerW, cursorY, dpi, bodyScale,
                    "Serving Size", servingSize);
            cursorY += bodyLineHDots;
        }

        for (String[] row : NUTRITION_FIXED_ITEMS) {
            if (cursorY + bodyLineHDots > boxB - padDots) break;
            String value = getNutritionFixedField(config, row[0], "value");
            if (value.trim().isEmpty()) continue;
            String unit = getNutritionFixedField(config, row[0], "unit");
            textCount += emitNutritionRow(out, innerX, innerW, cursorY, dpi, bodyScale,
                    row[1], nutritionDisplayValue(value, unit));
            cursorY += bodyLineHDots;
        }

        JSONArray extra = config.optJSONArray("extraNutrients");
        if (extra != null) {
            for (int i = 0; i < extra.length(); i++) {
                if (cursorY + bodyLineHDots > boxB - padDots) break;
                JSONObject item = extra.optJSONObject(i);
                if (item == null) continue;
                String name = getString(item, "name", "").trim();
                String value = getString(item, "value", "").trim();
                String unit = getString(item, "unit", "").trim();
                if (value.isEmpty()) continue;
                if (name.isEmpty()) name = "Other";
                textCount += emitNutritionRow(out, innerX, innerW, cursorY, dpi, bodyScale,
                        name, nutritionDisplayValue(value, unit));
                cursorY += bodyLineHDots;
            }
        }
        return textCount;
    }

    private static int emitNutritionRow(
            ByteArrayOutputStream out,
            double innerX,
            double innerW,
            int textY,
            int dpi,
            int bodyScale,
            String label,
            String value
    ) {
        int count = 0;
        String safeLabel = label == null ? "" : label.trim();
        String safeValue = value == null ? "" : value.trim();
        if (!safeLabel.isEmpty()) {
            count += addNativeTextLine(out, resolveTextX("left", innerX, innerW, dpi, safeLabel, bodyScale),
                    textY, bodyScale, safeLabel);
        }
        if (!safeValue.isEmpty()) {
            count += addNativeTextLine(out, resolveNutritionValueX(innerX, innerW, dpi, safeValue, bodyScale),
                    textY, bodyScale, safeValue);
        }
        return count;
    }

    private static int addNativeTextLine(ByteArrayOutputStream out, int x, int y, int scale, String text) {
        if (text == null || text.trim().isEmpty()) return 0;
        addLine(out, "TEXT " + x + "," + y + ",\"TSS24.BF2\",0," + scale + "," + scale
                + ",\"" + escapeTscString(text.trim()) + "\"");
        return 1;
    }

    /** @deprecated 营养表已改 emitNutritionNativeText;保留供参考 */
    private static BitmapPatch createNutritionPatch(JSONObject element, JSONObject config, int dpi, int pageWidthDots) {
        /** 直接在打印点阵分辨率绘制,避免 160px→340dot 缩放导致文字糊、边框错位 */
        int designW = Math.max(40, (int) Math.round(getDouble(element, "width", 0)));
        int designH = (int) Math.round(getDouble(config, "nativePrintHeight",
                getDouble(config, "NativePrintHeight", getDouble(element, "height", 72))));
        if (designH < 40) designH = 40;
        int patchX = pxToDots(getDouble(element, "x", 0), dpi);
        int patchY = yDots(getDouble(element, "y", 0), dpi);
        int maxPrintW = pageWidthDots - patchX - RIGHT_SAFE_MARGIN_DOTS;
        int idealPrintW = ensureMultipleOf8(Math.max(8, pxToDots(designW, dpi)));
        int printW = idealPrintW;
        if (maxPrintW >= 8) {
            printW = Math.min(idealPrintW, ensureMultipleOf8(maxPrintW));
        }
        int printH = Math.max(8, pxToDots(designH, dpi));
        float sx = (float) printW / (float) Math.max(1, designW);

        Bitmap bitmap = Bitmap.createBitmap(printW, printH, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);

        int pad = Math.max(2, Math.round(3f * sx));
        int contentLeft = pad;
        int innerRight = Math.max(pad + 24, printW - pad);
        int right = innerRight;
        int maxY = printH - pad - 1;

        int titleSize = clamp((int) Math.round(getDouble(config, "nutritionTitleFontSize", 16)), 11, 22);
        int bodySize = clamp(Math.round(titleSize * 0.72f), 8, 14);
        float titlePx = Math.max(9f, titleSize * sx);
        float bodyPx = Math.max(8f, bodySize * sx);
        float y = pad + titlePx;

        boolean titleBold = getBoolean(config, "nutritionTitleBold", false);
        boolean bodyBold = getBoolean(config, "nutritionBodyBold", false);

        Paint linePaint = new Paint();
        linePaint.setAntiAlias(false);
        linePaint.setColor(Color.BLACK);
        linePaint.setStrokeWidth(1f);

        Paint titlePaint = new Paint();
        titlePaint.setAntiAlias(false);
        titlePaint.setColor(Color.BLACK);
        titlePaint.setTextSize(titlePx);
        titlePaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, titleBold ? Typeface.BOLD : Typeface.NORMAL));
        titlePaint.setSubpixelText(false);
        titlePaint.setTextAlign(Align.LEFT);
        canvas.drawText("Nutrition Facts", contentLeft, y, titlePaint);
        y += Math.max(1f, 1f * sx);
        canvas.drawLine(contentLeft, y, innerRight, y, linePaint);
        y += Math.max(2f, 2f * sx);

        Paint labelPaint = new Paint();
        labelPaint.setAntiAlias(false);
        labelPaint.setColor(Color.BLACK);
        labelPaint.setTextSize(bodyPx);
        labelPaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, bodyBold ? Typeface.BOLD : Typeface.NORMAL));
        labelPaint.setSubpixelText(false);
        labelPaint.setTextAlign(Align.LEFT);

        Paint valuePaint = new Paint();
        valuePaint.setAntiAlias(false);
        valuePaint.setColor(Color.BLACK);
        valuePaint.setTextSize(bodyPx);
        valuePaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, bodyBold ? Typeface.BOLD : Typeface.NORMAL));
        valuePaint.setSubpixelText(false);
        valuePaint.setTextAlign(Align.RIGHT);

        String calories = getString(config, "calories", getString(config, "Calories",
                getNutritionFixedField(config, "calories", "value")));
        if (!calories.trim().isEmpty()) {
            y = drawNutritionPair(canvas, "Calories", nutritionDisplayValue(calories, ""), contentLeft, right, y, maxY, labelPaint, valuePaint);
        }

        String servingsPerContainer = getString(config, "servingsPerContainer", getString(config, "ServingsPerContainer", ""));
        if (!servingsPerContainer.trim().isEmpty()) {
            y = drawNutritionPair(canvas, "Servings Per Container", servingsPerContainer, contentLeft, right, y, maxY, labelPaint, valuePaint);
        }

        String servingSize = getString(config, "servingSize", getString(config, "ServingSize", ""));
        if (!servingSize.trim().isEmpty()) {
            y = drawNutritionPair(canvas, "Serving Size", servingSize, contentLeft, right, y, maxY, labelPaint, valuePaint);
        }

        for (String[] row : NUTRITION_FIXED_ITEMS) {
            String key = row[0];
            String name = row[1];
            String value = getNutritionFixedField(config, key, "value");
            if (value.trim().isEmpty()) continue;
            String unit = getNutritionFixedField(config, key, "unit");
            y = drawNutritionPair(canvas, name, nutritionDisplayValue(value, unit), contentLeft, right, y, maxY, labelPaint, valuePaint);
            if (y >= maxY) break;
        }

        if (y < maxY) {
            JSONArray extra = config.optJSONArray("extraNutrients");
            if (extra != null) {
                for (int i = 0; i < extra.length(); i++) {
                    JSONObject item = extra.optJSONObject(i);
                    if (item == null) continue;
                    String name = getString(item, "name", "").trim();
                    String value = getString(item, "value", "").trim();
                    String unit = getString(item, "unit", "").trim();
                    if (value.isEmpty()) continue;
                    if (name.isEmpty()) name = "Other";
                    y = drawNutritionPair(canvas, name, nutritionDisplayValue(value, unit), contentLeft, right, y, maxY, labelPaint, valuePaint);
                    if (y >= maxY) break;
                }
            }
        }

        MonochromeImage mono = bitmapToMonochrome(bitmap, 200);
        bitmap.recycle();
        if (mono == null) return null;
        return new BitmapPatch(patchX, patchY, mono);
    }

    private static float drawNutritionPair(
            Canvas canvas,
            String label,
            String value,
            int left,
            int right,
            float baseline,
            int maxY,
            Paint labelPaint,
            Paint valuePaint
    ) {
        if (baseline + labelPaint.getTextSize() + 1 > maxY) return maxY;
        String safeLabel = (label == null ? "" : label).replace("\n", " ").replace("\r", " ").trim();
        String safeValue = (value == null ? "" : value).replace("\n", " ").replace("\r", " ").trim();

        /** 数值列不得超过 (right-left);禁止再强制 minWidth=14,否则窄营养表(如 width=32dot)会挤爆列划分 */
        float totalWidth = (float) right - (float) left;
        if (totalWidth < 8f) {
            return maxY;
        }
        float minName = Math.min(40f, Math.max(14f, totalWidth * 0.5f));
        float valueColumnWidth = Math.min(totalWidth * 0.45f, Math.max(4f, totalWidth - minName));
        float valueColumnLeft = (float) right - valueColumnWidth;
        if (valueColumnLeft < left + 2f) {
            valueColumnLeft = left + 2f;
            valueColumnWidth = (float) right - valueColumnLeft;
        }
        float labelMaxRight = valueColumnLeft - 4f;
        float labelMaxWidth = Math.max(6f, labelMaxRight - left);

        if (!safeLabel.isEmpty() && labelPaint.measureText(safeLabel) > labelMaxWidth) {
            while (safeLabel.length() > 1 && labelPaint.measureText(safeLabel + "...") > labelMaxWidth) {
                safeLabel = safeLabel.substring(0, safeLabel.length() - 1);
            }
            safeLabel = safeLabel + "...";
        }
        labelPaint.setTextAlign(Align.LEFT);
        canvas.drawText(safeLabel, left, baseline + labelPaint.getTextSize(), labelPaint);
        if (!safeValue.isEmpty()) {
            valuePaint.setTextAlign(Align.RIGHT);
            float cellRight = (float) right - 2f;
            canvas.drawText(safeValue, cellRight, baseline + valuePaint.getTextSize(), valuePaint);
            valuePaint.setTextAlign(Align.LEFT);
        }
        return baseline + labelPaint.getTextSize() + 1;
    }

    private static String getNutritionFixedField(JSONObject config, String key, String field) {
        String directKey = "value".equals(field) ? key : key + "Unit";
        String direct = getString(config, directKey, "").trim();
        if (!direct.isEmpty()) return direct;
        JSONArray rows = config.optJSONArray("fixedNutrients");
        if (rows == null) return "";
        for (int i = 0; i < rows.length(); i++) {
            JSONObject item = rows.optJSONObject(i);
            if (item == null) continue;
            if (!key.equals(getString(item, "key", "").trim())) continue;
            return getString(item, field, "").trim();
        }
        return "";
    }

    private static String nutritionDisplayValue(String value, String unit) {
        String v = value == null ? "" : value.trim();
        String u = unit == null ? "" : unit.trim();
        if (v.isEmpty() && u.isEmpty()) return "";
        return "<" + v + (u.isEmpty() ? "" : (" " + u));
    }

    private static BitmapPatch createImagePatch(JSONObject element, JSONObject config, int dpi, String sourceOverride) {
        String source = sourceOverride;
        if (source == null || source.isEmpty()) {
            source = getString(config, "src", getString(config, "data", getString(config, "url", "")));
        }
        if (source.isEmpty()) return null;
        Bitmap sourceBitmap = decodeBitmap(source);
        if (sourceBitmap == null) return null;

        int width = ensureMultipleOf8(Math.max(8, pxToDots(getDouble(element, "width", 0), dpi)));
        int height = Math.max(8, pxToDots(getDouble(element, "height", 0), dpi));
        Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outputBitmap);
        canvas.drawColor(Color.WHITE);

        int sourceWidth = sourceBitmap.getWidth();
        int sourceHeight = sourceBitmap.getHeight();
        String scaleMode = getString(config, "scaleMode", "contain").toLowerCase();
        int targetWidth = width;
        int targetHeight = height;
        int targetLeft = 0;
        int targetTop = 0;

        if (sourceWidth > 0 && sourceHeight > 0 && !"fill".equals(scaleMode)) {
            double ratio = "cover".equals(scaleMode)
                    ? Math.max((double) width / sourceWidth, (double) height / sourceHeight)
                    : Math.min((double) width / sourceWidth, (double) height / sourceHeight);
            targetWidth = Math.max(1, (int) Math.round(sourceWidth * ratio));
            targetHeight = Math.max(1, (int) Math.round(sourceHeight * ratio));
            targetLeft = (width - targetWidth) / 2;
            targetTop = (height - targetHeight) / 2;
        }

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(sourceBitmap, targetWidth, targetHeight, true);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawBitmap(scaledBitmap, targetLeft, targetTop, paint);

        BitmapPatch patch = new BitmapPatch(pxToDots(getDouble(element, "x", 0), dpi),
                yDots(getDouble(element, "y", 0), dpi),
                bitmapToMonochrome(outputBitmap, (int) getDouble(config, "threshold", DEFAULT_THRESHOLD)));

        scaledBitmap.recycle();
        sourceBitmap.recycle();
        outputBitmap.recycle();
        return patch;
    }

    private static boolean isImageLikeSource(String source) {
        if (source == null) return false;
        String s = source.trim().toLowerCase();
        if (s.isEmpty()) return false;
        if (s.startsWith("data:image/")) return true;
        if (s.startsWith("file://")) return true;
        if (s.startsWith("/picture/") || s.startsWith("picture/")) return true;
        if (s.startsWith("/static/") || s.startsWith("static/")) return true;
        if (s.matches("^[a-z]:[\\\\/].*")) return true;
        return s.matches(".*\\.(png|jpe?g|gif|webp|bmp)(\\?.*)?$");
    }

    private static Bitmap decodeBitmap(String source) {
        try {
            if (source.startsWith("data:image/")) {
                int comma = source.indexOf(',');
                String payload = comma >= 0 ? source.substring(comma + 1) : "";
                if (payload.isEmpty()) return null;
                byte[] bytes = Base64.decode(payload, Base64.DEFAULT);
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
            if (source.matches("^[A-Za-z0-9+/=\\r\\n]+$") && source.length() > 128) {
                byte[] bytes = Base64.decode(source, Base64.DEFAULT);
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
            String path = source.startsWith("file://") ? source.substring(7) : source;
            return BitmapFactory.decodeFile(path);
        } catch (Exception e) {
            return null;
        }
    }

    private static java.util.List<String> splitTextLines(String text, Paint paint, int maxWidth) {
        java.util.List<String> lines = new java.util.ArrayList<>();
        String[] rawLines = (text == null ? "" : text.replace("\r", "")).split("\n");
        for (String segment : rawLines) {
            if (segment.isEmpty()) {
                lines.add("");
                continue;
            }
            StringBuilder current = new StringBuilder();
            for (int i = 0; i < segment.length(); i++) {
                char c = segment.charAt(i);
                String candidate = current.toString() + c;
                if (current.length() > 0 && paint.measureText(candidate) > maxWidth) {
                    lines.add(current.toString());
                    current.setLength(0);
                    current.append(c);
                } else {
                    current.append(c);
                }
            }
            if (current.length() > 0) lines.add(current.toString());
        }
        if (lines.isEmpty()) lines.add("");
        return lines;
    }

    /**
     * 限制位图宽度不超过标签右边界,避免 TSC 把溢出列折到 x=0(右边框出现在最左侧)。
     */
    private static BitmapPatch constrainPatchToPage(BitmapPatch patch, int pageWidthDots) {
        if (patch == null || patch.image == null || pageWidthDots <= 0) return patch;
        int x = Math.max(0, patch.x);
        int maxW = pageWidthDots - x - RIGHT_SAFE_MARGIN_DOTS;
        if (maxW < 8) return null;
        if (patch.image.width <= maxW) {
            if (x == patch.x) return patch;
            return new BitmapPatch(x, patch.y, patch.image);
        }
        int targetW = ensureMultipleOf8(maxW);
        MonochromeImage fitted = scaleMonochromeProportional(patch.image, targetW);
        if (fitted == null) return null;
        return new BitmapPatch(x, patch.y, fitted);
    }

    private static MonochromeImage scaleMonochromeProportional(MonochromeImage src, int targetWidth) {
        if (src == null || src.width <= 0 || src.height <= 0) return src;
        if (targetWidth >= src.width) return src;
        targetWidth = ensureMultipleOf8(Math.max(8, targetWidth));
        int targetHeight = Math.max(8, (int) Math.round((double) src.height * targetWidth / (double) src.width));
        Bitmap srcBitmap = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888);
        for (int y = 0; y < src.height; y++) {
            for (int x = 0; x < src.width; x++) {
                int v = src.pixels[y * src.width + x];
                srcBitmap.setPixel(x, y, v == 1 ? Color.BLACK : Color.WHITE);
            }
        }
        Bitmap scaled = Bitmap.createScaledBitmap(srcBitmap, targetWidth, targetHeight, false);
        srcBitmap.recycle();
        MonochromeImage mono = bitmapToMonochrome(scaled, DEFAULT_THRESHOLD);
        scaled.recycle();
        return mono;
    }

    /**
     * 与 JS pixelsToTscBitmapBytes 一致:mono 1=黑墨、0=白纸;TSC 位 0=黑点、位 1=不印。
     */
    private static void writeBitmapPatch(ByteArrayOutputStream out, BitmapPatch patch, int pageWidthDots) {
        writeBitmapPatchRaw(out, constrainPatchToPage(patch, pageWidthDots));
    }

    private static void writeBitmapPatchRaw(ByteArrayOutputStream out, BitmapPatch patch) {
        if (patch == null || patch.image == null) return;
        int bytesPerRow = patch.image.width / 8;
        addLine(out, "BITMAP " + patch.x + "," + patch.y + "," + bytesPerRow + "," + patch.image.height + ",0,");
        for (int y = 0; y < patch.image.height; y++) {
            for (int byteIndex = 0; byteIndex < bytesPerRow; byteIndex++) {
                int value = 0;
                for (int bit = 0; bit < 8; bit++) {
                    int x = byteIndex * 8 + bit;
                    int pixel = patch.image.pixels[y * patch.image.width + x];
                    if (pixel == 0) {
                        value |= (1 << (7 - bit));
                    }
                }
                out.write(value & 0xFF);
            }
        }
        out.write('\r');
        out.write('\n');
    }

    /** 设计 px 位图按 203dpi 缩放到打印点阵,与 APP 预览物理比例一致 */
    private static MonochromeImage monochromeScaledToPrintDots(Bitmap designBitmap, int dpi, int threshold) {
        if (designBitmap == null) return null;
        int designW = Math.max(1, designBitmap.getWidth());
        int designH = Math.max(1, designBitmap.getHeight());
        int printW = ensureMultipleOf8(Math.max(8, pxToDots(designW, dpi)));
        int printH = Math.max(8, pxToDots(designH, dpi));
        Bitmap scaled = Bitmap.createScaledBitmap(designBitmap, printW, printH, false);
        MonochromeImage mono = bitmapToMonochrome(scaled, threshold);
        if (scaled != designBitmap) {
            scaled.recycle();
        }
        return mono;
    }

    private static MonochromeImage bitmapToMonochrome(Bitmap bitmap, int threshold) {
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        /** 位图宽已是 8 倍数时不再右补白列,减少 TSC 行宽错位导致左边出现「折过来的右边框」 */
        int width = bitmapWidth % 8 == 0 ? bitmapWidth : ensureMultipleOf8(bitmapWidth);
        int[] pixels = new int[width * bitmapHeight];
        for (int y = 0; y < bitmapHeight; y++) {
            for (int x = 0; x < width; x++) {
                if (x >= bitmapWidth) {
                    pixels[y * width + x] = 0;
                    continue;
                }
                int color = bitmap.getPixel(x, y);
                int alpha = (color >>> 24) & 0xFF;
                int red = (color >>> 16) & 0xFF;
                int green = (color >>> 8) & 0xFF;
                int blue = color & 0xFF;
                double gray = red * 0.299 + green * 0.587 + blue * 0.114;
                pixels[y * width + x] = alpha <= 10 || gray > threshold ? 0 : 1;
            }
        }
        return new MonochromeImage(width, bitmapHeight, pixels);
    }

    private static MonochromeImage invertMonochrome(MonochromeImage image) {
        if (image == null || image.pixels == null) return image;
        int[] pixels = new int[image.pixels.length];
        for (int i = 0; i < image.pixels.length; i++) {
            pixels[i] = image.pixels[i] == 1 ? 0 : 1;
        }
        return new MonochromeImage(image.width, image.height, pixels);
    }

    private static void addLine(ByteArrayOutputStream out, String line) {
        byte[] bytes = line.getBytes(getPrinterCharset());
        out.write(bytes, 0, bytes.length);
        out.write('\r');
        out.write('\n');
    }

    private static Charset getPrinterCharset() {
        try {
            return Charset.forName("windows-1252");
        } catch (Throwable first) {
            try {
                return Charset.forName("Cp1252");
            } catch (Throwable second) {
                return StandardCharsets.ISO_8859_1;
            }
        }
    }

    private static CharsetEncoder getPrinterEncoder() {
        try {
            return getPrinterCharset().newEncoder();
        } catch (Throwable first) {
            try {
                return StandardCharsets.ISO_8859_1.newEncoder();
            } catch (Throwable second) {
                return null;
            }
        }
    }

    private static String escapeTscString(String value) {
        return value == null ? "" : value.replace("\\", "\\\\").replace("\"", "\\\"");
    }

    private static String normalizeBarcodeType(String value) {
        String key = value == null ? "CODE128" : value.trim().toUpperCase();
        switch (key) {
            case "CODE39": return "39";
            case "EAN13": return "EAN13";
            case "EAN8": return "EAN8";
            case "UPCA": return "UPCA";
            case "UPCE": return "UPCE";
            case "CODABAR": return "CODA";
            case "ITF14": return "ITF14";
            case "ITF": return "ITF";
            default: return "128";
        }
    }

    /** TSC CODABAR 需起止符;纯数字在部分佳博/Virtual BT 上 BARCODE 指令会静默失败 */
    private static String formatBarcodeValueForTsc(String symbology, String value) {
        if (value == null || value.trim().isEmpty()) return "";
        String raw = value.trim();
        if (!"CODA".equalsIgnoreCase(symbology)) return raw;
        String upper = raw.toUpperCase();
        boolean hasStart = upper.length() > 0 && "ABCD".indexOf(upper.charAt(0)) >= 0;
        boolean hasStop = upper.length() > 0 && "TNE*".indexOf(upper.charAt(upper.length() - 1)) >= 0;
        if (hasStart && hasStop) return upper;
        String body = raw.replaceAll("[^0-9\\-$:/.+]", "");
        if (body.isEmpty()) return raw;
        return "A" + body + "B";
    }

    private static String normalizeQrLevel(String value) {
        String key = value == null ? "M" : value.trim().toUpperCase();
        if ("L".equals(key) || "M".equals(key) || "Q".equals(key) || "H".equals(key)) return key;
        return "M";
    }

    private static int resolveQrModuleSize(double widthPx, double heightPx, int dpi, String value, String level) {
        int targetDots = Math.max(24, Math.min(pxToDots(widthPx, dpi), pxToDots(heightPx, dpi)));
        int moduleCount = Math.max(21, estimateQrModuleCount(value, level));
        return clamp(Math.floorDiv(targetDots, moduleCount), 3, 12);
    }

    private static int estimateQrModuleCount(String value, String level) {
        int length = Math.max(1, value == null ? 0 : value.length());
        int[] capacities;
        switch (level) {
            case "L": capacities = new int[]{17, 32, 53, 78, 106, 134, 154, 192, 230, 271}; break;
            case "Q": capacities = new int[]{11, 20, 32, 46, 60, 74, 86, 108, 130, 151}; break;
            case "H": capacities = new int[]{7, 14, 24, 34, 44, 58, 64, 84, 98, 119}; break;
            default: capacities = new int[]{14, 26, 42, 62, 84, 106, 122, 152, 180, 213};
        }
        int version = capacities.length;
        for (int i = 0; i < capacities.length; i++) {
            if (length <= capacities[i]) {
                version = i + 1;
                break;
            }
        }
        return 21 + (version - 1) * 4;
    }

    private static int resolveTextScale(double fontSizePx, int dpi) {
        int targetDots = Math.max(12, (int) Math.round(fontSizePx * dpi / DESIGN_DPI));
        return clamp(targetDots / 24.0, 1, 7);
    }

    private static int resolveTextX(String align, double xPx, double widthPx, int dpi, String text, int scale) {
        int left = pxToDots(xPx, dpi);
        if ("left".equals(align)) return left;
        int boxWidth = pxToDots(widthPx, dpi);
        int fontDots = Math.max(24, scale * 24);
        int textWidth = estimateTextWidthDots(text, fontDots);
        if ("center".equals(align)) return Math.max(0, left + Math.max(0, boxWidth - textWidth) / 2);
        return Math.max(0, left + Math.max(0, boxWidth - textWidth - RIGHT_SAFE_MARGIN_DOTS));
    }

    private static int resolveNutritionValueX(double innerX, double innerW, int dpi, String text, int scale) {
        int left = pxToDots(innerX, dpi);
        int boxWidth = pxToDots(innerW, dpi);
        int fontDots = Math.max(24, scale * 24);
        int textWidth = estimateTextWidthDots(text, fontDots);
        return Math.max(left, left + Math.max(0, boxWidth - textWidth - NUTRITION_VALUE_RIGHT_MARGIN_DOTS));
    }

    private static int estimateTextWidthDots(String text, int fontDots) {
        double total = 0;
        for (int i = 0; i < text.length(); i++) {
            total += text.charAt(i) > 255 ? fontDots : fontDots * 0.6;
        }
        return (int) Math.round(total);
    }

    private static int clamp(double value, int min, int max) {
        return Math.max(min, Math.min(max, (int) Math.round(value)));
    }

    private static int ensureMultipleOf8(int value) {
        int safe = Math.max(8, value);
        return safe % 8 == 0 ? safe : safe + (8 - safe % 8);
    }

    private static int pxToDots(double value, int dpi) {
        return Math.max(0, (int) Math.round(value * dpi / DESIGN_DPI));
    }

    /** 模板 y(px)→ 点阵 y,并加上与光栅路径一致的上边距,减轻顶部裁切 */
    private static int yDots(double yPx, int dpi) {
        return Math.max(0, pxToDots(yPx, dpi) + LABEL_TOP_MARGIN_DOTS);
    }

    private static double toMillimeter(double value, String unit) {
        if ("mm".equalsIgnoreCase(unit)) return value;
        if ("cm".equalsIgnoreCase(unit)) return value * 10;
        if ("px".equalsIgnoreCase(unit)) return value / DESIGN_DPI * 25.4;
        return value * 25.4;
    }

    private static double round1(double value) {
        return Math.round(value * 10.0) / 10.0;
    }

    private static String formatMm(double value) {
        return String.format(java.util.Locale.US, "%.1f", value);
    }

    private static String getString(JSONObject json, String key, String fallback) {
        Object value = json.opt(key);
        return value == null ? fallback : String.valueOf(value);
    }

    private static double getDouble(JSONObject json, String key, double fallback) {
        try {
            Object value = json.opt(key);
            if (value == null) return fallback;
            if (value instanceof Number) return ((Number) value).doubleValue();
            return Double.parseDouble(String.valueOf(value));
        } catch (Exception e) {
            return fallback;
        }
    }

    private static boolean getBoolean(JSONObject json, String key, boolean fallback) {
        try {
            Object value = json.opt(key);
            if (value == null) return fallback;
            if (value instanceof Boolean) return (Boolean) value;
            return Boolean.parseBoolean(String.valueOf(value));
        } catch (Exception e) {
            return fallback;
        }
    }

    private static final class BitmapPatch {
        final int x;
        final int y;
        final MonochromeImage image;

        BitmapPatch(int x, int y, MonochromeImage image) {
            this.x = x;
            this.y = y;
            this.image = image;
        }
    }

    private static final class MonochromeImage {
        final int width;
        final int height;
        final int[] pixels;

        MonochromeImage(int width, int height, int[] pixels) {
            this.width = width;
            this.height = height;
            this.pixels = pixels;
        }
    }

    public static final class BuildResult {
        public final byte[] bytes;
        public final int nativeTextCount;
        public final int rasterTextCount;
        public final int qrCodeCount;
        public final int barcodeCount;
        public final int imagePatchCount;
        public final int lineCount;
        public final int elementCount;

        public BuildResult(byte[] bytes, int nativeTextCount, int rasterTextCount, int qrCodeCount, int barcodeCount,
                    int imagePatchCount, int lineCount, int elementCount) {
            this.bytes = bytes == null ? new byte[0] : bytes;
            this.nativeTextCount = nativeTextCount;
            this.rasterTextCount = rasterTextCount;
            this.qrCodeCount = qrCodeCount;
            this.barcodeCount = barcodeCount;
            this.imagePatchCount = imagePatchCount;
            this.lineCount = lineCount;
            this.elementCount = elementCount;
        }
    }
}