Skip to content

FormattedTextField

src.text_layers.FormattedTextField

Bases: TextField

A utility class containing the required infrastructure to format text with action descriptors.

  • Formats any recognized mana symbols contained in the text.
  • Formats any modal/bullet point sections in the text.
  • Formats any italicized or bolded text, as well as line breaks.
Source code in src\text_layers.py
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
class FormattedTextField (TextField):
    """A utility class containing the required infrastructure to format text with action descriptors.

    * Formats any recognized mana symbols contained in the text.
    * Formats any modal/bullet point sections in the text.
    * Formats any italicized or bolded text, as well as line breaks.
    """
    FONT = CardFonts.RULES

    def __init__(self, layer: ArtLayer, contents: str = "", **kwargs):
        super().__init__(layer, contents, **kwargs)

        # Pre-cache text details
        _ = self.text_details

    """
    * Core Text Details
    """

    @cached_property
    def text_details(self) -> dict:

        # Generate italic text arrays from things in (parentheses), ability words, and the given flavor text
        italic_text = generate_italics(self.contents) if self.contents else []

        # Add flavor text to italics array
        if self.flavor_text.count("*") >= 2:
            # Don't italicize text between asterisk
            flavor_text_split = self.flavor_text.split("*")
            italic_text.extend([v for i, v in enumerate(flavor_text_split) if not i % 2 and not v == ''])
            self.flavor_text = ''.join(flavor_text_split)
        elif self.flavor_text:
            # Regular flavor text
            italic_text.append(self.flavor_text)

        # Locate symbols and update the rules string
        rules, symbols = locate_symbols(
            text=self.contents,
            symbol_map=self.kw_symbol_map,
            logger=CONSOLE)

        # Create the new input string
        input_str = f'{rules}\r{self.flavor_text}' if rules and self.flavor_text else (
            rules if rules else self.flavor_text)

        # Locate italics text indices
        italicized = locate_italics(
            st=input_str,
            italics_strings=italic_text,
            symbol_map=self.kw_symbol_map,
            logger=CONSOLE)

        # Return text details
        return {
            'rules_text': rules,
            'input_string': input_str,
            'symbol_indices': symbols,
            'italics_indices': italicized,
        }

    @cached_property
    def italics_indices(self) -> list[CardItalicString]:
        return self.text_details['italics_indices']

    @cached_property
    def symbol_indices(self) -> list[CardSymbolString]:
        return self.text_details['symbol_indices']

    @cached_property
    def input(self) -> str:
        return self.text_details['input_string']

    @property
    def divider(self) -> Optional[ArtLayer]:
        # Default to None unless overridden
        return

    """
    * Rules Text and Indexes
    """

    @cached_property
    def rules_text(self) -> str:
        return self.text_details['rules_text']

    @cached_property
    def rules_range(self) -> Optional[tuple[int, int]]:
        if not self.rules_text:
            return
        return 0, len(self.rules_text)

    @cached_property
    def rules_start(self) -> int:
        if self.rules_range:
            return self.rules_range[0]
        return -1

    @cached_property
    def rules_end(self) -> int:
        if self.rules_range:
            return self.rules_range[1]
        return -1

    """
    * Flavor Text and Indexes
    """

    @auto_prop_cached
    def flavor_text(self) -> str:
        return self.kwargs.get('flavor', '').replace('\n', '\r')

    @cached_property
    def flavor_text_range(self) -> Optional[tuple[int, int]]:
        if not self.flavor_text:
            return
        total = len(self.input)
        return total - len(self.flavor_text), total

    @cached_property
    def flavor_start(self) -> int:
        if self.flavor_text_range:
            return self.flavor_text_range[0]
        return -1

    @cached_property
    def flavor_end(self) -> int:
        if self.flavor_text_range:
            return self.flavor_text_range[1]
        return -1

    @cached_property
    def quote_index(self) -> int:
        if self.flavor_text_range:
            return self.input.find("\r", self.flavor_start + 3)
        return -1

    """
    * Colors
    """

    @cached_property
    def flavor_color(self) -> Optional[SolidColor]:
        """If defined separately, `color` is effectively the `rules_color`."""
        return self.kwargs.get('flavor_color')

    """
    * Fonts
    """

    @cached_property
    def font(self) -> str:
        """Font provided, or fallback on global constant."""
        return self.kw_font or CON.font_rules_text

    @cached_property
    def font_mana(self) -> str:
        """Mana font provided, or fallback on global constant."""
        return self.kw_font_mana or CON.font_mana

    @cached_property
    def font_italic(self) -> str:
        """Italic font provided, or fallback on global constant."""
        return self.kw_font_italic or CON.font_rules_text_italic

    @cached_property
    def font_bold(self) -> str:
        """Bold font provided, or fallback on global constant."""
        return self.kw_font_bold or CON.font_rules_text_bold

    """
    * Text Formatting Properties
    """

    @cached_property
    def line_break_lead(self) -> Union[int, float]:
        """Leading space before linebreaks."""
        return self.kwargs.get(
            'line_break_lead',
            0 if self.contents_centered else CON.line_break_lead
        )

    @cached_property
    def flavor_text_lead(self) -> Union[int, float]:
        """Leading space before linebreak separating rules and flavor text. Increased if divider is present."""
        if self.divider:
            return self.kwargs.get('flavor_text_lead_divider', CON.flavor_text_lead_divider)
        return self.kwargs.get('flavor_text_lead', CON.flavor_text_lead)

    """
    * Optional Properties
    """

    @cached_property
    def contents_centered(self) -> bool:
        return self.kwargs.get('centered', False)

    @cached_property
    def flavor_centered(self) -> bool:
        return self.kwargs.get('flavor_centered', self.contents_centered)

    @cached_property
    def bold_rules_text(self) -> bool:
        return self.kwargs.get('bold_rules_text', False)

    @cached_property
    def right_align_quote(self) -> bool:
        return self.kwargs.get('right_align_quote', False)

    @cached_property
    def font_size(self) -> float:
        if font_size := self.kwargs.get('font_size'):
            return font_size * get_text_scale_factor(self.layer)
        return self.TI.size * get_text_scale_factor(self.layer)

    """
    * Formatting Checks
    """

    @cached_property
    def is_flavor_text(self) -> bool:
        return bool(self.flavor_start >= 0)

    @cached_property
    def is_quote_text(self) -> bool:
        return bool(self.quote_index >= 0)

    @cached_property
    def is_modal(self) -> bool:
        return bool('\u2022' in self.input)

    """
    * Methods
    """

    def format_text(self):
        """Inserts rules and flavor text and formats it based on the defined mana
        symbols, italics text indices, and other predefined properties."""

        # Descriptors
        para_style = ActionDescriptor()
        para_range = ActionDescriptor()
        main_style = ActionDescriptor()
        main_range = ActionDescriptor()
        main_target = ActionDescriptor()
        main_desc = ActionDescriptor()

        # References
        main_ref = ActionReference()

        # Lists
        style_list = ActionList()
        main_list = ActionList()

        # Descriptor ID's
        idTo = sID('to')
        size = sID('size')
        idFrom = sID('from')
        textLayer = sID('textLayer')
        textStyle = sID('textStyle')
        ptUnit = sID('pointsUnit')
        spaceAfter = sID('spaceAfter')
        autoLeading = sID('autoLeading')
        startIndent = sID('startIndent')
        spaceBefore = sID('spaceBefore')
        leadingType = sID('leadingType')
        styleRange = sID('textStyleRange')
        paragraphStyle = sID('paragraphStyle')
        firstLineIndent = sID('firstLineIndent')
        fontPostScriptName = sID('fontPostScriptName')
        paragraphStyleRange = sID('paragraphStyleRange')

        # Spin up the text insertion action
        main_desc.putString(sID('textKey'), self.input)
        main_range.putInteger(idFrom, 0)
        main_range.putInteger(idTo, len(self.input))
        apply_color(main_style, self.color)
        main_style.putBoolean(autoLeading, False)
        main_style.putUnitDouble(size, ptUnit, self.font_size)
        main_style.putUnitDouble(sID('leading'), ptUnit, self.font_size)
        main_style.putString(fontPostScriptName, self.font)
        main_range.putObject(textStyle, textStyle, main_style)
        main_list.putObject(styleRange, main_range)

        # Bold the contents if necessary
        if self.rules_text and self.bold_rules_text:
            main_range.putInteger(idFrom, self.rules_start)
            main_range.putInteger(idTo, self.rules_end)
            main_style.putString(fontPostScriptName, self.font_bold)
            main_range.putObject(textStyle, textStyle, main_style)
            main_list.putObject(styleRange, main_range)

        # Italicize text from our italics indices
        if self.italics_indices:
            for start, end in self.italics_indices:
                main_range.putInteger(idFrom, start)
                main_range.putInteger(idTo, end)
                main_style.putString(fontPostScriptName, self.font_italic)
                main_range.putObject(textStyle, textStyle, main_style)
                main_list.putObject(styleRange, main_range)

        # Format each mana symbol
        if self.symbol_indices:
            for index, colors in self.symbol_indices:
                for i, color in enumerate(colors):
                    main_range.putInteger(idFrom, index + i)
                    main_range.putInteger(idTo, index + i + 1)
                    apply_color(main_style, color)
                    main_style.putString(fontPostScriptName, self.font_mana)
                    main_range.putObject(textStyle, textStyle, main_style)
                    main_list.putObject(styleRange, main_range)

        # Modal choice formatting
        if self.is_modal or self.is_flavor_text:
            para_range.putInteger(idFrom, 0)
            para_range.putInteger(idTo, len(self.input))
            para_style.putUnitDouble(firstLineIndent, ptUnit, 0)
            para_style.putUnitDouble(startIndent, ptUnit, 0)
            para_style.putUnitDouble(sID("endIndent"), ptUnit, 0)
            para_style.putUnitDouble(spaceBefore, ptUnit, self.line_break_lead)
            para_style.putUnitDouble(spaceAfter, ptUnit, 0)
            para_style.putInteger(sID("dropCapMultiplier"), 1)
            para_style.putEnumerated(leadingType, leadingType, sID("leadingBelow"))

        # Adjust paragraph formatting for modal card with bullet points
        if self.is_modal:
            default_style = ActionDescriptor()
            para_range.putInteger(idFrom, self.input.find("\u2022"))
            para_range.putInteger(idTo, self.input.rindex("\u2022") + 1)
            para_style.putUnitDouble(firstLineIndent, ptUnit, -CON.modal_indent)
            para_style.putUnitDouble(startIndent, ptUnit, CON.modal_indent)
            para_style.putUnitDouble(spaceBefore, ptUnit, 1)
            default_style.putString(fontPostScriptName, self.font_mana)
            default_style.putUnitDouble(size, ptUnit, 12)
            default_style.putBoolean(autoLeading, False)
            para_style.putObject(sID("defaultStyle"), textStyle, default_style)
            para_range.putObject(paragraphStyle, paragraphStyle, para_style)
            style_list.putObject(paragraphStyleRange, para_range)

        # Flavor text actions
        if self.is_flavor_text:

            # Add linebreak spacing between rules and flavor text
            para_range.putInteger(idFrom, self.flavor_start + 3)
            para_range.putInteger(idTo, self.flavor_start + 4)
            para_style.putUnitDouble(startIndent, ptUnit, 0)
            para_style.putUnitDouble(firstLineIndent, ptUnit, 0)
            para_style.putUnitDouble(sID("impliedStartIndent"), ptUnit, 0)
            para_style.putUnitDouble(sID("impliedFirstLineIndent"), ptUnit, 0)
            para_style.putUnitDouble(spaceBefore, ptUnit, self.flavor_text_lead)
            para_range.putObject(paragraphStyle, paragraphStyle, para_style)
            style_list.putObject(paragraphStyleRange, para_range)

            # Adjust flavor text color
            if self.flavor_color:
                main_range.PutInteger(idFrom, self.flavor_start)
                main_range.PutInteger(idTo, self.flavor_end)
                apply_color(main_style, self.flavor_color)
                main_style.putString(fontPostScriptName, self.font_italic)
                main_range.PutObject(textStyle, textStyle, main_style)
                main_list.putObject(styleRange, main_range)

            # Quote actions flavor text
            if self.is_quote_text:

                # Adjust line break spacing if there's a line break in the flavor text
                para_range.putInteger(idFrom, self.quote_index + 3)
                para_range.putInteger(idTo, len(self.input))
                para_style.putUnitDouble(spaceBefore, ptUnit, 0)
                para_range.putObject(paragraphStyle, paragraphStyle, para_style)
                style_list.putObject(paragraphStyleRange, para_range)

                # Optional, align quote credit to right
                if self.right_align_quote and '"\r—' in self.flavor_text:
                    para_range.putInteger(idFrom, self.input.find('"\r—') + 2)
                    para_range.putInteger(idTo, self.flavor_end)
                    para_style.putBoolean(sID('styleSheetHasParent'), True)
                    para_range.putEnumerated(sID('align'), sID('alignmentType'), sID('right'))
                    para_range.putObject(paragraphStyle, paragraphStyle, para_style)
                    style_list.putObject(paragraphStyleRange, para_range)

        # Apply action lists
        main_desc.putList(paragraphStyleRange, style_list)
        main_desc.putList(styleRange, main_list)

        # Push changes to text layer
        main_ref.putEnumerated(textLayer, sID("ordinal"), sID("targetEnum"))
        main_target.putReference(sID("target"), main_ref)
        main_target.putObject(idTo, textLayer, main_desc)
        APP.executeAction(sID("set"), main_target, NO_DIALOG)

    def execute(self):
        super().execute()

        # Format text
        self.format_text()

        # Justify center if required
        if self.contents_centered:
            self.TI.justification = Justification.Center

        # Ensure hyphenation disabled
        self.TI.hyphenation = False

