File size: 4,324 Bytes
29e1b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import re
from collections import Counter
from xml.etree import ElementTree as ET

from validator import ANIMATIONS, NS, PAINT, SVGError, parse_svg, seconds, svg_text, view_box

MOTIONS = ("bounce", "float", "rotate", "swing", "pulse", "fade")
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")


def add_motion(root: ET.Element, effect: str, duration: float) -> str:
    x, y, width, height = view_box(root)
    cx, cy = x + width / 2, y + height / 2
    group = ET.SubElement(root, NS + "g")
    for child in list(root)[:-1]:
        if child.tag.removeprefix(NS) not in {"defs", "title", "desc", *ANIMATIONS}:
            root.remove(child)
            group.append(child)

    timing = {"dur": f"{duration:g}s", "repeatCount": "indefinite"}
    if effect == "fade":
        ET.SubElement(group, NS + "animate", {
            **timing, "attributeName": "opacity", "values": "1;0.35;1",
        })
        return svg_text(root)
    if effect == "pulse":
        group.set("transform", f"translate({cx:g} {cy:g})")
        scaling = ET.SubElement(group, NS + "g")
        content = ET.SubElement(scaling, NS + "g", {"transform": f"translate({-cx:g} {-cy:g})"})
        for child in list(group)[:-1]:
            group.remove(child)
            content.append(child)
        group = scaling

    effects = {
        "bounce": ("translate", f"0 0;0 {-height * 0.10:g};0 0"),
        "float": ("translate", f"0 0;0 {-height * 0.045:g};0 0;0 {height * 0.045:g};0 0"),
        "rotate": ("rotate", f"0 {cx:g} {cy:g};360 {cx:g} {cy:g}"),
        "swing": ("rotate", f"0 {cx:g} {cy:g};12 {cx:g} {cy:g};0 {cx:g} {cy:g};-12 {cx:g} {cy:g};0 {cx:g} {cy:g}"),
        "pulse": ("scale", "1;1.08;1"),
    }
    transform, values = effects[effect]
    timing.update({"attributeName": "transform", "type": transform, "values": values})
    if transform != "rotate" or effect == "swing":
        segments = values.count(";")
        timing.update({
            "calcMode": "spline",
            "keyTimes": ";".join(f"{n / segments:g}" for n in range(segments + 1)),
            "keySplines": ";".join([".42 0 .58 1"] * segments),
        })
    ET.SubElement(group, NS + "animateTransform", timing)
    return svg_text(root)


def edit_motion(source: str, speed: float, repeat: str, color: str) -> str:
    if not 0.5 <= speed <= 3 or repeat not in {"original", "indefinite", "1", "2", "3", "5"}:
        raise SVGError("์†๋„์™€ ๋ฐ˜๋ณต ์„ค์ •์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”.")
    root = parse_svg(source, require_animation=True)
    color = color.strip()
    if color and not HEX_COLOR.fullmatch(color):
        raise SVGError("์ƒ‰์ƒ์€ #7C58DB์ฒ˜๋Ÿผ 6์ž๋ฆฌ HEX๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")
    palette = Counter(
        value.casefold()
        for node in root.iter() if node.tag.removeprefix(NS) not in ANIMATIONS
        for attr, value in node.attrib.items()
        if attr in PAINT and HEX_COLOR.fullmatch(value)
        and value.casefold() not in {"#ffffff", "#000000"}
    )
    original_color = palette.most_common(1)[0][0] if palette else None
    if color and original_color is None:
        raise SVGError("์ด SVG์—์„œ ๊ต์ฒดํ•  6์ž๋ฆฌ HEX ์ƒ‰์ƒ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")

    for node in root.iter():
        if node.tag.removeprefix(NS) in ANIMATIONS:
            if speed != 1:
                for attr in ("dur", "begin"):
                    if node.get(attr) not in (None, "0"):
                        adjusted = seconds(node.attrib[attr]) / speed
                        node.set(attr, f"{adjusted:.9f}".rstrip("0").rstrip(".") + "s")
            if repeat != "original":
                node.set("repeatCount", repeat)
                if repeat != "indefinite":
                    node.set("fill", "freeze")
            if color and node.get("attributeName") in PAINT:
                for attr in ("values", "from", "to", "by"):
                    if attr in node.attrib:
                        node.set(attr, ";".join(
                            color if part.strip().casefold() == original_color else part
                            for part in node.attrib[attr].split(";")
                        ))
        elif color:
            for attr in PAINT.intersection(node.attrib):
                if node.attrib[attr].casefold() == original_color:
                    node.set(attr, color)
    return svg_text(root)