Skip to content

BaseTemplate

src.templates._core.BaseTemplate

Master Template for Proxyshop all others should extend to.

Notes
  • Contains all the core architecture that is required for any template to function in Proxyshop, as well as a ton of optional built-in utility properties and methods for building templates.
Source code in src\templates\_core.py
  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
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
class BaseTemplate:
    """Master Template for Proxyshop all others should extend to.

    Notes:
        - Contains all the core architecture that is required for any template to function in Proxyshop,
            as well as a ton of optional built-in utility properties and methods for building templates.
    """
    frame_suffix = 'Normal'
    template_suffix = ''

    def __init__(self, layout: Any, **kwargs):

        # Setup manual properties
        self.layout = layout
        self._text = []

    """
    * Enabled Method Lists
    """

    @property
    def pre_render_methods(self) -> list[Callable]:
        """list[Callable]: Methods called before rendering begins.

        Methods:
            `process_layout_data`: Processes layout data before it is used to generate the card.
        """
        return [self.process_layout_data]

    @property
    def frame_layer_methods(self) -> list[Callable]:
        """list[Callable]: Methods called to insert and enable frame layers.

        Methods:
            `color_border`: Changes the border color if required and supported by the template.
            `enable_frame_layers`:
        """
        return [self.color_border, self.enable_frame_layers]

    @property
    def text_layer_methods(self) -> list[Callable]:
        """list[Callable]: Methods called to insert and format text layers."""
        return [
            self.collector_info,
            self.basic_text_layers,
            self.rules_text_and_pt_layers
        ]

    @property
    def post_text_methods(self) -> list[Callable]:
        """list[Callable]: Methods called after text is inserted and formatted."""
        return []

    @property
    def post_save_methods(self) -> list[Callable]:
        """list[Callable]: Methods called after the rendered image is saved."""
        return []

    """
    * Hook Method List
    """

    @property
    def hooks(self) -> list[Callable]:
        """list[Callable]: List of methods that will be called during the hooks execution step"""
        hooks = []
        if self.is_creature:
            # Creature hook
            hooks.append(self.hook_creature)
        if 'P' in self.layout.mana_cost or '/' in self.layout.mana_cost:
            # Large mana symbol hook
            hooks.append(self.hook_large_mana)
        return hooks

    def hook_creature(self) -> None:
        """Run this if card is a creature."""
        pass

    def hook_large_mana(self) -> None:
        """Run this if card has a large mana symbol."""
        pass

    """
    * App Properties
    """

    @auto_prop_cached
    def event(self) -> Event:
        """Event: Threading Event used to signal thread cancellation."""
        return Event()

    @auto_prop_cached
    def console(self) -> type[CONSOLE]:
        """type[CONSOLE]: Console output object used to communicate with the user."""
        return CONSOLE

    @property
    def app(self) -> PhotoshopHandler:
        """PhotoshopHandler: Photoshop Application object used to communicate with Photoshop."""
        return APP

    @auto_prop_cached
    def docref(self) -> Optional[Document]:
        """Optional[Document]: This template's document open in Photoshop."""
        if doc := psd.get_document(osp.basename(self.layout.template_file)):
            return doc
        return

    @auto_prop_cached
    def doc_selection(self) -> Selection:
        """Selection: Active document selection object."""
        return self.docref.selection

    @property
    def active_layer(self) -> Union[ArtLayer, LayerSet]:
        """Union[ArtLayer, LayerSet]: Get the currently active layer in the Photoshop document."""
        return self.docref.activeLayer

    @active_layer.setter
    def active_layer(self, value: Union[ArtLayer, LayerSet]):
        """Set the currently active layer in the Photoshop document.

        Args:
            value: An ArtLayer or LayerSet to make active.
        """
        self.docref.activeLayer = value

    """
    * SolidColor objects
    """

    @auto_prop_cached
    def RGB_BLACK(self) -> SolidColor:
        """SolidColor: A solid color object with RGB [0, 0, 0]."""
        return psd.rgb_black()

    @auto_prop_cached
    def RGB_WHITE(self) -> SolidColor:
        """SolidColor: A solid color object with RGB [255, 255, 255]."""
        return psd.rgb_white()

    """
    * File Saving
    """

    @auto_prop_cached
    def save_mode(self) -> Callable:
        """Callable: Function called to save the rendered image."""
        if CFG.output_file_type == OutputFileType.PNG:
            return psd.save_document_png
        if CFG.output_file_type == OutputFileType.PSD:
            return psd.save_document_psd
        return psd.save_document_jpeg

    @auto_prop_cached
    def output_directory(self) -> Path:
        """PathL Directory to save the rendered image."""
        if ENV.TEST_MODE:
            path = PATH.OUT / self.__class__.__name__
            path.mkdir(mode=777, parents=True, exist_ok=True)
            return path
        return PATH.OUT

    @auto_prop_cached
    def output_file_name(self) -> Path:
        """Path: The formatted filename for the rendered image."""
        name, tag_map = CFG.output_file_name, {
            '#name': self.layout.name_raw,
            '#artist': self.layout.artist,
            '#set': self.layout.set,
            '#num': str(self.layout.collector_number),
            '#frame': self.frame_suffix,
            '#suffix': self.template_suffix,
            '#creator': self.layout.creator,
            '#lang': self.layout.lang
        }

        # Replace conditional tags
        for n in Reg.PATH_CONDITION.findall(name):
            case_new, case = n, f'<{n}>'
            for tag, val in tag_map.items():
                if tag in case and not val:
                    name, case_new = name.replace(case, ''), ''
                    break
                if tag in case:
                    case_new = case_new.replace(tag, val)
            if case_new:
                name = name.replace(case, case_new)

        # Replace other tags
        for tag, value in tag_map.items():
            if value:
                name = name.replace(tag, value)
        path = Path(
            self.output_directory,
            sanitize_filename(name)
        ).with_suffix(f'.{CFG.output_file_type}')

        # Are we overwriting duplicate names?
        if not CFG.overwrite_duplicate:
            path = get_unique_filename(path)
        return path

    """
    * Cosmetic Extendable Checks
    """

    @property
    def is_hollow_crown(self) -> bool:
        """bool: Governs whether a hollow crown should be rendered."""
        return False

    @property
    def is_fullart(self) -> bool:
        """bool: Returns True if art must be treated as Fullart."""
        return False

    """
    * Boolean Checks
    """

    @property
    def is_creature(self) -> bool:
        """bool: Governs whether to add PT box and use Creature rules text."""
        return self.layout.is_creature

    @property
    def is_legendary(self) -> bool:
        """bool: Enables the legendary crown step."""
        return self.layout.is_legendary

    @property
    def is_land(self) -> bool:
        """bool: Governs whether to use normal or land pinlines group."""
        return self.layout.is_land

    @property
    def is_artifact(self) -> bool:
        """bool: Utility definition for custom templates. Returns True if card is an Artifact."""
        return self.layout.is_artifact

    @property
    def is_vehicle(self) -> bool:
        """bool: Utility definition for custom templates. Returns True if card is a Vehicle."""
        return self.layout.is_vehicle

    @property
    def is_hybrid(self) -> bool:
        """bool: Utility definition for custom templates. Returns True if card is hybrid color."""
        return self.layout.is_hybrid

    @property
    def is_colorless(self) -> bool:
        """bool: Enforces fullart framing for card art on many templates."""
        return self.layout.is_colorless

    @property
    def is_front(self) -> bool:
        """bool: Governs render behavior on MDFC and Transform cards."""
        return self.layout.is_front

    @property
    def is_transform(self) -> bool:
        """bool: Governs behavior on double faced card varieties."""
        return self.layout.is_transform

    @property
    def is_mdfc(self) -> bool:
        """bool: Governs behavior on double faced card varieties."""
        return self.layout.is_mdfc

    @property
    def is_companion(self) -> bool:
        """bool: Enables companion cosmetic elements."""
        return self.layout.is_companion

    @property
    def is_nyx(self) -> bool:
        """bool: Enables nyxtouched cosmetic elements."""
        return self.layout.is_nyx

    @property
    def is_snow(self) -> bool:
        """bool: Enables snow cosmetic elements."""
        return self.layout.is_snow

    @property
    def is_miracle(self) -> bool:
        """bool: Enables miracle cosmetic elements."""
        return self.layout.is_miracle

    @property
    def is_token(self) -> bool:
        """bool: Enables token cosmetic elements."""
        return self.layout.is_token

    @property
    def is_emblem(self) -> bool:
        """bool: Enables emblem cosmetic elements."""
        return self.layout.is_emblem

    """
    * Cached Properties
    * Calculated in BaseTemplate class
    """

    @auto_prop_cached
    def is_basic_land(self) -> bool:
        """bool: Governs Basic Land watermark and other Basic Land behavior."""
        return self.layout.is_basic_land

    @auto_prop_cached
    def is_centered(self) -> bool:
        """bool: Governs whether rules text is centered."""
        return bool(
            len(self.layout.flavor_text) <= 1
            and len(self.layout.oracle_text) <= 70
            and "\n" not in self.layout.oracle_text)

    @auto_prop_cached
    def is_name_shifted(self) -> bool:
        """bool: Governs whether to use the shifted name text layer."""
        return bool(self.is_transform or self.is_mdfc)

    @auto_prop_cached
    def is_type_shifted(self) -> bool:
        """bool: Governs whether to use the shifted typeline text layer."""
        return bool(self.layout.color_indicator)

    @auto_prop_cached
    def is_flipside_creature(self) -> bool:
        """bool: Governs double faced cards where opposing side is a creature."""
        return bool(self.layout.other_face_power and self.layout.other_face_toughness)

    @auto_prop_cached
    def is_art_vertical(self) -> bool:
        """bool: Returns True if art provided is vertically oriented, False if it is horizontal."""
        with Image.open(self.layout.art_file) as image:
            width, height = image.size
        if height > (width * 1.1):
            # Vertical orientation
            return True
        # Horizontal orientation
        return False

    @auto_prop_cached
    def is_content_aware_enabled(self) -> bool:
        """bool: Governs whether content aware fill should be performed during the art loading step."""
        if self.is_fullart and all([n not in self.art_reference.name for n in ['Full', 'Borderless']]):
            # By default, fill when we want a fullart image but didn't receive one
            return True
        return False

    @auto_prop_cached
    def is_collector_promo(self) -> bool:
        """bool: Governs whether to use promo star in collector info."""
        if CFG.collector_promo == CollectorPromo.Always:
            return True
        if self.layout.is_promo and CFG.collector_promo == CollectorPromo.Automatic:
            return True
        return False

    """
    * Frame Details
    """

    @property
    def art_frame(self) -> str:
        """str: Normal frame to use for positioning the art."""
        return LAYERS.ART_FRAME

    @property
    def art_frame_vertical(self) -> str:
        """str: Vertical orientation frame to use for positioning the art."""
        return LAYERS.FULL_ART_FRAME

    @auto_prop_cached
    def twins(self) -> str:
        """str: Name of the Twins layer, also usually the PT layer."""
        return self.layout.twins

    @auto_prop_cached
    def pinlines(self) -> str:
        """str: Name of the Pinlines layer."""
        return self.layout.pinlines

    @auto_prop_cached
    def identity(self) -> str:
        """str: Color identity of the card, e.g. WU."""
        return self.layout.identity

    @auto_prop_cached
    def background(self) -> str:
        """str: Name of the Background layer."""
        if not self.is_vehicle and self.layout.background == LAYERS.VEHICLE:
            return LAYERS.ARTIFACT
        return self.layout.background

    @auto_prop_cached
    def color_limit(self) -> int:
        """int: Number of colors where frame elements will no longer split (becomes gold)."""
        return 3

    """
    * Layer Groups
    """

    @auto_prop_cached
    def legal_group(self) -> LayerSet:
        """LayerSet: Group containing artist credit, collector info, and other legal details."""
        return self.docref.layerSets[LAYERS.LEGAL]

    @auto_prop_cached
    def border_group(self) -> Optional[Union[LayerSet, ArtLayer]]:
        """Optional[Union[LayerSet, ArtLayer]]: Group, or sometimes a layer, containing the card border."""
        if group := psd.getLayerSet(LAYERS.BORDER, self.docref):
            return group
        if layer := psd.getLayer(LAYERS.BORDER, self.docref):
            return layer
        return

    @auto_prop_cached
    def text_group(self) -> Optional[LayerSet]:
        """Optional[LayerSet]: Text and icon group, contains rules text and necessary symbols."""
        with suppress(Exception):
            return self.docref.layerSets[LAYERS.TEXT_AND_ICONS]
        return self.docref

    @auto_prop_cached
    def dfc_group(self) -> Optional[LayerSet]:
        """Optional[LayerSet]: Group containing double face elements."""
        face = LAYERS.FRONT if self.is_front else LAYERS.BACK
        if self.is_transform:
            return psd.getLayerSet(face, [self.text_group, LAYERS.TRANSFORM])
        if self.is_mdfc:
            return psd.getLayerSet(f'{LAYERS.MDFC} {face}', self.text_group)
        return

    @auto_prop_cached
    def mask_group(self) -> Optional[LayerSet]:
        """LayerSet: Group containing masks used to blend and adjust various layers."""
        with suppress(Exception):
            return self.docref.layerSets[LAYERS.MASKS]
        return

    """
    * Text Layers
    """

    @auto_prop_cached
    def text_layer_creator(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Proxy creator name text layer."""
        return psd.getLayer(LAYERS.CREATOR, self.legal_group)

    @auto_prop_cached
    def text_layer_name(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Card name text layer."""
        if self.is_name_shifted:
            psd.getLayer(LAYERS.NAME, self.text_group).visible = False
            name = psd.getLayer(LAYERS.NAME_SHIFT, self.text_group)
            name.visible = True
            return name
        return psd.getLayer(LAYERS.NAME, self.text_group)

    @auto_prop_cached
    def text_layer_mana(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Card mana cost text layer."""
        return psd.getLayer(LAYERS.MANA_COST, self.text_group)

    @auto_prop_cached
    def text_layer_type(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Card typeline text layer."""
        if self.is_type_shifted:
            psd.getLayer(LAYERS.TYPE_LINE, self.text_group).visible = False
            typeline = psd.getLayer(LAYERS.TYPE_LINE_SHIFT, self.text_group)
            typeline.visible = True
            return typeline
        return psd.getLayer(LAYERS.TYPE_LINE, self.text_group)

    @auto_prop_cached
    def text_layer_rules(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Card rules text layer."""
        if self.is_creature:
            return psd.getLayer(LAYERS.RULES_TEXT_CREATURE, self.text_group)
        return psd.getLayer(LAYERS.RULES_TEXT_NONCREATURE, self.text_group)

    @auto_prop_cached
    def text_layer_pt(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Card power and toughness text layer."""
        return psd.getLayer(LAYERS.POWER_TOUGHNESS, self.text_group)

    @auto_prop_cached
    def divider_layer(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Divider layer between rules text and flavor text."""
        if self.is_transform and self.is_front and self.is_flipside_creature:
            if TF_DIVIDER := psd.getLayer('Divider TF', self.text_group):
                return TF_DIVIDER
        return psd.getLayer(LAYERS.DIVIDER, self.text_group)

    """
    * Frame Layers
    """

    @property
    def art_layer(self) -> ArtLayer:
        """ArtLayer: Layer the art image is imported into."""
        return psd.getLayer(LAYERS.DEFAULT, self.docref)

    @auto_prop_cached
    def twins_layer(self) -> Optional[ArtLayer]:
        """Name and title boxes layer."""
        return psd.getLayer(self.twins, LAYERS.TWINS)

    @auto_prop_cached
    def pinlines_layer(self) -> Optional[ArtLayer]:
        """Pinlines (and textbox) layer."""
        if self.is_land:
            return psd.getLayer(self.pinlines, LAYERS.LAND_PINLINES_TEXTBOX)
        return psd.getLayer(self.pinlines, LAYERS.PINLINES_TEXTBOX)

    @auto_prop_cached
    def background_layer(self) -> Optional[ArtLayer]:
        """Background texture layer."""
        # Try finding Vehicle background
        if self.is_vehicle and self.background == LAYERS.VEHICLE:
            return psd.getLayer(
                LAYERS.VEHICLE, LAYERS.BACKGROUND
            ) or psd.getLayer(
                LAYERS.ARTIFACT, LAYERS.BACKGROUND)
        # All other backgrounds
        return psd.getLayer(self.background, LAYERS.BACKGROUND)

    @auto_prop_cached
    def pt_layer(self) -> Optional[ArtLayer]:
        """Power and toughness box layer."""
        # Test for Vehicle PT support
        if self.is_vehicle and self.background == LAYERS.VEHICLE:
            if layer := psd.getLayer(LAYERS.VEHICLE, LAYERS.PT_BOX):
                # Change font to white for Vehicle PT box
                self.text_layer_pt.textItem.color = self.RGB_WHITE
                return layer
        return psd.getLayer(self.twins, LAYERS.PT_BOX)

    @auto_prop_cached
    def crown_layer(self) -> Optional[ArtLayer]:
        """Legendary crown layer."""
        return psd.getLayer(self.pinlines, LAYERS.LEGENDARY_CROWN)

    @auto_prop_cached
    def crown_shadow_layer(self) -> Union[ArtLayer, LayerSet, None]:
        """Legendary crown hollow shadow layer."""
        return psd.getLayer(LAYERS.HOLLOW_CROWN_SHADOW, self.docref)

    @auto_prop_cached
    def color_indicator_layer(self) -> Optional[ArtLayer]:
        """Color indicator icon layer."""
        if self.layout.color_indicator:
            return psd.getLayer(self.layout.color_indicator, LAYERS.COLOR_INDICATOR)
        return

    @auto_prop_cached
    def transform_icon_layer(self) -> Optional[ArtLayer]:
        """Optional[ArtLayer]: Transform icon layer."""
        return psd.getLayer(self.layout.transform_icon, self.dfc_group)

    """
    * Reference Layers
    """

    @auto_prop_cached
    def art_reference(self) -> ReferenceLayer:
        """ReferenceLayer: Reference frame used to scale and position the art layer."""
        # Check if art is vertically oriented, or forced vertical, and for valid vertical frame
        if self.is_art_vertical or (self.is_fullart and CFG.vertical_fullart):
            if layer := psd.get_reference_layer(self.art_frame_vertical):
                return layer
        # Check for normal art frame
        return psd.get_reference_layer(self.art_frame) or psd.get_reference_layer(LAYERS.ART_FRAME)

    @auto_prop_cached
    def name_reference(self) -> Optional[ArtLayer]:
        """ArtLayer: By default, name uses Mana Cost as a reference to check collision against."""
        if self.is_basic_land:
            return
        return self.text_layer_mana

    @auto_prop_cached
    def type_reference(self) -> Optional[ArtLayer]:
        """ArtLayer: By default, typeline uses the expansion symbol to check collision against,
        otherwise fallback to the expansion symbols reference layer."""
        if self.is_basic_land:
            return
        return self.expansion_symbol_layer or self.expansion_reference

    @auto_prop_cached
    def textbox_reference(self) -> ReferenceLayer:
        """ReferenceLayer: Reference frame used to scale and position the rules text layer."""
        return psd.get_reference_layer(LAYERS.TEXTBOX_REFERENCE, self.text_group)

    @auto_prop_cached
    def pt_reference(self) -> Optional[ReferenceLayer]:
        """ArtLayer: Reference used to check rules text overlap with the PT Box."""
        if not self.is_creature:
            return
        return psd.get_reference_layer(LAYERS.PT_REFERENCE, self.text_group)

    """
    * Blending Masks
    """

    @auto_prop_cached
    def mask_layers(self) -> list[ArtLayer]:
        """List of layers containing masks used to blend multicolored layers."""
        if not self.mask_group:
            return []
        if mask := psd.getLayer(LAYERS.HALF, self.mask_group):
            return [mask]
        return []

    """
    * Processing Layout Data
    """

    def process_layout_data(self) -> None:
        """Performs any required pre-processing on the provided layout data."""

        # Strip flavor text, string or list
        if CFG.remove_flavor:
            self.layout.flavor_text = "" if isinstance(
                self.layout.flavor_text, str
            ) else ['' for _ in self.layout.flavor_text]

        # Strip reminder text, string or list
        if CFG.remove_reminder:
            self.layout.oracle_text = strip_reminder_text(
                self.layout.oracle_text
            ) if isinstance(
                self.layout.oracle_text, str
            ) else [strip_reminder_text(n) for n in self.layout.oracle_text]

    """
    * Loading Artwork
    """

    @property
    def art_action(self) -> Optional[Callable]:
        """Function that is called to perform an action on the imported art."""
        return

    @property
    def art_action_args(self) -> Optional[dict]:
        """Args to pass to art_action."""
        return

    def load_artwork(self) -> None:
        """Loads the specified art file into the specified layer."""

        # Check for fullart test image
        if ENV.TEST_MODE and self.is_fullart:
            self.layout.art_file = PATH.SRC_IMG / "test-fa.jpg"

        # Paste the file into the art
        self.active_layer = self.art_layer
        if self.art_action:
            psd.paste_file(
                layer=self.art_layer,
                path=self.layout.art_file,
                action=self.art_action,
                action_args=self.art_action_args,
                docref=self.docref)
        else:
            psd.import_art(
                layer=self.art_layer,
                path=self.layout.art_file,
                docref=self.docref)

        # Frame the artwork
        psd.frame_layer(self.active_layer, self.art_reference)

        # Perform content aware fill if needed
        if self.is_content_aware_enabled:

            # Perform a generative fill
            if CFG.generative_fill:
                docref = psd.generative_fill_edges(
                    layer=self.art_layer,
                    feather=CFG.feathered_fill,
                    close_doc=not CFG.select_variation,
                    docref=self.docref)
                if docref:
                    self.console.await_choice(
                        self.event, msg="Select a Generative Fill variation, then click Continue ...")
                    docref.close(SaveOptions.SaveChanges)
                return

            # Perform a content aware fill
            psd.content_aware_fill_edges(self.art_layer, CFG.feathered_fill)

    def paste_scryfall_scan(self, rotate: bool = False, visible: bool = True) -> Optional[ArtLayer]:
        """Downloads the card's scryfall scan, pastes it into the document next to the active layer,
        and frames it to fill the given reference layer.

        Args:
            rotate: Will rotate the card horizontally if True, useful for Planar cards.
            visible: Whether to leave the layer visible or hide it.

        Returns:
            ArtLayer if Scryfall scan was imported, otherwise None.
        """
        # Try to grab the scan from Scryfall
        if not self.layout.scryfall_scan:
            return
        scryfall_scan = get_card_scan(self.layout.scryfall_scan)
        if not scryfall_scan:
            return

        # Paste the scan into a new layer
        if layer := psd.import_art_into_new_layer(
                path=scryfall_scan,
                name="Scryfall Reference",
                docref=self.docref
        ):
            # Rotate the layer if necessary
            if rotate:
                layer.rotate(90)

            # Frame the layer and position it above the art layer
            bleed = int(self.docref.resolution / 8)
            dims = psd.get_dimensions_from_bounds(
                (bleed, bleed, self.docref.width - bleed, self.docref.height - bleed))
            psd.frame_layer(layer, dims)
            layer.move(self.art_layer, ElementPlacement.PlaceBefore)
            layer.visible = visible
            return layer

    """
    * Collector Info
    """

    def collector_info(self) -> None:
        """Format and add the collector info at the bottom."""

        # Ignore this step if legal layer not present
        if not self.legal_group:
            return

        # If creator is specified add the text
        if self.layout.creator and self.text_layer_creator:
            self.text_layer_creator.textItem.contents = self.layout.creator

        # Which collector info mode?
        if CFG.collector_mode in [
            CollectorMode.Default, CollectorMode.Modern
        ] and self.layout.collector_data:
            return self.collector_info_authentic()
        elif CFG.collector_mode == CollectorMode.ArtistOnly:
            return self.collector_info_artist_only()
        return self.collector_info_basic()

    def collector_info_basic(self) -> None:
        """Called to generate basic collector info."""

        # Collector layers
        artist_layer = psd.getLayer(LAYERS.ARTIST, self.legal_group)
        set_layer = psd.getLayer(LAYERS.SET, self.legal_group)
        set_TI = set_layer.textItem

        # Correct color for non-black border
        if self.border_color != BorderColor.Black:
            set_TI.color = self.RGB_BLACK
            artist_layer.textItem.color = self.RGB_BLACK

        # Fill optional collector star
        if self.is_collector_promo:
            psd.replace_text(set_layer, "•", MagicIcons.COLLECTOR_STAR)

        # Fill language, artist, and set
        if self.layout.lang != "en":
            psd.replace_text(set_layer, "EN", self.layout.lang.upper())
        psd.replace_text(artist_layer, "Artist", self.layout.artist)
        set_TI.contents = self.layout.set + set_TI.contents

    def collector_info_authentic(self) -> None:
        """Called to generate realistic collector info."""

        # Hide basic layers
        psd.getLayer(LAYERS.ARTIST, self.legal_group).visible = False
        psd.getLayer(LAYERS.SET, self.legal_group).visible = False

        # Get the collector layers
        group = psd.getLayerSet(LAYERS.COLLECTOR, self.legal_group)
        top = psd.getLayer(LAYERS.TOP, group).textItem
        bottom = psd.getLayer(LAYERS.BOTTOM, group)
        group.visible = True

        # Correct color for non-black border
        if self.border_color != 'black':
            top.color = self.RGB_BLACK
            bottom.textItem.color = self.RGB_BLACK

        # Fill in language if needed
        if self.layout.lang != "en":
            psd.replace_text(bottom, "EN", self.layout.lang.upper())

        # Fill optional collector star
        if self.is_collector_promo:
            psd.replace_text(bottom, "•", MagicIcons.COLLECTOR_STAR)

        # Apply the collector info
        top.contents = self.layout.collector_data
        psd.replace_text(bottom, "SET", self.layout.set)
        psd.replace_text(bottom, "Artist", self.layout.artist)

    def collector_info_artist_only(self) -> None:
        """Called to generate 'Artist Only' collector info."""

        # Collector layers
        artist_layer = psd.getLayer(LAYERS.ARTIST, self.legal_group)
        psd.getLayer(LAYERS.SET, self.legal_group).visible = False

        # Correct color for non-black border
        if self.border_color != BorderColor.Black:
            artist_layer.textItem.color = self.RGB_BLACK

        # Insert artist name
        psd.replace_text(artist_layer, "Artist", self.layout.artist)

    """
    * Expansion Symbol
    """

    @property
    def expansion_symbol_alignments(self) -> list[Dimensions]:
        """Alignments used for positioning the expansion symbol"""
        return [Dimensions.Right, Dimensions.CenterY]

    @auto_prop_cached
    def expansion_symbol_layer(self) -> Optional[ArtLayer]:
        """Expansion symbol layer, value set during the `load_expansion_symbol` method."""
        return

    @auto_prop_cached
    def expansion_reference(self) -> Optional[ArtLayer]:
        """Expansion symbol reference layer"""
        return psd.getLayer(LAYERS.EXPANSION_REFERENCE, self.text_group)

    def load_expansion_symbol(self) -> None:
        """Imports and positions the expansion symbol SVG image."""

        # Check for expansion symbol disabled
        if not CFG.symbol_enabled or not self.expansion_reference:
            return
        if not self.layout.symbol_svg:
            return self.log("Expansion symbol disabled, SVG file not found.")

        # Try to import the expansion symbol
        try:

            # Import and place the symbol
            svg = psd.import_svg(
                path=str(self.layout.symbol_svg),
                ref=self.expansion_reference,
                placement=ElementPlacement.PlaceBefore,
                docref=self.docref)

            # Frame the symbol
            psd.frame_layer_by_height(
                layer=svg,
                ref=self.expansion_reference,
                alignments=self.expansion_symbol_alignments)

            # Rename and reset property
            svg.name = 'Expansion Symbol'
            self.expansion_symbol_layer = svg

        except Exception as e:
            return self.log('Expansion symbol disabled due to an error.', e)

    """
    * Watermark
    """

    @auto_prop_cached
    def watermark_blend_mode(self) -> BlendMode:
        """Blend mode to use on the Watermark layer."""
        return BlendMode.ColorBurn

    @auto_prop_cached
    def watermark_color_map(self) -> dict:
        """Maps color values for Watermark."""
        return watermark_color_map.copy()

    @auto_prop_cached
    def watermark_colors(self) -> list[SolidColor]:
        """Colors to use for the Watermark."""
        if self.pinlines in self.watermark_color_map:
            return [self.watermark_color_map.get(self.pinlines, self.RGB_WHITE)]
        elif len(self.identity) < 3:
            return [self.watermark_color_map.get(c, self.RGB_WHITE) for c in self.identity]
        return []

    @auto_prop_cached
    def watermark_fx(self) -> list[LayerEffects]:
        """Defines the layer effects to use for the Watermark."""
        if len(self.watermark_colors) == 1:
            return [{
                'type': 'color-overlay', 'opacity': 100,
                'color': self.watermark_colors[0]
            }]
        if len(self.watermark_colors) == 2:
            return [{
                'type': 'gradient-overlay', 'rotation': 0,
                'colors': [
                    {'color': self.watermark_colors[0], 'location': 0, 'midpoint': 50},
                    {'color': self.watermark_colors[1], 'location': 4096, 'midpoint': 50}
                ]
            }]
        return []

    def create_watermark(self) -> None:
        """Builds the watermark."""
        # Required values to generate a Watermark
        if not all([
            self.layout.watermark_svg,
            self.layout.watermark,
            self.textbox_reference,
            self.watermark_colors,
            self.text_group
        ]):
            return

        # Get watermark custom settings if available
        wm_details = CON.watermarks.get(self.layout.watermark, {})

        # Import and frame the watermark
        wm = psd.import_svg(
            path=self.layout.watermark_svg,
            ref=self.text_group,
            placement=ElementPlacement.PlaceAfter,
            docref=self.docref)
        psd.frame_layer(
            layer=wm,
            ref=self.textbox_reference.dims,
            smallest=True,
            scale=wm_details.get('scale', 80))

        # Apply opacity, blending, and effects
        wm.opacity = wm_details.get('opacity', CFG.watermark_opacity)
        wm.blendMode = self.watermark_blend_mode
        psd.apply_fx(wm, self.watermark_fx)

    """
    * Basic Land Watermark
    """

    @auto_prop_cached
    def basic_watermark_color_map(self) -> dict:
        """Maps color values for Basic Land Watermark."""
        return basic_watermark_color_map.copy()

    @auto_prop_cached
    def basic_watermark_color(self) -> SolidColor:
        """Color to use for the Basic Land Watermark."""
        return psd.get_color(self.basic_watermark_color_map[self.layout.pinlines])

    @auto_prop_cached
    def basic_watermark_fx(self) -> list[LayerEffects]:
        """Defines the layer effects used on the Basic Land Watermark."""
        return [
            {
                'type': 'color-overlay', 'opacity': 100, 'color': self.basic_watermark_color},
            {
                'type': 'bevel', 'size': 28, 'softness': 14, 'depth': 100,
                'shadow_opacity': 72, 'highlight_opacity': 70,
                'rotation': 45, 'altitude': 22
            }
        ]

    def create_basic_watermark(self) -> None:
        """Builds a basic land watermark."""

        # Generate the watermark
        wm = psd.import_svg(
            path=self.layout.watermark_basic,
            ref=self.text_group,
            placement=ElementPlacement.PlaceAfter,
            docref=self.docref)
        psd.frame_layer_by_height(
            layer=wm,
            ref=self.textbox_reference.dims,
            scale=75)

        # Add effects
        psd.apply_fx(wm, self.basic_watermark_fx)

        # Add snow effects
        if self.is_snow:
            self.add_basic_watermark_snow_effects(wm)

        # Remove rules text step
        self.rules_text_and_pt_layers = lambda: None
        self.layout.oracle_text = ''
        self.layout.flavor_text = ''

    def add_basic_watermark_snow_effects(self, wm: ArtLayer):
        """Adds optional snow effects for 'Snow' Basic Land watermarks.

        Args:
            wm: ArtLayer containing the Basic Land Watermark.
        """
        pass

    """
    * Border
    """

    @auto_prop_cached
    def border_color(self) -> str:
        """Use 'black' unless an alternate color and a valid border group is provided."""
        if CFG.border_color != BorderColor.Black and self.border_group:
            return CFG.border_color
        return 'black'

    @try_photoshop
    def color_border(self) -> None:
        """Color this card's border based on given setting."""
        if self.border_color != BorderColor.Black:
            psd.apply_fx(self.border_group, [{
                'type': 'color-overlay',
                'color': psd.get_color(self.border_color)
            }])

    """
    * Formatted Text Layers
    """

    @property
    def text(self) -> list[FormattedTextLayer]:
        """List of text layer objects to execute."""
        return self._text

    @text.setter
    def text(self, value):
        """Add text layer to execute."""
        self._text = value

    def format_text_layers(self) -> None:
        """Validate and execute each formatted text layer."""
        for t in self.text:
            # Check for cancelled thread each iteration
            if self.event.is_set():
                return
            # Validate and execute
            if t and t.validate():
                t.execute()

    """
    * Document Actions
    """

    def check_photoshop(self) -> None:
        """Check if Photoshop is responsive to automation."""
        # Ensure the Photoshop Application is responsive
        check = self.app.refresh_app()
        if not isinstance(check, OSError):
            return

        # Connection with Photoshop couldn't be established, try again?
        if not self.console.await_choice(
                self.event, get_photoshop_error_message(check),
                end="Hit Continue to try again, or Cancel to end the operation.\n\n"
        ):
            # Cancel the operation
            raise OSError(check)
        self.check_photoshop()

    def reset(self) -> None:
        """Reset the document, purge the cache, end await."""
        try:
            if self.docref:
                psd.reset_document(self.docref)
        except PS_EXCEPTIONS:
            pass
        self.console.end_await()

    """
    * Tasks and Logging
    """

    def log(self, text: str, e: Optional[Exception] = None) -> None:
        """Writes a message to console if test mode isn't enabled, logs an exception if provided.

        Args:
            text: Message to write to console.
            e: Exception to log if provided.
        """
        if e:
            self.console.log_exception(e)
        if not ENV.TEST_MODE:
            self.console.update(text)

    def run_tasks(
            self,
            funcs: list[Callable],
            message: str,
            warning: bool = False,
            args: Union[Iterable[Any], None] = None,
            kwargs: Optional[dict] = None,
    ) -> bool:
        """Run a list of functions, checking for thread cancellation and exceptions on each.

        Args:
            funcs: List of functions to perform.
            message: Error message to raise if exception occurs.
            warning: Warn the user if True, otherwise raise error.
            args: Optional arguments to pass to the func. Empty tuple if not provided.
            kwargs: Optional keyword arguments to pass to the func. Empty dict if not provided.

        Returns:
            True if tasks completed, False if exception occurs or thread is cancelled.
        """

        # Default args and kwargs
        args = args or ()
        kwargs = kwargs or {}

        # Execute each function
        for func in funcs:
            if self.event.is_set():
                # Thread operation has been cancelled
                return False
            try:
                # Run the task
                func(*args, **kwargs)
            except Exception as e:
                # Raise error or warning
                if not warning:
                    self.raise_error(message=message, error=e)
                    return False
                self.raise_warning(message=message, error=e)
        return True

    def raise_error(self, message: str, error: Optional[Exception] = None) -> None:
        """Raise an error on the console display.

        Args:
            message: Message to be displayed
            error: Exception object
        """
        self.console.log_error(
            thr=self.event,
            card=self.layout.name,
            template=self.layout.template_file,
            msg=f'{msg_error(message)}\n'
                f'Check [b]/logs/error.txt[/b] for details.',
            e=error)
        self.reset()

    def raise_warning(self, message: str, error: Exception = None) -> None:
        """Raise a warning on the console display.

        Args:
            message: Message to be displayed.
            error: Exception object.
        """
        if error:
            self.console.log_exception(error)
            message += "\nCheck [b]/logs/error.txt[/b] for details."
        self.console.update(msg_warn(message), exception=error)

    """
    * Layer Generator Utilities
    * These methods create layers dynamically by blending rasterized layers or solid color
    adjustment layers together using masks.
    """

    def create_blended_layer(
            self,
            group: LayerSet,
            colors: Union[None, str, list[str]] = None,
            masks: Optional[list[ArtLayer]] = None,
            **kwargs
    ):
        """Either enable a single frame layer or create a multicolor layer using a gradient mask.

        Args:
            group: Group to look for the color layers within.
            colors: Color layers to look for.
            masks: Masks to use for blending the layers.
        """
        # Ensure masks is a list
        masks = masks or []

        # Establish our colors
        colors = colors or self.identity or self.pinlines
        if isinstance(colors, str) and not is_multicolor_string(colors):
            # Received a color string that isn't a frame color combination
            colors = [colors]
        elif len(colors) >= self.color_limit:
            # Received too big a color combination, revert to pinlines
            colors = [self.pinlines]
        elif isinstance(colors, str):
            # Convert string of colors to list
            colors = list(colors)

        # Single layer
        if len(colors) == 1:
            layer = psd.getLayer(colors[0], group)
            layer.visible = True
            return

        # Enable each layer color
        layers: list[ArtLayer] = []
        for i, color in enumerate(colors):

            # Make layer visible
            layer = psd.getLayer(color, group)
            if 'blend_mode' in kwargs:
                layer.blendMode = kwargs['blend_mode']
            layer.visible = True

            # Position the new layer and add a mask to previous, if previous layer exists
            if layers and len(masks) >= i:
                layer.move(layers[i - 1], ElementPlacement.PlaceAfter)
                psd.copy_layer_mask(masks[i - 1], layers[i - 1])

            # Add to the layer list
            layers.append(layer)

    @staticmethod
    def create_blended_solid_color(
            group: LayerSet,
            colors: list[SolidColor],
            masks: Optional[list[Union[ArtLayer, LayerSet]]] = None,
            **kwargs
    ) -> None:
        """Either enable a single frame layer or create a multicolor layer using a gradient mask.

        Args:
            group: Group to look for the color layers within.
            colors: Color layers to look for.
            masks: Masks to use for blending the layers.

        Keyword Args:
            blend_mode (BlendMode): Sets the blend mode of the generated solid color layers.
        """
        # Ensure masks is a list
        masks = masks or []

        # Enable each layer color
        layers: list[ArtLayer] = []
        for i, color in enumerate(colors):
            layer = psd.smart_layer(psd.create_color_layer(color, group))
            if 'blend_mode' in kwargs:
                layer.blendMode = kwargs['blend_mode']

            # Position the new layer and add a mask to previous, if previous layer exists
            if layers and len(masks) >= i:
                layer.move(layers[i - 1], ElementPlacement.PlaceAfter)
                psd.copy_layer_mask(masks[i - 1], layers[i - 1])
            layers.append(layer)

    def generate_layer(
            self, group: Union[ArtLayer, LayerSet],
            colors: Union[list[list[int]], list[int], list[dict], list[str], str],
            masks: Optional[list[ArtLayer]] = None,
            **kwargs
    ) -> Optional[ArtLayer]:
        """Takes information about a frame layer group and routes it to the correct
        generation function which blends rasterized layers, blends solid color layers, or
        generates a solid color/gradient adjustment layer.

        Notes:
            The result for a given 'colors' schema:
            - str: Enable a single texture layer.
            - list[str]: Blend multiple texture layers.
            - list[int]: Create a solid color adjustment layer.
            - list[dict]: Create a gradient adjustment layer.
            - list[list[int]]: Blend multiple solid color adjustment layers.

        Args:
            group: Layer or group containing layers.
            colors: Color definition for this frame layer generation.
            masks: Masks used to blend this generated layer.
        """
        # Assign a generator task based on colors value
        if isinstance(colors, str):
            # Hex color
            if colors.startswith('#'):
                return psd.create_color_layer(
                    color=colors,
                    layer=group,
                    docref=self.docref,
                    **kwargs)
            # Blended texture layers
            return self.create_blended_layer(
                group=group,
                colors=colors,
                masks=masks,
                **kwargs)
        if isinstance(colors, list):
            if all(isinstance(c, str) for c in colors):
                # Hex colors
                if colors[0].startswith('#'):
                    return psd.create_color_layer(
                        color=colors,
                        layer=group,
                        docref=self.docref,
                        **kwargs)
                # Blended texture layers
                return self.create_blended_layer(
                    group=group,
                    colors=colors,
                    masks=masks,
                    **kwargs)
            if all(isinstance(c, int) for c in colors):
                # RGB/CMYK adjustment layer
                return psd.create_color_layer(
                    color=colors,
                    layer=group,
                    docref=self.docref,
                    **kwargs)
            if all(isinstance(c, dict) for c in colors):
                # Gradient adjustment layer
                return psd.create_gradient_layer(
                    colors=colors,
                    layer=group,
                    docref=self.docref,
                    **kwargs)
            if all(isinstance(c, list) for c in colors):
                # Blended RGB/CMYK adjustment layers
                return self.create_blended_solid_color(
                    group=group,
                    colors=colors,
                    masks=masks,
                    **kwargs)

        # Failed to match a recognized color notation
        if group:
            self.log(f"Couldn't generate frame element: '{group.name}'")

    """
    * Extendable Methods
    * These methods are called during the execution chain but must be written in the child class.
    """

    def enable_frame_layers(self) -> None:
        """Enable the correct layers for this card's frame."""
        pass

    def enable_crown(self) -> None:
        """Enable layers required by the Legendary Crown."""
        pass

    def enable_hollow_crown(self) -> None:
        """Enable layers required by the Hollow Legendary Crown modification"""
        pass

    def basic_text_layers(self) -> None:
        """Establish mana cost, name (scaled to clear mana cost), and typeline (scaled to not overlap set symbol)."""
        pass

    def rules_text_and_pt_layers(self) -> None:
        """Set up the card's rules and power/toughness text based on whether the card is a creature."""
        pass

    """
    * Execution Sequence
    """

    def execute(self) -> bool:
        """Perform actions to render the card using this template.

        Notes:
            - Each action is wrapped in an exception check and breakpoint to cancel the thread
                if a cancellation signal was sent by the user.
            - Never override this method!
        """
        # Preliminary Photoshop check
        if not self.run_tasks(
                funcs=[self.check_photoshop],
                message="Unable to reach Photoshop!"
        ):
            return False

        # Pre-process layout data
        if not self.run_tasks(
                funcs=self.pre_render_methods,
                message="Pre-processing layout data failed!"
        ):
            return False

        # Load in the PSD template
        if not self.run_tasks(
                funcs=[self.app.load],
                message="PSD template failed to load!",
                args=[str(self.layout.template_file)]
        ):
            return False

        # Load in artwork and frame it
        if not self.run_tasks(
                funcs=[self.load_artwork],
                message="Unable to load artwork!"
        ):
            return False

        # Load in Scryfall scan and frame it
        if CFG.import_scryfall_scan:
            self.run_tasks(
                funcs=[self.paste_scryfall_scan],
                message="Couldn't import Scryfall scan, continuing without it!",
                warning=True)

        # Add expansion symbol
        self.run_tasks(
            funcs=[self.load_expansion_symbol],
            message="Unable to generate expansion symbol!",
            warning=True)

        # Add watermark
        if CFG.enable_basic_watermark and self.is_basic_land:
            # Basic land watermark
            if not self.run_tasks(
                    funcs=[self.create_basic_watermark],
                    message="Unable to generate basic land watermark!"
            ):
                return False
        elif CFG.watermark_mode is not WatermarkMode.Disabled:
            # Normal watermark
            if not self.run_tasks(
                    funcs=[self.create_watermark],
                    message="Unable to generate watermark!"
            ):
                return False

        # Enable layers to build our frame
        if not self.run_tasks(
                funcs=self.frame_layer_methods,
                message="Enabling layers failed!"
        ):
            return False

        # Format text layers
        if not self.run_tasks(
                funcs=[
                    *self.text_layer_methods,
                    self.format_text_layers,
                    *self.post_text_methods
                ],
                message="Formatting text layers failed!"
        ):
            return False

        # Specific hooks
        if not self.run_tasks(
                funcs=self.hooks,
                message="Encountered an error during triggered hooks step!"
        ):
            return False

        # Manual edit step?
        if CFG.exit_early and not ENV.TEST_MODE:
            self.console.await_choice(self.event)

        # Save the document
        if not self.run_tasks(
                funcs=[self.save_mode],
                message="Error during file save process!",
                kwargs={'path': self.output_file_name, 'docref': self.docref}
        ):
            return False

        # Post save methods
        if not self.run_tasks(
                funcs=self.post_save_methods,
                message="Image saved, but an error was encountered during the post-save step!"
        ):
            return False

        # Reset document, return success
        if not ENV.TEST_MODE:
            self.console.update(f"[b]{self.output_file_name.stem}[/b] rendered successfully!")
        self.reset()
        return True

Attributes

active_layer: Union[ArtLayer, LayerSet]

Union[ArtLayer, LayerSet]: Get the currently active layer in the Photoshop document.

app: PhotoshopHandler

art_action: Optional[Callable]

Function that is called to perform an action on the imported art.

art_action_args: Optional[dict]

Args to pass to art_action.

art_frame: str

art_frame_vertical: str

art_layer: ArtLayer

expansion_symbol_alignments: list[Dimensions]

Alignments used for positioning the expansion symbol

frame_layer_methods: list[Callable]

list[Callable]: Methods called to insert and enable frame layers.

Functions:

Name Description
`color_border`

Changes the border color if required and supported by the template.

`enable_frame_layers`

hooks: list[Callable]

list[Callable]: List of methods that will be called during the hooks execution step

is_artifact: bool

is_colorless: bool

is_companion: bool

is_creature: bool

is_emblem: bool

is_front: bool

is_fullart: bool

is_hollow_crown: bool

is_hybrid: bool

is_land: bool

is_legendary: bool

is_mdfc: bool

is_miracle: bool

is_nyx: bool

is_snow: bool

is_token: bool

is_transform: bool

is_vehicle: bool

post_save_methods: list[Callable]

list[Callable]: Methods called after the rendered image is saved.

post_text_methods: list[Callable]

list[Callable]: Methods called after text is inserted and formatted.

pre_render_methods: list[Callable]

list[Callable]: Methods called before rendering begins.

Functions:

Name Description
`process_layout_data`

Processes layout data before it is used to generate the card.

text: list[FormattedTextLayer]

List of text layer objects to execute.

text_layer_methods: list[Callable]

list[Callable]: Methods called to insert and format text layers.

Functions

RGB_BLACK() -> SolidColor

Source code in src\templates\_core.py
193
194
195
196
@auto_prop_cached
def RGB_BLACK(self) -> SolidColor:
    """SolidColor: A solid color object with RGB [0, 0, 0]."""
    return psd.rgb_black()

RGB_WHITE() -> SolidColor

Source code in src\templates\_core.py
198
199
200
201
@auto_prop_cached
def RGB_WHITE(self) -> SolidColor:
    """SolidColor: A solid color object with RGB [255, 255, 255]."""
    return psd.rgb_white()

add_basic_watermark_snow_effects(wm: ArtLayer)

Adds optional snow effects for 'Snow' Basic Land watermarks.

Parameters:

Name Type Description Default
wm ArtLayer

ArtLayer containing the Basic Land Watermark.

required
Source code in src\templates\_core.py
1066
1067
1068
1069
1070
1071
1072
def add_basic_watermark_snow_effects(self, wm: ArtLayer):
    """Adds optional snow effects for 'Snow' Basic Land watermarks.

    Args:
        wm: ArtLayer containing the Basic Land Watermark.
    """
    pass

art_reference() -> ReferenceLayer

Source code in src\templates\_core.py
631
632
633
634
635
636
637
638
639
@auto_prop_cached
def art_reference(self) -> ReferenceLayer:
    """ReferenceLayer: Reference frame used to scale and position the art layer."""
    # Check if art is vertically oriented, or forced vertical, and for valid vertical frame
    if self.is_art_vertical or (self.is_fullart and CFG.vertical_fullart):
        if layer := psd.get_reference_layer(self.art_frame_vertical):
            return layer
    # Check for normal art frame
    return psd.get_reference_layer(self.art_frame) or psd.get_reference_layer(LAYERS.ART_FRAME)

background() -> str

Source code in src\templates\_core.py
453
454
455
456
457
458
@auto_prop_cached
def background(self) -> str:
    """str: Name of the Background layer."""
    if not self.is_vehicle and self.layout.background == LAYERS.VEHICLE:
        return LAYERS.ARTIFACT
    return self.layout.background

background_layer() -> Optional[ArtLayer]

Background texture layer.

Source code in src\templates\_core.py
582
583
584
585
586
587
588
589
590
591
592
@auto_prop_cached
def background_layer(self) -> Optional[ArtLayer]:
    """Background texture layer."""
    # Try finding Vehicle background
    if self.is_vehicle and self.background == LAYERS.VEHICLE:
        return psd.getLayer(
            LAYERS.VEHICLE, LAYERS.BACKGROUND
        ) or psd.getLayer(
            LAYERS.ARTIFACT, LAYERS.BACKGROUND)
    # All other backgrounds
    return psd.getLayer(self.background, LAYERS.BACKGROUND)

basic_text_layers() -> None

Establish mana cost, name (scaled to clear mana cost), and typeline (scaled to not overlap set symbol).

Source code in src\templates\_core.py
1420
1421
1422
def basic_text_layers(self) -> None:
    """Establish mana cost, name (scaled to clear mana cost), and typeline (scaled to not overlap set symbol)."""
    pass

basic_watermark_color() -> SolidColor

Color to use for the Basic Land Watermark.

Source code in src\templates\_core.py
1022
1023
1024
1025
@auto_prop_cached
def basic_watermark_color(self) -> SolidColor:
    """Color to use for the Basic Land Watermark."""
    return psd.get_color(self.basic_watermark_color_map[self.layout.pinlines])

basic_watermark_color_map() -> dict

Maps color values for Basic Land Watermark.

Source code in src\templates\_core.py
1017
1018
1019
1020
@auto_prop_cached
def basic_watermark_color_map(self) -> dict:
    """Maps color values for Basic Land Watermark."""
    return basic_watermark_color_map.copy()

basic_watermark_fx() -> list[LayerEffects]

Defines the layer effects used on the Basic Land Watermark.

Source code in src\templates\_core.py
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
@auto_prop_cached
def basic_watermark_fx(self) -> list[LayerEffects]:
    """Defines the layer effects used on the Basic Land Watermark."""
    return [
        {
            'type': 'color-overlay', 'opacity': 100, 'color': self.basic_watermark_color},
        {
            'type': 'bevel', 'size': 28, 'softness': 14, 'depth': 100,
            'shadow_opacity': 72, 'highlight_opacity': 70,
            'rotation': 45, 'altitude': 22
        }
    ]

border_color() -> str

Use 'black' unless an alternate color and a valid border group is provided.

Source code in src\templates\_core.py
1078
1079
1080
1081
1082
1083
@auto_prop_cached
def border_color(self) -> str:
    """Use 'black' unless an alternate color and a valid border group is provided."""
    if CFG.border_color != BorderColor.Black and self.border_group:
        return CFG.border_color
    return 'black'

border_group() -> Optional[Union[LayerSet, ArtLayer]]

Optional[Union[LayerSet, ArtLayer]]: Group, or sometimes a layer, containing the card border.

Source code in src\templates\_core.py
474
475
476
477
478
479
480
481
@auto_prop_cached
def border_group(self) -> Optional[Union[LayerSet, ArtLayer]]:
    """Optional[Union[LayerSet, ArtLayer]]: Group, or sometimes a layer, containing the card border."""
    if group := psd.getLayerSet(LAYERS.BORDER, self.docref):
        return group
    if layer := psd.getLayer(LAYERS.BORDER, self.docref):
        return layer
    return

check_photoshop() -> None

Check if Photoshop is responsive to automation.

Source code in src\templates\_core.py
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def check_photoshop(self) -> None:
    """Check if Photoshop is responsive to automation."""
    # Ensure the Photoshop Application is responsive
    check = self.app.refresh_app()
    if not isinstance(check, OSError):
        return

    # Connection with Photoshop couldn't be established, try again?
    if not self.console.await_choice(
            self.event, get_photoshop_error_message(check),
            end="Hit Continue to try again, or Cancel to end the operation.\n\n"
    ):
        # Cancel the operation
        raise OSError(check)
    self.check_photoshop()

collector_info() -> None

Format and add the collector info at the bottom.

Source code in src\templates\_core.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def collector_info(self) -> None:
    """Format and add the collector info at the bottom."""

    # Ignore this step if legal layer not present
    if not self.legal_group:
        return

    # If creator is specified add the text
    if self.layout.creator and self.text_layer_creator:
        self.text_layer_creator.textItem.contents = self.layout.creator

    # Which collector info mode?
    if CFG.collector_mode in [
        CollectorMode.Default, CollectorMode.Modern
    ] and self.layout.collector_data:
        return self.collector_info_authentic()
    elif CFG.collector_mode == CollectorMode.ArtistOnly:
        return self.collector_info_artist_only()
    return self.collector_info_basic()

collector_info_artist_only() -> None

Called to generate 'Artist Only' collector info.

Source code in src\templates\_core.py
875
876
877
878
879
880
881
882
883
884
885
886
887
def collector_info_artist_only(self) -> None:
    """Called to generate 'Artist Only' collector info."""

    # Collector layers
    artist_layer = psd.getLayer(LAYERS.ARTIST, self.legal_group)
    psd.getLayer(LAYERS.SET, self.legal_group).visible = False

    # Correct color for non-black border
    if self.border_color != BorderColor.Black:
        artist_layer.textItem.color = self.RGB_BLACK

    # Insert artist name
    psd.replace_text(artist_layer, "Artist", self.layout.artist)

collector_info_authentic() -> None

Called to generate realistic collector info.

Source code in src\templates\_core.py
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
def collector_info_authentic(self) -> None:
    """Called to generate realistic collector info."""

    # Hide basic layers
    psd.getLayer(LAYERS.ARTIST, self.legal_group).visible = False
    psd.getLayer(LAYERS.SET, self.legal_group).visible = False

    # Get the collector layers
    group = psd.getLayerSet(LAYERS.COLLECTOR, self.legal_group)
    top = psd.getLayer(LAYERS.TOP, group).textItem
    bottom = psd.getLayer(LAYERS.BOTTOM, group)
    group.visible = True

    # Correct color for non-black border
    if self.border_color != 'black':
        top.color = self.RGB_BLACK
        bottom.textItem.color = self.RGB_BLACK

    # Fill in language if needed
    if self.layout.lang != "en":
        psd.replace_text(bottom, "EN", self.layout.lang.upper())

    # Fill optional collector star
    if self.is_collector_promo:
        psd.replace_text(bottom, "•", MagicIcons.COLLECTOR_STAR)

    # Apply the collector info
    top.contents = self.layout.collector_data
    psd.replace_text(bottom, "SET", self.layout.set)
    psd.replace_text(bottom, "Artist", self.layout.artist)

collector_info_basic() -> None

Called to generate basic collector info.

Source code in src\templates\_core.py
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
def collector_info_basic(self) -> None:
    """Called to generate basic collector info."""

    # Collector layers
    artist_layer = psd.getLayer(LAYERS.ARTIST, self.legal_group)
    set_layer = psd.getLayer(LAYERS.SET, self.legal_group)
    set_TI = set_layer.textItem

    # Correct color for non-black border
    if self.border_color != BorderColor.Black:
        set_TI.color = self.RGB_BLACK
        artist_layer.textItem.color = self.RGB_BLACK

    # Fill optional collector star
    if self.is_collector_promo:
        psd.replace_text(set_layer, "•", MagicIcons.COLLECTOR_STAR)

    # Fill language, artist, and set
    if self.layout.lang != "en":
        psd.replace_text(set_layer, "EN", self.layout.lang.upper())
    psd.replace_text(artist_layer, "Artist", self.layout.artist)
    set_TI.contents = self.layout.set + set_TI.contents

color_border() -> None

Color this card's border based on given setting.

Source code in src\templates\_core.py
1085
1086
1087
1088
1089
1090
1091
1092
@try_photoshop
def color_border(self) -> None:
    """Color this card's border based on given setting."""
    if self.border_color != BorderColor.Black:
        psd.apply_fx(self.border_group, [{
            'type': 'color-overlay',
            'color': psd.get_color(self.border_color)
        }])

color_indicator_layer() -> Optional[ArtLayer]

Color indicator icon layer.

Source code in src\templates\_core.py
615
616
617
618
619
620
@auto_prop_cached
def color_indicator_layer(self) -> Optional[ArtLayer]:
    """Color indicator icon layer."""
    if self.layout.color_indicator:
        return psd.getLayer(self.layout.color_indicator, LAYERS.COLOR_INDICATOR)
    return

color_limit() -> int

Source code in src\templates\_core.py
460
461
462
463
@auto_prop_cached
def color_limit(self) -> int:
    """int: Number of colors where frame elements will no longer split (becomes gold)."""
    return 3

console() -> type[CONSOLE]

type[CONSOLE]: Console output object used to communicate with the user.

Source code in src\templates\_core.py
153
154
155
156
@auto_prop_cached
def console(self) -> type[CONSOLE]:
    """type[CONSOLE]: Console output object used to communicate with the user."""
    return CONSOLE

create_basic_watermark() -> None

Builds a basic land watermark.

Source code in src\templates\_core.py
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
def create_basic_watermark(self) -> None:
    """Builds a basic land watermark."""

    # Generate the watermark
    wm = psd.import_svg(
        path=self.layout.watermark_basic,
        ref=self.text_group,
        placement=ElementPlacement.PlaceAfter,
        docref=self.docref)
    psd.frame_layer_by_height(
        layer=wm,
        ref=self.textbox_reference.dims,
        scale=75)

    # Add effects
    psd.apply_fx(wm, self.basic_watermark_fx)

    # Add snow effects
    if self.is_snow:
        self.add_basic_watermark_snow_effects(wm)

    # Remove rules text step
    self.rules_text_and_pt_layers = lambda: None
    self.layout.oracle_text = ''
    self.layout.flavor_text = ''

create_blended_layer(group: LayerSet, colors: Union[None, str, list[str]] = None, masks: Optional[list[ArtLayer]] = None, **kwargs)

Either enable a single frame layer or create a multicolor layer using a gradient mask.

Parameters:

Name Type Description Default
group LayerSet

Group to look for the color layers within.

required
colors None | str | list[str]

Color layers to look for.

None
masks list[ArtLayer] | None

Masks to use for blending the layers.

None
Source code in src\templates\_core.py
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
def create_blended_layer(
        self,
        group: LayerSet,
        colors: Union[None, str, list[str]] = None,
        masks: Optional[list[ArtLayer]] = None,
        **kwargs
):
    """Either enable a single frame layer or create a multicolor layer using a gradient mask.

    Args:
        group: Group to look for the color layers within.
        colors: Color layers to look for.
        masks: Masks to use for blending the layers.
    """
    # Ensure masks is a list
    masks = masks or []

    # Establish our colors
    colors = colors or self.identity or self.pinlines
    if isinstance(colors, str) and not is_multicolor_string(colors):
        # Received a color string that isn't a frame color combination
        colors = [colors]
    elif len(colors) >= self.color_limit:
        # Received too big a color combination, revert to pinlines
        colors = [self.pinlines]
    elif isinstance(colors, str):
        # Convert string of colors to list
        colors = list(colors)

    # Single layer
    if len(colors) == 1:
        layer = psd.getLayer(colors[0], group)
        layer.visible = True
        return

    # Enable each layer color
    layers: list[ArtLayer] = []
    for i, color in enumerate(colors):

        # Make layer visible
        layer = psd.getLayer(color, group)
        if 'blend_mode' in kwargs:
            layer.blendMode = kwargs['blend_mode']
        layer.visible = True

        # Position the new layer and add a mask to previous, if previous layer exists
        if layers and len(masks) >= i:
            layer.move(layers[i - 1], ElementPlacement.PlaceAfter)
            psd.copy_layer_mask(masks[i - 1], layers[i - 1])

        # Add to the layer list
        layers.append(layer)

create_blended_solid_color(group: LayerSet, colors: list[SolidColor], masks: Optional[list[Union[ArtLayer, LayerSet]]] = None, **kwargs) -> None

Either enable a single frame layer or create a multicolor layer using a gradient mask.

Parameters:

Name Type Description Default
group LayerSet

Group to look for the color layers within.

required
colors list[SolidColor]

Color layers to look for.

required
masks list[ArtLayer | LayerSet] | None

Masks to use for blending the layers.

None
Source code in src\templates\_core.py
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
@staticmethod
def create_blended_solid_color(
        group: LayerSet,
        colors: list[SolidColor],
        masks: Optional[list[Union[ArtLayer, LayerSet]]] = None,
        **kwargs
) -> None:
    """Either enable a single frame layer or create a multicolor layer using a gradient mask.

    Args:
        group: Group to look for the color layers within.
        colors: Color layers to look for.
        masks: Masks to use for blending the layers.

    Keyword Args:
        blend_mode (BlendMode): Sets the blend mode of the generated solid color layers.
    """
    # Ensure masks is a list
    masks = masks or []

    # Enable each layer color
    layers: list[ArtLayer] = []
    for i, color in enumerate(colors):
        layer = psd.smart_layer(psd.create_color_layer(color, group))
        if 'blend_mode' in kwargs:
            layer.blendMode = kwargs['blend_mode']

        # Position the new layer and add a mask to previous, if previous layer exists
        if layers and len(masks) >= i:
            layer.move(layers[i - 1], ElementPlacement.PlaceAfter)
            psd.copy_layer_mask(masks[i - 1], layers[i - 1])
        layers.append(layer)

create_watermark() -> None

Builds the watermark.

Source code in src\templates\_core.py
 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
def create_watermark(self) -> None:
    """Builds the watermark."""
    # Required values to generate a Watermark
    if not all([
        self.layout.watermark_svg,
        self.layout.watermark,
        self.textbox_reference,
        self.watermark_colors,
        self.text_group
    ]):
        return

    # Get watermark custom settings if available
    wm_details = CON.watermarks.get(self.layout.watermark, {})

    # Import and frame the watermark
    wm = psd.import_svg(
        path=self.layout.watermark_svg,
        ref=self.text_group,
        placement=ElementPlacement.PlaceAfter,
        docref=self.docref)
    psd.frame_layer(
        layer=wm,
        ref=self.textbox_reference.dims,
        smallest=True,
        scale=wm_details.get('scale', 80))

    # Apply opacity, blending, and effects
    wm.opacity = wm_details.get('opacity', CFG.watermark_opacity)
    wm.blendMode = self.watermark_blend_mode
    psd.apply_fx(wm, self.watermark_fx)

crown_layer() -> Optional[ArtLayer]

Legendary crown layer.

Source code in src\templates\_core.py
605
606
607
608
@auto_prop_cached
def crown_layer(self) -> Optional[ArtLayer]:
    """Legendary crown layer."""
    return psd.getLayer(self.pinlines, LAYERS.LEGENDARY_CROWN)

crown_shadow_layer() -> Union[ArtLayer, LayerSet, None]

Legendary crown hollow shadow layer.

Source code in src\templates\_core.py
610
611
612
613
@auto_prop_cached
def crown_shadow_layer(self) -> Union[ArtLayer, LayerSet, None]:
    """Legendary crown hollow shadow layer."""
    return psd.getLayer(LAYERS.HOLLOW_CROWN_SHADOW, self.docref)

dfc_group() -> Optional[LayerSet]

Optional[LayerSet]: Group containing double face elements.

Source code in src\templates\_core.py
490
491
492
493
494
495
496
497
498
@auto_prop_cached
def dfc_group(self) -> Optional[LayerSet]:
    """Optional[LayerSet]: Group containing double face elements."""
    face = LAYERS.FRONT if self.is_front else LAYERS.BACK
    if self.is_transform:
        return psd.getLayerSet(face, [self.text_group, LAYERS.TRANSFORM])
    if self.is_mdfc:
        return psd.getLayerSet(f'{LAYERS.MDFC} {face}', self.text_group)
    return

divider_layer() -> Optional[ArtLayer]

Optional[ArtLayer]: Divider layer between rules text and flavor text.

Source code in src\templates\_core.py
553
554
555
556
557
558
559
@auto_prop_cached
def divider_layer(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Divider layer between rules text and flavor text."""
    if self.is_transform and self.is_front and self.is_flipside_creature:
        if TF_DIVIDER := psd.getLayer('Divider TF', self.text_group):
            return TF_DIVIDER
    return psd.getLayer(LAYERS.DIVIDER, self.text_group)

doc_selection() -> Selection

Source code in src\templates\_core.py
170
171
172
173
@auto_prop_cached
def doc_selection(self) -> Selection:
    """Selection: Active document selection object."""
    return self.docref.selection

docref() -> Optional[Document]

Optional[Document]: This template's document open in Photoshop.

Source code in src\templates\_core.py
163
164
165
166
167
168
@auto_prop_cached
def docref(self) -> Optional[Document]:
    """Optional[Document]: This template's document open in Photoshop."""
    if doc := psd.get_document(osp.basename(self.layout.template_file)):
        return doc
    return

enable_crown() -> None

Enable layers required by the Legendary Crown.

Source code in src\templates\_core.py
1412
1413
1414
def enable_crown(self) -> None:
    """Enable layers required by the Legendary Crown."""
    pass

enable_frame_layers() -> None

Enable the correct layers for this card's frame.

Source code in src\templates\_core.py
1408
1409
1410
def enable_frame_layers(self) -> None:
    """Enable the correct layers for this card's frame."""
    pass

enable_hollow_crown() -> None

Enable layers required by the Hollow Legendary Crown modification

Source code in src\templates\_core.py
1416
1417
1418
def enable_hollow_crown(self) -> None:
    """Enable layers required by the Hollow Legendary Crown modification"""
    pass

event() -> Event

Source code in src\templates\_core.py
148
149
150
151
@auto_prop_cached
def event(self) -> Event:
    """Event: Threading Event used to signal thread cancellation."""
    return Event()

execute() -> bool

Perform actions to render the card using this template.

Notes
  • Each action is wrapped in an exception check and breakpoint to cancel the thread if a cancellation signal was sent by the user.
  • Never override this method!
Source code in src\templates\_core.py
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
def execute(self) -> bool:
    """Perform actions to render the card using this template.

    Notes:
        - Each action is wrapped in an exception check and breakpoint to cancel the thread
            if a cancellation signal was sent by the user.
        - Never override this method!
    """
    # Preliminary Photoshop check
    if not self.run_tasks(
            funcs=[self.check_photoshop],
            message="Unable to reach Photoshop!"
    ):
        return False

    # Pre-process layout data
    if not self.run_tasks(
            funcs=self.pre_render_methods,
            message="Pre-processing layout data failed!"
    ):
        return False

    # Load in the PSD template
    if not self.run_tasks(
            funcs=[self.app.load],
            message="PSD template failed to load!",
            args=[str(self.layout.template_file)]
    ):
        return False

    # Load in artwork and frame it
    if not self.run_tasks(
            funcs=[self.load_artwork],
            message="Unable to load artwork!"
    ):
        return False

    # Load in Scryfall scan and frame it
    if CFG.import_scryfall_scan:
        self.run_tasks(
            funcs=[self.paste_scryfall_scan],
            message="Couldn't import Scryfall scan, continuing without it!",
            warning=True)

    # Add expansion symbol
    self.run_tasks(
        funcs=[self.load_expansion_symbol],
        message="Unable to generate expansion symbol!",
        warning=True)

    # Add watermark
    if CFG.enable_basic_watermark and self.is_basic_land:
        # Basic land watermark
        if not self.run_tasks(
                funcs=[self.create_basic_watermark],
                message="Unable to generate basic land watermark!"
        ):
            return False
    elif CFG.watermark_mode is not WatermarkMode.Disabled:
        # Normal watermark
        if not self.run_tasks(
                funcs=[self.create_watermark],
                message="Unable to generate watermark!"
        ):
            return False

    # Enable layers to build our frame
    if not self.run_tasks(
            funcs=self.frame_layer_methods,
            message="Enabling layers failed!"
    ):
        return False

    # Format text layers
    if not self.run_tasks(
            funcs=[
                *self.text_layer_methods,
                self.format_text_layers,
                *self.post_text_methods
            ],
            message="Formatting text layers failed!"
    ):
        return False

    # Specific hooks
    if not self.run_tasks(
            funcs=self.hooks,
            message="Encountered an error during triggered hooks step!"
    ):
        return False

    # Manual edit step?
    if CFG.exit_early and not ENV.TEST_MODE:
        self.console.await_choice(self.event)

    # Save the document
    if not self.run_tasks(
            funcs=[self.save_mode],
            message="Error during file save process!",
            kwargs={'path': self.output_file_name, 'docref': self.docref}
    ):
        return False

    # Post save methods
    if not self.run_tasks(
            funcs=self.post_save_methods,
            message="Image saved, but an error was encountered during the post-save step!"
    ):
        return False

    # Reset document, return success
    if not ENV.TEST_MODE:
        self.console.update(f"[b]{self.output_file_name.stem}[/b] rendered successfully!")
    self.reset()
    return True

expansion_reference() -> Optional[ArtLayer]

Expansion symbol reference layer

Source code in src\templates\_core.py
903
904
905
906
@auto_prop_cached
def expansion_reference(self) -> Optional[ArtLayer]:
    """Expansion symbol reference layer"""
    return psd.getLayer(LAYERS.EXPANSION_REFERENCE, self.text_group)

expansion_symbol_layer() -> Optional[ArtLayer]

Expansion symbol layer, value set during the load_expansion_symbol method.

Source code in src\templates\_core.py
898
899
900
901
@auto_prop_cached
def expansion_symbol_layer(self) -> Optional[ArtLayer]:
    """Expansion symbol layer, value set during the `load_expansion_symbol` method."""
    return

format_text_layers() -> None

Validate and execute each formatted text layer.

Source code in src\templates\_core.py
1108
1109
1110
1111
1112
1113
1114
1115
1116
def format_text_layers(self) -> None:
    """Validate and execute each formatted text layer."""
    for t in self.text:
        # Check for cancelled thread each iteration
        if self.event.is_set():
            return
        # Validate and execute
        if t and t.validate():
            t.execute()

generate_layer(group: Union[ArtLayer, LayerSet], colors: Union[list[list[int]], list[int], list[dict], list[str], str], masks: Optional[list[ArtLayer]] = None, **kwargs) -> Optional[ArtLayer]

Takes information about a frame layer group and routes it to the correct generation function which blends rasterized layers, blends solid color layers, or generates a solid color/gradient adjustment layer.

Notes

The result for a given 'colors' schema: - str: Enable a single texture layer. - list[str]: Blend multiple texture layers. - list[int]: Create a solid color adjustment layer. - list[dict]: Create a gradient adjustment layer. - list[list[int]]: Blend multiple solid color adjustment layers.

Parameters:

Name Type Description Default
group ArtLayer | LayerSet

Layer or group containing layers.

required
colors list[list[int]] | list[int] | list[dict] | list[str] | str

Color definition for this frame layer generation.

required
masks list[ArtLayer] | None

Masks used to blend this generated layer.

None
Source code in src\templates\_core.py
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
def generate_layer(
        self, group: Union[ArtLayer, LayerSet],
        colors: Union[list[list[int]], list[int], list[dict], list[str], str],
        masks: Optional[list[ArtLayer]] = None,
        **kwargs
) -> Optional[ArtLayer]:
    """Takes information about a frame layer group and routes it to the correct
    generation function which blends rasterized layers, blends solid color layers, or
    generates a solid color/gradient adjustment layer.

    Notes:
        The result for a given 'colors' schema:
        - str: Enable a single texture layer.
        - list[str]: Blend multiple texture layers.
        - list[int]: Create a solid color adjustment layer.
        - list[dict]: Create a gradient adjustment layer.
        - list[list[int]]: Blend multiple solid color adjustment layers.

    Args:
        group: Layer or group containing layers.
        colors: Color definition for this frame layer generation.
        masks: Masks used to blend this generated layer.
    """
    # Assign a generator task based on colors value
    if isinstance(colors, str):
        # Hex color
        if colors.startswith('#'):
            return psd.create_color_layer(
                color=colors,
                layer=group,
                docref=self.docref,
                **kwargs)
        # Blended texture layers
        return self.create_blended_layer(
            group=group,
            colors=colors,
            masks=masks,
            **kwargs)
    if isinstance(colors, list):
        if all(isinstance(c, str) for c in colors):
            # Hex colors
            if colors[0].startswith('#'):
                return psd.create_color_layer(
                    color=colors,
                    layer=group,
                    docref=self.docref,
                    **kwargs)
            # Blended texture layers
            return self.create_blended_layer(
                group=group,
                colors=colors,
                masks=masks,
                **kwargs)
        if all(isinstance(c, int) for c in colors):
            # RGB/CMYK adjustment layer
            return psd.create_color_layer(
                color=colors,
                layer=group,
                docref=self.docref,
                **kwargs)
        if all(isinstance(c, dict) for c in colors):
            # Gradient adjustment layer
            return psd.create_gradient_layer(
                colors=colors,
                layer=group,
                docref=self.docref,
                **kwargs)
        if all(isinstance(c, list) for c in colors):
            # Blended RGB/CMYK adjustment layers
            return self.create_blended_solid_color(
                group=group,
                colors=colors,
                masks=masks,
                **kwargs)

    # Failed to match a recognized color notation
    if group:
        self.log(f"Couldn't generate frame element: '{group.name}'")

hook_creature() -> None

Run this if card is a creature.

Source code in src\templates\_core.py
136
137
138
def hook_creature(self) -> None:
    """Run this if card is a creature."""
    pass

hook_large_mana() -> None

Run this if card has a large mana symbol.

Source code in src\templates\_core.py
140
141
142
def hook_large_mana(self) -> None:
    """Run this if card has a large mana symbol."""
    pass

identity() -> str

Source code in src\templates\_core.py
448
449
450
451
@auto_prop_cached
def identity(self) -> str:
    """str: Color identity of the card, e.g. WU."""
    return self.layout.identity

is_art_vertical() -> bool

Source code in src\templates\_core.py
396
397
398
399
400
401
402
403
404
405
@auto_prop_cached
def is_art_vertical(self) -> bool:
    """bool: Returns True if art provided is vertically oriented, False if it is horizontal."""
    with Image.open(self.layout.art_file) as image:
        width, height = image.size
    if height > (width * 1.1):
        # Vertical orientation
        return True
    # Horizontal orientation
    return False

is_basic_land() -> bool

Source code in src\templates\_core.py
368
369
370
371
@auto_prop_cached
def is_basic_land(self) -> bool:
    """bool: Governs Basic Land watermark and other Basic Land behavior."""
    return self.layout.is_basic_land

is_centered() -> bool

Source code in src\templates\_core.py
373
374
375
376
377
378
379
@auto_prop_cached
def is_centered(self) -> bool:
    """bool: Governs whether rules text is centered."""
    return bool(
        len(self.layout.flavor_text) <= 1
        and len(self.layout.oracle_text) <= 70
        and "\n" not in self.layout.oracle_text)

is_collector_promo() -> bool

Source code in src\templates\_core.py
415
416
417
418
419
420
421
422
@auto_prop_cached
def is_collector_promo(self) -> bool:
    """bool: Governs whether to use promo star in collector info."""
    if CFG.collector_promo == CollectorPromo.Always:
        return True
    if self.layout.is_promo and CFG.collector_promo == CollectorPromo.Automatic:
        return True
    return False

is_content_aware_enabled() -> bool

Source code in src\templates\_core.py
407
408
409
410
411
412
413
@auto_prop_cached
def is_content_aware_enabled(self) -> bool:
    """bool: Governs whether content aware fill should be performed during the art loading step."""
    if self.is_fullart and all([n not in self.art_reference.name for n in ['Full', 'Borderless']]):
        # By default, fill when we want a fullart image but didn't receive one
        return True
    return False

is_flipside_creature() -> bool

Source code in src\templates\_core.py
391
392
393
394
@auto_prop_cached
def is_flipside_creature(self) -> bool:
    """bool: Governs double faced cards where opposing side is a creature."""
    return bool(self.layout.other_face_power and self.layout.other_face_toughness)

is_name_shifted() -> bool

Source code in src\templates\_core.py
381
382
383
384
@auto_prop_cached
def is_name_shifted(self) -> bool:
    """bool: Governs whether to use the shifted name text layer."""
    return bool(self.is_transform or self.is_mdfc)

is_type_shifted() -> bool

Source code in src\templates\_core.py
386
387
388
389
@auto_prop_cached
def is_type_shifted(self) -> bool:
    """bool: Governs whether to use the shifted typeline text layer."""
    return bool(self.layout.color_indicator)

legal_group() -> LayerSet

Source code in src\templates\_core.py
469
470
471
472
@auto_prop_cached
def legal_group(self) -> LayerSet:
    """LayerSet: Group containing artist credit, collector info, and other legal details."""
    return self.docref.layerSets[LAYERS.LEGAL]

load_artwork() -> None

Loads the specified art file into the specified layer.

Source code in src\templates\_core.py
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
def load_artwork(self) -> None:
    """Loads the specified art file into the specified layer."""

    # Check for fullart test image
    if ENV.TEST_MODE and self.is_fullart:
        self.layout.art_file = PATH.SRC_IMG / "test-fa.jpg"

    # Paste the file into the art
    self.active_layer = self.art_layer
    if self.art_action:
        psd.paste_file(
            layer=self.art_layer,
            path=self.layout.art_file,
            action=self.art_action,
            action_args=self.art_action_args,
            docref=self.docref)
    else:
        psd.import_art(
            layer=self.art_layer,
            path=self.layout.art_file,
            docref=self.docref)

    # Frame the artwork
    psd.frame_layer(self.active_layer, self.art_reference)

    # Perform content aware fill if needed
    if self.is_content_aware_enabled:

        # Perform a generative fill
        if CFG.generative_fill:
            docref = psd.generative_fill_edges(
                layer=self.art_layer,
                feather=CFG.feathered_fill,
                close_doc=not CFG.select_variation,
                docref=self.docref)
            if docref:
                self.console.await_choice(
                    self.event, msg="Select a Generative Fill variation, then click Continue ...")
                docref.close(SaveOptions.SaveChanges)
            return

        # Perform a content aware fill
        psd.content_aware_fill_edges(self.art_layer, CFG.feathered_fill)

load_expansion_symbol() -> None

Imports and positions the expansion symbol SVG image.

Source code in src\templates\_core.py
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
def load_expansion_symbol(self) -> None:
    """Imports and positions the expansion symbol SVG image."""

    # Check for expansion symbol disabled
    if not CFG.symbol_enabled or not self.expansion_reference:
        return
    if not self.layout.symbol_svg:
        return self.log("Expansion symbol disabled, SVG file not found.")

    # Try to import the expansion symbol
    try:

        # Import and place the symbol
        svg = psd.import_svg(
            path=str(self.layout.symbol_svg),
            ref=self.expansion_reference,
            placement=ElementPlacement.PlaceBefore,
            docref=self.docref)

        # Frame the symbol
        psd.frame_layer_by_height(
            layer=svg,
            ref=self.expansion_reference,
            alignments=self.expansion_symbol_alignments)

        # Rename and reset property
        svg.name = 'Expansion Symbol'
        self.expansion_symbol_layer = svg

    except Exception as e:
        return self.log('Expansion symbol disabled due to an error.', e)

log(text: str, e: Optional[Exception] = None) -> None

Writes a message to console if test mode isn't enabled, logs an exception if provided.

Parameters:

Name Type Description Default
text str

Message to write to console.

required
e Exception | None

Exception to log if provided.

None
Source code in src\templates\_core.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
def log(self, text: str, e: Optional[Exception] = None) -> None:
    """Writes a message to console if test mode isn't enabled, logs an exception if provided.

    Args:
        text: Message to write to console.
        e: Exception to log if provided.
    """
    if e:
        self.console.log_exception(e)
    if not ENV.TEST_MODE:
        self.console.update(text)

mask_group() -> Optional[LayerSet]

Source code in src\templates\_core.py
500
501
502
503
504
505
@auto_prop_cached
def mask_group(self) -> Optional[LayerSet]:
    """LayerSet: Group containing masks used to blend and adjust various layers."""
    with suppress(Exception):
        return self.docref.layerSets[LAYERS.MASKS]
    return

mask_layers() -> list[ArtLayer]

List of layers containing masks used to blend multicolored layers.

Source code in src\templates\_core.py
672
673
674
675
676
677
678
679
@auto_prop_cached
def mask_layers(self) -> list[ArtLayer]:
    """List of layers containing masks used to blend multicolored layers."""
    if not self.mask_group:
        return []
    if mask := psd.getLayer(LAYERS.HALF, self.mask_group):
        return [mask]
    return []

name_reference() -> Optional[ArtLayer]

Source code in src\templates\_core.py
641
642
643
644
645
646
@auto_prop_cached
def name_reference(self) -> Optional[ArtLayer]:
    """ArtLayer: By default, name uses Mana Cost as a reference to check collision against."""
    if self.is_basic_land:
        return
    return self.text_layer_mana

output_directory() -> Path

PathL Directory to save the rendered image.

Source code in src\templates\_core.py
216
217
218
219
220
221
222
223
@auto_prop_cached
def output_directory(self) -> Path:
    """PathL Directory to save the rendered image."""
    if ENV.TEST_MODE:
        path = PATH.OUT / self.__class__.__name__
        path.mkdir(mode=777, parents=True, exist_ok=True)
        return path
    return PATH.OUT

output_file_name() -> Path

Source code in src\templates\_core.py
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
@auto_prop_cached
def output_file_name(self) -> Path:
    """Path: The formatted filename for the rendered image."""
    name, tag_map = CFG.output_file_name, {
        '#name': self.layout.name_raw,
        '#artist': self.layout.artist,
        '#set': self.layout.set,
        '#num': str(self.layout.collector_number),
        '#frame': self.frame_suffix,
        '#suffix': self.template_suffix,
        '#creator': self.layout.creator,
        '#lang': self.layout.lang
    }

    # Replace conditional tags
    for n in Reg.PATH_CONDITION.findall(name):
        case_new, case = n, f'<{n}>'
        for tag, val in tag_map.items():
            if tag in case and not val:
                name, case_new = name.replace(case, ''), ''
                break
            if tag in case:
                case_new = case_new.replace(tag, val)
        if case_new:
            name = name.replace(case, case_new)

    # Replace other tags
    for tag, value in tag_map.items():
        if value:
            name = name.replace(tag, value)
    path = Path(
        self.output_directory,
        sanitize_filename(name)
    ).with_suffix(f'.{CFG.output_file_type}')

    # Are we overwriting duplicate names?
    if not CFG.overwrite_duplicate:
        path = get_unique_filename(path)
    return path

paste_scryfall_scan(rotate: bool = False, visible: bool = True) -> Optional[ArtLayer]

Downloads the card's scryfall scan, pastes it into the document next to the active layer, and frames it to fill the given reference layer.

Parameters:

Name Type Description Default
rotate bool

Will rotate the card horizontally if True, useful for Planar cards.

False
visible bool

Whether to leave the layer visible or hide it.

True

Returns:

Type Description
ArtLayer | None

ArtLayer if Scryfall scan was imported, otherwise None.

Source code in src\templates\_core.py
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
def paste_scryfall_scan(self, rotate: bool = False, visible: bool = True) -> Optional[ArtLayer]:
    """Downloads the card's scryfall scan, pastes it into the document next to the active layer,
    and frames it to fill the given reference layer.

    Args:
        rotate: Will rotate the card horizontally if True, useful for Planar cards.
        visible: Whether to leave the layer visible or hide it.

    Returns:
        ArtLayer if Scryfall scan was imported, otherwise None.
    """
    # Try to grab the scan from Scryfall
    if not self.layout.scryfall_scan:
        return
    scryfall_scan = get_card_scan(self.layout.scryfall_scan)
    if not scryfall_scan:
        return

    # Paste the scan into a new layer
    if layer := psd.import_art_into_new_layer(
            path=scryfall_scan,
            name="Scryfall Reference",
            docref=self.docref
    ):
        # Rotate the layer if necessary
        if rotate:
            layer.rotate(90)

        # Frame the layer and position it above the art layer
        bleed = int(self.docref.resolution / 8)
        dims = psd.get_dimensions_from_bounds(
            (bleed, bleed, self.docref.width - bleed, self.docref.height - bleed))
        psd.frame_layer(layer, dims)
        layer.move(self.art_layer, ElementPlacement.PlaceBefore)
        layer.visible = visible
        return layer

pinlines() -> str

Source code in src\templates\_core.py
443
444
445
446
@auto_prop_cached
def pinlines(self) -> str:
    """str: Name of the Pinlines layer."""
    return self.layout.pinlines

pinlines_layer() -> Optional[ArtLayer]

Pinlines (and textbox) layer.

Source code in src\templates\_core.py
575
576
577
578
579
580
@auto_prop_cached
def pinlines_layer(self) -> Optional[ArtLayer]:
    """Pinlines (and textbox) layer."""
    if self.is_land:
        return psd.getLayer(self.pinlines, LAYERS.LAND_PINLINES_TEXTBOX)
    return psd.getLayer(self.pinlines, LAYERS.PINLINES_TEXTBOX)

process_layout_data() -> None

Performs any required pre-processing on the provided layout data.

Source code in src\templates\_core.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def process_layout_data(self) -> None:
    """Performs any required pre-processing on the provided layout data."""

    # Strip flavor text, string or list
    if CFG.remove_flavor:
        self.layout.flavor_text = "" if isinstance(
            self.layout.flavor_text, str
        ) else ['' for _ in self.layout.flavor_text]

    # Strip reminder text, string or list
    if CFG.remove_reminder:
        self.layout.oracle_text = strip_reminder_text(
            self.layout.oracle_text
        ) if isinstance(
            self.layout.oracle_text, str
        ) else [strip_reminder_text(n) for n in self.layout.oracle_text]

pt_layer() -> Optional[ArtLayer]

Power and toughness box layer.

Source code in src\templates\_core.py
594
595
596
597
598
599
600
601
602
603
@auto_prop_cached
def pt_layer(self) -> Optional[ArtLayer]:
    """Power and toughness box layer."""
    # Test for Vehicle PT support
    if self.is_vehicle and self.background == LAYERS.VEHICLE:
        if layer := psd.getLayer(LAYERS.VEHICLE, LAYERS.PT_BOX):
            # Change font to white for Vehicle PT box
            self.text_layer_pt.textItem.color = self.RGB_WHITE
            return layer
    return psd.getLayer(self.twins, LAYERS.PT_BOX)

pt_reference() -> Optional[ReferenceLayer]

Source code in src\templates\_core.py
661
662
663
664
665
666
@auto_prop_cached
def pt_reference(self) -> Optional[ReferenceLayer]:
    """ArtLayer: Reference used to check rules text overlap with the PT Box."""
    if not self.is_creature:
        return
    return psd.get_reference_layer(LAYERS.PT_REFERENCE, self.text_group)

raise_error(message: str, error: Optional[Exception] = None) -> None

Raise an error on the console display.

Parameters:

Name Type Description Default
message str

Message to be displayed

required
error Exception | None

Exception object

None
Source code in src\templates\_core.py
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
def raise_error(self, message: str, error: Optional[Exception] = None) -> None:
    """Raise an error on the console display.

    Args:
        message: Message to be displayed
        error: Exception object
    """
    self.console.log_error(
        thr=self.event,
        card=self.layout.name,
        template=self.layout.template_file,
        msg=f'{msg_error(message)}\n'
            f'Check [b]/logs/error.txt[/b] for details.',
        e=error)
    self.reset()

raise_warning(message: str, error: Exception = None) -> None

Raise a warning on the console display.

Parameters:

Name Type Description Default
message str

Message to be displayed.

required
error Exception

Exception object.

None
Source code in src\templates\_core.py
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
def raise_warning(self, message: str, error: Exception = None) -> None:
    """Raise a warning on the console display.

    Args:
        message: Message to be displayed.
        error: Exception object.
    """
    if error:
        self.console.log_exception(error)
        message += "\nCheck [b]/logs/error.txt[/b] for details."
    self.console.update(msg_warn(message), exception=error)

reset() -> None

Reset the document, purge the cache, end await.

Source code in src\templates\_core.py
1138
1139
1140
1141
1142
1143
1144
1145
def reset(self) -> None:
    """Reset the document, purge the cache, end await."""
    try:
        if self.docref:
            psd.reset_document(self.docref)
    except PS_EXCEPTIONS:
        pass
    self.console.end_await()

rules_text_and_pt_layers() -> None

Set up the card's rules and power/toughness text based on whether the card is a creature.

Source code in src\templates\_core.py
1424
1425
1426
def rules_text_and_pt_layers(self) -> None:
    """Set up the card's rules and power/toughness text based on whether the card is a creature."""
    pass

run_tasks(funcs: list[Callable], message: str, warning: bool = False, args: Union[Iterable[Any], None] = None, kwargs: Optional[dict] = None) -> bool

Run a list of functions, checking for thread cancellation and exceptions on each.

Parameters:

Name Type Description Default
funcs list[Callable]

List of functions to perform.

required
message str

Error message to raise if exception occurs.

required
warning bool

Warn the user if True, otherwise raise error.

False
args Iterable[Any] | None

Optional arguments to pass to the func. Empty tuple if not provided.

None
kwargs dict | None

Optional keyword arguments to pass to the func. Empty dict if not provided.

None

Returns:

Type Description
bool

True if tasks completed, False if exception occurs or thread is cancelled.

Source code in src\templates\_core.py
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
def run_tasks(
        self,
        funcs: list[Callable],
        message: str,
        warning: bool = False,
        args: Union[Iterable[Any], None] = None,
        kwargs: Optional[dict] = None,
) -> bool:
    """Run a list of functions, checking for thread cancellation and exceptions on each.

    Args:
        funcs: List of functions to perform.
        message: Error message to raise if exception occurs.
        warning: Warn the user if True, otherwise raise error.
        args: Optional arguments to pass to the func. Empty tuple if not provided.
        kwargs: Optional keyword arguments to pass to the func. Empty dict if not provided.

    Returns:
        True if tasks completed, False if exception occurs or thread is cancelled.
    """

    # Default args and kwargs
    args = args or ()
    kwargs = kwargs or {}

    # Execute each function
    for func in funcs:
        if self.event.is_set():
            # Thread operation has been cancelled
            return False
        try:
            # Run the task
            func(*args, **kwargs)
        except Exception as e:
            # Raise error or warning
            if not warning:
                self.raise_error(message=message, error=e)
                return False
            self.raise_warning(message=message, error=e)
    return True

save_mode() -> Callable

Source code in src\templates\_core.py
207
208
209
210
211
212
213
214
@auto_prop_cached
def save_mode(self) -> Callable:
    """Callable: Function called to save the rendered image."""
    if CFG.output_file_type == OutputFileType.PNG:
        return psd.save_document_png
    if CFG.output_file_type == OutputFileType.PSD:
        return psd.save_document_psd
    return psd.save_document_jpeg

text_group() -> Optional[LayerSet]

Optional[LayerSet]: Text and icon group, contains rules text and necessary symbols.

Source code in src\templates\_core.py
483
484
485
486
487
488
@auto_prop_cached
def text_group(self) -> Optional[LayerSet]:
    """Optional[LayerSet]: Text and icon group, contains rules text and necessary symbols."""
    with suppress(Exception):
        return self.docref.layerSets[LAYERS.TEXT_AND_ICONS]
    return self.docref

text_layer_creator() -> Optional[ArtLayer]

Optional[ArtLayer]: Proxy creator name text layer.

Source code in src\templates\_core.py
511
512
513
514
@auto_prop_cached
def text_layer_creator(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Proxy creator name text layer."""
    return psd.getLayer(LAYERS.CREATOR, self.legal_group)

text_layer_mana() -> Optional[ArtLayer]

Optional[ArtLayer]: Card mana cost text layer.

Source code in src\templates\_core.py
526
527
528
529
@auto_prop_cached
def text_layer_mana(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Card mana cost text layer."""
    return psd.getLayer(LAYERS.MANA_COST, self.text_group)

text_layer_name() -> Optional[ArtLayer]

Optional[ArtLayer]: Card name text layer.

Source code in src\templates\_core.py
516
517
518
519
520
521
522
523
524
@auto_prop_cached
def text_layer_name(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Card name text layer."""
    if self.is_name_shifted:
        psd.getLayer(LAYERS.NAME, self.text_group).visible = False
        name = psd.getLayer(LAYERS.NAME_SHIFT, self.text_group)
        name.visible = True
        return name
    return psd.getLayer(LAYERS.NAME, self.text_group)

text_layer_pt() -> Optional[ArtLayer]

Optional[ArtLayer]: Card power and toughness text layer.

Source code in src\templates\_core.py
548
549
550
551
@auto_prop_cached
def text_layer_pt(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Card power and toughness text layer."""
    return psd.getLayer(LAYERS.POWER_TOUGHNESS, self.text_group)

text_layer_rules() -> Optional[ArtLayer]

Optional[ArtLayer]: Card rules text layer.

Source code in src\templates\_core.py
541
542
543
544
545
546
@auto_prop_cached
def text_layer_rules(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Card rules text layer."""
    if self.is_creature:
        return psd.getLayer(LAYERS.RULES_TEXT_CREATURE, self.text_group)
    return psd.getLayer(LAYERS.RULES_TEXT_NONCREATURE, self.text_group)

text_layer_type() -> Optional[ArtLayer]

Optional[ArtLayer]: Card typeline text layer.

Source code in src\templates\_core.py
531
532
533
534
535
536
537
538
539
@auto_prop_cached
def text_layer_type(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Card typeline text layer."""
    if self.is_type_shifted:
        psd.getLayer(LAYERS.TYPE_LINE, self.text_group).visible = False
        typeline = psd.getLayer(LAYERS.TYPE_LINE_SHIFT, self.text_group)
        typeline.visible = True
        return typeline
    return psd.getLayer(LAYERS.TYPE_LINE, self.text_group)

textbox_reference() -> ReferenceLayer

Source code in src\templates\_core.py
656
657
658
659
@auto_prop_cached
def textbox_reference(self) -> ReferenceLayer:
    """ReferenceLayer: Reference frame used to scale and position the rules text layer."""
    return psd.get_reference_layer(LAYERS.TEXTBOX_REFERENCE, self.text_group)

transform_icon_layer() -> Optional[ArtLayer]

Optional[ArtLayer]: Transform icon layer.

Source code in src\templates\_core.py
622
623
624
625
@auto_prop_cached
def transform_icon_layer(self) -> Optional[ArtLayer]:
    """Optional[ArtLayer]: Transform icon layer."""
    return psd.getLayer(self.layout.transform_icon, self.dfc_group)

twins() -> str

Source code in src\templates\_core.py
438
439
440
441
@auto_prop_cached
def twins(self) -> str:
    """str: Name of the Twins layer, also usually the PT layer."""
    return self.layout.twins

twins_layer() -> Optional[ArtLayer]

Name and title boxes layer.

Source code in src\templates\_core.py
570
571
572
573
@auto_prop_cached
def twins_layer(self) -> Optional[ArtLayer]:
    """Name and title boxes layer."""
    return psd.getLayer(self.twins, LAYERS.TWINS)

type_reference() -> Optional[ArtLayer]

otherwise fallback to the expansion symbols reference layer.

Source code in src\templates\_core.py
648
649
650
651
652
653
654
@auto_prop_cached
def type_reference(self) -> Optional[ArtLayer]:
    """ArtLayer: By default, typeline uses the expansion symbol to check collision against,
    otherwise fallback to the expansion symbols reference layer."""
    if self.is_basic_land:
        return
    return self.expansion_symbol_layer or self.expansion_reference

watermark_blend_mode() -> BlendMode

Blend mode to use on the Watermark layer.

Source code in src\templates\_core.py
944
945
946
947
@auto_prop_cached
def watermark_blend_mode(self) -> BlendMode:
    """Blend mode to use on the Watermark layer."""
    return BlendMode.ColorBurn

watermark_color_map() -> dict

Maps color values for Watermark.

Source code in src\templates\_core.py
949
950
951
952
@auto_prop_cached
def watermark_color_map(self) -> dict:
    """Maps color values for Watermark."""
    return watermark_color_map.copy()

watermark_colors() -> list[SolidColor]

Colors to use for the Watermark.

Source code in src\templates\_core.py
954
955
956
957
958
959
960
961
@auto_prop_cached
def watermark_colors(self) -> list[SolidColor]:
    """Colors to use for the Watermark."""
    if self.pinlines in self.watermark_color_map:
        return [self.watermark_color_map.get(self.pinlines, self.RGB_WHITE)]
    elif len(self.identity) < 3:
        return [self.watermark_color_map.get(c, self.RGB_WHITE) for c in self.identity]
    return []

watermark_fx() -> list[LayerEffects]

Defines the layer effects to use for the Watermark.

Source code in src\templates\_core.py
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
@auto_prop_cached
def watermark_fx(self) -> list[LayerEffects]:
    """Defines the layer effects to use for the Watermark."""
    if len(self.watermark_colors) == 1:
        return [{
            'type': 'color-overlay', 'opacity': 100,
            'color': self.watermark_colors[0]
        }]
    if len(self.watermark_colors) == 2:
        return [{
            'type': 'gradient-overlay', 'rotation': 0,
            'colors': [
                {'color': self.watermark_colors[0], 'location': 0, 'midpoint': 50},
                {'color': self.watermark_colors[1], 'location': 4096, 'midpoint': 50}
            ]
        }]
    return []