Attributes

flavor_color: Optional[SolidColor]

If defined separately, color is effectively the rules_color.

flavor_text_lead: Union[int, float]

Leading space before linebreak separating rules and flavor text. Increased if divider is present.

font: str

Font provided, or fallback on global constant.

font_bold: str

Bold font provided, or fallback on global constant.

font_italic: str

Italic font provided, or fallback on global constant.

font_mana: str

Mana font provided, or fallback on global constant.

line_break_lead: Union[int, float]

Leading space before linebreaks.

Functions

format_text()

Inserts rules and flavor text and formats it based on the defined mana symbols, italics text indices, and other predefined properties.

Source code in src\text_layers.py
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
def format_text(self):
    """Inserts rules and flavor text and formats it based on the defined mana
    symbols, italics text indices, and other predefined properties."""

    # Descriptors
    para_style = ActionDescriptor()
    para_range = ActionDescriptor()
    main_style = ActionDescriptor()
    main_range = ActionDescriptor()
    main_target = ActionDescriptor()
    main_desc = ActionDescriptor()

    # References
    main_ref = ActionReference()

    # Lists
    style_list = ActionList()
    main_list = ActionList()

    # Descriptor ID's
    idTo = sID('to')
    size = sID('size')
    idFrom = sID('from')
    textLayer = sID('textLayer')
    textStyle = sID('textStyle')
    ptUnit = sID('pointsUnit')
    spaceAfter = sID('spaceAfter')
    autoLeading = sID('autoLeading')
    startIndent = sID('startIndent')
    spaceBefore = sID('spaceBefore')
    leadingType = sID('leadingType')
    styleRange = sID('textStyleRange')
    paragraphStyle = sID('paragraphStyle')
    firstLineIndent = sID('firstLineIndent')
    fontPostScriptName = sID('fontPostScriptName')
    paragraphStyleRange = sID('paragraphStyleRange')

    # Spin up the text insertion action
    main_desc.putString(sID('textKey'), self.input)
    main_range.putInteger(idFrom, 0)
    main_range.putInteger(idTo, len(self.input))
    apply_color(main_style, self.color)
    main_style.putBoolean(autoLeading, False)
    main_style.putUnitDouble(size, ptUnit, self.font_size)
    main_style.putUnitDouble(sID('leading'), ptUnit, self.font_size)
    main_style.putString(fontPostScriptName, self.font)
    main_range.putObject(textStyle, textStyle, main_style)
    main_list.putObject(styleRange, main_range)

    # Bold the contents if necessary
    if self.rules_text and self.bold_rules_text:
        main_range.putInteger(idFrom, self.rules_start)
        main_range.putInteger(idTo, self.rules_end)
        main_style.putString(fontPostScriptName, self.font_bold)
        main_range.putObject(textStyle, textStyle, main_style)
        main_list.putObject(styleRange, main_range)

    # Italicize text from our italics indices
    if self.italics_indices:
        for start, end in self.italics_indices:
            main_range.putInteger(idFrom, start)
            main_range.putInteger(idTo, end)
            main_style.putString(fontPostScriptName, self.font_italic)
            main_range.putObject(textStyle, textStyle, main_style)
            main_list.putObject(styleRange, main_range)

    # Format each mana symbol
    if self.symbol_indices:
        for index, colors in self.symbol_indices:
            for i, color in enumerate(colors):
                main_range.putInteger(idFrom, index + i)
                main_range.putInteger(idTo, index + i + 1)
                apply_color(main_style, color)
                main_style.putString(fontPostScriptName, self.font_mana)
                main_range.putObject(textStyle, textStyle, main_style)
                main_list.putObject(styleRange, main_range)

    # Modal choice formatting
    if self.is_modal or self.is_flavor_text:
        para_range.putInteger(idFrom, 0)
        para_range.putInteger(idTo, len(self.input))
        para_style.putUnitDouble(firstLineIndent, ptUnit, 0)
        para_style.putUnitDouble(startIndent, ptUnit, 0)
        para_style.putUnitDouble(sID("endIndent"), ptUnit, 0)
        para_style.putUnitDouble(spaceBefore, ptUnit, self.line_break_lead)
        para_style.putUnitDouble(spaceAfter, ptUnit, 0)
        para_style.putInteger(sID("dropCapMultiplier"), 1)
        para_style.putEnumerated(leadingType, leadingType, sID("leadingBelow"))

    # Adjust paragraph formatting for modal card with bullet points
    if self.is_modal:
        default_style = ActionDescriptor()
        para_range.putInteger(idFrom, self.input.find("\u2022"))
        para_range.putInteger(idTo, self.input.rindex("\u2022") + 1)
        para_style.putUnitDouble(firstLineIndent, ptUnit, -CON.modal_indent)
        para_style.putUnitDouble(startIndent, ptUnit, CON.modal_indent)
        para_style.putUnitDouble(spaceBefore, ptUnit, 1)
        default_style.putString(fontPostScriptName, self.font_mana)
        default_style.putUnitDouble(size, ptUnit, 12)
        default_style.putBoolean(autoLeading, False)
        para_style.putObject(sID("defaultStyle"), textStyle, default_style)
        para_range.putObject(paragraphStyle, paragraphStyle, para_style)
        style_list.putObject(paragraphStyleRange, para_range)

    # Flavor text actions
    if self.is_flavor_text:

        # Add linebreak spacing between rules and flavor text
        para_range.putInteger(idFrom, self.flavor_start + 3)
        para_range.putInteger(idTo, self.flavor_start + 4)
        para_style.putUnitDouble(startIndent, ptUnit, 0)
        para_style.putUnitDouble(firstLineIndent, ptUnit, 0)
        para_style.putUnitDouble(sID("impliedStartIndent"), ptUnit, 0)
        para_style.putUnitDouble(sID("impliedFirstLineIndent"), ptUnit, 0)
        para_style.putUnitDouble(spaceBefore, ptUnit, self.flavor_text_lead)
        para_range.putObject(paragraphStyle, paragraphStyle, para_style)
        style_list.putObject(paragraphStyleRange, para_range)

        # Adjust flavor text color
        if self.flavor_color:
            main_range.PutInteger(idFrom, self.flavor_start)
            main_range.PutInteger(idTo, self.flavor_end)
            apply_color(main_style, self.flavor_color)
            main_style.putString(fontPostScriptName, self.font_italic)
            main_range.PutObject(textStyle, textStyle, main_style)
            main_list.putObject(styleRange, main_range)

        # Quote actions flavor text
        if self.is_quote_text:

            # Adjust line break spacing if there's a line break in the flavor text
            para_range.putInteger(idFrom, self.quote_index + 3)
            para_range.putInteger(idTo, len(self.input))
            para_style.putUnitDouble(spaceBefore, ptUnit, 0)
            para_range.putObject(paragraphStyle, paragraphStyle, para_style)
            style_list.putObject(paragraphStyleRange, para_range)

            # Optional, align quote credit to right
            if self.right_align_quote and '"\r—' in self.flavor_text:
                para_range.putInteger(idFrom, self.input.find('"\r—') + 2)
                para_range.putInteger(idTo, self.flavor_end)
                para_style.putBoolean(sID('styleSheetHasParent'), True)
                para_range.putEnumerated(sID('align'), sID('alignmentType'), sID('right'))
                para_range.putObject(paragraphStyle, paragraphStyle, para_style)
                style_list.putObject(paragraphStyleRange, para_range)

    # Apply action lists
    main_desc.putList(paragraphStyleRange, style_list)
    main_desc.putList(styleRange, main_list)

    # Push changes to text layer
    main_ref.putEnumerated(textLayer, sID("ordinal"), sID("targetEnum"))
    main_target.putReference(sID("target"), main_ref)
    main_target.putObject(idTo, textLayer, main_desc)
    APP.executeAction(sID("set"), main_target, NO_DIALOG)