1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
7 from librarian import dcparser, RDFNS
8 from librarian.util import get_translation
10 def last_words(text, n):
12 for w in reversed(text.split()):
20 return n, ' '.join(reversed(words))
23 class WLElement(etree.ElementBase):
24 SECTION_PRECEDENCE = None
39 EPUB_START_CHUNK = False
45 text_substitutions = [
56 def meta_object(self):
57 if not hasattr(self, '_meta_object'):
58 elem = self.find(RDFNS('RDF'))
60 self._meta_object = dcparser.BookInfo.from_element(elem)
62 self._meta_object = None
63 return self._meta_object
67 if self.meta_object is not None:
68 return self.meta_object
70 if self.getparent() is not None:
71 return self.getparent().meta
73 return self.document.base_meta
77 return get_translation(self.meta.language).gettext
79 def in_context_of(self, setting):
80 parent = self.getparent()
84 return getattr(parent, setting)
85 except AttributeError:
86 return parent.in_context_of(setting)
88 def get_context_map(self, setting, key, default=None):
89 parent = self.getparent()
93 return getattr(parent, setting)[key]
94 except AttributeError:
95 return parent.get_context_map(setting, key, default)
97 def signal(self, signal):
98 parent = self.getparent()
99 if parent is not None:
100 parent.signal(signal)
102 def raw_printable_text(self, builder):
103 from librarian.html import raw_printable_text
105 # TODO: podtagi, wyroznienia, etc
107 t += self.normalize_text(self.text, builder)
109 if not isinstance(c, WLElement):
111 if c.tag not in ('pe', 'pa', 'pt', 'pr', 'motyw'):
112 t += c.raw_printable_text(builder)
113 t += self.normalize_text(c.tail, builder)
116 def normalize_text(self, text, builder):
118 for e, s in self.text_substitutions:
119 text = text.replace(e, s)
121 if getattr(builder, 'normalize_whitespace', False):
122 text = re.sub(r'\s+', ' ', text)
124 if getattr(builder, 'hyphenator', None) is not None:
126 wlist = re.compile(r'\w+|[^\w]', re.UNICODE).findall(text)
128 newt += builder.hyphenator.inserted(w, '\u00AD')
132 text = re.sub(r'(?<=\s\w)\s+', '\u00A0', text)
136 def build_inner(self, builder):
137 build_method = builder.build_method_fn
138 child_count = len(self)
139 if self.CAN_HAVE_TEXT and self.text:
140 text = self.normalize_text(self.text, builder)
145 builder.push_text(text)
146 for i, child in enumerate(self):
148 if isinstance(child, WLElement):
149 getattr(child, build_method)(builder)
150 self.after_child(builder, real_child_count)
151 real_child_count += 1
153 # FIXME base builder api
154 elif getattr(builder, 'debug', False) and child.tag is etree.Comment:
155 builder.process_comment(child)
156 if self.CAN_HAVE_TEXT and child.tail:
157 text = self.normalize_text(child.tail, builder)
158 if self.STRIP and i == child_count - 1:
160 builder.push_text(text)
162 def after_child(self, builder, child_count):
163 fn = getattr(builder, 'after_child_fn', None)
165 getattr(self, builder.after_child_fn)(builder, child_count)
167 def txt_after_child(self, builder, child_count):
170 def txt_build_inner(self, builder):
171 self.build_inner(builder)
173 def txt_build(self, builder):
174 builder.push_margin(self.TXT_TOP_MARGIN)
175 builder.push_text(self.TXT_PREFIX, True)
176 self.txt_build_inner(builder)
177 builder.push_text(self.TXT_SUFFIX, True)
178 builder.push_margin(self.TXT_BOTTOM_MARGIN)
180 def html_build_inner(self, builder):
181 self.build_inner(builder)
183 def get_html_attr(self, builder):
184 attr = self.HTML_ATTR.copy()
186 attr['class'] = self.HTML_CLASS
188 # always copy the id attribute (?)
189 if self.attrib.get('id'):
190 attr['id'] = self.attrib['id']
191 if self.attrib.get('_id'):
192 attr['id'] = self.attrib['_id']
195 def html_build(self, builder):
196 # Do we need a number?
197 numbering = self.numbering
198 if numbering == 'main':
199 if builder.with_numbering and self.has_visible_numbering:
200 builder.add_visible_number(self)
203 builder.start_element(
205 self.get_html_attr(builder),
208 self.html_build_inner(builder)
210 builder.end_element()
212 def epub_build_inner(self, builder):
213 self.build_inner(builder)
215 def get_epub_attr(self, builder):
216 attr = self.EPUB_ATTR.copy()
218 attr['class'] = self.EPUB_CLASS
221 def epub_build(self, builder):
222 from librarian.elements.masters import Master
225 self.CAN_HAVE_TEXT = True
228 start_chunk = self.EPUB_START_CHUNK and isinstance(self.getparent(), Master)
231 builder.start_chunk()
234 if self.SECTION_PRECEDENCE and not self.in_context_of('NO_TOC'):
236 fragment = 'sub%d' % builder.assign_section_number()
237 self.attrib['id'] = fragment
239 builder.add_toc_entry(
241 self.raw_printable_text(builder),
242 self.SECTION_PRECEDENCE
246 attr = self.get_epub_attr(builder)
248 attr['id'] = fragment
250 chunkno, sourceline = 0, self.sourceline
252 chunkno, sourceline = len(builder.splits), sourceline - builder.splits[-1]
253 attr['data-debug'] = f'{chunkno}:{sourceline}'
254 builder.start_element(
259 self.epub_build_inner(builder)
261 builder.end_element()
264 from librarian.elements.masters import Master
265 from librarian.elements.blocks import DlugiCytat, PoezjaCyt
266 from librarian.elements.footnotes import Footnote
268 if self.SECTION_PRECEDENCE:
269 assert isinstance(self.getparent(), (Master, DlugiCytat, PoezjaCyt, Footnote)), \
270 'Header {} inside a <{}> instead of a master.'.format(
271 etree.tostring(self, encoding='unicode'), self.getparent().tag)
274 if isinstance(c, WLElement):
279 # TODO: Remove insanity here.
281 if isinstance(e, WLElement):
284 def snip(self, words, before=None, sub=False):
285 if sub and self.ASIDE:
289 if before is not None:
290 i = self.index(before)
298 words, text = last_words(self[i].tail, words)
299 snippet = [('text', text)] + snippet
302 words, subsnip = self[i].snip(words, sub=True)
303 snippet = subsnip + snippet
305 if words and self.text:
306 words, text = last_words(self.text, words)
307 snippet = [('text', text)] + snippet
309 snippet = [('start', self.tag, self.attrib)] + snippet + [('end',)]
311 if not sub and words and not self.ASIDE:
313 parent = self.getparent()
314 if parent is not None and parent.CAN_HAVE_TEXT:
315 words, parsnip = parent.snip(words, before=self)
316 return words, parsnip[:-1] + snippet + parsnip[-1:]
318 return words, snippet
320 def get_snippet(self, words=15):
321 from librarian.parser import parser
323 words, snippet = self.getparent().snip(words=words, before=self)
325 cursor = snipelem = parser.makeelement('snippet')
326 snipelem._meta_object = self.meta
329 elem = parser.makeelement(s[1], **s[2])
333 cursor = cursor.getparent()
336 cursor[-1].tail = (cursor[-1].tail or '') + s[1]
338 cursor.text = (cursor.text or '') + s[1]
344 numbering = self.NUMBERING
345 if numbering is None or self.in_context_of('DISABLE_NUMBERING'):
347 numbering = self.get_context_map('SUPPRESS_NUMBERING', numbering, numbering)
352 prefix = self.numbering
354 # TODO: self.context.main_numbering_prefix
355 prefix = 'f' # default numbering prefix
358 def assign_id(self, document):
359 numbering = self.numbering
361 number = str(document.counters[numbering])
362 self.attrib['_id'] = self.id_prefix + number
363 document.counters[numbering] += 1
365 if numbering == 'main':
366 self.attrib['_visible_numbering'] = str(document.counters['_visible'])
367 document.counters['_visible'] += 1
369 if numbering == 'fn':
370 self.attrib['_visible_numbering'] = number
373 return self.attrib.get('_id') or self.getparent().get_link()
376 class Snippet(WLElement):