1# -*- coding: utf-8 -*-
2
3# Copyright (C) 2005 Osmo Salomaa
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18"""MPL2 file."""
19
20import aeidon
21import re
22
23__all__ = ("MPL2",)
24
25
26class MPL2(aeidon.SubtitleFile):
27
28    """MPL2 file."""
29
30    format = aeidon.formats.MPL2
31    mode = aeidon.modes.TIME
32    _re_line = re.compile(r"^\[(-?\d+)\]\[(-?\d+)\](.*?)$")
33
34    def read(self):
35        """
36        Read file and return subtitles.
37
38        Raise :exc:`IOError` if reading fails.
39        Raise :exc:`UnicodeError` if decoding fails.
40        """
41        subtitles = []
42        for line in self._read_lines():
43            match = self._re_line.match(line)
44            if match is None: continue
45            subtitle = self._get_subtitle()
46            subtitle.start_seconds = float(match.group(1)) / 10
47            subtitle.end_seconds = float(match.group(2)) / 10
48            subtitle.main_text = match.group(3).replace("|", "\n")
49            subtitles.append(subtitle)
50        return subtitles
51
52    def write_to_file(self, subtitles, doc, f):
53        """
54        Write `subtitles` from `doc` to file `f`.
55
56        Raise :exc:`IOError` if writing fails.
57        Raise :exc:`UnicodeError` if encoding fails.
58        """
59        for subtitle in subtitles:
60            text = subtitle.get_text(doc).replace("\n", "|")
61            f.write(("[{:.0f}][{:.0f}]{}\n"
62                     .format(subtitle.start_seconds*10,
63                             subtitle.end_seconds*10,
64                             text)))
65