1import re
2
3from .time import times_to_ms
4from .formatbase import FormatBase
5from .ssaevent import SSAEvent
6
7
8# thanks to http://otsaloma.io/gaupol/doc/api/aeidon.files.mpl2_source.html
9MPL2_FORMAT = re.compile(r"^\[(-?\d+)\]\[(-?\d+)\](.*)", re.MULTILINE)
10
11
12class MPL2Format(FormatBase):
13    """MPL2 subtitle format implementation"""
14    @classmethod
15    def guess_format(cls, text):
16        """See :meth:`pysubs2.formats.FormatBase.guess_format()`"""
17        if MPL2_FORMAT.search(text):
18            return "mpl2"
19
20    @classmethod
21    def from_file(cls, subs, fp, format_, **kwargs):
22        """See :meth:`pysubs2.formats.FormatBase.from_file()`"""
23        def prepare_text(lines):
24            out = []
25            for s in lines.split("|"):
26                s = s.strip()
27
28                if s.startswith("/"):
29                    # line beginning with '/' is in italics
30                    s = r"{\i1}%s{\i0}" % s[1:].strip()
31
32                out.append(s)
33            return "\\N".join(out)
34
35        subs.events = [SSAEvent(start=times_to_ms(s=float(start) / 10), end=times_to_ms(s=float(end) / 10),
36                       text=prepare_text(text)) for start, end, text in MPL2_FORMAT.findall(fp.getvalue())]
37
38    @classmethod
39    def to_file(cls, subs, fp, format_, **kwargs):
40        """
41        See :meth:`pysubs2.formats.FormatBase.to_file()`
42
43        No styling is supported at the moment.
44
45        """
46        # TODO handle italics
47        for line in subs:
48            if line.is_comment:
49                continue
50
51            print("[{start}][{end}] {text}".format(start=int(line.start // 100),
52                                                   end=int(line.end // 100),
53                                                   text=line.plaintext.replace("\n", "|")),
54                  file=fp)
55