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"""MicroDVD file."""
19
20import aeidon
21import re
22
23__all__ = ("MicroDVD",)
24
25
26class MicroDVD(aeidon.SubtitleFile):
27
28    """MicroDVD file."""
29
30    format = aeidon.formats.MICRODVD
31    mode = aeidon.modes.FRAME
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 not None:
45                subtitle = self._get_subtitle()
46                subtitle.start_frame = int(match.group(1))
47                subtitle.end_frame = int(match.group(2))
48                subtitle.main_text = match.group(3).replace("|", "\n")
49                subtitles.append(subtitle)
50            elif line.startswith("{DEFAULT}"):
51                self.header = line
52        return subtitles
53
54    def write_to_file(self, subtitles, doc, f):
55        """
56        Write `subtitles` from `doc` to file `f`.
57
58        Raise :exc:`IOError` if writing fails.
59        Raise :exc:`UnicodeError` if encoding fails.
60        """
61        if self.header.strip():
62            f.write(self.header + "\n")
63        for subtitle in subtitles:
64            text = subtitle.get_text(doc).replace("\n", "|")
65            f.write(("{{{:d}}}{{{:d}}}{}\n"
66                     .format(subtitle.start_frame,
67                             subtitle.end_frame,
68                             text)))
69