2013-05-29 00:31:09 +03:00
|
|
|
import os
|
|
|
|
import os.path
|
|
|
|
import sys
|
2013-05-28 00:33:36 +03:00
|
|
|
|
2013-05-29 00:31:09 +03:00
|
|
|
from paragraphs import paragraph_refs_format
|
2013-05-28 00:33:36 +03:00
|
|
|
|
|
|
|
class OutputFormat (object):
|
|
|
|
def __init__(self, extension, name):
|
|
|
|
self.extension = extension
|
|
|
|
self.name = name
|
2013-05-29 00:31:09 +03:00
|
|
|
self.cached_templates = {}
|
2013-05-28 00:33:36 +03:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return ".%s: %s" % (self.extension, self.name)
|
|
|
|
|
|
|
|
def write(self, book, output):
|
|
|
|
self.write_begin(book, output)
|
|
|
|
self.write_shuffled_paragraphs(book.shuffle(), output)
|
|
|
|
self.write_end(book, output)
|
|
|
|
|
|
|
|
def write_begin(self, book, output):
|
2013-05-29 00:31:09 +03:00
|
|
|
print >> output, self.load_template("begin") % {
|
|
|
|
'max' : book.max
|
|
|
|
},
|
2013-05-28 00:33:36 +03:00
|
|
|
|
|
|
|
def write_shuffled_paragraphs(self, shuffled_paragraphs, output):
|
|
|
|
for p in shuffled_paragraphs.as_list[1:]:
|
|
|
|
self.write_paragraph(p, shuffled_paragraphs, output)
|
|
|
|
|
|
|
|
def write_paragraph(self, paragraph, shuffled_paragraphs, output):
|
2013-05-29 00:31:09 +03:00
|
|
|
def paragraph_link_render(to_paragraph, shuffled_paragraphs):
|
|
|
|
return self.load_template("paragraph_ref") % {
|
|
|
|
'nr' : shuffled_paragraphs.to_nr[to_paragraph],
|
|
|
|
'from_nr' : shuffled_paragraphs.to_nr[paragraph]
|
|
|
|
};
|
|
|
|
print >> output, self.load_template("paragraph") % {
|
|
|
|
'nr' : shuffled_paragraphs.to_nr[paragraph],
|
|
|
|
'text' : paragraph.format(shuffled_paragraphs,
|
|
|
|
paragraph_link_render)
|
|
|
|
},
|
2013-05-28 00:33:36 +03:00
|
|
|
|
|
|
|
def write_end(self, book, output):
|
2013-05-29 00:31:09 +03:00
|
|
|
print >> output, self.load_template("end") % {},
|
2013-05-28 00:33:36 +03:00
|
|
|
|
|
|
|
def supports(self, filename):
|
|
|
|
return filename.endswith('.' + self.extension)
|
2013-05-29 00:31:09 +03:00
|
|
|
|
|
|
|
def load_template(self, name):
|
|
|
|
"Templates is a mess and do not belong in the output class really."
|
|
|
|
if name in self.cached_templates:
|
|
|
|
return self.cached_templates[name]
|
|
|
|
filename = os.path.join(os.path.dirname(sys.argv[0]),
|
|
|
|
"output_formats",
|
|
|
|
self.extension,
|
|
|
|
name + "." + self.extension)
|
|
|
|
f = open(filename, "r")
|
|
|
|
template = f.read()
|
|
|
|
f.close()
|
|
|
|
self.cached_templates[name] = template
|
|
|
|
return template
|
|
|
|
|