id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
26,400
config.py
kovidgoyal_calibre/manual/plugin_examples/interface_demo/config.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.utils.config import JSONConfig from qt.core import QHBoxLayout, QLabel, QLineEdit, QWidget # This is where all preferences for this plugin will be stored # Remember that this name (i.e. plugins/interface_demo) is also # in a global namespace, so make it as unique as possible. # You should always prefix your config file name with plugins/, # so as to ensure you dont accidentally clobber a calibre config file prefs = JSONConfig('plugins/interface_demo') # Set defaults prefs.defaults['hello_world_msg'] = 'Hello, World!' class ConfigWidget(QWidget): def __init__(self): QWidget.__init__(self) self.l = QHBoxLayout() self.setLayout(self.l) self.label = QLabel('Hello world &message:') self.l.addWidget(self.label) self.msg = QLineEdit(self) self.msg.setText(prefs['hello_world_msg']) self.l.addWidget(self.msg) self.label.setBuddy(self.msg) def save_settings(self): prefs['hello_world_msg'] = self.msg.text()
1,217
Python
.py
28
38.928571
69
0.706282
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,401
__init__.py
kovidgoyal_calibre/manual/plugin_examples/interface_demo/__init__.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' # The class that all Interface Action plugin wrappers must inherit from from calibre.customize import InterfaceActionBase class InterfacePluginDemo(InterfaceActionBase): ''' This class is a simple wrapper that provides information about the actual plugin class. The actual interface plugin class is called InterfacePlugin and is defined in the ui.py file, as specified in the actual_plugin field below. The reason for having two classes is that it allows the command line calibre utilities to run without needing to load the GUI libraries. ''' name = 'Interface Plugin Demo' description = 'An advanced plugin demo' supported_platforms = ['windows', 'osx', 'linux'] author = 'Kovid Goyal' version = (1, 0, 0) minimum_calibre_version = (0, 7, 53) #: This field defines the GUI plugin class that contains all the code #: that actually does something. Its format is module_path:class_name #: The specified class must be defined in the specified module. actual_plugin = 'calibre_plugins.interface_demo.ui:InterfacePlugin' def is_customizable(self): ''' This method must return True to enable customization via Preferences->Plugins ''' return True def config_widget(self): ''' Implement this method and :meth:`save_settings` in your plugin to use a custom configuration dialog. This method, if implemented, must return a QWidget. The widget can have an optional method validate() that takes no arguments and is called immediately after the user clicks OK. Changes are applied if and only if the method returns True. If for some reason you cannot perform the configuration at this time, return a tuple of two strings (message, details), these will be displayed as a warning dialog to the user and the process will be aborted. The base class implementation of this method raises NotImplementedError so by default no user configuration is possible. ''' # It is important to put this import statement here rather than at the # top of the module as importing the config class will also cause the # GUI libraries to be loaded, which we do not want when using calibre # from the command line from calibre_plugins.interface_demo.config import ConfigWidget return ConfigWidget() def save_settings(self, config_widget): ''' Save the settings specified by the user with config_widget. :param config_widget: The widget returned by :meth:`config_widget`. ''' config_widget.save_settings() # Apply the changes ac = self.actual_plugin_ if ac is not None: ac.apply_settings()
3,080
Python
.py
63
41.904762
79
0.687333
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,402
main.py
kovidgoyal_calibre/manual/plugin_examples/interface_demo/main.py
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' if False: # This is here to keep my python error checker from complaining about # the builtin functions that will be defined by the plugin loading system # You do not need this code in your plugins get_icons = get_resources = None from calibre_plugins.interface_demo.config import prefs from qt.core import QDialog, QLabel, QMessageBox, QPushButton, QVBoxLayout class DemoDialog(QDialog): def __init__(self, gui, icon, do_user_config): QDialog.__init__(self, gui) self.gui = gui self.do_user_config = do_user_config # The current database shown in the GUI # db is an instance of the class LibraryDatabase from db/legacy.py # This class has many, many methods that allow you to do a lot of # things. For most purposes you should use db.new_api, which has # a much nicer interface from db/cache.py self.db = gui.current_db self.l = QVBoxLayout() self.setLayout(self.l) self.label = QLabel(prefs['hello_world_msg']) self.l.addWidget(self.label) self.setWindowTitle('Interface Plugin Demo') self.setWindowIcon(icon) self.about_button = QPushButton('About', self) self.about_button.clicked.connect(self.about) self.l.addWidget(self.about_button) self.marked_button = QPushButton( 'Show books with only one format in the calibre GUI', self) self.marked_button.clicked.connect(self.marked) self.l.addWidget(self.marked_button) self.view_button = QPushButton( 'View the most recently added book', self) self.view_button.clicked.connect(self.view) self.l.addWidget(self.view_button) self.update_metadata_button = QPushButton( 'Update metadata in a book\'s files', self) self.update_metadata_button.clicked.connect(self.update_metadata) self.l.addWidget(self.update_metadata_button) self.conf_button = QPushButton( 'Configure this plugin', self) self.conf_button.clicked.connect(self.config) self.l.addWidget(self.conf_button) self.resize(self.sizeHint()) def about(self): # Get the about text from a file inside the plugin zip file # The get_resources function is a builtin function defined for all your # plugin code. It loads files from the plugin zip file. It returns # the bytes from the specified file. # # Note that if you are loading more than one file, for performance, you # should pass a list of names to get_resources. In this case, # get_resources will return a dictionary mapping names to bytes. Names that # are not found in the zip file will not be in the returned dictionary. text = get_resources('about.txt') QMessageBox.about(self, 'About the Interface Plugin Demo', text.decode('utf-8')) def marked(self): ''' Show books with only one format ''' db = self.db.new_api matched_ids = {book_id for book_id in db.all_book_ids() if len(db.formats(book_id)) == 1} # Mark the records with the matching ids # new_api does not know anything about marked books, so we use the full # db object self.db.set_marked_ids(matched_ids) # Tell the GUI to search for all marked records self.gui.search.setEditText('marked:true') self.gui.search.do_search() def view(self): ''' View the most recently added book ''' most_recent = most_recent_id = None db = self.db.new_api for book_id, timestamp in db.all_field_for('timestamp', db.all_book_ids()).items(): if most_recent is None or timestamp > most_recent: most_recent = timestamp most_recent_id = book_id if most_recent_id is not None: # Get a reference to the View plugin view_plugin = self.gui.iactions['View'] # Ask the view plugin to launch the viewer for row_number view_plugin._view_calibre_books([most_recent_id]) def update_metadata(self): ''' Set the metadata in the files in the selected book's record to match the current metadata in the database. ''' from calibre.ebooks.metadata.meta import set_metadata from calibre.gui2 import error_dialog, info_dialog # Get currently selected books rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, 'Cannot update metadata', 'No books selected', show=True) # Map the rows to book ids ids = list(map(self.gui.library_view.model().id, rows)) db = self.db.new_api for book_id in ids: # Get the current metadata for this book from the db mi = db.get_metadata(book_id, get_cover=True, cover_as_data=True) fmts = db.formats(book_id) if not fmts: continue for fmt in fmts: fmt = fmt.lower() # Get a python file object for the format. This will be either # an in memory file or a temporary on disk file ffile = db.format(book_id, fmt, as_file=True) ffile.seek(0) # Set metadata in the format set_metadata(ffile, mi, fmt) ffile.seek(0) # Now replace the file in the calibre library with the updated # file. We dont use add_format_with_hooks as the hooks were # already run when the file was first added to calibre. db.add_format(book_id, fmt, ffile, run_hooks=False) info_dialog(self, 'Updated files', 'Updated the metadata in the files of %d book(s)'%len(ids), show=True) def config(self): self.do_user_config(parent=self) # Apply the changes self.label.setText(prefs['hello_world_msg'])
6,297
Python
.py
127
39.456693
97
0.631348
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,403
svg.py
kovidgoyal_calibre/src/odf/svg.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .draw import DrawElement from .element import Element from .namespaces import SVGNS # Autogenerated def DefinitionSrc(**args): return Element(qname=(SVGNS,'definition-src'), **args) def Desc(**args): return Element(qname=(SVGNS,'desc'), **args) def FontFaceFormat(**args): return Element(qname=(SVGNS,'font-face-format'), **args) def FontFaceName(**args): return Element(qname=(SVGNS,'font-face-name'), **args) def FontFaceSrc(**args): return Element(qname=(SVGNS,'font-face-src'), **args) def FontFaceUri(**args): return Element(qname=(SVGNS,'font-face-uri'), **args) def Lineargradient(**args): return DrawElement(qname=(SVGNS,'linearGradient'), **args) def Radialgradient(**args): return DrawElement(qname=(SVGNS,'radialGradient'), **args) def Stop(**args): return Element(qname=(SVGNS,'stop'), **args) def Title(**args): return Element(qname=(SVGNS,'title'), **args)
1,758
Python
.py
42
39.357143
80
0.747194
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,404
manifest.py
kovidgoyal_calibre/src/odf/manifest.py
#!/usr/bin/env python # Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # from .element import Element from .namespaces import MANIFESTNS # Autogenerated def Manifest(**args): return Element(qname=(MANIFESTNS,'manifest'), **args) def FileEntry(**args): return Element(qname=(MANIFESTNS,'file-entry'), **args) def EncryptionData(**args): return Element(qname=(MANIFESTNS,'encryption-data'), **args) def Algorithm(**args): return Element(qname=(MANIFESTNS,'algorithm'), **args) def KeyDerivation(**args): return Element(qname=(MANIFESTNS,'key-derivation'), **args)
1,365
Python
.py
33
39.363636
80
0.764973
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,405
teletype.py
kovidgoyal_calibre/src/odf/teletype.py
# # Create and extract text from ODF, handling whitespace correctly. # Copyright (C) 2008 J. David Eisenberg # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Class for handling whitespace properly in OpenDocument. While it is possible to use getTextContent() and setTextContent() to extract or create ODF content, these won't extract or create the appropriate <text:s>, <text:tab>, or <text:line-break> elements. This module takes care of that problem. """ from .element import Node from .text import LineBreak, S, Tab class WhitespaceText: def __init__(self): self.textBuffer = [] self.spaceCount = 0 def addTextToElement(self, odfElement, s): """ Process an input string, inserting <text:tab> elements for '\t', <text:line-break> elements for '\n', and <text:s> elements for runs of more than one blank. These will be added to the given element. """ i = 0 ch = ' ' # When we encounter a tab or newline, we can immediately # dump any accumulated text and then emit the appropriate # ODF element. # # When we encounter a space, we add it to the text buffer, # and then collect more spaces. If there are more spaces # after the first one, we dump the text buffer and then # then emit the appropriate <text:s> element. while i < len(s): ch = s[i] if ch == '\t': self._emitTextBuffer(odfElement) odfElement.addElement(Tab()) i += 1 elif ch == '\n': self._emitTextBuffer(odfElement) odfElement.addElement(LineBreak()) i += 1 elif ch == ' ': self.textBuffer.append(' ') i += 1 self.spaceCount = 0 while i < len(s) and (s[i] == ' '): self.spaceCount += 1 i += 1 if self.spaceCount > 0: self._emitTextBuffer(odfElement) self._emitSpaces(odfElement) else: self.textBuffer.append(ch) i += 1 self._emitTextBuffer(odfElement) def _emitTextBuffer(self, odfElement): """ Creates a Text Node whose contents are the current textBuffer. Side effect: clears the text buffer. """ if len(self.textBuffer) > 0: odfElement.addText(''.join(self.textBuffer)) self.textBuffer = [] def _emitSpaces(self, odfElement): """ Creates a <text:s> element for the current spaceCount. Side effect: sets spaceCount back to zero """ if self.spaceCount > 0: spaceElement = S(c=self.spaceCount) odfElement.addElement(spaceElement) self.spaceCount = 0 def addTextToElement(odfElement, s): wst = WhitespaceText() wst.addTextToElement(odfElement, s) def extractText(odfElement): """ Extract text content from an Element, with whitespace represented properly. Returns the text, with tabs, spaces, and newlines correctly evaluated. This method recursively descends through the children of the given element, accumulating text and "unwrapping" <text:s>, <text:tab>, and <text:line-break> elements along the way. """ result = [] if len(odfElement.childNodes) != 0: for child in odfElement.childNodes: if child.nodeType == Node.TEXT_NODE: result.append(child.data) elif child.nodeType == Node.ELEMENT_NODE: subElement = child tagName = subElement.qname if tagName == ("urn:oasis:names:tc:opendocument:xmlns:text:1.0", "line-break"): result.append("\n") elif tagName == ("urn:oasis:names:tc:opendocument:xmlns:text:1.0", "tab"): result.append("\t") elif tagName == ("urn:oasis:names:tc:opendocument:xmlns:text:1.0", "s"): c = subElement.getAttribute('c') if c: spaceCount = int(c) else: spaceCount = 1 result.append(" " * spaceCount) else: result.append(extractText(subElement)) return ''.join(result)
5,121
Python
.py
118
33.279661
95
0.599237
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,406
dr3d.py
kovidgoyal_calibre/src/odf/dr3d.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .draw import StyleRefElement from .namespaces import DR3DNS # Autogenerated def Cube(**args): return StyleRefElement(qname=(DR3DNS,'cube'), **args) def Extrude(**args): return StyleRefElement(qname=(DR3DNS,'extrude'), **args) def Light(Element, **args): return StyleRefElement(qname=(DR3DNS,'light'), **args) def Rotate(**args): return StyleRefElement(qname=(DR3DNS,'rotate'), **args) def Scene(**args): return StyleRefElement(qname=(DR3DNS,'scene'), **args) def Sphere(**args): return StyleRefElement(qname=(DR3DNS,'sphere'), **args)
1,398
Python
.py
33
40.181818
80
0.759259
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,407
form.py
kovidgoyal_calibre/src/odf/form.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import FORMNS # Autogenerated def Button(**args): return Element(qname=(FORMNS,'button'), **args) def Checkbox(**args): return Element(qname=(FORMNS,'checkbox'), **args) def Column(**args): return Element(qname=(FORMNS,'column'), **args) def Combobox(**args): return Element(qname=(FORMNS,'combobox'), **args) def ConnectionResource(**args): return Element(qname=(FORMNS,'connection-resource'), **args) def Date(**args): return Element(qname=(FORMNS,'date'), **args) def File(**args): return Element(qname=(FORMNS,'file'), **args) def FixedText(**args): return Element(qname=(FORMNS,'fixed-text'), **args) def Form(**args): return Element(qname=(FORMNS,'form'), **args) def FormattedText(**args): return Element(qname=(FORMNS,'formatted-text'), **args) def Frame(**args): return Element(qname=(FORMNS,'frame'), **args) def GenericControl(**args): return Element(qname=(FORMNS,'generic-control'), **args) def Grid(**args): return Element(qname=(FORMNS,'grid'), **args) def Hidden(**args): return Element(qname=(FORMNS,'hidden'), **args) def Image(**args): return Element(qname=(FORMNS,'image'), **args) def ImageFrame(**args): return Element(qname=(FORMNS,'image-frame'), **args) def Item(**args): return Element(qname=(FORMNS,'item'), **args) def ListProperty(**args): return Element(qname=(FORMNS,'list-property'), **args) def ListValue(**args): return Element(qname=(FORMNS,'list-value'), **args) def Listbox(**args): return Element(qname=(FORMNS,'listbox'), **args) def Number(**args): return Element(qname=(FORMNS,'number'), **args) def Option(**args): return Element(qname=(FORMNS,'option'), **args) def Password(**args): return Element(qname=(FORMNS,'password'), **args) def Properties(**args): return Element(qname=(FORMNS,'properties'), **args) def Property(**args): return Element(qname=(FORMNS,'property'), **args) def Radio(**args): return Element(qname=(FORMNS,'radio'), **args) def Text(**args): return Element(qname=(FORMNS,'text'), **args) def Textarea(**args): return Element(qname=(FORMNS,'textarea'), **args) def Time(**args): return Element(qname=(FORMNS,'time'), **args) def ValueRange(**args): return Element(qname=(FORMNS,'value-range'), **args)
3,215
Python
.py
81
36.444444
80
0.712565
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,408
odfmanifest.py
kovidgoyal_calibre/src/odf/odfmanifest.py
#!/usr/bin/env python # Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # This script lists the content of the manifest.xml file import io import zipfile from xml.sax import handler, make_parser from xml.sax.xmlreader import InputSource MANIFESTNS="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" # ----------------------------------------------------------------------------- # # ODFMANIFESTHANDLER # # ----------------------------------------------------------------------------- class ODFManifestHandler(handler.ContentHandler): """ The ODFManifestHandler parses a manifest file and produces a list of content """ def __init__(self): self.manifest = {} # Tags # FIXME: Also handle encryption data self.elements = { (MANIFESTNS, 'file-entry'): (self.s_file_entry, self.donothing), } def handle_starttag(self, tag, method, attrs): method(tag,attrs) def handle_endtag(self, tag, method): method(tag) def startElementNS(self, tag, qname, attrs): method = self.elements.get(tag, (None, None))[0] if method: self.handle_starttag(tag, method, attrs) else: self.unknown_starttag(tag,attrs) def endElementNS(self, tag, qname): method = self.elements.get(tag, (None, None))[1] if method: self.handle_endtag(tag, method) else: self.unknown_endtag(tag) def unknown_starttag(self, tag, attrs): pass def unknown_endtag(self, tag): pass def donothing(self, tag, attrs=None): pass def s_file_entry(self, tag, attrs): m = attrs.get((MANIFESTNS, 'media-type'),"application/octet-stream") p = attrs.get((MANIFESTNS, 'full-path')) self.manifest[p] = {'media-type':m, 'full-path':p} # ----------------------------------------------------------------------------- # # Reading the file # # ----------------------------------------------------------------------------- def manifestlist(manifestxml): odhandler = ODFManifestHandler() parser = make_parser() parser.setFeature(handler.feature_namespaces, 1) parser.setContentHandler(odhandler) parser.setErrorHandler(handler.ErrorHandler()) inpsrc = InputSource() inpsrc.setByteStream(io.BytesIO(manifestxml)) parser.setFeature(handler.feature_external_ges, False) # Changed by Kovid to ignore external DTDs parser.parse(inpsrc) return odhandler.manifest def odfmanifest(odtfile): z = zipfile.ZipFile(odtfile) manifest = z.read('META-INF/manifest.xml') z.close() return manifestlist(manifest) if __name__ == "__main__": import sys result = odfmanifest(sys.argv[1]) for file in result.values(): print("%-40s %-40s" % (file['media-type'], file['full-path']))
3,614
Python
.py
92
34.402174
102
0.633686
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,409
config.py
kovidgoyal_calibre/src/odf/config.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import CONFIGNS # Autogenerated def ConfigItem(**args): return Element(qname=(CONFIGNS, 'config-item'), **args) def ConfigItemMapEntry(**args): return Element(qname=(CONFIGNS,'config-item-map-entry'), **args) def ConfigItemMapIndexed(**args): return Element(qname=(CONFIGNS,'config-item-map-indexed'), **args) def ConfigItemMapNamed(**args): return Element(qname=(CONFIGNS,'config-item-map-named'), **args) def ConfigItemSet(**args): return Element(qname=(CONFIGNS, 'config-item-set'), **args)
1,392
Python
.py
31
42.83871
80
0.767062
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,410
meta.py
kovidgoyal_calibre/src/odf/meta.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import METANS # Autogenerated def AutoReload(**args): return Element(qname=(METANS,'auto-reload'), **args) def CreationDate(**args): return Element(qname=(METANS,'creation-date'), **args) def DateString(**args): return Element(qname=(METANS,'date-string'), **args) def DocumentStatistic(**args): return Element(qname=(METANS,'document-statistic'), **args) def EditingCycles(**args): return Element(qname=(METANS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname=(METANS,'editing-duration'), **args) def Generator(**args): return Element(qname=(METANS,'generator'), **args) def HyperlinkBehaviour(**args): return Element(qname=(METANS,'hyperlink-behaviour'), **args) def InitialCreator(**args): return Element(qname=(METANS,'initial-creator'), **args) def Keyword(**args): return Element(qname=(METANS,'keyword'), **args) def PrintDate(**args): return Element(qname=(METANS,'print-date'), **args) def PrintedBy(**args): return Element(qname=(METANS,'printed-by'), **args) def Template(**args): return Element(qname=(METANS,'template'), **args) def UserDefined(**args): return Element(qname=(METANS,'user-defined'), **args)
2,101
Python
.py
49
40.102041
80
0.743691
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,411
namespaces.py
kovidgoyal_calibre/src/odf/namespaces.py
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # TOOLSVERSION = "ODFPY/0.9.4dev" ANIMNS = "urn:oasis:names:tc:opendocument:xmlns:animation:1.0" CHARTNS = "urn:oasis:names:tc:opendocument:xmlns:chart:1.0" CHARTOOONS = "http://openoffice.org/2010/chart" CONFIGNS = "urn:oasis:names:tc:opendocument:xmlns:config:1.0" CSS3TNS = "http://www.w3.org/TR/css3-text/" # DBNS = u"http://openoffice.org/2004/database" DBNS = "urn:oasis:names:tc:opendocument:xmlns:database:1.0" DCNS = "http://purl.org/dc/elements/1.1/" DOMNS = "http://www.w3.org/2001/xml-events" DR3DNS = "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" DRAWNS = "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" FIELDNS = "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" FONS = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" FORMNS = "urn:oasis:names:tc:opendocument:xmlns:form:1.0" FORMXNS = "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0" GRDDLNS = "http://www.w3.org/2003/g/data-view#" KOFFICENS = "http://www.koffice.org/2005/" MANIFESTNS = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" MATHNS = "http://www.w3.org/1998/Math/MathML" METANS = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0" NUMBERNS = "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" OFFICENS = "urn:oasis:names:tc:opendocument:xmlns:office:1.0" OFNS = "urn:oasis:names:tc:opendocument:xmlns:of:1.2" OOOCNS = "http://openoffice.org/2004/calc" OOONS = "http://openoffice.org/2004/office" OOOWNS = "http://openoffice.org/2004/writer" PRESENTATIONNS = "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" RDFANS = "http://docs.oasis-open.org/opendocument/meta/rdfa#" RPTNS = "http://openoffice.org/2005/report" SCRIPTNS = "urn:oasis:names:tc:opendocument:xmlns:script:1.0" SMILNS = "urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0" STYLENS = "urn:oasis:names:tc:opendocument:xmlns:style:1.0" SVGNS = "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" TABLENS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0" TABLEOOONS = "http://openoffice.org/2009/table" TEXTNS = "urn:oasis:names:tc:opendocument:xmlns:text:1.0" XFORMSNS = "http://www.w3.org/2002/xforms" XHTMLNS = "http://www.w3.org/1999/xhtml" XLINKNS = "http://www.w3.org/1999/xlink" XMLNS = "http://www.w3.org/XML/1998/namespace" XSDNS = "http://www.w3.org/2001/XMLSchema" XSINS = "http://www.w3.org/2001/XMLSchema-instance" nsdict = { ANIMNS: 'anim', CHARTNS: 'chart', CHARTOOONS: 'chartooo', CONFIGNS: 'config', CSS3TNS: 'css3t', DBNS: 'db', DCNS: 'dc', DOMNS: 'dom', DR3DNS: 'dr3d', DRAWNS: 'draw', FIELDNS: 'field', FONS: 'fo', FORMNS: 'form', FORMXNS: 'formx', GRDDLNS: 'grddl', KOFFICENS: 'koffice', MANIFESTNS: 'manifest', MATHNS: 'math', METANS: 'meta', NUMBERNS: 'number', OFFICENS: 'office', OFNS: 'of', OOONS: 'ooo', OOOWNS: 'ooow', OOOCNS: 'oooc', PRESENTATIONNS: 'presentation', RDFANS: 'rdfa', RPTNS: 'rpt', SCRIPTNS: 'script', SMILNS: 'smil', STYLENS: 'style', SVGNS: 'svg', TABLENS: 'table', TABLEOOONS: 'tableooo', TEXTNS: 'text', XFORMSNS: 'xforms', XLINKNS: 'xlink', XHTMLNS: 'xhtml', XMLNS: 'xml', XSDNS: 'xsd', XSINS: 'xsi', }
4,328
Python
.py
104
39.403846
85
0.675669
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,412
dc.py
kovidgoyal_calibre/src/odf/dc.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import DCNS # Autogenerated def Creator(**args): return Element(qname=(DCNS,'creator'), **args) def Date(**args): return Element(qname=(DCNS,'date'), **args) def Description(**args): return Element(qname=(DCNS,'description'), **args) def Language(**args): return Element(qname=(DCNS,'language'), **args) def Subject(**args): return Element(qname=(DCNS,'subject'), **args) def Title(**args): return Element(qname=(DCNS,'title'), **args) # The following complete the Dublin Core elements, but there is no # guarantee a compliant implementation of OpenDocument will preserve # these elements # def Contributor(**args): # return Element(qname = (DCNS,'contributor'), **args) # def Coverage(**args): # return Element(qname = (DCNS,'coverage'), **args) # def Format(**args): # return Element(qname = (DCNS,'format'), **args) # def Identifier(**args): # return Element(qname = (DCNS,'identifier'), **args) # def Publisher(**args): # return Element(qname = (DCNS,'publisher'), **args) # def Relation(**args): # return Element(qname = (DCNS,'relation'), **args) # def Rights(**args): # return Element(qname = (DCNS,'rights'), **args) # def Source(**args): # return Element(qname = (DCNS,'source'), **args) # def Type(**args): # return Element(qname = (DCNS,'type'), **args)
2,206
Python
.py
54
38.944444
80
0.717913
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,413
presentation.py
kovidgoyal_calibre/src/odf/presentation.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import PRESENTATIONNS # ODF 1.0 section 9.6 and 9.7 # Autogenerated def AnimationGroup(**args): return Element(qname=(PRESENTATIONNS,'animation-group'), **args) def Animations(**args): return Element(qname=(PRESENTATIONNS,'animations'), **args) def DateTime(**args): return Element(qname=(PRESENTATIONNS,'date-time'), **args) def DateTimeDecl(**args): return Element(qname=(PRESENTATIONNS,'date-time-decl'), **args) def Dim(**args): return Element(qname=(PRESENTATIONNS,'dim'), **args) def EventListener(**args): return Element(qname=(PRESENTATIONNS,'event-listener'), **args) def Footer(**args): return Element(qname=(PRESENTATIONNS,'footer'), **args) def FooterDecl(**args): return Element(qname=(PRESENTATIONNS,'footer-decl'), **args) def Header(**args): return Element(qname=(PRESENTATIONNS,'header'), **args) def HeaderDecl(**args): return Element(qname=(PRESENTATIONNS,'header-decl'), **args) def HideShape(**args): return Element(qname=(PRESENTATIONNS,'hide-shape'), **args) def HideText(**args): return Element(qname=(PRESENTATIONNS,'hide-text'), **args) def Notes(**args): return Element(qname=(PRESENTATIONNS,'notes'), **args) def Placeholder(**args): return Element(qname=(PRESENTATIONNS,'placeholder'), **args) def Play(**args): return Element(qname=(PRESENTATIONNS,'play'), **args) def Settings(**args): return Element(qname=(PRESENTATIONNS,'settings'), **args) def Show(**args): return Element(qname=(PRESENTATIONNS,'show'), **args) def ShowShape(**args): return Element(qname=(PRESENTATIONNS,'show-shape'), **args) def ShowText(**args): return Element(qname=(PRESENTATIONNS,'show-text'), **args) def Sound(**args): return Element(qname=(PRESENTATIONNS,'sound'), **args)
2,673
Python
.py
62
40.129032
80
0.740654
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,414
style.py
kovidgoyal_calibre/src/odf/style.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import STYLENS def StyleElement(**args): e = Element(**args) if args.get('check_grammar', True) is True: if 'displayname' not in args: e.setAttrNS(STYLENS,'display-name', args.get('name')) return e # Autogenerated def BackgroundImage(**args): return Element(qname=(STYLENS,'background-image'), **args) def ChartProperties(**args): return Element(qname=(STYLENS,'chart-properties'), **args) def Column(**args): return Element(qname=(STYLENS,'column'), **args) def ColumnSep(**args): return Element(qname=(STYLENS,'column-sep'), **args) def Columns(**args): return Element(qname=(STYLENS,'columns'), **args) def DefaultStyle(**args): return Element(qname=(STYLENS,'default-style'), **args) def DrawingPageProperties(**args): return Element(qname=(STYLENS,'drawing-page-properties'), **args) def DropCap(**args): return Element(qname=(STYLENS,'drop-cap'), **args) def FontFace(**args): return Element(qname=(STYLENS,'font-face'), **args) def Footer(**args): return Element(qname=(STYLENS,'footer'), **args) def FooterLeft(**args): return Element(qname=(STYLENS,'footer-left'), **args) def FooterStyle(**args): return Element(qname=(STYLENS,'footer-style'), **args) def FootnoteSep(**args): return Element(qname=(STYLENS,'footnote-sep'), **args) def GraphicProperties(**args): return Element(qname=(STYLENS,'graphic-properties'), **args) def HandoutMaster(**args): return Element(qname=(STYLENS,'handout-master'), **args) def Header(**args): return Element(qname=(STYLENS,'header'), **args) def HeaderFooterProperties(**args): return Element(qname=(STYLENS,'header-footer-properties'), **args) def HeaderLeft(**args): return Element(qname=(STYLENS,'header-left'), **args) def HeaderStyle(**args): return Element(qname=(STYLENS,'header-style'), **args) def ListLevelProperties(**args): return Element(qname=(STYLENS,'list-level-properties'), **args) def Map(**args): return Element(qname=(STYLENS,'map'), **args) def MasterPage(**args): return StyleElement(qname=(STYLENS,'master-page'), **args) def PageLayout(**args): return Element(qname=(STYLENS,'page-layout'), **args) def PageLayoutProperties(**args): return Element(qname=(STYLENS,'page-layout-properties'), **args) def ParagraphProperties(**args): return Element(qname=(STYLENS,'paragraph-properties'), **args) def PresentationPageLayout(**args): return StyleElement(qname=(STYLENS,'presentation-page-layout'), **args) def RegionCenter(**args): return Element(qname=(STYLENS,'region-center'), **args) def RegionLeft(**args): return Element(qname=(STYLENS,'region-left'), **args) def RegionRight(**args): return Element(qname=(STYLENS,'region-right'), **args) def RubyProperties(**args): return Element(qname=(STYLENS,'ruby-properties'), **args) def SectionProperties(**args): return Element(qname=(STYLENS,'section-properties'), **args) def Style(**args): return StyleElement(qname=(STYLENS,'style'), **args) def TabStop(**args): return Element(qname=(STYLENS,'tab-stop'), **args) def TabStops(**args): return Element(qname=(STYLENS,'tab-stops'), **args) def TableCellProperties(**args): return Element(qname=(STYLENS,'table-cell-properties'), **args) def TableColumnProperties(**args): return Element(qname=(STYLENS,'table-column-properties'), **args) def TableProperties(**args): return Element(qname=(STYLENS,'table-properties'), **args) def TableRowProperties(**args): return Element(qname=(STYLENS,'table-row-properties'), **args) def TextProperties(**args): return Element(qname=(STYLENS,'text-properties'), **args)
4,611
Python
.py
105
40.333333
80
0.728239
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,415
thumbnail.py
kovidgoyal_calibre/src/odf/thumbnail.py
#!/usr/bin/env python # This contains a 128x128 px thumbnail in PNG format # Taken from https://cgit.freedesktop.org/libreoffice/core/tree/sysui/desktop/icons/hicolor/128x128/apps/main.png # License: GPL-3 import base64 iconstr = b""" iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAA3NCSVQICAjb4U/gAAAACXBIWXMA AA3XAAAN1wFCKJt4AAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAspQTFRF AAAAgICAZmZmVVVVgICAampqgICAYmJidnZ2aGhoa2treHh4ZGRkcHBwdnZ2ampqcXFxb29vc3Nz cXFxcHBwbm5uUlJSY2Njbm5ubW1tbGxsampqbW1tbGxsa2trfn5+aGhoampqaWlpfX19d3d3d3d3 ZGRkb29vYmJiVFRUZGRkZ2dnbm5uZmZmVFRUYmJiZGRkc3NzfX19c3NzfX19dXV1ZGRkampqdHR0 dXV1aWlpa2trbGxsbW1tb29vcHBwcXFxcnJydHR0ZWVlZmZmaGhoaGhofn5+d3d3Y2Njc3Nzbm5u cHBwZ2dnaGhoU1NTZGRkU1NTYmJifn5+d3d3bm5ub29vcXFxcnJyc3Nzd3d3eHh4eXl5enp6e3t7 fHx8fX19fn5+Y2NjaGhofn5+c3NzU1NTcnJyc3Nzfn5+U1NTYmJiZGRkaGhob29vcXFxcnJybm5u b29vbGxsbW1tbm5uc3Nzampqa2trbGxsdnZ2ZGRkaWlpaGhoaWlpZGRkZWVlZmZmZ2dnaGhoaWlp ampqa2trbGxsbW1tbm5ub29vcHBwcXFxcnJyc3NzdHR0dXV1dnZ2d3d3eHh4eXl5enp6e3t7fHx8 fX19fn5+U1NTVFRUVVVVVlZWV1dXWFhYWVlZWlpaW1tbXFxcXV1dXl5eX19fYGBgYWFhYmJiY2Nj ZGRkZWVlZmZmZ2dnaGhoaWlpampqa2trbGxsbW1tbm5ub29vcHBwcXFxcnJyc3NzdHR0dXV1dnZ2 d3d3eHh4eXl5enp6e3t7fHx8fX19fn5+r6+vsLCwsbGxsrKys7OztLS0tbW1tra2t7e3uLi4ubm5 urq6u7u7vLy85ubm5+fn6Ojo6enp6urq6+vr7Ozs7e3t7u7u7+/v8PDw8fHx8vLy8/Pz9PT09fX1 9vb29/f3+Pj4+fn5+vr6+/v7/Pz8/f39/v7+/////mjUnAAAAJp0Uk5TAAIFBggMDA0NFh8kKTI0 RkZHR0hJSktLUVJTVFRVVltdXl94iY6Pj5GSkpKVrK6urrG3uru/wcLCwsTExMTExMTExMXFxcrL zdPV1+Dh4eLi4+Pl6evu7u7u7u7u7u7u7u7x8vLz9vb29vf39/f39/f4+Pr6+vr7+/v7/Pz9/f7+ /v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/nFrVcgAAAWNSURBVHjavVtNaNRAFB4lCoJ4UPdHD/VQ QQVBKYragwpd0B4V7148WMGjdv0Hi7Z6EQU9FqltpQiePAleVPxfURCRaqvW2t31By3+tqLPJDNJ s92dmTebeckhfckkmS/ffPPy3ryuw6LbjIYFTWvvRU7A1B5kJya/vyr+qHgMm7++YbzysvBxP18O /4le6lQcrD7r7ldO6x8UUIR548rQv8hz5u3KKe67cOO3DMCSsxXvgehZ7Fta8k8np25szKku3vP2 mQzAUln/eiidRwpTCJar71shBTC3qn88CR0RBHPV9+28IgOQxtFfG0rH4UKgrsc7tPfVBrA6JDB6 HVQZldbHMrdcDgSCwavbNa8gAVAlAHmvESPFytzq6LzD9f1tYE6rijwEAND1GrVcBNzKd97lCL5e hFaGI8FRdo8kYiGU+eGBEEEPa1VqVwEAkP1HT3mj4B+HCL70sK0YDVYDADP6hZViJW7muwIEvd4o aDU4HQAYD0SogxK3QwSf+1grYiI6+v5xQFLAlQjtXfcEgn4np5+IjtL5mRCRCpSYDxB86mE57UR0 as8AqIOIdKDE9q77AsElyGk0WAUATN1QxEpPKVEg+NjrcqCeiA7u9XFEpEMldj4QCC47m9QT0amX /pqNKVbkRr5LICj1wmblRHQQXtCAiBSEs1EgKPaxzaqPgWPSP6LRHQVutJ8KEPT7HEg0KHdEUCek tMeBdxQiGBuY3YzVAFggwlOimI0POYLRS2yD0ccoJhFprkRwOQgQ9ECzkQZiEpEOlBgieN/HmvEf I4itiIxQIuw/9YgjeNfvcaAPSKDesGyaxUfBV6JAMHKZNes1UHFBLCI8BP6xy8FEgGADMiCxMiHT ECjxxGMeK48MzFrDG69h/EDsCZnxRsGzDwUI3vTNbPIbH+g1ABY8k+CAwcGTAsHrXmhy/3QPaTUA zAYRmUCJIYLhc+uWvR0a/qXTAFj6MLgI+IkDpwtciePXryMCErD2YcgEStwfIGCajxHYcQOhlQln 4/mbEwgAYPG7HOhgjFt7mASBzA+AJSJ8BJ4hQ+Bo+o9NhIuAW221ETjG/ZtCysAYP6yNoFZAAjZ1 yHXgH7bBrQm9BiJhkS0iMuw9N9tYNQJ5UGqRCH8UwNdBFQInZv84SFmhRNgNtyeQjgisEsFHwVfi NASSgARsE+Eh8E/s/lb4q3dEYJ+IDAgl7jv2XKuBurlWXZ8NlLht5LtaA0CiQwZZPhvZqsWDqKDU PhFZocTGQVR2TECEi8AzFqEcEQkR2VFvv6Ub4QcIidCukFiLRmqfwqyQUBKByY4JiUCtkEBSilCt kNApArdCQqdD9CoZ0BCBXq6n0iFyuZ5o0PUrpRCBSUVEzJJN7Eb7JRuzRlslmxiNVCUbtPNBrpKR 6ZC0ZINoNPUDJERQlmwwjfiSDQ0R1CUbI/qVjghoiEAHJHQ6rLdkYwuSWcnGPhGojxF1UqJzRECr Q3TJhjRNRTiiJCakyg8klp05mv4JiEAEJAkmx+qSTQLJsWnJJi4kk6CUigjUCgllVIwMSKiSY2xA QhWWYQMS0tUqfUBCG5bpAxLaqBgflNIQYZAd00XFOEeUUHJsq2SDb8QFJHQ6xGmAbpHG8B8aaYjQ BiRAqkN0UJpQckxaspHRj/IDhLE4KiAhJKLOko01SEYlmwSSY9OSjX1FYEo2RIpQrZDQZWdxSjZW UnLjko1lIrCOKLnkGFuysQfJpGRDQUTMko2dpMS0ZGM5OUaWbJJKjg1KNnaIMC3ZkJeMzEs21pZI 5QEJcc0CH5TSZWdSAJ/96wq6H9jGaPO3R1IAo3Q9RwkoSwG8AdTT64YittdSAEVLL6r5iV9JCqB8 9Dg1/e525oN8FrzYm21ctJGEBL49KQ6VKvpn/wE4qQRdyiC8rQAAAABJRU5ErkJggg== """ def thumbnail(): icon = base64.decodestring(iconstr) return icon if __name__ == "__main__": icon = thumbnail() f = open("thumbnail.png","wb") f.write(icon) f.close()
3,737
Python
.py
58
62.931034
113
0.938214
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,416
attrconverters.py
kovidgoyal_calibre/src/odf/attrconverters.py
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # import re from polyglot.builtins import string_or_bytes, unicode_type from .namespaces import ( ANIMNS, CHARTNS, CONFIGNS, DR3DNS, DRAWNS, FONS, FORMNS, MANIFESTNS, METANS, NUMBERNS, OFFICENS, PRESENTATIONNS, SCRIPTNS, SMILNS, STYLENS, SVGNS, TABLENS, TEXTNS, XFORMSNS, XLINKNS, ) pattern_color = re.compile(r'#[0-9a-fA-F]{6}') pattern_vector3D = re.compile(r'\([ ]*-?([0-9]+(\.[0-9]*)?|\.[0-9]+)([ ]+-?([0-9]+(\.[0-9]*)?|\.[0-9]+)){2}[ ]*\)') def make_NCName(arg): for c in (':',' '): arg = arg.replace(c,"_%x_" % ord(c)) return arg def cnv_anyURI(attribute, arg, element): return str(arg) def cnv_boolean(attribute, arg, element): if arg.lower() in ("false","no"): return "false" if arg: return "true" return "false" # Potentially accept color values def cnv_color(attribute, arg, element): """ A RGB color in conformance with §5.9.11 of [XSL], that is a RGB color in notation “#rrggbb”, where rr, gg and bb are 8-bit hexadecimal digits. """ return unicode_type(arg) def cnv_configtype(attribute, arg, element): if unicode_type(arg) not in ("boolean", "short", "int", "long", "double", "string", "datetime", "base64Binary"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) def cnv_data_source_has_labels(attribute, arg, element): if unicode_type(arg) not in ("none","row","column","both"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) # Understand different date formats def cnv_date(attribute, arg, element): """ A dateOrDateTime value is either an [xmlschema-2] date value or an [xmlschema-2] dateTime value. """ return unicode_type(arg) def cnv_dateTime(attribute, arg, element): """ A dateOrDateTime value is either an [xmlschema-2] date value or an [xmlschema-2] dateTime value. """ return unicode_type(arg) def cnv_double(attribute, arg, element): return unicode_type(arg) def cnv_duration(attribute, arg, element): return unicode_type(arg) def cnv_family(attribute, arg, element): """ A style family """ if unicode_type(arg) not in ("text", "paragraph", "section", "ruby", "table", "table-column", "table-row", "table-cell", "graphic", "presentation", "drawing-page", "chart"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) def __save_prefix(attribute, arg, element): prefix = arg.split(':',1)[0] if prefix == arg: return str(arg) namespace = element.get_knownns(prefix) if namespace is None: # raise ValueError, "'%s' is an unknown prefix" % unicode_type(prefix) return str(arg) return str(arg) def cnv_formula(attribute, arg, element): """ A string containing a formula. Formulas do not have a predefined syntax, but the string should begin with a namespace prefix, followed by a “:” (COLON, U+003A) separator, followed by the text of the formula. The namespace bound to the prefix determines the syntax and semantics of the formula. """ return __save_prefix(attribute, arg, element) def cnv_ID(attribute, arg, element): return unicode_type(arg) def cnv_IDREF(attribute, arg, element): return unicode_type(arg) def cnv_integer(attribute, arg, element): return unicode_type(arg) def cnv_legend_position(attribute, arg, element): if unicode_type(arg) not in ("start", "end", "top", "bottom", "top-start", "bottom-start", "top-end", "bottom-end"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) pattern_length = re.compile(r'-?([0-9]+(\.[0-9]*)?|\.[0-9]+)((cm)|(mm)|(in)|(pt)|(pc)|(px))') def cnv_length(attribute, arg, element): """ A (positive or negative) physical length, consisting of magnitude and unit, in conformance with the Units of Measure defined in §5.9.13 of [XSL]. """ global pattern_length if not pattern_length.match(arg): raise ValueError("'%s' is not a valid length" % arg) return arg def cnv_lengthorpercent(attribute, arg, element): failed = False try: return cnv_length(attribute, arg, element) except: failed = True try: return cnv_percent(attribute, arg, element) except: failed = True if failed: raise ValueError("'%s' is not a valid length or percent" % arg) return arg def cnv_metavaluetype(attribute, arg, element): if unicode_type(arg) not in ("float", "date", "time", "boolean", "string"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) def cnv_major_minor(attribute, arg, element): if arg not in ('major','minor'): raise ValueError("'%s' is not either 'minor' or 'major'" % arg) pattern_namespacedToken = re.compile(r'[0-9a-zA-Z_]+:[0-9a-zA-Z._\-]+') def cnv_namespacedToken(attribute, arg, element): global pattern_namespacedToken if not pattern_namespacedToken.match(arg): raise ValueError("'%s' is not a valid namespaced token" % arg) return __save_prefix(attribute, arg, element) def cnv_NCName(attribute, arg, element): """ NCName is defined in http://www.w3.org/TR/REC-xml-names/#NT-NCName Essentially an XML name minus ':' """ if isinstance(arg, string_or_bytes): return make_NCName(arg) else: return arg.getAttrNS(STYLENS, 'name') # This function takes either an instance of a style (preferred) # or a text string naming the style. If it is a text string, then it must # already have been converted to an NCName # The text-string argument is mainly for when we build a structure from XML def cnv_StyleNameRef(attribute, arg, element): try: return arg.getAttrNS(STYLENS, 'name') except: return arg # This function takes either an instance of a style (preferred) # or a text string naming the style. If it is a text string, then it must # already have been converted to an NCName # The text-string argument is mainly for when we build a structure from XML def cnv_DrawNameRef(attribute, arg, element): try: return arg.getAttrNS(DRAWNS, 'name') except: return arg # Must accept list of Style objects def cnv_NCNames(attribute, arg, element): return ' '.join(arg) def cnv_nonNegativeInteger(attribute, arg, element): return unicode_type(arg) pattern_percent = re.compile(r'-?([0-9]+(\.[0-9]*)?|\.[0-9]+)%') def cnv_percent(attribute, arg, element): global pattern_percent if not pattern_percent.match(arg): raise ValueError("'%s' is not a valid length" % arg) return arg # Real one doesn't allow floating point values pattern_points = re.compile(r'-?[0-9]+,-?[0-9]+([ ]+-?[0-9]+,-?[0-9]+)*') # pattern_points = re.compile(r'-?[0-9.]+,-?[0-9.]+([ ]+-?[0-9.]+,-?[0-9.]+)*') def cnv_points(attribute, arg, element): global pattern_points if isinstance(arg, string_or_bytes): if not pattern_points.match(arg): raise ValueError("x,y are separated by a comma and the points are separated by white spaces") return arg else: try: strarg = ' '.join(["%d,%d" % p for p in arg]) except: raise ValueError("Points must be string or [(0,0),(1,1)] - not %s" % arg) return strarg def cnv_positiveInteger(attribute, arg, element): return unicode_type(arg) def cnv_string(attribute, arg, element): return str(arg) def cnv_textnoteclass(attribute, arg, element): if unicode_type(arg) not in ("footnote", "endnote"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) # Understand different time formats def cnv_time(attribute, arg, element): return unicode_type(arg) def cnv_token(attribute, arg, element): return unicode_type(arg) pattern_viewbox = re.compile(r'-?[0-9]+([ ]+-?[0-9]+){3}$') def cnv_viewbox(attribute, arg, element): global pattern_viewbox if not pattern_viewbox.match(arg): raise ValueError("viewBox must be four integers separated by whitespaces") return arg def cnv_xlinkshow(attribute, arg, element): if unicode_type(arg) not in ("new", "replace", "embed"): raise ValueError("'%s' not allowed" % unicode_type(arg)) return unicode_type(arg) attrconverters = { ((ANIMNS,'audio-level'), None): cnv_double, ((ANIMNS,'color-interpolation'), None): cnv_string, ((ANIMNS,'color-interpolation-direction'), None): cnv_string, ((ANIMNS,'command'), None): cnv_string, ((ANIMNS,'formula'), None): cnv_string, ((ANIMNS,'id'), None): cnv_ID, ((ANIMNS,'iterate-interval'), None): cnv_duration, ((ANIMNS,'iterate-type'), None): cnv_string, ((ANIMNS,'name'), None): cnv_string, ((ANIMNS,'sub-item'), None): cnv_string, ((ANIMNS,'value'), None): cnv_string, # ((DBNS,u'type'), None): cnv_namespacedToken, ((CHARTNS,'attached-axis'), None): cnv_string, ((CHARTNS,'class'), (CHARTNS,'grid')): cnv_major_minor, ((CHARTNS,'class'), None): cnv_namespacedToken, ((CHARTNS,'column-mapping'), None): cnv_string, ((CHARTNS,'connect-bars'), None): cnv_boolean, ((CHARTNS,'data-label-number'), None): cnv_string, ((CHARTNS,'data-label-symbol'), None): cnv_boolean, ((CHARTNS,'data-label-text'), None): cnv_boolean, ((CHARTNS,'data-source-has-labels'), None): cnv_data_source_has_labels, ((CHARTNS,'deep'), None): cnv_boolean, ((CHARTNS,'dimension'), None): cnv_string, ((CHARTNS,'display-label'), None): cnv_boolean, ((CHARTNS,'error-category'), None): cnv_string, ((CHARTNS,'error-lower-indicator'), None): cnv_boolean, ((CHARTNS,'error-lower-limit'), None): cnv_string, ((CHARTNS,'error-margin'), None): cnv_string, ((CHARTNS,'error-percentage'), None): cnv_string, ((CHARTNS,'error-upper-indicator'), None): cnv_boolean, ((CHARTNS,'error-upper-limit'), None): cnv_string, ((CHARTNS,'gap-width'), None): cnv_string, ((CHARTNS,'interpolation'), None): cnv_string, ((CHARTNS,'interval-major'), None): cnv_string, ((CHARTNS,'interval-minor-divisor'), None): cnv_string, ((CHARTNS,'japanese-candle-stick'), None): cnv_boolean, ((CHARTNS,'label-arrangement'), None): cnv_string, ((CHARTNS,'label-cell-address'), None): cnv_string, ((CHARTNS,'legend-align'), None): cnv_string, ((CHARTNS,'legend-position'), None): cnv_legend_position, ((CHARTNS,'lines'), None): cnv_boolean, ((CHARTNS,'link-data-style-to-source'), None): cnv_boolean, ((CHARTNS,'logarithmic'), None): cnv_boolean, ((CHARTNS,'maximum'), None): cnv_string, ((CHARTNS,'mean-value'), None): cnv_boolean, ((CHARTNS,'minimum'), None): cnv_string, ((CHARTNS,'name'), None): cnv_string, ((CHARTNS,'origin'), None): cnv_string, ((CHARTNS,'overlap'), None): cnv_string, ((CHARTNS,'percentage'), None): cnv_boolean, ((CHARTNS,'pie-offset'), None): cnv_string, ((CHARTNS,'regression-type'), None): cnv_string, ((CHARTNS,'repeated'), None): cnv_nonNegativeInteger, ((CHARTNS,'row-mapping'), None): cnv_string, ((CHARTNS,'scale-text'), None): cnv_boolean, ((CHARTNS,'series-source'), None): cnv_string, ((CHARTNS,'solid-type'), None): cnv_string, ((CHARTNS,'spline-order'), None): cnv_string, ((CHARTNS,'spline-resolution'), None): cnv_string, ((CHARTNS,'stacked'), None): cnv_boolean, ((CHARTNS,'style-name'), None): cnv_StyleNameRef, ((CHARTNS,'symbol-height'), None): cnv_string, ((CHARTNS,'symbol-name'), None): cnv_string, ((CHARTNS,'symbol-type'), None): cnv_string, ((CHARTNS,'symbol-width'), None): cnv_string, ((CHARTNS,'text-overlap'), None): cnv_boolean, ((CHARTNS,'three-dimensional'), None): cnv_boolean, ((CHARTNS,'tick-marks-major-inner'), None): cnv_boolean, ((CHARTNS,'tick-marks-major-outer'), None): cnv_boolean, ((CHARTNS,'tick-marks-minor-inner'), None): cnv_boolean, ((CHARTNS,'tick-marks-minor-outer'), None): cnv_boolean, ((CHARTNS,'values-cell-range-address'), None): cnv_string, ((CHARTNS,'vertical'), None): cnv_boolean, ((CHARTNS,'visible'), None): cnv_boolean, ((CONFIGNS,'name'), None): cnv_formula, ((CONFIGNS,'type'), None): cnv_configtype, ((DR3DNS,'ambient-color'), None): cnv_string, ((DR3DNS,'back-scale'), None): cnv_string, ((DR3DNS,'backface-culling'), None): cnv_string, ((DR3DNS,'center'), None): cnv_string, ((DR3DNS,'close-back'), None): cnv_boolean, ((DR3DNS,'close-front'), None): cnv_boolean, ((DR3DNS,'depth'), None): cnv_length, ((DR3DNS,'diffuse-color'), None): cnv_string, ((DR3DNS,'direction'), None): cnv_string, ((DR3DNS,'distance'), None): cnv_length, ((DR3DNS,'edge-rounding'), None): cnv_string, ((DR3DNS,'edge-rounding-mode'), None): cnv_string, ((DR3DNS,'emissive-color'), None): cnv_string, ((DR3DNS,'enabled'), None): cnv_boolean, ((DR3DNS,'end-angle'), None): cnv_string, ((DR3DNS,'focal-length'), None): cnv_length, ((DR3DNS,'horizontal-segments'), None): cnv_string, ((DR3DNS,'lighting-mode'), None): cnv_boolean, ((DR3DNS,'max-edge'), None): cnv_string, ((DR3DNS,'min-edge'), None): cnv_string, ((DR3DNS,'normals-direction'), None): cnv_string, ((DR3DNS,'normals-kind'), None): cnv_string, ((DR3DNS,'projection'), None): cnv_string, ((DR3DNS,'shade-mode'), None): cnv_string, ((DR3DNS,'shadow'), None): cnv_string, ((DR3DNS,'shadow-slant'), None): cnv_nonNegativeInteger, ((DR3DNS,'shininess'), None): cnv_string, ((DR3DNS,'size'), None): cnv_string, ((DR3DNS,'specular'), None): cnv_boolean, ((DR3DNS,'specular-color'), None): cnv_string, ((DR3DNS,'texture-filter'), None): cnv_string, ((DR3DNS,'texture-generation-mode-x'), None): cnv_string, ((DR3DNS,'texture-generation-mode-y'), None): cnv_string, ((DR3DNS,'texture-kind'), None): cnv_string, ((DR3DNS,'texture-mode'), None): cnv_string, ((DR3DNS,'transform'), None): cnv_string, ((DR3DNS,'vertical-segments'), None): cnv_string, ((DR3DNS,'vpn'), None): cnv_string, ((DR3DNS,'vrp'), None): cnv_string, ((DR3DNS,'vup'), None): cnv_string, ((DRAWNS,'align'), None): cnv_string, ((DRAWNS,'angle'), None): cnv_integer, ((DRAWNS,'archive'), None): cnv_string, ((DRAWNS,'auto-grow-height'), None): cnv_boolean, ((DRAWNS,'auto-grow-width'), None): cnv_boolean, ((DRAWNS,'background-size'), None): cnv_string, ((DRAWNS,'blue'), None): cnv_string, ((DRAWNS,'border'), None): cnv_string, ((DRAWNS,'caption-angle'), None): cnv_string, ((DRAWNS,'caption-angle-type'), None): cnv_string, ((DRAWNS,'caption-escape'), None): cnv_string, ((DRAWNS,'caption-escape-direction'), None): cnv_string, ((DRAWNS,'caption-fit-line-length'), None): cnv_boolean, ((DRAWNS,'caption-gap'), None): cnv_string, ((DRAWNS,'caption-line-length'), None): cnv_length, ((DRAWNS,'caption-point-x'), None): cnv_string, ((DRAWNS,'caption-point-y'), None): cnv_string, ((DRAWNS,'caption-id'), None): cnv_IDREF, ((DRAWNS,'caption-type'), None): cnv_string, ((DRAWNS,'chain-next-name'), None): cnv_string, ((DRAWNS,'class-id'), None): cnv_string, ((DRAWNS,'class-names'), None): cnv_NCNames, ((DRAWNS,'code'), None): cnv_string, ((DRAWNS,'color'), None): cnv_string, ((DRAWNS,'color-inversion'), None): cnv_boolean, ((DRAWNS,'color-mode'), None): cnv_string, ((DRAWNS,'concave'), None): cnv_string, ((DRAWNS,'concentric-gradient-fill-allowed'), None): cnv_boolean, ((DRAWNS,'contrast'), None): cnv_string, ((DRAWNS,'control'), None): cnv_IDREF, ((DRAWNS,'copy-of'), None): cnv_string, ((DRAWNS,'corner-radius'), None): cnv_length, ((DRAWNS,'corners'), None): cnv_positiveInteger, ((DRAWNS,'cx'), None): cnv_string, ((DRAWNS,'cy'), None): cnv_string, ((DRAWNS,'data'), None): cnv_string, ((DRAWNS,'decimal-places'), None): cnv_string, ((DRAWNS,'display'), None): cnv_string, ((DRAWNS,'display-name'), None): cnv_string, ((DRAWNS,'distance'), None): cnv_lengthorpercent, ((DRAWNS,'dots1'), None): cnv_integer, ((DRAWNS,'dots1-length'), None): cnv_lengthorpercent, ((DRAWNS,'dots2'), None): cnv_integer, ((DRAWNS,'dots2-length'), None): cnv_lengthorpercent, ((DRAWNS,'end-angle'), None): cnv_double, ((DRAWNS,'end'), None): cnv_string, ((DRAWNS,'end-color'), None): cnv_string, ((DRAWNS,'end-glue-point'), None): cnv_nonNegativeInteger, ((DRAWNS,'end-guide'), None): cnv_length, ((DRAWNS,'end-intensity'), None): cnv_string, ((DRAWNS,'end-line-spacing-horizontal'), None): cnv_string, ((DRAWNS,'end-line-spacing-vertical'), None): cnv_string, ((DRAWNS,'end-shape'), None): cnv_IDREF, ((DRAWNS,'engine'), None): cnv_namespacedToken, ((DRAWNS,'enhanced-path'), None): cnv_string, ((DRAWNS,'escape-direction'), None): cnv_string, ((DRAWNS,'extrusion-allowed'), None): cnv_boolean, ((DRAWNS,'extrusion-brightness'), None): cnv_string, ((DRAWNS,'extrusion'), None): cnv_boolean, ((DRAWNS,'extrusion-color'), None): cnv_boolean, ((DRAWNS,'extrusion-depth'), None): cnv_double, ((DRAWNS,'extrusion-diffusion'), None): cnv_string, ((DRAWNS,'extrusion-first-light-direction'), None): cnv_string, ((DRAWNS,'extrusion-first-light-harsh'), None): cnv_boolean, ((DRAWNS,'extrusion-first-light-level'), None): cnv_string, ((DRAWNS,'extrusion-light-face'), None): cnv_boolean, ((DRAWNS,'extrusion-metal'), None): cnv_boolean, ((DRAWNS,'extrusion-number-of-line-segments'), None): cnv_integer, ((DRAWNS,'extrusion-origin'), None): cnv_double, ((DRAWNS,'extrusion-rotation-angle'), None): cnv_double, ((DRAWNS,'extrusion-rotation-center'), None): cnv_string, ((DRAWNS,'extrusion-second-light-direction'), None): cnv_string, ((DRAWNS,'extrusion-second-light-harsh'), None): cnv_boolean, ((DRAWNS,'extrusion-second-light-level'), None): cnv_string, ((DRAWNS,'extrusion-shininess'), None): cnv_string, ((DRAWNS,'extrusion-skew'), None): cnv_double, ((DRAWNS,'extrusion-specularity'), None): cnv_string, ((DRAWNS,'extrusion-viewpoint'), None): cnv_string, ((DRAWNS,'fill'), None): cnv_string, ((DRAWNS,'fill-color'), None): cnv_string, ((DRAWNS,'fill-gradient-name'), None): cnv_string, ((DRAWNS,'fill-hatch-name'), None): cnv_string, ((DRAWNS,'fill-hatch-solid'), None): cnv_boolean, ((DRAWNS,'fill-image-height'), None): cnv_lengthorpercent, ((DRAWNS,'fill-image-name'), None): cnv_DrawNameRef, ((DRAWNS,'fill-image-ref-point'), None): cnv_string, ((DRAWNS,'fill-image-ref-point-x'), None): cnv_string, ((DRAWNS,'fill-image-ref-point-y'), None): cnv_string, ((DRAWNS,'fill-image-width'), None): cnv_lengthorpercent, ((DRAWNS,'filter-name'), None): cnv_string, ((DRAWNS,'fit-to-contour'), None): cnv_boolean, ((DRAWNS,'fit-to-size'), None): cnv_boolean, ((DRAWNS,'formula'), None): cnv_string, ((DRAWNS,'frame-display-border'), None): cnv_boolean, ((DRAWNS,'frame-display-scrollbar'), None): cnv_boolean, ((DRAWNS,'frame-margin-horizontal'), None): cnv_string, ((DRAWNS,'frame-margin-vertical'), None): cnv_string, ((DRAWNS,'frame-name'), None): cnv_string, ((DRAWNS,'gamma'), None): cnv_string, ((DRAWNS,'glue-point-leaving-directions'), None): cnv_string, ((DRAWNS,'glue-point-type'), None): cnv_string, ((DRAWNS,'glue-points'), None): cnv_string, ((DRAWNS,'gradient-step-count'), None): cnv_string, ((DRAWNS,'green'), None): cnv_string, ((DRAWNS,'guide-distance'), None): cnv_string, ((DRAWNS,'guide-overhang'), None): cnv_length, ((DRAWNS,'handle-mirror-horizontal'), None): cnv_boolean, ((DRAWNS,'handle-mirror-vertical'), None): cnv_boolean, ((DRAWNS,'handle-polar'), None): cnv_string, ((DRAWNS,'handle-position'), None): cnv_string, ((DRAWNS,'handle-radius-range-maximum'), None): cnv_string, ((DRAWNS,'handle-radius-range-minimum'), None): cnv_string, ((DRAWNS,'handle-range-x-maximum'), None): cnv_string, ((DRAWNS,'handle-range-x-minimum'), None): cnv_string, ((DRAWNS,'handle-range-y-maximum'), None): cnv_string, ((DRAWNS,'handle-range-y-minimum'), None): cnv_string, ((DRAWNS,'handle-switched'), None): cnv_boolean, # ((DRAWNS,u'id'), None): cnv_ID, # ((DRAWNS,u'id'), None): cnv_nonNegativeInteger, # ?? line 6581 in RNG ((DRAWNS,'id'), None): cnv_string, ((DRAWNS,'image-opacity'), None): cnv_string, ((DRAWNS,'kind'), None): cnv_string, ((DRAWNS,'layer'), None): cnv_string, ((DRAWNS,'line-distance'), None): cnv_string, ((DRAWNS,'line-skew'), None): cnv_string, ((DRAWNS,'luminance'), None): cnv_string, ((DRAWNS,'marker-end-center'), None): cnv_boolean, ((DRAWNS,'marker-end'), None): cnv_string, ((DRAWNS,'marker-end-width'), None): cnv_length, ((DRAWNS,'marker-start-center'), None): cnv_boolean, ((DRAWNS,'marker-start'), None): cnv_string, ((DRAWNS,'marker-start-width'), None): cnv_length, ((DRAWNS,'master-page-name'), None): cnv_StyleNameRef, ((DRAWNS,'may-script'), None): cnv_boolean, ((DRAWNS,'measure-align'), None): cnv_string, ((DRAWNS,'measure-vertical-align'), None): cnv_string, ((DRAWNS,'mime-type'), None): cnv_string, ((DRAWNS,'mirror-horizontal'), None): cnv_boolean, ((DRAWNS,'mirror-vertical'), None): cnv_boolean, ((DRAWNS,'modifiers'), None): cnv_string, ((DRAWNS,'name'), None): cnv_NCName, # ((DRAWNS,u'name'), None): cnv_string, ((DRAWNS,'nav-order'), None): cnv_IDREF, ((DRAWNS,'nohref'), None): cnv_string, ((DRAWNS,'notify-on-update-of-ranges'), None): cnv_string, ((DRAWNS,'object'), None): cnv_string, ((DRAWNS,'ole-draw-aspect'), None): cnv_string, ((DRAWNS,'opacity'), None): cnv_string, ((DRAWNS,'opacity-name'), None): cnv_string, ((DRAWNS,'page-number'), None): cnv_positiveInteger, ((DRAWNS,'parallel'), None): cnv_boolean, ((DRAWNS,'path-stretchpoint-x'), None): cnv_double, ((DRAWNS,'path-stretchpoint-y'), None): cnv_double, ((DRAWNS,'placing'), None): cnv_string, ((DRAWNS,'points'), None): cnv_points, ((DRAWNS,'protected'), None): cnv_boolean, ((DRAWNS,'recreate-on-edit'), None): cnv_boolean, ((DRAWNS,'red'), None): cnv_string, ((DRAWNS,'rotation'), None): cnv_integer, ((DRAWNS,'secondary-fill-color'), None): cnv_string, ((DRAWNS,'shadow'), None): cnv_string, ((DRAWNS,'shadow-color'), None): cnv_string, ((DRAWNS,'shadow-offset-x'), None): cnv_length, ((DRAWNS,'shadow-offset-y'), None): cnv_length, ((DRAWNS,'shadow-opacity'), None): cnv_string, ((DRAWNS,'shape-id'), None): cnv_IDREF, ((DRAWNS,'sharpness'), None): cnv_string, ((DRAWNS,'show-unit'), None): cnv_boolean, ((DRAWNS,'start-angle'), None): cnv_double, ((DRAWNS,'start'), None): cnv_string, ((DRAWNS,'start-color'), None): cnv_string, ((DRAWNS,'start-glue-point'), None): cnv_nonNegativeInteger, ((DRAWNS,'start-guide'), None): cnv_length, ((DRAWNS,'start-intensity'), None): cnv_string, ((DRAWNS,'start-line-spacing-horizontal'), None): cnv_string, ((DRAWNS,'start-line-spacing-vertical'), None): cnv_string, ((DRAWNS,'start-shape'), None): cnv_IDREF, ((DRAWNS,'stroke'), None): cnv_string, ((DRAWNS,'stroke-dash'), None): cnv_string, ((DRAWNS,'stroke-dash-names'), None): cnv_string, ((DRAWNS,'stroke-linejoin'), None): cnv_string, ((DRAWNS,'style'), None): cnv_string, ((DRAWNS,'style-name'), None): cnv_StyleNameRef, ((DRAWNS,'symbol-color'), None): cnv_string, ((DRAWNS,'text-areas'), None): cnv_string, ((DRAWNS,'text-path-allowed'), None): cnv_boolean, ((DRAWNS,'text-path'), None): cnv_boolean, ((DRAWNS,'text-path-mode'), None): cnv_string, ((DRAWNS,'text-path-same-letter-heights'), None): cnv_boolean, ((DRAWNS,'text-path-scale'), None): cnv_string, ((DRAWNS,'text-rotate-angle'), None): cnv_double, ((DRAWNS,'text-style-name'), None): cnv_StyleNameRef, ((DRAWNS,'textarea-horizontal-align'), None): cnv_string, ((DRAWNS,'textarea-vertical-align'), None): cnv_string, ((DRAWNS,'tile-repeat-offset'), None): cnv_string, ((DRAWNS,'transform'), None): cnv_string, ((DRAWNS,'type'), None): cnv_string, ((DRAWNS,'unit'), None): cnv_string, ((DRAWNS,'value'), None): cnv_string, ((DRAWNS,'visible-area-height'), None): cnv_string, ((DRAWNS,'visible-area-left'), None): cnv_string, ((DRAWNS,'visible-area-top'), None): cnv_string, ((DRAWNS,'visible-area-width'), None): cnv_string, ((DRAWNS,'wrap-influence-on-position'), None): cnv_string, ((DRAWNS,'z-index'), None): cnv_nonNegativeInteger, ((FONS,'background-color'), None): cnv_string, ((FONS,'border-bottom'), None): cnv_string, ((FONS,'border'), None): cnv_string, ((FONS,'border-left'), None): cnv_string, ((FONS,'border-right'), None): cnv_string, ((FONS,'border-top'), None): cnv_string, ((FONS,'break-after'), None): cnv_string, ((FONS,'break-before'), None): cnv_string, ((FONS,'clip'), None): cnv_string, ((FONS,'color'), None): cnv_string, ((FONS,'column-count'), None): cnv_positiveInteger, ((FONS,'column-gap'), None): cnv_length, ((FONS,'country'), None): cnv_token, ((FONS,'end-indent'), None): cnv_length, ((FONS,'font-family'), None): cnv_string, ((FONS,'font-size'), None): cnv_string, ((FONS,'font-style'), None): cnv_string, ((FONS,'font-variant'), None): cnv_string, ((FONS,'font-weight'), None): cnv_string, ((FONS,'height'), None): cnv_string, ((FONS,'hyphenate'), None): cnv_boolean, ((FONS,'hyphenation-keep'), None): cnv_string, ((FONS,'hyphenation-ladder-count'), None): cnv_string, ((FONS,'hyphenation-push-char-count'), None): cnv_string, ((FONS,'hyphenation-remain-char-count'), None): cnv_string, ((FONS,'keep-together'), None): cnv_string, ((FONS,'keep-with-next'), None): cnv_string, ((FONS,'language'), None): cnv_token, ((FONS,'letter-spacing'), None): cnv_string, ((FONS,'line-height'), None): cnv_string, ((FONS,'margin-bottom'), None): cnv_string, ((FONS,'margin'), None): cnv_string, ((FONS,'margin-left'), None): cnv_string, ((FONS,'margin-right'), None): cnv_string, ((FONS,'margin-top'), None): cnv_string, ((FONS,'max-height'), None): cnv_string, ((FONS,'max-width'), None): cnv_string, ((FONS,'min-height'), None): cnv_lengthorpercent, ((FONS,'min-width'), None): cnv_string, ((FONS,'orphans'), None): cnv_string, ((FONS,'padding-bottom'), None): cnv_string, ((FONS,'padding'), None): cnv_string, ((FONS,'padding-left'), None): cnv_string, ((FONS,'padding-right'), None): cnv_string, ((FONS,'padding-top'), None): cnv_string, ((FONS,'page-height'), None): cnv_length, ((FONS,'page-width'), None): cnv_length, ((FONS,'space-after'), None): cnv_length, ((FONS,'space-before'), None): cnv_length, ((FONS,'start-indent'), None): cnv_length, ((FONS,'text-align'), None): cnv_string, ((FONS,'text-align-last'), None): cnv_string, ((FONS,'text-indent'), None): cnv_string, ((FONS,'text-shadow'), None): cnv_string, ((FONS,'text-transform'), None): cnv_string, ((FONS,'widows'), None): cnv_string, ((FONS,'width'), None): cnv_string, ((FONS,'wrap-option'), None): cnv_string, ((FORMNS,'allow-deletes'), None): cnv_boolean, ((FORMNS,'allow-inserts'), None): cnv_boolean, ((FORMNS,'allow-updates'), None): cnv_boolean, ((FORMNS,'apply-design-mode'), None): cnv_boolean, ((FORMNS,'apply-filter'), None): cnv_boolean, ((FORMNS,'auto-complete'), None): cnv_boolean, ((FORMNS,'automatic-focus'), None): cnv_boolean, ((FORMNS,'bound-column'), None): cnv_string, ((FORMNS,'button-type'), None): cnv_string, ((FORMNS,'command'), None): cnv_string, ((FORMNS,'command-type'), None): cnv_string, ((FORMNS,'control-implementation'), None): cnv_namespacedToken, ((FORMNS,'convert-empty-to-null'), None): cnv_boolean, ((FORMNS,'current-selected'), None): cnv_boolean, ((FORMNS,'current-state'), None): cnv_string, # ((FORMNS,u'current-value'), None): cnv_date, # ((FORMNS,u'current-value'), None): cnv_double, ((FORMNS,'current-value'), None): cnv_string, # ((FORMNS,u'current-value'), None): cnv_time, ((FORMNS,'data-field'), None): cnv_string, ((FORMNS,'datasource'), None): cnv_string, ((FORMNS,'default-button'), None): cnv_boolean, ((FORMNS,'delay-for-repeat'), None): cnv_duration, ((FORMNS,'detail-fields'), None): cnv_string, ((FORMNS,'disabled'), None): cnv_boolean, ((FORMNS,'dropdown'), None): cnv_boolean, ((FORMNS,'echo-char'), None): cnv_string, ((FORMNS,'enctype'), None): cnv_string, ((FORMNS,'escape-processing'), None): cnv_boolean, ((FORMNS,'filter'), None): cnv_string, ((FORMNS,'focus-on-click'), None): cnv_boolean, ((FORMNS,'for'), None): cnv_string, ((FORMNS,'id'), None): cnv_ID, ((FORMNS,'ignore-result'), None): cnv_boolean, ((FORMNS,'image-align'), None): cnv_string, ((FORMNS,'image-data'), None): cnv_anyURI, ((FORMNS,'image-position'), None): cnv_string, ((FORMNS,'is-tristate'), None): cnv_boolean, ((FORMNS,'label'), None): cnv_string, ((FORMNS,'list-source'), None): cnv_string, ((FORMNS,'list-source-type'), None): cnv_string, ((FORMNS,'master-fields'), None): cnv_string, ((FORMNS,'max-length'), None): cnv_nonNegativeInteger, # ((FORMNS,u'max-value'), None): cnv_date, # ((FORMNS,u'max-value'), None): cnv_double, ((FORMNS,'max-value'), None): cnv_string, # ((FORMNS,u'max-value'), None): cnv_time, ((FORMNS,'method'), None): cnv_string, # ((FORMNS,u'min-value'), None): cnv_date, # ((FORMNS,u'min-value'), None): cnv_double, ((FORMNS,'min-value'), None): cnv_string, # ((FORMNS,u'min-value'), None): cnv_time, ((FORMNS,'multi-line'), None): cnv_boolean, ((FORMNS,'multiple'), None): cnv_boolean, ((FORMNS,'name'), None): cnv_string, ((FORMNS,'navigation-mode'), None): cnv_string, ((FORMNS,'order'), None): cnv_string, ((FORMNS,'orientation'), None): cnv_string, ((FORMNS,'page-step-size'), None): cnv_positiveInteger, ((FORMNS,'printable'), None): cnv_boolean, ((FORMNS,'property-name'), None): cnv_string, ((FORMNS,'readonly'), None): cnv_boolean, ((FORMNS,'selected'), None): cnv_boolean, ((FORMNS,'size'), None): cnv_nonNegativeInteger, ((FORMNS,'state'), None): cnv_string, ((FORMNS,'step-size'), None): cnv_positiveInteger, ((FORMNS,'tab-cycle'), None): cnv_string, ((FORMNS,'tab-index'), None): cnv_nonNegativeInteger, ((FORMNS,'tab-stop'), None): cnv_boolean, ((FORMNS,'text-style-name'), None): cnv_StyleNameRef, ((FORMNS,'title'), None): cnv_string, ((FORMNS,'toggle'), None): cnv_boolean, ((FORMNS,'validation'), None): cnv_boolean, # ((FORMNS,u'value'), None): cnv_date, # ((FORMNS,u'value'), None): cnv_double, ((FORMNS,'value'), None): cnv_string, # ((FORMNS,u'value'), None): cnv_time, ((FORMNS,'visual-effect'), None): cnv_string, ((FORMNS,'xforms-list-source'), None): cnv_string, ((FORMNS,'xforms-submission'), None): cnv_string, ((MANIFESTNS,'algorithm-name'), None): cnv_string, ((MANIFESTNS,'checksum'), None): cnv_string, ((MANIFESTNS,'checksum-type'), None): cnv_string, ((MANIFESTNS,'full-path'), None): cnv_string, ((MANIFESTNS,'initialisation-vector'), None): cnv_string, ((MANIFESTNS,'iteration-count'), None): cnv_nonNegativeInteger, ((MANIFESTNS,'key-derivation-name'), None): cnv_string, ((MANIFESTNS,'media-type'), None): cnv_string, ((MANIFESTNS,'salt'), None): cnv_string, ((MANIFESTNS,'size'), None): cnv_nonNegativeInteger, ((METANS,'cell-count'), None): cnv_nonNegativeInteger, ((METANS,'character-count'), None): cnv_nonNegativeInteger, ((METANS,'date'), None): cnv_dateTime, ((METANS,'delay'), None): cnv_duration, ((METANS,'draw-count'), None): cnv_nonNegativeInteger, ((METANS,'frame-count'), None): cnv_nonNegativeInteger, ((METANS,'image-count'), None): cnv_nonNegativeInteger, ((METANS,'name'), None): cnv_string, ((METANS,'non-whitespace-character-count'), None): cnv_nonNegativeInteger, ((METANS,'object-count'), None): cnv_nonNegativeInteger, ((METANS,'ole-object-count'), None): cnv_nonNegativeInteger, ((METANS,'page-count'), None): cnv_nonNegativeInteger, ((METANS,'paragraph-count'), None): cnv_nonNegativeInteger, ((METANS,'row-count'), None): cnv_nonNegativeInteger, ((METANS,'sentence-count'), None): cnv_nonNegativeInteger, ((METANS,'syllable-count'), None): cnv_nonNegativeInteger, ((METANS,'table-count'), None): cnv_nonNegativeInteger, ((METANS,'value-type'), None): cnv_metavaluetype, ((METANS,'word-count'), None): cnv_nonNegativeInteger, ((NUMBERNS,'automatic-order'), None): cnv_boolean, ((NUMBERNS,'calendar'), None): cnv_string, ((NUMBERNS,'country'), None): cnv_token, ((NUMBERNS,'decimal-places'), None): cnv_integer, ((NUMBERNS,'decimal-replacement'), None): cnv_string, ((NUMBERNS,'denominator-value'), None): cnv_integer, ((NUMBERNS,'display-factor'), None): cnv_double, ((NUMBERNS,'format-source'), None): cnv_string, ((NUMBERNS,'grouping'), None): cnv_boolean, ((NUMBERNS,'language'), None): cnv_token, ((NUMBERNS,'min-denominator-digits'), None): cnv_integer, ((NUMBERNS,'min-exponent-digits'), None): cnv_integer, ((NUMBERNS,'min-integer-digits'), None): cnv_integer, ((NUMBERNS,'min-numerator-digits'), None): cnv_integer, ((NUMBERNS,'position'), None): cnv_integer, ((NUMBERNS,'possessive-form'), None): cnv_boolean, ((NUMBERNS,'style'), None): cnv_string, ((NUMBERNS,'textual'), None): cnv_boolean, ((NUMBERNS,'title'), None): cnv_string, ((NUMBERNS,'transliteration-country'), None): cnv_token, ((NUMBERNS,'transliteration-format'), None): cnv_string, ((NUMBERNS,'transliteration-language'), None): cnv_token, ((NUMBERNS,'transliteration-style'), None): cnv_string, ((NUMBERNS,'truncate-on-overflow'), None): cnv_boolean, ((OFFICENS,'automatic-update'), None): cnv_boolean, ((OFFICENS,'boolean-value'), None): cnv_boolean, ((OFFICENS,'conversion-mode'), None): cnv_string, ((OFFICENS,'currency'), None): cnv_string, ((OFFICENS,'date-value'), None): cnv_dateTime, ((OFFICENS,'dde-application'), None): cnv_string, ((OFFICENS,'dde-item'), None): cnv_string, ((OFFICENS,'dde-topic'), None): cnv_string, ((OFFICENS,'display'), None): cnv_boolean, ((OFFICENS,'mimetype'), None): cnv_string, ((OFFICENS,'name'), None): cnv_string, ((OFFICENS,'process-content'), None): cnv_boolean, ((OFFICENS,'server-map'), None): cnv_boolean, ((OFFICENS,'string-value'), None): cnv_string, ((OFFICENS,'target-frame'), None): cnv_string, ((OFFICENS,'target-frame-name'), None): cnv_string, ((OFFICENS,'time-value'), None): cnv_duration, ((OFFICENS,'title'), None): cnv_string, ((OFFICENS,'value'), None): cnv_double, ((OFFICENS,'value-type'), None): cnv_string, ((OFFICENS,'version'), None): cnv_string, ((PRESENTATIONNS,'action'), None): cnv_string, ((PRESENTATIONNS,'animations'), None): cnv_string, ((PRESENTATIONNS,'background-objects-visible'), None): cnv_boolean, ((PRESENTATIONNS,'background-visible'), None): cnv_boolean, ((PRESENTATIONNS,'class'), None): cnv_string, ((PRESENTATIONNS,'class-names'), None): cnv_NCNames, ((PRESENTATIONNS,'delay'), None): cnv_duration, ((PRESENTATIONNS,'direction'), None): cnv_string, ((PRESENTATIONNS,'display-date-time'), None): cnv_boolean, ((PRESENTATIONNS,'display-footer'), None): cnv_boolean, ((PRESENTATIONNS,'display-header'), None): cnv_boolean, ((PRESENTATIONNS,'display-page-number'), None): cnv_boolean, ((PRESENTATIONNS,'duration'), None): cnv_string, ((PRESENTATIONNS,'effect'), None): cnv_string, ((PRESENTATIONNS,'endless'), None): cnv_boolean, ((PRESENTATIONNS,'force-manual'), None): cnv_boolean, ((PRESENTATIONNS,'full-screen'), None): cnv_boolean, ((PRESENTATIONNS,'group-id'), None): cnv_string, ((PRESENTATIONNS,'master-element'), None): cnv_IDREF, ((PRESENTATIONNS,'mouse-as-pen'), None): cnv_boolean, ((PRESENTATIONNS,'mouse-visible'), None): cnv_boolean, ((PRESENTATIONNS,'name'), None): cnv_string, ((PRESENTATIONNS,'node-type'), None): cnv_string, ((PRESENTATIONNS,'object'), None): cnv_string, ((PRESENTATIONNS,'pages'), None): cnv_string, ((PRESENTATIONNS,'path-id'), None): cnv_string, ((PRESENTATIONNS,'pause'), None): cnv_duration, ((PRESENTATIONNS,'placeholder'), None): cnv_boolean, ((PRESENTATIONNS,'play-full'), None): cnv_boolean, ((PRESENTATIONNS,'presentation-page-layout-name'), None): cnv_StyleNameRef, ((PRESENTATIONNS,'preset-class'), None): cnv_string, ((PRESENTATIONNS,'preset-id'), None): cnv_string, ((PRESENTATIONNS,'preset-sub-type'), None): cnv_string, ((PRESENTATIONNS,'show'), None): cnv_string, ((PRESENTATIONNS,'show-end-of-presentation-slide'), None): cnv_boolean, ((PRESENTATIONNS,'show-logo'), None): cnv_boolean, ((PRESENTATIONNS,'source'), None): cnv_string, ((PRESENTATIONNS,'speed'), None): cnv_string, ((PRESENTATIONNS,'start-page'), None): cnv_string, ((PRESENTATIONNS,'start-scale'), None): cnv_string, ((PRESENTATIONNS,'start-with-navigator'), None): cnv_boolean, ((PRESENTATIONNS,'stay-on-top'), None): cnv_boolean, ((PRESENTATIONNS,'style-name'), None): cnv_StyleNameRef, ((PRESENTATIONNS,'transition-on-click'), None): cnv_string, ((PRESENTATIONNS,'transition-speed'), None): cnv_string, ((PRESENTATIONNS,'transition-style'), None): cnv_string, ((PRESENTATIONNS,'transition-type'), None): cnv_string, ((PRESENTATIONNS,'use-date-time-name'), None): cnv_string, ((PRESENTATIONNS,'use-footer-name'), None): cnv_string, ((PRESENTATIONNS,'use-header-name'), None): cnv_string, ((PRESENTATIONNS,'user-transformed'), None): cnv_boolean, ((PRESENTATIONNS,'verb'), None): cnv_nonNegativeInteger, ((PRESENTATIONNS,'visibility'), None): cnv_string, ((SCRIPTNS,'event-name'), None): cnv_formula, ((SCRIPTNS,'language'), None): cnv_formula, ((SCRIPTNS,'macro-name'), None): cnv_string, ((SMILNS,'accelerate'), None): cnv_double, ((SMILNS,'accumulate'), None): cnv_string, ((SMILNS,'additive'), None): cnv_string, ((SMILNS,'attributeName'), None): cnv_string, ((SMILNS,'autoReverse'), None): cnv_boolean, ((SMILNS,'begin'), None): cnv_string, ((SMILNS,'by'), None): cnv_string, ((SMILNS,'calcMode'), None): cnv_string, ((SMILNS,'decelerate'), None): cnv_double, ((SMILNS,'direction'), None): cnv_string, ((SMILNS,'dur'), None): cnv_string, ((SMILNS,'end'), None): cnv_string, ((SMILNS,'endsync'), None): cnv_string, ((SMILNS,'fadeColor'), None): cnv_string, ((SMILNS,'fill'), None): cnv_string, ((SMILNS,'fillDefault'), None): cnv_string, ((SMILNS,'from'), None): cnv_string, ((SMILNS,'keySplines'), None): cnv_string, ((SMILNS,'keyTimes'), None): cnv_string, ((SMILNS,'mode'), None): cnv_string, ((SMILNS,'repeatCount'), None): cnv_nonNegativeInteger, ((SMILNS,'repeatDur'), None): cnv_string, ((SMILNS,'restart'), None): cnv_string, ((SMILNS,'restartDefault'), None): cnv_string, ((SMILNS,'subtype'), None): cnv_string, ((SMILNS,'targetElement'), None): cnv_IDREF, ((SMILNS,'to'), None): cnv_string, ((SMILNS,'type'), None): cnv_string, ((SMILNS,'values'), None): cnv_string, ((STYLENS,'adjustment'), None): cnv_string, ((STYLENS,'apply-style-name'), None): cnv_StyleNameRef, ((STYLENS,'auto-text-indent'), None): cnv_boolean, ((STYLENS,'auto-update'), None): cnv_boolean, ((STYLENS,'background-transparency'), None): cnv_string, ((STYLENS,'base-cell-address'), None): cnv_string, ((STYLENS,'border-line-width-bottom'), None): cnv_string, ((STYLENS,'border-line-width'), None): cnv_string, ((STYLENS,'border-line-width-left'), None): cnv_string, ((STYLENS,'border-line-width-right'), None): cnv_string, ((STYLENS,'border-line-width-top'), None): cnv_string, ((STYLENS,'cell-protect'), None): cnv_string, ((STYLENS,'char'), None): cnv_string, ((STYLENS,'class'), None): cnv_string, ((STYLENS,'color'), None): cnv_string, ((STYLENS,'column-width'), None): cnv_string, ((STYLENS,'condition'), None): cnv_string, ((STYLENS,'country-asian'), None): cnv_string, ((STYLENS,'country-complex'), None): cnv_string, ((STYLENS,'data-style-name'), None): cnv_StyleNameRef, ((STYLENS,'decimal-places'), None): cnv_string, ((STYLENS,'default-outline-level'), None): cnv_positiveInteger, ((STYLENS,'diagonal-bl-tr'), None): cnv_string, ((STYLENS,'diagonal-bl-tr-widths'), None): cnv_string, ((STYLENS,'diagonal-tl-br'), None): cnv_string, ((STYLENS,'diagonal-tl-br-widths'), None): cnv_string, ((STYLENS,'direction'), None): cnv_string, ((STYLENS,'display'), None): cnv_boolean, ((STYLENS,'display-name'), None): cnv_string, ((STYLENS,'distance-after-sep'), None): cnv_length, ((STYLENS,'distance-before-sep'), None): cnv_length, ((STYLENS,'distance'), None): cnv_length, ((STYLENS,'dynamic-spacing'), None): cnv_boolean, ((STYLENS,'editable'), None): cnv_boolean, ((STYLENS,'family'), None): cnv_family, ((STYLENS,'filter-name'), None): cnv_string, ((STYLENS,'first-page-number'), None): cnv_string, ((STYLENS,'flow-with-text'), None): cnv_boolean, ((STYLENS,'font-adornments'), None): cnv_string, ((STYLENS,'font-charset'), None): cnv_string, ((STYLENS,'font-charset-asian'), None): cnv_string, ((STYLENS,'font-charset-complex'), None): cnv_string, ((STYLENS,'font-family-asian'), None): cnv_string, ((STYLENS,'font-family-complex'), None): cnv_string, ((STYLENS,'font-family-generic-asian'), None): cnv_string, ((STYLENS,'font-family-generic'), None): cnv_string, ((STYLENS,'font-family-generic-complex'), None): cnv_string, ((STYLENS,'font-independent-line-spacing'), None): cnv_boolean, ((STYLENS,'font-name-asian'), None): cnv_string, ((STYLENS,'font-name'), None): cnv_string, ((STYLENS,'font-name-complex'), None): cnv_string, ((STYLENS,'font-pitch-asian'), None): cnv_string, ((STYLENS,'font-pitch'), None): cnv_string, ((STYLENS,'font-pitch-complex'), None): cnv_string, ((STYLENS,'font-relief'), None): cnv_string, ((STYLENS,'font-size-asian'), None): cnv_string, ((STYLENS,'font-size-complex'), None): cnv_string, ((STYLENS,'font-size-rel-asian'), None): cnv_length, ((STYLENS,'font-size-rel'), None): cnv_length, ((STYLENS,'font-size-rel-complex'), None): cnv_length, ((STYLENS,'font-style-asian'), None): cnv_string, ((STYLENS,'font-style-complex'), None): cnv_string, ((STYLENS,'font-style-name-asian'), None): cnv_string, ((STYLENS,'font-style-name'), None): cnv_string, ((STYLENS,'font-style-name-complex'), None): cnv_string, ((STYLENS,'font-weight-asian'), None): cnv_string, ((STYLENS,'font-weight-complex'), None): cnv_string, ((STYLENS,'footnote-max-height'), None): cnv_length, ((STYLENS,'glyph-orientation-vertical'), None): cnv_string, ((STYLENS,'height'), None): cnv_string, ((STYLENS,'horizontal-pos'), None): cnv_string, ((STYLENS,'horizontal-rel'), None): cnv_string, ((STYLENS,'justify-single-word'), None): cnv_boolean, ((STYLENS,'language-asian'), None): cnv_string, ((STYLENS,'language-complex'), None): cnv_string, ((STYLENS,'layout-grid-base-height'), None): cnv_length, ((STYLENS,'layout-grid-color'), None): cnv_string, ((STYLENS,'layout-grid-display'), None): cnv_boolean, ((STYLENS,'layout-grid-lines'), None): cnv_string, ((STYLENS,'layout-grid-mode'), None): cnv_string, ((STYLENS,'layout-grid-print'), None): cnv_boolean, ((STYLENS,'layout-grid-ruby-below'), None): cnv_boolean, ((STYLENS,'layout-grid-ruby-height'), None): cnv_length, ((STYLENS,'leader-char'), None): cnv_string, ((STYLENS,'leader-color'), None): cnv_string, ((STYLENS,'leader-style'), None): cnv_string, ((STYLENS,'leader-text'), None): cnv_string, ((STYLENS,'leader-text-style'), None): cnv_StyleNameRef, ((STYLENS,'leader-type'), None): cnv_string, ((STYLENS,'leader-width'), None): cnv_string, ((STYLENS,'legend-expansion-aspect-ratio'), None): cnv_double, ((STYLENS,'legend-expansion'), None): cnv_string, ((STYLENS,'length'), None): cnv_positiveInteger, ((STYLENS,'letter-kerning'), None): cnv_boolean, ((STYLENS,'line-break'), None): cnv_string, ((STYLENS,'line-height-at-least'), None): cnv_string, ((STYLENS,'line-spacing'), None): cnv_length, ((STYLENS,'line-style'), None): cnv_string, ((STYLENS,'lines'), None): cnv_positiveInteger, ((STYLENS,'list-style-name'), None): cnv_StyleNameRef, ((STYLENS,'master-page-name'), None): cnv_StyleNameRef, ((STYLENS,'may-break-between-rows'), None): cnv_boolean, ((STYLENS,'min-row-height'), None): cnv_string, ((STYLENS,'mirror'), None): cnv_string, ((STYLENS,'name'), None): cnv_NCName, ((STYLENS,'name'), (STYLENS,'font-face')): cnv_string, ((STYLENS,'next-style-name'), None): cnv_StyleNameRef, ((STYLENS,'num-format'), None): cnv_string, ((STYLENS,'num-letter-sync'), None): cnv_boolean, ((STYLENS,'num-prefix'), None): cnv_string, ((STYLENS,'num-suffix'), None): cnv_string, ((STYLENS,'number-wrapped-paragraphs'), None): cnv_string, ((STYLENS,'overflow-behavior'), None): cnv_string, ((STYLENS,'page-layout-name'), None): cnv_StyleNameRef, ((STYLENS,'page-number'), None): cnv_string, ((STYLENS,'page-usage'), None): cnv_string, ((STYLENS,'paper-tray-name'), None): cnv_string, ((STYLENS,'parent-style-name'), None): cnv_StyleNameRef, ((STYLENS,'position'), (STYLENS,'tab-stop')): cnv_length, ((STYLENS,'position'), None): cnv_string, ((STYLENS,'print'), None): cnv_string, ((STYLENS,'print-content'), None): cnv_boolean, ((STYLENS,'print-orientation'), None): cnv_string, ((STYLENS,'print-page-order'), None): cnv_string, ((STYLENS,'protect'), None): cnv_boolean, ((STYLENS,'punctuation-wrap'), None): cnv_string, ((STYLENS,'register-true'), None): cnv_boolean, ((STYLENS,'register-truth-ref-style-name'), None): cnv_string, ((STYLENS,'rel-column-width'), None): cnv_string, ((STYLENS,'rel-height'), None): cnv_string, ((STYLENS,'rel-width'), None): cnv_string, ((STYLENS,'repeat'), None): cnv_string, ((STYLENS,'repeat-content'), None): cnv_boolean, ((STYLENS,'rotation-align'), None): cnv_string, ((STYLENS,'rotation-angle'), None): cnv_string, ((STYLENS,'row-height'), None): cnv_string, ((STYLENS,'ruby-align'), None): cnv_string, ((STYLENS,'ruby-position'), None): cnv_string, ((STYLENS,'run-through'), None): cnv_string, ((STYLENS,'scale-to'), None): cnv_string, ((STYLENS,'scale-to-pages'), None): cnv_string, ((STYLENS,'script-type'), None): cnv_string, ((STYLENS,'shadow'), None): cnv_string, ((STYLENS,'shrink-to-fit'), None): cnv_boolean, ((STYLENS,'snap-to-layout-grid'), None): cnv_boolean, ((STYLENS,'style'), None): cnv_string, ((STYLENS,'style-name'), None): cnv_StyleNameRef, ((STYLENS,'tab-stop-distance'), None): cnv_string, ((STYLENS,'table-centering'), None): cnv_string, ((STYLENS,'text-align-source'), None): cnv_string, ((STYLENS,'text-autospace'), None): cnv_string, ((STYLENS,'text-blinking'), None): cnv_boolean, ((STYLENS,'text-combine'), None): cnv_string, ((STYLENS,'text-combine-end-char'), None): cnv_string, ((STYLENS,'text-combine-start-char'), None): cnv_string, ((STYLENS,'text-emphasize'), None): cnv_string, ((STYLENS,'text-line-through-color'), None): cnv_string, ((STYLENS,'text-line-through-mode'), None): cnv_string, ((STYLENS,'text-line-through-style'), None): cnv_string, ((STYLENS,'text-line-through-text'), None): cnv_string, ((STYLENS,'text-line-through-text-style'), None): cnv_string, ((STYLENS,'text-line-through-type'), None): cnv_string, ((STYLENS,'text-line-through-width'), None): cnv_string, ((STYLENS,'text-outline'), None): cnv_boolean, ((STYLENS,'text-position'), None): cnv_string, ((STYLENS,'text-rotation-angle'), None): cnv_string, ((STYLENS,'text-rotation-scale'), None): cnv_string, ((STYLENS,'text-scale'), None): cnv_string, ((STYLENS,'text-underline-color'), None): cnv_string, ((STYLENS,'text-underline-mode'), None): cnv_string, ((STYLENS,'text-underline-style'), None): cnv_string, ((STYLENS,'text-underline-type'), None): cnv_string, ((STYLENS,'text-underline-width'), None): cnv_string, ((STYLENS,'type'), None): cnv_string, ((STYLENS,'use-optimal-column-width'), None): cnv_boolean, ((STYLENS,'use-optimal-row-height'), None): cnv_boolean, ((STYLENS,'use-window-font-color'), None): cnv_boolean, ((STYLENS,'vertical-align'), None): cnv_string, ((STYLENS,'vertical-pos'), None): cnv_string, ((STYLENS,'vertical-rel'), None): cnv_string, ((STYLENS,'volatile'), None): cnv_boolean, ((STYLENS,'width'), None): cnv_string, ((STYLENS,'wrap'), None): cnv_string, ((STYLENS,'wrap-contour'), None): cnv_boolean, ((STYLENS,'wrap-contour-mode'), None): cnv_string, ((STYLENS,'wrap-dynamic-threshold'), None): cnv_length, ((STYLENS,'writing-mode-automatic'), None): cnv_boolean, ((STYLENS,'writing-mode'), None): cnv_string, ((SVGNS,'accent-height'), None): cnv_integer, ((SVGNS,'alphabetic'), None): cnv_integer, ((SVGNS,'ascent'), None): cnv_integer, ((SVGNS,'bbox'), None): cnv_string, ((SVGNS,'cap-height'), None): cnv_integer, ((SVGNS,'cx'), None): cnv_string, ((SVGNS,'cy'), None): cnv_string, ((SVGNS,'d'), None): cnv_string, ((SVGNS,'descent'), None): cnv_integer, ((SVGNS,'fill-rule'), None): cnv_string, ((SVGNS,'font-family'), None): cnv_string, ((SVGNS,'font-size'), None): cnv_string, ((SVGNS,'font-stretch'), None): cnv_string, ((SVGNS,'font-style'), None): cnv_string, ((SVGNS,'font-variant'), None): cnv_string, ((SVGNS,'font-weight'), None): cnv_string, ((SVGNS,'fx'), None): cnv_string, ((SVGNS,'fy'), None): cnv_string, ((SVGNS,'gradientTransform'), None): cnv_string, ((SVGNS,'gradientUnits'), None): cnv_string, ((SVGNS,'hanging'), None): cnv_integer, ((SVGNS,'height'), None): cnv_length, ((SVGNS,'ideographic'), None): cnv_integer, ((SVGNS,'mathematical'), None): cnv_integer, ((SVGNS,'name'), None): cnv_string, ((SVGNS,'offset'), None): cnv_string, ((SVGNS,'origin'), None): cnv_string, ((SVGNS,'overline-position'), None): cnv_integer, ((SVGNS,'overline-thickness'), None): cnv_integer, ((SVGNS,'panose-1'), None): cnv_string, ((SVGNS,'path'), None): cnv_string, ((SVGNS,'r'), None): cnv_length, ((SVGNS,'rx'), None): cnv_length, ((SVGNS,'ry'), None): cnv_length, ((SVGNS,'slope'), None): cnv_integer, ((SVGNS,'spreadMethod'), None): cnv_string, ((SVGNS,'stemh'), None): cnv_integer, ((SVGNS,'stemv'), None): cnv_integer, ((SVGNS,'stop-color'), None): cnv_string, ((SVGNS,'stop-opacity'), None): cnv_double, ((SVGNS,'strikethrough-position'), None): cnv_integer, ((SVGNS,'strikethrough-thickness'), None): cnv_integer, ((SVGNS,'string'), None): cnv_string, ((SVGNS,'stroke-color'), None): cnv_string, ((SVGNS,'stroke-opacity'), None): cnv_string, ((SVGNS,'stroke-width'), None): cnv_length, ((SVGNS,'type'), None): cnv_string, ((SVGNS,'underline-position'), None): cnv_integer, ((SVGNS,'underline-thickness'), None): cnv_integer, ((SVGNS,'unicode-range'), None): cnv_string, ((SVGNS,'units-per-em'), None): cnv_integer, ((SVGNS,'v-alphabetic'), None): cnv_integer, ((SVGNS,'v-hanging'), None): cnv_integer, ((SVGNS,'v-ideographic'), None): cnv_integer, ((SVGNS,'v-mathematical'), None): cnv_integer, ((SVGNS,'viewBox'), None): cnv_viewbox, ((SVGNS,'width'), None): cnv_length, ((SVGNS,'widths'), None): cnv_string, ((SVGNS,'x'), None): cnv_length, ((SVGNS,'x-height'), None): cnv_integer, ((SVGNS,'x1'), None): cnv_lengthorpercent, ((SVGNS,'x2'), None): cnv_lengthorpercent, ((SVGNS,'y'), None): cnv_length, ((SVGNS,'y1'), None): cnv_lengthorpercent, ((SVGNS,'y2'), None): cnv_lengthorpercent, ((TABLENS,'acceptance-state'), None): cnv_string, ((TABLENS,'add-empty-lines'), None): cnv_boolean, ((TABLENS,'algorithm'), None): cnv_formula, ((TABLENS,'align'), None): cnv_string, ((TABLENS,'allow-empty-cell'), None): cnv_boolean, ((TABLENS,'application-data'), None): cnv_string, ((TABLENS,'automatic-find-labels'), None): cnv_boolean, ((TABLENS,'base-cell-address'), None): cnv_string, ((TABLENS,'bind-styles-to-content'), None): cnv_boolean, ((TABLENS,'border-color'), None): cnv_string, ((TABLENS,'border-model'), None): cnv_string, ((TABLENS,'buttons'), None): cnv_string, # ((TABLENS,u'case-sensitive'), None): cnv_boolean, ((TABLENS,'case-sensitive'), None): cnv_string, ((TABLENS,'cell-address'), None): cnv_string, ((TABLENS,'cell-range-address'), None): cnv_string, ((TABLENS,'cell-range'), None): cnv_string, ((TABLENS,'column'), None): cnv_integer, ((TABLENS,'comment'), None): cnv_string, ((TABLENS,'condition'), None): cnv_formula, ((TABLENS,'condition-source'), None): cnv_string, ((TABLENS,'condition-source-range-address'), None): cnv_string, ((TABLENS,'contains-error'), None): cnv_boolean, ((TABLENS,'contains-header'), None): cnv_boolean, ((TABLENS,'content-validation-name'), None): cnv_string, ((TABLENS,'copy-back'), None): cnv_boolean, ((TABLENS,'copy-formulas'), None): cnv_boolean, ((TABLENS,'copy-styles'), None): cnv_boolean, ((TABLENS,'count'), None): cnv_positiveInteger, ((TABLENS,'country'), None): cnv_token, ((TABLENS,'data-cell-range-address'), None): cnv_string, ((TABLENS,'data-field'), None): cnv_string, ((TABLENS,'data-type'), None): cnv_string, ((TABLENS,'database-name'), None): cnv_string, ((TABLENS,'database-table-name'), None): cnv_string, ((TABLENS,'date-end'), None): cnv_string, ((TABLENS,'date-start'), None): cnv_string, ((TABLENS,'date-value'), None): cnv_date, ((TABLENS,'default-cell-style-name'), None): cnv_StyleNameRef, ((TABLENS,'direction'), None): cnv_string, ((TABLENS,'display-border'), None): cnv_boolean, ((TABLENS,'display'), None): cnv_boolean, ((TABLENS,'display-duplicates'), None): cnv_boolean, ((TABLENS,'display-filter-buttons'), None): cnv_boolean, ((TABLENS,'display-list'), None): cnv_string, ((TABLENS,'display-member-mode'), None): cnv_string, ((TABLENS,'drill-down-on-double-click'), None): cnv_boolean, ((TABLENS,'enabled'), None): cnv_boolean, ((TABLENS,'end-cell-address'), None): cnv_string, ((TABLENS,'end'), None): cnv_string, ((TABLENS,'end-column'), None): cnv_integer, ((TABLENS,'end-position'), None): cnv_integer, ((TABLENS,'end-row'), None): cnv_integer, ((TABLENS,'end-table'), None): cnv_integer, ((TABLENS,'end-x'), None): cnv_length, ((TABLENS,'end-y'), None): cnv_length, ((TABLENS,'execute'), None): cnv_boolean, ((TABLENS,'expression'), None): cnv_formula, ((TABLENS,'field-name'), None): cnv_string, # ((TABLENS,u'field-number'), None): cnv_nonNegativeInteger, ((TABLENS,'field-number'), None): cnv_string, ((TABLENS,'filter-name'), None): cnv_string, ((TABLENS,'filter-options'), None): cnv_string, ((TABLENS,'formula'), None): cnv_formula, ((TABLENS,'function'), None): cnv_string, ((TABLENS,'grand-total'), None): cnv_string, ((TABLENS,'group-by-field-number'), None): cnv_nonNegativeInteger, ((TABLENS,'grouped-by'), None): cnv_string, ((TABLENS,'has-persistent-data'), None): cnv_boolean, ((TABLENS,'id'), None): cnv_string, ((TABLENS,'identify-categories'), None): cnv_boolean, ((TABLENS,'ignore-empty-rows'), None): cnv_boolean, ((TABLENS,'index'), None): cnv_nonNegativeInteger, ((TABLENS,'is-active'), None): cnv_boolean, ((TABLENS,'is-data-layout-field'), None): cnv_string, ((TABLENS,'is-selection'), None): cnv_boolean, ((TABLENS,'is-sub-table'), None): cnv_boolean, ((TABLENS,'label-cell-range-address'), None): cnv_string, ((TABLENS,'language'), None): cnv_token, ((TABLENS,'last-column-spanned'), None): cnv_positiveInteger, ((TABLENS,'last-row-spanned'), None): cnv_positiveInteger, ((TABLENS,'layout-mode'), None): cnv_string, ((TABLENS,'link-to-source-data'), None): cnv_boolean, ((TABLENS,'marked-invalid'), None): cnv_boolean, ((TABLENS,'matrix-covered'), None): cnv_boolean, ((TABLENS,'maximum-difference'), None): cnv_double, ((TABLENS,'member-count'), None): cnv_nonNegativeInteger, ((TABLENS,'member-name'), None): cnv_string, ((TABLENS,'member-type'), None): cnv_string, ((TABLENS,'message-type'), None): cnv_string, ((TABLENS,'mode'), None): cnv_string, ((TABLENS,'multi-deletion-spanned'), None): cnv_integer, ((TABLENS,'name'), None): cnv_string, ((TABLENS,'null-year'), None): cnv_positiveInteger, ((TABLENS,'number-columns-repeated'), None): cnv_positiveInteger, ((TABLENS,'number-columns-spanned'), None): cnv_positiveInteger, ((TABLENS,'number-matrix-columns-spanned'), None): cnv_positiveInteger, ((TABLENS,'number-matrix-rows-spanned'), None): cnv_positiveInteger, ((TABLENS,'number-rows-repeated'), None): cnv_positiveInteger, ((TABLENS,'number-rows-spanned'), None): cnv_positiveInteger, ((TABLENS,'object-name'), None): cnv_string, ((TABLENS,'on-update-keep-size'), None): cnv_boolean, ((TABLENS,'on-update-keep-styles'), None): cnv_boolean, ((TABLENS,'operator'), None): cnv_string, ((TABLENS,'order'), None): cnv_string, ((TABLENS,'orientation'), None): cnv_string, ((TABLENS,'page-breaks-on-group-change'), None): cnv_boolean, ((TABLENS,'parse-sql-statement'), None): cnv_boolean, ((TABLENS,'password'), None): cnv_string, ((TABLENS,'position'), None): cnv_integer, ((TABLENS,'precision-as-shown'), None): cnv_boolean, ((TABLENS,'print'), None): cnv_boolean, ((TABLENS,'print-ranges'), None): cnv_string, ((TABLENS,'protect'), None): cnv_boolean, ((TABLENS,'protected'), None): cnv_boolean, ((TABLENS,'protection-key'), None): cnv_string, ((TABLENS,'query-name'), None): cnv_string, ((TABLENS,'range-usable-as'), None): cnv_string, # ((TABLENS,u'refresh-delay'), None): cnv_boolean, ((TABLENS,'refresh-delay'), None): cnv_duration, ((TABLENS,'rejecting-change-id'), None): cnv_string, ((TABLENS,'row'), None): cnv_integer, ((TABLENS,'scenario-ranges'), None): cnv_string, ((TABLENS,'search-criteria-must-apply-to-whole-cell'), None): cnv_boolean, ((TABLENS,'selected-page'), None): cnv_string, ((TABLENS,'show-details'), None): cnv_boolean, # ((TABLENS,u'show-empty'), None): cnv_boolean, ((TABLENS,'show-empty'), None): cnv_string, ((TABLENS,'show-filter-button'), None): cnv_boolean, ((TABLENS,'sort-mode'), None): cnv_string, ((TABLENS,'source-cell-range-addresses'), None): cnv_string, ((TABLENS,'source-field-name'), None): cnv_string, ((TABLENS,'source-name'), None): cnv_string, ((TABLENS,'sql-statement'), None): cnv_string, ((TABLENS,'start'), None): cnv_string, ((TABLENS,'start-column'), None): cnv_integer, ((TABLENS,'start-position'), None): cnv_integer, ((TABLENS,'start-row'), None): cnv_integer, ((TABLENS,'start-table'), None): cnv_integer, ((TABLENS,'status'), None): cnv_string, ((TABLENS,'step'), None): cnv_double, ((TABLENS,'steps'), None): cnv_positiveInteger, ((TABLENS,'structure-protected'), None): cnv_boolean, ((TABLENS,'style-name'), None): cnv_StyleNameRef, ((TABLENS,'table-background'), None): cnv_boolean, ((TABLENS,'table'), None): cnv_integer, ((TABLENS,'table-name'), None): cnv_string, ((TABLENS,'target-cell-address'), None): cnv_string, ((TABLENS,'target-range-address'), None): cnv_string, ((TABLENS,'title'), None): cnv_string, ((TABLENS,'track-changes'), None): cnv_boolean, ((TABLENS,'type'), None): cnv_string, ((TABLENS,'use-labels'), None): cnv_string, ((TABLENS,'use-regular-expressions'), None): cnv_boolean, ((TABLENS,'used-hierarchy'), None): cnv_integer, ((TABLENS,'user-name'), None): cnv_string, ((TABLENS,'value'), None): cnv_string, ((TABLENS,'value-type'), None): cnv_string, ((TABLENS,'visibility'), None): cnv_string, ((TEXTNS,'active'), None): cnv_boolean, ((TEXTNS,'address'), None): cnv_string, ((TEXTNS,'alphabetical-separators'), None): cnv_boolean, ((TEXTNS,'anchor-page-number'), None): cnv_positiveInteger, ((TEXTNS,'anchor-type'), None): cnv_string, ((TEXTNS,'animation'), None): cnv_string, ((TEXTNS,'animation-delay'), None): cnv_string, ((TEXTNS,'animation-direction'), None): cnv_string, ((TEXTNS,'animation-repeat'), None): cnv_string, ((TEXTNS,'animation-start-inside'), None): cnv_boolean, ((TEXTNS,'animation-steps'), None): cnv_length, ((TEXTNS,'animation-stop-inside'), None): cnv_boolean, ((TEXTNS,'annote'), None): cnv_string, ((TEXTNS,'author'), None): cnv_string, ((TEXTNS,'bibliography-data-field'), None): cnv_string, ((TEXTNS,'bibliography-type'), None): cnv_string, ((TEXTNS,'booktitle'), None): cnv_string, ((TEXTNS,'bullet-char'), None): cnv_string, ((TEXTNS,'bullet-relative-size'), None): cnv_string, ((TEXTNS,'c'), None): cnv_nonNegativeInteger, ((TEXTNS,'capitalize-entries'), None): cnv_boolean, ((TEXTNS,'caption-sequence-format'), None): cnv_string, ((TEXTNS,'caption-sequence-name'), None): cnv_string, ((TEXTNS,'change-id'), None): cnv_IDREF, ((TEXTNS,'chapter'), None): cnv_string, ((TEXTNS,'citation-body-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'citation-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'class-names'), None): cnv_NCNames, ((TEXTNS,'column-name'), None): cnv_string, ((TEXTNS,'combine-entries'), None): cnv_boolean, ((TEXTNS,'combine-entries-with-dash'), None): cnv_boolean, ((TEXTNS,'combine-entries-with-pp'), None): cnv_boolean, ((TEXTNS,'comma-separated'), None): cnv_boolean, ((TEXTNS,'cond-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'condition'), None): cnv_formula, ((TEXTNS,'connection-name'), None): cnv_string, ((TEXTNS,'consecutive-numbering'), None): cnv_boolean, ((TEXTNS,'continue-numbering'), None): cnv_boolean, ((TEXTNS,'copy-outline-levels'), None): cnv_boolean, ((TEXTNS,'count-empty-lines'), None): cnv_boolean, ((TEXTNS,'count-in-text-boxes'), None): cnv_boolean, ((TEXTNS,'current-value'), None): cnv_boolean, ((TEXTNS,'custom1'), None): cnv_string, ((TEXTNS,'custom2'), None): cnv_string, ((TEXTNS,'custom3'), None): cnv_string, ((TEXTNS,'custom4'), None): cnv_string, ((TEXTNS,'custom5'), None): cnv_string, ((TEXTNS,'database-name'), None): cnv_string, ((TEXTNS,'date-adjust'), None): cnv_duration, ((TEXTNS,'date-value'), None): cnv_date, # ((TEXTNS,u'date-value'), None): cnv_dateTime, ((TEXTNS,'default-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'description'), None): cnv_string, ((TEXTNS,'display'), None): cnv_string, ((TEXTNS,'display-levels'), None): cnv_positiveInteger, ((TEXTNS,'display-outline-level'), None): cnv_nonNegativeInteger, ((TEXTNS,'dont-balance-text-columns'), None): cnv_boolean, ((TEXTNS,'duration'), None): cnv_duration, ((TEXTNS,'edition'), None): cnv_string, ((TEXTNS,'editor'), None): cnv_string, ((TEXTNS,'filter-name'), None): cnv_string, ((TEXTNS,'first-row-end-column'), None): cnv_string, ((TEXTNS,'first-row-start-column'), None): cnv_string, ((TEXTNS,'fixed'), None): cnv_boolean, ((TEXTNS,'footnotes-position'), None): cnv_string, ((TEXTNS,'formula'), None): cnv_formula, ((TEXTNS,'global'), None): cnv_boolean, ((TEXTNS,'howpublished'), None): cnv_string, ((TEXTNS,'id'), None): cnv_ID, # ((TEXTNS,u'id'), None): cnv_string, ((TEXTNS,'identifier'), None): cnv_string, ((TEXTNS,'ignore-case'), None): cnv_boolean, ((TEXTNS,'increment'), None): cnv_nonNegativeInteger, ((TEXTNS,'index-name'), None): cnv_string, ((TEXTNS,'index-scope'), None): cnv_string, ((TEXTNS,'institution'), None): cnv_string, ((TEXTNS,'is-hidden'), None): cnv_boolean, ((TEXTNS,'is-list-header'), None): cnv_boolean, ((TEXTNS,'isbn'), None): cnv_string, ((TEXTNS,'issn'), None): cnv_string, ((TEXTNS,'journal'), None): cnv_string, ((TEXTNS,'key'), None): cnv_string, ((TEXTNS,'key1'), None): cnv_string, ((TEXTNS,'key1-phonetic'), None): cnv_string, ((TEXTNS,'key2'), None): cnv_string, ((TEXTNS,'key2-phonetic'), None): cnv_string, ((TEXTNS,'kind'), None): cnv_string, ((TEXTNS,'label'), None): cnv_string, ((TEXTNS,'last-row-end-column'), None): cnv_string, ((TEXTNS,'last-row-start-column'), None): cnv_string, ((TEXTNS,'level'), None): cnv_positiveInteger, ((TEXTNS,'line-break'), None): cnv_boolean, ((TEXTNS,'line-number'), None): cnv_string, ((TEXTNS,'main-entry'), None): cnv_boolean, ((TEXTNS,'main-entry-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'master-page-name'), None): cnv_StyleNameRef, ((TEXTNS,'min-label-distance'), None): cnv_string, ((TEXTNS,'min-label-width'), None): cnv_string, ((TEXTNS,'month'), None): cnv_string, ((TEXTNS,'name'), None): cnv_string, ((TEXTNS,'note-class'), None): cnv_textnoteclass, ((TEXTNS,'note'), None): cnv_string, ((TEXTNS,'number'), None): cnv_string, ((TEXTNS,'number-lines'), None): cnv_boolean, ((TEXTNS,'number-position'), None): cnv_string, ((TEXTNS,'numbered-entries'), None): cnv_boolean, ((TEXTNS,'offset'), None): cnv_string, ((TEXTNS,'organizations'), None): cnv_string, ((TEXTNS,'outline-level'), None): cnv_string, ((TEXTNS,'page-adjust'), None): cnv_integer, ((TEXTNS,'pages'), None): cnv_string, ((TEXTNS,'paragraph-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'placeholder-type'), None): cnv_string, ((TEXTNS,'prefix'), None): cnv_string, ((TEXTNS,'protected'), None): cnv_boolean, ((TEXTNS,'protection-key'), None): cnv_string, ((TEXTNS,'publisher'), None): cnv_string, ((TEXTNS,'ref-name'), None): cnv_string, ((TEXTNS,'reference-format'), None): cnv_string, ((TEXTNS,'relative-tab-stop-position'), None): cnv_boolean, ((TEXTNS,'report-type'), None): cnv_string, ((TEXTNS,'restart-numbering'), None): cnv_boolean, ((TEXTNS,'restart-on-page'), None): cnv_boolean, ((TEXTNS,'row-number'), None): cnv_nonNegativeInteger, ((TEXTNS,'school'), None): cnv_string, ((TEXTNS,'section-name'), None): cnv_string, ((TEXTNS,'select-page'), None): cnv_string, ((TEXTNS,'separation-character'), None): cnv_string, ((TEXTNS,'series'), None): cnv_string, ((TEXTNS,'sort-algorithm'), None): cnv_string, ((TEXTNS,'sort-ascending'), None): cnv_boolean, ((TEXTNS,'sort-by-position'), None): cnv_boolean, ((TEXTNS,'space-before'), None): cnv_string, ((TEXTNS,'start-numbering-at'), None): cnv_string, # ((TEXTNS,u'start-value'), None): cnv_nonNegativeInteger, ((TEXTNS,'start-value'), None): cnv_positiveInteger, ((TEXTNS,'string-value'), None): cnv_string, ((TEXTNS,'string-value-if-false'), None): cnv_string, ((TEXTNS,'string-value-if-true'), None): cnv_string, ((TEXTNS,'string-value-phonetic'), None): cnv_string, ((TEXTNS,'style-name'), None): cnv_StyleNameRef, ((TEXTNS,'suffix'), None): cnv_string, ((TEXTNS,'tab-ref'), None): cnv_nonNegativeInteger, ((TEXTNS,'table-name'), None): cnv_string, ((TEXTNS,'table-type'), None): cnv_string, ((TEXTNS,'time-adjust'), None): cnv_duration, # ((TEXTNS,u'time-value'), None): cnv_dateTime, ((TEXTNS,'time-value'), None): cnv_time, ((TEXTNS,'title'), None): cnv_string, ((TEXTNS,'track-changes'), None): cnv_boolean, ((TEXTNS,'url'), None): cnv_string, ((TEXTNS,'use-caption'), None): cnv_boolean, ((TEXTNS,'use-chart-objects'), None): cnv_boolean, ((TEXTNS,'use-draw-objects'), None): cnv_boolean, ((TEXTNS,'use-floating-frames'), None): cnv_boolean, ((TEXTNS,'use-graphics'), None): cnv_boolean, ((TEXTNS,'use-index-marks'), None): cnv_boolean, ((TEXTNS,'use-index-source-styles'), None): cnv_boolean, ((TEXTNS,'use-keys-as-entries'), None): cnv_boolean, ((TEXTNS,'use-math-objects'), None): cnv_boolean, ((TEXTNS,'use-objects'), None): cnv_boolean, ((TEXTNS,'use-other-objects'), None): cnv_boolean, ((TEXTNS,'use-outline-level'), None): cnv_boolean, ((TEXTNS,'use-soft-page-breaks'), None): cnv_boolean, ((TEXTNS,'use-spreadsheet-objects'), None): cnv_boolean, ((TEXTNS,'use-tables'), None): cnv_boolean, ((TEXTNS,'value'), None): cnv_nonNegativeInteger, ((TEXTNS,'visited-style-name'), None): cnv_StyleNameRef, ((TEXTNS,'volume'), None): cnv_string, ((TEXTNS,'year'), None): cnv_string, ((XFORMSNS,'bind'), None): cnv_string, ((XLINKNS,'actuate'), None): cnv_string, ((XLINKNS,'href'), None): cnv_anyURI, ((XLINKNS,'show'), None): cnv_xlinkshow, ((XLINKNS,'title'), None): cnv_string, ((XLINKNS,'type'), None): cnv_string, } class AttrConverters: def convert(self, attribute, value, element): """ Based on the element, figures out how to check/convert the attribute value All values are converted to string """ conversion = attrconverters.get((attribute, element.qname), None) if conversion is not None: return conversion(attribute, value, element) else: conversion = attrconverters.get((attribute, None), None) if conversion is not None: return conversion(attribute, value, element) return str(value)
76,759
Python
.py
1,449
44.615597
124
0.603415
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,417
anim.py
kovidgoyal_calibre/src/odf/anim.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import ANIMNS # Autogenerated def Animate(**args): return Element(qname=(ANIMNS,'animate'), **args) def Animatecolor(**args): return Element(qname=(ANIMNS,'animateColor'), **args) def Animatemotion(**args): return Element(qname=(ANIMNS,'animateMotion'), **args) def Animatetransform(**args): return Element(qname=(ANIMNS,'animateTransform'), **args) def Audio(**args): return Element(qname=(ANIMNS,'audio'), **args) def Command(**args): return Element(qname=(ANIMNS,'command'), **args) def Iterate(**args): return Element(qname=(ANIMNS,'iterate'), **args) def Par(**args): return Element(qname=(ANIMNS,'par'), **args) def Param(**args): return Element(qname=(ANIMNS,'param'), **args) def Seq(**args): return Element(qname=(ANIMNS,'seq'), **args) def Set(**args): return Element(qname=(ANIMNS,'set'), **args) def Transitionfilter(**args): return Element(qname=(ANIMNS,'transitionFilter'), **args)
1,835
Python
.py
45
38.133333
80
0.738662
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,418
office.py
kovidgoyal_calibre/src/odf/office.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .draw import StyleRefElement from .element import Element from .namespaces import OFFICENS # Autogenerated def Annotation(**args): return StyleRefElement(qname=(OFFICENS,'annotation'), **args) def AutomaticStyles(**args): return Element(qname=(OFFICENS, 'automatic-styles'), **args) def BinaryData(**args): return Element(qname=(OFFICENS,'binary-data'), **args) def Body(**args): return Element(qname=(OFFICENS, 'body'), **args) def ChangeInfo(**args): return Element(qname=(OFFICENS,'change-info'), **args) def Chart(**args): return Element(qname=(OFFICENS,'chart'), **args) def DdeSource(**args): return Element(qname=(OFFICENS,'dde-source'), **args) def Document(version="1.1", **args): return Element(qname=(OFFICENS,'document'), version=version, **args) def DocumentContent(version="1.1", **args): return Element(qname=(OFFICENS, 'document-content'), version=version, **args) def DocumentMeta(version="1.1", **args): return Element(qname=(OFFICENS, 'document-meta'), version=version, **args) def DocumentSettings(version="1.1", **args): return Element(qname=(OFFICENS, 'document-settings'), version=version, **args) def DocumentStyles(version="1.1", **args): return Element(qname=(OFFICENS, 'document-styles'), version=version, **args) def Drawing(**args): return Element(qname=(OFFICENS,'drawing'), **args) def EventListeners(**args): return Element(qname=(OFFICENS,'event-listeners'), **args) def FontFaceDecls(**args): return Element(qname=(OFFICENS, 'font-face-decls'), **args) def Forms(**args): return Element(qname=(OFFICENS,'forms'), **args) def Image(**args): return Element(qname=(OFFICENS,'image'), **args) def MasterStyles(**args): return Element(qname=(OFFICENS, 'master-styles'), **args) def Meta(**args): return Element(qname=(OFFICENS, 'meta'), **args) def Presentation(**args): return Element(qname=(OFFICENS,'presentation'), **args) def Script(**args): return Element(qname=(OFFICENS, 'script'), **args) def Scripts(**args): return Element(qname=(OFFICENS, 'scripts'), **args) def Settings(**args): return Element(qname=(OFFICENS, 'settings'), **args) def Spreadsheet(**args): return Element(qname=(OFFICENS, 'spreadsheet'), **args) def Styles(**args): return Element(qname=(OFFICENS, 'styles'), **args) def Text(**args): return Element(qname=(OFFICENS, 'text'), **args) # Autogenerated end
3,298
Python
.py
75
40.84
82
0.727818
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,419
draw.py
kovidgoyal_calibre/src/odf/draw.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import DRAWNS, PRESENTATIONNS, STYLENS def StyleRefElement(stylename=None, classnames=None, **args): qattrs = {} if stylename is not None: f = stylename.getAttrNS(STYLENS, 'family') if f == 'graphic': qattrs[(DRAWNS,'style-name')]= stylename elif f == 'presentation': qattrs[(PRESENTATIONNS,'style-name')]= stylename else: raise ValueError("Style's family must be either 'graphic' or 'presentation'") if classnames is not None: f = classnames[0].getAttrNS(STYLENS, 'family') if f == 'graphic': qattrs[(DRAWNS,'class-names')]= classnames elif f == 'presentation': qattrs[(PRESENTATIONNS,'class-names')]= classnames else: raise ValueError("Style's family must be either 'graphic' or 'presentation'") return Element(qattributes=qattrs, **args) def DrawElement(name=None, **args): e = Element(name=name, **args) if 'displayname' not in args: e.setAttrNS(DRAWNS,'display-name', name) return e # Autogenerated def A(**args): return Element(qname=(DRAWNS,'a'), **args) def Applet(**args): return Element(qname=(DRAWNS,'applet'), **args) def AreaCircle(**args): return Element(qname=(DRAWNS,'area-circle'), **args) def AreaPolygon(**args): return Element(qname=(DRAWNS,'area-polygon'), **args) def AreaRectangle(**args): return Element(qname=(DRAWNS,'area-rectangle'), **args) def Caption(**args): return StyleRefElement(qname=(DRAWNS,'caption'), **args) def Circle(**args): return StyleRefElement(qname=(DRAWNS,'circle'), **args) def Connector(**args): return StyleRefElement(qname=(DRAWNS,'connector'), **args) def ContourPath(**args): return Element(qname=(DRAWNS,'contour-path'), **args) def ContourPolygon(**args): return Element(qname=(DRAWNS,'contour-polygon'), **args) def Control(**args): return StyleRefElement(qname=(DRAWNS,'control'), **args) def CustomShape(**args): return StyleRefElement(qname=(DRAWNS,'custom-shape'), **args) def Ellipse(**args): return StyleRefElement(qname=(DRAWNS,'ellipse'), **args) def EnhancedGeometry(**args): return Element(qname=(DRAWNS,'enhanced-geometry'), **args) def Equation(**args): return Element(qname=(DRAWNS,'equation'), **args) def FillImage(**args): return DrawElement(qname=(DRAWNS,'fill-image'), **args) def FloatingFrame(**args): return Element(qname=(DRAWNS,'floating-frame'), **args) def Frame(**args): return StyleRefElement(qname=(DRAWNS,'frame'), **args) def G(**args): return StyleRefElement(qname=(DRAWNS,'g'), **args) def GluePoint(**args): return Element(qname=(DRAWNS,'glue-point'), **args) def Gradient(**args): return DrawElement(qname=(DRAWNS,'gradient'), **args) def Handle(**args): return Element(qname=(DRAWNS,'handle'), **args) def Hatch(**args): return DrawElement(qname=(DRAWNS,'hatch'), **args) def Image(**args): return Element(qname=(DRAWNS,'image'), **args) def ImageMap(**args): return Element(qname=(DRAWNS,'image-map'), **args) def Layer(**args): return Element(qname=(DRAWNS,'layer'), **args) def LayerSet(**args): return Element(qname=(DRAWNS,'layer-set'), **args) def Line(**args): return StyleRefElement(qname=(DRAWNS,'line'), **args) def Marker(**args): return DrawElement(qname=(DRAWNS,'marker'), **args) def Measure(**args): return StyleRefElement(qname=(DRAWNS,'measure'), **args) def Object(**args): return Element(qname=(DRAWNS,'object'), **args) def ObjectOle(**args): return Element(qname=(DRAWNS,'object-ole'), **args) def Opacity(**args): return DrawElement(qname=(DRAWNS,'opacity'), **args) def Page(**args): return Element(qname=(DRAWNS,'page'), **args) def PageThumbnail(**args): return StyleRefElement(qname=(DRAWNS,'page-thumbnail'), **args) def Param(**args): return Element(qname=(DRAWNS,'param'), **args) def Path(**args): return StyleRefElement(qname=(DRAWNS,'path'), **args) def Plugin(**args): return Element(qname=(DRAWNS,'plugin'), **args) def Polygon(**args): return StyleRefElement(qname=(DRAWNS,'polygon'), **args) def Polyline(**args): return StyleRefElement(qname=(DRAWNS,'polyline'), **args) def Rect(**args): return StyleRefElement(qname=(DRAWNS,'rect'), **args) def RegularPolygon(**args): return StyleRefElement(qname=(DRAWNS,'regular-polygon'), **args) def StrokeDash(**args): return DrawElement(qname=(DRAWNS,'stroke-dash'), **args) def TextBox(**args): return Element(qname=(DRAWNS,'text-box'), **args)
5,525
Python
.py
133
37.210526
89
0.699641
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,420
element.py
kovidgoyal_calibre/src/odf/element.py
#!/usr/bin/env python # Copyright (C) 2007-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # Note: This script has copied a lot of text from xml.dom.minidom. # Whatever license applies to that file also applies to this file. # import xml.dom from xml.dom.minicompat import EmptyNodeList, defproperty from polyglot.builtins import unicode_type from . import grammar from .attrconverters import AttrConverters from .namespaces import nsdict # The following code is pasted form xml.sax.saxutils # Tt makes it possible to run the code without the xml sax package installed # To make it possible to have <rubbish> in your text elements, it is necessary to escape the texts def _escape(data, entities={}): """ Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ data = data.replace("&", "&amp;") data = data.replace("<", "&lt;") data = data.replace(">", "&gt;") for chars, entity in entities.items(): data = data.replace(chars, entity) return data def _quoteattr(data, entities={}): """ Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The \" character will be escaped as well, if necessary. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ entities['\n']='&#10;' entities['\r']='&#12;' data = _escape(data, entities) if '"' in data: if "'" in data: data = '"%s"' % data.replace('"', "&quot;") else: data = "'%s'" % data else: data = '"%s"' % data return data def _nssplit(qualifiedName): """ Split a qualified name into namespace part and local part. """ fields = qualifiedName.split(':', 1) if len(fields) == 2: return fields else: return (None, fields[0]) def _nsassign(namespace): return nsdict.setdefault(namespace,"ns" + unicode_type(len(nsdict))) # Exceptions class IllegalChild(Exception): """ Complains if you add an element to a parent where it is not allowed """ class IllegalText(Exception): """ Complains if you add text or cdata to an element where it is not allowed """ class Node(xml.dom.Node): """ super class for more specific nodes """ parentNode = None nextSibling = None previousSibling = None def hasChildNodes(self): """ Tells whether this element has any children; text nodes, subelements, whatever. """ if self.childNodes: return True else: return False def _get_childNodes(self): return self.childNodes def _get_firstChild(self): if self.childNodes: return self.childNodes[0] def _get_lastChild(self): if self.childNodes: return self.childNodes[-1] def insertBefore(self, newChild, refChild): """ Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. """ if newChild.nodeType not in self._child_node_types: raise IllegalChild(f"{newChild.tagName} cannot be child of {self.tagName}") if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: try: index = self.childNodes.index(refChild) except ValueError: raise xml.dom.NotFoundErr() self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None newChild.parentNode = self return newChild def appendChild(self, newChild): """ Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed. """ if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(newChild.childNodes): self.appendChild(c) # The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: raise IllegalChild(f"<{newChild.tagName}> is not allowed in {self.tagName}") if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) _append_child(self, newChild) newChild.nextSibling = None return newChild def removeChild(self, oldChild): """ Removes the child node indicated by oldChild from the list of children, and returns it. """ # FIXME: update ownerDocument.element_dict or find other solution try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if self.ownerDocument: self.ownerDocument.clear_caches() oldChild.parentNode = None return oldChild def __unicode__(self): val = [] for c in self.childNodes: val.append(str(c)) return ''.join(val) __str__ = __unicode__ defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes if childNodes: last = childNodes[-1] node.__dict__["previousSibling"] = last last.__dict__["nextSibling"] = node childNodes.append(node) node.__dict__["parentNode"] = self class Childless: """ Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ attributes = None childNodes = EmptyNodeList() firstChild = None lastChild = None def _get_firstChild(self): return None def _get_lastChild(self): return None def appendChild(self, node): """ Raises an error """ raise xml.dom.HierarchyRequestErr( self.tagName + " nodes cannot have children") def hasChildNodes(self): return False def insertBefore(self, newChild, refChild): """ Raises an error """ raise xml.dom.HierarchyRequestErr( self.tagName + " nodes do not have children") def removeChild(self, oldChild): """ Raises an error """ raise xml.dom.NotFoundErr( self.tagName + " nodes do not have children") def replaceChild(self, newChild, oldChild): """ Raises an error """ raise xml.dom.HierarchyRequestErr( self.tagName + " nodes do not have children") class Text(Childless, Node): nodeType = Node.TEXT_NODE tagName = "Text" def __init__(self, data): self.data = data def __str__(self): return self.data __unicode__ = __str__ def toXml(self,level,f): """ Write XML in UTF-8 """ if self.data: f.write(_escape(str(self.data).encode('utf-8'))) class CDATASection(Text, Childless): nodeType = Node.CDATA_SECTION_NODE def toXml(self,level,f): """ Generate XML output of the node. If the text contains "]]>", then escape it by going out of CDATA mode (]]>), then write the string and then go into CDATA mode again. (<![CDATA[) """ if self.data: f.write('<![CDATA[%s]]>' % self.data.replace(']]>',']]>]]><![CDATA[')) class Element(Node): """ Creates a arbitrary element and is intended to be subclassed not used on its own. This element is the base of every element it defines a class which resembles a xml-element. The main advantage of this kind of implementation is that you don't have to create a toXML method for every different object. Every element consists of an attribute, optional subelements, optional text and optional cdata. """ nodeType = Node.ELEMENT_NODE namespaces = {} # Due to shallow copy this is a static variable _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, attributes=None, text=None, cdata=None, qname=None, qattributes=None, check_grammar=True, **args): if qname is not None: self.qname = qname assert(hasattr(self, 'qname')) self.ownerDocument = None self.childNodes=[] self.allowed_children = grammar.allowed_children.get(self.qname) prefix = self.get_nsprefix(self.qname[0]) self.tagName = prefix + ":" + self.qname[1] if text is not None: self.addText(text) if cdata is not None: self.addCDATA(cdata) allowed_attrs = self.allowed_attributes() self.attributes={} # Load the attributes from the 'attributes' argument if attributes: for attr, value in attributes.items(): self.setAttribute(attr, value) # Load the qualified attributes if qattributes: for attr, value in qattributes.items(): self.setAttrNS(attr[0], attr[1], value) if allowed_attrs is not None: # Load the attributes from the 'args' argument for arg in args.keys(): self.setAttribute(arg, args[arg]) else: for arg in args.keys(): # If any attribute is allowed self.attributes[arg]=args[arg] if not check_grammar: return # Test that all mandatory attributes have been added. required = grammar.required_attributes.get(self.qname) if required: for r in required: if self.getAttrNS(r[0],r[1]) is None: raise AttributeError("Required attribute missing: {} in <{}>".format(r[1].lower().replace('-',''), self.tagName)) def get_knownns(self, prefix): """ Odfpy maintains a list of known namespaces. In some cases a prefix is used, and we need to know which namespace it resolves to. """ global nsdict for ns,p in nsdict.items(): if p == prefix: return ns return None def get_nsprefix(self, namespace): """ Odfpy maintains a list of known namespaces. In some cases we have a namespace URL, and needs to look up or assign the prefix for it. """ if namespace is None: namespace = "" prefix = _nsassign(namespace) if namespace not in self.namespaces: self.namespaces[namespace] = prefix return prefix def allowed_attributes(self): return grammar.allowed_attributes.get(self.qname) def _setOwnerDoc(self, element): element.ownerDocument = self.ownerDocument for child in element.childNodes: self._setOwnerDoc(child) def addElement(self, element, check_grammar=True): """ adds an element to an Element Element.addElement(Element) """ if check_grammar and self.allowed_children is not None: if element.qname not in self.allowed_children: raise IllegalChild(f"<{element.tagName}> is not allowed in <{self.tagName}>") self.appendChild(element) self._setOwnerDoc(element) if self.ownerDocument: self.ownerDocument.rebuild_caches(element) def addText(self, text, check_grammar=True): """ Adds text to an element Setting check_grammar=False turns off grammar checking """ if check_grammar and self.qname not in grammar.allows_text: raise IllegalText("The <%s> element does not allow text" % self.tagName) else: if text != '': self.appendChild(Text(text)) def addCDATA(self, cdata, check_grammar=True): """ Adds CDATA to an element Setting check_grammar=False turns off grammar checking """ if check_grammar and self.qname not in grammar.allows_text: raise IllegalText("The <%s> element does not allow text" % self.tagName) else: self.appendChild(CDATASection(cdata)) def removeAttribute(self, attr, check_grammar=True): """ Removes an attribute by name. """ allowed_attrs = self.allowed_attributes() if allowed_attrs is None: if isinstance(attr, tuple): prefix, localname = attr self.removeAttrNS(prefix, localname) else: raise AttributeError("Unable to add simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [a[1].lower().replace('-','') for a in allowed_attrs] if check_grammar and attr not in allowed_args: raise AttributeError(f"Attribute {attr} is not allowed in <{self.tagName}>") i = allowed_args.index(attr) self.removeAttrNS(allowed_attrs[i][0], allowed_attrs[i][1]) def setAttribute(self, attr, value, check_grammar=True): """ Add an attribute to the element This is sort of a convenience method. All attributes in ODF have namespaces. The library knows what attributes are legal and then allows the user to provide the attribute as a keyword argument and the library will add the correct namespace. Must overwrite, If attribute already exists. """ allowed_attrs = self.allowed_attributes() if allowed_attrs is None: if isinstance(attr, tuple): prefix, localname = attr self.setAttrNS(prefix, localname, value) else: raise AttributeError("Unable to add simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [a[1].lower().replace('-','') for a in allowed_attrs] if check_grammar and attr not in allowed_args: raise AttributeError(f"Attribute {attr} is not allowed in <{self.tagName}>") i = allowed_args.index(attr) self.setAttrNS(allowed_attrs[i][0], allowed_attrs[i][1], value) def setAttrNS(self, namespace, localpart, value): """ Add an attribute to the element In case you need to add an attribute the library doesn't know about then you must provide the full qualified name It will not check that the attribute is legal according to the schema. Must overwrite, If attribute already exists. """ c = AttrConverters() self.attributes[(namespace, localpart)] = c.convert((namespace, localpart), value, self) def getAttrNS(self, namespace, localpart): return self.attributes.get((namespace, localpart)) def removeAttrNS(self, namespace, localpart): del self.attributes[(namespace, localpart)] def getAttribute(self, attr): """ Get an attribute value. The method knows which namespace the attribute is in """ allowed_attrs = self.allowed_attributes() if allowed_attrs is None: if isinstance(attr, tuple): prefix, localname = attr return self.getAttrNS(prefix, localname) else: raise AttributeError("Unable to get simple attribute - use (namespace, localpart)") else: # Construct a list of allowed arguments allowed_args = [a[1].lower().replace('-','') for a in allowed_attrs] i = allowed_args.index(attr) return self.getAttrNS(allowed_attrs[i][0], allowed_attrs[i][1]) def write_open_tag(self, level, f): f.write('<'+self.tagName) if level == 0: for namespace, prefix in self.namespaces.items(): f.write(' xmlns:' + prefix + '="'+ _escape(unicode_type(namespace))+'"') for qname in self.attributes.keys(): prefix = self.get_nsprefix(qname[0]) f.write(' '+_escape(unicode_type(prefix+':'+qname[1]))+'='+_quoteattr(str(self.attributes[qname]).encode('utf-8'))) f.write('>') def write_close_tag(self, level, f): f.write('</'+self.tagName+'>') def toXml(self, level, f): """ Generate XML stream out of the tree structure """ f.write('<'+self.tagName) if level == 0: for namespace, prefix in self.namespaces.items(): f.write(' xmlns:' + prefix + '="'+ _escape(unicode_type(namespace))+'"') for qname in self.attributes.keys(): prefix = self.get_nsprefix(qname[0]) f.write(' '+_escape(unicode_type(prefix+':'+qname[1]))+'='+_quoteattr(str(self.attributes[qname]).encode('utf-8'))) if self.childNodes: f.write('>') for element in self.childNodes: element.toXml(level+1,f) f.write('</'+self.tagName+'>') else: f.write('/>') def _getElementsByObj(self, obj, accumulator): if self.qname == obj.qname: accumulator.append(self) for e in self.childNodes: if e.nodeType == Node.ELEMENT_NODE: accumulator = e._getElementsByObj(obj, accumulator) return accumulator def getElementsByType(self, element): """ Gets elements based on the type, which is function from text.py, draw.py etc. """ obj = element(check_grammar=False) return self._getElementsByObj(obj,[]) def isInstanceOf(self, element): """ This is a check to see if the object is an instance of a type """ obj = element(check_grammar=False) return self.qname == obj.qname
19,721
Python
.py
439
35.640091
133
0.628131
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,421
elementtypes.py
kovidgoyal_calibre/src/odf/elementtypes.py
#!/usr/bin/env python # Copyright (C) 2008 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .namespaces import ( ANIMNS, CHARTNS, DR3DNS, DRAWNS, FORMNS, MANIFESTNS, METANS, NUMBERNS, OFFICENS, PRESENTATIONNS, SCRIPTNS, STYLENS, SVGNS, TABLENS, TEXTNS, ) # Inline element don't cause a box # They are analogous to the HTML elements SPAN, B, I etc. inline_elements = ( (TEXTNS,'a'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark-ref'), (TEXTNS,'chapter'), (TEXTNS,'character-count'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'image-count'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note-ref'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-count'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'paragraph-count'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'printed-by'), (TEXTNS,'print-time'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'ruby-base'), (TEXTNS,'ruby-text'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'table-count'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), (TEXTNS,'word-count'), ) # It is almost impossible to determine what elements are block elements. # There are so many that don't fit the form block_elements = ( (TEXTNS,'h'), (TEXTNS,'p'), (TEXTNS,'list'), (TEXTNS,'list-item'), (TEXTNS,'section'), ) declarative_elements = ( (OFFICENS,'font-face-decls'), (PRESENTATIONNS,'date-time-decl'), (PRESENTATIONNS,'footer-decl'), (PRESENTATIONNS,'header-decl'), (TABLENS,'table-template'), (TEXTNS,'alphabetical-index-entry-template'), (TEXTNS,'alphabetical-index-source'), (TEXTNS,'bibliography-entry-template'), (TEXTNS,'bibliography-source'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'illustration-index-entry-template'), (TEXTNS,'illustration-index-source'), (TEXTNS,'index-source-styles'), (TEXTNS,'index-title-template'), (TEXTNS,'note-continuation-notice-backward'), (TEXTNS,'note-continuation-notice-forward'), (TEXTNS,'notes-configuration'), (TEXTNS,'object-index-entry-template'), (TEXTNS,'object-index-source'), (TEXTNS,'sequence-decls'), (TEXTNS,'table-index-entry-template'), (TEXTNS,'table-index-source'), (TEXTNS,'table-of-content-entry-template'), (TEXTNS,'table-of-content-source'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index-entry-template'), (TEXTNS,'user-index-source'), (TEXTNS,'variable-decls'), ) empty_elements = ( (ANIMNS,'animate'), (ANIMNS,'animateColor'), (ANIMNS,'animateMotion'), (ANIMNS,'animateTransform'), (ANIMNS,'audio'), (ANIMNS,'param'), (ANIMNS,'set'), (ANIMNS,'transitionFilter'), (CHARTNS,'categories'), (CHARTNS,'data-point'), (CHARTNS,'domain'), (CHARTNS,'error-indicator'), (CHARTNS,'floor'), (CHARTNS,'grid'), (CHARTNS,'legend'), (CHARTNS,'mean-value'), (CHARTNS,'regression-curve'), (CHARTNS,'stock-gain-marker'), (CHARTNS,'stock-loss-marker'), (CHARTNS,'stock-range-line'), (CHARTNS,'symbol-image'), (CHARTNS,'wall'), (DR3DNS,'cube'), (DR3DNS,'extrude'), (DR3DNS,'light'), (DR3DNS,'rotate'), (DR3DNS,'sphere'), (DRAWNS,'contour-path'), (DRAWNS,'contour-polygon'), (DRAWNS,'equation'), (DRAWNS,'fill-image'), (DRAWNS,'floating-frame'), (DRAWNS,'glue-point'), (DRAWNS,'gradient'), (DRAWNS,'handle'), (DRAWNS,'hatch'), (DRAWNS,'layer'), (DRAWNS,'marker'), (DRAWNS,'opacity'), (DRAWNS,'page-thumbnail'), (DRAWNS,'param'), (DRAWNS,'stroke-dash'), (FORMNS,'connection-resource'), (FORMNS,'list-value'), (FORMNS,'property'), (MANIFESTNS,'algorithm'), (MANIFESTNS,'key-derivation'), (METANS,'auto-reload'), (METANS,'document-statistic'), (METANS,'hyperlink-behaviour'), (METANS,'template'), (NUMBERNS,'am-pm'), (NUMBERNS,'boolean'), (NUMBERNS,'day'), (NUMBERNS,'day-of-week'), (NUMBERNS,'era'), (NUMBERNS,'fraction'), (NUMBERNS,'hours'), (NUMBERNS,'minutes'), (NUMBERNS,'month'), (NUMBERNS,'quarter'), (NUMBERNS,'scientific-number'), (NUMBERNS,'seconds'), (NUMBERNS,'text-content'), (NUMBERNS,'week-of-year'), (NUMBERNS,'year'), (OFFICENS,'dde-source'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (PRESENTATIONNS,'placeholder'), (PRESENTATIONNS,'play'), (PRESENTATIONNS,'show'), (PRESENTATIONNS,'sound'), (SCRIPTNS,'event-listener'), (STYLENS,'column'), (STYLENS,'column-sep'), (STYLENS,'drop-cap'), (STYLENS,'footnote-sep'), (STYLENS,'list-level-properties'), (STYLENS,'map'), (STYLENS,'ruby-properties'), (STYLENS,'table-column-properties'), (STYLENS,'tab-stop'), (STYLENS,'text-properties'), (SVGNS,'definition-src'), (SVGNS,'font-face-format'), (SVGNS,'font-face-name'), (SVGNS,'stop'), (TABLENS,'body'), (TABLENS,'cell-address'), (TABLENS,'cell-range-source'), (TABLENS,'change-deletion'), (TABLENS,'consolidation'), (TABLENS,'database-source-query'), (TABLENS,'database-source-sql'), (TABLENS,'database-source-table'), (TABLENS,'data-pilot-display-info'), (TABLENS,'data-pilot-field-reference'), (TABLENS,'data-pilot-group-member'), (TABLENS,'data-pilot-layout-info'), (TABLENS,'data-pilot-member'), (TABLENS,'data-pilot-sort-info'), (TABLENS,'data-pilot-subtotal'), (TABLENS,'dependency'), (TABLENS,'error-macro'), (TABLENS,'even-columns'), (TABLENS,'even-rows'), (TABLENS,'filter-condition'), (TABLENS,'first-column'), (TABLENS,'first-row'), (TABLENS,'highlighted-range'), (TABLENS,'insertion-cut-off'), (TABLENS,'iteration'), (TABLENS,'label-range'), (TABLENS,'last-column'), (TABLENS,'last-row'), (TABLENS,'movement-cut-off'), (TABLENS,'named-expression'), (TABLENS,'named-range'), (TABLENS,'null-date'), (TABLENS,'odd-columns'), (TABLENS,'odd-rows'), (TABLENS,'operation'), (TABLENS,'scenario'), (TABLENS,'sort-by'), (TABLENS,'sort-groups'), (TABLENS,'source-range-address'), (TABLENS,'source-service'), (TABLENS,'subtotal-field'), (TABLENS,'table-column'), (TABLENS,'table-source'), (TABLENS,'target-range-address'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decl'), (TEXTNS,'index-entry-bibliography'), (TEXTNS,'index-entry-chapter'), (TEXTNS,'index-entry-link-end'), (TEXTNS,'index-entry-link-start'), (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), (TEXTNS,'index-source-style'), (TEXTNS,'line-break'), (TEXTNS,'page'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'s'), (TEXTNS,'section-source'), (TEXTNS,'sequence-decl'), (TEXTNS,'soft-page-break'), (TEXTNS,'sort-key'), (TEXTNS,'tab'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-field-decl'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-decl') )
10,116
Python
.py
334
25.661677
80
0.641944
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,422
text.py
kovidgoyal_calibre/src/odf/text.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import TEXTNS from .style import StyleElement # Autogenerated def A(**args): return Element(qname=(TEXTNS,'a'), **args) def AlphabeticalIndex(**args): return Element(qname=(TEXTNS,'alphabetical-index'), **args) def AlphabeticalIndexAutoMarkFile(**args): return Element(qname=(TEXTNS,'alphabetical-index-auto-mark-file'), **args) def AlphabeticalIndexEntryTemplate(**args): return Element(qname=(TEXTNS,'alphabetical-index-entry-template'), **args) def AlphabeticalIndexMark(**args): return Element(qname=(TEXTNS,'alphabetical-index-mark'), **args) def AlphabeticalIndexMarkEnd(**args): return Element(qname=(TEXTNS,'alphabetical-index-mark-end'), **args) def AlphabeticalIndexMarkStart(**args): return Element(qname=(TEXTNS,'alphabetical-index-mark-start'), **args) def AlphabeticalIndexSource(**args): return Element(qname=(TEXTNS,'alphabetical-index-source'), **args) def AuthorInitials(**args): return Element(qname=(TEXTNS,'author-initials'), **args) def AuthorName(**args): return Element(qname=(TEXTNS,'author-name'), **args) def Bibliography(**args): return Element(qname=(TEXTNS,'bibliography'), **args) def BibliographyConfiguration(**args): return Element(qname=(TEXTNS,'bibliography-configuration'), **args) def BibliographyEntryTemplate(**args): return Element(qname=(TEXTNS,'bibliography-entry-template'), **args) def BibliographyMark(**args): return Element(qname=(TEXTNS,'bibliography-mark'), **args) def BibliographySource(**args): return Element(qname=(TEXTNS,'bibliography-source'), **args) def Bookmark(**args): return Element(qname=(TEXTNS,'bookmark'), **args) def BookmarkEnd(**args): return Element(qname=(TEXTNS,'bookmark-end'), **args) def BookmarkRef(**args): return Element(qname=(TEXTNS,'bookmark-ref'), **args) def BookmarkStart(**args): return Element(qname=(TEXTNS,'bookmark-start'), **args) def Change(**args): return Element(qname=(TEXTNS,'change'), **args) def ChangeEnd(**args): return Element(qname=(TEXTNS,'change-end'), **args) def ChangeStart(**args): return Element(qname=(TEXTNS,'change-start'), **args) def ChangedRegion(**args): return Element(qname=(TEXTNS,'changed-region'), **args) def Chapter(**args): return Element(qname=(TEXTNS,'chapter'), **args) def CharacterCount(**args): return Element(qname=(TEXTNS,'character-count'), **args) def ConditionalText(**args): return Element(qname=(TEXTNS,'conditional-text'), **args) def CreationDate(**args): return Element(qname=(TEXTNS,'creation-date'), **args) def CreationTime(**args): return Element(qname=(TEXTNS,'creation-time'), **args) def Creator(**args): return Element(qname=(TEXTNS,'creator'), **args) def DatabaseDisplay(**args): return Element(qname=(TEXTNS,'database-display'), **args) def DatabaseName(**args): return Element(qname=(TEXTNS,'database-name'), **args) def DatabaseNext(**args): return Element(qname=(TEXTNS,'database-next'), **args) def DatabaseRowNumber(**args): return Element(qname=(TEXTNS,'database-row-number'), **args) def DatabaseRowSelect(**args): return Element(qname=(TEXTNS,'database-row-select'), **args) def Date(**args): return Element(qname=(TEXTNS,'date'), **args) def DdeConnection(**args): return Element(qname=(TEXTNS,'dde-connection'), **args) def DdeConnectionDecl(**args): return Element(qname=(TEXTNS,'dde-connection-decl'), **args) def DdeConnectionDecls(**args): return Element(qname=(TEXTNS,'dde-connection-decls'), **args) def Deletion(**args): return Element(qname=(TEXTNS,'deletion'), **args) def Description(**args): return Element(qname=(TEXTNS,'description'), **args) def EditingCycles(**args): return Element(qname=(TEXTNS,'editing-cycles'), **args) def EditingDuration(**args): return Element(qname=(TEXTNS,'editing-duration'), **args) def ExecuteMacro(**args): return Element(qname=(TEXTNS,'execute-macro'), **args) def Expression(**args): return Element(qname=(TEXTNS,'expression'), **args) def FileName(**args): return Element(qname=(TEXTNS,'file-name'), **args) def FormatChange(**args): return Element(qname=(TEXTNS,'format-change'), **args) def H(**args): return Element(qname=(TEXTNS, 'h'), **args) def HiddenParagraph(**args): return Element(qname=(TEXTNS,'hidden-paragraph'), **args) def HiddenText(**args): return Element(qname=(TEXTNS,'hidden-text'), **args) def IllustrationIndex(**args): return Element(qname=(TEXTNS,'illustration-index'), **args) def IllustrationIndexEntryTemplate(**args): return Element(qname=(TEXTNS,'illustration-index-entry-template'), **args) def IllustrationIndexSource(**args): return Element(qname=(TEXTNS,'illustration-index-source'), **args) def ImageCount(**args): return Element(qname=(TEXTNS,'image-count'), **args) def IndexBody(**args): return Element(qname=(TEXTNS,'index-body'), **args) def IndexEntryBibliography(**args): return Element(qname=(TEXTNS,'index-entry-bibliography'), **args) def IndexEntryChapter(**args): return Element(qname=(TEXTNS,'index-entry-chapter'), **args) def IndexEntryLinkEnd(**args): return Element(qname=(TEXTNS,'index-entry-link-end'), **args) def IndexEntryLinkStart(**args): return Element(qname=(TEXTNS,'index-entry-link-start'), **args) def IndexEntryPageNumber(**args): return Element(qname=(TEXTNS,'index-entry-page-number'), **args) def IndexEntrySpan(**args): return Element(qname=(TEXTNS,'index-entry-span'), **args) def IndexEntryTabStop(**args): return Element(qname=(TEXTNS,'index-entry-tab-stop'), **args) def IndexEntryText(**args): return Element(qname=(TEXTNS,'index-entry-text'), **args) def IndexSourceStyle(**args): return Element(qname=(TEXTNS,'index-source-style'), **args) def IndexSourceStyles(**args): return Element(qname=(TEXTNS,'index-source-styles'), **args) def IndexTitle(**args): return Element(qname=(TEXTNS,'index-title'), **args) def IndexTitleTemplate(**args): return Element(qname=(TEXTNS,'index-title-template'), **args) def InitialCreator(**args): return Element(qname=(TEXTNS,'initial-creator'), **args) def Insertion(**args): return Element(qname=(TEXTNS,'insertion'), **args) def Keywords(**args): return Element(qname=(TEXTNS,'keywords'), **args) def LineBreak(**args): return Element(qname=(TEXTNS,'line-break'), **args) def LinenumberingConfiguration(**args): return Element(qname=(TEXTNS,'linenumbering-configuration'), **args) def LinenumberingSeparator(**args): return Element(qname=(TEXTNS,'linenumbering-separator'), **args) def List(**args): return Element(qname=(TEXTNS,'list'), **args) def ListHeader(**args): return Element(qname=(TEXTNS,'list-header'), **args) def ListItem(**args): return Element(qname=(TEXTNS,'list-item'), **args) def ListLevelStyleBullet(**args): return Element(qname=(TEXTNS,'list-level-style-bullet'), **args) def ListLevelStyleImage(**args): return Element(qname=(TEXTNS,'list-level-style-image'), **args) def ListLevelStyleNumber(**args): return Element(qname=(TEXTNS,'list-level-style-number'), **args) def ListStyle(**args): return StyleElement(qname=(TEXTNS,'list-style'), **args) def Measure(**args): return Element(qname=(TEXTNS,'measure'), **args) def ModificationDate(**args): return Element(qname=(TEXTNS,'modification-date'), **args) def ModificationTime(**args): return Element(qname=(TEXTNS,'modification-time'), **args) def Note(**args): return Element(qname=(TEXTNS,'note'), **args) def NoteBody(**args): return Element(qname=(TEXTNS,'note-body'), **args) def NoteCitation(**args): return Element(qname=(TEXTNS,'note-citation'), **args) def NoteContinuationNoticeBackward(**args): return Element(qname=(TEXTNS,'note-continuation-notice-backward'), **args) def NoteContinuationNoticeForward(**args): return Element(qname=(TEXTNS,'note-continuation-notice-forward'), **args) def NoteRef(**args): return Element(qname=(TEXTNS,'note-ref'), **args) def NotesConfiguration(**args): return Element(qname=(TEXTNS,'notes-configuration'), **args) def Number(**args): return Element(qname=(TEXTNS,'number'), **args) def NumberedParagraph(**args): return Element(qname=(TEXTNS,'numbered-paragraph'), **args) def ObjectCount(**args): return Element(qname=(TEXTNS,'object-count'), **args) def ObjectIndex(**args): return Element(qname=(TEXTNS,'object-index'), **args) def ObjectIndexEntryTemplate(**args): return Element(qname=(TEXTNS,'object-index-entry-template'), **args) def ObjectIndexSource(**args): return Element(qname=(TEXTNS,'object-index-source'), **args) def OutlineLevelStyle(**args): return Element(qname=(TEXTNS,'outline-level-style'), **args) def OutlineStyle(**args): return Element(qname=(TEXTNS,'outline-style'), **args) def P(**args): return Element(qname=(TEXTNS, 'p'), **args) def Page(**args): return Element(qname=(TEXTNS,'page'), **args) def PageContinuation(**args): return Element(qname=(TEXTNS,'page-continuation'), **args) def PageCount(**args): return Element(qname=(TEXTNS,'page-count'), **args) def PageNumber(**args): return Element(qname=(TEXTNS,'page-number'), **args) def PageSequence(**args): return Element(qname=(TEXTNS,'page-sequence'), **args) def PageVariableGet(**args): return Element(qname=(TEXTNS,'page-variable-get'), **args) def PageVariableSet(**args): return Element(qname=(TEXTNS,'page-variable-set'), **args) def ParagraphCount(**args): return Element(qname=(TEXTNS,'paragraph-count'), **args) def Placeholder(**args): return Element(qname=(TEXTNS,'placeholder'), **args) def PrintDate(**args): return Element(qname=(TEXTNS,'print-date'), **args) def PrintTime(**args): return Element(qname=(TEXTNS,'print-time'), **args) def PrintedBy(**args): return Element(qname=(TEXTNS,'printed-by'), **args) def ReferenceMark(**args): return Element(qname=(TEXTNS,'reference-mark'), **args) def ReferenceMarkEnd(**args): return Element(qname=(TEXTNS,'reference-mark-end'), **args) def ReferenceMarkStart(**args): return Element(qname=(TEXTNS,'reference-mark-start'), **args) def ReferenceRef(**args): return Element(qname=(TEXTNS,'reference-ref'), **args) def Ruby(**args): return Element(qname=(TEXTNS,'ruby'), **args) def RubyBase(**args): return Element(qname=(TEXTNS,'ruby-base'), **args) def RubyText(**args): return Element(qname=(TEXTNS,'ruby-text'), **args) def S(**args): return Element(qname=(TEXTNS,'s'), **args) def Script(**args): return Element(qname=(TEXTNS,'script'), **args) def Section(**args): return Element(qname=(TEXTNS,'section'), **args) def SectionSource(**args): return Element(qname=(TEXTNS,'section-source'), **args) def SenderCity(**args): return Element(qname=(TEXTNS,'sender-city'), **args) def SenderCompany(**args): return Element(qname=(TEXTNS,'sender-company'), **args) def SenderCountry(**args): return Element(qname=(TEXTNS,'sender-country'), **args) def SenderEmail(**args): return Element(qname=(TEXTNS,'sender-email'), **args) def SenderFax(**args): return Element(qname=(TEXTNS,'sender-fax'), **args) def SenderFirstname(**args): return Element(qname=(TEXTNS,'sender-firstname'), **args) def SenderInitials(**args): return Element(qname=(TEXTNS,'sender-initials'), **args) def SenderLastname(**args): return Element(qname=(TEXTNS,'sender-lastname'), **args) def SenderPhonePrivate(**args): return Element(qname=(TEXTNS,'sender-phone-private'), **args) def SenderPhoneWork(**args): return Element(qname=(TEXTNS,'sender-phone-work'), **args) def SenderPosition(**args): return Element(qname=(TEXTNS,'sender-position'), **args) def SenderPostalCode(**args): return Element(qname=(TEXTNS,'sender-postal-code'), **args) def SenderStateOrProvince(**args): return Element(qname=(TEXTNS,'sender-state-or-province'), **args) def SenderStreet(**args): return Element(qname=(TEXTNS,'sender-street'), **args) def SenderTitle(**args): return Element(qname=(TEXTNS,'sender-title'), **args) def Sequence(**args): return Element(qname=(TEXTNS,'sequence'), **args) def SequenceDecl(**args): return Element(qname=(TEXTNS,'sequence-decl'), **args) def SequenceDecls(**args): return Element(qname=(TEXTNS,'sequence-decls'), **args) def SequenceRef(**args): return Element(qname=(TEXTNS,'sequence-ref'), **args) def SheetName(**args): return Element(qname=(TEXTNS,'sheet-name'), **args) def SoftPageBreak(**args): return Element(qname=(TEXTNS,'soft-page-break'), **args) def SortKey(**args): return Element(qname=(TEXTNS,'sort-key'), **args) def Span(**args): return Element(qname=(TEXTNS,'span'), **args) def Subject(**args): return Element(qname=(TEXTNS,'subject'), **args) def Tab(**args): return Element(qname=(TEXTNS,'tab'), **args) def TableCount(**args): return Element(qname=(TEXTNS,'table-count'), **args) def TableFormula(**args): return Element(qname=(TEXTNS,'table-formula'), **args) def TableIndex(**args): return Element(qname=(TEXTNS,'table-index'), **args) def TableIndexEntryTemplate(**args): return Element(qname=(TEXTNS,'table-index-entry-template'), **args) def TableIndexSource(**args): return Element(qname=(TEXTNS,'table-index-source'), **args) def TableOfContent(**args): return Element(qname=(TEXTNS,'table-of-content'), **args) def TableOfContentEntryTemplate(**args): return Element(qname=(TEXTNS,'table-of-content-entry-template'), **args) def TableOfContentSource(**args): return Element(qname=(TEXTNS,'table-of-content-source'), **args) def TemplateName(**args): return Element(qname=(TEXTNS,'template-name'), **args) def TextInput(**args): return Element(qname=(TEXTNS,'text-input'), **args) def Time(**args): return Element(qname=(TEXTNS,'time'), **args) def Title(**args): return Element(qname=(TEXTNS,'title'), **args) def TocMark(**args): return Element(qname=(TEXTNS,'toc-mark'), **args) def TocMarkEnd(**args): return Element(qname=(TEXTNS,'toc-mark-end'), **args) def TocMarkStart(**args): return Element(qname=(TEXTNS,'toc-mark-start'), **args) def TrackedChanges(**args): return Element(qname=(TEXTNS,'tracked-changes'), **args) def UserDefined(**args): return Element(qname=(TEXTNS,'user-defined'), **args) def UserFieldDecl(**args): return Element(qname=(TEXTNS,'user-field-decl'), **args) def UserFieldDecls(**args): return Element(qname=(TEXTNS,'user-field-decls'), **args) def UserFieldGet(**args): return Element(qname=(TEXTNS,'user-field-get'), **args) def UserFieldInput(**args): return Element(qname=(TEXTNS,'user-field-input'), **args) def UserIndex(**args): return Element(qname=(TEXTNS,'user-index'), **args) def UserIndexEntryTemplate(**args): return Element(qname=(TEXTNS,'user-index-entry-template'), **args) def UserIndexMark(**args): return Element(qname=(TEXTNS,'user-index-mark'), **args) def UserIndexMarkEnd(**args): return Element(qname=(TEXTNS,'user-index-mark-end'), **args) def UserIndexMarkStart(**args): return Element(qname=(TEXTNS,'user-index-mark-start'), **args) def UserIndexSource(**args): return Element(qname=(TEXTNS,'user-index-source'), **args) def VariableDecl(**args): return Element(qname=(TEXTNS,'variable-decl'), **args) def VariableDecls(**args): return Element(qname=(TEXTNS,'variable-decls'), **args) def VariableGet(**args): return Element(qname=(TEXTNS,'variable-get'), **args) def VariableInput(**args): return Element(qname=(TEXTNS,'variable-input'), **args) def VariableSet(**args): return Element(qname=(TEXTNS,'variable-set'), **args) def WordCount(**args): return Element(qname=(TEXTNS,'word-count'), **args)
17,013
Python
.py
380
40.936842
80
0.721116
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,423
table.py
kovidgoyal_calibre/src/odf/table.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import TABLENS # Autogenerated def Body(**args): return Element(qname=(TABLENS,'body'), **args) def CalculationSettings(**args): return Element(qname=(TABLENS,'calculation-settings'), **args) def CellAddress(**args): return Element(qname=(TABLENS,'cell-address'), **args) def CellContentChange(**args): return Element(qname=(TABLENS,'cell-content-change'), **args) def CellContentDeletion(**args): return Element(qname=(TABLENS,'cell-content-deletion'), **args) def CellRangeSource(**args): return Element(qname=(TABLENS,'cell-range-source'), **args) def ChangeDeletion(**args): return Element(qname=(TABLENS,'change-deletion'), **args) def ChangeTrackTableCell(**args): return Element(qname=(TABLENS,'change-track-table-cell'), **args) def Consolidation(**args): return Element(qname=(TABLENS,'consolidation'), **args) def ContentValidation(**args): return Element(qname=(TABLENS,'content-validation'), **args) def ContentValidations(**args): return Element(qname=(TABLENS,'content-validations'), **args) def CoveredTableCell(**args): return Element(qname=(TABLENS,'covered-table-cell'), **args) def CutOffs(**args): return Element(qname=(TABLENS,'cut-offs'), **args) def DataPilotDisplayInfo(**args): return Element(qname=(TABLENS,'data-pilot-display-info'), **args) def DataPilotField(**args): return Element(qname=(TABLENS,'data-pilot-field'), **args) def DataPilotFieldReference(**args): return Element(qname=(TABLENS,'data-pilot-field-reference'), **args) def DataPilotGroup(**args): return Element(qname=(TABLENS,'data-pilot-group'), **args) def DataPilotGroupMember(**args): return Element(qname=(TABLENS,'data-pilot-group-member'), **args) def DataPilotGroups(**args): return Element(qname=(TABLENS,'data-pilot-groups'), **args) def DataPilotLayoutInfo(**args): return Element(qname=(TABLENS,'data-pilot-layout-info'), **args) def DataPilotLevel(**args): return Element(qname=(TABLENS,'data-pilot-level'), **args) def DataPilotMember(**args): return Element(qname=(TABLENS,'data-pilot-member'), **args) def DataPilotMembers(**args): return Element(qname=(TABLENS,'data-pilot-members'), **args) def DataPilotSortInfo(**args): return Element(qname=(TABLENS,'data-pilot-sort-info'), **args) def DataPilotSubtotal(**args): return Element(qname=(TABLENS,'data-pilot-subtotal'), **args) def DataPilotSubtotals(**args): return Element(qname=(TABLENS,'data-pilot-subtotals'), **args) def DataPilotTable(**args): return Element(qname=(TABLENS,'data-pilot-table'), **args) def DataPilotTables(**args): return Element(qname=(TABLENS,'data-pilot-tables'), **args) def DatabaseRange(**args): return Element(qname=(TABLENS,'database-range'), **args) def DatabaseRanges(**args): return Element(qname=(TABLENS,'database-ranges'), **args) def DatabaseSourceQuery(**args): return Element(qname=(TABLENS,'database-source-query'), **args) def DatabaseSourceSql(**args): return Element(qname=(TABLENS,'database-source-sql'), **args) def DatabaseSourceTable(**args): return Element(qname=(TABLENS,'database-source-table'), **args) def DdeLink(**args): return Element(qname=(TABLENS,'dde-link'), **args) def DdeLinks(**args): return Element(qname=(TABLENS,'dde-links'), **args) def Deletion(**args): return Element(qname=(TABLENS,'deletion'), **args) def Deletions(**args): return Element(qname=(TABLENS,'deletions'), **args) def Dependencies(**args): return Element(qname=(TABLENS,'dependencies'), **args) def Dependency(**args): return Element(qname=(TABLENS,'dependency'), **args) def Detective(**args): return Element(qname=(TABLENS,'detective'), **args) def ErrorMacro(**args): return Element(qname=(TABLENS,'error-macro'), **args) def ErrorMessage(**args): return Element(qname=(TABLENS,'error-message'), **args) def EvenColumns(**args): return Element(qname=(TABLENS,'even-columns'), **args) def EvenRows(**args): return Element(qname=(TABLENS,'even-rows'), **args) def Filter(**args): return Element(qname=(TABLENS,'filter'), **args) def FilterAnd(**args): return Element(qname=(TABLENS,'filter-and'), **args) def FilterCondition(**args): return Element(qname=(TABLENS,'filter-condition'), **args) def FilterOr(**args): return Element(qname=(TABLENS,'filter-or'), **args) def FirstColumn(**args): return Element(qname=(TABLENS,'first-column'), **args) def FirstRow(**args): return Element(qname=(TABLENS,'first-row'), **args) def HelpMessage(**args): return Element(qname=(TABLENS,'help-message'), **args) def HighlightedRange(**args): return Element(qname=(TABLENS,'highlighted-range'), **args) def Insertion(**args): return Element(qname=(TABLENS,'insertion'), **args) def InsertionCutOff(**args): return Element(qname=(TABLENS,'insertion-cut-off'), **args) def Iteration(**args): return Element(qname=(TABLENS,'iteration'), **args) def LabelRange(**args): return Element(qname=(TABLENS,'label-range'), **args) def LabelRanges(**args): return Element(qname=(TABLENS,'label-ranges'), **args) def LastColumn(**args): return Element(qname=(TABLENS,'last-column'), **args) def LastRow(**args): return Element(qname=(TABLENS,'last-row'), **args) def Movement(**args): return Element(qname=(TABLENS,'movement'), **args) def MovementCutOff(**args): return Element(qname=(TABLENS,'movement-cut-off'), **args) def NamedExpression(**args): return Element(qname=(TABLENS,'named-expression'), **args) def NamedExpressions(**args): return Element(qname=(TABLENS,'named-expressions'), **args) def NamedRange(**args): return Element(qname=(TABLENS,'named-range'), **args) def NullDate(**args): return Element(qname=(TABLENS,'null-date'), **args) def OddColumns(**args): return Element(qname=(TABLENS,'odd-columns'), **args) def OddRows(**args): return Element(qname=(TABLENS,'odd-rows'), **args) def Operation(**args): return Element(qname=(TABLENS,'operation'), **args) def Previous(**args): return Element(qname=(TABLENS,'previous'), **args) def Scenario(**args): return Element(qname=(TABLENS,'scenario'), **args) def Shapes(**args): return Element(qname=(TABLENS,'shapes'), **args) def Sort(**args): return Element(qname=(TABLENS,'sort'), **args) def SortBy(**args): return Element(qname=(TABLENS,'sort-by'), **args) def SortGroups(**args): return Element(qname=(TABLENS,'sort-groups'), **args) def SourceCellRange(**args): return Element(qname=(TABLENS,'source-cell-range'), **args) def SourceRangeAddress(**args): return Element(qname=(TABLENS,'source-range-address'), **args) def SourceService(**args): return Element(qname=(TABLENS,'source-service'), **args) def SubtotalField(**args): return Element(qname=(TABLENS,'subtotal-field'), **args) def SubtotalRule(**args): return Element(qname=(TABLENS,'subtotal-rule'), **args) def SubtotalRules(**args): return Element(qname=(TABLENS,'subtotal-rules'), **args) def Table(**args): return Element(qname=(TABLENS,'table'), **args) def TableCell(**args): return Element(qname=(TABLENS,'table-cell'), **args) def TableColumn(**args): return Element(qname=(TABLENS,'table-column'), **args) def TableColumnGroup(**args): return Element(qname=(TABLENS,'table-column-group'), **args) def TableColumns(**args): return Element(qname=(TABLENS,'table-columns'), **args) def TableHeaderColumns(**args): return Element(qname=(TABLENS,'table-header-columns'), **args) def TableHeaderRows(**args): return Element(qname=(TABLENS,'table-header-rows'), **args) def TableRow(**args): return Element(qname=(TABLENS,'table-row'), **args) def TableRowGroup(**args): return Element(qname=(TABLENS,'table-row-group'), **args) def TableRows(**args): return Element(qname=(TABLENS,'table-rows'), **args) def TableSource(**args): return Element(qname=(TABLENS,'table-source'), **args) def TableTemplate(**args): return Element(qname=(TABLENS,'table-template'), **args) def TargetRangeAddress(**args): return Element(qname=(TABLENS,'target-range-address'), **args) def TrackedChanges(**args): return Element(qname=(TABLENS,'tracked-changes'), **args)
9,289
Python
.py
209
40.736842
80
0.72306
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,424
script.py
kovidgoyal_calibre/src/odf/script.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import SCRIPTNS # ODF 1.0 section 12.4.1 # The <script:event-listener> element binds an event to a macro. # Autogenerated def EventListener(**args): return Element(qname=(SCRIPTNS,'event-listener'), **args)
1,082
Python
.py
25
41.88
80
0.779258
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,425
number.py
kovidgoyal_calibre/src/odf/number.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import NUMBERNS from .style import StyleElement # Autogenerated def AmPm(**args): return Element(qname=(NUMBERNS,'am-pm'), **args) def Boolean(**args): return Element(qname=(NUMBERNS,'boolean'), **args) def BooleanStyle(**args): return StyleElement(qname=(NUMBERNS,'boolean-style'), **args) def CurrencyStyle(**args): return StyleElement(qname=(NUMBERNS,'currency-style'), **args) def CurrencySymbol(**args): return Element(qname=(NUMBERNS,'currency-symbol'), **args) def DateStyle(**args): return StyleElement(qname=(NUMBERNS,'date-style'), **args) def Day(**args): return Element(qname=(NUMBERNS,'day'), **args) def DayOfWeek(**args): return Element(qname=(NUMBERNS,'day-of-week'), **args) def EmbeddedText(**args): return Element(qname=(NUMBERNS,'embedded-text'), **args) def Era(**args): return Element(qname=(NUMBERNS,'era'), **args) def Fraction(**args): return Element(qname=(NUMBERNS,'fraction'), **args) def Hours(**args): return Element(qname=(NUMBERNS,'hours'), **args) def Minutes(**args): return Element(qname=(NUMBERNS,'minutes'), **args) def Month(**args): return Element(qname=(NUMBERNS,'month'), **args) def Number(**args): return Element(qname=(NUMBERNS,'number'), **args) def NumberStyle(**args): return StyleElement(qname=(NUMBERNS,'number-style'), **args) def PercentageStyle(**args): return StyleElement(qname=(NUMBERNS,'percentage-style'), **args) def Quarter(**args): return Element(qname=(NUMBERNS,'quarter'), **args) def ScientificNumber(**args): return Element(qname=(NUMBERNS,'scientific-number'), **args) def Seconds(**args): return Element(qname=(NUMBERNS,'seconds'), **args) def Text(**args): return Element(qname=(NUMBERNS,'text'), **args) def TextContent(**args): return Element(qname=(NUMBERNS,'text-content'), **args) def TextStyle(**args): return StyleElement(qname=(NUMBERNS,'text-style'), **args) def TimeStyle(**args): return StyleElement(qname=(NUMBERNS,'time-style'), **args) def WeekOfYear(**args): return Element(qname=(NUMBERNS,'week-of-year'), **args) def Year(**args): return Element(qname=(NUMBERNS,'year'), **args)
3,086
Python
.py
74
38.567568
80
0.728533
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,426
odf2moinmoin.py
kovidgoyal_calibre/src/odf/odf2moinmoin.py
# Copyright (C) 2006-2008 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # See http://trac.edgewall.org/wiki/WikiFormatting # # Contributor(s): # import xml.dom.minidom import zipfile from polyglot.builtins import unicode_type from .elementtypes import empty_elements, inline_elements from .namespaces import nsdict IGNORED_TAGS = [ 'draw:a' 'draw:g', 'draw:line', 'draw:object-ole', 'office:annotation', 'presentation:notes', 'svg:desc', ] + [nsdict[item[0]]+":"+item[1] for item in empty_elements] INLINE_TAGS = [nsdict[item[0]]+":"+item[1] for item in inline_elements] class TextProps: """ Holds properties for a text style. """ def __init__(self): self.italic = False self.bold = False self.fixed = False self.underlined = False self.strikethrough = False self.superscript = False self.subscript = False def setItalic(self, value): if value == "italic": self.italic = True elif value == "normal": self.italic = False def setBold(self, value): if value == "bold": self.bold = True elif value == "normal": self.bold = False def setFixed(self, value): self.fixed = value def setUnderlined(self, value): if value and value != "none": self.underlined = True def setStrikethrough(self, value): if value and value != "none": self.strikethrough = True def setPosition(self, value): if value is None or value == '': return posisize = value.split(' ') textpos = posisize[0] if textpos.find('%') == -1: if textpos == "sub": self.superscript = False self.subscript = True elif textpos == "super": self.superscript = True self.subscript = False else: itextpos = int(textpos[:textpos.find('%')]) if itextpos > 10: self.superscript = False self.subscript = True elif itextpos < -10: self.superscript = True self.subscript = False def __unicode__(self): return "[italic={}, bold=i{}, fixed={}]".format(unicode_type(self.italic), unicode_type(self.bold), unicode_type(self.fixed)) __str__ = __unicode__ class ParagraphProps: """ Holds properties of a paragraph style. """ def __init__(self): self.blockquote = False self.headingLevel = 0 self.code = False self.title = False self.indented = 0 def setIndented(self, value): self.indented = value def setHeading(self, level): self.headingLevel = level def setTitle(self, value): self.title = value def setCode(self, value): self.code = value def __unicode__(self): return "[bq=%s, h=%d, code=%s]" % (unicode_type(self.blockquote), self.headingLevel, unicode_type(self.code)) __str__ = __unicode__ class ListProperties: """ Holds properties for a list style. """ def __init__(self): self.ordered = False def setOrdered(self, value): self.ordered = value class ODF2MoinMoin: def __init__(self, filepath): self.footnotes = [] self.footnoteCounter = 0 self.textStyles = {"Standard": TextProps()} self.paragraphStyles = {"Standard": ParagraphProps()} self.listStyles = {} self.fixedFonts = [] self.hasTitle = 0 self.lastsegment = None # Tags self.elements = { 'draw:page': self.textToString, 'draw:frame': self.textToString, 'draw:image': self.draw_image, 'draw:text-box': self.textToString, 'text:a': self.text_a, 'text:note': self.text_note, } for tag in IGNORED_TAGS: self.elements[tag] = self.do_nothing for tag in INLINE_TAGS: self.elements[tag] = self.inline_markup self.elements['text:line-break'] = self.text_line_break self.elements['text:s'] = self.text_s self.elements['text:tab'] = self.text_tab self.load(filepath) def processFontDeclarations(self, fontDecl): """ Extracts necessary font information from a font-declaration element. """ for fontFace in fontDecl.getElementsByTagName("style:font-face"): if fontFace.getAttribute("style:font-pitch") == "fixed": self.fixedFonts.append(fontFace.getAttribute("style:name")) def extractTextProperties(self, style, parent=None): """ Extracts text properties from a style element. """ textProps = TextProps() textPropEl = style.getElementsByTagName("style:text-properties") if not textPropEl: return textProps textPropEl = textPropEl[0] textProps.setItalic(textPropEl.getAttribute("fo:font-style")) textProps.setBold(textPropEl.getAttribute("fo:font-weight")) textProps.setUnderlined(textPropEl.getAttribute("style:text-underline-style")) textProps.setStrikethrough(textPropEl.getAttribute("style:text-line-through-style")) textProps.setPosition(textPropEl.getAttribute("style:text-position")) if textPropEl.getAttribute("style:font-name") in self.fixedFonts: textProps.setFixed(True) return textProps def extractParagraphProperties(self, style, parent=None): """ Extracts paragraph properties from a style element. """ paraProps = ParagraphProps() name = style.getAttribute("style:name") if name.startswith("Heading_20_"): level = name[11:] try: level = int(level) paraProps.setHeading(level) except: level = 0 if name == "Title": paraProps.setTitle(True) paraPropEl = style.getElementsByTagName("style:paragraph-properties") if paraPropEl: paraPropEl = paraPropEl[0] leftMargin = paraPropEl.getAttribute("fo:margin-left") if leftMargin: try: leftMargin = float(leftMargin[:-2]) if leftMargin > 0.01: paraProps.setIndented(True) except: pass textProps = self.extractTextProperties(style) if textProps.fixed: paraProps.setCode(True) return paraProps def processStyles(self, styleElements): """ Runs through "style" elements extracting necessary information. """ for style in styleElements: name = style.getAttribute("style:name") if name == "Standard": continue family = style.getAttribute("style:family") parent = style.getAttribute("style:parent-style-name") if family == "text": self.textStyles[name] = self.extractTextProperties(style, parent) elif family == "paragraph": self.paragraphStyles[name] = \ self.extractParagraphProperties(style, parent) self.textStyles[name] = self.extractTextProperties(style, parent) def processListStyles(self, listStyleElements): for style in listStyleElements: name = style.getAttribute("style:name") prop = ListProperties() if style.hasChildNodes(): subitems = [el for el in style.childNodes if el.nodeType == xml.dom.Node.ELEMENT_NODE and el.tagName == "text:list-level-style-number"] if len(subitems) > 0: prop.setOrdered(True) self.listStyles[name] = prop def load(self, filepath): """ Loads an ODT file. """ zip = zipfile.ZipFile(filepath) styles_doc = xml.dom.minidom.parseString(zip.read("styles.xml")) fontfacedecls = styles_doc.getElementsByTagName("office:font-face-decls") if fontfacedecls: self.processFontDeclarations(fontfacedecls[0]) self.processStyles(styles_doc.getElementsByTagName("style:style")) self.processListStyles(styles_doc.getElementsByTagName("text:list-style")) self.content = xml.dom.minidom.parseString(zip.read("content.xml")) fontfacedecls = self.content.getElementsByTagName("office:font-face-decls") if fontfacedecls: self.processFontDeclarations(fontfacedecls[0]) self.processStyles(self.content.getElementsByTagName("style:style")) self.processListStyles(self.content.getElementsByTagName("text:list-style")) def compressCodeBlocks(self, text): """ Removes extra blank lines from code blocks. """ return text lines = text.split("\n") buffer = [] numLines = len(lines) for i in range(numLines): if (lines[i].strip() or i == numLines-1 or i == 0 or not (lines[i-1].startswith(" ") and lines[i+1].startswith(" "))): buffer.append("\n" + lines[i]) return ''.join(buffer) # ----------------------------------- def do_nothing(self, node): return '' def draw_image(self, node): """ """ link = node.getAttribute("xlink:href") if link and link[:2] == './': # Indicates a sub-object, which isn't supported return "%s\n" % link if link and link[:9] == 'Pictures/': link = link[9:] return "[[Image(%s)]]\n" % link def text_a(self, node): text = self.textToString(node) link = node.getAttribute("xlink:href") if link.strip() == text.strip(): return "[%s] " % link.strip() else: return f"[{link.strip()} {text.strip()}] " def text_line_break(self, node): return "[[BR]]" def text_note(self, node): cite = (node.getElementsByTagName("text:note-citation")[0] .childNodes[0].nodeValue) body = (node.getElementsByTagName("text:note-body")[0] .childNodes[0]) self.footnotes.append((cite, self.textToString(body))) return "^%s^" % cite def text_s(self, node): try: num = int(node.getAttribute("text:c")) return " "*num except: return " " def text_tab(self, node): return " " def inline_markup(self, node): text = self.textToString(node) if not text.strip(): return '' # don't apply styles to white space styleName = node.getAttribute("text:style-name") style = self.textStyles.get(styleName, TextProps()) if style.fixed: return "`" + text + "`" mark = [] if style: if style.italic: mark.append("''") if style.bold: mark.append("'''") if style.underlined: mark.append("__") if style.strikethrough: mark.append("~~") if style.superscript: mark.append("^") if style.subscript: mark.append(",,") revmark = mark[:] revmark.reverse() return "{}{}{}".format(''.join(mark), text, ''.join(revmark)) # ----------------------------------- def listToString(self, listElement, indent=0): self.lastsegment = listElement.tagName buffer = [] styleName = listElement.getAttribute("text:style-name") props = self.listStyles.get(styleName, ListProperties()) i = 0 for item in listElement.childNodes: buffer.append(" "*indent) i += 1 if props.ordered: number = unicode_type(i) number = " " + number + ". " buffer.append(" 1. ") else: buffer.append(" * ") subitems = [el for el in item.childNodes if el.tagName in ["text:p", "text:h", "text:list"]] for subitem in subitems: if subitem.tagName == "text:list": buffer.append("\n") buffer.append(self.listToString(subitem, indent+3)) else: buffer.append(self.paragraphToString(subitem, indent+3)) self.lastsegment = subitem.tagName self.lastsegment = item.tagName buffer.append("\n") return ''.join(buffer) def tableToString(self, tableElement): """ MoinMoin uses || to delimit table cells """ self.lastsegment = tableElement.tagName buffer = [] for item in tableElement.childNodes: self.lastsegment = item.tagName if item.tagName == "table:table-header-rows": buffer.append(self.tableToString(item)) if item.tagName == "table:table-row": buffer.append("\n||") for cell in item.childNodes: buffer.append(self.inline_markup(cell)) buffer.append("||") self.lastsegment = cell.tagName return ''.join(buffer) def toString(self): """ Converts the document to a string. FIXME: Result from second call differs from first call """ body = self.content.getElementsByTagName("office:body")[0] text = body.childNodes[0] buffer = [] paragraphs = [el for el in text.childNodes if el.tagName in ["draw:page", "text:p", "text:h","text:section", "text:list", "table:table"]] for paragraph in paragraphs: if paragraph.tagName == "text:list": text = self.listToString(paragraph) elif paragraph.tagName == "text:section": text = self.textToString(paragraph) elif paragraph.tagName == "table:table": text = self.tableToString(paragraph) else: text = self.paragraphToString(paragraph) if text: buffer.append(text) if self.footnotes: buffer.append("----") for cite, body in self.footnotes: buffer.append(f"{cite}: {body}") buffer.append("") return self.compressCodeBlocks('\n'.join(buffer)) def textToString(self, element): buffer = [] for node in element.childNodes: if node.nodeType == xml.dom.Node.TEXT_NODE: buffer.append(node.nodeValue) elif node.nodeType == xml.dom.Node.ELEMENT_NODE: tag = node.tagName if tag in ("draw:text-box", "draw:frame"): buffer.append(self.textToString(node)) elif tag in ("text:p", "text:h"): text = self.paragraphToString(node) if text: buffer.append(text) elif tag == "text:list": buffer.append(self.listToString(node)) else: method = self.elements.get(tag) if method: buffer.append(method(node)) else: buffer.append(" {" + tag + "} ") return ''.join(buffer) def paragraphToString(self, paragraph, indent=0): dummyParaProps = ParagraphProps() style_name = paragraph.getAttribute("text:style-name") paraProps = self.paragraphStyles.get(style_name, dummyParaProps) text = self.inline_markup(paragraph) if paraProps and not paraProps.code: text = text.strip() if paragraph.tagName == "text:p" and self.lastsegment == "text:p": text = "\n" + text self.lastsegment = paragraph.tagName if paraProps.title: self.hasTitle = 1 return "= " + text + " =\n" outlinelevel = paragraph.getAttribute("text:outline-level") if outlinelevel: level = int(outlinelevel) if self.hasTitle: level += 1 if level >= 1: return "=" * level + " " + text + " " + "=" * level + "\n" elif paraProps.code: return "{{{\n" + text + "\n}}}\n" if paraProps.indented: return self.wrapParagraph(text, indent=indent, blockquote=True) else: return self.wrapParagraph(text, indent=indent) def wrapParagraph(self, text, indent=0, blockquote=False): counter = 0 buffer = [] LIMIT = 50 if blockquote: buffer.append(" ") return ''.join(buffer) + text # Unused from here for token in text.split(): if counter > LIMIT - indent: buffer.append("\n" + " "*indent) if blockquote: buffer.append(" ") counter = 0 buffer.append(token + " ") counter += len(token) return ''.join(buffer)
18,178
Python
.py
440
30.022727
114
0.566617
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,427
grammar.py
kovidgoyal_calibre/src/odf/grammar.py
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # __doc__=""" In principle the OpenDocument schema converted to python structures. Currently it contains the legal child elements of a given element. To be used for validation check in the API """ from .namespaces import ( ANIMNS, CHARTNS, CONFIGNS, DCNS, DR3DNS, DRAWNS, FONS, FORMNS, MANIFESTNS, MATHNS, METANS, NUMBERNS, OFFICENS, PRESENTATIONNS, SCRIPTNS, SMILNS, STYLENS, SVGNS, TABLENS, TEXTNS, XFORMSNS, XLINKNS, ) # The following code is generated from the RelaxNG schema with this notice: # OASIS OpenDocument v1.1 # OASIS Standard, 1 Feb 2007 # Relax-NG Schema # $Id$ # © 2002-2007 OASIS Open # © 1999-2007 Sun Microsystems, Inc. # This document and translations of it may be copied and furnished # to others, and derivative works that comment on or otherwise explain # it or assist in its implementation may be prepared, copied, # published and distributed, in whole or in part, without restriction # of any kind, provided that the above copyright notice and this # paragraph are included on all such copies and derivative works. # However, this document itself does not be modified in any way, such # as by removing the copyright notice or references to OASIS, except # as needed for the purpose of developing OASIS specifications, in # which case the procedures for copyrights defined in the OASIS # Intellectual Property Rights document must be followed, or as # required to translate it into languages other than English. # allowed_children = { (DCNS,'creator') : ( ), (DCNS,'date') : ( ), (DCNS,'description') : ( ), (DCNS,'language') : ( ), (DCNS,'subject') : ( ), (DCNS,'title') : ( ), # Completes Dublin Core start # (DCNS,'contributor') : ( # ), # (DCNS,'coverage') : ( # ), # (DCNS,'format') : ( # ), # (DCNS,'identifier') : ( # ), # (DCNS,'publisher') : ( # ), # (DCNS,'relation') : ( # ), # (DCNS,'rights') : ( # ), # (DCNS,'source') : ( # ), # (DCNS,'type') : ( # ), # Completes Dublin Core end (MATHNS,'math') : None, (XFORMSNS,'model') : None, (ANIMNS,'animate') : ( ), (ANIMNS,'animateColor') : ( ), (ANIMNS,'animateMotion') : ( ), (ANIMNS,'animateTransform') : ( ), (ANIMNS,'audio') : ( ), (ANIMNS,'command') : ( (ANIMNS,'param'), ), # allowed_children (ANIMNS,'iterate') : ( (ANIMNS,'animate'), (ANIMNS,'animateColor'), (ANIMNS,'animateMotion'), (ANIMNS,'animateTransform'), (ANIMNS,'audio'), (ANIMNS,'command'), (ANIMNS,'iterate'), (ANIMNS,'par'), (ANIMNS,'seq'), (ANIMNS,'set'), (ANIMNS,'transitionFilter'), ), (ANIMNS,'par') : ( (ANIMNS,'animate'), (ANIMNS,'animateColor'), (ANIMNS,'animateMotion'), (ANIMNS,'animateTransform'), (ANIMNS,'audio'), (ANIMNS,'command'), (ANIMNS,'iterate'), (ANIMNS,'par'), (ANIMNS,'seq'), (ANIMNS,'set'), (ANIMNS,'transitionFilter'), ), # allowed_children (ANIMNS,'param') : ( ), (ANIMNS,'seq') : ( (ANIMNS,'animate'), (ANIMNS,'animateColor'), (ANIMNS,'animateMotion'), (ANIMNS,'animateTransform'), (ANIMNS,'audio'), (ANIMNS,'command'), (ANIMNS,'iterate'), (ANIMNS,'par'), (ANIMNS,'seq'), (ANIMNS,'set'), (ANIMNS,'transitionFilter'), ), (ANIMNS,'set') : ( ), (ANIMNS,'transitionFilter') : ( ), (CHARTNS,'axis') : ( (CHARTNS,'categories'), (CHARTNS,'grid'), (CHARTNS,'title'), ), # allowed_children (CHARTNS,'categories') : ( ), (CHARTNS,'chart') : ( (CHARTNS,'footer'), (CHARTNS,'legend'), (CHARTNS,'plot-area'), (CHARTNS,'subtitle'), (CHARTNS,'title'), (TABLENS,'table'), ), (CHARTNS,'data-point') : ( ), (CHARTNS,'domain') : ( ), (CHARTNS,'error-indicator') : ( ), (CHARTNS,'floor') : ( ), (CHARTNS,'footer') : ( (TEXTNS,'p'), ), (CHARTNS,'grid') : ( ), (CHARTNS,'legend') : ( ), # allowed_children (CHARTNS,'mean-value') : ( ), (CHARTNS,'plot-area') : ( (CHARTNS,'axis'), (CHARTNS,'floor'), (CHARTNS,'series'), (CHARTNS,'stock-gain-marker'), (CHARTNS,'stock-loss-marker'), (CHARTNS,'stock-range-line'), (CHARTNS,'wall'), (DR3DNS,'light'), ), (CHARTNS,'regression-curve') : ( ), (CHARTNS,'series') : ( (CHARTNS,'data-point'), (CHARTNS,'domain'), (CHARTNS,'error-indicator'), (CHARTNS,'mean-value'), (CHARTNS,'regression-curve'), ), (CHARTNS,'stock-gain-marker') : ( ), (CHARTNS,'stock-loss-marker') : ( ), # allowed_children (CHARTNS,'stock-range-line') : ( ), (CHARTNS,'subtitle') : ( (TEXTNS,'p'), ), (CHARTNS,'symbol-image') : ( ), (CHARTNS,'title') : ( (TEXTNS,'p'), ), (CHARTNS,'wall') : ( ), (CONFIGNS,'config-item') : ( ), (CONFIGNS,'config-item-map-entry') : ( (CONFIGNS,'config-item'), (CONFIGNS,'config-item-map-indexed'), (CONFIGNS,'config-item-map-named'), (CONFIGNS,'config-item-set'), ), (CONFIGNS,'config-item-map-indexed') : ( (CONFIGNS,'config-item-map-entry'), ), (CONFIGNS,'config-item-map-named') : ( (CONFIGNS,'config-item-map-entry'), ), # allowed_children (CONFIGNS,'config-item-set') : ( (CONFIGNS,'config-item'), (CONFIGNS,'config-item-map-indexed'), (CONFIGNS,'config-item-map-named'), (CONFIGNS,'config-item-set'), ), (MANIFESTNS,'algorithm') : ( ), (MANIFESTNS,'encryption-data') : ( (MANIFESTNS,'algorithm'), (MANIFESTNS,'key-derivation'), ), (MANIFESTNS,'file-entry') : ( (MANIFESTNS,'encryption-data'), ), (MANIFESTNS,'key-derivation') : ( ), (MANIFESTNS,'manifest') : ( (MANIFESTNS,'file-entry'), ), (NUMBERNS,'am-pm') : ( ), (NUMBERNS,'boolean') : ( ), # allowed_children (NUMBERNS,'boolean-style') : ( (NUMBERNS,'boolean'), (NUMBERNS,'text'), (STYLENS,'map'), (STYLENS,'text-properties'), ), (NUMBERNS,'currency-style') : ( (NUMBERNS,'currency-symbol'), (NUMBERNS,'number'), (NUMBERNS,'text'), (STYLENS,'map'), (STYLENS,'text-properties'), ), (NUMBERNS,'currency-symbol') : ( ), (NUMBERNS,'date-style') : ( (NUMBERNS,'am-pm'), (NUMBERNS,'day'), (NUMBERNS,'day-of-week'), (NUMBERNS,'era'), (NUMBERNS,'hours'), (NUMBERNS,'minutes'), (NUMBERNS,'month'), (NUMBERNS,'quarter'), (NUMBERNS,'seconds'), (NUMBERNS,'text'), (NUMBERNS,'week-of-year'), (NUMBERNS,'year'), (STYLENS,'map'), (STYLENS,'text-properties'), ), # allowed_children (NUMBERNS,'day') : ( ), (NUMBERNS,'day-of-week') : ( ), (NUMBERNS,'embedded-text') : ( ), (NUMBERNS,'era') : ( ), (NUMBERNS,'fraction') : ( ), (NUMBERNS,'hours') : ( ), (NUMBERNS,'minutes') : ( ), (NUMBERNS,'month') : ( ), (NUMBERNS,'number') : ( (NUMBERNS,'embedded-text'), ), (NUMBERNS,'number-style') : ( (NUMBERNS,'fraction'), (NUMBERNS,'number'), (NUMBERNS,'scientific-number'), (NUMBERNS,'text'), (STYLENS,'map'), (STYLENS,'text-properties'), ), # allowed_children (NUMBERNS,'percentage-style') : ( (NUMBERNS,'number'), (NUMBERNS,'text'), (STYLENS,'map'), (STYLENS,'text-properties'), ), (NUMBERNS,'quarter') : ( ), (NUMBERNS,'scientific-number') : ( ), (NUMBERNS,'seconds') : ( ), (NUMBERNS,'text') : ( ), (NUMBERNS,'text-content') : ( ), (NUMBERNS,'text-style') : ( (NUMBERNS,'text'), (NUMBERNS,'text-content'), (STYLENS,'map'), (STYLENS,'text-properties'), ), # allowed_children (NUMBERNS,'time-style') : ( (NUMBERNS,'am-pm'), (NUMBERNS,'hours'), (NUMBERNS,'minutes'), (NUMBERNS,'seconds'), (NUMBERNS,'text'), (STYLENS,'map'), (STYLENS,'text-properties'), ), # allowed_children (NUMBERNS,'week-of-year') : ( ), (NUMBERNS,'year') : ( ), (DR3DNS,'cube') : ( ), (DR3DNS,'extrude') : ( ), (DR3DNS,'light') : ( ), (DR3DNS,'rotate') : ( ), (DR3DNS,'scene') : ( (DR3DNS,'cube'), (DR3DNS,'extrude'), (DR3DNS,'light'), (DR3DNS,'rotate'), (DR3DNS,'scene'), (DR3DNS,'sphere'), (SVGNS,'title'), (SVGNS,'desc'), ), (DR3DNS,'sphere') : ( ), (DRAWNS,'a') : ( (DRAWNS,'frame'), ), # allowed_children (DRAWNS,'applet') : ( (DRAWNS,'param'), ), (DRAWNS,'area-circle') : ( (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'area-polygon') : ( (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'area-rectangle') : ( (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'caption') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'circle') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), # allowed_children (DRAWNS,'connector') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'contour-path') : ( ), (DRAWNS,'contour-polygon') : ( ), (DRAWNS,'control') : ( (DRAWNS,'glue-point'), (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'custom-shape') : ( (DRAWNS,'enhanced-geometry'), (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), # allowed_children (DRAWNS,'ellipse') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'enhanced-geometry') : ( (DRAWNS,'equation'), (DRAWNS,'handle'), ), (DRAWNS,'equation') : ( ), # allowed_children (DRAWNS,'fill-image') : ( ), (DRAWNS,'floating-frame') : ( ), (DRAWNS,'frame') : ( (DRAWNS,'applet'), (DRAWNS,'contour-path'), (DRAWNS,'contour-polygon'), (DRAWNS,'floating-frame'), (DRAWNS,'glue-point'), (DRAWNS,'image'), (DRAWNS,'image-map'), (DRAWNS,'object'), (DRAWNS,'object-ole'), (DRAWNS,'plugin'), (DRAWNS,'text-box'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), ), # allowed_children (DRAWNS,'g') : ( (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'glue-point'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (SVGNS,'desc'), (SVGNS,'title'), (OFFICENS,'event-listeners'), ), (DRAWNS,'glue-point') : ( ), (DRAWNS,'gradient') : ( ), (DRAWNS,'handle') : ( ), (DRAWNS,'hatch') : ( ), # allowed_children (DRAWNS,'image') : ( (OFFICENS,'binary-data'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'image-map') : ( (DRAWNS,'area-circle'), (DRAWNS,'area-polygon'), (DRAWNS,'area-rectangle'), ), (DRAWNS,'layer') : ( (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'layer-set') : ( (DRAWNS,'layer'), ), (DRAWNS,'line') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'marker') : ( ), (DRAWNS,'measure') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (TEXTNS,'list'), (TEXTNS,'p'), (SVGNS,'title'), (SVGNS,'desc'), ), (DRAWNS,'object') : ( (MATHNS,'math'), (OFFICENS,'document'), ), # allowed_children (DRAWNS,'object-ole') : ( (OFFICENS,'binary-data'), ), (DRAWNS,'opacity') : ( ), (DRAWNS,'page') : ( (ANIMNS,'animate'), (ANIMNS,'animateColor'), (ANIMNS,'animateMotion'), (ANIMNS,'animateTransform'), (ANIMNS,'audio'), (ANIMNS,'command'), (ANIMNS,'iterate'), (ANIMNS,'par'), (ANIMNS,'seq'), (ANIMNS,'set'), (ANIMNS,'transitionFilter'), (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'forms'), (PRESENTATIONNS,'animations'), (PRESENTATIONNS,'notes'), ), # allowed_children (DRAWNS,'page-thumbnail') : ( (SVGNS,'desc'), (SVGNS,'title'), ), (DRAWNS,'param') : ( ), (DRAWNS,'path') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'plugin') : ( (DRAWNS,'param'), ), (DRAWNS,'polygon') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'title'), (SVGNS,'desc'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'polyline') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), # allowed_children (DRAWNS,'rect') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'regular-polygon') : ( (DRAWNS,'glue-point'), (OFFICENS,'event-listeners'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'list'), (TEXTNS,'p'), ), (DRAWNS,'stroke-dash') : ( ), (DRAWNS,'text-box') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), # allowed_children (FORMNS,'button') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'checkbox') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'column') : ( (FORMNS,'checkbox'), (FORMNS,'combobox'), (FORMNS,'date'), (FORMNS,'formatted-text'), (FORMNS,'listbox'), (FORMNS,'number'), (FORMNS,'text'), (FORMNS,'textarea'), ), (FORMNS,'combobox') : ( (FORMNS,'item'), (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'connection-resource') : ( ), (FORMNS,'date') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'file') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'fixed-text') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), # allowed_children (FORMNS,'form') : ( (FORMNS,'button'), (FORMNS,'checkbox'), (FORMNS,'combobox'), (FORMNS,'connection-resource'), (FORMNS,'date'), (FORMNS,'file'), (FORMNS,'fixed-text'), (FORMNS,'form'), (FORMNS,'formatted-text'), (FORMNS,'frame'), (FORMNS,'generic-control'), (FORMNS,'grid'), (FORMNS,'hidden'), (FORMNS,'image'), (FORMNS,'image-frame'), (FORMNS,'listbox'), (FORMNS,'number'), (FORMNS,'password'), (FORMNS,'properties'), (FORMNS,'radio'), (FORMNS,'text'), (FORMNS,'textarea'), (FORMNS,'time'), (FORMNS,'value-range'), (OFFICENS,'event-listeners'), ), (FORMNS,'formatted-text') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'frame') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'generic-control') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'grid') : ( (FORMNS,'column'), (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'hidden') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'image') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), # allowed_children (FORMNS,'image-frame') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'item') : ( ), (FORMNS,'list-property') : ( (FORMNS,'list-value'), (FORMNS,'list-value'), (FORMNS,'list-value'), (FORMNS,'list-value'), (FORMNS,'list-value'), (FORMNS,'list-value'), (FORMNS,'list-value'), ), (FORMNS,'list-value') : ( ), (FORMNS,'listbox') : ( (FORMNS,'option'), (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'number') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'option') : ( ), (FORMNS,'password') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'properties') : ( (FORMNS,'list-property'), (FORMNS,'property'), ), (FORMNS,'property') : ( ), (FORMNS,'radio') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'text') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'textarea') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), (TEXTNS,'p'), ), (FORMNS,'time') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (FORMNS,'value-range') : ( (FORMNS,'properties'), (OFFICENS,'event-listeners'), ), (METANS,'auto-reload') : ( ), (METANS,'creation-date') : ( ), (METANS,'date-string') : ( ), (METANS,'document-statistic') : ( ), (METANS,'editing-cycles') : ( ), (METANS,'editing-duration') : ( ), (METANS,'generator') : ( ), (METANS,'hyperlink-behaviour') : ( ), (METANS,'initial-creator') : ( ), (METANS,'keyword') : ( ), (METANS,'print-date') : ( ), (METANS,'printed-by') : ( ), (METANS,'template') : ( ), (METANS,'user-defined') : ( ), # allowed_children (OFFICENS,'annotation') : ( (DCNS,'creator'), (DCNS,'date'), (METANS,'date-string'), (TEXTNS,'list'), (TEXTNS,'p'), ), (OFFICENS,'automatic-styles') : ( (NUMBERNS,'boolean-style'), (NUMBERNS,'currency-style'), (NUMBERNS,'date-style'), (NUMBERNS,'number-style'), (NUMBERNS,'percentage-style'), (NUMBERNS,'text-style'), (NUMBERNS,'time-style'), (STYLENS,'page-layout'), (STYLENS,'style'), (TEXTNS,'list-style'), ), (OFFICENS,'binary-data') : ( ), (OFFICENS,'body') : ( (OFFICENS,'chart'), (OFFICENS,'drawing'), (OFFICENS,'image'), (OFFICENS,'presentation'), (OFFICENS,'spreadsheet'), (OFFICENS,'text'), ), (OFFICENS,'change-info') : ( (DCNS,'creator'), (DCNS,'date'), (TEXTNS,'p'), ), (OFFICENS,'chart') : ( (CHARTNS,'chart'), (TABLENS,'calculation-settings'), (TABLENS,'consolidation'), (TABLENS,'content-validations'), (TABLENS,'data-pilot-tables'), (TABLENS,'database-ranges'), (TABLENS,'dde-links'), (TABLENS,'label-ranges'), (TABLENS,'named-expressions'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'sequence-decls'), (TEXTNS,'user-field-decls'), (TEXTNS,'variable-decls'), ), (OFFICENS,'dde-source') : ( ), (OFFICENS,'document') : ( (OFFICENS,'automatic-styles'), (OFFICENS,'body'), (OFFICENS,'font-face-decls'), (OFFICENS,'master-styles'), (OFFICENS,'meta'), (OFFICENS,'scripts'), (OFFICENS,'settings'), (OFFICENS,'styles'), ), (OFFICENS,'document-content') : ( (OFFICENS,'automatic-styles'), (OFFICENS,'body'), (OFFICENS,'font-face-decls'), (OFFICENS,'scripts'), ), (OFFICENS,'document-meta') : ( (OFFICENS,'meta'), ), (OFFICENS,'document-settings') : ( (OFFICENS,'settings'), ), (OFFICENS,'document-styles') : ( (OFFICENS,'automatic-styles'), (OFFICENS,'font-face-decls'), (OFFICENS,'master-styles'), (OFFICENS,'styles'), ), (OFFICENS,'drawing') : ( (DRAWNS,'page'), (TABLENS,'calculation-settings'), (TABLENS,'consolidation'), (TABLENS,'content-validations'), (TABLENS,'data-pilot-tables'), (TABLENS,'database-ranges'), (TABLENS,'dde-links'), (TABLENS,'label-ranges'), (TABLENS,'named-expressions'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'sequence-decls'), (TEXTNS,'user-field-decls'), (TEXTNS,'variable-decls'), ), (OFFICENS,'event-listeners') : ( (PRESENTATIONNS,'event-listener'), (SCRIPTNS,'event-listener'), ), (OFFICENS,'font-face-decls') : ( (STYLENS,'font-face'), ), # allowed_children (OFFICENS,'forms') : ( (XFORMSNS,'model'), (FORMNS,'form'), ), (OFFICENS,'image') : ( (DRAWNS,'frame'), ), (OFFICENS,'master-styles') : ( (DRAWNS,'layer-set'), (STYLENS,'handout-master'), (STYLENS,'master-page'), (TABLENS,'table-template'), ), (OFFICENS,'meta') : ( (DCNS,'creator'), (DCNS,'date'), (DCNS,'description'), (DCNS,'language'), (DCNS,'subject'), (DCNS,'title'), # Completes Dublin Core start # (DCNS,'contributor'), # (DCNS,'coverage'), # (DCNS,'format'), # (DCNS,'identifier'), # (DCNS,'publisher'), # (DCNS,'relation'), # (DCNS,'rights'), # (DCNS,'source'), # (DCNS,'type'), # Completes Dublin Core end (METANS,'auto-reload'), (METANS,'creation-date'), (METANS,'document-statistic'), (METANS,'editing-cycles'), (METANS,'editing-duration'), (METANS,'generator'), (METANS,'hyperlink-behaviour'), (METANS,'initial-creator'), (METANS,'keyword'), (METANS,'print-date'), (METANS,'printed-by'), (METANS,'template'), (METANS,'user-defined'), ), (OFFICENS,'presentation') : ( (DRAWNS,'page'), (PRESENTATIONNS,'date-time-decl'), (PRESENTATIONNS,'footer-decl'), (PRESENTATIONNS,'header-decl'), (PRESENTATIONNS,'settings'), (TABLENS,'calculation-settings'), (TABLENS,'consolidation'), (TABLENS,'content-validations'), (TABLENS,'data-pilot-tables'), (TABLENS,'database-ranges'), (TABLENS,'dde-links'), (TABLENS,'label-ranges'), (TABLENS,'named-expressions'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'sequence-decls'), (TEXTNS,'user-field-decls'), (TEXTNS,'variable-decls'), ), # allowed_children (OFFICENS,'script') : None, (OFFICENS,'scripts') : ( (OFFICENS,'event-listeners'), (OFFICENS,'script'), ), (OFFICENS,'settings') : ( (CONFIGNS,'config-item-set'), ), (OFFICENS,'spreadsheet') : ( (TABLENS,'calculation-settings'), (TABLENS,'consolidation'), (TABLENS,'content-validations'), (TABLENS,'data-pilot-tables'), (TABLENS,'database-ranges'), (TABLENS,'dde-links'), (TABLENS,'label-ranges'), (TABLENS,'named-expressions'), (TABLENS,'table'), (TABLENS,'tracked-changes'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'sequence-decls'), (TEXTNS,'user-field-decls'), (TEXTNS,'variable-decls'), ), (OFFICENS,'styles') : ( (NUMBERNS,'boolean-style'), (NUMBERNS,'currency-style'), (NUMBERNS,'date-style'), (NUMBERNS,'number-style'), (NUMBERNS,'percentage-style'), (NUMBERNS,'text-style'), (NUMBERNS,'time-style'), (DRAWNS,'fill-image'), (DRAWNS,'gradient'), (DRAWNS,'hatch'), (DRAWNS,'marker'), (DRAWNS,'opacity'), (DRAWNS,'stroke-dash'), (STYLENS,'default-style'), (STYLENS,'presentation-page-layout'), (STYLENS,'style'), (SVGNS,'linearGradient'), (SVGNS,'radialGradient'), (TEXTNS,'bibliography-configuration'), (TEXTNS,'linenumbering-configuration'), (TEXTNS,'list-style'), (TEXTNS,'notes-configuration'), (TEXTNS,'outline-style'), ), (OFFICENS,'text') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'forms'), (TABLENS,'calculation-settings'), (TABLENS,'consolidation'), (TABLENS,'content-validations'), (TABLENS,'data-pilot-tables'), (TABLENS,'database-ranges'), (TABLENS,'dde-links'), (TABLENS,'label-ranges'), (TABLENS,'named-expressions'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'page-sequence'), (TEXTNS,'section'), (TEXTNS,'sequence-decls'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'tracked-changes'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index'), (TEXTNS,'variable-decls'), ), (PRESENTATIONNS,'animation-group') : ( (PRESENTATIONNS,'dim'), (PRESENTATIONNS,'hide-shape'), (PRESENTATIONNS,'hide-text'), (PRESENTATIONNS,'play'), (PRESENTATIONNS,'show-shape'), (PRESENTATIONNS,'show-text'), ), (PRESENTATIONNS,'animations') : ( (PRESENTATIONNS,'animation-group'), (PRESENTATIONNS,'dim'), (PRESENTATIONNS,'hide-shape'), (PRESENTATIONNS,'hide-text'), (PRESENTATIONNS,'play'), (PRESENTATIONNS,'show-shape'), (PRESENTATIONNS,'show-text'), ), (PRESENTATIONNS,'date-time') : ( ), (PRESENTATIONNS,'date-time-decl') : ( ), (PRESENTATIONNS,'dim') : ( (PRESENTATIONNS,'sound'), ), (PRESENTATIONNS,'event-listener') : ( (PRESENTATIONNS,'sound'), ), (PRESENTATIONNS,'footer') : ( ), (PRESENTATIONNS,'footer-decl') : ( ), (PRESENTATIONNS,'header') : ( ), (PRESENTATIONNS,'header-decl') : ( ), (PRESENTATIONNS,'hide-shape') : ( (PRESENTATIONNS,'sound'), ), (PRESENTATIONNS,'hide-text') : ( (PRESENTATIONNS,'sound'), ), # allowed_children (PRESENTATIONNS,'notes') : ( (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'forms'), ), (PRESENTATIONNS,'placeholder') : ( ), (PRESENTATIONNS,'play') : ( ), (PRESENTATIONNS,'settings') : ( (PRESENTATIONNS,'show'), ), (PRESENTATIONNS,'show') : ( ), (PRESENTATIONNS,'show-shape') : ( (PRESENTATIONNS,'sound'), ), (PRESENTATIONNS,'show-text') : ( (PRESENTATIONNS,'sound'), ), (PRESENTATIONNS,'sound') : ( ), (SCRIPTNS,'event-listener') : ( ), (STYLENS,'background-image') : ( (OFFICENS,'binary-data'), ), (STYLENS,'chart-properties') : ( (CHARTNS,'symbol-image'), ), (STYLENS,'column') : ( ), (STYLENS,'column-sep') : ( ), (STYLENS,'columns') : ( (STYLENS,'column'), (STYLENS,'column-sep'), ), (STYLENS,'default-style') : ( (STYLENS,'chart-properties'), (STYLENS,'drawing-page-properties'), (STYLENS,'graphic-properties'), (STYLENS,'paragraph-properties'), (STYLENS,'ruby-properties'), (STYLENS,'section-properties'), (STYLENS,'table-cell-properties'), (STYLENS,'table-column-properties'), (STYLENS,'table-properties'), (STYLENS,'table-row-properties'), (STYLENS,'text-properties'), ), (STYLENS,'drawing-page-properties') : ( (PRESENTATIONNS,'sound'), ), (STYLENS,'drop-cap') : ( ), (STYLENS,'font-face') : ( (SVGNS,'definition-src'), (SVGNS,'font-face-src'), ), (STYLENS,'footer') : ( (STYLENS,'region-center'), (STYLENS,'region-left'), (STYLENS,'region-right'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'sequence-decls'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'tracked-changes'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index'), (TEXTNS,'variable-decls'), ), # allowed_children (STYLENS,'footer-left') : ( (STYLENS,'region-center'), (STYLENS,'region-left'), (STYLENS,'region-right'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'sequence-decls'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'tracked-changes'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index'), (TEXTNS,'variable-decls'), ), (STYLENS,'footer-style') : ( (STYLENS,'header-footer-properties'), ), (STYLENS,'footnote-sep') : ( ), (STYLENS,'graphic-properties') : ( (STYLENS,'background-image'), (STYLENS,'columns'), (TEXTNS,'list-style'), ), # allowed_children (STYLENS,'handout-master') : ( (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), ), (STYLENS,'header') : ( (STYLENS,'region-center'), (STYLENS,'region-left'), (STYLENS,'region-right'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'sequence-decls'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'tracked-changes'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index'), (TEXTNS,'variable-decls'), ), # allowed_children (STYLENS,'header-footer-properties') : ( (STYLENS,'background-image'), ), (STYLENS,'header-left') : ( (STYLENS,'region-center'), (STYLENS,'region-left'), (STYLENS,'region-right'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'alphabetical-index-auto-mark-file'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'dde-connection-decls'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'sequence-decls'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'tracked-changes'), (TEXTNS,'user-field-decls'), (TEXTNS,'user-index'), (TEXTNS,'variable-decls'), ), (STYLENS,'header-style') : ( (STYLENS,'header-footer-properties'), ), (STYLENS,'list-level-properties') : ( ), (STYLENS,'map') : ( ), (STYLENS,'master-page') : ( (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'forms'), (PRESENTATIONNS,'notes'), (STYLENS,'footer'), (STYLENS,'footer-left'), (STYLENS,'header'), (STYLENS,'header-left'), (STYLENS,'style'), ), (STYLENS,'page-layout') : ( (STYLENS,'footer-style'), (STYLENS,'header-style'), (STYLENS,'page-layout-properties'), ), (STYLENS,'page-layout-properties') : ( (STYLENS,'background-image'), (STYLENS,'columns'), (STYLENS,'footnote-sep'), ), # allowed_children (STYLENS,'paragraph-properties') : ( (STYLENS,'background-image'), (STYLENS,'drop-cap'), (STYLENS,'tab-stops'), ), (STYLENS,'presentation-page-layout') : ( (PRESENTATIONNS,'placeholder'), ), (STYLENS,'region-center') : ( (TEXTNS,'p'), ), (STYLENS,'region-left') : ( (TEXTNS,'p'), ), (STYLENS,'region-right') : ( (TEXTNS,'p'), ), (STYLENS,'ruby-properties') : ( ), (STYLENS,'section-properties') : ( (STYLENS,'background-image'), (STYLENS,'columns'), (TEXTNS,'notes-configuration'), ), (STYLENS,'style') : ( (STYLENS,'chart-properties'), (STYLENS,'drawing-page-properties'), (STYLENS,'graphic-properties'), (STYLENS,'map'), (STYLENS,'paragraph-properties'), (STYLENS,'ruby-properties'), (STYLENS,'section-properties'), (STYLENS,'table-cell-properties'), (STYLENS,'table-column-properties'), (STYLENS,'table-properties'), (STYLENS,'table-row-properties'), (STYLENS,'text-properties'), ), (STYLENS,'tab-stop') : ( ), (STYLENS,'tab-stops') : ( (STYLENS,'tab-stop'), ), # allowed_children (STYLENS,'table-cell-properties') : ( (STYLENS,'background-image'), ), (STYLENS,'table-column-properties') : ( ), (STYLENS,'table-properties') : ( (STYLENS,'background-image'), ), (STYLENS,'table-row-properties') : ( (STYLENS,'background-image'), ), (STYLENS,'text-properties') : ( ), (SVGNS,'definition-src') : ( ), (SVGNS,'desc') : ( ), (SVGNS,'font-face-format') : ( ), (SVGNS,'font-face-name') : ( ), (SVGNS,'font-face-src') : ( (SVGNS,'font-face-name'), (SVGNS,'font-face-uri'), ), (SVGNS,'font-face-uri') : ( (SVGNS,'font-face-format'), ), (SVGNS,'linearGradient') : ( (SVGNS,'stop'), ), (SVGNS,'radialGradient') : ( (SVGNS,'stop'), ), (SVGNS,'stop') : ( ), (SVGNS,'title') : ( ), (TABLENS,'body') : ( ), (TABLENS,'calculation-settings') : ( (TABLENS,'iteration'), (TABLENS,'null-date'), ), # allowed_children (TABLENS,'cell-address') : ( ), (TABLENS,'cell-content-change') : ( (OFFICENS,'change-info'), (TABLENS,'cell-address'), (TABLENS,'deletions'), (TABLENS,'dependencies'), (TABLENS,'previous'), ), (TABLENS,'cell-content-deletion') : ( (TABLENS,'cell-address'), (TABLENS,'change-track-table-cell'), ), (TABLENS,'cell-range-source') : ( ), (TABLENS,'change-deletion') : ( ), (TABLENS,'change-track-table-cell') : ( (TEXTNS,'p'), ), (TABLENS,'consolidation') : ( ), (TABLENS,'content-validation') : ( (OFFICENS,'event-listeners'), (TABLENS,'error-macro'), (TABLENS,'error-message'), (TABLENS,'help-message'), ), # allowed_children (TABLENS,'content-validations') : ( (TABLENS,'content-validation'), ), (TABLENS,'covered-table-cell') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (TABLENS,'cell-range-source'), (TABLENS,'detective'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), # allowed_children (TABLENS,'cut-offs') : ( (TABLENS,'insertion-cut-off'), (TABLENS,'movement-cut-off'), ), (TABLENS,'data-pilot-display-info') : ( ), (TABLENS,'data-pilot-field') : ( (TABLENS,'data-pilot-field-reference'), (TABLENS,'data-pilot-groups'), (TABLENS,'data-pilot-level'), ), (TABLENS,'data-pilot-field-reference') : ( ), (TABLENS,'data-pilot-group') : ( (TABLENS,'data-pilot-group-member'), ), (TABLENS,'data-pilot-group-member') : ( ), (TABLENS,'data-pilot-groups') : ( (TABLENS,'data-pilot-group'), ), (TABLENS,'data-pilot-layout-info') : ( ), (TABLENS,'data-pilot-level') : ( (TABLENS,'data-pilot-display-info'), (TABLENS,'data-pilot-layout-info'), (TABLENS,'data-pilot-members'), (TABLENS,'data-pilot-sort-info'), (TABLENS,'data-pilot-subtotals'), ), (TABLENS,'data-pilot-member') : ( ), (TABLENS,'data-pilot-members') : ( (TABLENS,'data-pilot-member'), ), (TABLENS,'data-pilot-sort-info') : ( ), (TABLENS,'data-pilot-subtotal') : ( ), (TABLENS,'data-pilot-subtotals') : ( (TABLENS,'data-pilot-subtotal'), ), # allowed_children (TABLENS,'data-pilot-table') : ( (TABLENS,'data-pilot-field'), (TABLENS,'database-source-query'), (TABLENS,'database-source-sql'), (TABLENS,'database-source-table'), (TABLENS,'source-cell-range'), (TABLENS,'source-service'), ), (TABLENS,'data-pilot-tables') : ( (TABLENS,'data-pilot-table'), ), (TABLENS,'database-range') : ( (TABLENS,'database-source-query'), (TABLENS,'database-source-sql'), (TABLENS,'database-source-table'), (TABLENS,'filter'), (TABLENS,'sort'), (TABLENS,'subtotal-rules'), ), (TABLENS,'database-ranges') : ( (TABLENS,'database-range'), ), (TABLENS,'database-source-query') : ( ), (TABLENS,'database-source-sql') : ( ), (TABLENS,'database-source-table') : ( ), # allowed_children (TABLENS,'dde-link') : ( (OFFICENS,'dde-source'), (TABLENS,'table'), ), (TABLENS,'dde-links') : ( (TABLENS,'dde-link'), ), (TABLENS,'deletion') : ( (OFFICENS,'change-info'), (TABLENS,'cut-offs'), (TABLENS,'deletions'), (TABLENS,'dependencies'), ), (TABLENS,'deletions') : ( (TABLENS,'cell-content-deletion'), (TABLENS,'change-deletion'), ), (TABLENS,'dependencies') : ( (TABLENS,'dependency'), ), (TABLENS,'dependency') : ( ), (TABLENS,'detective') : ( (TABLENS,'highlighted-range'), (TABLENS,'operation'), ), # allowed_children (TABLENS,'error-macro') : ( ), (TABLENS,'error-message') : ( (TEXTNS,'p'), ), (TABLENS,'even-columns') : ( ), (TABLENS,'even-rows') : ( ), (TABLENS,'filter') : ( (TABLENS,'filter-and'), (TABLENS,'filter-condition'), (TABLENS,'filter-or'), ), (TABLENS,'filter-and') : ( (TABLENS,'filter-condition'), (TABLENS,'filter-or'), ), (TABLENS,'filter-condition') : ( ), (TABLENS,'filter-or') : ( (TABLENS,'filter-and'), (TABLENS,'filter-condition'), ), # allowed_children (TABLENS,'first-column') : ( ), (TABLENS,'first-row') : ( ), (TABLENS,'help-message') : ( (TEXTNS,'p'), ), (TABLENS,'highlighted-range') : ( ), (TABLENS,'insertion') : ( (OFFICENS,'change-info'), (TABLENS,'deletions'), (TABLENS,'dependencies'), ), (TABLENS,'insertion-cut-off') : ( ), (TABLENS,'iteration') : ( ), (TABLENS,'label-range') : ( ), (TABLENS,'label-ranges') : ( (TABLENS,'label-range'), ), (TABLENS,'last-column') : ( ), (TABLENS,'last-row') : ( ), (TABLENS,'movement') : ( (OFFICENS,'change-info'), (TABLENS,'deletions'), (TABLENS,'dependencies'), (TABLENS,'source-range-address'), (TABLENS,'target-range-address'), ), (TABLENS,'movement-cut-off') : ( ), (TABLENS,'named-expression') : ( ), (TABLENS,'named-expressions') : ( (TABLENS,'named-expression'), (TABLENS,'named-range'), ), # allowed_children (TABLENS,'named-range') : ( ), (TABLENS,'null-date') : ( ), (TABLENS,'odd-columns') : ( ), (TABLENS,'odd-rows') : ( ), (TABLENS,'operation') : ( ), (TABLENS,'previous') : ( (TABLENS,'change-track-table-cell'), ), (TABLENS,'scenario') : ( ), (TABLENS,'shapes') : ( (DR3DNS,'scene'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), ), # allowed_children (TABLENS,'sort') : ( (TABLENS,'sort-by'), ), (TABLENS,'sort-by') : ( ), (TABLENS,'sort-groups') : ( ), (TABLENS,'source-cell-range') : ( (TABLENS,'filter'), ), (TABLENS,'source-range-address') : ( ), (TABLENS,'source-service') : ( ), (TABLENS,'subtotal-field') : ( ), (TABLENS,'subtotal-rule') : ( (TABLENS,'subtotal-field'), ), (TABLENS,'subtotal-rules') : ( (TABLENS,'sort-groups'), (TABLENS,'subtotal-rule'), ), # allowed_children (TABLENS,'table') : ( (OFFICENS,'dde-source'), (OFFICENS,'forms'), (TEXTNS,'soft-page-break'), (TABLENS,'scenario'), (TABLENS,'shapes'), (TABLENS,'table-column'), (TABLENS,'table-column-group'), (TABLENS,'table-columns'), (TABLENS,'table-header-columns'), (TABLENS,'table-header-rows'), (TABLENS,'table-row'), (TABLENS,'table-row-group'), (TABLENS,'table-rows'), (TABLENS,'table-source'), ), (TABLENS,'table-cell') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (TABLENS,'cell-range-source'), (TABLENS,'detective'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), # allowed_children (TABLENS,'table-column') : ( ), (TABLENS,'table-column-group') : ( (TABLENS,'table-column'), (TABLENS,'table-column-group'), (TABLENS,'table-columns'), (TABLENS,'table-header-columns'), ), (TABLENS,'table-columns') : ( (TABLENS,'table-column'), ), (TABLENS,'table-header-columns') : ( (TABLENS,'table-column'), ), (TABLENS,'table-header-rows') : ( (TABLENS,'table-row'), (TEXTNS,'soft-page-break'), ), (TABLENS,'table-row') : ( (TABLENS,'covered-table-cell'), (TABLENS,'table-cell'), ), (TABLENS,'table-row-group') : ( (TABLENS,'table-header-rows'), (TABLENS,'table-row'), (TABLENS,'table-row-group'), (TABLENS,'table-rows'), (TEXTNS,'soft-page-break'), ), (TABLENS,'table-rows') : ( (TABLENS,'table-row'), (TEXTNS,'soft-page-break'), ), # allowed_children (TABLENS,'table-source') : ( ), (TABLENS,'table-template') : ( (TABLENS,'body'), (TABLENS,'even-columns'), (TABLENS,'even-rows'), (TABLENS,'first-column'), (TABLENS,'first-row'), (TABLENS,'last-column'), (TABLENS,'last-row'), (TABLENS,'odd-columns'), (TABLENS,'odd-rows'), ), (TABLENS,'target-range-address') : ( ), (TABLENS,'tracked-changes') : ( (TABLENS,'cell-content-change'), (TABLENS,'deletion'), (TABLENS,'insertion'), (TABLENS,'movement'), ), # allowed_children (TEXTNS,'a') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (OFFICENS,'event-listeners'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (TEXTNS,'a'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-ref'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'chapter'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'line-break'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note'), (TEXTNS,'note-ref'), (TEXTNS,'page-count'), (TEXTNS,'paragraph-count'), (TEXTNS,'word-count'), (TEXTNS,'character-count'), (TEXTNS,'table-count'), (TEXTNS,'image-count'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'print-time'), (TEXTNS,'printed-by'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'s'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'soft-page-break'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'tab'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), ), # allowed_children (TEXTNS,'alphabetical-index') : ( (TEXTNS,'alphabetical-index-source'), (TEXTNS,'index-body'), ), (TEXTNS,'alphabetical-index-auto-mark-file') : ( ), (TEXTNS,'alphabetical-index-entry-template') : ( (TEXTNS,'index-entry-chapter'), (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), (TEXTNS,'alphabetical-index-mark') : ( ), (TEXTNS,'alphabetical-index-mark-end') : ( ), (TEXTNS,'alphabetical-index-mark-start') : ( ), (TEXTNS,'alphabetical-index-source') : ( (TEXTNS,'alphabetical-index-entry-template'), (TEXTNS,'index-title-template'), ), (TEXTNS,'author-initials') : ( ), (TEXTNS,'author-name') : ( ), (TEXTNS,'bibliography') : ( (TEXTNS,'bibliography-source'), (TEXTNS,'index-body'), ), (TEXTNS,'bibliography-configuration') : ( (TEXTNS,'sort-key'), ), (TEXTNS,'bibliography-entry-template') : ( (TEXTNS,'index-entry-bibliography'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), ), # allowed_children (TEXTNS,'bibliography-mark') : ( ), (TEXTNS,'bibliography-source') : ( (TEXTNS,'bibliography-entry-template'), (TEXTNS,'index-title-template'), ), (TEXTNS,'bookmark') : ( ), (TEXTNS,'bookmark-end') : ( ), (TEXTNS,'bookmark-ref') : ( ), (TEXTNS,'bookmark-start') : ( ), (TEXTNS,'change') : ( ), (TEXTNS,'change-end') : ( ), (TEXTNS,'change-start') : ( ), (TEXTNS,'changed-region') : ( (TEXTNS,'deletion'), (TEXTNS,'format-change'), (TEXTNS,'insertion'), ), (TEXTNS,'chapter') : ( ), (TEXTNS,'character-count') : ( ), (TEXTNS,'conditional-text') : ( ), (TEXTNS,'creation-date') : ( ), (TEXTNS,'creation-time') : ( ), (TEXTNS,'creator') : ( ), (TEXTNS,'database-display') : ( (FORMNS,'connection-resource'), ), (TEXTNS,'database-name') : ( (FORMNS,'connection-resource'), ), (TEXTNS,'database-next') : ( (FORMNS,'connection-resource'), ), (TEXTNS,'database-row-number') : ( (FORMNS,'connection-resource'), ), (TEXTNS,'database-row-select') : ( (FORMNS,'connection-resource'), ), (TEXTNS,'date') : ( ), (TEXTNS,'dde-connection') : ( ), (TEXTNS,'dde-connection-decl') : ( ), (TEXTNS,'dde-connection-decls') : ( (TEXTNS,'dde-connection-decl'), ), # allowed_children (TEXTNS,'deletion') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'change-info'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), (TEXTNS,'description') : ( ), (TEXTNS,'editing-cycles') : ( ), (TEXTNS,'editing-duration') : ( ), (TEXTNS,'execute-macro') : ( (OFFICENS,'event-listeners'), ), (TEXTNS,'expression') : ( ), (TEXTNS,'file-name') : ( ), (TEXTNS,'format-change') : ( (OFFICENS,'change-info'), ), # allowed_children (TEXTNS,'h') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (TEXTNS,'a'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-ref'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'chapter'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'line-break'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note'), (TEXTNS,'note-ref'), (TEXTNS,'number'), (TEXTNS,'page-count'), (TEXTNS,'paragraph-count'), (TEXTNS,'word-count'), (TEXTNS,'character-count'), (TEXTNS,'table-count'), (TEXTNS,'image-count'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'print-time'), (TEXTNS,'printed-by'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'s'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'soft-page-break'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'tab'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), ), # allowed_children (TEXTNS,'hidden-paragraph') : ( ), (TEXTNS,'hidden-text') : ( ), (TEXTNS,'illustration-index') : ( (TEXTNS,'illustration-index-source'), (TEXTNS,'index-body'), ), (TEXTNS,'illustration-index-entry-template') : ( (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), (TEXTNS,'illustration-index-source') : ( (TEXTNS,'illustration-index-entry-template'), (TEXTNS,'index-title-template'), ), (TEXTNS,'image-count') : ( ), # allowed_children (TEXTNS,'index-body') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), (TEXTNS,'index-entry-bibliography') : ( ), (TEXTNS,'index-entry-chapter') : ( ), (TEXTNS,'index-entry-link-end') : ( ), (TEXTNS,'index-entry-link-start') : ( ), (TEXTNS,'index-entry-page-number') : ( ), (TEXTNS,'index-entry-span') : ( ), (TEXTNS,'index-entry-tab-stop') : ( ), (TEXTNS,'index-entry-text') : ( ), (TEXTNS,'index-source-style') : ( ), (TEXTNS,'index-source-styles') : ( (TEXTNS,'index-source-style'), ), # allowed_children (TEXTNS,'index-title') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'index-title'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), (TEXTNS,'index-title-template') : ( ), (TEXTNS,'initial-creator') : ( ), (TEXTNS,'insertion') : ( (OFFICENS,'change-info'), ), (TEXTNS,'keywords') : ( ), (TEXTNS,'line-break') : ( ), (TEXTNS,'linenumbering-configuration') : ( (TEXTNS,'linenumbering-separator'), ), (TEXTNS,'linenumbering-separator') : ( ), (TEXTNS,'list') : ( (TEXTNS,'list-header'), (TEXTNS,'list-item'), ), (TEXTNS,'list-header') : ( (TEXTNS,'h'), (TEXTNS,'list'), (TEXTNS,'number'), (TEXTNS,'p'), (TEXTNS,'soft-page-break'), ), (TEXTNS,'list-item') : ( (TEXTNS,'h'), (TEXTNS,'list'), (TEXTNS,'number'), (TEXTNS,'p'), (TEXTNS,'soft-page-break'), ), (TEXTNS,'list-level-style-bullet') : ( (STYLENS,'list-level-properties'), (STYLENS,'text-properties'), ), (TEXTNS,'list-level-style-image') : ( (OFFICENS,'binary-data'), (STYLENS,'list-level-properties'), ), (TEXTNS,'list-level-style-number') : ( (STYLENS,'list-level-properties'), (STYLENS,'text-properties'), ), (TEXTNS,'list-style') : ( (TEXTNS,'list-level-style-bullet'), (TEXTNS,'list-level-style-image'), (TEXTNS,'list-level-style-number'), ), (TEXTNS,'measure') : ( ), (TEXTNS,'modification-date') : ( ), (TEXTNS,'modification-time') : ( ), (TEXTNS,'note') : ( (TEXTNS,'note-body'), (TEXTNS,'note-citation'), ), # allowed_children (TEXTNS,'note-body') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), (TEXTNS,'note-citation') : ( ), (TEXTNS,'note-continuation-notice-backward') : ( ), (TEXTNS,'note-continuation-notice-forward') : ( ), (TEXTNS,'note-ref') : ( ), (TEXTNS,'notes-configuration') : ( (TEXTNS,'note-continuation-notice-backward'), (TEXTNS,'note-continuation-notice-forward'), ), (TEXTNS,'number') : ( ), (TEXTNS,'numbered-paragraph') : ( (TEXTNS,'h'), (TEXTNS,'number'), (TEXTNS,'p'), ), (TEXTNS,'object-count') : ( ), (TEXTNS,'object-index') : ( (TEXTNS,'index-body'), (TEXTNS,'object-index-source'), ), (TEXTNS,'object-index-entry-template') : ( (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), (TEXTNS,'object-index-source') : ( (TEXTNS,'index-title-template'), (TEXTNS,'object-index-entry-template'), ), (TEXTNS,'outline-level-style') : ( (STYLENS,'list-level-properties'), (STYLENS,'text-properties'), ), (TEXTNS,'outline-style') : ( (TEXTNS,'outline-level-style'), ), # allowed_children (TEXTNS,'p') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (TEXTNS,'a'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-ref'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'chapter'), (TEXTNS,'character-count'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'image-count'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'line-break'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note'), (TEXTNS,'note-ref'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-count'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'paragraph-count'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'printed-by'), (TEXTNS,'print-time'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'s'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'soft-page-break'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'tab'), (TEXTNS,'table-count'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), (TEXTNS,'word-count'), ), (TEXTNS,'page') : ( ), (TEXTNS,'page-count') : ( ), (TEXTNS,'page-continuation') : ( ), (TEXTNS,'page-number') : ( ), (TEXTNS,'page-sequence') : ( (TEXTNS,'page'), ), (TEXTNS,'page-variable-get') : ( ), (TEXTNS,'page-variable-set') : ( ), (TEXTNS,'paragraph-count') : ( ), (TEXTNS,'placeholder') : ( ), (TEXTNS,'print-date') : ( ), (TEXTNS,'print-time') : ( ), (TEXTNS,'printed-by') : ( ), (TEXTNS,'reference-mark') : ( ), (TEXTNS,'reference-mark-end') : ( ), # allowed_children (TEXTNS,'reference-mark-start') : ( ), (TEXTNS,'reference-ref') : ( ), (TEXTNS,'ruby') : ( (TEXTNS,'ruby-base'), (TEXTNS,'ruby-text'), ), (TEXTNS,'ruby-base') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (TEXTNS,'a'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-ref'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'chapter'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'line-break'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note'), (TEXTNS,'note-ref'), (TEXTNS,'page-count'), (TEXTNS,'paragraph-count'), (TEXTNS,'word-count'), (TEXTNS,'character-count'), (TEXTNS,'table-count'), (TEXTNS,'image-count'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'print-time'), (TEXTNS,'printed-by'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'s'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'soft-page-break'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'tab'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), ), # allowed_children (TEXTNS,'ruby-text') : ( ), (TEXTNS,'s') : ( ), (TEXTNS,'script') : ( ), (TEXTNS,'section') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'dde-source'), (TABLENS,'table'), (TEXTNS,'alphabetical-index'), (TEXTNS,'bibliography'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'h'), (TEXTNS,'illustration-index'), (TEXTNS,'list'), (TEXTNS,'numbered-paragraph'), (TEXTNS,'object-index'), (TEXTNS,'p'), (TEXTNS,'section'), (TEXTNS,'section-source'), (TEXTNS,'soft-page-break'), (TEXTNS,'table-index'), (TEXTNS,'table-of-content'), (TEXTNS,'user-index'), ), (TEXTNS,'section-source') : ( ), (TEXTNS,'sender-city') : ( ), (TEXTNS,'sender-company') : ( ), (TEXTNS,'sender-country') : ( ), # allowed_children (TEXTNS,'sender-email') : ( ), (TEXTNS,'sender-fax') : ( ), (TEXTNS,'sender-firstname') : ( ), (TEXTNS,'sender-initials') : ( ), (TEXTNS,'sender-lastname') : ( ), (TEXTNS,'sender-phone-private') : ( ), (TEXTNS,'sender-phone-work') : ( ), (TEXTNS,'sender-position') : ( ), (TEXTNS,'sender-postal-code') : ( ), (TEXTNS,'sender-state-or-province') : ( ), (TEXTNS,'sender-street') : ( ), (TEXTNS,'sender-title') : ( ), (TEXTNS,'sequence') : ( ), (TEXTNS,'sequence-decl') : ( ), (TEXTNS,'sequence-decls') : ( (TEXTNS,'sequence-decl'), ), (TEXTNS,'sequence-ref') : ( ), (TEXTNS,'sheet-name') : ( ), (TEXTNS,'soft-page-break') : ( ), (TEXTNS,'sort-key') : ( ), # allowed_children (TEXTNS,'span') : ( (DR3DNS,'scene'), (DRAWNS,'a'), (DRAWNS,'caption'), (DRAWNS,'circle'), (DRAWNS,'connector'), (DRAWNS,'control'), (DRAWNS,'custom-shape'), (DRAWNS,'ellipse'), (DRAWNS,'frame'), (DRAWNS,'g'), (DRAWNS,'line'), (DRAWNS,'measure'), (DRAWNS,'page-thumbnail'), (DRAWNS,'path'), (DRAWNS,'polygon'), (DRAWNS,'polyline'), (DRAWNS,'rect'), (DRAWNS,'regular-polygon'), (OFFICENS,'annotation'), (PRESENTATIONNS,'date-time'), (PRESENTATIONNS,'footer'), (PRESENTATIONNS,'header'), (TEXTNS,'a'), (TEXTNS,'alphabetical-index-mark'), (TEXTNS,'alphabetical-index-mark-end'), (TEXTNS,'alphabetical-index-mark-start'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark'), (TEXTNS,'bookmark-end'), (TEXTNS,'bookmark-ref'), (TEXTNS,'bookmark-start'), (TEXTNS,'change'), (TEXTNS,'change-end'), (TEXTNS,'change-start'), (TEXTNS,'chapter'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-next'), (TEXTNS,'database-row-number'), (TEXTNS,'database-row-select'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'line-break'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note'), (TEXTNS,'note-ref'), (TEXTNS,'page-count'), (TEXTNS,'paragraph-count'), (TEXTNS,'word-count'), (TEXTNS,'character-count'), (TEXTNS,'table-count'), (TEXTNS,'image-count'), (TEXTNS,'object-count'), (TEXTNS,'page-continuation'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'print-time'), (TEXTNS,'printed-by'), (TEXTNS,'reference-mark'), (TEXTNS,'reference-mark-end'), (TEXTNS,'reference-mark-start'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby'), (TEXTNS,'s'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), (TEXTNS,'soft-page-break'), (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'tab'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'toc-mark'), (TEXTNS,'toc-mark-end'), (TEXTNS,'toc-mark-start'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'user-index-mark'), (TEXTNS,'user-index-mark-end'), (TEXTNS,'user-index-mark-start'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), ), # allowed_children (TEXTNS,'subject') : ( ), (TEXTNS,'tab') : ( ), (TEXTNS,'table-count') : ( ), (TEXTNS,'table-formula') : ( ), (TEXTNS,'table-index') : ( (TEXTNS,'index-body'), (TEXTNS,'table-index-source'), ), (TEXTNS,'table-index-entry-template') : ( (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), (TEXTNS,'table-index-source') : ( (TEXTNS,'index-title-template'), (TEXTNS,'table-index-entry-template'), ), (TEXTNS,'table-of-content') : ( (TEXTNS,'index-body'), (TEXTNS,'table-of-content-source'), ), (TEXTNS,'table-of-content-entry-template') : ( (TEXTNS,'index-entry-chapter'), (TEXTNS,'index-entry-link-end'), (TEXTNS,'index-entry-link-start'), (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), (TEXTNS,'table-of-content-source') : ( (TEXTNS,'index-source-styles'), (TEXTNS,'index-title-template'), (TEXTNS,'table-of-content-entry-template'), ), (TEXTNS,'template-name') : ( ), (TEXTNS,'text-input') : ( ), (TEXTNS,'time') : ( ), (TEXTNS,'title') : ( ), (TEXTNS,'toc-mark') : ( ), (TEXTNS,'toc-mark-end') : ( ), (TEXTNS,'toc-mark-start') : ( ), # allowed_children (TEXTNS,'tracked-changes') : ( (TEXTNS,'changed-region'), ), (TEXTNS,'user-defined') : ( ), (TEXTNS,'user-field-decl') : ( ), (TEXTNS,'user-field-decls') : ( (TEXTNS,'user-field-decl'), ), (TEXTNS,'user-field-get') : ( ), (TEXTNS,'user-field-input') : ( ), (TEXTNS,'user-index') : ( (TEXTNS,'index-body'), (TEXTNS,'user-index-source'), ), (TEXTNS,'user-index-entry-template') : ( (TEXTNS,'index-entry-chapter'), (TEXTNS,'index-entry-page-number'), (TEXTNS,'index-entry-span'), (TEXTNS,'index-entry-tab-stop'), (TEXTNS,'index-entry-text'), ), # allowed_children (TEXTNS,'user-index-mark') : ( ), (TEXTNS,'user-index-mark-end') : ( ), (TEXTNS,'user-index-mark-start') : ( ), (TEXTNS,'user-index-source') : ( (TEXTNS,'index-source-styles'), (TEXTNS,'index-title-template'), (TEXTNS,'user-index-entry-template'), ), (TEXTNS,'variable-decl') : ( ), (TEXTNS,'variable-decls') : ( (TEXTNS,'variable-decl'), ), (TEXTNS,'variable-get') : ( ), (TEXTNS,'variable-input') : ( ), (TEXTNS,'variable-set') : ( ), (TEXTNS,'word-count') : ( ), } # # List of elements that allows text nodes # allows_text = ( (CONFIGNS,'config-item'), (DCNS,'creator'), (DCNS,'date'), (DCNS,'description'), (DCNS,'language'), (DCNS,'subject'), (DCNS,'title'), # Completes Dublin Core start # (DCNS,'contributor'), # (DCNS,'coverage'), # (DCNS,'format'), # (DCNS,'identifier'), # (DCNS,'publisher'), # (DCNS,'relation'), # (DCNS,'rights'), # (DCNS,'source'), # (DCNS,'type'), # Completes Dublin Core end (FORMNS,'item'), (FORMNS,'option'), (MATHNS,'math'), (METANS,'creation-date'), (METANS,'date-string'), (METANS,'editing-cycles'), (METANS,'editing-duration'), # allows_text (METANS,'generator'), (METANS,'initial-creator'), (METANS,'keyword'), (METANS,'print-date'), (METANS,'printed-by'), (METANS,'user-defined'), (NUMBERNS,'currency-symbol'), (NUMBERNS,'embedded-text'), (NUMBERNS,'text'), (OFFICENS,'binary-data'), (OFFICENS,'script'), (PRESENTATIONNS,'date-time-decl'), (PRESENTATIONNS,'footer-decl'), (PRESENTATIONNS,'header-decl'), (SVGNS,'desc'), (SVGNS,'title'), (TEXTNS,'a'), (TEXTNS,'author-initials'), (TEXTNS,'author-name'), (TEXTNS,'bibliography-mark'), (TEXTNS,'bookmark-ref'), (TEXTNS,'chapter'), (TEXTNS,'character-count'), (TEXTNS,'conditional-text'), (TEXTNS,'creation-date'), (TEXTNS,'creation-time'), (TEXTNS,'creator'), (TEXTNS,'database-display'), (TEXTNS,'database-name'), (TEXTNS,'database-row-number'), (TEXTNS,'date'), (TEXTNS,'dde-connection'), (TEXTNS,'description'), (TEXTNS,'editing-cycles'), (TEXTNS,'editing-duration'), (TEXTNS,'execute-macro'), (TEXTNS,'expression'), (TEXTNS,'file-name'), (TEXTNS,'h'), (TEXTNS,'hidden-paragraph'), (TEXTNS,'hidden-text'), (TEXTNS,'image-count'), # allowed_children (TEXTNS,'index-entry-span'), (TEXTNS,'index-title-template'), (TEXTNS,'initial-creator'), (TEXTNS,'keywords'), (TEXTNS,'linenumbering-separator'), (TEXTNS,'measure'), (TEXTNS,'modification-date'), (TEXTNS,'modification-time'), (TEXTNS,'note-citation'), (TEXTNS,'note-continuation-notice-backward'), (TEXTNS,'note-continuation-notice-forward'), (TEXTNS,'note-ref'), (TEXTNS,'number'), (TEXTNS,'object-count'), (TEXTNS,'p'), (TEXTNS,'page-continuation'), (TEXTNS,'page-count'), (TEXTNS,'page-number'), (TEXTNS,'page-variable-get'), (TEXTNS,'page-variable-set'), (TEXTNS,'paragraph-count'), (TEXTNS,'placeholder'), (TEXTNS,'print-date'), (TEXTNS,'print-time'), (TEXTNS,'printed-by'), (TEXTNS,'reference-ref'), (TEXTNS,'ruby-base'), (TEXTNS,'ruby-text'), (TEXTNS,'script'), (TEXTNS,'sender-city'), (TEXTNS,'sender-company'), (TEXTNS,'sender-country'), (TEXTNS,'sender-email'), (TEXTNS,'sender-fax'), (TEXTNS,'sender-firstname'), (TEXTNS,'sender-initials'), (TEXTNS,'sender-lastname'), (TEXTNS,'sender-phone-private'), (TEXTNS,'sender-phone-work'), (TEXTNS,'sender-position'), (TEXTNS,'sender-postal-code'), (TEXTNS,'sender-state-or-province'), (TEXTNS,'sender-street'), (TEXTNS,'sender-title'), (TEXTNS,'sequence'), (TEXTNS,'sequence-ref'), (TEXTNS,'sheet-name'), # allowed_children (TEXTNS,'span'), (TEXTNS,'subject'), (TEXTNS,'table-count'), (TEXTNS,'table-formula'), (TEXTNS,'template-name'), (TEXTNS,'text-input'), (TEXTNS,'time'), (TEXTNS,'title'), (TEXTNS,'user-defined'), (TEXTNS,'user-field-get'), (TEXTNS,'user-field-input'), (TEXTNS,'variable-get'), (TEXTNS,'variable-input'), (TEXTNS,'variable-set'), (TEXTNS,'word-count'), ) # Only the elements with at least one required attribute is listed required_attributes = { (ANIMNS,'animate'): ( (SMILNS,'attributeName'), ), (ANIMNS,'animateColor'): ( (SMILNS,'attributeName'), ), (ANIMNS,'animateMotion'): ( (SMILNS,'attributeName'), ), (ANIMNS,'animateTransform'): ( (SVGNS,'type'), (SMILNS,'attributeName'), ), (ANIMNS,'command'): ( (ANIMNS,'command'), ), (ANIMNS,'param'): ( (ANIMNS,'name'), (ANIMNS,'value'), ), (ANIMNS,'set'): ( (SMILNS,'attributeName'), ), # required_attributes (ANIMNS,'transitionFilter'): ( (SMILNS,'type'), ), (CHARTNS,'axis'): ( (CHARTNS,'dimension'), ), (CHARTNS,'chart'): ( (CHARTNS,'class'), ), (CHARTNS,'symbol-image'): ( (XLINKNS,'href'), ), (CONFIGNS,'config-item'): ( (CONFIGNS,'type'), (CONFIGNS,'name'), ), (CONFIGNS,'config-item-map-indexed'): ( (CONFIGNS,'name'), ), (CONFIGNS,'config-item-map-named'): ( (CONFIGNS,'name'), ), (CONFIGNS,'config-item-set'): ( (CONFIGNS,'name'), ), # required_attributes (NUMBERNS,'boolean-style'): ( (STYLENS,'name'), ), (NUMBERNS,'currency-style'): ( (STYLENS,'name'), ), (NUMBERNS,'date-style'): ( (STYLENS,'name'), ), (NUMBERNS,'embedded-text'): ( (NUMBERNS,'position'), ), (NUMBERNS,'number-style'): ( (STYLENS,'name'), ), (NUMBERNS,'percentage-style'): ( (STYLENS,'name'), ), (NUMBERNS,'text-style'): ( (STYLENS,'name'), ), (NUMBERNS,'time-style'): ( (STYLENS,'name'), ), (DR3DNS,'extrude'): ( (SVGNS,'d'), (SVGNS,'viewBox'), ), (DR3DNS,'light'): ( (DR3DNS,'direction'), ), (DR3DNS,'rotate'): ( (SVGNS,'viewBox'), (SVGNS,'d'), ), # required_attributes (DRAWNS,'a'): ( (XLINKNS,'href'), ), (DRAWNS,'area-circle'): ( (SVGNS,'cy'), (SVGNS,'cx'), (SVGNS,'r'), ), (DRAWNS,'area-polygon'): ( (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'points'), (SVGNS,'y'), (SVGNS,'x'), (SVGNS,'viewBox'), ), (DRAWNS,'area-rectangle'): ( (SVGNS,'y'), (SVGNS,'x'), (SVGNS,'height'), (SVGNS,'width'), ), (DRAWNS,'contour-path'): ( (DRAWNS,'recreate-on-edit'), (SVGNS,'viewBox'), (SVGNS,'d'), ), (DRAWNS,'contour-polygon'): ( (DRAWNS,'points'), (DRAWNS,'recreate-on-edit'), (SVGNS,'viewBox'), ), (DRAWNS,'control'): ( (DRAWNS,'control'), ), (DRAWNS,'fill-image'): ( (XLINKNS,'href'), (DRAWNS,'name'), ), (DRAWNS,'floating-frame'): ( (XLINKNS,'href'), ), (DRAWNS,'glue-point'): ( (SVGNS,'y'), (SVGNS,'x'), (DRAWNS,'id'), (DRAWNS,'escape-direction'), ), # required_attributes (DRAWNS,'gradient'): ( (DRAWNS,'style'), ), (DRAWNS,'handle'): ( (DRAWNS,'handle-position'), ), (DRAWNS,'hatch'): ( (DRAWNS,'style'), (DRAWNS,'name'), ), (DRAWNS,'layer'): ( (DRAWNS,'name'), ), (DRAWNS,'line'): ( (SVGNS,'y1'), (SVGNS,'x2'), (SVGNS,'x1'), (SVGNS,'y2'), ), (DRAWNS,'marker'): ( (SVGNS,'d'), (DRAWNS,'name'), (SVGNS,'viewBox'), ), (DRAWNS,'measure'): ( (SVGNS,'y1'), (SVGNS,'x2'), (SVGNS,'x1'), (SVGNS,'y2'), ), (DRAWNS,'opacity'): ( (DRAWNS,'style'), ), (DRAWNS,'page'): ( (DRAWNS,'master-page-name'), ), (DRAWNS,'path'): ( (SVGNS,'d'), (SVGNS,'viewBox'), ), (DRAWNS,'plugin'): ( (XLINKNS,'href'), ), (DRAWNS,'polygon'): ( (DRAWNS,'points'), (SVGNS,'viewBox'), ), # required_attributes (DRAWNS,'polyline'): ( (DRAWNS,'points'), (SVGNS,'viewBox'), ), (DRAWNS,'regular-polygon'): ( (DRAWNS,'corners'), ), (DRAWNS,'stroke-dash'): ( (DRAWNS,'name'), ), (FORMNS,'button'): ( (FORMNS,'id'), ), (FORMNS,'checkbox'): ( (FORMNS,'id'), ), (FORMNS,'combobox'): ( (FORMNS,'id'), ), (FORMNS,'connection-resource'): ( (XLINKNS,'href'), ), (FORMNS,'date'): ( (FORMNS,'id'), ), (FORMNS,'file'): ( (FORMNS,'id'), ), (FORMNS,'fixed-text'): ( (FORMNS,'id'), ), (FORMNS,'formatted-text'): ( (FORMNS,'id'), ), (FORMNS,'frame'): ( (FORMNS,'id'), ), (FORMNS,'generic-control'): ( (FORMNS,'id'), ), (FORMNS,'grid'): ( (FORMNS,'id'), ), (FORMNS,'hidden'): ( (FORMNS,'id'), ), # required_attributes (FORMNS,'image'): ( (FORMNS,'id'), ), (FORMNS,'image-frame'): ( (FORMNS,'id'), ), (FORMNS,'list-property'): ( (FORMNS,'property-name'), ), (FORMNS,'list-value'): ( (OFFICENS,'string-value'), ), (FORMNS,'listbox'): ( (FORMNS,'id'), ), (FORMNS,'number'): ( (FORMNS,'id'), ), (FORMNS,'password'): ( (FORMNS,'id'), ), (FORMNS,'property'): ( (FORMNS,'property-name'), ), (FORMNS,'radio'): ( (FORMNS,'id'), ), (FORMNS,'text'): ( (FORMNS,'id'), ), (FORMNS,'textarea'): ( (FORMNS,'id'), ), (FORMNS,'time'): ( (FORMNS,'id'), ), (FORMNS,'value-range'): ( (FORMNS,'id'), ), (MANIFESTNS,'algorithm') : ( (MANIFESTNS,'algorithm-name'), (MANIFESTNS,'initialisation-vector'), ), (MANIFESTNS,'encryption-data') : ( (MANIFESTNS,'checksum-type'), (MANIFESTNS,'checksum'), ), (MANIFESTNS,'file-entry') : ( (MANIFESTNS,'full-path'), (MANIFESTNS,'media-type'), ), (MANIFESTNS,'key-derivation') : ( (MANIFESTNS,'key-derivation-name'), (MANIFESTNS,'salt'), (MANIFESTNS,'iteration-count'), ), # required_attributes (METANS,'template'): ( (XLINKNS,'href'), ), (METANS,'user-defined'): ( (METANS,'name'), ), (OFFICENS,'dde-source'): ( (OFFICENS,'dde-topic'), (OFFICENS,'dde-application'), (OFFICENS,'dde-item'), ), (OFFICENS,'document'): ( (OFFICENS,'mimetype'), ), (OFFICENS,'script'): ( (SCRIPTNS,'language'), ), (PRESENTATIONNS,'date-time-decl'): ( (PRESENTATIONNS,'source'), (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'dim'): ( (DRAWNS,'color'), (DRAWNS,'shape-id'), ), # required_attributes (PRESENTATIONNS,'event-listener'): ( (PRESENTATIONNS,'action'), (SCRIPTNS,'event-name'), ), (PRESENTATIONNS,'footer-decl'): ( (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'header-decl'): ( (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'hide-shape'): ( (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'hide-text'): ( (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'placeholder'): ( (SVGNS,'y'), (SVGNS,'x'), (SVGNS,'height'), (PRESENTATIONNS,'object'), (SVGNS,'width'), ), (PRESENTATIONNS,'play'): ( (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'show'): ( (PRESENTATIONNS,'name'), (PRESENTATIONNS,'pages'), ), (PRESENTATIONNS,'show-shape'): ( (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'show-text'): ( (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'sound'): ( (XLINKNS,'href'), ), (SCRIPTNS,'event-listener'): ( (SCRIPTNS,'language'), (SCRIPTNS,'event-name'), ), (STYLENS,'column'): ( (STYLENS,'rel-width'), ), # required_attributes (STYLENS,'column-sep'): ( (STYLENS,'width'), ), (STYLENS,'columns'): ( (FONS,'column-count'), ), (STYLENS,'font-face'): ( (STYLENS,'name'), ), (STYLENS,'handout-master'): ( (STYLENS,'page-layout-name'), ), (STYLENS,'map'): ( (STYLENS,'apply-style-name'), (STYLENS,'condition'), ), (STYLENS,'master-page'): ( (STYLENS,'page-layout-name'), (STYLENS,'name'), ), (STYLENS,'page-layout'): ( (STYLENS,'name'), ), (STYLENS,'presentation-page-layout'): ( (STYLENS,'name'), ), (STYLENS,'style'): ( (STYLENS,'name'), ), (STYLENS,'tab-stop'): ( (STYLENS,'position'), ), (SVGNS,'definition-src'): ( (XLINKNS,'href'), ), (SVGNS,'font-face-uri'): ( (XLINKNS,'href'), ), (SVGNS,'linearGradient'): ( (DRAWNS,'name'), ), (SVGNS,'radialGradient'): ( (DRAWNS,'name'), ), (SVGNS,'stop'): ( (SVGNS,'offset'), ), # required_attributes (TABLENS,'body'): ( (TEXTNS,'style-name'), ), (TABLENS,'cell-address'): ( (TABLENS,'column'), (TABLENS,'table'), (TABLENS,'row'), ), (TABLENS,'cell-content-change'): ( (TABLENS,'id'), ), (TABLENS,'cell-range-source'): ( (TABLENS,'last-row-spanned'), (TABLENS,'last-column-spanned'), (XLINKNS,'href'), (TABLENS,'name'), ), (TABLENS,'consolidation'): ( (TABLENS,'function'), (TABLENS,'source-cell-range-addresses'), (TABLENS,'target-cell-address'), ), (TABLENS,'content-validation'): ( (TABLENS,'name'), ), (TABLENS,'data-pilot-display-info'): ( (TABLENS,'member-count'), (TABLENS,'data-field'), (TABLENS,'enabled'), (TABLENS,'display-member-mode'), ), # required_attributes (TABLENS,'data-pilot-field'): ( (TABLENS,'source-field-name'), ), (TABLENS,'data-pilot-field-reference'): ( (TABLENS,'field-name'), (TABLENS,'type'), ), (TABLENS,'data-pilot-group'): ( (TABLENS,'name'), ), (TABLENS,'data-pilot-group-member'): ( (TABLENS,'name'), ), (TABLENS,'data-pilot-groups'): ( (TABLENS,'source-field-name'), (TABLENS,'step'), (TABLENS,'grouped-by'), ), (TABLENS,'data-pilot-layout-info'): ( (TABLENS,'add-empty-lines'), (TABLENS,'layout-mode'), ), (TABLENS,'data-pilot-member'): ( (TABLENS,'name'), ), (TABLENS,'data-pilot-sort-info'): ( (TABLENS,'order'), ), (TABLENS,'data-pilot-subtotal'): ( (TABLENS,'function'), ), (TABLENS,'data-pilot-table'): ( (TABLENS,'target-range-address'), (TABLENS,'name'), ), (TABLENS,'database-range'): ( (TABLENS,'target-range-address'), ), # required_attributes (TABLENS,'database-source-query'): ( (TABLENS,'query-name'), (TABLENS,'database-name'), ), (TABLENS,'database-source-sql'): ( (TABLENS,'database-name'), (TABLENS,'sql-statement'), ), (TABLENS,'database-source-table'): ( (TABLENS,'database-table-name'), (TABLENS,'database-name'), ), (TABLENS,'deletion'): ( (TABLENS,'position'), (TABLENS,'type'), (TABLENS,'id'), ), (TABLENS,'dependency'): ( (TABLENS,'id'), ), (TABLENS,'even-columns'): ( (TEXTNS,'style-name'), ), (TABLENS,'even-rows'): ( (TEXTNS,'style-name'), ), (TABLENS,'filter-condition'): ( (TABLENS,'operator'), (TABLENS,'field-number'), (TABLENS,'value'), ), (TABLENS,'first-column'): ( (TEXTNS,'style-name'), ), (TABLENS,'first-row'): ( (TEXTNS,'style-name'), ), (TABLENS,'insertion'): ( (TABLENS,'position'), (TABLENS,'type'), (TABLENS,'id'), ), (TABLENS,'insertion-cut-off'): ( (TABLENS,'position'), (TABLENS,'id'), ), # required_attributes (TABLENS,'label-range'): ( (TABLENS,'label-cell-range-address'), (TABLENS,'data-cell-range-address'), (TABLENS,'orientation'), ), (TABLENS,'last-column'): ( (TEXTNS,'style-name'), ), (TABLENS,'last-row'): ( (TEXTNS,'style-name'), ), (TABLENS,'movement'): ( (TABLENS,'id'), ), (TABLENS,'named-expression'): ( (TABLENS,'expression'), (TABLENS,'name'), ), (TABLENS,'named-range'): ( (TABLENS,'name'), (TABLENS,'cell-range-address'), ), (TABLENS,'odd-columns'): ( (TEXTNS,'style-name'), ), (TABLENS,'odd-rows'): ( (TEXTNS,'style-name'), ), (TABLENS,'operation'): ( (TABLENS,'index'), (TABLENS,'name'), ), # required_attributes (TABLENS,'scenario'): ( (TABLENS,'is-active'), (TABLENS,'scenario-ranges'), ), (TABLENS,'sort-by'): ( (TABLENS,'field-number'), ), (TABLENS,'source-cell-range'): ( (TABLENS,'cell-range-address'), ), (TABLENS,'source-service'): ( (TABLENS,'source-name'), (TABLENS,'object-name'), (TABLENS,'name'), ), (TABLENS,'subtotal-field'): ( (TABLENS,'function'), (TABLENS,'field-number'), ), (TABLENS,'subtotal-rule'): ( (TABLENS,'group-by-field-number'), ), (TABLENS,'table-source'): ( (XLINKNS,'href'), ), (TABLENS,'table-template'): ( (TEXTNS,'last-row-end-column'), (TEXTNS,'first-row-end-column'), (TEXTNS,'name'), (TEXTNS,'last-row-start-column'), (TEXTNS,'first-row-start-column'), ), (TEXTNS,'a'): ( (XLINKNS,'href'), ), # required_attributes (TEXTNS,'alphabetical-index'): ( (TEXTNS,'name'), ), (TEXTNS,'alphabetical-index-auto-mark-file'): ( (XLINKNS,'href'), ), (TEXTNS,'alphabetical-index-entry-template'): ( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), (TEXTNS,'alphabetical-index-mark'): ( (TEXTNS,'string-value'), ), (TEXTNS,'alphabetical-index-mark-end'): ( (TEXTNS,'id'), ), (TEXTNS,'alphabetical-index-mark-start'): ( (TEXTNS,'id'), ), (TEXTNS,'bibliography'): ( (TEXTNS,'name'), ), (TEXTNS,'bibliography-entry-template'): ( (TEXTNS,'style-name'), (TEXTNS,'bibliography-type'), ), (TEXTNS,'bibliography-mark'): ( (TEXTNS,'bibliography-type'), ), (TEXTNS,'bookmark'): ( (TEXTNS,'name'), ), # required_attributes (TEXTNS,'bookmark-end'): ( (TEXTNS,'name'), ), (TEXTNS,'bookmark-start'): ( (TEXTNS,'name'), ), (TEXTNS,'change'): ( (TEXTNS,'change-id'), ), (TEXTNS,'change-end'): ( (TEXTNS,'change-id'), ), (TEXTNS,'change-start'): ( (TEXTNS,'change-id'), ), (TEXTNS,'changed-region'): ( (TEXTNS,'id'), ), (TEXTNS,'chapter'): ( (TEXTNS,'display'), (TEXTNS,'outline-level'), ), (TEXTNS,'conditional-text'): ( (TEXTNS,'string-value-if-true'), (TEXTNS,'string-value-if-false'), (TEXTNS,'condition'), ), (TEXTNS,'database-display'): ( (TEXTNS,'column-name'), (TEXTNS,'table-name'), ), (TEXTNS,'database-name'): ( (TEXTNS,'table-name'), ), (TEXTNS,'database-next'): ( (TEXTNS,'table-name'), ), (TEXTNS,'database-row-number'): ( (TEXTNS,'table-name'), ), (TEXTNS,'database-row-select'): ( (TEXTNS,'table-name'), ), (TEXTNS,'dde-connection'): ( (TEXTNS,'connection-name'), ), # required_attributes (TEXTNS,'dde-connection-decl'): ( (OFFICENS,'dde-topic'), (OFFICENS,'dde-application'), (OFFICENS,'name'), (OFFICENS,'dde-item'), ), (TEXTNS,'h'): ( (TEXTNS,'outline-level'), ), (TEXTNS,'hidden-paragraph'): ( (TEXTNS,'condition'), ), (TEXTNS,'hidden-text'): ( (TEXTNS,'string-value'), (TEXTNS,'condition'), ), (TEXTNS,'illustration-index'): ( (TEXTNS,'name'), ), (TEXTNS,'illustration-index-entry-template'): ( (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-bibliography'): ( (TEXTNS,'bibliography-data-field'), ), (TEXTNS,'index-source-style'): ( (TEXTNS,'style-name'), ), (TEXTNS,'index-source-styles'): ( (TEXTNS,'outline-level'), ), (TEXTNS,'index-title'): ( (TEXTNS,'name'), ), (TEXTNS,'list-level-style-bullet'): ( (TEXTNS,'bullet-char'), (TEXTNS,'level'), ), (TEXTNS,'list-level-style-image'): ( (TEXTNS,'level'), ), (TEXTNS,'list-level-style-number'): ( (TEXTNS,'level'), ), (TEXTNS,'list-style'): ( (STYLENS,'name'), ), # required_attributes (TEXTNS,'measure'): ( (TEXTNS,'kind'), ), (TEXTNS,'note'): ( (TEXTNS,'note-class'), ), (TEXTNS,'note-ref'): ( (TEXTNS,'note-class'), ), (TEXTNS,'notes-configuration'): ( (TEXTNS,'note-class'), ), (TEXTNS,'object-index'): ( (TEXTNS,'name'), ), (TEXTNS,'object-index-entry-template'): ( (TEXTNS,'style-name'), ), (TEXTNS,'outline-level-style'): ( (TEXTNS,'level'), ), (TEXTNS,'page'): ( (TEXTNS,'master-page-name'), ), (TEXTNS,'page-continuation'): ( (TEXTNS,'select-page'), ), (TEXTNS,'placeholder'): ( (TEXTNS,'placeholder-type'), ), (TEXTNS,'reference-mark'): ( (TEXTNS,'name'), ), (TEXTNS,'reference-mark-end'): ( (TEXTNS,'name'), ), (TEXTNS,'reference-mark-start'): ( (TEXTNS,'name'), ), (TEXTNS,'section'): ( (TEXTNS,'name'), ), (TEXTNS,'sequence'): ( (TEXTNS,'name'), ), (TEXTNS,'sequence-decl'): ( (TEXTNS,'display-outline-level'), (TEXTNS,'name'), ), # required_attributes (TEXTNS,'sort-key'): ( (TEXTNS,'key'), ), (TEXTNS,'table-index'): ( (TEXTNS,'name'), ), (TEXTNS,'table-index-entry-template'): ( (TEXTNS,'style-name'), ), (TEXTNS,'table-of-content'): ( (TEXTNS,'name'), ), (TEXTNS,'table-of-content-entry-template'): ( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), (TEXTNS,'toc-mark'): ( (TEXTNS,'string-value'), ), (TEXTNS,'toc-mark-end'): ( (TEXTNS,'id'), ), (TEXTNS,'toc-mark-start'): ( (TEXTNS,'id'), ), (TEXTNS,'user-defined'): ( (TEXTNS,'name'), ), (TEXTNS,'user-field-decl'): ( (TEXTNS,'name'), ), (TEXTNS,'user-field-get'): ( (TEXTNS,'name'), ), (TEXTNS,'user-field-input'): ( (TEXTNS,'name'), ), (TEXTNS,'user-index'): ( (TEXTNS,'name'), ), (TEXTNS,'user-index-entry-template'): ( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), # required_attributes (TEXTNS,'user-index-mark'): ( (TEXTNS,'index-name'), (TEXTNS,'string-value'), ), (TEXTNS,'user-index-mark-end'): ( (TEXTNS,'id'), ), (TEXTNS,'user-index-mark-start'): ( (TEXTNS,'index-name'), (TEXTNS,'id'), ), (TEXTNS,'user-index-source'): ( (TEXTNS,'index-name'), ), (TEXTNS,'variable-decl'): ( (TEXTNS,'name'), (OFFICENS,'value-type'), ), (TEXTNS,'variable-get'): ( (TEXTNS,'name'), ), (TEXTNS,'variable-input'): ( (TEXTNS,'name'), (OFFICENS,'value-type'), ), (TEXTNS,'variable-set'): ( (TEXTNS,'name'), ), } # Empty list means the element has no allowed attributes # None means anything goes allowed_attributes = { (DCNS,'creator'):( ), (DCNS,'date'):( ), (DCNS,'description'):( ), (DCNS,'language'):( ), (DCNS,'subject'):( ), (DCNS,'title'):( ), # Completes Dublin Core start # (DCNS,'contributor') : ( # ), # (DCNS,'coverage') : ( # ), # (DCNS,'format') : ( # ), # (DCNS,'identifier') : ( # ), # (DCNS,'publisher') : ( # ), # (DCNS,'relation') : ( # ), # (DCNS,'rights') : ( # ), # (DCNS,'source') : ( # ), # (DCNS,'type') : ( # ), # Completes Dublin Core end (MATHNS,'math'): None, (XFORMSNS,'model'): None, # allowed_attributes (ANIMNS,'animate'):( (ANIMNS,'formula'), (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'additive'), (SMILNS,'attributeName'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'by'), (SMILNS,'calcMode'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'from'), (SMILNS,'keySplines'), (SMILNS,'keyTimes'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), (SMILNS,'to'), (SMILNS,'values'), ), # allowed_attributes (ANIMNS,'animateColor'):( (ANIMNS,'color-interpolation'), (ANIMNS,'color-interpolation-direction'), (ANIMNS,'formula'), (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'additive'), (SMILNS,'attributeName'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'by'), (SMILNS,'calcMode'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'from'), (SMILNS,'keySplines'), (SMILNS,'keyTimes'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), (SMILNS,'to'), (SMILNS,'values'), ), # allowed_attributes (ANIMNS,'animateMotion'):( (ANIMNS,'formula'), (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'additive'), (SMILNS,'attributeName'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'by'), (SMILNS,'calcMode'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'from'), (SMILNS,'keySplines'), (SMILNS,'keyTimes'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), (SMILNS,'to'), (SMILNS,'values'), (SVGNS,'origin'), (SVGNS,'path'), ), # allowed_attributes (ANIMNS,'animateTransform'):( (ANIMNS,'formula'), (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'additive'), (SMILNS,'attributeName'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'by'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'from'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), (SMILNS,'to'), (SMILNS,'values'), (SVGNS,'type'), ), # allowed_attributes (ANIMNS,'audio'):( (ANIMNS,'audio-level'), (ANIMNS,'id'), (PRESENTATIONNS,'group-id'), (PRESENTATIONNS,'master-element'), (PRESENTATIONNS,'node-type'), (PRESENTATIONNS,'preset-class'), (PRESENTATIONNS,'preset-id'), (PRESENTATIONNS,'preset-sub-type'), (SMILNS,'begin'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (XLINKNS,'href'), ), (ANIMNS,'command'):( (PRESENTATIONNS,'node-type'), (SMILNS,'begin'), (SMILNS,'end'), (PRESENTATIONNS,'group-id'), (PRESENTATIONNS,'preset-class'), (PRESENTATIONNS,'preset-id'), (ANIMNS,'sub-item'), (ANIMNS,'command'), (PRESENTATIONNS,'preset-sub-type'), (SMILNS,'targetElement'), (ANIMNS,'id'), (PRESENTATIONNS,'master-element'), ), # allowed_attributes (ANIMNS,'iterate'):( (ANIMNS,'id'), (ANIMNS,'iterate-interval'), (ANIMNS,'iterate-type'), (ANIMNS,'sub-item'), (PRESENTATIONNS,'group-id'), (PRESENTATIONNS,'master-element'), (PRESENTATIONNS,'node-type'), (PRESENTATIONNS,'preset-class'), (PRESENTATIONNS,'preset-id'), (PRESENTATIONNS,'preset-sub-type'), (SMILNS,'accelerate'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'endsync'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), ), (ANIMNS,'par'):( (PRESENTATIONNS,'node-type'), (SMILNS,'decelerate'), (SMILNS,'begin'), (SMILNS,'end'), (PRESENTATIONNS,'group-id'), (SMILNS,'accelerate'), (SMILNS,'repeatDur'), (SMILNS,'repeatCount'), (SMILNS,'autoReverse'), (PRESENTATIONNS,'preset-class'), (SMILNS,'fillDefault'), (PRESENTATIONNS,'preset-id'), (PRESENTATIONNS,'preset-sub-type'), (SMILNS,'restartDefault'), (SMILNS,'endsync'), (SMILNS,'dur'), (SMILNS,'fill'), (ANIMNS,'id'), (SMILNS,'restart'), (PRESENTATIONNS,'master-element'), ), # allowed_attributes (ANIMNS,'param'):( (ANIMNS,'name'), (ANIMNS,'value'), ), (ANIMNS,'seq'):( (ANIMNS,'id'), (PRESENTATIONNS,'group-id'), (PRESENTATIONNS,'master-element'), (PRESENTATIONNS,'node-type'), (PRESENTATIONNS,'preset-class'), (PRESENTATIONNS,'preset-id'), (PRESENTATIONNS,'preset-sub-type'), (SMILNS,'accelerate'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'endsync'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), ), (ANIMNS,'set'):( (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'autoReverse'), (SMILNS,'additive'), (SMILNS,'attributeName'), (SMILNS,'begin'), (SMILNS,'decelerate'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'targetElement'), (SMILNS,'to'), ), # allowed_attributes (ANIMNS,'transitionFilter'):( (ANIMNS,'formula'), (ANIMNS,'sub-item'), (SMILNS,'accelerate'), (SMILNS,'accumulate'), (SMILNS,'additive'), (SMILNS,'autoReverse'), (SMILNS,'begin'), (SMILNS,'by'), (SMILNS,'calcMode'), (SMILNS,'decelerate'), (SMILNS,'direction'), (SMILNS,'dur'), (SMILNS,'end'), (SMILNS,'fadeColor'), (SMILNS,'fill'), (SMILNS,'fillDefault'), (SMILNS,'from'), (SMILNS,'mode'), (SMILNS,'repeatCount'), (SMILNS,'repeatDur'), (SMILNS,'restart'), (SMILNS,'restartDefault'), (SMILNS,'subtype'), (SMILNS,'targetElement'), (SMILNS,'to'), (SMILNS,'type'), (SMILNS,'values'), ), # allowed_attributes (CHARTNS,'axis'):( (CHARTNS,'style-name'), (CHARTNS,'dimension'), (CHARTNS,'name'), ), (CHARTNS,'categories'):( (TABLENS,'cell-range-address'), ), (CHARTNS,'chart'):( (CHARTNS,'column-mapping'), (CHARTNS,'row-mapping'), (SVGNS,'height'), (SVGNS,'width'), (CHARTNS,'style-name'), (CHARTNS,'class'), ), (CHARTNS,'data-point'):( (CHARTNS,'repeated'), (CHARTNS,'style-name'), ), (CHARTNS,'domain'):( (TABLENS,'cell-range-address'), ), (CHARTNS,'error-indicator'):( (CHARTNS,'style-name'), ), (CHARTNS,'floor'):( (SVGNS,'width'), (CHARTNS,'style-name'), ), # allowed_attributes (CHARTNS,'footer'):( (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'cell-range'), (CHARTNS,'style-name'), ), (CHARTNS,'grid'):( (CHARTNS,'style-name'), (CHARTNS,'class'), ), (CHARTNS,'legend'):( (CHARTNS,'legend-align'), (STYLENS,'legend-expansion-aspect-ratio'), (STYLENS,'legend-expansion'), (CHARTNS,'legend-position'), (CHARTNS,'style-name'), (SVGNS,'y'), (SVGNS,'x'), ), (CHARTNS,'mean-value'):( (CHARTNS,'style-name'), ), (CHARTNS,'plot-area'):( (DR3DNS,'ambient-color'), (DR3DNS,'distance'), (DR3DNS,'vrp'), (DR3DNS,'focal-length'), (CHARTNS,'data-source-has-labels'), (DR3DNS,'lighting-mode'), (DR3DNS,'shade-mode'), (DR3DNS,'transform'), (DR3DNS,'shadow-slant'), (SVGNS,'height'), (SVGNS,'width'), (CHARTNS,'style-name'), (DR3DNS,'vup'), (SVGNS,'y'), (SVGNS,'x'), (DR3DNS,'vpn'), (TABLENS,'cell-range-address'), (DR3DNS,'projection'), ), (CHARTNS,'regression-curve'):( (CHARTNS,'style-name'), ), (CHARTNS,'series'):( (CHARTNS,'style-name'), (CHARTNS,'attached-axis'), (CHARTNS,'values-cell-range-address'), (CHARTNS,'label-cell-address'), (CHARTNS,'class'), ), (CHARTNS,'stock-gain-marker'):( (CHARTNS,'style-name'), ), # allowed_attributes (CHARTNS,'stock-loss-marker'):( (CHARTNS,'style-name'), ), (CHARTNS,'stock-range-line'):( (CHARTNS,'style-name'), ), (CHARTNS,'subtitle'):( (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'cell-range'), (CHARTNS,'style-name'), ), (CHARTNS,'symbol-image'):( (XLINKNS,'href'), ), (CHARTNS,'title'):( (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'cell-range'), (CHARTNS,'style-name'), ), (CHARTNS,'wall'):( (SVGNS,'width'), (CHARTNS,'style-name'), ), (CONFIGNS,'config-item'):( (CONFIGNS,'type'), (CONFIGNS,'name'), ), (CONFIGNS,'config-item-map-entry'):( (CONFIGNS,'name'), ), (CONFIGNS,'config-item-map-indexed'):( (CONFIGNS,'name'), ), (CONFIGNS,'config-item-map-named'):( (CONFIGNS,'name'), ), (CONFIGNS,'config-item-set'):( (CONFIGNS,'name'), ), # allowed_attributes (NUMBERNS,'am-pm'):( ), (NUMBERNS,'boolean'):( ), (NUMBERNS,'boolean-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), ), (NUMBERNS,'currency-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), (NUMBERNS,'automatic-order'), ), (NUMBERNS,'currency-symbol'):( (NUMBERNS,'country'), (NUMBERNS,'language'), ), # allowed_attributes (NUMBERNS,'date-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (NUMBERNS,'format-source'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), (NUMBERNS,'automatic-order'), ), (NUMBERNS,'day'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), ), (NUMBERNS,'day-of-week'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), ), (NUMBERNS,'embedded-text'):( (NUMBERNS,'position'), ), (NUMBERNS,'era'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), ), (NUMBERNS,'fraction'):( (NUMBERNS,'grouping'), (NUMBERNS,'min-denominator-digits'), (NUMBERNS,'min-numerator-digits'), (NUMBERNS,'min-integer-digits'), (NUMBERNS,'denominator-value'), ), (NUMBERNS,'hours'):( (NUMBERNS,'style'), ), # allowed_attributes (NUMBERNS,'minutes'):( (NUMBERNS,'style'), ), (NUMBERNS,'month'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), (NUMBERNS,'possessive-form'), (NUMBERNS,'textual'), ), (NUMBERNS,'number'):( (NUMBERNS,'display-factor'), (NUMBERNS,'decimal-places'), (NUMBERNS,'decimal-replacement'), (NUMBERNS,'min-integer-digits'), (NUMBERNS,'grouping'), ), (NUMBERNS,'number-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), ), # allowed_attributes (NUMBERNS,'percentage-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), ), (NUMBERNS,'quarter'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), ), (NUMBERNS,'scientific-number'):( (NUMBERNS,'min-exponent-digits'), (NUMBERNS,'decimal-places'), (NUMBERNS,'min-integer-digits'), (NUMBERNS,'grouping'), ), (NUMBERNS,'seconds'):( (NUMBERNS,'style'), (NUMBERNS,'decimal-places'), ), (NUMBERNS,'text'):( ), (NUMBERNS,'text-content'):( ), (NUMBERNS,'text-style'):( (NUMBERNS,'transliteration-language'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'transliteration-format'), (NUMBERNS,'transliteration-style'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), ), (NUMBERNS,'time-style'):( (NUMBERNS,'transliteration-language'), (NUMBERNS,'transliteration-format'), (STYLENS,'name'), (STYLENS,'display-name'), (NUMBERNS,'language'), (NUMBERNS,'title'), (NUMBERNS,'country'), (NUMBERNS,'truncate-on-overflow'), (NUMBERNS,'transliteration-style'), (NUMBERNS,'format-source'), (STYLENS,'volatile'), (NUMBERNS,'transliteration-country'), ), (NUMBERNS,'week-of-year'):( (NUMBERNS,'calendar'), ), (NUMBERNS,'year'):( (NUMBERNS,'style'), (NUMBERNS,'calendar'), ), (DR3DNS,'cube'):( (DR3DNS,'min-edge'), (DR3DNS,'max-edge'), (DRAWNS,'layer'), (DR3DNS,'transform'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'id'), ), (DR3DNS,'extrude'):( (DRAWNS,'layer'), (SVGNS,'d'), (DR3DNS,'transform'), (SVGNS,'viewBox'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'id'), ), (DR3DNS,'light'):( (DR3DNS,'diffuse-color'), (DR3DNS,'direction'), (DR3DNS,'specular'), (DR3DNS,'enabled'), ), (DR3DNS,'rotate'):( (DRAWNS,'layer'), (SVGNS,'d'), (DR3DNS,'transform'), (SVGNS,'viewBox'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'id'), ), # allowed_attributes (DR3DNS,'scene'):( (DR3DNS,'ambient-color'), (DR3DNS,'distance'), (DR3DNS,'focal-length'), (DR3DNS,'lighting-mode'), (DR3DNS,'projection'), (DR3DNS,'shade-mode'), (DR3DNS,'shadow-slant'), (DR3DNS,'transform'), (DR3DNS,'vpn'), (DR3DNS,'vrp'), (DR3DNS,'vup'), (DRAWNS,'id'), (DRAWNS,'caption-id'), (DRAWNS,'layer'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'style-name'), (SVGNS,'height'), (SVGNS,'width'), (SVGNS,'x'), (SVGNS,'y'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), (DR3DNS,'sphere'):( (DRAWNS,'layer'), (DR3DNS,'center'), (DR3DNS,'transform'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'id'), (DR3DNS,'size'), ), (DRAWNS,'a'):( (OFFICENS,'name'), (OFFICENS,'title'), (XLINKNS,'show'), (OFFICENS,'target-frame-name'), (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (OFFICENS,'server-map'), ), (DRAWNS,'applet'):( (DRAWNS,'code'), (XLINKNS,'show'), (DRAWNS,'object'), (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (DRAWNS,'archive'), (DRAWNS,'may-script'), ), (DRAWNS,'area-circle'):( (OFFICENS,'name'), (XLINKNS,'show'), (SVGNS,'cx'), (XLINKNS,'type'), (DRAWNS,'nohref'), (SVGNS,'cy'), (XLINKNS,'href'), (SVGNS,'r'), (OFFICENS,'target-frame-name'), ), (DRAWNS,'area-polygon'):( (OFFICENS,'name'), (XLINKNS,'show'), (XLINKNS,'type'), (SVGNS,'height'), (DRAWNS,'nohref'), (SVGNS,'width'), (XLINKNS,'href'), (SVGNS,'y'), (SVGNS,'x'), (OFFICENS,'target-frame-name'), (SVGNS,'viewBox'), (DRAWNS,'points'), ), (DRAWNS,'area-rectangle'):( (OFFICENS,'name'), (XLINKNS,'show'), (XLINKNS,'type'), (SVGNS,'height'), (DRAWNS,'nohref'), (SVGNS,'width'), (XLINKNS,'href'), (SVGNS,'y'), (SVGNS,'x'), (OFFICENS,'target-frame-name'), ), (DRAWNS,'caption'):( (TABLENS,'table-background'), (DRAWNS,'layer'), (DRAWNS,'caption-id'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (DRAWNS,'caption-point-y'), (DRAWNS,'caption-point-x'), (DRAWNS,'transform'), (TABLENS,'end-y'), (DRAWNS,'corner-radius'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (SVGNS,'height'), (DRAWNS,'id'), (TEXTNS,'anchor-type'), ), (DRAWNS,'circle'):( (DRAWNS,'end-angle'), (DRAWNS,'id'), (DRAWNS,'kind'), (DRAWNS,'layer'), (DRAWNS,'name'), (DRAWNS,'start-angle'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (DRAWNS,'caption-id'), (DRAWNS,'text-style-name'), (DRAWNS,'transform'), (DRAWNS,'z-index'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'style-name'), (SVGNS,'cx'), (SVGNS,'cy'), (SVGNS,'height'), (SVGNS,'r'), (SVGNS,'width'), (SVGNS,'x'), (SVGNS,'y'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), (DRAWNS,'connector'):( (DRAWNS,'layer'), (DRAWNS,'end-shape'), (TEXTNS,'anchor-page-number'), (SVGNS,'y1'), (SVGNS,'y2'), (TABLENS,'table-background'), (TABLENS,'end-cell-address'), (DRAWNS,'transform'), (DRAWNS,'id'), (TABLENS,'end-y'), (TABLENS,'end-x'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'caption-id'), (DRAWNS,'type'), (DRAWNS,'start-shape'), (DRAWNS,'z-index'), (PRESENTATIONNS,'style-name'), (DRAWNS,'start-glue-point'), (SVGNS,'x2'), (SVGNS,'x1'), (TEXTNS,'anchor-type'), (DRAWNS,'line-skew'), (DRAWNS,'name'), (DRAWNS,'end-glue-point'), (DRAWNS,'text-style-name'), ), (DRAWNS,'contour-path'):( (SVGNS,'d'), (SVGNS,'width'), (DRAWNS,'recreate-on-edit'), (SVGNS,'viewBox'), (SVGNS,'height'), ), (DRAWNS,'contour-polygon'):( (SVGNS,'width'), (DRAWNS,'points'), (DRAWNS,'recreate-on-edit'), (SVGNS,'viewBox'), (SVGNS,'height'), ), (DRAWNS,'control'):( (DRAWNS,'control'), (DRAWNS,'layer'), (DRAWNS,'caption-id'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (TABLENS,'table-background'), (DRAWNS,'transform'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (DRAWNS,'id'), (TEXTNS,'anchor-type'), ), (DRAWNS,'custom-shape'):( (DRAWNS,'engine'), (DRAWNS,'caption-id'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (TABLENS,'table-background'), (DRAWNS,'transform'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (DRAWNS,'data'), (DRAWNS,'id'), (TEXTNS,'anchor-type'), ), # allowed_attributes (DRAWNS,'ellipse'):( (DRAWNS,'layer'), (DRAWNS,'start-angle'), (SVGNS,'cy'), (SVGNS,'cx'), (TABLENS,'table-background'), (TABLENS,'end-cell-address'), (SVGNS,'rx'), (DRAWNS,'transform'), (DRAWNS,'id'), (SVGNS,'width'), (TABLENS,'end-y'), (TABLENS,'end-x'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (DRAWNS,'end-angle'), (DRAWNS,'z-index'), (DRAWNS,'caption-id'), (PRESENTATIONNS,'style-name'), (SVGNS,'height'), (TEXTNS,'anchor-type'), (SVGNS,'ry'), (DRAWNS,'kind'), (DRAWNS,'name'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (DRAWNS,'text-style-name'), ), # allowed_attributes (DRAWNS,'enhanced-geometry'):( (DRAWNS,'extrusion-rotation-center'), (DRAWNS,'extrusion-shininess'), (DRAWNS,'extrusion-rotation-angle'), (DRAWNS,'extrusion-allowed'), (DRAWNS,'extrusion-first-light-level'), (DRAWNS,'extrusion-specularity'), (DRAWNS,'extrusion-viewpoint'), (DRAWNS,'extrusion-second-light-level'), (DRAWNS,'extrusion-origin'), (DRAWNS,'extrusion-color'), (SVGNS,'viewBox'), (DR3DNS,'projection'), (DRAWNS,'extrusion-metal'), (DRAWNS,'extrusion-number-of-line-segments'), (DRAWNS,'text-path-same-letter-heights'), (DRAWNS,'extrusion-first-light-harsh'), (DRAWNS,'enhanced-path'), (DRAWNS,'text-rotate-angle'), (DRAWNS,'type'), (DRAWNS,'glue-point-leaving-directions'), (DRAWNS,'concentric-gradient-fill-allowed'), (DRAWNS,'text-path-scale'), (DRAWNS,'extrusion-brightness'), (DRAWNS,'extrusion-first-light-direction'), (DRAWNS,'extrusion-light-face'), (DRAWNS,'text-path-allowed'), (DRAWNS,'glue-points'), (DRAWNS,'mirror-vertical'), (DRAWNS,'extrusion-depth'), (DRAWNS,'extrusion-diffusion'), (DRAWNS,'extrusion-second-light-direction'), (DRAWNS,'extrusion-skew'), (DR3DNS,'shade-mode'), (DRAWNS,'path-stretchpoint-y'), (DRAWNS,'modifiers'), (DRAWNS,'extrusion'), (DRAWNS,'path-stretchpoint-x'), (DRAWNS,'text-areas'), (DRAWNS,'mirror-horizontal'), (DRAWNS,'text-path-mode'), (DRAWNS,'extrusion-second-light-harsh'), (DRAWNS,'glue-point-type'), (DRAWNS,'text-path'), ), # allowed_attributes (DRAWNS,'equation'):( (DRAWNS,'formula'), (DRAWNS,'name'), ), (DRAWNS,'fill-image'):( (DRAWNS,'name'), (XLINKNS,'show'), (XLINKNS,'actuate'), (SVGNS,'height'), (SVGNS,'width'), (XLINKNS,'href'), (DRAWNS,'display-name'), (XLINKNS,'type'), ), (DRAWNS,'floating-frame'):( (XLINKNS,'href'), (XLINKNS,'actuate'), (DRAWNS,'frame-name'), (XLINKNS,'type'), (XLINKNS,'show'), ), (DRAWNS,'frame'):( (DRAWNS,'copy-of'), (DRAWNS,'id'), (DRAWNS,'layer'), (DRAWNS,'name'), (DRAWNS,'class-names'), (DRAWNS,'caption-id'), (DRAWNS,'style-name'), (DRAWNS,'text-style-name'), (DRAWNS,'transform'), (DRAWNS,'z-index'), (PRESENTATIONNS,'class'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'placeholder'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'user-transformed'), (STYLENS,'rel-height'), (STYLENS,'rel-width'), (SVGNS,'height'), (SVGNS,'width'), (SVGNS,'x'), (SVGNS,'y'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), # allowed_attributes (DRAWNS,'g'):( (DRAWNS,'id'), (DRAWNS,'caption-id'), (DRAWNS,'name'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (DRAWNS,'z-index'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'style-name'), (SVGNS,'y'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), (DRAWNS,'glue-point'):( (SVGNS,'y'), (SVGNS,'x'), (DRAWNS,'align'), (DRAWNS,'id'), (DRAWNS,'escape-direction'), ), (DRAWNS,'gradient'):( (DRAWNS,'style'), (DRAWNS,'angle'), (DRAWNS,'name'), (DRAWNS,'end-color'), (DRAWNS,'start-color'), (DRAWNS,'cy'), (DRAWNS,'cx'), (DRAWNS,'display-name'), (DRAWNS,'border'), (DRAWNS,'end-intensity'), (DRAWNS,'start-intensity'), ), (DRAWNS,'handle'):( (DRAWNS,'handle-radius-range-minimum'), (DRAWNS,'handle-switched'), (DRAWNS,'handle-range-y-maximum'), (DRAWNS,'handle-mirror-horizontal'), (DRAWNS,'handle-range-x-maximum'), (DRAWNS,'handle-mirror-vertical'), (DRAWNS,'handle-range-y-minimum'), (DRAWNS,'handle-radius-range-maximum'), (DRAWNS,'handle-range-x-minimum'), (DRAWNS,'handle-position'), (DRAWNS,'handle-polar'), ), (DRAWNS,'hatch'):( (DRAWNS,'distance'), (DRAWNS,'style'), (DRAWNS,'name'), (DRAWNS,'color'), (DRAWNS,'display-name'), (DRAWNS,'rotation'), ), (DRAWNS,'image'):( (DRAWNS,'filter-name'), (XLINKNS,'href'), (XLINKNS,'type'), (XLINKNS,'actuate'), (XLINKNS,'show'), ), (DRAWNS,'image-map'):( ), (DRAWNS,'layer'):( (DRAWNS,'protected'), (DRAWNS,'name'), (DRAWNS,'display'), ), # allowed_attributes (DRAWNS,'layer-set'):( ), (DRAWNS,'line'):( (DRAWNS,'class-names'), (DRAWNS,'id'), (DRAWNS,'caption-id'), (DRAWNS,'layer'), (DRAWNS,'name'), (DRAWNS,'style-name'), (DRAWNS,'text-style-name'), (DRAWNS,'transform'), (DRAWNS,'z-index'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'style-name'), (SVGNS,'x1'), (SVGNS,'x2'), (SVGNS,'y1'), (SVGNS,'y2'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), (DRAWNS,'marker'):( (SVGNS,'d'), (DRAWNS,'display-name'), (DRAWNS,'name'), (SVGNS,'viewBox'), ), # allowed_attributes (DRAWNS,'measure'):( (TABLENS,'end-cell-address'), (DRAWNS,'layer'), (SVGNS,'y2'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (DRAWNS,'transform'), (TABLENS,'table-background'), (SVGNS,'x2'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y1'), (DRAWNS,'caption-id'), (TABLENS,'end-y'), (SVGNS,'x1'), (DRAWNS,'id'), (TEXTNS,'anchor-type'), ), (DRAWNS,'object'):( (XLINKNS,'type'), (XLINKNS,'href'), (DRAWNS,'notify-on-update-of-ranges'), (XLINKNS,'actuate'), (XLINKNS,'show'), ), (DRAWNS,'object-ole'):( (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (DRAWNS,'class-id'), (XLINKNS,'show'), ), (DRAWNS,'opacity'):( (DRAWNS,'style'), (DRAWNS,'angle'), (DRAWNS,'name'), (DRAWNS,'start'), (DRAWNS,'cy'), (DRAWNS,'cx'), (DRAWNS,'end'), (DRAWNS,'display-name'), (DRAWNS,'border'), ), (DRAWNS,'page'):( (PRESENTATIONNS,'presentation-page-layout-name'), (DRAWNS,'name'), (DRAWNS,'nav-order'), (PRESENTATIONNS,'use-footer-name'), (DRAWNS,'style-name'), (PRESENTATIONNS,'use-header-name'), (DRAWNS,'master-page-name'), (DRAWNS,'id'), (PRESENTATIONNS,'use-date-time-name'), ), (DRAWNS,'page-thumbnail'):( (TABLENS,'table-background'), (DRAWNS,'caption-id'), (PRESENTATIONNS,'user-transformed'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'id'), (DRAWNS,'transform'), (DRAWNS,'page-number'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (PRESENTATIONNS,'placeholder'), (PRESENTATIONNS,'class'), (TEXTNS,'anchor-type'), ), (DRAWNS,'param'):( (DRAWNS,'name'), (DRAWNS,'value'), ), # allowed_attributes (DRAWNS,'path'):( (TABLENS,'table-background'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'caption-id'), (SVGNS,'d'), (DRAWNS,'text-style-name'), (DRAWNS,'id'), (DRAWNS,'transform'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-type'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (SVGNS,'viewBox'), (DRAWNS,'name'), ), (DRAWNS,'plugin'):( (XLINKNS,'type'), (XLINKNS,'href'), (DRAWNS,'mime-type'), (XLINKNS,'actuate'), (XLINKNS,'show'), ), (DRAWNS,'polygon'):( (DRAWNS,'caption-id'), (TABLENS,'table-background'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (DRAWNS,'id'), (DRAWNS,'transform'), (PRESENTATIONNS,'style-name'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'points'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (SVGNS,'viewBox'), (TEXTNS,'anchor-type'), ), # allowed_attributes (DRAWNS,'polyline'):( (TABLENS,'table-background'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (DRAWNS,'id'), (DRAWNS,'caption-id'), (DRAWNS,'transform'), (PRESENTATIONNS,'style-name'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'points'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (TEXTNS,'anchor-page-number'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (SVGNS,'viewBox'), (TEXTNS,'anchor-type'), ), (DRAWNS,'rect'):( (DRAWNS,'corner-radius'), (DRAWNS,'caption-id'), (DRAWNS,'id'), (DRAWNS,'layer'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (DRAWNS,'transform'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (PRESENTATIONNS,'style-name'), (SVGNS,'height'), (SVGNS,'width'), (SVGNS,'x'), (SVGNS,'y'), (TABLENS,'end-cell-address'), (TABLENS,'end-x'), (TABLENS,'end-y'), (TABLENS,'table-background'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), ), # allowed_attributes (DRAWNS,'regular-polygon'):( (TABLENS,'table-background'), (DRAWNS,'layer'), (TABLENS,'end-cell-address'), (DRAWNS,'caption-id'), (DRAWNS,'name'), (DRAWNS,'text-style-name'), (TEXTNS,'anchor-page-number'), (DRAWNS,'concave'), (DRAWNS,'sharpness'), (DRAWNS,'transform'), (SVGNS,'height'), (SVGNS,'width'), (DRAWNS,'z-index'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (DRAWNS,'corners'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (DRAWNS,'id'), (TEXTNS,'anchor-type'), ), (DRAWNS,'stroke-dash'):( (DRAWNS,'distance'), (DRAWNS,'dots1-length'), (DRAWNS,'name'), (DRAWNS,'dots2-length'), (DRAWNS,'style'), (DRAWNS,'dots1'), (DRAWNS,'display-name'), (DRAWNS,'dots2'), ), (DRAWNS,'text-box'):( (FONS,'min-width'), (DRAWNS,'corner-radius'), (FONS,'max-height'), (FONS,'min-height'), (DRAWNS,'chain-next-name'), (FONS,'max-width'), (TEXTNS,'id'), ), # allowed_attributes (FORMNS,'button'):( (FORMNS,'tab-stop'), (FORMNS,'focus-on-click'), (FORMNS,'image-align'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'button-type'), (FORMNS,'title'), (FORMNS,'default-button'), (FORMNS,'value'), (FORMNS,'label'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'image-data'), (XLINKNS,'href'), (FORMNS,'toggle'), (FORMNS,'xforms-submission'), (OFFICENS,'target-frame'), (FORMNS,'id'), (FORMNS,'image-position'), ), (FORMNS,'checkbox'):( (FORMNS,'tab-stop'), (FORMNS,'image-align'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'title'), (FORMNS,'is-tristate'), (FORMNS,'current-state'), (FORMNS,'value'), (FORMNS,'label'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'state'), (FORMNS,'visual-effect'), (FORMNS,'id'), (FORMNS,'image-position'), ), (FORMNS,'column'):( (FORMNS,'control-implementation'), (FORMNS,'text-style-name'), (FORMNS,'name'), (FORMNS,'label'), ), (FORMNS,'combobox'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'dropdown'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'tab-index'), (FORMNS,'auto-complete'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (FORMNS,'list-source'), (FORMNS,'title'), (FORMNS,'list-source-type'), (FORMNS,'id'), (FORMNS,'current-value'), (FORMNS,'size'), ), # allowed_attributes (FORMNS,'connection-resource'):( (XLINKNS,'href'), ), (FORMNS,'date'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (FORMNS,'min-value'), (FORMNS,'data-field'), (FORMNS,'max-value'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'file'):( (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'fixed-text'):( (FORMNS,'name'), (FORMNS,'for'), (FORMNS,'title'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'multi-line'), (FORMNS,'label'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'id'), ), # allowed_attributes (FORMNS,'form'):( (XLINKNS,'actuate'), (XLINKNS,'href'), (FORMNS,'allow-deletes'), (FORMNS,'command-type'), (FORMNS,'apply-filter'), (XLINKNS,'type'), (FORMNS,'method'), (OFFICENS,'target-frame'), (FORMNS,'navigation-mode'), (FORMNS,'detail-fields'), (FORMNS,'master-fields'), (FORMNS,'allow-updates'), (FORMNS,'name'), (FORMNS,'tab-cycle'), (FORMNS,'control-implementation'), (FORMNS,'escape-processing'), (FORMNS,'filter'), (FORMNS,'command'), (FORMNS,'datasource'), (FORMNS,'enctype'), (FORMNS,'allow-inserts'), (FORMNS,'ignore-result'), (FORMNS,'order'), ), (FORMNS,'formatted-text'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'max-value'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (FORMNS,'min-value'), (FORMNS,'validation'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'frame'):( (FORMNS,'name'), (FORMNS,'for'), (FORMNS,'title'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'label'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'id'), ), # allowed_attributes (FORMNS,'generic-control'):( (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'name'), (FORMNS,'id'), ), (FORMNS,'grid'):( (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'id'), ), (FORMNS,'hidden'):( (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'name'), (FORMNS,'value'), (FORMNS,'id'), ), (FORMNS,'image'):( (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'button-type'), (FORMNS,'title'), (FORMNS,'value'), (OFFICENS,'target-frame'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'image-data'), (XLINKNS,'href'), (FORMNS,'id'), ), (FORMNS,'image-frame'):( (FORMNS,'name'), (FORMNS,'title'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'readonly'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'image-data'), (FORMNS,'id'), ), (FORMNS,'item'):( (FORMNS,'label'), ), (FORMNS,'list-property'):( (FORMNS,'property-name'), (OFFICENS,'value-type'), ), (FORMNS,'list-value'):( (OFFICENS,'string-value'), ), # allowed_attributes (FORMNS,'listbox'):( (FORMNS,'tab-stop'), (FORMNS,'bound-column'), (FORMNS,'multiple'), (FORMNS,'name'), (FORMNS,'dropdown'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'tab-index'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'list-source'), (FORMNS,'title'), (FORMNS,'list-source-type'), (FORMNS,'id'), (FORMNS,'xforms-list-source'), (FORMNS,'size'), ), (FORMNS,'number'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (FORMNS,'min-value'), (FORMNS,'data-field'), (FORMNS,'max-value'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'option'):( (FORMNS,'current-selected'), (FORMNS,'selected'), (FORMNS,'value'), (FORMNS,'label'), ), (FORMNS,'password'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'echo-char'), (FORMNS,'id'), ), (FORMNS,'properties'):( ), (FORMNS,'property'):( (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (FORMNS,'property-name'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (OFFICENS,'value-type'), (OFFICENS,'time-value'), ), (FORMNS,'radio'):( (FORMNS,'tab-stop'), (FORMNS,'selected'), (FORMNS,'image-align'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'current-selected'), (FORMNS,'value'), (FORMNS,'label'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'title'), (FORMNS,'visual-effect'), (FORMNS,'id'), (FORMNS,'image-position'), ), (FORMNS,'text'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'textarea'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'data-field'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'time'):( (FORMNS,'convert-empty-to-null'), (FORMNS,'max-length'), (FORMNS,'tab-stop'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (FORMNS,'min-value'), (FORMNS,'data-field'), (FORMNS,'max-value'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'readonly'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'id'), (FORMNS,'current-value'), ), (FORMNS,'value-range'):( (FORMNS,'tab-stop'), (FORMNS,'max-value'), (FORMNS,'name'), (FORMNS,'tab-index'), (FORMNS,'control-implementation'), (XFORMSNS,'bind'), (FORMNS,'title'), (FORMNS,'value'), (FORMNS,'disabled'), (FORMNS,'printable'), (FORMNS,'orientation'), (FORMNS,'page-step-size'), (FORMNS,'delay-for-repeat'), (FORMNS,'min-value'), (FORMNS,'id'), (FORMNS,'step-size'), ), (MANIFESTNS,'algorithm') : ( (MANIFESTNS,'algorithm-name'), (MANIFESTNS,'initialisation-vector'), ), (MANIFESTNS,'encryption-data') : ( (MANIFESTNS,'checksum-type'), (MANIFESTNS,'checksum'), ), (MANIFESTNS,'file-entry') : ( (MANIFESTNS,'full-path'), (MANIFESTNS,'media-type'), (MANIFESTNS,'size'), ), (MANIFESTNS,'key-derivation') : ( (MANIFESTNS,'key-derivation-name'), (MANIFESTNS,'salt'), (MANIFESTNS,'iteration-count'), ), (MANIFESTNS,'manifest'):( ), # allowed_attributes (METANS,'auto-reload'):( (METANS,'delay'), (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (XLINKNS,'show'), ), (METANS,'creation-date'):( ), (METANS,'date-string'):( ), (METANS,'document-statistic'):( (METANS,'non-whitespace-character-count'), (METANS,'ole-object-count'), (METANS,'table-count'), (METANS,'row-count'), (METANS,'character-count'), (METANS,'sentence-count'), (METANS,'draw-count'), (METANS,'paragraph-count'), (METANS,'word-count'), (METANS,'object-count'), (METANS,'syllable-count'), (METANS,'image-count'), (METANS,'page-count'), (METANS,'frame-count'), (METANS,'cell-count'), ), (METANS,'editing-cycles'):( ), (METANS,'editing-duration'):( ), (METANS,'generator'):( ), # allowed_attributes (METANS,'hyperlink-behaviour'):( (OFFICENS,'target-frame-name'), (XLINKNS,'show'), ), (METANS,'initial-creator'):( ), (METANS,'keyword'):( ), (METANS,'print-date'):( ), (METANS,'printed-by'):( ), (METANS,'template'):( (METANS,'date'), (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (XLINKNS,'title'), ), (METANS,'user-defined'):( (METANS,'name'), (METANS,'value-type'), ), (OFFICENS,'annotation'):( (DRAWNS,'layer'), (SVGNS,'height'), (TEXTNS,'anchor-page-number'), (TABLENS,'table-background'), (TABLENS,'end-cell-address'), (DRAWNS,'transform'), (DRAWNS,'id'), (SVGNS,'width'), (DRAWNS,'class-names'), (DRAWNS,'style-name'), (PRESENTATIONNS,'class-names'), (TABLENS,'end-x'), (DRAWNS,'text-style-name'), (DRAWNS,'z-index'), (PRESENTATIONNS,'style-name'), (TEXTNS,'anchor-type'), (DRAWNS,'name'), (DRAWNS,'caption-point-y'), (DRAWNS,'caption-point-x'), (DRAWNS,'corner-radius'), (SVGNS,'y'), (SVGNS,'x'), (TABLENS,'end-y'), (OFFICENS,'display'), ), (OFFICENS,'automatic-styles'):( ), (OFFICENS,'binary-data'):( ), (OFFICENS,'body'):( ), (OFFICENS,'change-info'):( ), (OFFICENS,'chart'):( ), (OFFICENS,'dde-source'):( (OFFICENS,'dde-application'), (OFFICENS,'automatic-update'), (OFFICENS,'conversion-mode'), (OFFICENS,'dde-item'), (OFFICENS,'dde-topic'), (OFFICENS,'name'), ), (OFFICENS,'document'):( (OFFICENS,'mimetype'), (OFFICENS,'version'), ), (OFFICENS,'document-content'):( (OFFICENS,'version'), ), (OFFICENS,'document-meta'):( (OFFICENS,'version'), ), (OFFICENS,'document-settings'):( (OFFICENS,'version'), ), (OFFICENS,'document-styles'):( (OFFICENS,'version'), ), (OFFICENS,'drawing'):( ), (OFFICENS,'event-listeners'):( ), (OFFICENS,'font-face-decls'):( ), (OFFICENS,'forms'):( (FORMNS,'automatic-focus'), (FORMNS,'apply-design-mode'), ), (OFFICENS,'image'):( ), # allowed_attributes (OFFICENS,'master-styles'):( ), (OFFICENS,'meta'):( ), (OFFICENS,'presentation'):( ), (OFFICENS,'script'):( (SCRIPTNS,'language'), ), (OFFICENS,'scripts'):( ), (OFFICENS,'settings'):( ), (OFFICENS,'spreadsheet'):( (TABLENS,'structure-protected'), (TABLENS,'protection-key'), ), (OFFICENS,'styles'):( ), (OFFICENS,'text'):( (TEXTNS,'global'), (TEXTNS,'use-soft-page-breaks'), ), (PRESENTATIONNS,'animation-group'):( ), (PRESENTATIONNS,'animations'):( ), (PRESENTATIONNS,'date-time'):( ), (PRESENTATIONNS,'date-time-decl'):( (PRESENTATIONNS,'source'), (STYLENS,'data-style-name'), (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'dim'):( (DRAWNS,'color'), (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'event-listener'):( (PRESENTATIONNS,'direction'), (XLINKNS,'show'), (XLINKNS,'type'), (XLINKNS,'actuate'), (PRESENTATIONNS,'effect'), (SCRIPTNS,'event-name'), (PRESENTATIONNS,'start-scale'), (XLINKNS,'href'), (PRESENTATIONNS,'verb'), (PRESENTATIONNS,'action'), (PRESENTATIONNS,'speed'), ), (PRESENTATIONNS,'footer'):( ), (PRESENTATIONNS,'footer-decl'):( (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'header'):( ), (PRESENTATIONNS,'header-decl'):( (PRESENTATIONNS,'name'), ), (PRESENTATIONNS,'hide-shape'):( (PRESENTATIONNS,'direction'), (PRESENTATIONNS,'effect'), (PRESENTATIONNS,'delay'), (PRESENTATIONNS,'start-scale'), (PRESENTATIONNS,'path-id'), (PRESENTATIONNS,'speed'), (DRAWNS,'shape-id'), ), # allowed_attributes (PRESENTATIONNS,'hide-text'):( (PRESENTATIONNS,'direction'), (PRESENTATIONNS,'effect'), (PRESENTATIONNS,'delay'), (PRESENTATIONNS,'start-scale'), (PRESENTATIONNS,'path-id'), (PRESENTATIONNS,'speed'), (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'notes'):( (STYLENS,'page-layout-name'), (DRAWNS,'style-name'), (PRESENTATIONNS,'use-header-name'), (PRESENTATIONNS,'use-date-time-name'), (PRESENTATIONNS,'use-footer-name'), ), (PRESENTATIONNS,'placeholder'):( (SVGNS,'y'), (SVGNS,'x'), (SVGNS,'height'), (PRESENTATIONNS,'object'), (SVGNS,'width'), ), (PRESENTATIONNS,'play'):( (PRESENTATIONNS,'speed'), (DRAWNS,'shape-id'), ), # allowed_attributes (PRESENTATIONNS,'settings'):( (PRESENTATIONNS,'animations'), (PRESENTATIONNS,'endless'), (PRESENTATIONNS,'force-manual'), (PRESENTATIONNS,'full-screen'), (PRESENTATIONNS,'mouse-as-pen'), (PRESENTATIONNS,'mouse-visible'), (PRESENTATIONNS,'pause'), (PRESENTATIONNS,'show'), (PRESENTATIONNS,'show-end-of-presentation-slide'), (PRESENTATIONNS,'show-logo'), (PRESENTATIONNS,'start-page'), (PRESENTATIONNS,'start-with-navigator'), (PRESENTATIONNS,'stay-on-top'), (PRESENTATIONNS,'transition-on-click'), ), (PRESENTATIONNS,'show'):( (PRESENTATIONNS,'name'), (PRESENTATIONNS,'pages'), ), (PRESENTATIONNS,'show-shape'):( (PRESENTATIONNS,'direction'), (PRESENTATIONNS,'effect'), (PRESENTATIONNS,'delay'), (PRESENTATIONNS,'start-scale'), (PRESENTATIONNS,'path-id'), (PRESENTATIONNS,'speed'), (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'show-text'):( (PRESENTATIONNS,'direction'), (PRESENTATIONNS,'effect'), (PRESENTATIONNS,'delay'), (PRESENTATIONNS,'start-scale'), (PRESENTATIONNS,'path-id'), (PRESENTATIONNS,'speed'), (DRAWNS,'shape-id'), ), (PRESENTATIONNS,'sound'):( (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (PRESENTATIONNS,'play-full'), (XLINKNS,'show'), ), # allowed_attributes (SCRIPTNS,'event-listener'):( (SCRIPTNS,'language'), (SCRIPTNS,'macro-name'), (XLINKNS,'actuate'), (SCRIPTNS,'event-name'), (XLINKNS,'href'), (XLINKNS,'type'), ), (STYLENS,'background-image'):( (DRAWNS,'opacity'), (STYLENS,'repeat'), (XLINKNS,'show'), (XLINKNS,'actuate'), (STYLENS,'filter-name'), (XLINKNS,'href'), (STYLENS,'position'), (XLINKNS,'type'), ), (STYLENS,'chart-properties'): ( (CHARTNS,'connect-bars'), (CHARTNS,'data-label-number'), (CHARTNS,'data-label-symbol'), (CHARTNS,'data-label-text'), (CHARTNS,'deep'), (CHARTNS,'display-label'), (CHARTNS,'error-category'), (CHARTNS,'error-lower-indicator'), (CHARTNS,'error-lower-limit'), (CHARTNS,'error-margin'), (CHARTNS,'error-percentage'), (CHARTNS,'error-upper-indicator'), (CHARTNS,'error-upper-limit'), (CHARTNS,'gap-width'), (CHARTNS,'interpolation'), (CHARTNS,'interval-major'), (CHARTNS,'interval-minor-divisor'), (CHARTNS,'japanese-candle-stick'), (CHARTNS,'label-arrangement'), (CHARTNS,'lines'), (CHARTNS,'link-data-style-to-source'), (CHARTNS,'logarithmic'), (CHARTNS,'maximum'), (CHARTNS,'mean-value'), (CHARTNS,'minimum'), (CHARTNS,'origin'), (CHARTNS,'overlap'), (CHARTNS,'percentage'), (CHARTNS,'pie-offset'), (CHARTNS,'regression-type'), (CHARTNS,'scale-text'), (CHARTNS,'series-source'), (CHARTNS,'solid-type'), (CHARTNS,'spline-order'), (CHARTNS,'spline-resolution'), (CHARTNS,'stacked'), (CHARTNS,'symbol-height'), (CHARTNS,'symbol-name'), (CHARTNS,'symbol-type'), (CHARTNS,'symbol-width'), (CHARTNS,'text-overlap'), (CHARTNS,'three-dimensional'), (CHARTNS,'tick-marks-major-inner'), (CHARTNS,'tick-marks-major-outer'), (CHARTNS,'tick-marks-minor-inner'), (CHARTNS,'tick-marks-minor-outer'), (CHARTNS,'vertical'), (CHARTNS,'visible'), (STYLENS,'direction'), (STYLENS,'rotation-angle'), (TEXTNS,'line-break'), ), (STYLENS,'column'):( (FONS,'end-indent'), (FONS,'space-before'), (FONS,'start-indent'), (FONS,'space-after'), (STYLENS,'rel-width'), ), (STYLENS,'column-sep'):( (STYLENS,'color'), (STYLENS,'width'), (STYLENS,'style'), (STYLENS,'vertical-align'), (STYLENS,'height'), ), (STYLENS,'columns'):( (FONS,'column-count'), (FONS,'column-gap'), ), (STYLENS,'default-style'):( (STYLENS,'family'), ), # allowed_attributes (STYLENS,'drawing-page-properties'): ( (DRAWNS,'fill'), (DRAWNS,'fill-color'), (DRAWNS,'secondary-fill-color'), (DRAWNS,'fill-gradient-name'), (DRAWNS,'gradient-step-count'), (DRAWNS,'fill-hatch-name'), (DRAWNS,'fill-hatch-solid'), (DRAWNS,'fill-image-name'), (STYLENS,'repeat'), (DRAWNS,'fill-image-width'), (DRAWNS,'fill-image-height'), (DRAWNS,'fill-image-ref-point-x'), (DRAWNS,'fill-image-ref-point-y'), (DRAWNS,'fill-image-ref-point'), (DRAWNS,'tile-repeat-offset'), (DRAWNS,'opacity'), (DRAWNS,'opacity-name'), (SVGNS,'fill-rule'), (PRESENTATIONNS,'transition-type'), (PRESENTATIONNS,'transition-style'), (PRESENTATIONNS,'transition-speed'), (SMILNS,'type'), (SMILNS,'subtype'), (SMILNS,'direction'), (SMILNS,'fadeColor'), (PRESENTATIONNS,'duration'), (PRESENTATIONNS,'visibility'), (DRAWNS,'background-size'), (PRESENTATIONNS,'background-objects-visible'), (PRESENTATIONNS,'background-visible'), (PRESENTATIONNS,'display-header'), (PRESENTATIONNS,'display-footer'), (PRESENTATIONNS,'display-page-number'), (PRESENTATIONNS,'display-date-time'), ), (STYLENS,'drop-cap'):( (STYLENS,'distance'), (STYLENS,'length'), (STYLENS,'style-name'), (STYLENS,'lines'), ), # allowed_attributes (STYLENS,'font-face'):( (STYLENS,'font-adornments'), (STYLENS,'font-charset'), (STYLENS,'font-family-generic'), (STYLENS,'font-pitch'), (STYLENS,'name'), (SVGNS,'accent-height'), (SVGNS,'alphabetic'), (SVGNS,'ascent'), (SVGNS,'bbox'), (SVGNS,'cap-height'), (SVGNS,'descent'), (SVGNS,'font-family'), (SVGNS,'font-size'), (SVGNS,'font-stretch'), (SVGNS,'font-style'), (SVGNS,'font-variant'), (SVGNS,'font-weight'), (SVGNS,'hanging'), (SVGNS,'ideographic'), (SVGNS,'mathematical'), (SVGNS,'overline-position'), (SVGNS,'overline-thickness'), (SVGNS,'panose-1'), (SVGNS,'slope'), (SVGNS,'stemh'), (SVGNS,'stemv'), (SVGNS,'strikethrough-position'), (SVGNS,'strikethrough-thickness'), (SVGNS,'underline-position'), (SVGNS,'underline-thickness'), (SVGNS,'unicode-range'), (SVGNS,'units-per-em'), (SVGNS,'v-alphabetic'), (SVGNS,'v-hanging'), (SVGNS,'v-ideographic'), (SVGNS,'v-mathematical'), (SVGNS,'widths'), (SVGNS,'x-height'), ), (STYLENS,'footer'):( (STYLENS,'display'), ), (STYLENS,'footer-left'):( (STYLENS,'display'), ), (STYLENS,'footer-style'):( ), (STYLENS,'footnote-sep'):( (STYLENS,'distance-after-sep'), (STYLENS,'color'), (STYLENS,'rel-width'), (STYLENS,'width'), (STYLENS,'distance-before-sep'), (STYLENS,'line-style'), (STYLENS,'adjustment'), ), # allowed_attributes (STYLENS,'graphic-properties'): ( (DR3DNS,'ambient-color'), (DR3DNS,'back-scale'), (DR3DNS,'backface-culling'), (DR3DNS,'close-back'), (DR3DNS,'close-front'), (DR3DNS,'depth'), (DR3DNS,'diffuse-color'), (DR3DNS,'edge-rounding'), (DR3DNS,'edge-rounding-mode'), (DR3DNS,'emissive-color'), (DR3DNS,'end-angle'), (DR3DNS,'horizontal-segments'), (DR3DNS,'lighting-mode'), (DR3DNS,'normals-direction'), (DR3DNS,'normals-kind'), (DR3DNS,'shadow'), (DR3DNS,'shininess'), (DR3DNS,'specular-color'), (DR3DNS,'texture-filter'), (DR3DNS,'texture-generation-mode-x'), (DR3DNS,'texture-generation-mode-y'), (DR3DNS,'texture-kind'), (DR3DNS,'texture-mode'), (DR3DNS,'vertical-segments'), (DRAWNS,'auto-grow-height'), (DRAWNS,'auto-grow-width'), (DRAWNS,'blue'), (DRAWNS,'caption-angle'), (DRAWNS,'caption-angle-type'), (DRAWNS,'caption-escape'), (DRAWNS,'caption-escape-direction'), (DRAWNS,'caption-fit-line-length'), (DRAWNS,'caption-gap'), (DRAWNS,'caption-line-length'), (DRAWNS,'caption-type'), (DRAWNS,'color-inversion'), (DRAWNS,'color-mode'), (DRAWNS,'contrast'), (DRAWNS,'decimal-places'), (DRAWNS,'end-guide'), (DRAWNS,'end-line-spacing-horizontal'), (DRAWNS,'end-line-spacing-vertical'), (DRAWNS,'fill'), (DRAWNS,'fill-color'), (DRAWNS,'fill-gradient-name'), (DRAWNS,'fill-hatch-name'), (DRAWNS,'fill-hatch-solid'), (DRAWNS,'fill-image-height'), (DRAWNS,'fill-image-name'), (DRAWNS,'fill-image-ref-point'), (DRAWNS,'fill-image-ref-point-x'), (DRAWNS,'fill-image-ref-point-y'), (DRAWNS,'fill-image-width'), # allowed_attributes (DRAWNS,'fit-to-contour'), (DRAWNS,'fit-to-size'), (DRAWNS,'frame-display-border'), (DRAWNS,'frame-display-scrollbar'), (DRAWNS,'frame-margin-horizontal'), (DRAWNS,'frame-margin-vertical'), (DRAWNS,'gamma'), (DRAWNS,'gradient-step-count'), (DRAWNS,'green'), (DRAWNS,'guide-distance'), (DRAWNS,'guide-overhang'), (DRAWNS,'image-opacity'), (DRAWNS,'line-distance'), (DRAWNS,'luminance'), (DRAWNS,'marker-end'), (DRAWNS,'marker-end-center'), (DRAWNS,'marker-end-width'), (DRAWNS,'marker-start'), (DRAWNS,'marker-start-center'), (DRAWNS,'marker-start-width'), (DRAWNS,'measure-align'), (DRAWNS,'measure-vertical-align'), (DRAWNS,'ole-draw-aspect'), (DRAWNS,'opacity'), (DRAWNS,'opacity-name'), (DRAWNS,'parallel'), (DRAWNS,'placing'), (DRAWNS,'red'), (DRAWNS,'secondary-fill-color'), (DRAWNS,'shadow'), (DRAWNS,'shadow-color'), (DRAWNS,'shadow-offset-x'), (DRAWNS,'shadow-offset-y'), (DRAWNS,'shadow-opacity'), (DRAWNS,'show-unit'), (DRAWNS,'start-guide'), (DRAWNS,'start-line-spacing-horizontal'), (DRAWNS,'start-line-spacing-vertical'), (DRAWNS,'stroke'), (DRAWNS,'stroke-dash'), (DRAWNS,'stroke-dash-names'), (DRAWNS,'stroke-linejoin'), (DRAWNS,'symbol-color'), (DRAWNS,'textarea-horizontal-align'), (DRAWNS,'textarea-vertical-align'), (DRAWNS,'tile-repeat-offset'), (DRAWNS,'unit'), (DRAWNS,'visible-area-height'), (DRAWNS,'visible-area-left'), (DRAWNS,'visible-area-top'), (DRAWNS,'visible-area-width'), (DRAWNS,'wrap-influence-on-position'), # allowed_attributes (FONS,'background-color'), (FONS,'border'), (FONS,'border-bottom'), (FONS,'border-left'), (FONS,'border-right'), (FONS,'border-top'), (FONS,'clip'), (FONS,'margin'), (FONS,'margin-bottom'), (FONS,'margin-left'), (FONS,'margin-right'), (FONS,'margin-top'), (FONS,'max-height'), (FONS,'max-width'), (FONS,'min-height'), (FONS,'min-width'), (FONS,'padding'), (FONS,'padding-bottom'), (FONS,'padding-left'), (FONS,'padding-right'), (FONS,'padding-top'), (FONS,'wrap-option'), (STYLENS,'border-line-width'), (STYLENS,'border-line-width-bottom'), (STYLENS,'border-line-width-left'), (STYLENS,'border-line-width-right'), (STYLENS,'border-line-width-top'), (STYLENS,'editable'), (STYLENS,'flow-with-text'), (STYLENS,'horizontal-pos'), (STYLENS,'horizontal-rel'), (STYLENS,'mirror'), (STYLENS,'number-wrapped-paragraphs'), (STYLENS,'overflow-behavior'), (STYLENS,'print-content'), (STYLENS,'protect'), (STYLENS,'rel-height'), (STYLENS,'rel-width'), (STYLENS,'repeat'), (STYLENS,'run-through'), (STYLENS,'shadow'), (STYLENS,'vertical-pos'), (STYLENS,'vertical-rel'), (STYLENS,'wrap'), (STYLENS,'wrap-contour'), (STYLENS,'wrap-contour-mode'), (STYLENS,'wrap-dynamic-threshold'), (STYLENS,'writing-mode'), (SVGNS,'fill-rule'), (SVGNS,'height'), (SVGNS,'stroke-color'), (SVGNS,'stroke-opacity'), (SVGNS,'stroke-width'), (SVGNS,'width'), (SVGNS,'x'), (SVGNS,'y'), (TEXTNS,'anchor-page-number'), (TEXTNS,'anchor-type'), (TEXTNS,'animation'), (TEXTNS,'animation-delay'), (TEXTNS,'animation-direction'), (TEXTNS,'animation-repeat'), (TEXTNS,'animation-start-inside'), (TEXTNS,'animation-steps'), (TEXTNS,'animation-stop-inside'), ), (STYLENS,'handout-master'):( (PRESENTATIONNS,'presentation-page-layout-name'), (STYLENS,'page-layout-name'), (PRESENTATIONNS,'use-footer-name'), (DRAWNS,'style-name'), (PRESENTATIONNS,'use-header-name'), (PRESENTATIONNS,'use-date-time-name'), ), # allowed_attributes (STYLENS,'header'):( (STYLENS,'display'), ), (STYLENS,'header-footer-properties'): ( (FONS,'background-color'), (FONS,'border'), (FONS,'border-bottom'), (FONS,'border-left'), (FONS,'border-right'), (FONS,'border-top'), (FONS,'margin'), (FONS,'margin-bottom'), (FONS,'margin-left'), (FONS,'margin-right'), (FONS,'margin-top'), (FONS,'min-height'), (FONS,'padding'), (FONS,'padding-bottom'), (FONS,'padding-left'), (FONS,'padding-right'), (FONS,'padding-top'), (STYLENS,'border-line-width'), (STYLENS,'border-line-width-bottom'), (STYLENS,'border-line-width-left'), (STYLENS,'border-line-width-right'), (STYLENS,'border-line-width-top'), (STYLENS,'dynamic-spacing'), (STYLENS,'shadow'), (SVGNS,'height'), ), (STYLENS,'header-left'):( (STYLENS,'display'), ), (STYLENS,'header-style'):( ), # allowed_attributes (STYLENS,'list-level-properties'): ( (FONS,'height'), (FONS,'text-align'), (FONS,'width'), (STYLENS,'font-name'), (STYLENS,'vertical-pos'), (STYLENS,'vertical-rel'), (SVGNS,'y'), (TEXTNS,'min-label-distance'), (TEXTNS,'min-label-width'), (TEXTNS,'space-before'), ), (STYLENS,'map'):( (STYLENS,'apply-style-name'), (STYLENS,'base-cell-address'), (STYLENS,'condition'), ), (STYLENS,'master-page'):( (STYLENS,'page-layout-name'), (STYLENS,'display-name'), (DRAWNS,'style-name'), (STYLENS,'name'), (STYLENS,'next-style-name'), ), (STYLENS,'page-layout'):( (STYLENS,'name'), (STYLENS,'page-usage'), ), # allowed_attributes (STYLENS,'page-layout-properties'): ( (FONS,'background-color'), (FONS,'border'), (FONS,'border-bottom'), (FONS,'border-left'), (FONS,'border-right'), (FONS,'border-top'), (FONS,'margin'), (FONS,'margin-bottom'), (FONS,'margin-left'), (FONS,'margin-right'), (FONS,'margin-top'), (FONS,'padding'), (FONS,'padding-bottom'), (FONS,'padding-left'), (FONS,'padding-right'), (FONS,'padding-top'), (FONS,'page-height'), (FONS,'page-width'), (STYLENS,'border-line-width'), (STYLENS,'border-line-width-bottom'), (STYLENS,'border-line-width-left'), (STYLENS,'border-line-width-right'), (STYLENS,'border-line-width-top'), (STYLENS,'first-page-number'), (STYLENS,'footnote-max-height'), (STYLENS,'layout-grid-base-height'), (STYLENS,'layout-grid-color'), (STYLENS,'layout-grid-display'), (STYLENS,'layout-grid-lines'), (STYLENS,'layout-grid-mode'), (STYLENS,'layout-grid-print'), (STYLENS,'layout-grid-ruby-below'), (STYLENS,'layout-grid-ruby-height'), (STYLENS,'num-format'), (STYLENS,'num-letter-sync'), (STYLENS,'num-prefix'), (STYLENS,'num-suffix'), (STYLENS,'paper-tray-name'), (STYLENS,'print'), (STYLENS,'print-orientation'), (STYLENS,'print-page-order'), (STYLENS,'register-truth-ref-style-name'), (STYLENS,'scale-to'), (STYLENS,'scale-to-pages'), (STYLENS,'shadow'), (STYLENS,'table-centering'), (STYLENS,'writing-mode'), ), # allowed_attributes (STYLENS,'paragraph-properties'): ( (FONS,'background-color'), (FONS,'border'), (FONS,'border-bottom'), (FONS,'border-left'), (FONS,'border-right'), (FONS,'border-top'), (FONS,'break-after'), (FONS,'break-before'), (FONS,'hyphenation-keep'), (FONS,'hyphenation-ladder-count'), (FONS,'keep-together'), (FONS,'keep-with-next'), (FONS,'line-height'), (FONS,'margin'), (FONS,'margin-bottom'), (FONS,'margin-left'), (FONS,'margin-right'), (FONS,'margin-top'), (FONS,'orphans'), (FONS,'padding'), (FONS,'padding-bottom'), (FONS,'padding-left'), (FONS,'padding-right'), (FONS,'padding-top'), (FONS,'text-align'), (FONS,'text-align-last'), (FONS,'text-indent'), (FONS,'widows'), (STYLENS,'auto-text-indent'), (STYLENS,'background-transparency'), (STYLENS,'border-line-width'), (STYLENS,'border-line-width-bottom'), (STYLENS,'border-line-width-left'), (STYLENS,'border-line-width-right'), (STYLENS,'border-line-width-top'), (STYLENS,'font-independent-line-spacing'), (STYLENS,'justify-single-word'), (STYLENS,'line-break'), (STYLENS,'line-height-at-least'), (STYLENS,'line-spacing'), (STYLENS,'page-number'), (STYLENS,'punctuation-wrap'), (STYLENS,'register-true'), (STYLENS,'shadow'), (STYLENS,'snap-to-layout-grid'), (STYLENS,'tab-stop-distance'), (STYLENS,'text-autospace'), (STYLENS,'vertical-align'), (STYLENS,'writing-mode'), (STYLENS,'writing-mode-automatic'), (TEXTNS,'line-number'), (TEXTNS,'number-lines'), ), (STYLENS,'presentation-page-layout'):( (STYLENS,'display-name'), (STYLENS,'name'), ), # allowed_attributes (STYLENS,'region-center'):( ), (STYLENS,'region-left'):( ), (STYLENS,'region-right'):( ), (STYLENS,'ruby-properties'): ( (STYLENS,'ruby-position'), (STYLENS,'ruby-align'), ), (STYLENS,'section-properties'): ( (FONS,'background-color'), (FONS,'margin-left'), (FONS,'margin-right'), (STYLENS,'protect'), (STYLENS,'writing-mode'), (TEXTNS,'dont-balance-text-columns'), ), (STYLENS,'style'):( (STYLENS,'family'), (STYLENS,'list-style-name'), (STYLENS,'name'), (STYLENS,'auto-update'), (STYLENS,'default-outline-level'), (STYLENS,'class'), (STYLENS,'next-style-name'), (STYLENS,'data-style-name'), (STYLENS,'master-page-name'), (STYLENS,'display-name'), (STYLENS,'parent-style-name'), ), # allowed_attributes (STYLENS,'tab-stop'):( (STYLENS,'leader-text-style'), (STYLENS,'leader-width'), (STYLENS,'leader-style'), (STYLENS,'char'), (STYLENS,'leader-color'), (STYLENS,'position'), (STYLENS,'leader-text'), (STYLENS,'type'), (STYLENS,'leader-type'), ), (STYLENS,'tab-stops'):( ), (STYLENS,'table-cell-properties'): ( (FONS,'background-color'), (FONS,'border'), (FONS,'border-bottom'), (FONS,'border-left'), (FONS,'border-right'), (FONS,'border-top'), (FONS,'padding'), (FONS,'padding-bottom'), (FONS,'padding-left'), (FONS,'padding-right'), (FONS,'padding-top'), (FONS,'wrap-option'), (STYLENS,'border-line-width'), (STYLENS,'border-line-width-bottom'), (STYLENS,'border-line-width-left'), (STYLENS,'border-line-width-right'), (STYLENS,'border-line-width-top'), (STYLENS,'cell-protect'), (STYLENS,'decimal-places'), (STYLENS,'diagonal-bl-tr'), (STYLENS,'diagonal-bl-tr-widths'), (STYLENS,'diagonal-tl-br'), (STYLENS,'diagonal-tl-br-widths'), (STYLENS,'direction'), (STYLENS,'glyph-orientation-vertical'), (STYLENS,'print-content'), (STYLENS,'repeat-content'), (STYLENS,'rotation-align'), (STYLENS,'rotation-angle'), (STYLENS,'shadow'), (STYLENS,'shrink-to-fit'), (STYLENS,'text-align-source'), (STYLENS,'vertical-align'), ), # allowed_attributes (STYLENS,'table-column-properties'): ( (FONS,'break-after'), (FONS,'break-before'), (STYLENS,'column-width'), (STYLENS,'rel-column-width'), (STYLENS,'use-optimal-column-width'), ), (STYLENS,'table-properties'): ( (FONS,'background-color'), (FONS,'break-after'), (FONS,'break-before'), (FONS,'keep-with-next'), (FONS,'margin'), (FONS,'margin-bottom'), (FONS,'margin-left'), (FONS,'margin-right'), (FONS,'margin-top'), (STYLENS,'may-break-between-rows'), (STYLENS,'page-number'), (STYLENS,'rel-width'), (STYLENS,'shadow'), (STYLENS,'width'), (STYLENS,'writing-mode'), (TABLENS,'align'), (TABLENS,'border-model'), (TABLENS,'display'), ), (STYLENS,'table-row-properties'): ( (FONS,'background-color'), (FONS,'break-after'), (FONS,'break-before'), (FONS,'keep-together'), (STYLENS,'min-row-height'), (STYLENS,'row-height'), (STYLENS,'use-optimal-row-height'), ), # allowed_attributes (STYLENS,'text-properties'): ( (FONS,'background-color'), (FONS,'color'), (FONS,'country'), (FONS,'font-family'), (FONS,'font-size'), (FONS,'font-style'), (FONS,'font-variant'), (FONS,'font-weight'), (FONS,'hyphenate'), (FONS,'hyphenation-push-char-count'), (FONS,'hyphenation-remain-char-count'), (FONS,'language'), (FONS,'letter-spacing'), (FONS,'text-shadow'), (FONS,'text-transform'), (STYLENS,'country-asian'), (STYLENS,'country-complex'), (STYLENS,'font-charset'), (STYLENS,'font-charset-asian'), (STYLENS,'font-charset-complex'), (STYLENS,'font-family-asian'), (STYLENS,'font-family-complex'), (STYLENS,'font-family-generic'), (STYLENS,'font-family-generic-asian'), (STYLENS,'font-family-generic-complex'), (STYLENS,'font-name'), (STYLENS,'font-name-asian'), (STYLENS,'font-name-complex'), (STYLENS,'font-pitch'), (STYLENS,'font-pitch-asian'), (STYLENS,'font-pitch-complex'), (STYLENS,'font-relief'), (STYLENS,'font-size-asian'), (STYLENS,'font-size-complex'), (STYLENS,'font-size-rel'), (STYLENS,'font-size-rel-asian'), (STYLENS,'font-size-rel-complex'), (STYLENS,'font-style-asian'), (STYLENS,'font-style-complex'), (STYLENS,'font-style-name'), (STYLENS,'font-style-name-asian'), (STYLENS,'font-style-name-complex'), (STYLENS,'font-weight-asian'), (STYLENS,'font-weight-complex'), (STYLENS,'language-asian'), (STYLENS,'language-complex'), (STYLENS,'letter-kerning'), (STYLENS,'script-type'), (STYLENS,'text-blinking'), (STYLENS,'text-combine'), (STYLENS,'text-combine-end-char'), (STYLENS,'text-combine-start-char'), (STYLENS,'text-emphasize'), (STYLENS,'text-line-through-color'), (STYLENS,'text-line-through-mode'), (STYLENS,'text-line-through-style'), (STYLENS,'text-line-through-text'), (STYLENS,'text-line-through-text-style'), (STYLENS,'text-line-through-type'), (STYLENS,'text-line-through-width'), (STYLENS,'text-outline'), (STYLENS,'text-position'), (STYLENS,'text-rotation-angle'), (STYLENS,'text-rotation-scale'), (STYLENS,'text-scale'), (STYLENS,'text-underline-color'), (STYLENS,'text-underline-mode'), (STYLENS,'text-underline-style'), (STYLENS,'text-underline-type'), (STYLENS,'text-underline-width'), (STYLENS,'use-window-font-color'), (TEXTNS,'condition'), (TEXTNS,'display'), ), (SVGNS,'definition-src'):( (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), ), (SVGNS,'desc'):( ), (SVGNS,'font-face-format'):( (SVGNS,'string'), ), # allowed_attributes (SVGNS,'font-face-name'):( (SVGNS,'name'), ), (SVGNS,'font-face-src'):( ), (SVGNS,'font-face-uri'):( (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), ), (SVGNS,'linearGradient'):( (SVGNS,'y2'), (DRAWNS,'name'), (SVGNS,'spreadMethod'), (SVGNS,'gradientUnits'), (SVGNS,'x2'), (SVGNS,'gradientTransform'), (SVGNS,'y1'), (DRAWNS,'display-name'), (SVGNS,'x1'), ), (SVGNS,'radialGradient'):( (DRAWNS,'name'), (SVGNS,'fx'), (SVGNS,'fy'), (SVGNS,'spreadMethod'), (SVGNS,'gradientUnits'), (SVGNS,'cy'), (SVGNS,'cx'), (SVGNS,'gradientTransform'), (DRAWNS,'display-name'), (SVGNS,'r'), ), (SVGNS,'stop'):( (SVGNS,'stop-color'), (SVGNS,'stop-opacity'), (SVGNS,'offset'), ), (SVGNS,'title'):( ), # allowed_attributes (TABLENS,'body'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'calculation-settings'):( (TABLENS,'automatic-find-labels'), (TABLENS,'case-sensitive'), (TABLENS,'search-criteria-must-apply-to-whole-cell'), (TABLENS,'precision-as-shown'), (TABLENS,'use-regular-expressions'), (TABLENS,'null-year'), ), (TABLENS,'cell-address'):( (TABLENS,'column'), (TABLENS,'table'), (TABLENS,'row'), ), (TABLENS,'cell-content-change'):( (TABLENS,'id'), (TABLENS,'rejecting-change-id'), (TABLENS,'acceptance-state'), ), (TABLENS,'cell-content-deletion'):( (TABLENS,'id'), ), (TABLENS,'cell-range-source'):( (TABLENS,'last-row-spanned'), (TABLENS,'last-column-spanned'), (TABLENS,'name'), (TABLENS,'filter-options'), (XLINKNS,'actuate'), (TABLENS,'filter-name'), (XLINKNS,'href'), (TABLENS,'refresh-delay'), (XLINKNS,'type'), ), (TABLENS,'change-deletion'):( (TABLENS,'id'), ), (TABLENS,'change-track-table-cell'):( (OFFICENS,'string-value'), (TABLENS,'cell-address'), (TABLENS,'number-matrix-columns-spanned'), (TABLENS,'number-matrix-rows-spanned'), (TABLENS,'matrix-covered'), (OFFICENS,'value-type'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (OFFICENS,'value'), (TABLENS,'formula'), (OFFICENS,'time-value'), ), (TABLENS,'consolidation'):( (TABLENS,'function'), (TABLENS,'source-cell-range-addresses'), (TABLENS,'target-cell-address'), (TABLENS,'link-to-source-data'), (TABLENS,'use-labels'), ), (TABLENS,'content-validation'):( (TABLENS,'base-cell-address'), (TABLENS,'display-list'), (TABLENS,'allow-empty-cell'), (TABLENS,'name'), (TABLENS,'condition'), ), (TABLENS,'content-validations'):( ), # allowed_attributes (TABLENS,'covered-table-cell'):( (TABLENS,'protect'), (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (TABLENS,'style-name'), (TABLENS,'content-validation-name'), (OFFICENS,'value-type'), (TABLENS,'number-columns-repeated'), (TABLENS,'formula'), (OFFICENS,'time-value'), ), (TABLENS,'cut-offs'):( ), (TABLENS,'data-pilot-display-info'):( (TABLENS,'member-count'), (TABLENS,'data-field'), (TABLENS,'enabled'), (TABLENS,'display-member-mode'), ), (TABLENS,'data-pilot-field'):( (TABLENS,'selected-page'), (TABLENS,'function'), (TABLENS,'orientation'), (TABLENS,'used-hierarchy'), (TABLENS,'is-data-layout-field'), (TABLENS,'source-field-name'), ), (TABLENS,'data-pilot-field-reference'):( (TABLENS,'member-name'), (TABLENS,'field-name'), (TABLENS,'member-type'), (TABLENS,'type'), ), # allowed_attributes (TABLENS,'data-pilot-group'):( (TABLENS,'name'), ), (TABLENS,'data-pilot-group-member'):( (TABLENS,'name'), ), (TABLENS,'data-pilot-groups'):( (TABLENS,'date-end'), (TABLENS,'end'), (TABLENS,'start'), (TABLENS,'source-field-name'), (TABLENS,'step'), (TABLENS,'date-start'), (TABLENS,'grouped-by'), ), (TABLENS,'data-pilot-layout-info'):( (TABLENS,'add-empty-lines'), (TABLENS,'layout-mode'), ), (TABLENS,'data-pilot-level'):( (TABLENS,'show-empty'), ), # allowed_attributes (TABLENS,'data-pilot-member'):( (TABLENS,'show-details'), (TABLENS,'name'), (TABLENS,'display'), ), (TABLENS,'data-pilot-members'):( ), (TABLENS,'data-pilot-sort-info'):( (TABLENS,'data-field'), (TABLENS,'sort-mode'), (TABLENS,'order'), ), (TABLENS,'data-pilot-subtotal'):( (TABLENS,'function'), ), (TABLENS,'data-pilot-subtotals'):( ), (TABLENS,'data-pilot-table'):( (TABLENS,'buttons'), (TABLENS,'application-data'), (TABLENS,'name'), (TABLENS,'drill-down-on-double-click'), (TABLENS,'target-range-address'), (TABLENS,'ignore-empty-rows'), (TABLENS,'identify-categories'), (TABLENS,'show-filter-button'), (TABLENS,'grand-total'), ), # allowed_attributes (TABLENS,'data-pilot-tables'):( ), (TABLENS,'database-range'):( (TABLENS,'orientation'), (TABLENS,'target-range-address'), (TABLENS,'contains-header'), (TABLENS,'on-update-keep-size'), (TABLENS,'name'), (TABLENS,'is-selection'), (TABLENS,'refresh-delay'), (TABLENS,'display-filter-buttons'), (TABLENS,'has-persistent-data'), (TABLENS,'on-update-keep-styles'), ), (TABLENS,'database-ranges'):( ), (TABLENS,'database-source-query'):( (TABLENS,'query-name'), (TABLENS,'database-name'), ), # allowed_attributes (TABLENS,'database-source-sql'):( (TABLENS,'parse-sql-statement'), (TABLENS,'database-name'), (TABLENS,'sql-statement'), ), (TABLENS,'database-source-table'):( (TABLENS,'database-table-name'), (TABLENS,'database-name'), ), (TABLENS,'dde-link'):( ), (TABLENS,'dde-links'):( ), (TABLENS,'deletion'):( (TABLENS,'rejecting-change-id'), (TABLENS,'multi-deletion-spanned'), (TABLENS,'acceptance-state'), (TABLENS,'table'), (TABLENS,'position'), (TABLENS,'type'), (TABLENS,'id'), ), # allowed_attributes (TABLENS,'deletions'):( ), (TABLENS,'dependencies'):( ), (TABLENS,'dependency'):( (TABLENS,'id'), ), (TABLENS,'detective'):( ), (TABLENS,'error-macro'):( (TABLENS,'execute'), ), (TABLENS,'error-message'):( (TABLENS,'display'), (TABLENS,'message-type'), (TABLENS,'title'), ), (TABLENS,'even-columns'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'even-rows'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), # allowed_attributes (TABLENS,'filter'):( (TABLENS,'target-range-address'), (TABLENS,'display-duplicates'), (TABLENS,'condition-source-range-address'), (TABLENS,'condition-source'), ), (TABLENS,'filter-and'):( ), (TABLENS,'filter-condition'):( (TABLENS,'operator'), (TABLENS,'field-number'), (TABLENS,'data-type'), (TABLENS,'case-sensitive'), (TABLENS,'value'), ), (TABLENS,'filter-or'):( ), (TABLENS,'first-column'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'first-row'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), # allowed_attributes (TABLENS,'help-message'):( (TABLENS,'display'), (TABLENS,'title'), ), (TABLENS,'highlighted-range'):( (TABLENS,'contains-error'), (TABLENS,'direction'), (TABLENS,'marked-invalid'), (TABLENS,'cell-range-address'), ), (TABLENS,'insertion'):( (TABLENS,'count'), (TABLENS,'rejecting-change-id'), (TABLENS,'acceptance-state'), (TABLENS,'table'), (TABLENS,'position'), (TABLENS,'type'), (TABLENS,'id'), ), (TABLENS,'insertion-cut-off'):( (TABLENS,'position'), (TABLENS,'id'), ), (TABLENS,'iteration'):( (TABLENS,'status'), (TABLENS,'maximum-difference'), (TABLENS,'steps'), ), # allowed_attributes (TABLENS,'label-range'):( (TABLENS,'label-cell-range-address'), (TABLENS,'data-cell-range-address'), (TABLENS,'orientation'), ), (TABLENS,'label-ranges'):( ), (TABLENS,'last-column'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'last-row'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'movement'):( (TABLENS,'id'), (TABLENS,'rejecting-change-id'), (TABLENS,'acceptance-state'), ), (TABLENS,'movement-cut-off'):( (TABLENS,'position'), (TABLENS,'end-position'), (TABLENS,'start-position'), ), (TABLENS,'named-expression'):( (TABLENS,'base-cell-address'), (TABLENS,'expression'), (TABLENS,'name'), ), (TABLENS,'named-expressions'):( ), (TABLENS,'named-range'):( (TABLENS,'range-usable-as'), (TABLENS,'base-cell-address'), (TABLENS,'name'), (TABLENS,'cell-range-address'), ), (TABLENS,'null-date'):( (TABLENS,'date-value'), (TABLENS,'value-type'), ), (TABLENS,'odd-columns'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'odd-rows'):( (TEXTNS,'paragraph-style-name'), (TEXTNS,'style-name'), ), (TABLENS,'operation'):( (TABLENS,'index'), (TABLENS,'name'), ), (TABLENS,'previous'):( (TABLENS,'id'), ), (TABLENS,'scenario'):( (TABLENS,'comment'), (TABLENS,'border-color'), (TABLENS,'copy-back'), (TABLENS,'is-active'), (TABLENS,'protected'), (TABLENS,'copy-formulas'), (TABLENS,'copy-styles'), (TABLENS,'scenario-ranges'), (TABLENS,'display-border'), ), (TABLENS,'shapes'):( ), (TABLENS,'sort'):( (TABLENS,'case-sensitive'), (TABLENS,'algorithm'), (TABLENS,'target-range-address'), (TABLENS,'country'), (TABLENS,'language'), (TABLENS,'bind-styles-to-content'), ), (TABLENS,'sort-by'):( (TABLENS,'field-number'), (TABLENS,'data-type'), (TABLENS,'order'), ), (TABLENS,'sort-groups'):( (TABLENS,'data-type'), (TABLENS,'order'), ), (TABLENS,'source-cell-range'):( (TABLENS,'cell-range-address'), ), (TABLENS,'source-range-address'):( (TABLENS,'column'), (TABLENS,'end-column'), (TABLENS,'start-table'), (TABLENS,'end-row'), (TABLENS,'table'), (TABLENS,'start-row'), (TABLENS,'row'), (TABLENS,'end-table'), (TABLENS,'start-column'), ), # allowed_attributes (TABLENS,'source-service'):( (TABLENS,'user-name'), (TABLENS,'source-name'), (TABLENS,'password'), (TABLENS,'object-name'), (TABLENS,'name'), ), (TABLENS,'subtotal-field'):( (TABLENS,'function'), (TABLENS,'field-number'), ), (TABLENS,'subtotal-rule'):( (TABLENS,'group-by-field-number'), ), (TABLENS,'subtotal-rules'):( (TABLENS,'bind-styles-to-content'), (TABLENS,'page-breaks-on-group-change'), (TABLENS,'case-sensitive'), ), (TABLENS,'table'):( (TABLENS,'name'), (TABLENS,'is-sub-table'), (TABLENS,'style-name'), (TABLENS,'protected'), (TABLENS,'print-ranges'), (TABLENS,'print'), (TABLENS,'protection-key'), ), (TABLENS,'table-cell'):( (TABLENS,'protect'), (TABLENS,'number-matrix-rows-spanned'), (TABLENS,'number-matrix-columns-spanned'), (OFFICENS,'string-value'), (TABLENS,'number-columns-spanned'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (TABLENS,'style-name'), (TABLENS,'content-validation-name'), (OFFICENS,'value-type'), (TABLENS,'number-rows-spanned'), (TABLENS,'number-columns-repeated'), (TABLENS,'formula'), (OFFICENS,'time-value'), ), # allowed_attributes (TABLENS,'table-column'):( (TABLENS,'style-name'), (TABLENS,'default-cell-style-name'), (TABLENS,'visibility'), (TABLENS,'number-columns-repeated'), ), (TABLENS,'table-column-group'):( (TABLENS,'display'), ), (TABLENS,'table-columns'):( ), (TABLENS,'table-header-columns'):( ), (TABLENS,'table-header-rows'):( ), (TABLENS,'table-row'):( (TABLENS,'number-rows-repeated'), (TABLENS,'style-name'), (TABLENS,'visibility'), (TABLENS,'default-cell-style-name'), ), (TABLENS,'table-row-group'):( (TABLENS,'display'), ), (TABLENS,'table-rows'):( ), (TABLENS,'table-source'):( (TABLENS,'filter-options'), (XLINKNS,'actuate'), (TABLENS,'filter-name'), (XLINKNS,'href'), (TABLENS,'mode'), (TABLENS,'table-name'), (XLINKNS,'type'), (TABLENS,'refresh-delay'), ), (TABLENS,'table-template'):( (TEXTNS,'last-row-end-column'), (TEXTNS,'first-row-end-column'), (TEXTNS,'name'), (TEXTNS,'last-row-start-column'), (TEXTNS,'first-row-start-column'), ), (TABLENS,'target-range-address'):( (TABLENS,'column'), (TABLENS,'end-column'), (TABLENS,'start-table'), (TABLENS,'end-row'), (TABLENS,'table'), (TABLENS,'start-row'), (TABLENS,'row'), (TABLENS,'end-table'), (TABLENS,'start-column'), ), (TABLENS,'tracked-changes'):( (TABLENS,'track-changes'), ), # allowed_attributes (TEXTNS,'a'):( (TEXTNS,'visited-style-name'), (OFFICENS,'name'), (OFFICENS,'title'), (XLINKNS,'show'), (OFFICENS,'target-frame-name'), (XLINKNS,'actuate'), (TEXTNS,'style-name'), (XLINKNS,'href'), (XLINKNS,'type'), ), (TEXTNS,'alphabetical-index'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'alphabetical-index-auto-mark-file'):( (XLINKNS,'href'), (XLINKNS,'type'), ), (TEXTNS,'alphabetical-index-entry-template'):( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), (TEXTNS,'alphabetical-index-mark'):( (TEXTNS,'main-entry'), (TEXTNS,'key1-phonetic'), (TEXTNS,'key2'), (TEXTNS,'key1'), (TEXTNS,'string-value'), (TEXTNS,'key2-phonetic'), (TEXTNS,'string-value-phonetic'), ), # allowed_attributes (TEXTNS,'alphabetical-index-mark-end'):( (TEXTNS,'id'), ), (TEXTNS,'alphabetical-index-mark-start'):( (TEXTNS,'main-entry'), (TEXTNS,'key1-phonetic'), (TEXTNS,'key2'), (TEXTNS,'key1'), (TEXTNS,'string-value-phonetic'), (TEXTNS,'key2-phonetic'), (TEXTNS,'id'), ), (TEXTNS,'alphabetical-index-source'):( (TEXTNS,'capitalize-entries'), (FONS,'language'), (TEXTNS,'relative-tab-stop-position'), (TEXTNS,'alphabetical-separators'), (TEXTNS,'combine-entries-with-pp'), (TEXTNS,'combine-entries-with-dash'), (TEXTNS,'sort-algorithm'), (TEXTNS,'ignore-case'), (TEXTNS,'combine-entries'), (TEXTNS,'comma-separated'), (FONS,'country'), (TEXTNS,'index-scope'), (TEXTNS,'main-entry-style-name'), (TEXTNS,'use-keys-as-entries'), ), # allowed_attributes (TEXTNS,'author-initials'):( (TEXTNS,'fixed'), ), (TEXTNS,'author-name'):( (TEXTNS,'fixed'), ), (TEXTNS,'bibliography'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'bibliography-configuration'):( (TEXTNS,'suffix'), (FONS,'language'), (TEXTNS,'numbered-entries'), (FONS,'country'), (TEXTNS,'sort-by-position'), (TEXTNS,'sort-algorithm'), (TEXTNS,'prefix'), ), (TEXTNS,'bibliography-entry-template'):( (TEXTNS,'style-name'), (TEXTNS,'bibliography-type'), ), # allowed_attributes (TEXTNS,'bibliography-mark'):( (TEXTNS,'address'), (TEXTNS,'annote'), (TEXTNS,'author'), (TEXTNS,'bibliography-type'), (TEXTNS,'booktitle'), (TEXTNS,'chapter'), (TEXTNS,'custom1'), (TEXTNS,'custom2'), (TEXTNS,'custom3'), (TEXTNS,'custom4'), (TEXTNS,'custom5'), (TEXTNS,'edition'), (TEXTNS,'editor'), (TEXTNS,'howpublished'), (TEXTNS,'identifier'), (TEXTNS,'institution'), (TEXTNS,'isbn'), (TEXTNS,'issn'), (TEXTNS,'journal'), (TEXTNS,'month'), (TEXTNS,'note'), (TEXTNS,'number'), (TEXTNS,'organizations'), (TEXTNS,'pages'), (TEXTNS,'publisher'), (TEXTNS,'report-type'), (TEXTNS,'school'), (TEXTNS,'series'), (TEXTNS,'title'), (TEXTNS,'url'), (TEXTNS,'volume'), (TEXTNS,'year'), ), (TEXTNS,'bibliography-source'):( ), (TEXTNS,'bookmark'):( (TEXTNS,'name'), ), (TEXTNS,'bookmark-end'):( (TEXTNS,'name'), ), (TEXTNS,'bookmark-ref'):( (TEXTNS,'ref-name'), (TEXTNS,'reference-format'), ), (TEXTNS,'bookmark-start'):( (TEXTNS,'name'), ), # allowed_attributes (TEXTNS,'change'):( (TEXTNS,'change-id'), ), (TEXTNS,'change-end'):( (TEXTNS,'change-id'), ), (TEXTNS,'change-start'):( (TEXTNS,'change-id'), ), (TEXTNS,'changed-region'):( (TEXTNS,'id'), ), (TEXTNS,'chapter'):( (TEXTNS,'display'), (TEXTNS,'outline-level'), ), (TEXTNS,'conditional-text'):( (TEXTNS,'string-value-if-true'), (TEXTNS,'current-value'), (TEXTNS,'string-value-if-false'), (TEXTNS,'condition'), ), (TEXTNS,'creation-date'):( (TEXTNS,'date-value'), (TEXTNS,'fixed'), (STYLENS,'data-style-name'), ), (TEXTNS,'creation-time'):( (TEXTNS,'fixed'), (TEXTNS,'time-value'), (STYLENS,'data-style-name'), ), (TEXTNS,'creator'):( (TEXTNS,'fixed'), ), (TEXTNS,'database-display'):( (TEXTNS,'column-name'), (TEXTNS,'table-name'), (TEXTNS,'table-type'), (TEXTNS,'database-name'), (STYLENS,'data-style-name'), ), (TEXTNS,'database-name'):( (TEXTNS,'table-name'), (TEXTNS,'table-type'), (TEXTNS,'database-name'), ), (TEXTNS,'database-next'):( (TEXTNS,'table-name'), (TEXTNS,'table-type'), (TEXTNS,'database-name'), (TEXTNS,'condition'), ), (TEXTNS,'database-row-number'):( (STYLENS,'num-format'), (TEXTNS,'database-name'), (TEXTNS,'value'), (STYLENS,'num-letter-sync'), (TEXTNS,'table-name'), (TEXTNS,'table-type'), ), (TEXTNS,'database-row-select'):( (TEXTNS,'row-number'), (TEXTNS,'table-name'), (TEXTNS,'table-type'), (TEXTNS,'database-name'), (TEXTNS,'condition'), ), # allowed_attributes (TEXTNS,'date'):( (TEXTNS,'date-value'), (TEXTNS,'fixed'), (TEXTNS,'date-adjust'), (STYLENS,'data-style-name'), ), (TEXTNS,'dde-connection'):( (TEXTNS,'connection-name'), ), (TEXTNS,'dde-connection-decl'):( (OFFICENS,'automatic-update'), (OFFICENS,'dde-topic'), (OFFICENS,'dde-application'), (OFFICENS,'name'), (OFFICENS,'dde-item'), ), (TEXTNS,'dde-connection-decls'):( ), (TEXTNS,'deletion'):( ), (TEXTNS,'description'):( (TEXTNS,'fixed'), ), (TEXTNS,'editing-cycles'):( (TEXTNS,'fixed'), ), (TEXTNS,'editing-duration'):( (TEXTNS,'duration'), (TEXTNS,'fixed'), (STYLENS,'data-style-name'), ), (TEXTNS,'execute-macro'):( (TEXTNS,'name'), ), (TEXTNS,'expression'):( (TEXTNS,'display'), (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (STYLENS,'data-style-name'), (OFFICENS,'value-type'), (TEXTNS,'formula'), (OFFICENS,'time-value'), ), (TEXTNS,'file-name'):( (TEXTNS,'fixed'), (TEXTNS,'display'), ), # allowed_attributes (TEXTNS,'format-change'):( ), (TEXTNS,'h'):( (TEXTNS,'restart-numbering'), (TEXTNS,'cond-style-name'), (TEXTNS,'is-list-header'), (TEXTNS,'style-name'), (TEXTNS,'class-names'), (TEXTNS,'start-value'), (TEXTNS,'id'), (TEXTNS,'outline-level'), ), (TEXTNS,'hidden-paragraph'):( (TEXTNS,'is-hidden'), (TEXTNS,'condition'), ), (TEXTNS,'hidden-text'):( (TEXTNS,'string-value'), (TEXTNS,'is-hidden'), (TEXTNS,'condition'), ), (TEXTNS,'illustration-index'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'illustration-index-entry-template'):( (TEXTNS,'style-name'), ), (TEXTNS,'illustration-index-source'):( (TEXTNS,'index-scope'), (TEXTNS,'caption-sequence-name'), (TEXTNS,'use-caption'), (TEXTNS,'caption-sequence-format'), (TEXTNS,'relative-tab-stop-position'), ), (TEXTNS,'index-body'):( ), (TEXTNS,'index-entry-bibliography'):( (TEXTNS,'bibliography-data-field'), (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-chapter'):( (TEXTNS,'style-name'), (TEXTNS,'display'), ), # allowed_attributes (TEXTNS,'index-entry-link-end'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-link-start'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-page-number'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-span'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-entry-tab-stop'):( (STYLENS,'position'), (TEXTNS,'style-name'), (STYLENS,'type'), (STYLENS,'leader-char'), ), (TEXTNS,'index-entry-text'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-source-style'):( (TEXTNS,'style-name'), ), (TEXTNS,'index-source-styles'):( (TEXTNS,'outline-level'), ), (TEXTNS,'index-title'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'index-title-template'):( (TEXTNS,'style-name'), ), (TEXTNS,'initial-creator'):( (TEXTNS,'fixed'), ), (TEXTNS,'insertion'):( ), # allowed_attributes (TEXTNS,'keywords'):( (TEXTNS,'fixed'), ), (TEXTNS,'line-break'):( ), (TEXTNS,'linenumbering-configuration'):( (TEXTNS,'number-position'), (TEXTNS,'number-lines'), (STYLENS,'num-format'), (TEXTNS,'count-empty-lines'), (TEXTNS,'count-in-text-boxes'), (TEXTNS,'style-name'), (STYLENS,'num-letter-sync'), (TEXTNS,'increment'), (TEXTNS,'offset'), (TEXTNS,'restart-on-page'), ), (TEXTNS,'linenumbering-separator'):( (TEXTNS,'increment'), ), (TEXTNS,'list'):( (TEXTNS,'style-name'), (TEXTNS,'continue-numbering'), ), (TEXTNS,'list-header'):( ), (TEXTNS,'list-item'):( (TEXTNS,'start-value'), ), (TEXTNS,'list-level-style-bullet'):( (TEXTNS,'level'), (STYLENS,'num-prefix'), (STYLENS,'num-suffix'), (TEXTNS,'bullet-relative-size'), (TEXTNS,'style-name'), (TEXTNS,'bullet-char'), ), (TEXTNS,'list-level-style-image'):( (XLINKNS,'show'), (XLINKNS,'actuate'), (XLINKNS,'href'), (XLINKNS,'type'), (TEXTNS,'level'), ), (TEXTNS,'list-level-style-number'):( (TEXTNS,'level'), (TEXTNS,'display-levels'), (STYLENS,'num-format'), (STYLENS,'num-suffix'), (TEXTNS,'style-name'), (STYLENS,'num-prefix'), (STYLENS,'num-letter-sync'), (TEXTNS,'start-value'), ), # allowed_attributes (TEXTNS,'list-style'):( (TEXTNS,'consecutive-numbering'), (STYLENS,'display-name'), (STYLENS,'name'), ), (TEXTNS,'measure'):( (TEXTNS,'kind'), ), (TEXTNS,'modification-date'):( (TEXTNS,'date-value'), (TEXTNS,'fixed'), (STYLENS,'data-style-name'), ), (TEXTNS,'modification-time'):( (TEXTNS,'fixed'), (TEXTNS,'time-value'), (STYLENS,'data-style-name'), ), (TEXTNS,'note'):( (TEXTNS,'note-class'), (TEXTNS,'id'), ), (TEXTNS,'note-body'):( ), (TEXTNS,'note-citation'):( (TEXTNS,'label'), ), (TEXTNS,'note-continuation-notice-backward'):( ), (TEXTNS,'note-continuation-notice-forward'):( ), (TEXTNS,'note-ref'):( (TEXTNS,'ref-name'), (TEXTNS,'note-class'), (TEXTNS,'reference-format'), ), (TEXTNS,'notes-configuration'):( (TEXTNS,'citation-body-style-name'), (STYLENS,'num-format'), (TEXTNS,'default-style-name'), (STYLENS,'num-suffix'), (TEXTNS,'start-numbering-at'), (STYLENS,'num-prefix'), (STYLENS,'num-letter-sync'), (TEXTNS,'citation-style-name'), (TEXTNS,'footnotes-position'), (TEXTNS,'master-page-name'), (TEXTNS,'start-value'), (TEXTNS,'note-class'), ), (TEXTNS,'number'):( ), (TEXTNS,'numbered-paragraph'):( (TEXTNS,'continue-numbering'), (TEXTNS,'style-name'), (TEXTNS,'start-value'), (TEXTNS,'level'), ), (TEXTNS,'object-count'):( (STYLENS,'num-format'), (STYLENS,'num-letter-sync'), ), (TEXTNS,'object-index'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), # allowed_attributes (TEXTNS,'object-index-entry-template'):( (TEXTNS,'style-name'), ), (TEXTNS,'object-index-source'):( (TEXTNS,'use-draw-objects'), (TEXTNS,'use-math-objects'), (TEXTNS,'relative-tab-stop-position'), (TEXTNS,'use-chart-objects'), (TEXTNS,'index-scope'), (TEXTNS,'use-spreadsheet-objects'), (TEXTNS,'use-other-objects'), ), (TEXTNS,'outline-level-style'):( (TEXTNS,'level'), (TEXTNS,'display-levels'), (STYLENS,'num-format'), (STYLENS,'num-suffix'), (TEXTNS,'style-name'), (STYLENS,'num-prefix'), (STYLENS,'num-letter-sync'), (TEXTNS,'start-value'), ), (TEXTNS,'outline-style'):( ), (TEXTNS,'p'):( (TEXTNS,'cond-style-name'), (TEXTNS,'style-name'), (TEXTNS,'class-names'), (TEXTNS,'id'), ), (TEXTNS,'page'):( (TEXTNS,'master-page-name'), ), (TEXTNS,'page-continuation'):( (TEXTNS,'string-value'), (TEXTNS,'select-page'), ), (TEXTNS,'page-number'):( (TEXTNS,'page-adjust'), (STYLENS,'num-format'), (TEXTNS,'fixed'), (STYLENS,'num-letter-sync'), (TEXTNS,'select-page'), ), (TEXTNS,'page-sequence'):( ), (TEXTNS,'page-variable-get'):( (STYLENS,'num-format'), (STYLENS,'num-letter-sync'), ), (TEXTNS,'page-variable-set'):( (TEXTNS,'active'), (TEXTNS,'page-adjust'), ), (TEXTNS,'placeholder'):( (TEXTNS,'placeholder-type'), (TEXTNS,'description'), ), (TEXTNS,'print-date'):( (TEXTNS,'date-value'), (TEXTNS,'fixed'), (STYLENS,'data-style-name'), ), (TEXTNS,'print-time'):( (TEXTNS,'fixed'), (TEXTNS,'time-value'), (STYLENS,'data-style-name'), ), (TEXTNS,'printed-by'):( (TEXTNS,'fixed'), ), (TEXTNS,'reference-mark'):( (TEXTNS,'name'), ), (TEXTNS,'reference-mark-end'):( (TEXTNS,'name'), ), (TEXTNS,'reference-mark-start'):( (TEXTNS,'name'), ), (TEXTNS,'ruby'):( (TEXTNS,'style-name'), ), (TEXTNS,'ruby-base'):( ), (TEXTNS,'ruby-text'):( (TEXTNS,'style-name'), ), (TEXTNS,'s'):( (TEXTNS,'c'), ), (TEXTNS,'script'):( (XLINKNS,'href'), (XLINKNS,'type'), (SCRIPTNS,'language'), ), (TEXTNS,'section'):( (TEXTNS,'name'), (TEXTNS,'protection-key'), (TEXTNS,'style-name'), (TEXTNS,'protected'), (TEXTNS,'display'), (TEXTNS,'condition'), ), (TEXTNS,'section-source'):( (TEXTNS,'filter-name'), (XLINKNS,'href'), (XLINKNS,'type'), (TEXTNS,'section-name'), (XLINKNS,'show'), ), (TEXTNS,'sender-city'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-company'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-country'):( (TEXTNS,'fixed'), ), # allowed_attributes (TEXTNS,'sender-email'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-fax'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-firstname'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-initials'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-lastname'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-phone-private'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-phone-work'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-position'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-postal-code'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-state-or-province'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-street'):( (TEXTNS,'fixed'), ), (TEXTNS,'sender-title'):( (TEXTNS,'fixed'), ), (TEXTNS,'sequence'):( (TEXTNS,'formula'), (STYLENS,'num-format'), (STYLENS,'num-letter-sync'), (TEXTNS,'name'), (TEXTNS,'ref-name'), ), (TEXTNS,'sequence-decl'):( (TEXTNS,'separation-character'), (TEXTNS,'display-outline-level'), (TEXTNS,'name'), ), (TEXTNS,'sequence-decls'):( ), (TEXTNS,'sequence-ref'):( (TEXTNS,'ref-name'), (TEXTNS,'reference-format'), ), (TEXTNS,'sheet-name'):( ), (TEXTNS,'soft-page-break'):( ), (TEXTNS,'sort-key'):( (TEXTNS,'sort-ascending'), (TEXTNS,'key'), ), # allowed_attributes (TEXTNS,'span'):( (TEXTNS,'style-name'), (TEXTNS,'class-names'), ), (TEXTNS,'subject'):( (TEXTNS,'fixed'), ), (TEXTNS,'tab'):( (TEXTNS,'tab-ref'), ), (TEXTNS,'table-formula'):( (TEXTNS,'formula'), (STYLENS,'data-style-name'), (TEXTNS,'display'), ), (TEXTNS,'table-index'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'table-index-entry-template'):( (TEXTNS,'style-name'), ), (TEXTNS,'table-index-source'):( (TEXTNS,'index-scope'), (TEXTNS,'caption-sequence-name'), (TEXTNS,'use-caption'), (TEXTNS,'caption-sequence-format'), (TEXTNS,'relative-tab-stop-position'), ), # allowed_attributes (TEXTNS,'table-of-content'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'table-of-content-entry-template'):( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), (TEXTNS,'table-of-content-source'):( (TEXTNS,'index-scope'), (TEXTNS,'outline-level'), (TEXTNS,'relative-tab-stop-position'), (TEXTNS,'use-index-marks'), (TEXTNS,'use-outline-level'), (TEXTNS,'use-index-source-styles'), ), (TEXTNS,'template-name'):( (TEXTNS,'display'), ), (TEXTNS,'text-input'):( (TEXTNS,'description'), ), (TEXTNS,'time'):( (TEXTNS,'time-adjust'), (TEXTNS,'fixed'), (TEXTNS,'time-value'), (STYLENS,'data-style-name'), ), (TEXTNS,'title'):( (TEXTNS,'fixed'), ), (TEXTNS,'toc-mark'):( (TEXTNS,'string-value'), (TEXTNS,'outline-level'), ), (TEXTNS,'toc-mark-end'):( (TEXTNS,'id'), ), (TEXTNS,'toc-mark-start'):( (TEXTNS,'id'), (TEXTNS,'outline-level'), ), (TEXTNS,'tracked-changes'):( (TEXTNS,'track-changes'), ), (TEXTNS,'user-defined'):( (TEXTNS,'name'), (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'date-value'), (STYLENS,'data-style-name'), (TEXTNS,'fixed'), (OFFICENS,'time-value'), ), (TEXTNS,'user-field-decl'):( (TEXTNS,'name'), (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (OFFICENS,'value-type'), (TEXTNS,'formula'), (OFFICENS,'time-value'), ), (TEXTNS,'user-field-decls'):( ), (TEXTNS,'user-field-get'):( (STYLENS,'data-style-name'), (TEXTNS,'name'), (TEXTNS,'display'), ), # allowed_attributes (TEXTNS,'user-field-input'):( (STYLENS,'data-style-name'), (TEXTNS,'name'), (TEXTNS,'description'), ), (TEXTNS,'user-index'):( (TEXTNS,'protected'), (TEXTNS,'style-name'), (TEXTNS,'name'), (TEXTNS,'protection-key'), ), (TEXTNS,'user-index-entry-template'):( (TEXTNS,'style-name'), (TEXTNS,'outline-level'), ), (TEXTNS,'user-index-mark'):( (TEXTNS,'index-name'), (TEXTNS,'string-value'), (TEXTNS,'outline-level'), ), (TEXTNS,'user-index-mark-end'):( (TEXTNS,'id'), (TEXTNS,'outline-level'), ), (TEXTNS,'user-index-mark-start'):( (TEXTNS,'index-name'), (TEXTNS,'id'), (TEXTNS,'outline-level'), ), # allowed_attributes (TEXTNS,'user-index-source'):( (TEXTNS,'copy-outline-levels'), (TEXTNS,'index-name'), (TEXTNS,'index-scope'), (TEXTNS,'relative-tab-stop-position'), (TEXTNS,'use-floating-frames'), (TEXTNS,'use-graphics'), (TEXTNS,'use-index-marks'), (TEXTNS,'use-objects'), (TEXTNS,'use-tables'), ), (TEXTNS,'variable-decl'):( (TEXTNS,'name'), (OFFICENS,'value-type'), ), (TEXTNS,'variable-decls'):( ), (TEXTNS,'variable-get'):( (STYLENS,'data-style-name'), (TEXTNS,'name'), (TEXTNS,'display'), ), (TEXTNS,'variable-input'):( (STYLENS,'data-style-name'), (TEXTNS,'display'), (TEXTNS,'name'), (OFFICENS,'value-type'), (TEXTNS,'description'), ), (TEXTNS,'variable-set'):( (TEXTNS,'name'), (TEXTNS,'display'), (OFFICENS,'string-value'), (OFFICENS,'value'), (OFFICENS,'boolean-value'), (OFFICENS,'currency'), (OFFICENS,'date-value'), (STYLENS,'data-style-name'), (OFFICENS,'value-type'), (TEXTNS,'formula'), (OFFICENS,'time-value'), ), # allowed_attributes }
288,414
Python
.py
8,430
20.358956
80
0.422386
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,428
opendocument.py
kovidgoyal_calibre/src/odf/opendocument.py
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # __doc__="""Use OpenDocument to generate your documents.""" import mimetypes import sys import time import zipfile from io import BytesIO from xml.sax.xmlreader import InputSource from polyglot.builtins import unicode_type from polyglot.io import PolyglotBytesIO, PolyglotStringIO from . import element, manifest, meta from .attrconverters import make_NCName from .namespaces import CHARTNS, DRAWNS, METANS, OFFICENS, PRESENTATIONNS, STYLENS, TABLENS, TEXTNS, TOOLSVERSION from .odfmanifest import manifestlist from .office import ( AutomaticStyles, Body, Chart, Document, DocumentContent, DocumentMeta, DocumentSettings, DocumentStyles, Drawing, FontFaceDecls, Image, MasterStyles, Meta, Presentation, Scripts, Settings, Spreadsheet, Styles, Text, ) __version__= TOOLSVERSION _XMLPROLOGUE = "<?xml version='1.0' encoding='UTF-8'?>\n" UNIXPERMS = 0o100644 << 16 # -rw-r--r-- IS_FILENAME = 0 IS_IMAGE = 1 # We need at least Python 2.2 assert sys.version_info[0]>=2 and sys.version_info[1] >= 2 # sys.setrecursionlimit(100) # The recursion limit is set conservative so mistakes like # s=content() s.addElement(s) won't eat up too much processor time. odmimetypes = { 'application/vnd.oasis.opendocument.text': '.odt', 'application/vnd.oasis.opendocument.text-template': '.ott', 'application/vnd.oasis.opendocument.graphics': '.odg', 'application/vnd.oasis.opendocument.graphics-template': '.otg', 'application/vnd.oasis.opendocument.presentation': '.odp', 'application/vnd.oasis.opendocument.presentation-template': '.otp', 'application/vnd.oasis.opendocument.spreadsheet': '.ods', 'application/vnd.oasis.opendocument.spreadsheet-template': '.ots', 'application/vnd.oasis.opendocument.chart': '.odc', 'application/vnd.oasis.opendocument.chart-template': '.otc', 'application/vnd.oasis.opendocument.image': '.odi', 'application/vnd.oasis.opendocument.image-template': '.oti', 'application/vnd.oasis.opendocument.formula': '.odf', 'application/vnd.oasis.opendocument.formula-template': '.otf', 'application/vnd.oasis.opendocument.text-master': '.odm', 'application/vnd.oasis.opendocument.text-web': '.oth', } class OpaqueObject: def __init__(self, filename, mediatype, content=None): self.mediatype = mediatype self.filename = filename self.content = content class OpenDocument: """ A class to hold the content of an OpenDocument document Use the xml method to write the XML source to the screen or to a file d = OpenDocument(mimetype) fd.write(d.xml()) """ thumbnail = None def __init__(self, mimetype, add_generator=True): self.mimetype = mimetype self.childobjects = [] self._extra = [] self.folder = "" # Always empty for toplevel documents self.topnode = Document(mimetype=self.mimetype) self.topnode.ownerDocument = self self.clear_caches() self.Pictures = {} self.meta = Meta() self.topnode.addElement(self.meta) if add_generator: self.meta.addElement(meta.Generator(text=TOOLSVERSION)) self.scripts = Scripts() self.topnode.addElement(self.scripts) self.fontfacedecls = FontFaceDecls() self.topnode.addElement(self.fontfacedecls) self.settings = Settings() self.topnode.addElement(self.settings) self.styles = Styles() self.topnode.addElement(self.styles) self.automaticstyles = AutomaticStyles() self.topnode.addElement(self.automaticstyles) self.masterstyles = MasterStyles() self.topnode.addElement(self.masterstyles) self.body = Body() self.topnode.addElement(self.body) def rebuild_caches(self, node=None): if node is None: node = self.topnode self.build_caches(node) for e in node.childNodes: if e.nodeType == element.Node.ELEMENT_NODE: self.rebuild_caches(e) def clear_caches(self): self.element_dict = {} self._styles_dict = {} self._styles_ooo_fix = {} def build_caches(self, element): """ Called from element.py """ if element.qname not in self.element_dict: self.element_dict[element.qname] = [] self.element_dict[element.qname].append(element) if element.qname == (STYLENS, 'style'): self.__register_stylename(element) # Add to style dictionary styleref = element.getAttrNS(TEXTNS,'style-name') if styleref is not None and styleref in self._styles_ooo_fix: element.setAttrNS(TEXTNS,'style-name', self._styles_ooo_fix[styleref]) def __register_stylename(self, element): ''' Register a style. But there are three style dictionaries: office:styles, office:automatic-styles and office:master-styles Chapter 14 ''' name = element.getAttrNS(STYLENS, 'name') if name is None: return if element.parentNode.qname in ((OFFICENS,'styles'), (OFFICENS,'automatic-styles')): if name in self._styles_dict: newname = 'M'+name # Rename style self._styles_ooo_fix[name] = newname # From here on all references to the old name will refer to the new one name = newname element.setAttrNS(STYLENS, 'name', name) self._styles_dict[name] = element def toXml(self, filename=''): xml=PolyglotBytesIO() xml.write(_XMLPROLOGUE) self.body.toXml(0, xml) if not filename: return xml.getvalue() else: f=open(filename,'wb') f.write(xml.getvalue()) f.close() def xml(self): """ Generates the full document as an XML file Always written as a bytestream in UTF-8 encoding """ self.__replaceGenerator() xml=PolyglotBytesIO() xml.write(_XMLPROLOGUE) self.topnode.toXml(0, xml) return xml.getvalue() def contentxml(self): """ Generates the content.xml file Always written as a bytestream in UTF-8 encoding """ xml=PolyglotBytesIO() xml.write(_XMLPROLOGUE) x = DocumentContent() x.write_open_tag(0, xml) if self.scripts.hasChildNodes(): self.scripts.toXml(1, xml) if self.fontfacedecls.hasChildNodes(): self.fontfacedecls.toXml(1, xml) a = AutomaticStyles() stylelist = self._used_auto_styles([self.styles, self.automaticstyles, self.body]) if len(stylelist) > 0: a.write_open_tag(1, xml) for s in stylelist: s.toXml(2, xml) a.write_close_tag(1, xml) else: a.toXml(1, xml) self.body.toXml(1, xml) x.write_close_tag(0, xml) return xml.getvalue() def __manifestxml(self): """ Generates the manifest.xml file The self.manifest isn't available unless the document is being saved """ xml=PolyglotBytesIO() xml.write(_XMLPROLOGUE) self.manifest.toXml(0,xml) return xml.getvalue() def metaxml(self): """ Generates the meta.xml file """ self.__replaceGenerator() x = DocumentMeta() x.addElement(self.meta) xml=PolyglotStringIO() xml.write(_XMLPROLOGUE) x.toXml(0,xml) return xml.getvalue() def settingsxml(self): """ Generates the settings.xml file """ x = DocumentSettings() x.addElement(self.settings) xml=PolyglotStringIO() xml.write(_XMLPROLOGUE) x.toXml(0,xml) return xml.getvalue() def _parseoneelement(self, top, stylenamelist): """ Finds references to style objects in master-styles and add the style name to the style list if not already there. Recursive """ for e in top.childNodes: if e.nodeType == element.Node.ELEMENT_NODE: for styleref in ( (CHARTNS,'style-name'), (DRAWNS,'style-name'), (DRAWNS,'text-style-name'), (PRESENTATIONNS,'style-name'), (STYLENS,'data-style-name'), (STYLENS,'list-style-name'), (STYLENS,'page-layout-name'), (STYLENS,'style-name'), (TABLENS,'default-cell-style-name'), (TABLENS,'style-name'), (TEXTNS,'style-name')): if e.getAttrNS(styleref[0],styleref[1]): stylename = e.getAttrNS(styleref[0],styleref[1]) if stylename not in stylenamelist: stylenamelist.append(stylename) stylenamelist = self._parseoneelement(e, stylenamelist) return stylenamelist def _used_auto_styles(self, segments): """ Loop through the masterstyles elements, and find the automatic styles that are used. These will be added to the automatic-styles element in styles.xml """ stylenamelist = [] for top in segments: stylenamelist = self._parseoneelement(top, stylenamelist) stylelist = [] for e in self.automaticstyles.childNodes: if e.getAttrNS(STYLENS,'name') in stylenamelist: stylelist.append(e) return stylelist def stylesxml(self): """ Generates the styles.xml file """ xml=PolyglotStringIO() xml.write(_XMLPROLOGUE) x = DocumentStyles() x.write_open_tag(0, xml) if self.fontfacedecls.hasChildNodes(): self.fontfacedecls.toXml(1, xml) self.styles.toXml(1, xml) a = AutomaticStyles() a.write_open_tag(1, xml) for s in self._used_auto_styles([self.masterstyles]): s.toXml(2, xml) a.write_close_tag(1, xml) if self.masterstyles.hasChildNodes(): self.masterstyles.toXml(1, xml) x.write_close_tag(0, xml) return xml.getvalue() def addPicture(self, filename, mediatype=None, content=None): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures' If passed a file ptr, mediatype must be set """ if content is None: if mediatype is None: mediatype, encoding = mimetypes.guess_type(filename) if mediatype is None: mediatype = '' try: ext = filename[filename.rindex('.'):] except: ext='' else: ext = mimetypes.guess_extension(mediatype) manifestfn = f"Pictures/{(time.time()*10000000000):0.0f}{ext}" self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) else: manifestfn = filename self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) return manifestfn def addPictureFromFile(self, filename, mediatype=None): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures'. If mediatype is not given, it will be guessed from the filename extension. """ if mediatype is None: mediatype, encoding = mimetypes.guess_type(filename) if mediatype is None: mediatype = '' try: ext = filename[filename.rindex('.'):] except ValueError: ext='' else: ext = mimetypes.guess_extension(mediatype) manifestfn = f"Pictures/{(time.time()*10000000000):0.0f}{ext}" self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) return manifestfn def addPictureFromString(self, content, mediatype): """ Add a picture It uses the same convention as OOo, in that it saves the picture in the zipfile in the subdirectory 'Pictures'. The content variable is a string that contains the binary image data. The mediatype indicates the image format. """ ext = mimetypes.guess_extension(mediatype) manifestfn = f"Pictures/{(time.time()*10000000000):0.0f}{ext}" self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) return manifestfn def addThumbnail(self, filecontent=None): """ Add a fixed thumbnail The thumbnail in the library is big, so this is pretty useless. """ if filecontent is None: import thumbnail self.thumbnail = thumbnail.thumbnail() else: self.thumbnail = filecontent def addObject(self, document, objectname=None): """ Adds an object (subdocument). The object must be an OpenDocument class The return value will be the folder in the zipfile the object is stored in """ self.childobjects.append(document) if objectname is None: document.folder = "%s/Object %d" % (self.folder, len(self.childobjects)) else: document.folder = objectname return ".%s" % document.folder def _savePictures(self, object, folder): for arcname, picturerec in object.Pictures.items(): what_it_is, fileobj, mediatype = picturerec self.manifest.addElement(manifest.FileEntry(fullpath=f"{folder}{arcname}", mediatype=mediatype)) if what_it_is == IS_FILENAME: self._z.write(fileobj, arcname, zipfile.ZIP_STORED) else: zi = zipfile.ZipInfo(unicode_type(arcname), self._now) zi.compress_type = zipfile.ZIP_STORED zi.external_attr = UNIXPERMS self._z.writestr(zi, fileobj) # According to section 17.7.3 in ODF 1.1, the pictures folder should not have a manifest entry # if hasPictures: # self.manifest.addElement(manifest.FileEntry(fullpath="%sPictures/" % folder, mediatype="")) # Look in subobjects subobjectnum = 1 for subobject in object.childobjects: self._savePictures(subobject,'%sObject %d/' % (folder, subobjectnum)) subobjectnum += 1 def __replaceGenerator(self): """ Section 3.1.1: The application MUST NOT export the original identifier belonging to the application that created the document. """ for m in self.meta.childNodes[:]: if m.qname == (METANS, 'generator'): self.meta.removeChild(m) self.meta.addElement(meta.Generator(text=TOOLSVERSION)) def save(self, outputfile, addsuffix=False): """ Save the document under the filename. If the filename is '-' then save to stdout """ if outputfile == '-': outputfp = zipfile.ZipFile(sys.stdout,"w") else: if addsuffix: outputfile = outputfile + odmimetypes.get(self.mimetype,'.xxx') outputfp = zipfile.ZipFile(outputfile, "w") self.__zipwrite(outputfp) outputfp.close() def write(self, outputfp): """ User API to write the ODF file to an open file descriptor Writes the ZIP format """ zipoutputfp = zipfile.ZipFile(outputfp,"w") self.__zipwrite(zipoutputfp) def __zipwrite(self, outputfp): """ Write the document to an open file pointer This is where the real work is done """ self._z = outputfp self._now = time.localtime()[:6] self.manifest = manifest.Manifest() # Write mimetype zi = zipfile.ZipInfo('mimetype', self._now) zi.compress_type = zipfile.ZIP_STORED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.mimetype) self._saveXmlObjects(self,"") # Write pictures self._savePictures(self,"") # Write the thumbnail if self.thumbnail is not None: self.manifest.addElement(manifest.FileEntry(fullpath="Thumbnails/", mediatype='')) self.manifest.addElement(manifest.FileEntry(fullpath="Thumbnails/thumbnail.png", mediatype='')) zi = zipfile.ZipInfo("Thumbnails/thumbnail.png", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.thumbnail) # Write any extra files for op in self._extra: if op.filename == "META-INF/documentsignatures.xml": continue # Don't save signatures self.manifest.addElement(manifest.FileEntry(fullpath=op.filename, mediatype=op.mediatype)) zi = zipfile.ZipInfo(op.filename.encode('utf-8'), self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS if op.content is not None: self._z.writestr(zi, op.content) # Write manifest zi = zipfile.ZipInfo("META-INF/manifest.xml", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, self.__manifestxml()) del self._z del self._now del self.manifest def _saveXmlObjects(self, object, folder): if self == object: self.manifest.addElement(manifest.FileEntry(fullpath="/", mediatype=object.mimetype)) else: self.manifest.addElement(manifest.FileEntry(fullpath=folder, mediatype=object.mimetype)) # Write styles self.manifest.addElement(manifest.FileEntry(fullpath="%sstyles.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%sstyles.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.stylesxml()) # Write content self.manifest.addElement(manifest.FileEntry(fullpath="%scontent.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%scontent.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.contentxml()) # Write settings if object.settings.hasChildNodes(): self.manifest.addElement(manifest.FileEntry(fullpath="%ssettings.xml" % folder, mediatype="text/xml")) zi = zipfile.ZipInfo("%ssettings.xml" % folder, self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.settingsxml()) # Write meta if self == object: self.manifest.addElement(manifest.FileEntry(fullpath="meta.xml", mediatype="text/xml")) zi = zipfile.ZipInfo("meta.xml", self._now) zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr = UNIXPERMS self._z.writestr(zi, object.metaxml()) # Write subobjects subobjectnum = 1 for subobject in object.childobjects: self._saveXmlObjects(subobject, '%sObject %d/' % (folder, subobjectnum)) subobjectnum += 1 # Document's DOM methods def createElement(self, element): """ Inconvenient interface to create an element, but follows XML-DOM. Does not allow attributes as argument, therefore can't check grammar. """ return element(check_grammar=False) def createTextNode(self, data): """ Method to create a text node """ return element.Text(data) def createCDATASection(self, data): """ Method to create a CDATA section """ return element.CDATASection(data) def getMediaType(self): """ Returns the media type """ return self.mimetype def getStyleByName(self, name): """ Finds a style object based on the name """ ncname = make_NCName(name) if self._styles_dict == {}: self.rebuild_caches() return self._styles_dict.get(ncname, None) def getElementsByType(self, element): """ Gets elements based on the type, which is function from text.py, draw.py etc. """ obj = element(check_grammar=False) if self.element_dict == {}: self.rebuild_caches() return self.element_dict.get(obj.qname, []) # Convenience functions def OpenDocumentChart(): """ Creates a chart document """ doc = OpenDocument('application/vnd.oasis.opendocument.chart') doc.chart = Chart() doc.body.addElement(doc.chart) return doc def OpenDocumentDrawing(): """ Creates a drawing document """ doc = OpenDocument('application/vnd.oasis.opendocument.graphics') doc.drawing = Drawing() doc.body.addElement(doc.drawing) return doc def OpenDocumentImage(): """ Creates an image document """ doc = OpenDocument('application/vnd.oasis.opendocument.image') doc.image = Image() doc.body.addElement(doc.image) return doc def OpenDocumentPresentation(): """ Creates a presentation document """ doc = OpenDocument('application/vnd.oasis.opendocument.presentation') doc.presentation = Presentation() doc.body.addElement(doc.presentation) return doc def OpenDocumentSpreadsheet(): """ Creates a spreadsheet document """ doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet') doc.spreadsheet = Spreadsheet() doc.body.addElement(doc.spreadsheet) return doc def OpenDocumentText(): """ Creates a text document """ doc = OpenDocument('application/vnd.oasis.opendocument.text') doc.text = Text() doc.body.addElement(doc.text) return doc def OpenDocumentTextMaster(): """ Creates a text master document """ doc = OpenDocument('application/vnd.oasis.opendocument.text-master') doc.text = Text() doc.body.addElement(doc.text) return doc def __loadxmlparts(z, manifest, doc, objectpath): from xml.sax import handler, make_parser from .load import LoadParser for xmlfile in (objectpath+'settings.xml', objectpath+'meta.xml', objectpath+'content.xml', objectpath+'styles.xml'): if xmlfile not in manifest: continue try: xmlpart = z.read(xmlfile) doc._parsing = xmlfile parser = make_parser() parser.setFeature(handler.feature_namespaces, 1) parser.setContentHandler(LoadParser(doc)) parser.setErrorHandler(handler.ErrorHandler()) inpsrc = InputSource() inpsrc.setByteStream(BytesIO(xmlpart)) parser.setFeature(handler.feature_external_ges, False) # Changed by Kovid to ignore external DTDs parser.parse(inpsrc) del doc._parsing except KeyError: pass def load(odffile): """ Load an ODF file into memory Returns a reference to the structure """ z = zipfile.ZipFile(odffile) try: mimetype = z.read('mimetype') except KeyError: # Added by Kovid to handle malformed odt files mimetype = 'application/vnd.oasis.opendocument.text' doc = OpenDocument(mimetype, add_generator=False) # Look in the manifest file to see if which of the four files there are manifestpart = z.read('META-INF/manifest.xml') manifest = manifestlist(manifestpart) __loadxmlparts(z, manifest, doc, '') for mentry,mvalue in manifest.items(): if mentry[:9] == "Pictures/" and len(mentry) > 9: doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry)) elif mentry == "Thumbnails/thumbnail.png": doc.addThumbnail(z.read(mentry)) elif mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'): pass # Load subobjects into structure elif mentry[:7] == "Object " and len(mentry) < 11 and mentry[-1] == "/": subdoc = OpenDocument(mvalue['media-type'], add_generator=False) doc.addObject(subdoc, "/" + mentry[:-1]) __loadxmlparts(z, manifest, subdoc, mentry) elif mentry[:7] == "Object ": pass # Don't load subobjects as opaque objects else: if mvalue['full-path'][-1] == '/': doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None)) else: doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry))) # Add the SUN junk here to the struct somewhere # It is cached data, so it can be out-of-date z.close() b = doc.getElementsByType(Body) if mimetype[:39] == 'application/vnd.oasis.opendocument.text': doc.text = b[0].firstChild elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics': doc.graphics = b[0].firstChild elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation': doc.presentation = b[0].firstChild elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet': doc.spreadsheet = b[0].firstChild elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart': doc.chart = b[0].firstChild elif mimetype[:40] == 'application/vnd.oasis.opendocument.image': doc.image = b[0].firstChild elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula': doc.formula = b[0].firstChild return doc # vim: set expandtab sw=4 :
26,809
Python
.py
620
34.172581
121
0.629142
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,429
userfield.py
kovidgoyal_calibre/src/odf/userfield.py
#!/usr/bin/env python # Copyright (C) 2006-2009 Søren Roug, European Environment Agency # # This is free software. You may redistribute it under the terms # of the Apache license and the GNU General Public License Version # 2 or at your option any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): Michael Howitz, gocept gmbh & co. kg # # $Id: userfield.py 447 2008-07-10 20:01:30Z roug $ """Class to show and manipulate user fields in odf documents.""" import sys import zipfile from odf.namespaces import OFFICENS from odf.opendocument import load from odf.text import UserFieldDecl OUTENCODING = "utf-8" # OpenDocument v.1.0 section 6.7.1 VALUE_TYPES = { 'float': (OFFICENS, 'value'), 'percentage': (OFFICENS, 'value'), 'currency': (OFFICENS, 'value'), 'date': (OFFICENS, 'date-value'), 'time': (OFFICENS, 'time-value'), 'boolean': (OFFICENS, 'boolean-value'), 'string': (OFFICENS, 'string-value'), } class UserFields: """List, view and manipulate user fields.""" # these attributes can be a filename or a file like object src_file = None dest_file = None def __init__(self, src=None, dest=None): """Constructor src ... source document name, file like object or None for stdin dest ... destination document name, file like object or None for stdout """ self.src_file = src self.dest_file = dest self.document = None def loaddoc(self): if isinstance(self.src_file, (bytes, str)): # src_file is a filename, check if it is a zip-file if not zipfile.is_zipfile(self.src_file): raise TypeError("%s is no odt file." % self.src_file) elif self.src_file is None: # use stdin if no file given self.src_file = sys.stdin self.document = load(self.src_file) def savedoc(self): # write output if self.dest_file is None: # use stdout if no filename given self.document.save('-') else: self.document.save(self.dest_file) def list_fields(self): """List (extract) all known user-fields. Returns list of user-field names. """ return [x[0] for x in self.list_fields_and_values()] def list_fields_and_values(self, field_names=None): """List (extract) user-fields with type and value. field_names ... list of field names to show or None for all. Returns list of tuples (<field name>, <field type>, <value>). """ self.loaddoc() found_fields = [] all_fields = self.document.getElementsByType(UserFieldDecl) for f in all_fields: value_type = f.getAttribute('valuetype') if value_type == 'string': value = f.getAttribute('stringvalue') else: value = f.getAttribute('value') field_name = f.getAttribute('name') if field_names is None or field_name in field_names: found_fields.append((field_name.encode(OUTENCODING), value_type.encode(OUTENCODING), value.encode(OUTENCODING))) return found_fields def list_values(self, field_names): """Extract the contents of given field names from the file. field_names ... list of field names Returns list of field values. """ return [x[2] for x in self.list_fields_and_values(field_names)] def get(self, field_name): """Extract the contents of this field from the file. Returns field value or None if field does not exist. """ values = self.list_values([field_name]) if not values: return None return values[0] def get_type_and_value(self, field_name): """Extract the type and contents of this field from the file. Returns tuple (<type>, <field-value>) or None if field does not exist. """ fields = self.list_fields_and_values([field_name]) if not fields: return None field_name, value_type, value = fields[0] return value_type, value def update(self, data): """Set the value of user fields. The field types will be the same. data ... dict, with field name as key, field value as value Returns None """ self.loaddoc() all_fields = self.document.getElementsByType(UserFieldDecl) for f in all_fields: field_name = f.getAttribute('name') if field_name in data: value_type = f.getAttribute('valuetype') value = data.get(field_name) if value_type == 'string': f.setAttribute('stringvalue', value) else: f.setAttribute('value', value) self.savedoc()
5,374
Python
.py
130
32.861538
80
0.622743
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,430
math.py
kovidgoyal_calibre/src/odf/math.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import MATHNS # ODF 1.0 section 12.5 # Mathematical content is represented by MathML 2.0 # Autogenerated def Math(**args): return Element(qname=(MATHNS,'math'), **args)
1,044
Python
.py
25
40.36
80
0.778875
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,431
chart.py
kovidgoyal_calibre/src/odf/chart.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import CHARTNS # Autogenerated def Axis(**args): return Element(qname=(CHARTNS,'axis'), **args) def Categories(**args): return Element(qname=(CHARTNS,'categories'), **args) def Chart(**args): return Element(qname=(CHARTNS,'chart'), **args) def DataPoint(**args): return Element(qname=(CHARTNS,'data-point'), **args) def Domain(**args): return Element(qname=(CHARTNS,'domain'), **args) def ErrorIndicator(**args): return Element(qname=(CHARTNS,'error-indicator'), **args) def Floor(**args): return Element(qname=(CHARTNS,'floor'), **args) def Footer(**args): return Element(qname=(CHARTNS,'footer'), **args) def Grid(**args): return Element(qname=(CHARTNS,'grid'), **args) def Legend(**args): return Element(qname=(CHARTNS,'legend'), **args) def MeanValue(**args): return Element(qname=(CHARTNS,'mean-value'), **args) def PlotArea(**args): return Element(qname=(CHARTNS,'plot-area'), **args) def RegressionCurve(**args): return Element(qname=(CHARTNS,'regression-curve'), **args) def Series(**args): return Element(qname=(CHARTNS,'series'), **args) def StockGainMarker(**args): return Element(qname=(CHARTNS,'stock-gain-marker'), **args) def StockLossMarker(**args): return Element(qname=(CHARTNS,'stock-loss-marker'), **args) def StockRangeLine(**args): return Element(qname=(CHARTNS,'stock-range-line'), **args) def Subtitle(**args): return Element(qname=(CHARTNS,'subtitle'), **args) def SymbolImage(**args): return Element(qname=(CHARTNS,'symbol-image'), **args) def Title(**args): return Element(qname=(CHARTNS,'title'), **args) def Wall(**args): return Element(qname=(CHARTNS,'wall'), **args)
2,592
Python
.py
63
38.095238
80
0.726248
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,432
easyliststyle.py
kovidgoyal_calibre/src/odf/easyliststyle.py
# Create a <text:list-style> element from a text string. # Copyright (C) 2008 J. David Eisenberg # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Contributor(s): # import re from polyglot.builtins import unicode_type from .style import ListLevelProperties from .text import ListLevelStyleBullet, ListLevelStyleNumber, ListStyle """ Create a <text:list-style> element from a string or array. List styles require a lot of code to create one level at a time. These routines take a string and delimiter, or a list of strings, and creates a <text:list-style> element for you. Each item in the string (or array) represents a list level * style for levels 1-10.</p> * * <p>If an item contains <code>1</code>, <code>I</code>, * <code>i</code>, <code>A</code>, or <code>a</code>, then it is presumed * to be a numbering style; otherwise it is a bulleted style.</p> """ _MAX_LIST_LEVEL = 10 SHOW_ALL_LEVELS = True SHOW_ONE_LEVEL = False def styleFromString(name, specifiers, delim, spacing, showAllLevels): specArray = specifiers.split(delim) return styleFromList(name, specArray, spacing, showAllLevels) def styleFromList(styleName, specArray, spacing, showAllLevels): bullet = "" numPrefix = "" numSuffix = "" cssLengthNum = 0 cssLengthUnits = "" numbered = False displayLevels = 0 listStyle = ListStyle(name=styleName) numFormatPattern = re.compile("([1IiAa])") cssLengthPattern = re.compile("([^a-z]+)\\s*([a-z]+)?") m = cssLengthPattern.search(spacing) if (m is not None): cssLengthNum = float(m.group(1)) if (m.lastindex == 2): cssLengthUnits = m.group(2) i = 0 while i < len(specArray): specification = specArray[i] m = numFormatPattern.search(specification) if (m is not None): numPrefix = specification[0:m.start(1)] numSuffix = specification[m.end(1):] bullet = "" numbered = True if (showAllLevels): displayLevels = i + 1 else: displayLevels = 1 else: # it's a bullet style bullet = specification numPrefix = "" numSuffix = "" displayLevels = 1 numbered = False if (numbered): lls = ListLevelStyleNumber(level=(i+1)) if (numPrefix != ''): lls.setAttribute('numprefix', numPrefix) if (numSuffix != ''): lls.setAttribute('numsuffix', numSuffix) lls.setAttribute('displaylevels', displayLevels) else: lls = ListLevelStyleBullet(level=(i+1),bulletchar=bullet[0]) llp = ListLevelProperties() llp.setAttribute('spacebefore', unicode_type(cssLengthNum * (i+1)) + cssLengthUnits) llp.setAttribute('minlabelwidth', unicode_type(cssLengthNum) + cssLengthUnits) lls.addElement(llp) listStyle.addElement(lls) i += 1 return listStyle # vim: set expandtab sw=4 :
3,705
Python
.py
93
33.83871
92
0.665
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,433
xforms.py
kovidgoyal_calibre/src/odf/xforms.py
# Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from .element import Element from .namespaces import XFORMSNS # ODF 1.0 section 11.2 # XForms is designed to be embedded in another XML format. # Autogenerated def Model(**args): return Element(qname=(XFORMSNS,'model'), **args) def Instance(**args): return Element(qname=(XFORMSNS,'instance'), **args) def Bind(**args): return Element(qname=(XFORMSNS,'bind'), **args)
1,208
Python
.py
29
39.931034
80
0.766667
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,434
load.py
kovidgoyal_calibre/src/odf/load.py
#!/usr/bin/env python # Copyright (C) 2007-2008 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # This script is to be embedded in opendocument.py later # The purpose is to read an ODT/ODP/ODS file and create the datastructure # in memory. The user should then be able to make operations and then save # the structure again. from xml.sax import handler from .element import Element from .namespaces import OFFICENS # # Parse the XML files # class LoadParser(handler.ContentHandler): """ Extract headings from content.xml of an ODT file """ triggers = ( (OFFICENS, 'automatic-styles'), (OFFICENS, 'body'), (OFFICENS, 'font-face-decls'), (OFFICENS, 'master-styles'), (OFFICENS, 'meta'), (OFFICENS, 'scripts'), (OFFICENS, 'settings'), (OFFICENS, 'styles')) def __init__(self, document): self.doc = document self.data = [] self.level = 0 self.parse = False def characters(self, data): if self.parse is False: return self.data.append(data) def startElementNS(self, tag, qname, attrs): if tag in self.triggers: self.parse = True if self.doc._parsing != "styles.xml" and tag == (OFFICENS, 'font-face-decls'): self.parse = False if self.parse is False: return self.level = self.level + 1 # Add any accumulated text content content = ''.join(self.data) if len(content.strip()) > 0: self.parent.addText(content, check_grammar=False) self.data = [] # Create the element attrdict = {} for (att,value) in attrs.items(): attrdict[att] = value try: e = Element(qname=tag, qattributes=attrdict, check_grammar=False) self.curr = e except AttributeError as v: print("Error: %s" % v) if tag == (OFFICENS, 'automatic-styles'): e = self.doc.automaticstyles elif tag == (OFFICENS, 'body'): e = self.doc.body elif tag == (OFFICENS, 'master-styles'): e = self.doc.masterstyles elif tag == (OFFICENS, 'meta'): e = self.doc.meta elif tag == (OFFICENS,'scripts'): e = self.doc.scripts elif tag == (OFFICENS,'settings'): e = self.doc.settings elif tag == (OFFICENS,'styles'): e = self.doc.styles elif self.doc._parsing == "styles.xml" and tag == (OFFICENS, 'font-face-decls'): e = self.doc.fontfacedecls elif hasattr(self,'parent'): self.parent.addElement(e, check_grammar=False) self.parent = e def endElementNS(self, tag, qname): if self.parse is False: return self.level = self.level - 1 # Changed by Kovid to deal with <span> tags with only whitespace # content. data = q = ''.join(self.data) tn = getattr(self.curr, 'tagName', '') try: do_strip = not tn.startswith('text:') except: do_strip = True if do_strip: q = q.strip() if q: self.curr.addText(data, check_grammar=False) self.data = [] self.curr = self.curr.parentNode self.parent = self.curr if tag in self.triggers: self.parse = False
4,115
Python
.py
107
30.906542
88
0.620025
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,435
odf2xhtml.py
kovidgoyal_calibre/src/odf/odf2xhtml.py
#!/usr/bin/env python # Copyright (C) 2006-2010 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # import pdb # pdb.set_trace() from collections import defaultdict from xml.dom import Node from xml.sax import handler from xml.sax.saxutils import escape, quoteattr from polyglot.builtins import unicode_type from .namespaces import ( ANIMNS, CHARTNS, CONFIGNS, DCNS, DR3DNS, DRAWNS, FONS, FORMNS, MATHNS, METANS, NUMBERNS, OFFICENS, PRESENTATIONNS, SCRIPTNS, SMILNS, STYLENS, SVGNS, TABLENS, TEXTNS, XLINKNS, ) from .opendocument import load if False: # Added by Kovid DR3DNS, MATHNS, CHARTNS, CONFIGNS, ANIMNS, FORMNS, SMILNS, SCRIPTNS # Handling of styles # # First there are font face declarations. These set up a font style that will be # referenced from a text-property. The declaration describes the font making # it possible for the application to find a similar font should the system not # have that particular one. The StyleToCSS stores these attributes to be used # for the CSS2 font declaration. # # Then there are default-styles. These set defaults for various style types: # "text", "paragraph", "section", "ruby", "table", "table-column", "table-row", # "table-cell", "graphic", "presentation", "drawing-page", "chart". # Since CSS2 can't refer to another style, ODF2XHTML add these to all # styles unless overridden. # # The real styles are declared in the <style:style> element. They have a # family referring to the default-styles, and may have a parent style. # # Styles have scope. The same name can be used for both paragraph and # character etc. styles Since CSS2 has no scope we use a prefix. (Not elegant) # In ODF a style can have a parent, these parents can be chained. class StyleToCSS: """ The purpose of the StyleToCSS class is to contain the rules to convert ODF styles to CSS2. Since it needs the generic fonts, it would probably make sense to also contain the Styles in a dict as well.. """ def __init__(self): # Font declarations self.fontdict = {} # Fill-images from presentations for backgrounds self.fillimages = {} self.ruleconversions = { (DRAWNS,'fill-image-name'): self.c_drawfillimage, (FONS,"background-color"): self.c_fo, (FONS,"border"): self.c_fo, (FONS,"border-bottom"): self.c_fo, (FONS,"border-left"): self.c_fo, (FONS,"border-right"): self.c_fo, (FONS,"border-top"): self.c_fo, (FONS,"break-after"): self.c_break, # Added by Kovid (FONS,"break-before"): self.c_break, # Added by Kovid (FONS,"color"): self.c_fo, (FONS,"font-family"): self.c_fo, (FONS,"font-size"): self.c_fo, (FONS,"font-style"): self.c_fo, (FONS,"font-variant"): self.c_fo, (FONS,"font-weight"): self.c_fo, (FONS,"line-height"): self.c_fo, (FONS,"margin"): self.c_fo, (FONS,"margin-bottom"): self.c_fo, (FONS,"margin-left"): self.c_fo, (FONS,"margin-right"): self.c_fo, (FONS,"margin-top"): self.c_fo, (FONS,"min-height"): self.c_fo, (FONS,"padding"): self.c_fo, (FONS,"padding-bottom"): self.c_fo, (FONS,"padding-left"): self.c_fo, (FONS,"padding-right"): self.c_fo, (FONS,"padding-top"): self.c_fo, (FONS,"page-width"): self.c_page_width, (FONS,"page-height"): self.c_page_height, (FONS,"text-align"): self.c_text_align, (FONS,"text-indent") :self.c_fo, (TABLENS,'border-model') :self.c_border_model, (STYLENS,'column-width') : self.c_width, (STYLENS,"font-name"): self.c_fn, (STYLENS,'horizontal-pos'): self.c_hp, (STYLENS,'text-position'): self.c_text_position, (STYLENS,'text-line-through-style'): self.c_text_line_through_style, (STYLENS,'text-underline-style'): self.c_text_underline_style, (STYLENS,'width') : self.c_width, # FIXME Should do style:vertical-pos here } def save_font(self, name, family, generic): """ It is possible that the HTML browser doesn't know how to show a particular font. Fortunately ODF provides generic fallbacks. Unfortunately they are not the same as CSS2. CSS2: serif, sans-serif, cursive, fantasy, monospace ODF: roman, swiss, modern, decorative, script, system This method put the font and fallback into a dictionary """ htmlgeneric = "sans-serif" if generic == "roman": htmlgeneric = "serif" elif generic == "swiss": htmlgeneric = "sans-serif" elif generic == "modern": htmlgeneric = "monospace" elif generic == "decorative": htmlgeneric = "sans-serif" elif generic == "script": htmlgeneric = "monospace" elif generic == "system": htmlgeneric = "serif" self.fontdict[name] = (family, htmlgeneric) def c_drawfillimage(self, ruleset, sdict, rule, val): """ Fill a figure with an image. Since CSS doesn't let you resize images this should really be implemented as an absolutely position <img> with a width and a height """ sdict['background-image'] = "url('%s')" % self.fillimages[val] def c_fo(self, ruleset, sdict, rule, val): """ XSL formatting attributes """ selector = rule[1] sdict[selector] = val def c_break(self, ruleset, sdict, rule, val): # Added by Kovid property = 'page-' + rule[1] values = {'auto': 'auto', 'column': 'always', 'page': 'always', 'even-page': 'left', 'odd-page': 'right', 'inherit': 'inherit'} sdict[property] = values.get(val, 'auto') def c_border_model(self, ruleset, sdict, rule, val): """ Convert to CSS2 border model """ if val == 'collapsing': sdict['border-collapse'] ='collapse' else: sdict['border-collapse'] ='separate' def c_width(self, ruleset, sdict, rule, val): """ Set width of box """ sdict['width'] = val def c_text_align(self, ruleset, sdict, rule, align): """ Text align """ if align == "start": align = "left" if align == "end": align = "right" sdict['text-align'] = align def c_fn(self, ruleset, sdict, rule, fontstyle): """ Generate the CSS font family A generic font can be found in two ways. In a <style:font-face> element or as a font-family-generic attribute in text-properties. """ generic = ruleset.get((STYLENS,'font-family-generic')) if generic is not None: self.save_font(fontstyle, fontstyle, generic) family, htmlgeneric = self.fontdict.get(fontstyle, (fontstyle, 'serif')) sdict['font-family'] = '%s, %s' % (family, htmlgeneric) def c_text_position(self, ruleset, sdict, rule, tp): """ Text position. This is used e.g. to make superscript and subscript This attribute can have one or two values. The first value must be present and specifies the vertical text position as a percentage that relates to the current font height or it takes one of the values sub or super. Negative percentages or the sub value place the text below the baseline. Positive percentages or the super value place the text above the baseline. If sub or super is specified, the application can choose an appropriate text position. The second value is optional and specifies the font height as a percentage that relates to the current font-height. If this value is not specified, an appropriate font height is used. Although this value may change the font height that is displayed, it never changes the current font height that is used for additional calculations. """ textpos = tp.split(' ') if len(textpos) == 2 and textpos[0] != "0%": # Bug in OpenOffice. If vertical-align is 0% - ignore the text size. sdict['font-size'] = textpos[1] if textpos[0] == "super": sdict['vertical-align'] = "33%" elif textpos[0] == "sub": sdict['vertical-align'] = "-33%" else: sdict['vertical-align'] = textpos[0] def c_hp(self, ruleset, sdict, rule, hpos): # FIXME: Frames wrap-style defaults to 'parallel', graphics to 'none'. # It is properly set in the parent-styles, but the program doesn't # collect the information. wrap = ruleset.get((STYLENS,'wrap'),'parallel') # Can have: from-left, left, center, right, from-inside, inside, outside if hpos == "center": sdict['margin-left'] = "auto" sdict['margin-right'] = "auto" # else: # # force it to be *something* then delete it # sdict['margin-left'] = sdict['margin-right'] = '' # del sdict['margin-left'], sdict['margin-right'] if hpos in ("right","outside"): if wrap in ("left", "parallel","dynamic"): sdict['float'] = "right" elif wrap == "run-through": sdict['position'] = "absolute" # Simulate run-through sdict['top'] = "0" sdict['right'] = "0" else: # No wrapping sdict['margin-left'] = "auto" sdict['margin-right'] = "0px" elif hpos in ("left", "inside"): if wrap in ("right", "parallel","dynamic"): sdict['float'] = "left" elif wrap == "run-through": sdict['position'] = "absolute" # Simulate run-through sdict['top'] = "0" sdict['left'] = "0" else: # No wrapping sdict['margin-left'] = "0px" sdict['margin-right'] = "auto" elif hpos in ("from-left", "from-inside"): if wrap in ("right", "parallel"): sdict['float'] = "left" else: sdict['position'] = "relative" # No wrapping if (SVGNS,'x') in ruleset: sdict['left'] = ruleset[(SVGNS,'x')] def c_page_width(self, ruleset, sdict, rule, val): """ Set width of box HTML doesn't really have a page-width. It is always 100% of the browser width """ sdict['width'] = val def c_text_underline_style(self, ruleset, sdict, rule, val): """ Set underline decoration HTML doesn't really have a page-width. It is always 100% of the browser width """ if val and val != "none": sdict['text-decoration'] = "underline" def c_text_line_through_style(self, ruleset, sdict, rule, val): """ Set underline decoration HTML doesn't really have a page-width. It is always 100% of the browser width """ if val and val != "none": sdict['text-decoration'] = "line-through" def c_page_height(self, ruleset, sdict, rule, val): """ Set height of box """ sdict['height'] = val def convert_styles(self, ruleset): """ Rule is a tuple of (namespace, name). If the namespace is '' then it is already CSS2 """ sdict = {} for rule,val in ruleset.items(): if rule[0] == '': sdict[rule[1]] = val continue method = self.ruleconversions.get(rule, None) if method: method(ruleset, sdict, rule, val) return sdict class TagStack: def __init__(self): self.stack = [] def push(self, tag, attrs): self.stack.append((tag, attrs)) def pop(self): item = self.stack.pop() return item def stackparent(self): item = self.stack[-1] return item[1] def rfindattr(self, attr): """ Find a tag with the given attribute """ for tag, attrs in self.stack: if attr in attrs: return attrs[attr] return None def count_tags(self, tag): c = 0 for ttag, tattrs in self.stack: if ttag == tag: c = c + 1 return c special_styles = { 'S-Emphasis':'em', 'S-Citation':'cite', 'S-Strong_20_Emphasis':'strong', 'S-Variable':'var', 'S-Definition':'dfn', 'S-Teletype':'tt', 'P-Heading_20_1':'h1', 'P-Heading_20_2':'h2', 'P-Heading_20_3':'h3', 'P-Heading_20_4':'h4', 'P-Heading_20_5':'h5', 'P-Heading_20_6':'h6', # 'P-Caption':'caption', 'P-Addressee':'address', # 'P-List_20_Heading':'dt', # 'P-List_20_Contents':'dd', 'P-Preformatted_20_Text':'pre', # 'P-Table_20_Heading':'th', # 'P-Table_20_Contents':'td', # 'P-Text_20_body':'p' } # ----------------------------------------------------------------------------- # # ODFCONTENTHANDLER # # ----------------------------------------------------------------------------- class ODF2XHTML(handler.ContentHandler): """ The ODF2XHTML parses an ODF file and produces XHTML""" def __init__(self, generate_css=True, embedable=False): # Tags self.generate_css = generate_css self.frame_stack = [] self.list_number_map = defaultdict(lambda : 1) self.list_id_map = {} self.list_class_stack = [] self.elements = { (DCNS, 'title'): (self.s_processcont, self.e_dc_title), (DCNS, 'language'): (self.s_processcont, self.e_dc_contentlanguage), (DCNS, 'creator'): (self.s_processcont, self.e_dc_creator), (DCNS, 'description'): (self.s_processcont, self.e_dc_metatag), (DCNS, 'date'): (self.s_processcont, self.e_dc_metatag), (DRAWNS, 'custom-shape'): (self.s_custom_shape, self.e_custom_shape), (DRAWNS, 'frame'): (self.s_draw_frame, self.e_draw_frame), (DRAWNS, 'image'): (self.s_draw_image, None), (DRAWNS, 'fill-image'): (self.s_draw_fill_image, None), (DRAWNS, "layer-set"):(self.s_ignorexml, None), (DRAWNS, 'object'): (self.s_draw_object, None), (DRAWNS, 'object-ole'): (self.s_draw_object_ole, None), (DRAWNS, 'page'): (self.s_draw_page, self.e_draw_page), (DRAWNS, 'text-box'): (self.s_draw_textbox, self.e_draw_textbox), (METANS, 'creation-date'):(self.s_processcont, self.e_dc_metatag), (METANS, 'generator'):(self.s_processcont, self.e_dc_metatag), (METANS, 'initial-creator'): (self.s_processcont, self.e_dc_metatag), (METANS, 'keyword'): (self.s_processcont, self.e_dc_metatag), (NUMBERNS, "boolean-style"):(self.s_ignorexml, None), (NUMBERNS, "currency-style"):(self.s_ignorexml, None), (NUMBERNS, "date-style"):(self.s_ignorexml, None), (NUMBERNS, "number-style"):(self.s_ignorexml, None), (NUMBERNS, "text-style"):(self.s_ignorexml, None), (OFFICENS, "annotation"):(self.s_ignorexml, None), (OFFICENS, "automatic-styles"):(self.s_office_automatic_styles, None), (OFFICENS, "document"):(self.s_office_document_content, self.e_office_document_content), (OFFICENS, "document-content"):(self.s_office_document_content, self.e_office_document_content), (OFFICENS, "forms"):(self.s_ignorexml, None), (OFFICENS, "master-styles"):(self.s_office_master_styles, None), (OFFICENS, "meta"):(self.s_ignorecont, None), (OFFICENS, "presentation"):(self.s_office_presentation, self.e_office_presentation), (OFFICENS, "spreadsheet"):(self.s_office_spreadsheet, self.e_office_spreadsheet), (OFFICENS, "styles"):(self.s_office_styles, None), (OFFICENS, "text"):(self.s_office_text, self.e_office_text), (OFFICENS, "scripts"):(self.s_ignorexml, None), (OFFICENS, "settings"):(self.s_ignorexml, None), (PRESENTATIONNS, "notes"):(self.s_ignorexml, None), # (STYLENS, "default-page-layout"):(self.s_style_default_page_layout, self.e_style_page_layout), (STYLENS, "default-page-layout"):(self.s_ignorexml, None), (STYLENS, "default-style"):(self.s_style_default_style, self.e_style_default_style), (STYLENS, "drawing-page-properties"):(self.s_style_handle_properties, None), (STYLENS, "font-face"):(self.s_style_font_face, None), # (STYLENS, "footer"):(self.s_style_footer, self.e_style_footer), # (STYLENS, "footer-style"):(self.s_style_footer_style, None), (STYLENS, "graphic-properties"):(self.s_style_handle_properties, None), (STYLENS, "handout-master"):(self.s_ignorexml, None), # (STYLENS, "header"):(self.s_style_header, self.e_style_header), # (STYLENS, "header-footer-properties"):(self.s_style_handle_properties, None), # (STYLENS, "header-style"):(self.s_style_header_style, None), (STYLENS, "master-page"):(self.s_style_master_page, None), (STYLENS, "page-layout-properties"):(self.s_style_handle_properties, None), (STYLENS, "page-layout"):(self.s_style_page_layout, self.e_style_page_layout), # (STYLENS, "page-layout"):(self.s_ignorexml, None), (STYLENS, "paragraph-properties"):(self.s_style_handle_properties, None), (STYLENS, "style"):(self.s_style_style, self.e_style_style), (STYLENS, "table-cell-properties"):(self.s_style_handle_properties, None), (STYLENS, "table-column-properties"):(self.s_style_handle_properties, None), (STYLENS, "table-properties"):(self.s_style_handle_properties, None), (STYLENS, "text-properties"):(self.s_style_handle_properties, None), (SVGNS, 'desc'): (self.s_ignorexml, None), (TABLENS, 'covered-table-cell'): (self.s_ignorexml, None), (TABLENS, 'table-cell'): (self.s_table_table_cell, self.e_table_table_cell), (TABLENS, 'table-column'): (self.s_table_table_column, None), (TABLENS, 'table-row'): (self.s_table_table_row, self.e_table_table_row), (TABLENS, 'table'): (self.s_table_table, self.e_table_table), (TEXTNS, 'a'): (self.s_text_a, self.e_text_a), (TEXTNS, "alphabetical-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "bibliography-configuration"):(self.s_ignorexml, None), (TEXTNS, "bibliography-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'bookmark'): (self.s_text_bookmark, None), (TEXTNS, 'bookmark-start'): (self.s_text_bookmark, None), (TEXTNS, 'reference-mark-start'): (self.s_text_bookmark, None), # Added by Kovid (TEXTNS, 'bookmark-ref'): (self.s_text_bookmark_ref, self.e_text_a), (TEXTNS, 'reference-ref'): (self.s_text_bookmark_ref, self.e_text_a), # Added by Kovid (TEXTNS, 'bookmark-ref-start'): (self.s_text_bookmark_ref, None), (TEXTNS, 'h'): (self.s_text_h, self.e_text_h), (TEXTNS, "illustration-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'line-break'):(self.s_text_line_break, None), (TEXTNS, "linenumbering-configuration"):(self.s_ignorexml, None), (TEXTNS, "list"):(self.s_text_list, self.e_text_list), (TEXTNS, "list-item"):(self.s_text_list_item, self.e_text_list_item), (TEXTNS, "list-level-style-bullet"):(self.s_text_list_level_style_bullet, self.e_text_list_level_style_bullet), (TEXTNS, "list-level-style-number"):(self.s_text_list_level_style_number, self.e_text_list_level_style_number), (TEXTNS, "list-style"):(None, None), (TEXTNS, "note"):(self.s_text_note, None), (TEXTNS, "note-body"):(self.s_text_note_body, self.e_text_note_body), (TEXTNS, "note-citation"):(None, self.e_text_note_citation), (TEXTNS, "notes-configuration"):(self.s_ignorexml, None), (TEXTNS, "object-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'p'): (self.s_text_p, self.e_text_p), (TEXTNS, 's'): (self.s_text_s, None), (TEXTNS, 'span'): (self.s_text_span, self.e_text_span), (TEXTNS, 'tab'): (self.s_text_tab, None), (TEXTNS, "table-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "table-of-content-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "user-index-source"):(self.s_text_x_source, self.e_text_x_source), } if embedable: self.make_embedable() self._resetobject() def set_plain(self): """ Tell the parser to not generate CSS """ self.generate_css = False def set_embedable(self): """ Tells the converter to only output the parts inside the <body>""" self.elements[(OFFICENS, "text")] = (None,None) self.elements[(OFFICENS, "spreadsheet")] = (None,None) self.elements[(OFFICENS, "presentation")] = (None,None) self.elements[(OFFICENS, "document-content")] = (None,None) def add_style_file(self, stylefilename, media=None): """ Add a link to an external style file. Also turns of the embedding of styles in the HTML """ self.use_internal_css = False self.stylefilename = stylefilename if media: self.metatags.append(f'<link rel="stylesheet" type="text/css" href="{stylefilename}" media="{media}"/>\n') else: self.metatags.append('<link rel="stylesheet" type="text/css" href="%s"/>\n' % (stylefilename)) def _resetfootnotes(self): # Footnotes and endnotes self.notedict = {} self.currentnote = 0 self.notebody = '' def _resetobject(self): self.lines = [] self._wfunc = self._wlines self.xmlfile = '' self.title = '' self.language = '' self.creator = '' self.data = [] self.tagstack = TagStack() self.htmlstack = [] self.pstack = [] self.processelem = True self.processcont = True self.listtypes = {} self.headinglevels = [0, 0,0,0,0,0, 0,0,0,0,0] # level 0 to 10 self.use_internal_css = True self.cs = StyleToCSS() self.anchors = {} # Style declarations self.stylestack = [] self.styledict = {} self.currentstyle = None self.list_starts = {} self._resetfootnotes() # Tags from meta.xml self.metatags = [] def writeout(self, s): if s != '': self._wfunc(s) def writedata(self): d = ''.join(self.data) if d != '': self.writeout(escape(d)) def opentag(self, tag, attrs={}, block=False): """ Create an open HTML tag """ self.htmlstack.append((tag,attrs,block)) a = [] for key,val in attrs.items(): a.append(f'''{key}={quoteattr(val)}''') if len(a) == 0: self.writeout("<%s>" % tag) else: self.writeout("<{} {}>".format(tag, " ".join(a))) if block: self.writeout("\n") def closetag(self, tag, block=True): """ Close an open HTML tag """ self.htmlstack.pop() self.writeout("</%s>" % tag) if block: self.writeout("\n") def emptytag(self, tag, attrs={}): a = [] for key,val in attrs.items(): a.append(f'''{key}={quoteattr(val)}''') self.writeout("<{} {}/>\n".format(tag, " ".join(a))) # -------------------------------------------------- # Interface to parser # -------------------------------------------------- def characters(self, data): if self.processelem and self.processcont: self.data.append(data) def startElementNS(self, tag, qname, attrs): self.pstack.append((self.processelem, self.processcont)) if self.processelem: method = self.elements.get(tag, (None, None))[0] if method: self.handle_starttag(tag, method, attrs) else: self.unknown_starttag(tag,attrs) self.tagstack.push(tag, attrs) def endElementNS(self, tag, qname): stag, attrs = self.tagstack.pop() if self.processelem: method = self.elements.get(tag, (None, None))[1] if method: self.handle_endtag(tag, attrs, method) else: self.unknown_endtag(tag, attrs) self.processelem, self.processcont = self.pstack.pop() # -------------------------------------------------- def handle_starttag(self, tag, method, attrs): method(tag,attrs) def handle_endtag(self, tag, attrs, method): method(tag, attrs) def unknown_starttag(self, tag, attrs): pass def unknown_endtag(self, tag, attrs): pass def s_ignorexml(self, tag, attrs): """ Ignore this xml element and all children of it It will automatically stop ignoring """ self.processelem = False def s_ignorecont(self, tag, attrs): """ Stop processing the text nodes """ self.processcont = False def s_processcont(self, tag, attrs): """ Start processing the text nodes """ self.processcont = True def classname(self, attrs): """ Generate a class name from a style name """ c = attrs.get((TEXTNS,'style-name'),'') c = c.replace(".","_") return c def get_anchor(self, name): """ Create a unique anchor id for a href name """ if name not in self.anchors: # Changed by Kovid self.anchors[name] = "anchor%d" % (len(self.anchors) + 1) return self.anchors.get(name) def purgedata(self): self.data = [] # ----------------------------------------------------------------------------- # # Handle meta data # # ----------------------------------------------------------------------------- def e_dc_title(self, tag, attrs): """ Get the title from the meta data and create a HTML <title> """ self.title = ''.join(self.data) # self.metatags.append('<title>%s</title>\n' % escape(self.title)) self.data = [] def e_dc_metatag(self, tag, attrs): """ Any other meta data is added as a <meta> element """ self.metatags.append('<meta name="{}" content={}/>\n'.format(tag[1], quoteattr(''.join(self.data)))) self.data = [] def e_dc_contentlanguage(self, tag, attrs): """ Set the content language. Identifies the targeted audience """ self.language = ''.join(self.data) self.metatags.append('<meta http-equiv="content-language" content="%s"/>\n' % escape(self.language)) self.data = [] def e_dc_creator(self, tag, attrs): """ Set the content creator. Identifies the targeted audience """ self.creator = ''.join(self.data) self.metatags.append('<meta http-equiv="creator" content="%s"/>\n' % escape(self.creator)) self.data = [] def s_custom_shape(self, tag, attrs): """ A <draw:custom-shape> is made into a <div> in HTML which is then styled """ anchor_type = attrs.get((TEXTNS,'anchor-type'),'notfound') htmltag = 'div' name = "G-" + attrs.get((DRAWNS,'style-name'), "") if name == 'G-': name = "PR-" + attrs.get((PRESENTATIONNS,'style-name'), "") name = name.replace(".","_") if anchor_type == "paragraph": style = 'position:absolute;' elif anchor_type == 'char': style = "position:absolute;" elif anchor_type == 'as-char': htmltag = 'div' style = '' else: style = "position: absolute;" if (SVGNS,"width") in attrs: style = style + "width:" + attrs[(SVGNS,"width")] + ";" if (SVGNS,"height") in attrs: style = style + "height:" + attrs[(SVGNS,"height")] + ";" if (SVGNS,"x") in attrs: style = style + "left:" + attrs[(SVGNS,"x")] + ";" if (SVGNS,"y") in attrs: style = style + "top:" + attrs[(SVGNS,"y")] + ";" if self.generate_css: self.opentag(htmltag, {'class': name, 'style': style}) else: self.opentag(htmltag) def e_custom_shape(self, tag, attrs): """ End the <draw:frame> """ self.closetag('div') def s_draw_frame(self, tag, attrs): """ A <draw:frame> is made into a <div> in HTML which is then styled """ self.frame_stack.append([]) anchor_type = attrs.get((TEXTNS,'anchor-type'),'notfound') htmltag = 'div' name = "G-" + attrs.get((DRAWNS,'style-name'), "") if name == 'G-': name = "PR-" + attrs.get((PRESENTATIONNS,'style-name'), "") name = name.replace(".","_") if anchor_type == "paragraph": style = 'position:relative;' elif anchor_type == 'char': style = "position:relative;" elif anchor_type == 'as-char': htmltag = 'div' style = '' else: style = "position:absolute;" if (SVGNS,"width") in attrs: style = style + "width:" + attrs[(SVGNS,"width")] + ";" if (SVGNS,"height") in attrs: style = style + "height:" + attrs[(SVGNS,"height")] + ";" if (SVGNS,"x") in attrs: style = style + "left:" + attrs[(SVGNS,"x")] + ";" if (SVGNS,"y") in attrs: style = style + "top:" + attrs[(SVGNS,"y")] + ";" if self.generate_css: self.opentag(htmltag, {'class': name, 'style': style}) else: self.opentag(htmltag) def e_draw_frame(self, tag, attrs): """ End the <draw:frame> """ self.closetag('div') self.frame_stack.pop() def s_draw_fill_image(self, tag, attrs): name = attrs.get((DRAWNS,'name'), "NoName") imghref = attrs[(XLINKNS,"href")] imghref = self.rewritelink(imghref) self.cs.fillimages[name] = imghref def rewritelink(self, imghref): """ Intended to be overloaded if you don't store your pictures in a Pictures subfolder """ return imghref def s_draw_image(self, tag, attrs): """ A <draw:image> becomes an <img/> element """ if self.frame_stack: if self.frame_stack[-1]: return self.frame_stack[-1].append('img') parent = self.tagstack.stackparent() anchor_type = parent.get((TEXTNS,'anchor-type')) imghref = attrs[(XLINKNS,"href")] imghref = self.rewritelink(imghref) htmlattrs = {'alt':"", 'src':imghref} if self.generate_css: if anchor_type != "char": htmlattrs['style'] = "display: block;" self.emptytag('img', htmlattrs) def s_draw_object(self, tag, attrs): """ A <draw:object> is embedded object in the document (e.g. spreadsheet in presentation). """ return # Added by Kovid objhref = attrs[(XLINKNS,"href")] # Remove leading "./": from "./Object 1" to "Object 1" # objhref = objhref [2:] # Not using os.path.join since it fails to find the file on Windows. # objcontentpath = '/'.join([objhref, 'content.xml']) for c in self.document.childnodes: if c.folder == objhref: self._walknode(c.topnode) def s_draw_object_ole(self, tag, attrs): """ A <draw:object-ole> is embedded OLE object in the document (e.g. MS Graph). """ try: class_id = attrs[(DRAWNS,"class-id")] except KeyError: # Added by Kovid to ignore <draw> without the right return # attributes if class_id and class_id.lower() == "00020803-0000-0000-c000-000000000046": # Microsoft Graph 97 Chart tagattrs = {'name':'object_ole_graph', 'class':'ole-graph'} self.opentag('a', tagattrs) self.closetag('a', tagattrs) def s_draw_page(self, tag, attrs): """ A <draw:page> is a slide in a presentation. We use a <fieldset> element in HTML. Therefore if you convert a ODP file, you get a series of <fieldset>s. Override this for your own purpose. """ name = attrs.get((DRAWNS,'name'), "NoName") stylename = attrs.get((DRAWNS,'style-name'), "") stylename = stylename.replace(".","_") masterpage = attrs.get((DRAWNS,'master-page-name'),"") masterpage = masterpage.replace(".","_") if self.generate_css: self.opentag('fieldset', {'class':f"DP-{stylename} MP-{masterpage}"}) else: self.opentag('fieldset') self.opentag('legend') self.writeout(escape(name)) self.closetag('legend') def e_draw_page(self, tag, attrs): self.closetag('fieldset') def s_draw_textbox(self, tag, attrs): style = '' if (FONS,"min-height") in attrs: style = style + "min-height:" + attrs[(FONS,"min-height")] + ";" self.opentag('div') # self.opentag('div', {'style': style}) def e_draw_textbox(self, tag, attrs): """ End the <draw:text-box> """ self.closetag('div') def html_body(self, tag, attrs): self.writedata() if self.generate_css and self.use_internal_css: self.opentag('style', {'type':"text/css"}, True) self.writeout('/*<![CDATA[*/\n') self.generate_stylesheet() self.writeout('/*]]>*/\n') self.closetag('style') self.purgedata() self.closetag('head') self.opentag('body', block=True) # background-color: white removed by Kovid for #9118 # Specifying an explicit bg color prevents ebook readers # from successfully inverting colors # Added styling for endnotes default_styles = """ img { width: 100%; height: 100%; } * { padding: 0; margin: 0; } body { margin: 0 1em; } ol, ul { padding-left: 2em; } a.citation { text-decoration: none } h1.notes-header { page-break-before: always } dl.notes dt { font-size: large } dl.notes dt a { text-decoration: none } dl.notes dd { page-break-after: always } dl.notes dd:last-of-type { page-break-after: avoid } """ def generate_stylesheet(self): for name in self.stylestack: styles = self.styledict.get(name) # Preload with the family's default style if '__style-family' in styles and styles['__style-family'] in self.styledict: familystyle = self.styledict[styles['__style-family']].copy() del styles['__style-family'] for style, val in styles.items(): familystyle[style] = val styles = familystyle # Resolve the remaining parent styles while '__parent-style-name' in styles and styles['__parent-style-name'] in self.styledict: parentstyle = self.styledict[styles['__parent-style-name']].copy() del styles['__parent-style-name'] for style, val in styles.items(): parentstyle[style] = val styles = parentstyle self.styledict[name] = styles # Write the styles to HTML self.writeout(self.default_styles) # Changed by Kovid to not write out endless copies of the same style css_styles = {} for name in self.stylestack: styles = self.styledict.get(name) css2 = tuple(self.cs.convert_styles(styles).items()) if css2 in css_styles: css_styles[css2].append(name) else: css_styles[css2] = [name] def filter_margins(css2): names = {k for k, v in css2} ignore = set() if {'margin-left', 'margin-right', 'margin-top', 'margin-bottom'}.issubset(names): # These come from XML and we cannot preserve XML attribute # order so we assume that margin is to be overridden See # https://bugs.launchpad.net/calibre/+bug/941134 and # https://bugs.launchpad.net/calibre/+bug/1002702 ignore.add('margin') css2 = sorted(css2, key=lambda x:{'margin':0}.get(x[0], 1)) for k, v in css2: if k not in ignore: yield k, v for css2, names in css_styles.items(): self.writeout("%s {\n" % ', '.join(names)) for style, val in filter_margins(css2): self.writeout(f"\t{style}: {val};\n") self.writeout("}\n") def generate_footnotes(self): if self.currentnote == 0: return # Changed by Kovid to improve endnote functionality from builtins import _ self.opentag('h1', {'class':'notes-header'}) self.writeout(_('Notes')) self.closetag('h1') self.opentag('dl', {'class':'notes'}) for key in range(1,self.currentnote+1): note = self.notedict[key] # for key,note in self.notedict.items(): self.opentag('dt', {'id':"footnote-%d" % key}) # self.opentag('sup') # self.writeout(escape(note['citation'])) # self.closetag('sup', False) self.writeout('[') self.opentag('a', {'href': "#citation-%d" % key}) self.writeout("←%d" % key) self.closetag('a') self.writeout(']\xa0') self.closetag('dt') self.opentag('dd') self.writeout(note['body']) self.closetag('dd') self.closetag('dl') def s_office_automatic_styles(self, tag, attrs): if self.xmlfile == 'styles.xml': self.autoprefix = "A" else: self.autoprefix = "" def s_office_document_content(self, tag, attrs): """ First tag in the content.xml file""" self.writeout('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ') self.writeout('"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n') self.opentag('html', {'xmlns':"http://www.w3.org/1999/xhtml"}, True) self.opentag('head', block=True) self.emptytag('meta', {'http-equiv':"Content-Type", 'content':"text/html;charset=UTF-8"}) for metaline in self.metatags: self.writeout(metaline) self.writeout('<title>%s</title>\n' % escape(self.title)) def e_office_document_content(self, tag, attrs): """ Last tag """ self.closetag('html') def s_office_master_styles(self, tag, attrs): """ """ def s_office_presentation(self, tag, attrs): """ For some odd reason, OpenOffice Impress doesn't define a default-style for the 'paragraph'. We therefore force a standard when we see it is a presentation """ self.styledict['p'] = {(FONS,'font-size'): "24pt"} self.styledict['presentation'] = {(FONS,'font-size'): "24pt"} self.html_body(tag, attrs) def e_office_presentation(self, tag, attrs): self.generate_footnotes() self.closetag('body') def s_office_spreadsheet(self, tag, attrs): self.html_body(tag, attrs) def e_office_spreadsheet(self, tag, attrs): self.generate_footnotes() self.closetag('body') def s_office_styles(self, tag, attrs): self.autoprefix = "" def s_office_text(self, tag, attrs): """ OpenDocument text """ self.styledict['frame'] = {(STYLENS,'wrap'): 'parallel'} self.html_body(tag, attrs) def e_office_text(self, tag, attrs): self.generate_footnotes() self.closetag('body') def s_style_handle_properties(self, tag, attrs): """ Copy all attributes to a struct. We will later convert them to CSS2 """ if self.currentstyle is None: # Added by Kovid return for key,attr in attrs.items(): self.styledict[self.currentstyle][key] = attr familymap = {'frame':'frame', 'paragraph':'p', 'presentation':'presentation', 'text':'span','section':'div', 'table':'table','table-cell':'td','table-column':'col', 'table-row':'tr','graphic':'graphic'} def s_style_default_style(self, tag, attrs): """ A default style is like a style on an HTML tag """ family = attrs[(STYLENS,'family')] htmlfamily = self.familymap.get(family,'unknown') self.currentstyle = htmlfamily # self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} def e_style_default_style(self, tag, attrs): self.currentstyle = None def s_style_font_face(self, tag, attrs): """ It is possible that the HTML browser doesn't know how to show a particular font. Luckily ODF provides generic fallbacks Unfortunately they are not the same as CSS2. CSS2: serif, sans-serif, cursive, fantasy, monospace ODF: roman, swiss, modern, decorative, script, system """ name = attrs[(STYLENS,"name")] family = attrs[(SVGNS,"font-family")] generic = attrs.get((STYLENS,'font-family-generic'),"") self.cs.save_font(name, family, generic) def s_style_footer(self, tag, attrs): self.opentag('div', {'id':"footer"}) self.purgedata() def e_style_footer(self, tag, attrs): self.writedata() self.closetag('div') self.purgedata() def s_style_footer_style(self, tag, attrs): self.currentstyle = "@print #footer" self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} def s_style_header(self, tag, attrs): self.opentag('div', {'id':"header"}) self.purgedata() def e_style_header(self, tag, attrs): self.writedata() self.closetag('div') self.purgedata() def s_style_header_style(self, tag, attrs): self.currentstyle = "@print #header" self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} def s_style_default_page_layout(self, tag, attrs): """ Collect the formatting for the default page layout style. """ self.currentstyle = "@page" self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} def s_style_page_layout(self, tag, attrs): """ Collect the formatting for the page layout style. This won't work in CSS 2.1, as page identifiers are not allowed. It is legal in CSS3, but the rest of the application doesn't specify when to use what page layout """ name = attrs[(STYLENS,'name')] name = name.replace(".","_") self.currentstyle = ".PL-" + name self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} def e_style_page_layout(self, tag, attrs): """ End this style """ self.currentstyle = None def s_style_master_page(self, tag, attrs): """ Collect the formatting for the page layout style. """ name = attrs[(STYLENS,'name')] name = name.replace(".","_") self.currentstyle = ".MP-" + name self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {('','position'):'relative'} # Then load the pagelayout style if we find it pagelayout = attrs.get((STYLENS,'page-layout-name'), None) if pagelayout: pagelayout = ".PL-" + pagelayout if pagelayout in self.styledict: styles = self.styledict[pagelayout] for style, val in styles.items(): self.styledict[self.currentstyle][style] = val else: self.styledict[self.currentstyle]['__parent-style-name'] = pagelayout self.s_ignorexml(tag, attrs) # Short prefixes for class selectors _familyshort = {'drawing-page':'DP', 'paragraph':'P', 'presentation':'PR', 'text':'S', 'section':'D', 'table':'T', 'table-cell':'TD', 'table-column':'TC', 'table-row':'TR', 'graphic':'G'} def s_style_style(self, tag, attrs): """ Collect the formatting for the style. Styles have scope. The same name can be used for both paragraph and character styles Since CSS has no scope we use a prefix. (Not elegant) In ODF a style can have a parent, these parents can be chained. We may not have encountered the parent yet, but if we have, we resolve it. """ name = attrs[(STYLENS,'name')] name = name.replace(".","_") family = attrs[(STYLENS,'family')] htmlfamily = self.familymap.get(family,'unknown') sfamily = self._familyshort.get(family,'X') name = f"{self.autoprefix}{sfamily}-{name}" parent = attrs.get((STYLENS,'parent-style-name')) self.currentstyle = special_styles.get(name,"."+name) self.stylestack.append(self.currentstyle) if self.currentstyle not in self.styledict: self.styledict[self.currentstyle] = {} self.styledict[self.currentstyle]['__style-family'] = htmlfamily # Then load the parent style if we find it if parent: parent = parent.replace(".", "_") parent = f"{sfamily}-{parent}" parent = special_styles.get(parent, "."+parent) if parent in self.styledict: styles = self.styledict[parent] for style, val in styles.items(): self.styledict[self.currentstyle][style] = val else: self.styledict[self.currentstyle]['__parent-style-name'] = parent def e_style_style(self, tag, attrs): """ End this style """ self.currentstyle = None def s_table_table(self, tag, attrs): """ Start a table """ c = attrs.get((TABLENS,'style-name'), None) if c and self.generate_css: c = c.replace(".","_") self.opentag('table',{'class': "T-%s" % c}) else: self.opentag('table') self.purgedata() def e_table_table(self, tag, attrs): """ End a table """ self.writedata() self.closetag('table') self.purgedata() def s_table_table_cell(self, tag, attrs): """ Start a table cell """ # FIXME: number-columns-repeated § 8.1.3 # repeated = int(attrs.get( (TABLENS,'number-columns-repeated'), 1)) htmlattrs = {} rowspan = attrs.get((TABLENS,'number-rows-spanned')) if rowspan: htmlattrs['rowspan'] = rowspan colspan = attrs.get((TABLENS,'number-columns-spanned')) if colspan: htmlattrs['colspan'] = colspan c = attrs.get((TABLENS,'style-name')) if c: htmlattrs['class'] = 'TD-%s' % c.replace(".","_") self.opentag('td', htmlattrs) self.purgedata() def e_table_table_cell(self, tag, attrs): """ End a table cell """ self.writedata() self.closetag('td') self.purgedata() def s_table_table_column(self, tag, attrs): """ Start a table column """ c = attrs.get((TABLENS,'style-name'), None) repeated = int(attrs.get((TABLENS,'number-columns-repeated'), 1)) htmlattrs = {} if c: htmlattrs['class'] = "TC-%s" % c.replace(".","_") for x in range(repeated): self.emptytag('col', htmlattrs) self.purgedata() def s_table_table_row(self, tag, attrs): """ Start a table row """ # FIXME: table:number-rows-repeated c = attrs.get((TABLENS,'style-name'), None) htmlattrs = {} if c: htmlattrs['class'] = "TR-%s" % c.replace(".","_") self.opentag('tr', htmlattrs) self.purgedata() def e_table_table_row(self, tag, attrs): """ End a table row """ self.writedata() self.closetag('tr') self.purgedata() def s_text_a(self, tag, attrs): """ Anchors start """ self.writedata() href = attrs[(XLINKNS,"href")].split("|")[0] if href[:1] == "#": # Changed by Kovid href = "#" + self.get_anchor(href[1:]) self.opentag('a', {'href':href}) self.purgedata() def e_text_a(self, tag, attrs): """ End an anchor or bookmark reference """ self.writedata() self.closetag('a', False) self.purgedata() def s_text_bookmark(self, tag, attrs): """ Bookmark definition """ name = attrs[(TEXTNS,'name')] html_id = self.get_anchor(name) self.writedata() self.opentag('span', {'id':html_id}) self.closetag('span', False) self.purgedata() def s_text_bookmark_ref(self, tag, attrs): """ Bookmark reference """ name = attrs[(TEXTNS,'ref-name')] html_id = "#" + self.get_anchor(name) self.writedata() self.opentag('a', {'href':html_id}) self.purgedata() def s_text_h(self, tag, attrs): """ Headings start """ level = int(attrs[(TEXTNS,'outline-level')]) if level > 6: level = 6 # Heading levels go only to 6 in XHTML if level < 1: level = 1 self.headinglevels[level] = self.headinglevels[level] + 1 name = self.classname(attrs) for x in range(level + 1,10): self.headinglevels[x] = 0 special = special_styles.get("P-"+name) if special or not self.generate_css: self.opentag('h%s' % level) else: self.opentag('h%s' % level, {'class':"P-%s" % name}) self.purgedata() def e_text_h(self, tag, attrs): """ Headings end Side-effect: If there is no title in the metadata, then it is taken from the first heading of any level. """ self.writedata() level = int(attrs[(TEXTNS,'outline-level')]) if level > 6: level = 6 # Heading levels go only to 6 in XHTML if level < 1: level = 1 lev = self.headinglevels[1:level+1] outline = '.'.join(map(str,lev)) heading = ''.join(self.data) if self.title == '': self.title = heading # Changed by Kovid tail = ''.join(self.data) anchor = self.get_anchor(f"{outline}.{tail}") anchor2 = self.get_anchor(tail) # Added by kovid to fix #7506 self.opentag('a', {'id': anchor}) self.closetag('a', False) self.opentag('a', {'id': anchor2}) self.closetag('a', False) self.closetag('h%s' % level) self.purgedata() def s_text_line_break(self, tag, attrs): """ Force a line break (<br/>) """ self.writedata() self.emptytag('br') self.purgedata() def s_text_list(self, tag, attrs): """ Start a list (<ul> or <ol>) To know which level we're at, we have to count the number of <text:list> elements on the tagstack. """ name = attrs.get((TEXTNS,'style-name')) continue_numbering = attrs.get((TEXTNS, 'continue-numbering')) == 'true' continue_list = attrs.get((TEXTNS, 'continue-list')) list_id = attrs.get(('http://www.w3.org/XML/1998/namespace', 'id')) level = self.tagstack.count_tags(tag) + 1 if name: name = name.replace(".","_") else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list. name = self.tagstack.rfindattr((TEXTNS,'style-name')) list_class = "%s_%d" % (name, level) tag_name = self.listtypes.get(list_class,'ul') number_class = tag_name + list_class if list_id: self.list_id_map[list_id] = number_class if continue_list: if continue_list in self.list_id_map: tglc = self.list_id_map[continue_list] self.list_number_map[number_class] = self.list_number_map[tglc] else: self.list_number_map.pop(number_class, None) else: if not continue_numbering: self.list_number_map.pop(number_class, None) self.list_class_stack.append(number_class) attrs = {} if tag_name == 'ol' and self.list_number_map[number_class] != 1: attrs = {'start': unicode_type(self.list_number_map[number_class])} if self.generate_css: attrs['class'] = list_class self.opentag('%s' % tag_name, attrs) self.purgedata() def e_text_list(self, tag, attrs): """ End a list """ self.writedata() if self.list_class_stack: self.list_class_stack.pop() name = attrs.get((TEXTNS,'style-name')) level = self.tagstack.count_tags(tag) + 1 if name: name = name.replace(".","_") else: # FIXME: If a list is contained in a table cell or text box, # the list level must return to 1, even though the table or # textbox itself may be nested within another list. name = self.tagstack.rfindattr((TEXTNS,'style-name')) list_class = "%s_%d" % (name, level) self.closetag(self.listtypes.get(list_class,'ul')) self.purgedata() def s_text_list_item(self, tag, attrs): """ Start list item """ number_class = self.list_class_stack[-1] if self.list_class_stack else None if number_class: self.list_number_map[number_class] += 1 self.opentag('li') self.purgedata() def e_text_list_item(self, tag, attrs): """ End list item """ self.writedata() self.closetag('li') self.purgedata() def s_text_list_level_style_bullet(self, tag, attrs): """ CSS doesn't have the ability to set the glyph to a particular character, so we just go through the available glyphs """ name = self.tagstack.rfindattr((STYLENS,'name')) level = attrs[(TEXTNS,'level')] self.prevstyle = self.currentstyle list_class = f"{name}_{level}" self.listtypes[list_class] = 'ul' self.currentstyle = ".{}_{}".format(name.replace(".","_"), level) self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} level = int(level) listtype = ("square", "disc", "circle")[level % 3] self.styledict[self.currentstyle][('','list-style-type')] = listtype def e_text_list_level_style_bullet(self, tag, attrs): self.currentstyle = self.prevstyle del self.prevstyle def s_text_list_level_style_number(self, tag, attrs): name = self.tagstack.stackparent()[(STYLENS,'name')] level = attrs[(TEXTNS,'level')] num_format = attrs.get((STYLENS,'num-format'),"1") start_value = attrs.get((TEXTNS, 'start-value'), '1') list_class = f"{name}_{level}" self.prevstyle = self.currentstyle self.currentstyle = ".{}_{}".format(name.replace(".","_"), level) if start_value != '1': self.list_starts[self.currentstyle] = start_value self.listtypes[list_class] = 'ol' self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} if num_format == "1": listtype = "decimal" elif num_format == "I": listtype = "upper-roman" elif num_format == "i": listtype = "lower-roman" elif num_format == "A": listtype = "upper-alpha" elif num_format == "a": listtype = "lower-alpha" else: listtype = "decimal" self.styledict[self.currentstyle][('','list-style-type')] = listtype def e_text_list_level_style_number(self, tag, attrs): self.currentstyle = self.prevstyle del self.prevstyle def s_text_note(self, tag, attrs): self.writedata() self.purgedata() self.currentnote = self.currentnote + 1 self.notedict[self.currentnote] = {} self.notebody = [] def e_text_note(self, tag, attrs): pass def collectnote(self,s): if s != '': self.notebody.append(s) def s_text_note_body(self, tag, attrs): self._orgwfunc = self._wfunc self._wfunc = self.collectnote def e_text_note_body(self, tag, attrs): self._wfunc = self._orgwfunc self.notedict[self.currentnote]['body'] = ''.join(self.notebody) self.notebody = '' del self._orgwfunc def e_text_note_citation(self, tag, attrs): # Changed by Kovid to improve formatting and enable backlinks mark = ''.join(self.data) self.notedict[self.currentnote]['citation'] = mark self.opentag('sup') self.opentag('a', { 'href': "#footnote-%s" % self.currentnote, 'class': 'citation', 'id':'citation-%s' % self.currentnote }) # self.writeout( escape(mark) ) # Since HTML only knows about endnotes, there is too much risk that the # marker is reused in the source. Therefore we force numeric markers self.writeout(str(self.currentnote)) self.closetag('a') self.closetag('sup') def s_text_p(self, tag, attrs): """ Paragraph """ htmlattrs = {} specialtag = "p" c = attrs.get((TEXTNS,'style-name'), None) if c: c = c.replace(".","_") specialtag = special_styles.get("P-"+c) if specialtag is None: specialtag = 'p' if self.generate_css: htmlattrs['class'] = "P-%s" % c self.opentag(specialtag, htmlattrs) self.purgedata() def e_text_p(self, tag, attrs): """ End Paragraph """ specialtag = "p" c = attrs.get((TEXTNS,'style-name'), None) if c: c = c.replace(".","_") specialtag = special_styles.get("P-"+c) if specialtag is None: specialtag = 'p' self.writedata() if not self.data: # Added by Kovid # Give substance to empty paragraphs, as rendered by OOo self.writeout('&#160;') self.closetag(specialtag) self.purgedata() def s_text_s(self, tag, attrs): # Changed by Kovid to fix non breaking spaces being prepended to # element instead of being part of the text flow. # We don't use an entity for the nbsp as the contents of self.data will # be escaped on writeout. """ Generate a number of spaces. We use the non breaking space for the text:s ODF element. """ try: c = int(attrs.get((TEXTNS, 'c'), 1)) except: c = 0 if c > 0: self.data.append('\u00a0'*c) def s_text_span(self, tag, attrs): """ The <text:span> element matches the <span> element in HTML. It is typically used to properties of the text. """ self.writedata() c = attrs.get((TEXTNS,'style-name'), None) htmlattrs = {} # Changed by Kovid to handle inline special styles defined on <text:span> tags. # Apparently LibreOffice does this. special = 'span' if c: c = c.replace(".","_") special = special_styles.get("S-"+c) if special is None: special = 'span' if self.generate_css: htmlattrs['class'] = "S-%s" % c self.opentag(special, htmlattrs) self.purgedata() def e_text_span(self, tag, attrs): """ End the <text:span> """ self.writedata() c = attrs.get((TEXTNS,'style-name'), None) # Changed by Kovid to handle inline special styles defined on <text:span> tags. # Apparently LibreOffice does this. special = 'span' if c: c = c.replace(".","_") special = special_styles.get("S-"+c) if special is None: special = 'span' self.closetag(special, False) self.purgedata() def s_text_tab(self, tag, attrs): """ Move to the next tabstop. We ignore this in HTML """ self.writedata() self.writeout(' ') self.purgedata() def s_text_x_source(self, tag, attrs): """ Various indexes and tables of contents. We ignore those. """ self.writedata() self.purgedata() self.s_ignorexml(tag, attrs) def e_text_x_source(self, tag, attrs): """ Various indexes and tables of contents. We ignore those. """ self.writedata() self.purgedata() # ----------------------------------------------------------------------------- # # Reading the file # # ----------------------------------------------------------------------------- def load(self, odffile): """ Loads a document into the parser and parses it. The argument can either be a filename or a document in memory. """ self.lines = [] self._wfunc = self._wlines if isinstance(odffile, (bytes, str)) or hasattr(odffile, 'read'): # Added by Kovid self.document = load(odffile) else: self.document = odffile self._walknode(self.document.topnode) def _walknode(self, node): if node.nodeType == Node.ELEMENT_NODE: self.startElementNS(node.qname, node.tagName, node.attributes) for c in node.childNodes: self._walknode(c) self.endElementNS(node.qname, node.tagName) if node.nodeType == Node.TEXT_NODE or node.nodeType == Node.CDATA_SECTION_NODE: self.characters(str(node)) def odf2xhtml(self, odffile): """ Load a file and return the XHTML """ self.load(odffile) return self.xhtml() def _wlines(self,s): if s: self.lines.append(s) def xhtml(self): """ Returns the xhtml """ return ''.join(self.lines) def _writecss(self, s): if s: self._csslines.append(s) def _writenothing(self, s): pass def css(self): """ Returns the CSS content """ self._csslines = [] self._wfunc = self._writecss self.generate_stylesheet() res = ''.join(self._csslines) self._wfunc = self._wlines del self._csslines return res def save(self, outputfile, addsuffix=False): """ Save the HTML under the filename. If the filename is '-' then save to stdout We have the last style filename in self.stylefilename """ if outputfile == '-': import sys # Added by Kovid outputfp = sys.stdout else: if addsuffix: outputfile = outputfile + ".html" outputfp = open(outputfile, "wb") outputfp.write(self.xhtml().encode('us-ascii','xmlcharrefreplace')) outputfp.close() class ODF2XHTMLembedded(ODF2XHTML): """ The ODF2XHTML parses an ODF file and produces XHTML""" def __init__(self, lines, generate_css=True, embedable=False): self._resetobject() self.lines = lines # Tags self.generate_css = generate_css self.elements = { # (DCNS, 'title'): (self.s_processcont, self.e_dc_title), # (DCNS, 'language'): (self.s_processcont, self.e_dc_contentlanguage), # (DCNS, 'creator'): (self.s_processcont, self.e_dc_metatag), # (DCNS, 'description'): (self.s_processcont, self.e_dc_metatag), # (DCNS, 'date'): (self.s_processcont, self.e_dc_metatag), (DRAWNS, 'frame'): (self.s_draw_frame, self.e_draw_frame), (DRAWNS, 'image'): (self.s_draw_image, None), (DRAWNS, 'fill-image'): (self.s_draw_fill_image, None), (DRAWNS, "layer-set"):(self.s_ignorexml, None), (DRAWNS, 'page'): (self.s_draw_page, self.e_draw_page), (DRAWNS, 'object'): (self.s_draw_object, None), (DRAWNS, 'object-ole'): (self.s_draw_object_ole, None), (DRAWNS, 'text-box'): (self.s_draw_textbox, self.e_draw_textbox), # (METANS, 'creation-date'):(self.s_processcont, self.e_dc_metatag), # (METANS, 'generator'):(self.s_processcont, self.e_dc_metatag), # (METANS, 'initial-creator'): (self.s_processcont, self.e_dc_metatag), # (METANS, 'keyword'): (self.s_processcont, self.e_dc_metatag), (NUMBERNS, "boolean-style"):(self.s_ignorexml, None), (NUMBERNS, "currency-style"):(self.s_ignorexml, None), (NUMBERNS, "date-style"):(self.s_ignorexml, None), (NUMBERNS, "number-style"):(self.s_ignorexml, None), (NUMBERNS, "text-style"):(self.s_ignorexml, None), # (OFFICENS, "automatic-styles"):(self.s_office_automatic_styles, None), # (OFFICENS, "document-content"):(self.s_office_document_content, self.e_office_document_content), (OFFICENS, "forms"):(self.s_ignorexml, None), # (OFFICENS, "master-styles"):(self.s_office_master_styles, None), (OFFICENS, "meta"):(self.s_ignorecont, None), # (OFFICENS, "presentation"):(self.s_office_presentation, self.e_office_presentation), # (OFFICENS, "spreadsheet"):(self.s_office_spreadsheet, self.e_office_spreadsheet), # (OFFICENS, "styles"):(self.s_office_styles, None), # (OFFICENS, "text"):(self.s_office_text, self.e_office_text), (OFFICENS, "scripts"):(self.s_ignorexml, None), (PRESENTATIONNS, "notes"):(self.s_ignorexml, None), # (STYLENS, "default-page-layout"):(self.s_style_default_page_layout, self.e_style_page_layout), # (STYLENS, "default-page-layout"):(self.s_ignorexml, None), # (STYLENS, "default-style"):(self.s_style_default_style, self.e_style_default_style), # (STYLENS, "drawing-page-properties"):(self.s_style_handle_properties, None), # (STYLENS, "font-face"):(self.s_style_font_face, None), # (STYLENS, "footer"):(self.s_style_footer, self.e_style_footer), # (STYLENS, "footer-style"):(self.s_style_footer_style, None), # (STYLENS, "graphic-properties"):(self.s_style_handle_properties, None), # (STYLENS, "handout-master"):(self.s_ignorexml, None), # (STYLENS, "header"):(self.s_style_header, self.e_style_header), # (STYLENS, "header-footer-properties"):(self.s_style_handle_properties, None), # (STYLENS, "header-style"):(self.s_style_header_style, None), # (STYLENS, "master-page"):(self.s_style_master_page, None), # (STYLENS, "page-layout-properties"):(self.s_style_handle_properties, None), # (STYLENS, "page-layout"):(self.s_style_page_layout, self.e_style_page_layout), # (STYLENS, "page-layout"):(self.s_ignorexml, None), # (STYLENS, "paragraph-properties"):(self.s_style_handle_properties, None), # (STYLENS, "style"):(self.s_style_style, self.e_style_style), # (STYLENS, "table-cell-properties"):(self.s_style_handle_properties, None), # (STYLENS, "table-column-properties"):(self.s_style_handle_properties, None), # (STYLENS, "table-properties"):(self.s_style_handle_properties, None), # (STYLENS, "text-properties"):(self.s_style_handle_properties, None), (SVGNS, 'desc'): (self.s_ignorexml, None), (TABLENS, 'covered-table-cell'): (self.s_ignorexml, None), (TABLENS, 'table-cell'): (self.s_table_table_cell, self.e_table_table_cell), (TABLENS, 'table-column'): (self.s_table_table_column, None), (TABLENS, 'table-row'): (self.s_table_table_row, self.e_table_table_row), (TABLENS, 'table'): (self.s_table_table, self.e_table_table), (TEXTNS, 'a'): (self.s_text_a, self.e_text_a), (TEXTNS, "alphabetical-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "bibliography-configuration"):(self.s_ignorexml, None), (TEXTNS, "bibliography-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'h'): (self.s_text_h, self.e_text_h), (TEXTNS, "illustration-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'line-break'):(self.s_text_line_break, None), (TEXTNS, "linenumbering-configuration"):(self.s_ignorexml, None), (TEXTNS, "list"):(self.s_text_list, self.e_text_list), (TEXTNS, "list-item"):(self.s_text_list_item, self.e_text_list_item), (TEXTNS, "list-level-style-bullet"):(self.s_text_list_level_style_bullet, self.e_text_list_level_style_bullet), (TEXTNS, "list-level-style-number"):(self.s_text_list_level_style_number, self.e_text_list_level_style_number), (TEXTNS, "list-style"):(None, None), (TEXTNS, "note"):(self.s_text_note, None), (TEXTNS, "note-body"):(self.s_text_note_body, self.e_text_note_body), (TEXTNS, "note-citation"):(None, self.e_text_note_citation), (TEXTNS, "notes-configuration"):(self.s_ignorexml, None), (TEXTNS, "object-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, 'p'): (self.s_text_p, self.e_text_p), (TEXTNS, 's'): (self.s_text_s, None), (TEXTNS, 'span'): (self.s_text_span, self.e_text_span), (TEXTNS, 'tab'): (self.s_text_tab, None), (TEXTNS, "table-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "table-of-content-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "user-index-source"):(self.s_text_x_source, self.e_text_x_source), (TEXTNS, "page-number"):(None, None), }
71,246
Python
.py
1,582
35.945006
119
0.579444
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,436
__init__.py
kovidgoyal_calibre/src/templite/__init__.py
#!/usr/bin/env python # # Templite+ # A light-weight, fully functional, general purpose templating engine # # Copyright (c) 2009 joonis new media # Author: Thimo Kraemer <thimo.kraemer@joonis.de> # # Based on Templite - Tomer Filiba # http://code.activestate.com/recipes/496702/ # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # import re import sys from polyglot.builtins import unicode_type class Templite: auto_emit = re.compile(r'''(^['"])|(^[a-zA-Z0-9_\[\]'"]+$)''') def __init__(self, template, start='${', end='}$'): if len(start) != 2 or len(end) != 2: raise ValueError('each delimiter must be two characters long') delimiter = re.compile('%s(.*?)%s' % (re.escape(start), re.escape(end)), re.DOTALL) offset = 0 tokens = [] for i, part in enumerate(delimiter.split(template)): part = part.replace('\\'.join(list(start)), start) part = part.replace('\\'.join(list(end)), end) if i % 2 == 0: if not part: continue part = part.replace('\\', '\\\\').replace('"', '\\"') part = '\t' * offset + 'emit("""%s""")' % part else: part = part.rstrip() if not part: continue if part.lstrip().startswith(':'): if not offset: raise SyntaxError('no block statement to terminate: ${%s}$' % part) offset -= 1 part = part.lstrip()[1:] if not part.endswith(':'): continue elif self.auto_emit.match(part.lstrip()): part = 'emit(%s)' % part.lstrip() lines = part.splitlines() margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip()) part = '\n'.join('\t' * offset + l[margin:] for l in lines) if part.endswith(':'): offset += 1 tokens.append(part) if offset: raise SyntaxError('%i block statement(s) not terminated' % offset) self.__code = compile('\n'.join(tokens), '<templite %r>' % template[:20], 'exec') def render(self, __namespace=None, **kw): """ renders the template according to the given namespace. __namespace - a dictionary serving as a namespace for evaluation **kw - keyword arguments which are added to the namespace """ namespace = {} if __namespace: namespace.update(__namespace) if kw: namespace.update(kw) namespace['emit'] = self.write __stdout = sys.stdout sys.stdout = self self.__output = [] eval(self.__code, namespace) sys.stdout = __stdout return ''.join(self.__output) def write(self, *args): for a in args: self.__output.append(unicode_type(a))
3,749
Python
.py
88
33.511364
91
0.555708
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,437
html_entities.py
kovidgoyal_calibre/src/polyglot/html_entities.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from html.entities import name2codepoint name2codepoint
179
Python
.py
5
34.4
73
0.819767
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,438
functools.py
kovidgoyal_calibre/src/polyglot/functools.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from functools import lru_cache lru_cache
164
Python
.py
5
31.4
72
0.789809
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,439
queue.py
kovidgoyal_calibre/src/polyglot/queue.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from queue import Queue, Empty, Full, PriorityQueue, LifoQueue # noqa
193
Python
.py
4
47
73
0.776596
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,440
io.py
kovidgoyal_calibre/src/polyglot/io.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from io import BytesIO, StringIO class PolyglotStringIO(StringIO): def __init__(self, initial_data=None, encoding='utf-8', errors='strict'): StringIO.__init__(self) self._encoding_for_bytes = encoding self._errors = errors if initial_data is not None: self.write(initial_data) def write(self, x): if isinstance(x, bytes): x = x.decode(self._encoding_for_bytes, errors=self._errors) StringIO.write(self, x) class PolyglotBytesIO(BytesIO): def __init__(self, initial_data=None, encoding='utf-8', errors='strict'): BytesIO.__init__(self) self._encoding_for_bytes = encoding self._errors = errors if initial_data is not None: self.write(initial_data) def write(self, x): if not isinstance(x, bytes): x = x.encode(self._encoding_for_bytes, errors=self._errors) BytesIO.write(self, x)
1,069
Python
.py
26
33.576923
77
0.64182
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,441
http_client.py
kovidgoyal_calibre/src/polyglot/http_client.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from http.client import ( _CS_IDLE, _CS_REQ_SENT, BAD_REQUEST, FORBIDDEN, FOUND, HTTP_VERSION_NOT_SUPPORTED, INTERNAL_SERVER_ERROR, METHOD_NOT_ALLOWED, MOVED_PERMANENTLY, NOT_FOUND, NOT_IMPLEMENTED, NOT_MODIFIED, OK, PARTIAL_CONTENT, PRECONDITION_FAILED, PRECONDITION_REQUIRED, REQUEST_ENTITY_TOO_LARGE, REQUEST_TIMEOUT, REQUEST_URI_TOO_LONG, REQUESTED_RANGE_NOT_SATISFIABLE, SEE_OTHER, SERVICE_UNAVAILABLE, UNAUTHORIZED, UNPROCESSABLE_ENTITY, HTTPConnection, HTTPSConnection, responses, ) if False: responses, HTTPConnection, HTTPSConnection, BAD_REQUEST, FOUND, FORBIDDEN, HTTP_VERSION_NOT_SUPPORTED, INTERNAL_SERVER_ERROR, METHOD_NOT_ALLOWED MOVED_PERMANENTLY, NOT_FOUND, NOT_IMPLEMENTED, NOT_MODIFIED, OK, PARTIAL_CONTENT, PRECONDITION_FAILED, REQUEST_ENTITY_TOO_LARGE, REQUEST_URI_TOO_LONG REQUESTED_RANGE_NOT_SATISFIABLE, REQUEST_TIMEOUT, SEE_OTHER, SERVICE_UNAVAILABLE, UNAUTHORIZED, _CS_IDLE, _CS_REQ_SENT PRECONDITION_REQUIRED, UNPROCESSABLE_ENTITY
1,205
Python
.py
37
28.162162
153
0.744425
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,442
smtplib.py
kovidgoyal_calibre/src/polyglot/smtplib.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import sys from functools import partial class FilteredLog: ' Hide AUTH credentials from the log ' def __init__(self, debug_to=None): self.debug_to = debug_to or partial(print, file=sys.stderr) def __call__(self, *a): if a and len(a) == 2 and a[0] == 'send:': a = list(a) raw = a[1] if len(raw) > 100: raw = raw[:100] + (b'...' if isinstance(raw, bytes) else '...') q = b'AUTH ' if isinstance(raw, bytes) else 'AUTH ' if q in raw: raw = 'AUTH <censored>' a[1] = raw self.debug_to(*a) import smtplib class SMTP(smtplib.SMTP): def __init__(self, *a, **kw): self.debug_to = FilteredLog(kw.pop('debug_to', None)) super().__init__(*a, **kw) def _print_debug(self, *a): if self.debug_to is not None: self.debug_to(*a) else: super()._print_debug(*a) class SMTP_SSL(smtplib.SMTP_SSL): def __init__(self, *a, **kw): self.debug_to = FilteredLog(kw.pop('debug_to', None)) super().__init__(*a, **kw) def _print_debug(self, *a): if self.debug_to is not None: self.debug_to(*a) else: super()._print_debug(*a)
1,399
Python
.py
39
27.589744
79
0.542411
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,443
builtins.py
kovidgoyal_calibre/src/polyglot/builtins.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import os import sys is_py3 = sys.version_info.major >= 3 native_string_type = str iterkeys = iter def hasenv(x): return getenv(x) is not None def as_bytes(x, encoding='utf-8'): if isinstance(x, unicode_type): return x.encode(encoding) if isinstance(x, bytes): return x if isinstance(x, bytearray): return bytes(x) if isinstance(x, memoryview): return x.tobytes() ans = unicode_type(x) if isinstance(ans, unicode_type): ans = ans.encode(encoding) return ans def as_unicode(x, encoding='utf-8', errors='strict'): if isinstance(x, bytes): return x.decode(encoding, errors) return unicode_type(x) def only_unicode_recursive(x, encoding='utf-8', errors='strict'): # Convert any bytestrings in sets/lists/tuples/dicts to unicode if isinstance(x, bytes): return x.decode(encoding, errors) if isinstance(x, unicode_type): return x if isinstance(x, (set, list, tuple, frozenset)): return type(x)(only_unicode_recursive(i, encoding, errors) for i in x) if isinstance(x, dict): return { only_unicode_recursive(k, encoding, errors): only_unicode_recursive(v, encoding, errors) for k, v in iteritems(x) } return x def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None import builtins zip = builtins.zip map = builtins.map filter = builtins.filter range = builtins.range codepoint_to_chr = chr unicode_type = str string_or_bytes = str, bytes string_or_unicode = str long_type = int raw_input = input getcwd = os.getcwd getenv = os.getenv def error_message(exc): args = getattr(exc, 'args', None) if args and isinstance(args[0], unicode_type): return args[0] return unicode_type(exc) def iteritems(d): return iter(d.items()) def itervalues(d): return iter(d.values()) def environ_item(x): if isinstance(x, bytes): x = x.decode('utf-8') return x def exec_path(path, ctx=None): ctx = ctx or {} with open(path, 'rb') as f: code = f.read() code = compile(code, f.name, 'exec') exec(code, ctx) def cmp(a, b): return (a > b) - (a < b) def int_to_byte(x): return bytes((x, )) def reload(module): import importlib return importlib.reload(module) def print_to_binary_file(fileobj, encoding='utf-8'): def print(*a, **kw): f = kw.get('file', fileobj) if a: sep = as_bytes(kw.get('sep', ' '), encoding) for x in a: x = as_bytes(x, encoding) f.write(x) if x is not a[-1]: f.write(sep) f.write(as_bytes(kw.get('end', '\n'))) return print
3,058
Python
.py
103
23.796117
78
0.624872
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,444
plistlib.py
kovidgoyal_calibre/src/polyglot/plistlib.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from plistlib import loads, dumps # noqa loads_binary_or_xml = loads
191
Python
.py
5
37
72
0.767568
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,445
reprlib.py
kovidgoyal_calibre/src/polyglot/reprlib.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from reprlib import repr repr
153
Python
.py
5
29.2
73
0.794521
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,446
http_cookie.py
kovidgoyal_calibre/src/polyglot/http_cookie.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from http.cookies import SimpleCookie # noqa from http.cookiejar import CookieJar, Cookie # noqa
223
Python
.py
5
43.4
73
0.78341
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,447
socketserver.py
kovidgoyal_calibre/src/polyglot/socketserver.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Eli Schwartz <eschwartz@archlinux.org> from socketserver import TCPServer, ThreadingMixIn # noqa
181
Python
.py
4
44
73
0.795455
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,448
binary.py
kovidgoyal_calibre/src/polyglot/binary.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from base64 import standard_b64decode, standard_b64encode from binascii import hexlify, unhexlify from polyglot.builtins import unicode_type def as_base64_bytes(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode(enc) return standard_b64encode(x) def as_base64_unicode(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode(enc) return standard_b64encode(x).decode('ascii') def from_base64_unicode(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode('ascii') return standard_b64decode(x).decode(enc) def from_base64_bytes(x): if isinstance(x, unicode_type): x = x.encode('ascii') return standard_b64decode(x) def as_hex_bytes(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode(enc) return hexlify(x) def as_hex_unicode(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode(enc) return hexlify(x).decode('ascii') def from_hex_unicode(x, enc='utf-8'): if isinstance(x, unicode_type): x = x.encode('ascii') return unhexlify(x).decode(enc) def from_hex_bytes(x): if isinstance(x, unicode_type): x = x.encode('ascii') return unhexlify(x)
1,346
Python
.py
38
30.552632
72
0.679597
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,449
http_server.py
kovidgoyal_calibre/src/polyglot/http_server.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from http.server import HTTPServer, SimpleHTTPRequestHandler # noqa
190
Python
.py
4
46.25
72
0.794595
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,450
urllib.py
kovidgoyal_calibre/src/polyglot/urllib.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from urllib.request import (build_opener, getproxies, install_opener, # noqa HTTPBasicAuthHandler, HTTPCookieProcessor, HTTPDigestAuthHandler, # noqa url2pathname, urlopen, Request) # noqa from urllib.parse import (parse_qs, quote, unquote as uq, quote_plus, urldefrag, # noqa urlencode, urljoin, urlparse, urlunparse, urlsplit, urlunsplit) # noqa from urllib.error import HTTPError, URLError # noqa def unquote(x, encoding='utf-8', errors='replace'): binary = isinstance(x, bytes) if binary: x = x.decode(encoding, errors) ans = uq(x, encoding, errors) if binary: ans = ans.encode(encoding, errors) return ans def unquote_plus(x, encoding='utf-8', errors='replace'): q, repl = (b'+', b' ') if isinstance(x, bytes) else ('+', ' ') x = x.replace(q, repl) return unquote(x, encoding=encoding, errors=errors)
1,010
Python
.py
21
43.380952
88
0.695829
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,451
live_css.pyj
kovidgoyal_calibre/src/pyj/live_css.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> # globals: CSSRule from __python__ import bound_methods, hash_literals INHERITED_PROPS = { # {{{ 'azimuth': '2', 'border-collapse': '2', 'border-spacing': '2', 'caption-side': '2', 'color': '2', 'cursor': '2', 'direction': '2', 'elevation': '2', 'empty-cells': '2', 'fit': '3', 'fit-position': '3', 'font': '2', 'font-family': '2', 'font-size': '2', 'font-size-adjust': '2', 'font-stretch': '2', 'font-style': '2', 'font-variant': '2', 'font-weight': '2', 'hanging-punctuation': '3', 'hyphenate-after': '3', 'hyphenate-before': '3', 'hyphenate-character': '3', 'hyphenate-lines': '3', 'hyphenate-resource': '3', 'hyphens': '3', 'image-resolution': '3', 'letter-spacing': '2', 'line-height': '2', 'line-stacking': '3', 'line-stacking-ruby': '3', 'line-stacking-shift': '3', 'line-stacking-strategy': '3', 'list-style': '2', 'list-style-image': '2', 'list-style-position': '2', 'list-style-type': '2', 'marquee-direction': '3', 'orphans': '2', 'overflow-style': '3', 'page': '2', 'page-break-inside': '2', 'pitch': '2', 'pitch-range': '2', 'presentation-level': '3', 'punctuation-trim': '3', 'quotes': '2', 'richness': '2', 'ruby-align': '3', 'ruby-overhang': '3', 'ruby-position': '3', 'speak': '2', 'speak-header': '2', 'speak-numeral': '2', 'speak-punctuation': '2', 'speech-rate': '2', 'stress': '2', 'text-align': '2', 'text-align-last': '3', 'text-emphasis': '3', 'text-height': '3', 'text-indent': '2', 'text-justify': '3', 'text-outline': '3', 'text-replace': '?', 'text-shadow': '3', 'text-transform': '2', 'text-wrap': '3', 'visibility': '2', 'voice-balance': '3', 'voice-family': '2', 'voice-rate': '3', 'voice-pitch': '3', 'voice-pitch-range': '3', 'voice-stress': '3', 'voice-volume': '3', 'volume': '2', 'white-space': '2', 'white-space-collapse': '3', 'widows': '2', 'word-break': '3', 'word-spacing': '2', 'word-wrap': '3', # the mozilla extensions are all proprietary properties '-moz-force-broken-image-icon': 'm', '-moz-image-region': 'm', '-moz-stack-sizing': 'm', '-moz-user-input': 'm', '-x-system-font': 'm', # the opera extensions are all draft implementations of CSS3 properties '-xv-voice-balance': 'o', '-xv-voice-pitch': 'o', '-xv-voice-pitch-range': 'o', '-xv-voice-rate': 'o', '-xv-voice-stress': 'o', '-xv-voice-volume': 'o', # the explorer extensions are all draft implementations of CSS3 properties '-ms-text-align-last': 'e', '-ms-text-justify': 'e', '-ms-word-break': 'e', '-ms-word-wrap': 'e' } # }}} def get_sourceline_address(node): sourceline = parseInt(node.dataset.lnum) tags = v'[]' for elem in document.querySelectorAll(f'[data-lnum="{sourceline}"]'): tags.push(elem.tagName.toLowerCase()) if elem is node: break return v'[sourceline, tags]' def get_color(property, val): color = None if property.indexOf('color') > -1: try: color = window.parseCSSColor(val) # Use the csscolor library to get an rgba 4-tuple except: pass return color def get_style_properties(style, all_properties, node_style, is_ancestor): i = 0 properties = v'[]' while i < style.length: property = style.item(i) if property: property = property.toLowerCase() val = style.getPropertyValue(property) else: val = None if property and val and (not is_ancestor or INHERITED_PROPS[property]): properties.push(v'[property, val, style.getPropertyPriority(property), get_color(property, val)]') if not all_properties[property]: cval = node_style.getPropertyValue(property) cval all_properties[property] = v'[cval, get_color(property, cval)]' i += 1 return properties def get_sheet_rules(sheet): if sheet.disabled or not sheet.cssRules: return v'[]' sheet_media = sheet.media and sheet.media.mediaText if sheet_media and sheet_media.length and not window.matchMedia(sheet_media).matches: return v'[]' return sheet.cssRules def selector_matches(node, selector): try: return node.matches(selector) except: # happens if the selector uses epub|type if 'epub|' in selector: sanitized_sel = str.replace(selector, 'epub|', '*|') try: # TODO: Actually parse the selector and extract the attribute # and check it manually return node.matches(sanitized_sel) except: return False return False def process_rules(node, rules, address, sheet, sheet_index, all_properties, node_style, is_ancestor, ans): offset = 0 for rule_index in range(rules.length): rule = rules[rule_index] rule_address = address.concat(v'[rule_index - offset]') if rule.type is CSSRule.MEDIA_RULE: process_rules(node, rule.cssRules, rule_address, sheet, sheet_index, all_properties, node_style, is_ancestor, ans) continue if rule.type is not CSSRule.STYLE_RULE: if rule.type is CSSRule.NAMESPACE_RULE: offset += 1 continue st = rule.selectorText if not selector_matches(node, st): continue type = 'sheet' href = sheet.href if not href: href = get_sourceline_address(sheet.ownerNode) type = 'elem' # Technically, we should check for the highest specificity # matching selector, but we cheat and use the first one parts = st.split(',') if parts.length > 1: for q in parts: if selector_matches(node, q): st = q break properties = get_style_properties(rule.style, all_properties, node_style, is_ancestor) if properties.length > 0: data = {'selector':st, 'type':type, 'href':href, 'properties':properties, 'rule_address':rule_address, 'sheet_index':sheet_index} ans.push(data) def get_matched_css(node, is_ancestor, all_properties): ans = v'[]' node_style = window.getComputedStyle(node) sheets = document.styleSheets for sheet_index in range(sheets.length): sheet = sheets[sheet_index] process_rules(node, get_sheet_rules(sheet), v'[]', sheet, sheet_index, all_properties, node_style, is_ancestor, ans) if node.getAttribute('style'): properties = get_style_properties(node.style, all_properties, node_style, is_ancestor) if properties.length > 0: data = {'selector':None, 'type':'inline', 'href':get_sourceline_address(node), 'properties':properties, 'rule_address':None, 'sheet_index':None} ans.push(data) return ans.reverse()
7,399
Python
.py
207
29.550725
156
0.575255
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,452
editor.pyj
kovidgoyal_calibre/src/pyj/editor.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from fs_images import fix_fullscreen_svg_images from live_css import get_matched_css, get_sourceline_address from qt import from_python, to_python FAKE_HOST = '__FAKE_HOST__' FAKE_PROTOCOL = '__FAKE_PROTOCOL__' def is_hidden(elem): while elem: if (elem.style and (elem.style.visibility is 'hidden' or elem.style.display is 'none')): return True elem = elem.parentNode return False def is_block(elem): style = window.getComputedStyle(elem) return style.display is 'block' or style.display is 'flex-box' or style.display is 'box' def in_table(elem): while elem: tn = elem.tagName.toLowerCase() if elem.tagName else '' if tn is 'table': return True elem = elem.parentNode return False def find_containing_block(elem): while elem and elem.dataset.isBlock is not '1': elem = elem.parentNode return elem def line_height(): ans = line_height.ans if not ans: ds = window.getComputedStyle(document.body) try: # will fail if line-height = "normal" lh = float(ds.lineHeight) except: try: lh = 1.2 * float(ds.fontSize) except: lh = 15 ans = line_height.ans = max(5, lh) return ans def scroll_to_node(node, sync_context): if node is document.body: window.scrollTo(0, 0) else: node.scrollIntoView() if sync_context: window.scrollBy(0, -sync_context * line_height()) state = {'blocks_found': False, 'in_split_mode': False} def go_to_line(lnum, sync_context): for node in document.querySelectorAll(f'[data-lnum="{lnum}"]'): if is_hidden(node): continue scroll_to_node(node, sync_context) break @from_python def go_to_sourceline_address(sourceline, tags, sync_context): nodes = document.querySelectorAll(f'[data-lnum="{sourceline}"]') for index in range(nodes.length): node = nodes[index] if index >= tags.length or node.tagName.toLowerCase() is not tags[index]: break if index == tags.length - 1 and not is_hidden(node): return scroll_to_node(node, sync_context) go_to_line(sourceline, sync_context) def line_numbers(): found_body = False ans = v'[]' for node in document.getElementsByTagName('*'): if not found_body and node.tagName.toLowerCase() is "body": found_body = True if found_body: ans.push(node.dataset.lnum) return ans def find_blocks(): if state.blocks_found: return for elem in document.body.getElementsByTagName('*'): if is_block(elem) and not in_table(elem): elem.setAttribute('data-is-block', '1') state.blocks_found = True @from_python def set_split_mode(enabled): state.in_split_mode = enabled document.body.dataset.inSplitMode = '1' if enabled else '0' if enabled: find_blocks() def report_split(node): loc = v'[]' totals = v'[]' parent = find_containing_block(node) while parent and parent.tagName.toLowerCase() is not 'body': totals.push(parent.parentNode.children.length) num = 0 sibling = parent.previousElementSibling while sibling: num += 1 sibling = sibling.previousElementSibling loc.push(num) parent = parent.parentNode loc.reverse() totals.reverse() to_python.request_split(loc, totals) def onclick(event): event.preventDefault() if state.in_split_mode: report_split(event.target) else: e = event.target address = get_sourceline_address(e) # Find the closest containing link, if any href = tn = '' while e and e is not document.body and e is not document and e is not document.documentElement and (tn is not 'a' or not href): tn = e.tagName.toLowerCase() if e.tagName else '' href = e.getAttribute('href') e = e.parentNode if to_python.request_sync: to_python.request_sync(tn, href, address) return False @from_python def go_to_anchor(anchor): elem = document.getElementById(anchor) if not elem: elem = document.querySelector(f'[name="{anchor}"]') if elem: elem.scrollIntoView() address = get_sourceline_address(elem) if to_python.request_sync: to_python.request_sync('', '', address) @from_python def live_css(editor_name, sourceline, tags): all_properties = {} ans = {'nodes':v'[]', 'computed_css':all_properties, 'editor_name': editor_name, 'sourceline': sourceline, 'tags': tags} target = None i = 0 for node in document.querySelectorAll(f'[data-lnum="{sourceline}"]'): tn = node.tagName.toLowerCase() if node.tagName else '' if tn is not tags[i]: if to_python.live_css_data: to_python.live_css_data(ans) return i += 1 target = node if i >= tags.length: break ancestor_specificity = 0 while target and target.ownerDocument: css = get_matched_css(target, ancestor_specificity is not 0, all_properties) # We want to show the Matched CSS rules header even if no rules matched if css.length > 0 or ancestor_specificity is 0: tn = target.tagName.toLowerCase() if target.tagName else '' ans.nodes.push({ 'name': tn, 'css': css, 'ancestor_specificity': -ancestor_specificity, 'sourceline': target.getAttribute('data-lnum') }) target = target.parentNode ancestor_specificity += 1 if to_python.live_css_data: to_python.live_css_data(ans) def check_for_maths(): if document.body.getElementsByTagNameNS('http://www.w3.org/1998/Math/MathML', 'math').length > 0: return True for s in document.scripts: if s.type is 'text/x-mathjax-config': return True return False def load_mathjax(): script = E.script(type='text/javascript') script.async = True script.src = f'{FAKE_PROTOCOL}://{FAKE_HOST}/calibre_internal-mathjax/startup.js' document.head.appendChild(script) if document.body: settings = JSON.parse(window.navigator.userAgent.split('|')[1]) css = '[data-in-split-mode="1"] [data-is-block="1"]:hover { cursor: pointer !important; border-top: solid 5px green !important }' if settings.os is 'macos': # See settings.pyj for reason for webkit-hyphenate-character css += '\n* { -webkit-hyphenate-character: "-" !important }\n' document.body.addEventListener('click', onclick, True) document.documentElement.appendChild(E.style(type='text/css', css)) fix_fullscreen_svg_images() if check_for_maths(): load_mathjax()
7,060
Python
.py
185
30.87027
135
0.640883
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,453
test_utils.pyj
kovidgoyal_calibre/src/pyj/test_utils.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from testing import assert_equal, test from utils import fmt_sidx, human_readable, rating_to_stars from session import deep_eq @test def misc_utils(): assert_equal(rating_to_stars(3, True), '★⯨') assert_equal(fmt_sidx(10), 'X') assert_equal(fmt_sidx(1.2), '1.20') assert_equal(list(map(human_readable, [1, 1024.0, 1025, 1024*1024*2.3])), ["1 B", "1 KB", "1 KB", "2.3 MB"]) assert_equal(False, deep_eq({"portrait":0, "landscape":0}, {"landscape":3, "portrait":0})) assert_equal(False, deep_eq(1, 2)) assert_equal(True, deep_eq(1, 1))
718
Python
.py
15
44.533333
112
0.683908
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,454
test.pyj
kovidgoyal_calibre/src/pyj/test.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals import traceback import initialize # noqa: unused-import import test_date # noqa: unused-import import test_utils # noqa: unused-import import read_book.test_cfi # noqa: unused-import import test_annotations # noqa: unused-import from testing import registered_tests, reset_dom def get_matching_tests_for_name(name): ans = [] for k in Object.keys(registered_tests): q = k.split('.')[-1] if not name or q is name: ans.append(registered_tests[k]) return ans def get_traceback(): lines = traceback.format_exception() last_line = lines[-1] final_lines = v'[]' pat = /at assert_[0-9a-zA-Z_]+ \(/ for line in lines[:-1]: if pat.test(line): break final_lines.push(line) final_lines.push(last_line) return final_lines.join('') def run_tests(tests): failed_tests = [] count = 0 for f in tests: print(f.test_name, '...') reset_dom() try: f() count += 1 except: tb = get_traceback() console.error(tb) failed_tests.append((f.test_name, tb)) return failed_tests, count def main(): tests = get_matching_tests_for_name() st = window.performance.now() failed_tests, total = run_tests(tests) time = (window.performance.now() - st) / 1000 if failed_tests.length: console.error(f'{failed_tests.length} out of {total} failed in {time:.1f} seconds') else: print(f'Ran {total} tests in {time:.1f} seconds') return 1 if failed_tests.length else 0 window.main = main document.title = 'initialized'
1,790
Python
.py
54
27.314815
91
0.639582
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,455
session.pyj
kovidgoyal_calibre/src/pyj/session.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from uuid import short_uuid from ajax import ajax_send all_settings = { 'copy_to_library_dupes': {'default': 'add;overwrite', 'category': 'book_list'}, 'last_sort_order': {'default': {}, 'category': 'book_list'}, 'show_all_metadata': {'default': False, 'category': 'book_list'}, # show all metadata fields in the book details panel 'sort': {'default': 'timestamp.desc', 'category': 'book_list'}, # comma separated list of items of the form: field.order 'view_mode': {'default': 'cover_grid', 'category': 'book_list'}, 'fts_related_words': {'default': True, 'category': 'book_list'}, # Tag Browser settings 'and_search_terms': {'default': False, 'category': 'tag_browser'}, # how to add search terms to the search expression from the Tag Browser 'collapse_at': {'default': 25, 'category': 'tag_browser'}, # number of items at which sub-groups are created, 0 to disable 'dont_collapse': {'default': '', 'category': 'tag_browser'}, # comma separated list of category names 'hide_empty_categories': {'default': 'no', 'category': 'tag_browser'}, 'partition_method': {'default': 'first letter', 'category': 'tag_browser'}, # other choices: 'disable', 'partition' 'sort_tags_by': {'default': 'name', 'category': 'tag_browser'}, # other choices: popularity, rating # Book reader settings 'background_image_fade': {'default': 0, 'category': 'read_book', 'is_local': True}, 'background_image_style': {'default': 'scaled', 'category': 'read_book', 'is_local': True}, 'background_image': {'default': None, 'category': 'read_book', 'is_local': True}, 'base_font_size': {'default': 16, 'category': 'read_book', 'is_local': True}, 'book_scrollbar': {'default': False, 'category': 'read_book'}, 'columns_per_screen': {'default': {'portrait':0, 'landscape':0}, 'category': 'read_book', 'is_local': True}, 'controls_help_shown_count': {'default': 0, 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'controls_help_shown_count_rtl_page_progression': {'default': 0, 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'cover_preserve_aspect_ratio': {'default': True, 'category': 'read_book'}, 'current_color_scheme': {'default': 'system', 'category': 'read_book'}, 'footer': {'default': {'left': 'menu-icon-on-hover', 'right': 'progress'}, 'category': 'read_book'}, 'header': {'default': {'right': 'menu-icon-on-hover'}, 'category': 'read_book'}, 'controls_footer': {'default': {'right': 'progress'}, 'category': 'read_book'}, 'left-margin': {'default': {}, 'category': 'read_book'}, 'right-margin': {'default': {}, 'category': 'read_book'}, 'hide_tooltips': {'default': False, 'category': 'read_book'}, 'keyboard_shortcuts': {'default': {}, 'category': 'read_book'}, 'lines_per_sec_auto': {'default': 1, 'category': 'read_book', 'is_local': True}, 'lines_per_sec_smooth': {'default': 20, 'category': 'read_book', 'is_local': True}, 'margin_bottom': {'default': 20, 'category': 'read_book', 'is_local': True}, 'margin_left': {'default': 20, 'category': 'read_book', 'is_local': True}, 'margin_right': {'default': 20, 'category': 'read_book', 'is_local': True}, 'margin_top': {'default': 20, 'category': 'read_book', 'is_local': True}, 'max_text_height': {'default': 0, 'category': 'read_book', 'is_local': True}, 'max_text_width': {'default': 0, 'category': 'read_book', 'is_local': True}, 'override_book_colors': {'default': 'never', 'category': 'read_book'}, 'paged_margin_clicks_scroll_by_screen': {'default': True, 'category': 'read_book'}, 'paged_wheel_scrolls_by_screen': {'default': False, 'category': 'read_book'}, 'paged_wheel_section_jumps': {'default': True, 'category': 'read_book'}, 'paged_pixel_scroll_threshold': {'default': 60, 'category': 'read_book'}, 'read_mode': {'default': 'paged', 'category': 'read_book', 'is_local': True}, 'scroll_auto_boundary_delay': {'default': 5, 'category': 'read_book', 'is_local': True}, 'scroll_stop_boundaries': {'default': False, 'category': 'read_book', 'is_local': True}, 'standalone_font_settings': {'default': {}, 'category': 'read_book', 'is_local': True}, 'standalone_misc_settings': {'default': {}, 'category': 'read_book', 'is_local': True}, 'standalone_recently_opened': {'default': v'[]', 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'user_color_schemes': {'default': {}, 'category': 'read_book'}, 'user_stylesheet': {'default': '', 'category': 'read_book', 'is_local': True}, 'word_actions': {'default': v'[]', 'category': 'read_book'}, 'highlight_style': {'default': None, 'category': 'read_book', 'is_local': True}, 'highlights_export_format': {'default': 'text', 'category': 'read_book', 'is_local': True}, 'custom_highlight_styles': {'default': v'[]', 'category': 'read_book'}, 'show_selection_bar': {'default': True, 'category': 'read_book'}, 'net_search_url': {'default': 'https://google.com/search?q={q}', 'category': 'read_book'}, 'selection_bar_actions': {'default': v"['copy', 'lookup', 'highlight', 'remove_highlight', 'search_net', 'clear']", 'category': 'read_book'}, 'selection_bar_quick_highlights': {'default': v"[]", 'category': 'read_book'}, 'skipped_dialogs': {'default': v'{}', 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'tts': {'default': v'{}', 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'tts_backend': {'default': v'{}', 'category': 'read_book', 'is_local': True, 'disallowed_in_profile': True}, 'fullscreen_when_opening': {'default': 'auto', 'category': 'read_book', 'is_local': True}, 'book_search_mode': {'default': 'contains', 'category': 'read_book', 'is_local': True}, 'book_search_case_sensitive': {'default': False, 'category': 'read_book', 'is_local': True}, 'reverse_page_turn_zones': {'default': False, 'category': 'read_book', 'is_local': True}, 'gesture_overrides': {'default': {}, 'category': 'read_book'}, 'cite_text_template': {'default': '[{text}]({url})', 'category': 'read_book'}, 'cite_hl_template': {'default': '[{text}]({url})', 'category': 'read_book'}, } defaults = {} for x in Object.entries(all_settings): defaults[x[0]] = x[1].default def session_defaults(): return defaults def storage_available(which): which = which or 'localStorage' try: storage = window[which] x = '__storage__test__' storage.setItem(x, x) storage.removeItem(x) return True except: return False class FakeStorage: def __init__(self): self.data = {} def getItem(self, key): return self.data[key] def setItem(self, key, value): if jstype(value) is not 'string': value = JSON.stringify(value) self.data[key] = value def clear(self): self.data = {} def get_session_storage(): if not get_session_storage.ans: if storage_available('localStorage'): get_session_storage.ans = window.localStorage elif storage_available('sessionStorage'): get_session_storage.ans = window.sessionStorage console.error('localStorage not available using sessionStorage instead') else: get_session_storage.ans = FakeStorage() console.error('sessionStorage and localStorage not available using a temp cache instead') return get_session_storage.ans class SessionData: def __init__(self, global_prefix=None): self.global_prefix = global_prefix or 'calibre-session-' self.storage = get_session_storage() self.overflow_storage = {} self.has_overflow = False def get(self, key, defval): key = self.global_prefix + key if self.has_overflow: ans = self.overflow_storage[key] if ans is undefined: ans = self.storage.getItem(key) else: ans = self.storage.getItem(key) if ans is undefined or ans is None: if defval is undefined: defval = None return defval try: return JSON.parse(ans) except: if defval is undefined: defval = None return defval def set(self, key, value): key = self.global_prefix + key if value is None: self.storage.removeItem(key) v'delete self.overflow_storage[key]' return True value = JSON.stringify(value) try: self.storage.setItem(key, value) v'delete self.overflow_storage[key]' return True except: self.overflow_storage[key] = value self.has_overflow = True console.error('session storage has overflowed, using a temp cache instead') return False def set_bulk(self, changes): for key in Object.keys(changes): self.set(key, changes[key]) def clear(self): self.storage.clear() self.overflow_storage = {} self.has_overflow = False def local_storage(): if not local_storage.storage: local_storage.storage = SessionData('calibre-local-') return local_storage.storage def get_device_uuid(): if not get_device_uuid.ans: s = local_storage() ans = s.get('device_uuid') if not ans: ans = short_uuid() s.set('device_uuid', ans) get_device_uuid.ans = ans return get_device_uuid.ans def deep_eq(a, b): if a is b: return True if Array.isArray(a) and Array.isArray(b): if a.length is not b.length: return False for i in range(a.length): if not deep_eq(a[i], b[i]): return False return True if a is None or b is None or a is undefined or b is undefined: return False if jstype(a) is not 'object' or jstype(b) is not 'object': return False ka = Object.keys(a) if ka.length is not Object.keys(b).length: return False for key in ka: if not deep_eq(a[key], b[key]): return False return True def setting_val_is_default(setting_name, curval): defval = defaults[setting_name] return deep_eq(defval, curval) def get_subset_of_settings(sd, filter_func): ans = {} for setting_name in Object.keys(all_settings): curval = sd.get(setting_name, ans) metadata = all_settings[setting_name] is_set = curval is not ans if filter_func(setting_name, metadata, is_set, curval): ans[setting_name] = window.structuredClone(curval if is_set else metadata.default) return ans def apply_profile(sd, profile, filter_func): changes = {} for setting_name in Object.keys(all_settings): metadata = all_settings[setting_name] curval = sd.get(setting_name, changes) is_set = curval is not changes if filter_func(setting_name, metadata, is_set, curval): newval = None if Object.prototype.hasOwnProperty.call(profile, setting_name): newval = profile[setting_name] if deep_eq(newval, metadata.default): newval = None changes[setting_name] = window.structuredClone(newval) sd.set_bulk(changes) return changes standalone_reader_defaults = { 'remember_window_geometry': False, 'remember_last_read': True, 'show_actions_toolbar': False, 'show_actions_toolbar_in_fullscreen': False, 'save_annotations_in_ebook': True, 'sync_annots_user': '', 'singleinstance': False, 'auto_hide_mouse': True, 'restore_docks': True, } def settings_for_reader_profile(sd): margin_text_settings = {'footer': True, 'header': True, 'controls_footer': True, 'left-margin': True, 'right-margin': True} def filter_func(setting_name, metadata, is_set, curval): if margin_text_settings[setting_name]: curval = window.structuredClone(curval) for x in v"['left', 'right', 'middle']": if curval[x] is 'empty': v'delete curval[x]' elif setting_name is 'standalone_misc_settings': curval = window.structuredClone(curval) for key in Object.keys(curval): if curval[key] is standalone_reader_defaults[key]: v'delete curval[key]' if not is_set or metadata.category is not 'read_book' or metadata.disallowed_in_profile or deep_eq(curval, metadata.default): return False return True return get_subset_of_settings(sd, filter_func) def apply_reader_profile(sd, profile): def filter_func(setting_name, metadata, is_set, curval): return metadata.category is 'read_book' and not metadata.disallowed_in_profile apply_profile(sd, profile, filter_func) default_interface_data = { 'username': None, 'output_format': 'EPUB', 'input_formats': {'EPUB', 'MOBI', 'AZW3'}, 'gui_pubdate_display_format': 'MMM yyyy', 'gui_timestamp_display_format': 'dd MMM yyyy', 'gui_last_modified_display_format': 'dd MMM yyyy', 'use_roman_numerals_for_series_number': True, 'default_library_id': None, 'default_book_list_mode': session_defaults().view_mode, 'library_map': None, 'search_the_net_urls': [], 'donate_link': 'https://calibre-ebook.com/donate', 'icon_map': {}, 'icon_path': '', 'custom_list_template': None, 'num_per_page': 50, 'lang_code_for_user_manual': '', } def get_interface_data(): if not get_interface_data.storage: get_interface_data.storage = SessionData('calibre-interface-data-') ans = get_interface_data.storage.get('current') if ans: ans.is_default = False else: ans = {'is_default': True} for k in default_interface_data: ans[k] = default_interface_data[k] return ans def update_interface_data(new_data): data = get_interface_data() for k in default_interface_data: nval = new_data[k] if k is not undefined: data[k] = nval if not get_interface_data.storage: get_interface_data.storage = SessionData('calibre-interface-data-') get_interface_data.storage.set('current', data) def get_translations(newval): if not get_translations.storage: get_translations.storage = SessionData('calibre-translations-') if newval?: get_translations.storage.set('current', newval) else: return get_translations.storage.get('current') def is_setting_local(name): m = all_settings[name] return m.is_local if m else True class UserSessionData(SessionData): def __init__(self, username, saved_data): self.prefix = (username or '') + '-' self.has_user = bool(username) self.username = username SessionData.__init__(self) self.echo_changes = False self.changes = {} self.has_changes = False self.push_timer_id = None if saved_data: for key in saved_data: if not is_setting_local(key): self.set(key, saved_data[key]) self.echo_changes = True def defval(self, key): ans = session_defaults()[key] if ans: ans = window.structuredClone(ans) return ans def get(self, key, defval): if defval is undefined: defval = self.defval(key) return SessionData.get(self, (self.prefix + key), defval) def get_library_option(self, library_id, key, defval): if not library_id: return self.get(key, defval) lkey = key + '-||-' + library_id if defval is undefined: defval = self.defval(key) return self.get(lkey, defval) def set(self, key, value): if self.echo_changes and self.has_user and not is_setting_local(key): self.changes[key] = value self.has_changes = True if self.push_timer_id is not None: clearTimeout(self.push_timer_id) self.push_timer_id = setTimeout(self.push_to_server.bind(self), 1000) return SessionData.set(self, (self.prefix + key), value) def set_library_option(self, library_id, key, value): if library_id: key = key + '-||-' + library_id return self.set(key, value) def push_to_server(self): if self.has_changes: ajax_send('interface-data/set-session-data', self.changes, def(end_type, xhr, ev): if end_type is not 'load': console.error('Failed to send session data to server: ' + xhr.error_html) ) self.changes = {} self.has_changes = False
17,045
Python
.py
354
40.443503
145
0.620963
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,456
initialize.pyj
kovidgoyal_calibre/src/pyj/initialize.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from pythonize import strings strings()
177
Python
.py
5
34
72
0.794118
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,457
autoreload.pyj
kovidgoyal_calibre/src/pyj/autoreload.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals MAX_RETRIES = 10 class Watcher: def __init__(self, autoreload_port): host = document.location.host.split(':')[0] self.url = 'ws://' + host + ':' + autoreload_port self.retries = 0 self.interval = 100 self.disable = False self.opened_at_least_once = False self.reconnect() def reconnect(self): try: self.ws = WebSocket(self.url) except DOMException as e: if e.name == 'SecurityError': console.log('Not allowed to connect to auto-reload watcher, probably because using a self-signed, or otherwise invalid SSL certificate') return raise self.ws.onopen = def(event): self.retries = 0 self.opened_at_least_once = True self.interval = 100 print('Connected to reloading WebSocket server at: ' + self.url) window.addEventListener('beforeunload', def (event): print('Shutting down connection to reload server, before page unload') self.disable = True self.ws.close() ) self.ws.onmessage = def(event): if event.data is not 'ping': print('Received mesasge from reload server: ' + event.data) if event.data is 'reload': self.reload_app() self.ws.onclose = def (event): if self.disable or not self.opened_at_least_once: return print('Connection to reload server closed with code: ' + event.code + ' and reason: ' + event.reason) self.retries += 1 if (self.retries < MAX_RETRIES): setTimeout(self.reconnect, self.interval) else: self.reload_app() def reload_app(self): window.location.reload(True) def create_auto_reload_watcher(autoreload_port): if not create_auto_reload_watcher.watcher: create_auto_reload_watcher.watcher = Watcher(autoreload_port) return create_auto_reload_watcher.watcher
2,223
Python
.py
51
32.921569
152
0.600555
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,458
srv.pyj
kovidgoyal_calibre/src/pyj/srv.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> # globals: ρσ_get_module, self from __python__ import hash_literals import initialize # noqa: unused-import from ajax import ajax, console_print, set_default_timeout from autoreload import create_auto_reload_watcher from book_list.globals import main_js from book_list.main import main autoreload_enabled = False AUTO_UPDATE_THRESHOLD = 1000 # millisecs def worker_main(entry_point): m = ρσ_get_module(entry_point) main = m?.main if main: main() else: console.log('worker entry_point ' + entry_point + ' not found') def iframe_main(script): script.parentNode.removeChild(script) # free up some memory script = undefined m = ρσ_get_module(window.iframe_entry_point) main = m?.main if main: main() else: console.log('iframe entry_point ' + window.iframe_entry_point + ' not found') def toplevel_main(): script = document.currentScript or document.scripts[0] main_js(script.textContent) script.parentNode.removeChild(script) # save some memory script = undefined # We wait for all page elements to load, since this is a single page app # with a largely empty starting document, we can use this to preload any resources # we know are going to be needed immediately. window.addEventListener('load', main) ajax('ajax-setup', def(end_type, xhr, event): nonlocal autoreload_enabled, print if end_type is 'load': try: data = JSON.parse(xhr.responseText) except: return tim = data.ajax_timeout if not isNaN(tim) and tim > 0: set_default_timeout(tim) port = data.auto_reload_port if not isNaN(port) and port > 0: autoreload_enabled = True create_auto_reload_watcher(port) if data.allow_console_print: print = console_print ).send() # We must bypass cache as otherwise we could get stale info if document?: iframe_script = document.getElementById('bootstrap') if iframe_script: iframe_main(iframe_script) else: toplevel_main() elif self?: entry_point = self.location.hash[1:] worker_main(entry_point)
2,351
Python
.py
62
31.112903
86
0.66696
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,459
date.pyj
kovidgoyal_calibre/src/pyj/date.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals UNDEFINED_DATE_ISO = '0101-01-01T00:00:00+00:00' UNDEFINED_DATE = Date(UNDEFINED_DATE_ISO) def is_date_undefined(date): dy, uy = date.getUTCFullYear(), UNDEFINED_DATE.getUTCFullYear() return dy < uy or ( dy is uy and date.getUTCMonth() is UNDEFINED_DATE.getUTCMonth() and date.getUTCDate() <= UNDEFINED_DATE.getUTCDate() + 1) # format_date() {{{ lcdata = { 'abday': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 'abmon': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], 'day' : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], 'mon' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], } supports_locales = False try: Date().toLocaleString('dfkjghdfkgj') except RangeError: supports_locales = True except: pass def fmt_date_pat(): ans = fmt_date_pat.ans if not ans?: ans = fmt_date_pat.ans = /(s{1,2})|(m{1,2})|(h{1,2})|(H{1,2})|(zzz)|(z)|(ap)|(AP)|(a)|(A)|(t)|(d{1,4}|M{1,4}|(?:yyyy|yy))/g return ans def fd_format_hour(dt, ampm, hr, as_utc): h = dt.getUTCHours() if as_utc else dt.getHours() if ampm: h %= 12 if h is 0: h = 12 return h.toString() if hr.length is 1 else str.format('{:02d}', h) def fd_format_hour24(dt, ampm, hr, as_utc): return fd_format_hour(dt, False, hr, as_utc) def fd_format_minute(dt, ampm, min, as_utc): m = dt.getUTCMinutes() if as_utc else dt.getMinutes() return m.toString() if min.length is 1 else str.format('{:02d}', m) def fd_format_second(dt, ampm, min, as_utc): s = dt.getUTCSeconds() if as_utc else dt.getSeconds() return s.toString() if min.length is 1 else str.format('{:02d}', s) def fd_format_ms(dt, ampm, min, as_utc): s = dt.getUTCMilliseconds() if as_utc else dt.getSeconds() return s.toString() if min.length is 1 else str.format('{:03d}', s) def fd_format_timezone(dt, ampm, t, as_utc): short = dt.toLocaleTimeString() full = dt.toLocaleTimeString(v'[]', {'timeZoneName': 'long'}) idx = full.indexOf(short) if idx > -1: return full[idx + short.length:].strip() return window.Intl.DateTimeFormat().resolvedOptions().timeZone def fd_format_ampm(dt, ampm, ap, as_utc): h = dt.getUTCHours() if as_utc else dt.getHours() ans = 'am' if h < 12 else 'pm' return ans if (ap is 'ap' or ap is 'a') else ans.toUpperCase() def fd_format_day(dt, ampm, dy, as_utc): d = dt.getUTCDate() if as_utc else dt.getDate() if dy.length is 1: return d.toString() if dy.length is 2: return str.format('{:02d}', d) if supports_locales: options = {'weekday': ('short' if dy.length is 3 else 'long')} if as_utc: options['timeZone'] = 'UTC' return dt.toLocaleString(window.navigator.language, options) w = dt.getUTCDay() if as_utc else dt.getDay() return lcdata['abday' if dy.length is 3 else 'day'][(w + 1) % 7] def fd_format_month(dt, ampm, mo, as_utc): m = dt.getUTCMonth() if as_utc else dt.getMonth() if mo.length is 1: return (m + 1).toString() if mo.length is 2: return str.format('{:02d}', m + 1) if supports_locales: options = {'month': {1:'numeric', 2:'2-digit', 3:'short', 4:'long'}[mo.length] or 'long'} if as_utc: options['timeZone'] = 'UTC' return dt.toLocaleString(window.navigator.language, options) return lcdata['abmon' if mo.length is 3 else 'mon'][m] def fd_format_year(dt, ampm, yr, as_utc): y = dt.getUTCFullYear() if as_utc else dt.getFullYear() if yr.length is 2: return str.format('{:02d}', y % 100) return str.format('{:04d}', y) fd_function_index = { 'd': fd_format_day, 'M': fd_format_month, 'y': fd_format_year, 'h': fd_format_hour, 'H': fd_format_hour24, 'm': fd_format_minute, 's': fd_format_second, 'a': fd_format_ampm, 'A': fd_format_ampm, 'z': fd_format_ms, 't': fd_format_timezone, } def am_pm_pat(): ans = am_pm_pat.ans if not ans?: ans = am_pm_pat.ans = /(ap)|(a)|(AP)|(A)/ return ans def as_iso(date): tzo = -date.getTimezoneOffset() dif = '+' if tzo >= 0 else '-' def pad(num): return ('0' if num < 10 else '') + num return ( date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()) + dif + pad(Math.floor(Math.abs(tzo) / 60)) + ':' + pad(Math.abs(tzo) % 60) ) def format_date(date=None, fmt='dd MMM yyyy', as_utc=False): fmt = fmt or 'dd MMM yyyy' ampm = am_pm_pat().test(fmt) if jstype(date) is 'string': date = Date(date) date = date or Date() if is_date_undefined(date): return '' if fmt is 'iso': return as_iso(date) return fmt.replace(fmt_date_pat(), def(match): if not match: return '' try: return fd_function_index[match[0]](date, ampm, match, as_utc) except Exception: print(str.format('Failed to format date with format: {} and match: {}', fmt, match)) return '' ) # }}}
5,479
Python
.py
137
34.270073
136
0.597288
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,460
worker.pyj
kovidgoyal_calibre/src/pyj/worker.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from book_list.globals import main_js def worker_js_url(entry_point): if not worker_js_url.ans: worker_js_url.ans = window.URL.createObjectURL(Blob([main_js()]), {'type': 'text/javascript'}) return worker_js_url.ans + '#' + entry_point def start_worker(entry_point): return new window.Worker(worker_js_url(entry_point))
495
Python
.py
10
46
102
0.729167
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,461
complete.pyj
kovidgoyal_calibre/src/pyj/complete.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods from dom import ensure_id, unique_id, clear from elementmaker import E from session import local_storage from popups import CompletionPopup from utils import uniq class EditWithComplete: def __init__(self, name, placeholder=None, tooltip=None, parent=None, input_type='text', onenterkey=None): inpt = E.input(type=input_type, name=name, title=tooltip or '', placeholder=placeholder or '', autocomplete='off') self.input_id = ensure_id(inpt) self.onenterkey = onenterkey self.completion_popup = CompletionPopup(parent=parent, onselect=self.apply_completion) inpt.addEventListener('keydown', self.onkeydown) inpt.addEventListener('input', self.oninput) self.completion_popup.add_associated_widget(inpt) if parent: parent.appendChild(inpt) @property def text_input(self): return document.getElementById(self.input_id) def apply_completion(self, text): if text: ti = self.text_input ti.value = text ti.focus() return True def onkeydown(self, event): if self.completion_popup.is_visible and self.completion_popup.handle_keydown(event): event.preventDefault(), event.stopPropagation() return if event.key is 'Enter': if self.completion_popup.is_visible: if self.apply_completion(self.completion_popup.current_text): self.completion_popup.hide() event.preventDefault(), event.stopPropagation() return if self.onenterkey: event.preventDefault(), event.stopPropagation() self.onenterkey() elif event.key is 'Tab': if self.completion_popup.is_visible: if self.apply_completion(self.completion_popup.current_text): self.completion_popup.hide() else: self.completion_popup.move_highlight() event.preventDefault(), event.stopPropagation() elif event.key is 'ArrowDown': ti = self.text_input if not ti.value: self.completion_popup.set_query('') self.completion_popup.popup(ti) event.preventDefault(), event.stopPropagation() def oninput(self, event): ti = self.text_input self.completion_popup.set_query(ti.value or '') self.completion_popup.popup(ti) def hide_completion_popup(self): self.completion_popup.hide() def add_associated_widget(self, widget_or_id): self.completion_popup.add_associated_widget(widget_or_id) def set_all_items(self, items): self.completion_popup.set_all_items(items) def create_search_bar(action, name, tooltip=None, placeholder=None, button=None, history_size=100, associated_widgets=None): parent = E.div(style="display:flex") ewc = EditWithComplete(name, parent=parent, tooltip=tooltip, placeholder=placeholder, input_type='search') parent.lastChild.style.width = '100%' history_name = 'search-bar-history-' + name def update_completion_items(): items = local_storage().get(history_name) if items?.length: ewc.set_all_items(items) update_completion_items() def trigger(): text = ewc.text_input.value ewc.hide_completion_popup() action(text) if text and text.strip(): items = local_storage().get(history_name) or v'[]' idx = items.indexOf(text) if idx > -1: items.splice(idx, 1) items.unshift(text) local_storage().set(history_name, uniq(items[:history_size])) update_completion_items() ewc.onenterkey = trigger parent.querySelector('input').addEventListener('search', trigger) if button: ewc.add_associated_widget(button) button.addEventListener('click', trigger) if associated_widgets is not None: for w in associated_widgets: ewc.add_associated_widget(w) return parent def create_simple_input_with_history_native(name, tooltip=None, placeholder=None, history_size=100, input_type='text'): # cannot use in standalone viewer because of: https://bugreports.qt.io/browse/QTBUG-54433 # fixed in Qt 6.4.0 dl_id = unique_id() dl = document.createElement('datalist') dl.id = dl_id history_name = f'simple_input_history_{name}' def update_completion_items(x): items = local_storage().get(history_name) dl = x or document.getElementById(dl_id) if dl: clear(dl) if items?.length: for item in items: dl.appendChild(E.option(value=item)) def save_completion_items(): text = document.getElementById(dl_id).nextSibling.value if text and text.strip(): items = local_storage().get(history_name) or v'[]' idx = items.indexOf(text) if idx > -1: items.splice(idx, 1) items.unshift(text) local_storage().set(history_name, uniq(items[:history_size])) update_completion_items() update_completion_items(dl) ans = E.span( data_calibre_history_input='1', dl, E.input(type=input_type, name=name, list=dl_id, title=tooltip or '', placeholder=placeholder or ''), ) ans.addEventListener('save_history', save_completion_items) return ans def create_simple_input_with_history(name, tooltip=None, placeholder=None, history_size=100, input_type='text'): # to use simply add the returned element to the DOM and when you want to # save a new completion item, use dispatchEvent to send a 'save_history' # event to it. parent = E.span(data_calibre_history_input='1') ewc = EditWithComplete(name, parent=parent, tooltip=tooltip, placeholder=placeholder, input_type=input_type) history_name = f'simple_input_history_{name}' def update_completion_items(): items = local_storage().get(history_name) if items?.length: ewc.set_all_items(items) update_completion_items() def save_completion_items(): text = ewc.text_input.value if text and text.strip(): items = local_storage().get(history_name) or v'[]' idx = items.indexOf(text) if idx > -1: items.splice(idx, 1) items.unshift(text) local_storage().set(history_name, uniq(items[:history_size])) update_completion_items() parent.addEventListener('save_history', save_completion_items) return parent # }}} def main(container): container.appendChild(create_search_bar(print, 'test-search-bar', placeholder='Testing search bar')) container.firstChild.lastChild.focus() # ewc = EditWithComplete(parent=container, placeholder='Testing edit with complete') # ewc.set_all_items('a a1 a11 a12 a13 b b1 b2 b3'.split(' ')) # ewc.text_input.focus()
7,215
Python
.py
159
36.18239
124
0.645184
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,462
range_utils.pyj
kovidgoyal_calibre/src/pyj/range_utils.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> # globals: NodeFilter, Range from __python__ import bound_methods, hash_literals def is_non_empty_text_node(node): return (node.nodeType is Node.TEXT_NODE or node.nodeType is Node.CDATA_SECTION_NODE) and node.nodeValue.length > 0 def is_element_visible(elem): s = window.getComputedStyle(elem) return s.display is not 'none' and s.visibility is not 'hidden' def is_node_visible(node): if node.nodeType is not Node.ELEMENT_NODE: node = node.parentElement if not node: return False current = node while current: if not is_element_visible(current): return False current = current.parentElement return True def select_nodes_from_range(r, predicate): parent = r.commonAncestorContainer doc = parent.ownerDocument or document iterator = doc.createNodeIterator(parent) in_range = False ans = v'[]' while True: node = iterator.nextNode() if not node: break if not in_range and node.isSameNode(r.startContainer): in_range = True if in_range: if predicate(node): ans.push(node) if node.isSameNode(r.endContainer): break return ans def select_first_node_from_range(r, predicate): parent = r.commonAncestorContainer doc = parent.ownerDocument or document iterator = doc.createNodeIterator(parent) in_range = False while True: node = iterator.nextNode() if not node: break if not in_range and node.isSameNode(r.startContainer): in_range = True if in_range: if predicate(node): return node if node.isSameNode(r.endContainer): break def text_nodes_in_range(r): return select_nodes_from_range(r, is_non_empty_text_node) def all_annots_in_range(r, annot_id_uuid_map, ans): parent = r.commonAncestorContainer doc = parent.ownerDocument or document iterator = doc.createNodeIterator(parent) is_full_tree = parent is doc.documentElement in_range = is_full_tree while True: node = iterator.nextNode() if not node: break if not in_range and node.isSameNode(r.startContainer): in_range = True if in_range: if node.dataset and node.dataset.calibreRangeWrapper: annot_id = annot_id_uuid_map[node.dataset.calibreRangeWrapper] if annot_id: if not ans: return annot_id ans[annot_id] = True if not is_full_tree and node.isSameNode(r.endContainer): break return ans def first_annot_in_range(r, annot_id_uuid_map): return all_annots_in_range(r, annot_id_uuid_map) def all_annots_in_selection(sel, annot_id_uuid_map): ans = v'{}' for i in range(sel.rangeCount): all_annots_in_range(sel.getRangeAt(i), annot_id_uuid_map, ans) return Object.keys(ans) def remove(node): if node.parentNode: node.parentNode.removeChild(node) def replace_node(replacement, node): p = node.parentNode p.insertBefore(replacement, node) remove(node) return p def unwrap(node): r = (node.ownerDocument or document).createRange() r.selectNodeContents(node) p = replace_node(r.extractContents(), node) if p: p.normalize() def unwrap_crw(crw): for node in document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]'): unwrap(node) def unwrap_all_crw(): for node in document.querySelectorAll('span[data-calibre-range-wrapper]'): unwrap(node) def select_crw(crw): nodes = document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]') if nodes and nodes.length: r = document.createRange() r.setStart(nodes[0].firstChild, 0) r.setEnd(nodes[-1].lastChild, nodes[-1].lastChild.nodeValue.length) sel = window.getSelection() sel.removeAllRanges() sel.addRange(r) return True print(f'range-wrapper: {crw} does not exist') return False def wrap_range(r, wrapper): try: r.surroundContents(wrapper) except: wrapper.appendChild(r.extractContents()) r.insertNode(wrapper) def create_wrapper_function(wrapper_elem, r, intersecting_wrappers, process_wrapper, all_wrappers): start_node = r.startContainer end_node = r.endContainer start_offset = r.startOffset end_offset = r.endOffset def wrap_node(node): nonlocal start_node, end_node, start_offset, end_offset current_range = (node.ownerDocument or document).createRange() current_wrapper = wrapper_elem.cloneNode() current_range.selectNodeContents(node) # adjust start and end in case the current node is one of the # boundaries of the original range if node.isSameNode(start_node): current_range.setStart(node, start_offset) start_node = current_wrapper start_offset = 0 if node.isSameNode(end_node): current_range.setEnd(node, end_offset) end_node = current_wrapper end_offset = 1 if current_range.collapsed: # Dont wrap empty ranges. This is needed otherwise two adjacent # selections of text will incorrectly be detected as overlapping. # For example: highlight abc then def in the word abcdef here the # second highlight's first range is the collapsed range at the end # of <span wrapper-for-first-highlight>abc<span wrapper-for-2nd></span></span> return crw = node.parentNode?.dataset?.calibreRangeWrapper if crw: intersecting_wrappers[crw] = True wrap_range(current_range, current_wrapper) if process_wrapper: process_wrapper(current_wrapper) all_wrappers.push(current_wrapper) return wrap_node wrapper_counter = 0 def wrap_text_in_range(styler, r, class_to_add_to_last, process_wrapper): if not r: sel = window.getSelection() if not sel or not sel.rangeCount: return None, v'[]' r = sel.getRangeAt(0) if r.isCollapsed: return None, v'[]' wrapper_elem = document.createElement('span') wrapper_elem.dataset.calibreRangeWrapper = v'++wrapper_counter' + '' if styler: styler(wrapper_elem) intersecting_wrappers = {} all_wrappers = v'[]' wrap_node = create_wrapper_function(wrapper_elem, r, intersecting_wrappers, process_wrapper, all_wrappers) text_nodes_in_range(r).map(wrap_node) ancestor = r.commonAncestorContainer if ancestor.nodeType is Node.TEXT_NODE: ancestor = ancestor.parentNode # remove any empty text nodes created by surroundContents() on either # side of the wrapper. This happens for instance on Chrome when # wrapping all text inside <i>some text</i> ancestor.normalize() crw = wrapper_elem.dataset.calibreRangeWrapper v'delete intersecting_wrappers[crw]' if class_to_add_to_last and all_wrappers.length: all_wrappers[-1].classList.add(class_to_add_to_last) return crw, Object.keys(intersecting_wrappers) def last_span_for_crw(crw): nodes = document.querySelectorAll(f'span[data-calibre-range-wrapper="{crw}"]') if nodes and nodes.length: return nodes[-1] def reset_highlight_counter(): nonlocal wrapper_counter wrapper_counter = 0 def get_annot_id_for(node, offset, annot_id_uuid_map): if not node: return if node.nodeType is Node.ELEMENT_NODE: if node.dataset?.calibreRangeWrapper: return annot_id_uuid_map[node.dataset.calibreRangeWrapper] if offset is 0: if node.firstChild?.nodeType is Node.ELEMENT_NODE and node.firstChild.dataset?.calibreRangeWrapper: return annot_id_uuid_map[node.firstChild.dataset.calibreRangeWrapper] elif offset < node.childNodes.length: node = node.childNodes[offset] return get_annot_id_for(node, 0, annot_id_uuid_map) elif node.nodeType is Node.TEXT_NODE: if node.parentNode?.nodeType is Node.ELEMENT_NODE and node.parentNode.dataset?.calibreRangeWrapper: return annot_id_uuid_map[node.parentNode.dataset.calibreRangeWrapper] def highlight_associated_with_selection(sel, annot_id_uuid_map): # Return the annotation id for a highlight intersecting the selection if sel.rangeCount: annot_id = get_annot_id_for(sel.focusNode, sel.focusOffset, annot_id_uuid_map) or get_annot_id_for(sel.anchorNode, sel.anchorOffset, annot_id_uuid_map) if annot_id: return annot_id for v'var i = 0; i < sel.rangeCount; i++': r = sel.getRangeAt(i) annot_id = first_annot_in_range(r, annot_id_uuid_map) if annot_id: return annot_id
9,084
Python
.py
220
33.336364
159
0.666099
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,463
image_popup.pyj
kovidgoyal_calibre/src/pyj/image_popup.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import absolute_path from dom import add_extra_css, svgicon, unique_id from gettext import gettext as _ from popups import MODAL_Z_INDEX from read_book.flow_mode import FlickAnimator from read_book.touch import TouchHandler, install_handlers from utils import debounce add_extra_css(def(): bg = '#333' fg = '#ddd' button_bg = '#333' css = f'.calibre-image-popup {{ background-color: {bg}; color: {fg}; }}' css += f'.calibre-image-popup a {{ padding: 0.25ex; display: inline-block; border-radius: 100%; cursor: pointer; background-color: {button_bg}; }}' css += f'.calibre-image-popup.fit-to-window a.fit-to-window {{ color: {button_bg}; background-color: {fg}; }}' return css ) def fit_image(width, height, pwidth, pheight): ''' Fit image in box of width pwidth and height pheight. @param width: Width of image @param height: Height of image @param pwidth: Width of box @param pheight: Height of box @return: scaled, new_width, new_height. scaled is True iff new_width and/or new_height is different from width or height. ''' scaled = height > pheight or width > pwidth if height > pheight: corrf = pheight / float(height) width, height = Math.floor(corrf*width), pheight if width > pwidth: corrf = pwidth / float(width) width, height = pwidth, Math.floor(corrf*height) if height > pheight: corrf = pheight / float(height) width, height = Math.floor(corrf*width), pheight return scaled, int(width), int(height) class ImagePopup(TouchHandler): def __init__(self): TouchHandler.__init__(self) self.flick_animator = fa = FlickAnimator() fa.scroll_x = self.scroll_x fa.scroll_y = self.scroll_y fa.cancel_current_drag_scroll = def(): pass self._container = None self.container_id = unique_id('image-popup') self.img = None self.img_loading = False self.img_ok = False @property def container(self): if self._container is None: self._container = E.div( style=f'display:none; position:absolute; left:0; top: 0; z-index: {MODAL_Z_INDEX}; width: 100vw; height: 100vh; padding: 0; margin: 0; border-width: 0; box-sizing: border-box', id=self.container_id, tabindex='0', class_='calibre-image-popup', onkeydown=self.onkeydown, onwheel=self.onwheel, E.div( style='position: fixed; top: 0; left: 0; text-align: right; width: 100%; font-size: 200%; padding: 0.25ex; box-sizing: border-box; display: flex; justify-content: space-between', E.a( svgicon('fit-to-screen'), title=_('Fit image to screen'), class_='fit-to-window', onclick=self.toggle_fit_to_window, ), E.a( svgicon('close'), title=_('Close'), onclick=self.hide_container ), ), E.canvas( width=window.innerWidth + '', height=window.innerHeight + '', style='width: 100%; height: 100%; margin: 0; padding: 0; border-width: 0; box-sizing: border-box; display: block', aria_label='Popup view of image', ), ) document.body.appendChild(self._container) install_handlers(self.canvas, self) window.addEventListener('resize', debounce(self.resize_canvas, 250)) return self._container def onwheel(self, ev): ev.stopPropagation(), ev.preventDefault() dy = ev.deltaY dx = ev.deltaX if ev.deltaMode is window.WheelEvent.DOM_DELTA_LINE: dy *= 20 dx *= 20 self.scroll_y(dy) self.scroll_x(dx) def onkeydown(self, ev): ev.preventDefault(), ev.stopPropagation() if ev.key is ' ': return self.toggle_fit_to_window() if ev.key is 'Escape': return self.hide_container() if ev.key is 'ArrowDown': return self.scroll_down((window.innerHeight - 10) if ev.getModifierState("Control") else 10) if ev.key is 'PageDown': return self.scroll_down(window.innerHeight-10) if ev.key is 'ArrowUp': return self.scroll_up((window.innerHeight - 10) if ev.getModifierState("Control") else 10) if ev.key is 'PageUp': return self.scroll_up(window.innerHeight-10) if ev.key is 'ArrowLeft': return self.scroll_left((window.innerWidth - 10) if ev.getModifierState("Control") else 10) if ev.key is 'ArrowRight': return self.scroll_right((window.innerWidth - 10) if ev.getModifierState("Control") else 10) def handle_gesture(self, gesture): self.flick_animator.stop() if gesture.type is 'swipe': if not self.img_ok or self.fit_to_window: return if gesture.points.length > 1 and not gesture.is_held: delta = gesture.points[-2] - gesture.points[-1] if Math.abs(delta) >= 1: if gesture.axis is 'vertical': self.scroll_y(delta) else: self.scroll_x(delta) if not gesture.active and not gesture.is_held: self.flick_animator.start(gesture) if gesture.type is 'pinch' and self.img_ok: if gesture.direction is 'in': self.fit_to_window = True else: self.fit_to_window = False self.update_canvas() @property def vertical_max_bounce_distance(self): return Math.min(60, window.innerHeight / 2) @property def horizontal_max_bounce_distance(self): return Math.min(60, window.innerWidth / 2) def scroll_down(self, amt): if self.img_ok and not self.fit_to_window: canvas_height = self.canvas_height if self.img.height <= canvas_height: return miny = canvas_height - self.img.height - self.vertical_max_bounce_distance y = Math.max(self.y - amt, miny) if y is not self.y: self.y = y self.update_canvas() def scroll_up(self, amt): if self.img_ok and not self.fit_to_window: canvas_height = self.canvas_height if self.img.height <= canvas_height: return y = Math.min(self.y + amt, self.vertical_max_bounce_distance) if y is not self.y: self.y = y self.update_canvas() def scroll_right(self, amt): if self.img_ok and not self.fit_to_window: canvas_width = self.canvas_width if self.img.width <= canvas_width: return minx = canvas_width - self.img.width - self.horizontal_max_bounce_distance x = Math.max(self.x - amt, minx) if x is not self.x: self.x = x self.update_canvas() def scroll_left(self, amt): if self.img_ok and not self.fit_to_window: canvas_width = self.canvas_width if self.img.width <= canvas_width: return x = Math.min(self.x + amt, self.horizontal_max_bounce_distance) if x is not self.x: self.x = x self.update_canvas() def scroll_y(self, amt): if amt < 0: self.scroll_up(-amt) elif amt > 0: self.scroll_down(amt) def scroll_x(self, amt): if amt < 0: self.scroll_left(-amt) elif amt > 0: self.scroll_right(amt) @property def canvas(self): return self.container.getElementsByTagName('canvas')[0] @property def fit_to_window(self): return self.container.classList.contains('fit-to-window') @fit_to_window.setter def fit_to_window(self, val): c = self.container if val: c.classList.add('fit-to-window') c.querySelector('a.fit-to-window').title = _('Do not fit image to window') else: c.classList.remove('fit-to-window') c.querySelector('a.fit-to-window').title = _('Fit image to window') def resize_canvas(self): c = self.canvas dpr = Math.max(1, window.devicePixelRatio) c.width = Math.ceil(window.innerWidth * dpr) c.height = Math.ceil(window.innerHeight * dpr) c.style.width = (c.width / dpr) + 'px' c.style.height = (c.height / dpr) + 'px' ctx = c.getContext('2d') ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.scale(dpr, dpr) ctx.fillStyle = ctx.strokeStyle = '#eee' ctx.font = '16px sans-serif' self.update_canvas() def show_container(self): self.flick_animator.stop() self.container.style.display = 'block' def hide_container(self): self.flick_animator.stop() self.container.style.display = 'none' def show_url(self, url): self.img = Image() self.img.addEventListener('load', self.image_loaded) self.img.addEventListener('error', self.image_failed) self.img_loading = True self.x = self.y = 0 self.img_ok = False self.fit_to_window = True self.img.src = url self.show_container() self.resize_canvas() @property def canvas_width(self): return self.canvas.width / Math.max(1, window.devicePixelRatio) @property def canvas_height(self): return self.canvas.height / Math.max(1, window.devicePixelRatio) def update_canvas(self): canvas = self.canvas ctx = canvas.getContext('2d') ctx.clearRect(0, 0, canvas.width, canvas.height) canvas_width, canvas_height = self.canvas_width, self.canvas_height def draw_centered_text(text): tm = ctx.measureText(text) x = Math.max(0, (canvas_width - tm.width) / 2) y = (canvas_height - 16) / 2 ctx.fillText(text, x, y) if self.img_loading: draw_centered_text(_('Loading image, please wait…')) return if not self.img_ok: draw_centered_text(_('Loading the image failed')) return def draw_full_image_fit_to_canvas(): scaled, width, height = fit_image(self.img.width, self.img.height, canvas_width, canvas_height) scaled x = (canvas_width - width) / 2 y = (canvas_height - height) / 2 ctx.drawImage(self.img, x, y, width, height) if self.fit_to_window: draw_full_image_fit_to_canvas() return ctx.drawImage(self.img, self.x, self.y) def toggle_fit_to_window(self): self.fit_to_window ^= True self.x = self.y = 0 self.update_canvas() def image_loaded(self): self.img_loading = False self.img_ok = True self.update_canvas() def image_failed(self): self.img_loading = False self.img_ok = False self.update_canvas() popup = None def show_image(url): nonlocal popup if popup is None: popup = ImagePopup() popup.show_url(url) def develop(container): show_image(absolute_path('get/cover/1698'))
11,672
Python
.py
279
31.612903
198
0.586711
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,464
ajax.pyj
kovidgoyal_calibre/src/pyj/ajax.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from gettext import gettext as _ default_timeout = 60 def set_default_timeout(val): nonlocal default_timeout default_timeout = val def encode_query_component(x): ans = encodeURIComponent(x) # The following exceptions are to make epubcfi() look better ans = ans.replace(/%2[fF]/g, '/') ans = ans.replace(/%40/g, '@') ans = ans.replace(/%5[bB]/g, '[') ans = ans.replace(/%5[dD]/g, ']') ans = ans.replace(/%5[eE]/g, '^') ans = ans.replace(/%3[aA]/g, ':') return ans def encode_query(query, qchar): if not query: return '' qchar = qchar or '?' keys = Object.keys(query).sort() ans = '' if keys.length: for k in keys: val = query[k] if val is undefined or val is None or val is '': continue ans += qchar + encodeURIComponent(k) + '=' + encode_query_component(val.toString()) qchar = '&' return ans def absolute_path(path): if path[0] is not '/': slash = '' if window.location.pathname[-1] is '/' else '/' path = window.location.pathname + slash + path return path def workaround_qt_bug(xhr, end_type, ok_code=200): if end_type is 'error' and xhr.status is ok_code and window.navigator.userAgent.indexOf('calibre-viewer') is 0: end_type = 'load' return end_type def ajax(path, on_complete, on_progress=None, bypass_cache=True, method='GET', query=None, timeout=None, ok_code=200, progress_totals_needed=True): # Run an AJAX request. on_complete must be a function that accepts three # arguments: end_type, xhr, ev where end_type is one of 'abort', 'error', # 'load', 'timeout'. In case end_type is anything other than 'load' you can # get a descriptive error message via `xhr.error_html`. on_progress, if # provided must be a function accepting three arguments: loaded, total, xhr # where loaded is the number of bytes received, total is the total size. # # Returns the xhr object, call xhr.send() to start the request. if timeout is None: timeout = default_timeout query = query or {} xhr = XMLHttpRequest() eq = encode_query(query) has_query = eq.length > 0 path = absolute_path(path) + eq if bypass_cache: path += ('&' if has_query else '?') + Date().getTime() xhr.request_path = path xhr.error_html = '' def set_error(event, is_network_error): if is_network_error: xhr.error_html = str.format(_('Failed to communicate with "{}", network error. Is the server running and accessible?'), xhr.request_path) elif event is 'timeout': xhr.error_html = str.format(_('Failed to communicate with "{}", timed out after: {} seconds'), xhr.request_path, timeout) elif event is 'abort': xhr.error_html = str.format(_('Failed to communicate with "{}", aborted'), xhr.request_path) else: try: rtext = xhr.responseText or '' except: rtext = '' xhr.error_html = str.format(_('Failed to communicate with "{}", with status: [{} ({})] {}<br><br>{}'), xhr.request_path, xhr.status, event, xhr.statusText, rtext[:200]) def progress_callback(ev): if ev.lengthComputable: on_progress(ev.loaded, ev.total, xhr) elif ev.loaded: if not progress_totals_needed: on_progress(ev.loaded, undefined, xhr) return ul = xhr.getResponseHeader('Calibre-Uncompressed-Length') if ul: try: ul = int(ul) except Exception: return on_progress(ev.loaded, ul, xhr) def complete_callback(end_type, ev): is_network_error = ev if end_type is 'error' else False if xhr.status is not ok_code and end_type is 'load': end_type = 'error' end_type = workaround_qt_bug(xhr, end_type, ok_code) if end_type is not 'load': set_error(end_type, is_network_error) on_complete(end_type, xhr, ev) if on_progress: xhr.addEventListener('progress', progress_callback) xhr.addEventListener('abort', def(ev): complete_callback('abort', ev);) xhr.addEventListener('error', def(ev): complete_callback('error', ev);) xhr.addEventListener('load', def(ev): complete_callback('load', ev);) xhr.addEventListener('timeout', def(ev): complete_callback('timeout', ev);) xhr.open(method, path) xhr.timeout = timeout * 1000 # IE requires timeout to be set after open return xhr def ajax_send(path, data, on_complete, on_progress=None, query=None, timeout=None, ok_code=200): # Unfortunately, browsers do not allow sending of data with HTTP GET, except # as query parameters, so we have to use POST xhr = ajax(path, on_complete, on_progress, False, 'POST', query, timeout, ok_code) xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8') xhr.send(JSON.stringify(data)) return xhr def ajax_send_file(path, file, on_complete, on_progress, timeout=None, ok_code=200): xhr = ajax(path, on_complete, on_progress, False, 'POST', timeout, ok_code) if file.type: xhr.overrideMimeType(file.type) xhr.send(file) return xhr def console_print(*args): ρσ_print(*args) # noqa: undef data = ' '.join(map(str, args)) + '\n' xhr = ajax('console-print', def():pass;, method='POST', progress_totals_needed=False) xhr.send(data) # TODO: Implement AJAX based switch user by: # 1) POST to a logout URL with an incorrect username and password # 2) Have the server accept that incorrect username/password # 3) Navigate to / which should cause the browser to re-prompt for username and password # (only problem is login dialog will likely pre-show the wrong username) To workaround that, # You can consider using a dedicated ajax based login form, see http://www.peej.co.uk/articles/http-auth-with-html-forms.html)
6,162
Python
.py
129
40.527132
180
0.643667
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,465
fs_images.pyj
kovidgoyal_calibre/src/pyj/fs_images.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals def is_svg_fs_markup(names, svg): if svg is not None: if names.length is 2 or names.length is 3: if names[-1] is 'image' and names[-2] is 'svg': if names.length is 2 or names[0] is 'div': if svg.width is '100%' and svg.height is '100%': return True return False def fix_fullscreen_svg_images(): # Full screen images using SVG no longer render correctly # webengine. This is because it sets the width to the # viewport width and simply adjusts the height accordingly # So we replace 100% with 100vw and 100vh to get the desired # rendering child_names = v'[]' for node in document.body.childNodes: if node.tagName: name = node.tagName.toLowerCase() if name is not 'style' and name is not 'script': child_names.push(name) if child_names.length > 1: break if child_names.length is 1 and (child_names[0] is 'div' or child_names[0] is 'svg'): names = v'[]' svg = None for node in document.body.querySelectorAll('*'): if node.tagName: name = node.tagName.toLowerCase() if name is not 'style' and name is not 'script': names.push(name) if name is 'svg': svg = node if is_svg_fs_markup(names, svg): svg.setAttribute('width', '100vw') svg.setAttribute('height', '100vh')
1,677
Python
.py
38
33.526316
88
0.584455
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,466
modals.pyj
kovidgoyal_calibre/src/pyj/modals.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from elementmaker import E from gettext import gettext as _ from ajax import ajax, ajax_send from book_list.theme import get_color, get_font_size from dom import add_extra_css, build_rule, clear, set_css, svgicon, unique_id from popups import MODAL_Z_INDEX from utils import safe_set_inner_html from widgets import create_button from book_list.globals import get_session_data modal_container = None modal_count = 0 add_extra_css(def(): style = build_rule( '#modal-container > div > a:hover', color=get_color('dialog-foreground') + ' !important', background_color=get_color('dialog-background') + ' !important' ) style += build_rule( '.button-box', display='flex', justify_content='flex-end', padding='1rem 0rem', overflow='hidden' ) style += build_rule('.button-box .calibre-push-button', transform_origin='right') return style ) class Modal: def __init__(self, create_func, on_close, show_close, onkeydown): nonlocal modal_count self.create_func, self.on_close, self.show_close = create_func, on_close, show_close self.onkeydown = onkeydown modal_count += 1 self.id = modal_count class ModalContainer: def __init__(self): div = E.div(id='modal-container', tabindex='0', E.div( # popup E.div(class_='modal_height_container'), # content area E.a(svgicon('close'), title=_('Close'), onclick=self.close_current_modal.bind(self)) ) ) div.addEventListener('keydown', self.onkeydown.bind(self), {'passive': False}) document.body.appendChild(div) # Container style set_css(div, position='fixed', top='0', right='0', bottom='0', left='0', # Stretch over entire window background_color='rgba(0,0,0,0.8)', z_index=MODAL_Z_INDEX + '', display='none', user_select='none', justify_content='center', align_items='center', ) # Popup style set_css(div.firstChild, position='relative', display='inline-block', min_width='25vw', max_width='70vw', # Needed for iPhone 5 border_radius='1em', padding='1em 2em', margin_right='1em', margin_left='1em', background=get_color('dialog-background'), color=get_color('dialog-foreground'), background_image=get_color('dialog-background-image'), get_color('dialog-background'), get_color('dialog-background2') ) # Close button style set_css(div.firstChild.lastChild, font_size='1.5em', line_height='100%', cursor='pointer', position='absolute', right='-0.5em', top='-0.5em', width='1em', height='1em', background_color=get_color('window-foreground'), color=get_color('window-background'), display='inline-box', border_radius='50%', padding='4px', text_align='center', box_shadow='1px 1px 3px black' ) # Content container style # need padding: 1px to avoid scrollbar in modal on Qt WebEngine 6.3 set_css(div.firstChild.firstChild, user_select='text', max_height='60vh', overflow='auto', padding='1px') self.modals = v'[]' self.current_modal = None self.hide = self.close_current_modal.bind(self) @property def modal_container(self): return document.getElementById('modal-container') def show_modal(self, create_func, on_close=None, show_close=True, onkeydown=None): self.modals.push(Modal(create_func, on_close, show_close, onkeydown)) modal_id = self.modals[-1].id self.update() window.setTimeout(def(): self.modal_container.focus();, 0) return modal_id def hide_modal(self, modal_id): if self.current_modal is not None and self.current_modal.id is modal_id: self.clear_current_modal() else: doomed_modal = None for i, modal in enumerate(self.modals): if modal.id is modal_id: doomed_modal = i break if doomed_modal is not None: self.modals.splice(doomed_modal, 1) def update(self): if self.current_modal is None and self.modals: self.current_modal = self.modals.shift() c = self.modal_container try: self.current_modal.create_func(c.firstChild.firstChild, self.hide) except: self.current_modal = None raise if c.style.display is 'none': c.style.display = 'flex' c.firstChild.lastChild.style.visibility = 'visible' if self.current_modal.show_close else 'hidden' def clear_current_modal(self): self.current_modal = None c = self.modal_container clear(c.firstChild.firstChild) if self.modals.length is 0: set_css(c, display='none') else: self.update() def close_current_modal(self, event): if self.current_modal is not None: if self.current_modal.on_close is not None and self.current_modal.on_close(event) is True: return self.clear_current_modal() def close_all_modals(self): while self.current_modal is not None: self.close_current_modal() def onkeydown(self, event): if self.current_modal is not None and self.current_modal.onkeydown: return self.current_modal.onkeydown(event, self.clear_current_modal.bind(self)) if (event.key is 'Escape' or event.key is 'Esc') and not event.altKey and not event.ctrlKey and not event.metaKey and not event.shiftKey: event.preventDefault(), event.stopPropagation() self.close_current_modal(event) def create_simple_dialog_markup(title, msg, details, icon, prefix, icon_color, parent): details = details or '' show_details = E.a(class_='blue-link', style='padding-top:1em; display:inline-block; margin-left: auto', _('Show details')) show_details.addEventListener('click', def(): show_details.style.display = 'none' show_details.nextSibling.style.display = 'block' ) is_html_msg = /<[a-zA-Z]/.test(msg) html_container = E.div() if is_html_msg: safe_set_inner_html(html_container, msg) details_container = E.span() if /<[a-zA-Z]/.test(details): safe_set_inner_html(details_container, details) else: details_container.textContent = details if prefix: prefix = E.span(' ' + prefix + ' ', style='white-space:pre; font-variant: small-caps') else: prefix = '\xa0' parent.appendChild( E.div( style='max-width:40em; text-align: left', E.h2( E.span(svgicon(icon), style=f'color:{icon_color}'), prefix, title, style='font-weight: bold; font-size: ' + get_font_size('title') ), E.div((html_container if is_html_msg else msg), style='padding-top: 1em; margin-top: 1em; border-top: 1px solid currentColor'), E.div(style='display: ' + ('block' if details else 'none'), show_details, E.div(details_container, style='display:none; white-space:pre-wrap; font-size: smaller; margin-top: 1em; border-top: solid 1px currentColor; padding-top: 1em' ) ) ) ) def create_simple_dialog(title, msg, details, icon, prefix, on_close=None, icon_color='red'): show_modal(create_simple_dialog_markup.bind(None, title, msg, details, icon, prefix, icon_color), on_close=on_close) def create_custom_dialog(title, content_generator_func, on_close=None, onkeydown=None): def create_func(parent, close_modal): content_div = E.div() parent.appendChild( E.div( style='max-width:60em; text-align: left', E.h2(title, style='font-weight: bold; font-size: ' + get_font_size('title')), E.div(content_div, style='padding-top: 1em; margin-top: 1em; border-top: 1px solid currentColor'), )) content_generator_func(content_div, close_modal) show_modal(create_func, on_close=on_close, onkeydown=onkeydown) def get_text_dialog(title, callback, initial_text=None, msg=None, rows=12): called = {} cid = unique_id() def keyaction(ok, close_modal): if called.done: return called.done = True text = document.getElementById(cid).value or '' if close_modal: close_modal() callback(ok, text) def on_keydown(event, close_modal): if event.altKey or event.ctrlKey or event.metaKey or event.shiftKey: return if event.key is 'Escape' or event.key is 'Esc': event.preventDefault(), event.stopPropagation() keyaction(False, close_modal) create_custom_dialog( title, def(parent, close_modal): parent.appendChild(E.div( E.textarea(initial_text or '', placeholder=msg or '', id=cid, rows=rows + '', style='min-width: min(40rem, 60vw)'), E.div(class_='button-box', create_button(_('OK'), 'check', keyaction.bind(None, True, close_modal), highlight=True), '\xa0', create_button(_('Cancel'), 'close', keyaction.bind(None, False, close_modal)) ), )) window.setTimeout(def(): parent.querySelector('textarea').focus();, 10) , on_close=keyaction.bind(None, False, None), onkeydown=on_keydown ) def question_dialog( title, msg, callback, yes_text=None, no_text=None, skip_dialog_name=None, skip_dialog_msg=None, skip_dialog_skipped_value=True, skip_dialog_skip_precheck=True, ): yes_text = yes_text or _('Yes') no_text = no_text or _('No') called = {} def keyaction(yes, close_modal): if called.done: return called.done = True if skip_dialog_name: if not skip_box.querySelector('input').checked: sd = get_session_data() skipped_dialogs = Object.assign(v'{}', sd.get('skipped_dialogs', v'{}')) skipped_dialogs[skip_dialog_name] = Date().toISOString() sd.set('skipped_dialogs', skipped_dialogs) if close_modal: close_modal() callback(yes) def on_keydown(event, close_modal): if event.altKey or event.ctrlKey or event.metaKey or event.shiftKey: return if event.key is 'Escape' or event.key is 'Esc': event.preventDefault(), event.stopPropagation() keyaction(False, close_modal) if event.key is 'Enter' or event.key is 'Return' or event.key is 'Space': event.preventDefault(), event.stopPropagation() keyaction(True, close_modal) skip_box = E.div(style='margin-top: 2ex;') if skip_dialog_name: sd = get_session_data() skipped_dialogs = sd.get('skipped_dialogs', v'{}') if skipped_dialogs[skip_dialog_name]: return callback(skip_dialog_skipped_value) skip_dialog_msg = skip_dialog_msg or _('Show this confirmation again') skip_box.appendChild(E.label(E.input(type='checkbox', name='skip_dialog'), '\xa0', skip_dialog_msg)) if skip_dialog_skip_precheck: skip_box.querySelector('input').checked = True else: skip_box.style.display = 'none' create_custom_dialog( title, def(parent, close_modal): parent.appendChild(E.div( E.div(msg), skip_box, E.div(class_='button-box', create_button(yes_text, 'check', keyaction.bind(None, True, close_modal), highlight=True), '\xa0', create_button(no_text, 'close', keyaction.bind(None, False, close_modal)) )) ) , on_close=keyaction.bind(None, False, None), onkeydown=on_keydown ) def create_progress_dialog(msg, on_close): msg = msg or _('Loading, please wait...') pbar, msg_div = E.progress(style='display:inline-block'), E.div(msg, style='text-align:center; padding-top:1ex') def create_func(parent): parent.appendChild(E.div(style='text-align: center', pbar, msg_div)) show_close = on_close is not None modal_id = show_modal(create_func, on_close, show_close) return { 'close': def(): modal_container.hide_modal(modal_id);, 'update_progress': def(amount, total): pbar.max, pbar.value = total, amount;, 'set_msg': def(new_msg): safe_set_inner_html(msg_div, new_msg);, } # def test_progress(): # counter = 0 # pd = progress_dialog('Testing progress dialog, please wait...', def(): # nonlocal counter # counter = 101 # console.log('pd canceled') # ) # def update(): # nonlocal counter # counter += 1 # pd.update_progress(counter, 100) # if counter < 100: # setTimeout(update, 150) # else: # pd.close() # update() # # def test_error(): # error_dialog( # 'Hello, world!', # 'Some long text to test rendering/line breaking in error dialogs that contain lots of text like this test error dialog from hell in a handbasket with fruits and muppets making a scene.', # ['a word ' for i in range(10000)].join(' ') # ) def create_modal_container(): nonlocal modal_container if modal_container is None: modal_container = ModalContainer() # window.setTimeout(def(): # document.getElementById('books-view-1').addEventListener('click', test_progress) # , 10) return modal_container def show_modal(create_func, on_close=None, show_close=True, onkeydown=None): return modal_container.show_modal(create_func, on_close, show_close, onkeydown) def close_all_modals(): return modal_container.close_all_modals() def error_dialog(title, msg, details=None, on_close=None): create_simple_dialog(title, msg, details, 'bug', _('Error:'), on_close) def warning_dialog(title, msg, details=None, on_close=None): create_simple_dialog(title, msg, details, 'warning', _('Warning:'), on_close) def info_dialog(title, msg, details=None, on_close=None): create_simple_dialog(title, msg, details, 'check', '', on_close, icon_color='green') def progress_dialog(msg, on_close=None): # Show a modal dialog with a progress bar and an optional close button. # If the user clicks the close button, on_close is called and the dialog is closed. # Returns an object with the methods: close(), update_progress(amount, total), set_msg() # Call update_progress() to update the progress bar # Call set_msg() to change the displayed message # Call close() once the task being performed is finished return create_progress_dialog(msg, on_close) def ajax_progress_dialog(path, on_complete, msg, extra_data_for_callback=None, **kw): pd = None def on_complete_callback(event_type, xhr, ev): nonlocal pd pd.close() pd = undefined return on_complete(event_type, xhr, ev) def on_progress_callback(loaded, total, xhr): pd.update_progress(loaded, total) xhr = ajax(path, on_complete_callback, on_progress=on_progress_callback, **kw) xhr.extra_data_for_callback = extra_data_for_callback pd = progress_dialog(msg, xhr.abort.bind(xhr)) xhr.send() return xhr, pd def ajax_send_progress_dialog(path, data, on_complete, msg, **kw): pd = None def on_complete_callback(event_type, xhr, ev): nonlocal pd pd.close() pd = undefined return on_complete(event_type, xhr, ev) def on_progress_callback(loaded, total, xhr): pd.update_progress(loaded, total) xhr = ajax_send(path, data, on_complete_callback, on_progress=on_progress_callback, **kw) pd = progress_dialog(msg, xhr.abort.bind(xhr)) return xhr, pd
16,223
Python
.py
349
38.045845
196
0.626628
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,467
viewer-main.pyj
kovidgoyal_calibre/src/pyj/viewer-main.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E import initialize # noqa: unused-import import traceback from ajax import absolute_path, ajax, workaround_qt_bug from book_list.globals import get_session_data, set_session_data from book_list.library_data import library_data from book_list.theme import css_for_variables, get_color from date import format_date from dom import get_widget_css, set_css from gettext import gettext as _, install from modals import create_modal_container from qt import from_python, to_python from read_book.db import new_book from read_book.footnotes import main as footnotes_main from read_book.globals import ( default_color_schemes, runtime, set_system_colors, ui_operations ) from read_book.iframe import main as iframe_main from read_book.open_book import remove_recently_opened from read_book.prefs.head_foot import set_time_formatter from read_book.view import View from session import ( apply_reader_profile, default_interface_data, local_storage, session_defaults, settings_for_reader_profile ) from utils import debounce, encode_query_with_path, parse_url_params from viewer.constants import FAKE_HOST, FAKE_PROTOCOL runtime.is_standalone_viewer = True runtime.FAKE_HOST = FAKE_HOST runtime.SANDBOX_HOST = FAKE_HOST.rpartition('.')[0] + '.sandbox' runtime.FAKE_PROTOCOL = FAKE_PROTOCOL book = None view = None def file_received(name, file_data, proceed, end_type, xhr, ev): end_type = workaround_qt_bug(xhr, end_type) if end_type is 'abort': return if end_type is not 'load': show_error(_('Failed to load file from book'), _( 'Could not load the file: {} with error: {}').format(name, xhr.error_html)) return if not xhr.responseType or xhr.responseType is 'text': result = xhr.responseText else if xhr.responseType is 'blob': result = xhr.response else: show_error(_('Failed to load file from book'), _( 'Could not load the file: {} unknown response type: {}').format(name, xhr.responseType)) return proceed(result, name, file_data.mimetype, book) def get_url_for_book_file_name(name): return absolute_path('book/' + name) def get_file(book, name, proceed): entry = book.manifest.files[name] if not entry: raise ValueError(f'No file named {name} in the book manifest') xhr = ajax('book/' + name, file_received.bind(None, name, entry, proceed), ok_code=0) if entry.is_html or entry.mimetype.startswith('text/') or entry.mimetype is 'application/javascript': xhr.responseType = 'text' else: xhr.responseType = 'blob' xhr.send() profiles_callbacks = {'all': None, 'saved': None} @from_python def profile_response(which, x): if which is 'all-profiles': profiles_callbacks.all(x) profiles_callbacks.all = None elif which is 'save-profile': profiles_callbacks.saved() profiles_callbacks.saved = None elif which is 'apply-profile': sd = get_session_data() apply_reader_profile(sd, x) if view: view.preferences_changed() ui_operations.apply_profile(x) elif which is 'request-save': sd = get_session_data() settings = settings_for_reader_profile(sd) save_profile(x, settings, def(): pass;) def get_all_profiles(proceed): profiles_callbacks.all = proceed to_python.profile_op('all-profiles', '', None) def save_profile(name, settings, proceed): profiles_callbacks.saved = proceed to_python.profile_op('save-profile', name, settings) def get_mathjax_files(proceed): proceed({}) def update_url_state(replace): if view and view.currently_showing: bookpos = view.currently_showing.bookpos if bookpos: query = {'bookpos': bookpos} query = encode_query_with_path(query) if replace: window.history.replaceState(None, '', query) else: window.history.pushState(None, '', query) def on_pop_state(): if view and view.currently_showing: data = parse_url_params() if data.bookpos and data.bookpos.startswith('epubcfi(/'): view.goto_cfi(data.bookpos) def show_error(title, msg, details): to_python.show_error(title, msg, details) def manifest_received(key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url, end_type, xhr, ev): nonlocal book end_type = workaround_qt_bug(xhr, end_type) if end_type is 'load': book = new_book(key, {}) data = xhr.response book.manifest = data[0] book.metadata = book.manifest.metadata = data[1] book.manifest.pathtoebook = pathtoebook book.highlights = highlights book.stored_files = {} book.calibre_book_url = book_url book.calibre_book_in_library_url = book_in_library_url book.saved_reading_rates = reading_rates book.is_complete = True v'delete book.manifest["metadata"]' v'delete book.manifest["last_read_positions"]' view.display_book(book, initial_position) else: show_error(_('Could not open book'), _( 'Failed to load book manifest, click "Show details" for more info'), xhr.error_html or None) def clone(x): if x: x = window.structuredClone(x) return x class SessionData: def __init__(self, prefs): defaults = session_defaults() self.data = {k: clone(defaults[k]) if prefs[k] is undefined else clone(prefs[k]) for k in defaults} def get(self, key, defval): ans = self.data[key] if ans is undefined or ans is None: if defval is undefined: defval = None return defval return ans def set(self, key, val): if val is None: self.data[key] = clone(session_defaults()[key]) else: self.data[key] = val to_python.set_session_data(key, val) def set_bulk(self, changes): defaults = session_defaults() for key in Object.keys(changes): val = changes[key] if val is None: self.data[key] = clone(defaults[key]) else: self.data[key] = val to_python.set_session_data(changes, None) def clear(self): defaults = session_defaults() self.data = {k: clone(defaults[k]) for k in defaults} to_python.set_session_data('*', None) class LocalStorage: def __init__(self, data): self.data = data def get(self, key, defval): ans = self.data[key] if ans is undefined or ans is None: if defval is undefined: defval = None return defval return ans def set(self, key, val): self.data[key] = val to_python.set_local_storage(key, val) def clear(self): self.data = {} to_python.set_local_storage('*', None) def create_session_data(prefs, local_storage_data): sd = SessionData(prefs) set_session_data(sd) local_storage.storage = LocalStorage(local_storage_data) @from_python def create_view(prefs, local_storage, field_metadata, ui_data): nonlocal view set_system_colors(ui_data.system_colors) runtime.all_font_families = ui_data.all_font_families library_data.field_metadata = field_metadata document.documentElement.style.fontFamily = f'"{ui_data.ui_font_family}", sans-serif' document.documentElement.style.fontSize = ui_data.ui_font_sz runtime.QT_VERSION = ui_data.QT_VERSION set_time_formatter(def (d): return format_date(d, ui_data.short_time_fmt) ) if view is None: create_session_data(prefs, local_storage) view = View(document.getElementById('view')) window.addEventListener('resize', debounce(view.on_resize.bind(self), 250)) to_python.view_created({'default_color_schemes': default_color_schemes}) default_interface_data.use_roman_numerals_for_series_number = ui_data.use_roman_numerals_for_series_number if ui_data.show_home_page_on_ready: view.overlay.open_book(False) @from_python def set_system_palette(system_colors): set_system_colors(system_colors) if view: view.update_color_scheme() @from_python def highlight_action(uuid, which): if view: view.highlight_action(uuid, which) @from_python def generic_action(which, data): if which is 'set-notes-in-highlight': view.set_notes_for_highlight(data.uuid, data.notes or '') if which is 'show-status-message': view.show_status_message(data.text) if which is 'remove-recently-opened': remove_recently_opened(data.path) @from_python def tts_event(which, data): view.read_aloud.handle_tts_event(which, data) @from_python def show_home_page(): view.overlay.open_book(False) @from_python def start_book_load(key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url): xhr = ajax('manifest', manifest_received.bind(None, key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url), ok_code=0) xhr.responseType = 'json' xhr.send() @from_python def goto_toc_node(node_id): view.goto_toc_node(node_id) @from_python def goto_cfi(cfi, add_to_history): return view.goto_cfi(cfi, v'!!add_to_history') @from_python def full_screen_state_changed(viewer_in_full_screen): runtime.viewer_in_full_screen = viewer_in_full_screen @from_python def get_current_cfi(request_id): view.get_current_cfi(request_id, ui_operations.report_cfi) @from_python def goto_frac(frac): if view: view.goto_frac(frac) @from_python def background_image_changed(img_id, url): img = document.getElementById(img_id) if img: img.src = f'{url}?{Date().getTime()}' img.dataset.url = url @from_python def trigger_shortcut(which): if view: view.on_handle_shortcut({'name': which}) @from_python def show_search_result(sr): if view: if sr.on_discovery: view.discover_search_result(sr) else: view.show_search_result(sr) @from_python def prepare_for_close(): if view: view.prepare_for_close() else: ui_operations.close_prep_finished(None) @from_python def repair_after_fullscreen_switch(): if view: view.show_status_message('...', 200) @from_python def viewer_font_size_changed(): if view: view.viewer_font_size_changed() def onerror(msg, script_url, line_number, column_number, error_object): if not error_object: # cross domain error return False fname = script_url.rpartition('/')[-1] or script_url msg += '<br><span style="font-size:smaller">' + 'Error at {}:{}:{}'.format(fname, line_number, column_number or '') + '</span>' details = '' console.log(error_object) details = traceback.format_exception(error_object).join('') show_error(_('Unhandled error'), msg, details) return True if window is window.top: # main TRANSLATIONS_DATA = v'__TRANSLATIONS_DATA__' if TRANSLATIONS_DATA: install(TRANSLATIONS_DATA) ui_operations.get_all_profiles = get_all_profiles ui_operations.save_profile = save_profile ui_operations.apply_profile = def(profile): to_python.profile_op('apply-profile-to-viewer-ui', "", profile) ui_operations.get_file = get_file ui_operations.get_url_for_book_file_name = get_url_for_book_file_name ui_operations.get_mathjax_files = get_mathjax_files ui_operations.update_url_state = update_url_state ui_operations.show_error = show_error ui_operations.redisplay_book = def(): view.redisplay_book() ui_operations.reload_book = def(): to_python.reload_book() ui_operations.forward_gesture = def(gesture): view.forward_gesture(gesture) ui_operations.update_color_scheme = def(): view.update_color_scheme() ui_operations.update_font_size = def(): view.update_font_size() ui_operations.focus_iframe = def(): view.focus_iframe() ui_operations.goto_cfi = def(cfi): return view.goto_cfi(cfi) ui_operations.goto_frac = def(frac): return view.goto_frac(frac) ui_operations.goto_book_position = def(bpos): return view.goto_book_position(bpos) ui_operations.goto_reference = def(ref): return view.goto_reference(ref) ui_operations.toggle_toc = def(): to_python.toggle_toc() ui_operations.toggle_bookmarks = def(): to_python.toggle_bookmarks() ui_operations.toggle_highlights = def(): to_python.toggle_highlights() ui_operations.new_bookmark = def(request_id, data): if request_id is 'new-bookmark': to_python.new_bookmark(data) ui_operations.toggle_inspector = def(): to_python.toggle_inspector() ui_operations.content_file_changed = def(name): to_python.content_file_changed(name) ui_operations.show_search = def(text, trigger): to_python.show_search(text, v'!!trigger') ui_operations.find_next = def(previous): to_python.find_next(previous) ui_operations.reset_interface = def(): sd = get_session_data() defaults = session_defaults() m = sd.get('standalone_misc_settings', {}) v'delete m.show_actions_toolbar' sd.set('standalone_misc_settings', m) sd.set('book_scrollbar', False) view.book_scrollbar.apply_visibility() sd.set('header', defaults.header) sd.set('footer', defaults.footer) view.update_header_footer() to_python.reset_interface() ui_operations.open_url = def(url): to_python.open_url(url) ui_operations.quit = def(): to_python.quit() ui_operations.toggle_lookup = def(force_show): to_python.toggle_lookup(v'!!force_show') ui_operations.selection_changed = def(selected_text, annot_id): to_python.selection_changed(selected_text, annot_id or None) ui_operations.update_current_toc_nodes = def(families): to_python.update_current_toc_nodes(families) ui_operations.toggle_full_screen = def(): to_python.toggle_full_screen() ui_operations.report_cfi = def(request_id, data): to_python.report_cfi(request_id, data) ui_operations.ask_for_open = def(path): to_python.ask_for_open(path) ui_operations.copy_selection = def(text, html): to_python.copy_selection(text or None, html or None) ui_operations.view_image = def(name): to_python.view_image(name) ui_operations.copy_image = def(name): to_python.copy_image(name) ui_operations.change_background_image = def(img_id): to_python.change_background_image(img_id) ui_operations.quit = def(): to_python.quit() ui_operations.overlay_visibility_changed = def(visible): to_python.overlay_visibility_changed(visible) ui_operations.reference_mode_changed = def(enabled): to_python.reference_mode_changed(enabled) ui_operations.show_loading_message = def(msg): to_python.show_loading_message(msg) ui_operations.export_shortcut_map = def(smap): to_python.export_shortcut_map(smap) ui_operations.print_book = def(): to_python.print_book() ui_operations.clear_history = def(): to_python.clear_history() ui_operations.customize_toolbar = def(): to_python.customize_toolbar() ui_operations.autoscroll_state_changed = def(active): to_python.autoscroll_state_changed(active) ui_operations.read_aloud_state_changed = def(active): to_python.read_aloud_state_changed(active) ui_operations.search_result_not_found = def(sr): to_python.search_result_not_found(sr) ui_operations.search_result_discovered = def(sr): to_python.search_result_discovered(sr) ui_operations.scrollbar_context_menu = def(x, y, frac): to_python.scrollbar_context_menu(x, y, frac) ui_operations.close_prep_finished = def(cfi): to_python.close_prep_finished(cfi) ui_operations.annots_changed = def(amap): if amap.highlight: to_python.highlights_changed(amap.highlight) ui_operations.speak_simple_text = def(text): to_python.speak_simple_text(text) ui_operations.tts = def(action, data): to_python.tts(action, data or v'{}') ui_operations.edit_book = def (spine_name, frac, selected_text): to_python.edit_book(spine_name, frac, selected_text or '') ui_operations.show_book_folder = def(): to_python.show_book_folder() ui_operations.show_help = def(which): to_python.show_help(which) ui_operations.on_iframe_ready = def(): to_python.on_iframe_ready() ui_operations.update_reading_rates = def(rates): to_python.update_reading_rates(rates) document.body.appendChild(E.div(id='view')) window.onerror = onerror create_modal_container() document.head.appendChild(E.style(css_for_variables() + '\n\n' + get_widget_css())) set_css(document.body, background_color=get_color('window-background'), color=get_color('window-foreground')) setTimeout(def(): window.onpopstate = on_pop_state , 0) # We do this after event loop ticks over to avoid catching popstate events that some browsers send on page load else: # iframe if document.location.pathname.endsWith('/__index__'): iframe_main() elif document.location.pathname.endsWith('/__popup__'): footnotes_main()
17,791
Python
.py
436
34.392202
161
0.676162
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,468
popups.pyj
kovidgoyal_calibre/src/pyj/popups.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods from book_list.theme import get_color from dom import set_css, ensure_id, clear, build_rule, add_extra_css from elementmaker import E MODAL_Z_INDEX = 1000 POPUP_Z_INDEX = MODAL_Z_INDEX + 1 popup_count = 0 shown_popups = set() associated_widgets = {} def element_contains_click_event(element, event): r = element.getBoundingClientRect() return r.left <= event.clientX <= r.right and r.top <= event.clientY <= r.bottom def click_in_popup(event): for popup_id in shown_popups: popup = document.getElementById(popup_id) if popup and element_contains_click_event(popup, event): return True w = associated_widgets[popup_id] if w and w.length: for wid in w: widget = document.getElementById(wid) if widget and element_contains_click_event(widget, event): return True return False def filter_clicks(event): if shown_popups.length: if not click_in_popup(event): for popup_id in shown_popups: hide_popup(popup_id) shown_popups.clear() event.stopPropagation(), event.preventDefault() def install_event_filters(): window.addEventListener('click', filter_clicks, True) def create_popup(parent, idprefix): nonlocal popup_count popup_count += 1 pid = (idprefix or 'popup') + '-' + popup_count # Position has to be fixed so that setting style.top/style.bottom works in # viewport co-ordinates div = E.div(id=pid, style='display: none; position: fixed; z-index: {}'.format(POPUP_Z_INDEX)) parent = parent or document.body parent.appendChild(div) return div def show_popup(popup_id, associated_widget_ids=None): elem = document.getElementById(popup_id) elem.style.display = 'block' shown_popups.add(popup_id) associated_widgets[popup_id] = associated_widget_ids def hide_popup(popup_id): elem = document.getElementById(popup_id) if elem: elem.style.display = 'none' v'delete associated_widgets[popup_id]' class CompletionPopup: CLASS = 'popup-completion-items' CURRENT_ITEM_CLASS = 'popup-completion-current-item' def __init__(self, parent=None, max_items=25, onselect=None): self.max_items = max_items c = create_popup(parent) set_css(c, user_select='none') self.container_id = c.getAttribute('id') self.onselect = onselect self.items = [] self.matches = [] c.appendChild(E.div(class_=self.CLASS)) self.associated_widget_ids = set() self.current_query, self.is_upwards = '', False self.applied_query = self.current_query @property def container(self): return document.getElementById(self.container_id) @property def is_visible(self): return self.container.style.display is not 'none' def set_all_items(self, items): self.items = list(items) self.matches = [] self.applied_query = None def add_associated_widget(self, widget_or_id): if jstype(widget_or_id) is not 'string': widget_or_id = ensure_id(widget_or_id) self.associated_widget_ids.add(widget_or_id) def popup(self, widget): if not self.is_visible: if self.applied_query is not self.current_query: self._apply_query() if self.matches.length: self.show_at_widget(widget) def show_at_widget(self, w): br = w.getBoundingClientRect() if br.top > window.innerHeight - br.bottom: y, upwards = br.top, True else: y, upwards = br.bottom, False self._show_at(br.left, y, br.width, upwards) def set_query(self, query): self.current_query = query if self.is_visible and self.applied_query is not self.current_query: self._apply_query() if not self.matches.length: self.hide() def hide(self): self.container.style.display = 'none' c = self.current_item if c: c.classList.remove(self.CURRENT_ITEM_CLASS) def handle_keydown(self, event): key = event.key if key is 'Escape' or key is 'Esc': self.hide() return True if key is 'ArrowUp': self.move_highlight(True) return True if key is 'ArrowDown': self.move_highlight(False) return True return False @property def current_item(self): c = self.container return c.querySelector('div.{} > div.{}'.format(self.CLASS, self.CURRENT_ITEM_CLASS)) @property def current_text(self): return self.current_item?.textContent def move_highlight(self, up=None): if up is None: up = self.is_upwards ans = None div = self.current_item if div: div.classList.remove(self.CURRENT_ITEM_CLASS) ans = div.previousSibling if up else div.nextSibling if not ans: c = self.container.firstChild ans = c.lastChild if up else c.firstChild if ans: ans.classList.add(self.CURRENT_ITEM_CLASS) def _show_at(self, x, y, width, upwards): self.is_upwards = upwards c = self.container cs = c.style cs.left = x + 'px' cs.top = 'auto' if upwards else y + 'px' cs.bottom = (window.innerHeight - y) + 'px' if upwards else 'auto' cs.width = width + 'px' cs.maxHeight = ((y if upwards else window.innerHeight - y) - 10) + 'px' show_popup(self.container_id, self.associated_widget_ids) def _apply_query(self): q = self.current_query.toLowerCase() self.matches.clear() self.applied_query = self.current_query if not q: self.matches = list(self.items[:self.max_items + 1]) else: i = 0 while self.matches.length < self.max_items and i < self.items.length: if self.items[i].toLowerCase().startswith(q): self.matches.push(self.items[i]) i += 1 self._render_matches() def _render_matches(self): c = self.container clear(c.firstChild) items = self.matches if self.is_upwards: items = reversed(items) for m in items: c.firstChild.appendChild(E.div(m, onmouseenter=self.onmouseenter, onclick=self.onclick)) def onmouseenter(self, event): div = self.current_item if div: div.classList.remove(self.CURRENT_ITEM_CLASS) event.currentTarget.classList.add(self.CURRENT_ITEM_CLASS) def onclick(self, event): self.onmouseenter(event) try: if self.onselect: self.onselect(self.current_text) finally: self.hide() add_extra_css(def(): sel = 'div.' + CompletionPopup.CLASS style = build_rule(sel, overflow='hidden', text_align='left', background_color=get_color('window-background'), border='solid 1px ' + get_color('window-foreground')) sel += ' > div' style += build_rule(sel, cursor='pointer', padding='1ex 1rem', white_space='nowrap', text_overflow='ellipsis', overflow='hidden') sel += '.' + CompletionPopup.CURRENT_ITEM_CLASS style += build_rule(sel, color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background')) return style )
7,639
Python
.py
192
31.416667
168
0.626888
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,469
testing.pyj
kovidgoyal_calibre/src/pyj/testing.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from dom import clear def raise_fail(preamble, msg, call_site): if msg: msg = '. ' + msg else: msg = '' if call_site?.module_name: msg += f' [in module {call_site.module_name}:{call_site.line}:{call_site.col}]' raise AssertionError(preamble + msg) def repr_of(a): if not a: return a q = a.outerHTML if q: return q.split('>')[0] + '>' if a.nodeType is Node.TEXT_NODE: return repr(a.nodeValue) return str(a) def assert_equal(a, b, msg, call_site=None): def fail(): ra = repr_of(a) rb = repr_of(b) p = f'{ra} != {rb}' raise_fail(p, msg, call_site) atype = jstype(a) btype = jstype(b) base_types = {'number': True, 'boolean': True, 'string': True, 'undefined': True} if base_types[atype] or base_types[btype] or a is None or b is None: if a is not b: fail() return if a.__eq__: if not a.__eq__(b): fail() return if a.isSameNode: if not a.isSameNode(b): fail() return if b.__eq__: if not b.__eq__(a): fail() return if b.isSameNode: if not b.isSameNode(a): fail() return if a.length? or b.length?: if a.length is not b.length: fail() for i in range(a.length): assert_equal(a[i], b[i]) return if atype is 'object': for key in Object.keys(a): assert_equal(a[key], b[key]) if btype is 'object': for key in Object.keys(b): assert_equal(a[key], b[key]) if atype is not 'object' and btype is not 'object': fail() def assert_true(x, msg, call_site=None): if not x: raise_fail(f'{x} is not truthy', msg, call_site) def assert_false(x, msg, call_site=None): if x: raise_fail(f'{x} is truthy', msg, call_site) def reset_dom(): html = document.documentElement clear(html) head = document.createElement('head') body = document.createElement('body') html.appendChild(head) html.appendChild(body) registered_tests = {} def test(f): mod = f.__module__ or 'unknown_test_module' f.test_name = mod + '.' + f.name registered_tests[f.test_name] = f return f
2,469
Python
.py
83
22.879518
87
0.570342
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,470
lru_cache.pyj
kovidgoyal_calibre/src/pyj/lru_cache.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods def lru_node(key, val): return {'key': key, 'val':val, 'prev':None, 'next':None} class LRUCache: def __init__(self, size): self.limit = 200 self.clear(size) def set_head(self, node): node.next = self.head node.prev = None if self.head is not None: self.head.prev = node self.head = node if self.tail is None: self.tail = node self.size += 1 self.map[node.key] = node def pop(self, key): node = self.map[key] if not node: return if node.prev is not None: node.prev.next = node.next else: self.head = node.next if node.next is not None: node.next.prev = node.prev else: self.tail = node.prev v'delete self.map[key]' self.size -= 1 def set(self, key, val): node = lru_node(key, val) existing = self.map[key] if existing: existing.value = node.value self.pop(node.key) elif self.size > self.limit: v'delete self.map[self.tail.key]' self.size -= 1 self.tail = self.tail.prev self.tail.next = None self.set_head(node) def get(self, key, defval): existing = self.map[key] if not existing: return None if defval is undefined else defval val = existing.value node = lru_node(key, val) self.pop(key) self.set_head(node) return val def clear(self, size): self.size = 0 self.map = {} self.head = self.tail = None if jstype(size) is 'number': self.limit = size
1,880
Python
.py
60
22.3
72
0.549724
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,471
dom.pyj
kovidgoyal_calibre/src/pyj/dom.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals simple_vendor_prefixes = { 'animation': v"['webkit', 'moz', 'o']", 'animation-name': v"['webkit', 'moz', 'o']", 'animation-duration': v"['webkit', 'moz', 'o']", 'animation-timing-function': v"['webkit', 'moz', 'o']", 'animation-delay': v"['webkit', 'moz', 'o']", 'animation-iteration-count': v"['webkit', 'moz', 'o']", 'animation-direction': v"['webkit', 'moz', 'o']", 'animation-fill-mode': v"['webkit', 'moz', 'o']", 'animation-play-state': v"['webkit', 'moz', 'o']", 'hyphens': v"['webkit', 'moz', 'ms']", 'transform': v"['webkit', 'ms', 'moz', 'o']", 'transform-origin': v"['webkit', 'ms', 'moz', 'o']", 'transition': v"['webkit', 'moz', 'o']", 'filter': v"['webkit']", 'user-select': v"['webkit', 'moz', 'ms']", 'break-before': v"['webkit-column']", 'break-after': v"['webkit-column']", 'break-inside': v"['webkit-column']", 'column-gap': v"['webkit', 'moz']", 'column-width': v"['webkit', 'moz']", 'column-rule': v"['webkit', 'moz']", 'column-fill': v"['moz']", } def set_css(elem, **kw): if jstype(elem) is 'string': elem = document.querySelector(elem) s = elem.style if s: for prop in kw: name, val = str.replace(str.rstrip(prop, '_'), '_', '-'), kw[prop] if val is None or val is undefined: s.removeProperty(name) else: s.setProperty(name, val) prefixes = simple_vendor_prefixes[name] if prefixes: for prefix in prefixes: if val is None or val is undefined: s.removeProperty('-' + prefix + '-' + name) else: s.setProperty('-' + prefix + '-' + name, val) return elem def set_important_css(elem, **kw): if jstype(elem) is 'string': elem = document.querySelector(elem) s = elem.style if s: for prop in kw: name, val = str.replace(str.rstrip(prop, '_'), '_', '-'), kw[prop] if val is None or val is undefined: s.removeProperty(name) else: s.setProperty(name, val, 'important') prefixes = simple_vendor_prefixes[name] if prefixes: for prefix in prefixes: if val is None or val is undefined: s.removeProperty('-' + prefix + '-' + name) else: s.setProperty('-' + prefix + '-' + name, val, 'important') return elem def build_rule(selector, **kw): ans = v'[selector + " { "]' for prop in kw: name, val = str.replace(str.rstrip(prop, '_'), '_', '-'), kw[prop] ans.push(name + ':' + val + ';') prefixes = simple_vendor_prefixes[name] if prefixes: for prefix in prefixes: ans.push('-' + prefix + '-' + name + ':' + val + ';') ans.push('}') return ans.join('\n') + '\n' def clear(): for v'var i = 0; i < arguments.length; i++': node = arguments[i] while node.firstChild: node.removeChild(node.firstChild) def remove_all_attributes(): for v'var i = 0; i < arguments.length; i++': node = arguments[i] while node.attributes.length > 0: node.removeAttributeNode(node.attributes[0]) def create_keyframes(animation_name, *frames): ans = v'[]' for prefix in '-webkit-', '-moz-', '-o-', '': ans.push('@' + prefix + 'keyframes ' + animation_name + ' {') for frame in frames: ans.push(frame) ans.push('}') return ans.join('\n') + '\n' def change_icon_image(icon_element, new_name, tooltip): if new_name: icon_element.firstChild.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#icon-' + new_name) else: icon_element.firstChild.removeAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href') if tooltip?: x = icon_element.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'title') if not x.length: tt = document.createElementNS('http://www.w3.org/2000/svg', 'title') icon_element.appendChild(tt) x = v'[tt]' x[0].textContent = tooltip def svgicon(name, height, width, tooltip): ans = document.createElementNS('http://www.w3.org/2000/svg', 'svg') ans.setAttribute('style', 'fill: currentColor; height: {}; width: {}; vertical-align: text-top'.format(height ? '2ex', width ? '2ex')) u = document.createElementNS('http://www.w3.org/2000/svg', 'use') ans.appendChild(u) if name: ans.firstChild.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#icon-' + name) if tooltip: tt = document.createElementNS('http://www.w3.org/2000/svg', 'title') tt.textContent = tooltip ans.appendChild(tt) return ans def element(elem_id, child_selector): ans = document.getElementById(elem_id) if elem_id else document.body if child_selector: ans = ans.querySelector(child_selector) return ans def selector(id_selector, *args): ans = '#' + id_selector for x in args: ans += ' ' + x return ans def rule(id_selector, *args, **kw): return build_rule(selector(id_selector, *args), **kw) def unique_id(prefix): prefix = prefix or 'auto-id' unique_id.counts[prefix] = num = (unique_id.counts[prefix] or 0) + 1 return prefix + '-' + num unique_id.counts = {} def ensure_id(w, prefix): ans = w.getAttribute('id') if not ans: ans = unique_id(prefix) w.setAttribute('id', ans) return ans extra_css = v'[]' add_extra_css = extra_css.push.bind(extra_css) def get_widget_css(): ans = v'[]' for func in extra_css: ans.push(func()) return ans.join('\n') def set_radio_group_value(parent, name, val): changed = False for inp in parent.querySelectorAll(f'input[name={name}]'): inp.checked = inp.value is val changed = True if not changed: raise KeyError(f'No radio group with name={name} found')
6,245
Python
.py
155
32.567742
138
0.569545
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,472
widgets.pyj
kovidgoyal_calibre/src/pyj/widgets.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from dom import build_rule, clear, svgicon, create_keyframes, set_css, change_icon_image, add_extra_css, ensure_id from elementmaker import E from book_list.theme import get_color # Button {{{ def create_button(text, icon=None, action=None, tooltip=None, highlight=False, download_filename=None, class_=''): ic = '' if icon: ic = svgicon(icon) text = '\xa0' + text ans = E.a(ic, E.span(text), class_='calibre-push-button ' + class_, href='javascript: void(0)', role='button', title=tooltip or '') if download_filename and v'"download" in ans': ans.setAttribute('download', download_filename) if action is not None: if jstype(action) is 'string': ans.setAttribute('href', action) else: ans.addEventListener('click', def(event): event.preventDefault(), action(event);) if highlight: set_css(ans, font_size='larger', font_weight='bold') return ans create_button.style = build_rule('a.calibre-push-button', border_radius='1em', background_clip='padding-box', background_color=get_color('button-start'), background_image='linear-gradient(to bottom, {}, {})'.format(get_color('button-start'), get_color('button-end')), padding='0.5ex 1em', color=get_color('button-text'), cursor='pointer', font_size='inherit', display='inline-flex', align_items='center', user_select='none', box_shadow='0px 2px 1px rgba(50, 50, 50, 0.75)', white_space='nowrap' ) create_button.style += build_rule('a.calibre-push-button:hover', transform='scale(1.05)') create_button.style += build_rule('a.calibre-push-button:active', transform='scale(1.1)') # This is needed because of a bug in Firefox: https://bugs.launchpad.net/bugs/1881385 create_button.style += build_rule('a.calibre-push-button:visited', color=get_color('button-text')) # }}} # Spinner {{{ def create_spinner(height, width): ans = svgicon('cog', height, width) ans.classList.add('spin') return ans create_spinner.style = build_rule('.spin', animation='spin 2s infinite linear') create_spinner.style += create_keyframes('spin', 'from { transform: rotate(0deg); } to { transform: rotate(359deg);}') # }}} # Breadcrumbs {{{ class Breadcrumbs: STYLE_RULES = build_rule( '.calibre-breadcrumbs', user_select='none', white_space='nowrap', background_color=get_color('window-background2'), z_index='-1', border_radius='10px', margin='1ex 1em', margin_bottom='0' ) STYLE_RULES += build_rule( '.calibre-breadcrumbs > li', cursor='pointer', display='inline-block', line_height='26px', margin='0 9px 0 -10px', padding='0.5ex 1rem', position='relative' ) STYLE_RULES += build_rule('.calibre-breadcrumbs > li:hover', color=get_color('window-hover-foreground')) STYLE_RULES += build_rule('.calibre-breadcrumbs > li:active', color=get_color('window-hover-foreground'), transform='scale(1.5)') STYLE_RULES += build_rule( '.calibre-breadcrumbs > li:before, .calibre-breadcrumbs > li:after', border_right='2px solid currentColor', content='""', display='block', height='50%', position='absolute', left='0', top='0', right='0', transform='skewX(45deg)' ) STYLE_RULES += build_rule( '.calibre-breadcrumbs > li:after', bottom='0', top='auto', transform='skewX(-45deg)' ) STYLE_RULES += build_rule( '.calibre-breadcrumbs > li:last-of-type:before, .calibre-breadcrumbs > li:last-of-type:after', display='none') def __init__(self, container): self.container_id = ensure_id(container, 'calibre-breadcrumbs-') container.classList.add('calibre-breadcrumbs') clear(container) @property def container(self): return document.getElementById(self.container_id) def reset(self): clear(self.container) def add_crumb(self, callback): li = E.li() if callback: li.addEventListener('click', callback) self.container.appendChild(li) return li # }}} # Simple Tree {{{ def create_tree(root, populate_data, onclick): container = E.div(class_='simple-tree') set_css(container, overflow='auto') def toggle_node(li): if li.dataset.treeState is 'closed': li.dataset.treeState = 'open' li.lastChild.style.display = 'block' change_icon_image(li.firstChild.firstChild, 'caret-down') else: li.dataset.treeState = 'closed' li.lastChild.style.display = 'none' change_icon_image(li.firstChild.firstChild, 'caret-right') def bullet(icon): ans = svgicon(icon, '2ex', '2ex') ans.style.minWidth = '2ex' ans.style.minHeight = '2ex' return ans def process_node(node, parent_container, level): if node.children?.length: ul = E.div() parent_container.appendChild(ul) for child in node.children: icon = 'caret-right' if child.children?.length else None li = E.div(style='display:flex; flex-direction:column; margin: 1ex 1em; margin-left: {}em'.format(level+1), E.div(style='display:flex; align-items: center', bullet(icon), E.span('\xa0'), E.a( href='javascript: void(0)', class_='simple-link tree-item-title', onclick=def (event): if onclick: if event.button is 0: event.preventDefault(), event.stopPropagation() onclick(event, event.currentTarget.parentNode.parentNode) ), ), E.div(style='display:none', data_tree_subtree_container='1'), data_tree_state='closed', ) ul.appendChild(li) populate_data(child, li, li.firstChild.lastChild) if icon: set_css(li.firstChild.firstChild, cursor='pointer') li.firstChild.firstChild.addEventListener('click', def(event): toggle_node(event.currentTarget.parentNode.parentNode) ) process_node(child, li.lastChild, level + 1) if root: process_node(root, container, 0) return container def find_text_in_tree(container, q): q = q.lower() last_match = container.querySelector('a[data-tree-last-match]') if last_match: last_match.parentNode.style.backgroundColor = 'transparent' last_match.parentNode.style.borderRadius = '0' lm = last_match.getAttribute('data-tree-last-match') last_match.removeAttribute('data-tree-last-match') if lm is not q: last_match = None if not q: return before = [] seen = False ans = None for a in container.querySelectorAll('a.tree-item-title'): if a is last_match: seen = True else: if a.textContent.lower().indexOf(q) != -1: if seen: ans = a break if last_match is None: ans = a break before.push(a) if not ans and before.length: ans = before[0] ans = ans or last_match if ans: ans.dataset.treeLastMatch = q if ans: ans.parentNode.style.backgroundColor = get_color('tree-highlight-item') ans.parentNode.style.borderRadius = '5px' ans = ans.parentNode.parentNode return ans def scroll_tree_item_into_view(item): p = item.parentNode?.parentNode while p and p.getAttribute('data-tree-subtree-container'): p.style.display = 'block' p = p.parentNode?.parentNode?.parentNode item.scrollIntoView() # }}} add_extra_css(def(): ans = 'a, button:focus { outline: none }; a, button::-moz-focus-inner { border: 0 }\n' ans += '.simple-link { cursor: pointer } .simple-link:hover { color: HC } .simple-link:active { transform: scale(1.5) }\n'.replace('HC', get_color('window-hover-foreground')) ans += '.blue-link { cursor: pointer; color: COL } .blue-link:visited { color: COL} .blue-link:hover { color: HC } .blue-link:active { transform: scale(1.5) }\n'.replace('HC', get_color('window-hover-foreground')).replace(/COL/g, get_color('link-foreground')) ans += create_button.style + '\n' ans += create_button.style + '\n' ans += create_spinner.style + '\n' ans += Breadcrumbs.STYLE_RULES + '\n' # Chrome hardcodes the size of these to 13.3px. In safari on some devices # the font size is smaller than the body font size and small enough to # trigger page zooms. So set it to 1em so they scale with body font size. ans += ''' select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"] { font-size: 1em } ''' return ans ) def enable_escape_key(container, action): container.setAttribute('tabindex', '0') container.addEventListener('keydown', def(ev): if ev.key is 'Escape': ev.stopPropagation(), ev.preventDefault() action() , {'passive': False}) container.focus()
9,756
Python
.py
209
37.492823
263
0.613225
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,473
qt.pyj
kovidgoyal_calibre/src/pyj/qt.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals special_title = '__SPECIAL_TITLE__' slots = {} def ping(suffix): document.title = special_title + suffix def signal(): args = Array.from(arguments) to_python._queue_message({'type': 'signal', 'name': this, 'args': args}) class ToPython: def __init__(self): self._messages = v'[]' self._last_ping_value = 0 self._ping_timer_id = -1 self._queue_message({'type': 'qt-ready'}) def _ping(self): if self._ping_timer_id < 0: self._last_ping_value = 0 if self._last_ping_value else 1 self._ping_timer_id = setTimeout(def(): ping(self._last_ping_value) self._ping_timer_id = -1 , 0) def _queue_message(self, msg): self._messages.push(msg) self._ping() def _register_signals(self, signals): for signal_name in signals: self[signal_name] = signal.bind(signal_name) def _poll(self): ans = self._messages self._messages = v'[]' return ans def _from_python(self, name, args): callback = slots[name] if callback: callback.apply(None, args) else: console.warn(f'Attempt to call non-existent python-to-js slot named: {name}') to_python = None # TODO: Implement this via message passing from sub-frames if window is window.top: window.python_comm = to_python = ToPython() def from_python(func): slots[func.name] = func
1,628
Python
.py
44
29.727273
89
0.612883
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,474
test_date.pyj
kovidgoyal_calibre/src/pyj/test_date.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from date import format_date from testing import test, assert_equal def test_fd(date, fmt, ans): q = format_date(date, fmt, as_utc=True) assert_equal(ans, q) @test def date_formatting(): test_fd('1101-01-01T09:00:00+00:00', 'hh h', '09 9') test_fd('1101-01-01T12:15:00+00:00', 'h:m ap', '12:15 pm') test_fd('1101-01-01T00:15:00+00:00', 'h:m ap', '12:15 am') test_fd('1101-01-01T13:15:00+00:00', 'h:m ap', '1:15 pm') test_fd('1101-01-01T09:01:00+00:00', 'h:mm AP', '9:01 AM') test_fd('1101-01-01T09:05:01.012+00:00', 'hh h mm m ss s z zzz ap AP a A yy yyyy', '09 9 05 5 01 1 12 012 am AM am AM 01 1101') test_fd('2001-01-02T09:00:00+00:00', 'M MM MMM MMMM', '1 01 Jan January') test_fd('2001-01-01T12:00:00+00:00', 'd dd ddd dddd', '1 01 Mon Monday') # test_fd('2001-01-01T12:00:00+05:30', 'd t', '1 India Standard Time')
1,019
Python
.py
19
50.105263
131
0.645582
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,475
file_uploads.pyj
kovidgoyal_calibre/src/pyj/file_uploads.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from dom import ensure_id from utils import human_readable, safe_set_inner_html def upload_files_widget(container, proceed, msg, single_file=False, accept_extensions=None): container_id = ensure_id(container, 'upload-files') def files_selected(): files = this.files container = document.getElementById(container_id) container.removeChild(container.lastChild) if callable(proceed) and files.length: proceed(container_id, files) msg = msg or _('Upload books by either <a>selecting the book files</a> or drag and drop the files here') c = E.div(E.span(), E.input(type='file', style='display:none', onchange=files_selected)) if not single_file: c.lastChild.setAttribute('multiple', 'multiple') if accept_extensions: c.lastChild.setAttribute('accept', ', '.join(['.' + x for x in accept_extensions.split(' ')])) c.style.minHeight = '80vh' c.style.padding = '1rem' c.style.borderBottom = 'solid 1px currentColor' safe_set_inner_html(c.firstChild, msg) a = c.getElementsByTagName('a')[0] a.setAttribute('href', 'javascript: void(0)') a.classList.add('blue-link') a.addEventListener('click', def(): document.getElementById(container_id).querySelector('input[type=file]').click() , False) container.appendChild(c) def stop(e): e.stopPropagation(), e.preventDefault() def drop(e): stop(e) dt = e.dataTransfer files_selected.call(dt) c.addEventListener('dragenter', stop, False) c.addEventListener('dragover', stop, False) c.addEventListener('drop', drop, False) return c def update_status_widget(w, sent, total): if total: p = w.getElementsByTagName('progress')[0] p.setAttribute('value', '' + sent) p.setAttribute('max', '' + total) w.lastChild.textContent = _(' {percent:.0%} of {total}').format(percent=sent / total, total=human_readable(total)) def upload_status_widget(name, job_id): ans = E.div(style='padding: 1rem 1ex;', data_job='' + job_id) if name: ans.appendChild(E.h3(E.b(name))) ans.appendChild(E.progress()) ans.appendChild(E.span()) return ans
2,426
Python
.py
55
38.272727
122
0.679253
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,476
select.pyj
kovidgoyal_calibre/src/pyj/select.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals if document?.caretPositionFromPoint: caret_position_from_point = document.caretPositionFromPoint.bind(document) else: caret_position_from_point = def(x, y): r = document.caretRangeFromPoint(x, y) if r: return {'offsetNode': r.startContainer, 'offset': r.startOffset} return None def word_boundary_regex(): ans = word_boundary_regex.ans if ans is undefined: ans = word_boundary_regex.ans = /[\s!-#%-\x2A,-/:;\x3F@\x5B-\x5D_\x7B}\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/ return ans def expand_offset_to_word(string, offset): start = offset pat = word_boundary_regex() while start >= 1 and not pat.test(string.charAt(start - 1)): start -= 1 end, sz = offset, string.length while end < sz and not pat.test(string.charAt(end)): end += 1 return {'word': string[start:end], 'start': start, 'end': end} def word_at_point(x, y): p = caret_position_from_point(x, y) if p and p.offsetNode?.nodeType is Node.TEXT_NODE: word_info = expand_offset_to_word(p.offsetNode.data, p.offset) if word_info.word: r = document.createRange() r.setStart(p.offsetNode, word_info.start) r.setEnd(p.offsetNode, word_info.end) return r def first_visible_word(): width = window.innerWidth height = window.innerHeight xdelta = width // 10 ydelta = height // 10 for y in range(0, height, ydelta): for x in range(0, width, xdelta): r = word_at_point(x, y) if r?: return r def empty_range_extents(): return { 'start': {'x': 0, 'y': 0, 'height': 0, 'width': 0, 'onscreen': False, 'selected_prev': False}, 'end': {'x': 0, 'y': 0, 'height': 0, 'width': 0, 'onscreen': False, 'selected_prev': False} } # Returns a node that we know will produce a reasonable bounding box closest to the start or end # of the DOM tree from the specified node. # Currently: safe_nodes and text nodes. # This a depth first traversal, with the modification that if a node is reached that meets the criteria, # the traversal stops, because higher nodes in the DOM tree always have larger bounds than their children. safe_nodes = {'img': True, 'br': True, 'hr': True} def get_selection_node_at_boundary(node, start): stack = v'[]' stack.push({'node': node, 'visited': False}) while stack.length > 0: top = stack[-1] # If the top node is a target type, we know that no nodes below it can be more to the start or end # than it, so return it immediately. name = top.node.nodeName.toLowerCase() if top.node.nodeName else '' if top.node.nodeType is Node.TEXT_NODE or safe_nodes[name]: return top.node # Otherwise, depth-first traversal. else if top.visited: stack.pop() else: top.visited = True if top.node.childNodes: for c in top.node.childNodes if start else reversed(top.node.childNodes): stack.push({'node': c, 'visited': False}) def range_extents(q, in_flow_mode): ans = empty_range_extents() if not q: return ans start = q.cloneRange() end = q.cloneRange() def rect_onscreen(r): # we use -1 rather than zero for the top limit because on some # platforms the browser engine returns that for top line selections. # See https://bugs.launchpad.net/calibre/+bug/2024375/ for a test case. if r.right <= window.innerWidth and r.bottom <= window.innerHeight and r.left >= 0 and r.top >= -1: return True return False def apply_rect_to_ans(rect, ans): ans.x = Math.round(rect.left) ans.y = Math.round(rect.top) ans.height = Math.round(rect.height) ans.width = Math.round(rect.width) ans.onscreen = rect_onscreen(rect) return ans def for_boundary(r, ans, is_start): rect = r.getBoundingClientRect() if rect.height is 0 and rect.width is 0: # this tends to happen when moving the mouse downwards # at the boundary between paragraphs if r.startContainer?.nodeType is Node.ELEMENT_NODE: node = r.startContainer if r.startOffset and node.childNodes.length > r.startOffset: node = node.childNodes[r.startOffset] boundary_node = get_selection_node_at_boundary(node, is_start) # If we found a node that will produce a reasonable bounding box at a boundary, use it: if boundary_node: if boundary_node.nodeType is Node.TEXT_NODE: if is_start: r.setStart(boundary_node, boundary_node.length - 1) r.setEnd(boundary_node, boundary_node.length) else: r.setStart(boundary_node, 0) r.setEnd(boundary_node, 1) rect = r.getBoundingClientRect() else: rect = boundary_node.getBoundingClientRect() if not is_start: ans.selected_prev = True # we cant use getBoundingClientRect as the node might be split # among multiple columns else if node.getClientRects: rects = node.getClientRects() if rects.length: erect = rects[0] rect = {'left': erect.left, 'top': erect.top, 'right': erect.left + 2, 'bottom': erect.top + 2, 'width': 2, 'height': 2} apply_rect_to_ans(rect, ans) if q.startContainer.nodeType is Node.ELEMENT_NODE: start.collapse(True) for_boundary(start, ans.start, True) elif q.startOffset is 0 and q.startContainer.length is 0: start.collapse(True) for_boundary(start, ans.start, True) elif q.startOffset is q.startContainer.length: start.setStart(q.startContainer, q.startOffset - 1) start.setEnd(q.startContainer, q.startOffset) rect = start.getBoundingClientRect() apply_rect_to_ans(rect, ans.start).selected_prev = True else: start.setStart(q.startContainer, q.startOffset) start.setEnd(q.startContainer, q.startOffset + 1) rect = start.getBoundingClientRect() apply_rect_to_ans(rect, ans.start) if q.endContainer.nodeType is Node.ELEMENT_NODE: end.collapse(False) for_boundary(end, ans.end, False) elif q.endOffset is 0 and q.endContainer.length is 0: end.collapse(False) for_boundary(end, ans.end, False) elif q.endOffset is q.endContainer.length: end.setStart(q.endContainer, q.endOffset - 1) end.setEnd(q.endContainer, q.endOffset) rect = end.getBoundingClientRect() apply_rect_to_ans(rect, ans.end).selected_prev = True else: end.setStart(q.endContainer, q.endOffset) end.setEnd(q.endContainer, q.endOffset + 1) rect = end.getBoundingClientRect() apply_rect_to_ans(rect, ans.end) if ans.end.height is 2 and ans.start.height > 2: ans.end.height = ans.start.height if ans.start.height is 2 and ans.end.height > 2: ans.start.height = ans.end.height return ans def selection_extents(in_flow_mode): sel = window.getSelection() if not sel or not sel.rangeCount or sel.isCollapsed: return empty_range_extents() return range_extents(sel.getRangeAt(0), in_flow_mode) def is_start_closer_to_point(pos): sel = window.getSelection() if not sel.rangeCount: return p = caret_position_from_point(pos.x, pos.y) if p: r = sel.getRangeAt(0) sr = document.createRange() sr.setStart(r.startContainer, r.startOffset) sr.setEnd(p.offsetNode, p.offset) er = document.createRange() er.setStart(p.offsetNode, p.offset) er.setEnd(r.endContainer, r.endOffset) return sr.toString().length < er.toString().length return False def move_end_of_selection(pos, start): sel = window.getSelection() if not sel.rangeCount: return p = caret_position_from_point(pos.x, pos.y) if not p: return r = sel.getRangeAt(0) if start is None: q = document.createRange() q.setStart(p.offsetNode, p.offset) q.setEnd(p.offsetNode, p.offset) if r.compareBoundaryPoints(window.Range.START_TO_START, q) >= 0: start = True elif r.compareBoundaryPoints(window.Range.END_TO_END, q) <= 0: start = False else: # point is inside the selection start = False new_range = document.createRange() if start: new_range.setStart(p.offsetNode, p.offset) new_range.setEnd(r.endContainer, r.endOffset) other_boundary_changed = r.endContainer is not new_range.endContainer or r.endOffset is not new_range.endOffset else: new_range.setStart(r.startContainer, r.startOffset) new_range.setEnd(p.offsetNode, p.offset) other_boundary_changed = r.startContainer is not new_range.startContainer or r.startOffset is not new_range.startOffset if new_range.collapsed and other_boundary_changed: # we ignore the case when the new range is collapsed and the other end # of the selection is also moved as this is a chromium bug. See https://bugs.launchpad.net/bugs/2054934 return sel.removeAllRanges() sel.addRange(new_range)
10,984
Python
.py
216
41.587963
1,298
0.647639
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,477
test_annotations.pyj
kovidgoyal_calibre/src/pyj/test_annotations.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from read_book.annotations import merge_annot_lists from testing import assert_equal, test, assert_true def bm(title, bmid, year=20, first_cfi_number=1): return { 'title': title, 'id': bmid, 'timestamp': f'20{year}-06-29T03:21:48.895323+00:00', 'pos_type': 'epubcfi', 'pos': str.format('epubcfi(/{}/4/8)', first_cfi_number) } def hl(uuid, hlid, year=20, first_cfi_number=1): return { 'uuid': uuid, 'id': hlid, 'timestamp': f'20{year}-06-29T03:21:48.895323+00:00', 'start_cfi': '/4/8', 'spine_index': first_cfi_number } @test def merging_annotations(): for atype in 'bookmark highlight'.split(' '): f = bm if atype == 'bookmark' else hl a = [f('one', 1, 20, 2), f('two', 2, 20, 4), f('a', 3, 20, 16),] b = [f('one', 10, 30, 2), f('two', 20, 10, 4), f('b', 30, 20, 8),] changed, c = merge_annot_lists(a, b, atype) assert_true(changed) def get_id(x): return x.id assert_equal(list(map(get_id, c)), [10, 2, 30, 3])
1,190
Python
.py
26
39.807692
89
0.600866
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,478
utils.pyj
kovidgoyal_calibre/src/pyj/utils.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from ajax import encode_query from encodings import hexlify from book_list.theme import get_font_family is_ios = v'!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)' ios_major_version = 0 if !is_ios and v'!!navigator.platform' and window? and window.navigator.platform is 'MacIntel' and window.navigator.maxTouchPoints > 1: # iPad Safari in desktop mode https://stackoverflow.com/questions/57765958/how-to-detect-ipad-and-ipad-os-version-in-ios-13-and-up is_ios = True if is_ios: v = v'navigator.appVersion.match(/OS (\d+)/)' if v and v[1]: ios_major_version = parseInt(v[1], 10) or 0 def default_context_menu_should_be_allowed(evt): if evt.target and evt.target.tagName and evt.target.tagName.toLowerCase() in ('input', 'textarea'): return True return False def debounce(func, wait, immediate=False): # Returns a function, that, as long as it continues to be invoked, will not # be triggered. The function will be called after it stops being called for # wait milliseconds. If `immediate` is True, trigger the function on the # leading edge, instead of the trailing. timeout = None return def debounce_inner(): # noqa: unused-local nonlocal timeout context, args = this, arguments def later(): nonlocal timeout timeout = None if not immediate: func.apply(context, args) call_now = immediate and not timeout window.clearTimeout(timeout) timeout = window.setTimeout(later, wait) if call_now: func.apply(context, args) if Object.assign: copy_hash = def (obj): return Object.assign({}, obj) else: copy_hash = def (obj): return {k:obj[k] for k in Object.keys(obj)} def parse_url_params(url=None, allow_multiple=False): cache = parse_url_params.cache url = url or window.location.href if cache[url]: return copy_hash(parse_url_params.cache[url]) qs = url.indexOf('#') ans = {} if qs < 0: cache[url] = ans return copy_hash(ans) q = url.slice(qs + 1, (url.length + 1)) if not q: cache[url] = ans return copy_hash(ans) pairs = q.replace(/\+/g, " ").split("&") for pair in pairs: key, val = pair.partition('=')[::2] key, val = decodeURIComponent(key), decodeURIComponent(val) if allow_multiple: if ans[key] is undefined: ans[key] = v'[]' ans[key].append(val) else: ans[key] = val cache[url] = ans return copy_hash(ans) parse_url_params.cache = {} def encode_query_with_path(query, path): path = path or window.location.pathname return path + encode_query(query, '#') def full_screen_supported(elem): elem = elem or document.documentElement if elem.requestFullScreen or elem.webkitRequestFullScreen or elem.mozRequestFullScreen: return True return False def request_full_screen(elem): elem = elem or document.documentElement options = {'navigationUI': 'hide'} if elem.requestFullScreen: elem.requestFullScreen(options) elif elem.webkitRequestFullScreen: elem.webkitRequestFullScreen() elif elem.mozRequestFullScreen: elem.mozRequestFullScreen() def full_screen_element(): return document.fullscreenElement or document.webkitFullscreenElement or document.mozFullScreenElement or document.msFullscreenElement _roman = list(zip( [1000,900,500,400,100,90,50,40,10,9,5,4,1], ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] )) def roman(num): if num <= 0 or num >= 4000 or int(num) is not num: return num + '' result = [] for d, r in _roman: while num >= d: result.append(r) num -= d return result.join('') def fmt_sidx(val, fmt='{:.2f}', use_roman=True): if val is undefined or val is None or val is '': return '1' if int(val) is float(val): if use_roman: return roman(val) return int(val) + '' return fmt.format(float(val)) def rating_to_stars(value, allow_half_stars=False, star='★', half='⯨'): r = max(0, min(int(value or 0), 10)) if allow_half_stars: ans = star.repeat(r // 2) if r % 2: ans += half else: ans = star.repeat(int(r/2.0)) return ans def human_readable(size, sep=' '): if size <= 0: return f'0{sep}B' i = Math.floor(Math.log(size) / Math.log(1024)) size = (size / Math.pow(1024, i)).toFixed(1) if size.endswith('.0'): size = size[:-2] suffix = v"['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']"[i] return size + sep + suffix def document_height(): html = document.documentElement return max(document.body.scrollHeight, document.body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) def document_width(): html = document.documentElement return max(document.body.scrollWidth, document.body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth) _data_ns = None def data_ns(name): nonlocal _data_ns if _data_ns is None: rand = Uint8Array(12) window.crypto.getRandomValues(rand) _data_ns = 'data-' + hexlify(rand) + '-' return _data_ns + name def get_elem_data(elem, name, defval): ans = elem.getAttribute(data_ns(name)) if ans is None: return defval ? None return JSON.parse(ans) def set_elem_data(elem, name, val): elem.setAttribute(data_ns(name), JSON.stringify(val)) def username_key(username): return ('u' if username else 'n') + username def html_escape(text): repl = { '&': "&amp;", '"': "&quot;", '<': "&lt;", '>': "&gt;" } return String.prototype.replace.call(text, /[&"<>]/g, def (c): return repl[c];) def uniq(vals): # Remove all duplicates from vals, while preserving order ans = v'[]' seen = {} for x in vals: if not seen[x]: seen[x] = True ans.push(x) return ans def conditional_timeout(elem_id, timeout, func): def ct_impl(): elem = document.getElementById(elem_id) if elem: func.call(elem) window.setTimeout(ct_impl, timeout) def simple_markup(html): html = (html or '').replace(/\uffff/g, '').replace( /<\s*(\/?[a-zA-Z1-6]+)[^>]*>/g, def (match, tag): tag = tag.toLowerCase() is_closing = '/' if tag[0] is '/' else '' if is_closing: tag = tag[1:] if simple_markup.allowed_tags.indexOf(tag) < 0: tag = 'span' return f'\uffff{is_closing}{tag}\uffff' ) div = document.createElement('b') div.textContent = html html = div.innerHTML return html.replace(/\uffff(\/?[a-z1-6]+)\uffff/g, '<$1>') simple_markup.allowed_tags = v"'a|b|i|br|hr|h1|h2|h3|h4|h5|h6|div|em|strong|span'.split('|')" def safe_set_inner_html(elem, html): elem.innerHTML = simple_markup(html) return elem def sandboxed_html(html, style, sandbox): ans = document.createElement('iframe') ans.setAttribute('sandbox', sandbox or '') ans.setAttribute('seamless', '') ans.style.width = '100%' html = html or '' css = 'html, body { margin: 0; padding: 0; font-family: __FONT__ } p:first-child { margin-top: 0; padding-top: 0; -webkit-margin-before: 0 }'.replace('__FONT__', get_font_family()) css += style or '' final_html = f'<!DOCTYPE html><html><head><style>{css}</style></head><body>{html}</body></html>' ans.srcdoc = final_html return ans
7,753
Python
.py
200
32.535
184
0.633409
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,479
iframe_comm.pyj
kovidgoyal_calibre/src/pyj/iframe_comm.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from aes import GCM from elementmaker import E import traceback from book_list.globals import get_translations, main_js from book_list.theme import get_font_family from dom import ensure_id from gettext import install LOADING_DOC = ''' <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script type="text/javascript" id="bootstrap"> window.iframe_entry_point = '__ENTRY_POINT__'; // different in different iframes window.default_font_family = '__FONT__'; // from the theme __SCRIPT__ end_script </head> <body> <div style="font-size:larger; font-weight: bold; margin-top:48vh; text-align:center"> __BS__ </div> </body> </html> '''.replace('end_script', '<' + '/script>') # cannot have a closing script tag as this is embedded inside a script tag in index.html class Messenger: def __init__(self): self.secret = Uint8Array(64) def reset(self): window.crypto.getRandomValues(self.secret) self.gcm_to_iframe = GCM(self.secret.subarray(0, 32)) self.gcm_from_iframe = GCM(self.secret.subarray(32)) def encrypt(self, data): return self.gcm_to_iframe.encrypt(JSON.stringify(data)) def decrypt(self, data): return JSON.parse(self.gcm_from_iframe.decrypt(data)) class IframeWrapper: def __init__(self, handlers, iframe, entry_point, bootstrap_text): self.messenger = Messenger() self.iframe_id = ensure_id(iframe, 'content-iframe') self.reload_count = 0 if ':' in entry_point: self.needs_init = iframe.src is not entry_point self.srcdoc_created = True self.constructor_url = entry_point self.entry_point = None else: self.needs_init = True self.srcdoc_created = False self.constructor_url = None self.entry_point = entry_point self.ready = False self.encrypted_communications = False self.bootstrap_text = bootstrap_text or '' self.handlers = {k: handlers[k] for k in handlers} self.on_ready_handler = self.handlers.ready self.handlers.ready = self.on_iframe_ready window.addEventListener('message', self.handle_message, False) def destroy(self): window.removeEventListener('message', self.handle_message, False) @property def iframe(self): return document.getElementById(self.iframe_id) def create_srcdoc(self): r = /__([A-Z][A-Z_0-9]*[A-Z0-9])__/g if self.entry_point: data = { 'BS': self.bootstrap_text, 'SCRIPT': main_js(), 'FONT': get_font_family(), 'ENTRY_POINT': self.entry_point, } self.iframe.srcdoc = LOADING_DOC.replace(r, def(match, field): return data[field];) else: self.iframe.src = self.constructor_url self.srcdoc_created = True def init(self): if not self.needs_init: return self.needs_init = False iframe = self.iframe if self.srcdoc_created: if self.entry_point: sdoc = iframe.srcdoc iframe.srcdoc = '<p>&nbsp;</p>' iframe.srcdoc = sdoc else: self.reload_count += 1 ch = '&' if '?' in self.constructor_url else '?' iframe.src = self.constructor_url + f'{ch}rc={self.reload_count}' else: self.create_srcdoc() def reset(self): self.ready = False self.needs_init = True self.encrypted_communications = False def _send_message(self, action, encrypted, data): if not self.ready: return data.action = action msg = {'data':data, 'encrypted': encrypted} if encrypted: msg.data = self.messenger.encrypt(data) self.iframe.contentWindow.postMessage(msg, '*') def send_message(self, action, **data): self._send_message(action, self.encrypted_communications, data) def send_unencrypted_message(self, action, **data): self._send_message(action, False, data) def handle_message(self, event): if event.source is not self.iframe?.contentWindow: return data = event.data if self.encrypted_communications: if data.tag is undefined: print('Ignoring unencrypted message from iframe:', data) return try: data = self.messenger.decrypt(data) except Exception as e: print('Could not decrypt message from iframe:') console.log(e) traceback.print_exc() return if not data.action: return func = self.handlers[data.action] if func: func(data) else: print('Unknown action in message from iframe to parent:', data.action) def on_iframe_ready(self, data): self.messenger.reset() msg = {'secret': self.messenger.secret, 'translations': get_translations()} self.ready = True callback = None if self.on_ready_handler: callback = self.on_ready_handler(msg) self._send_message('initialize', False, msg) self.encrypted_communications = True if callback: callback() def create_wrapped_iframe(handlers, bootstrap_text, entry_point, kw): if ':' in entry_point: # this is a document loaded via the fake protocol from web_view.py kw.src = entry_point kw.sandbox = (kw.sandbox or '') + ' allow-same-origin' iframe = E.iframe(**kw) ans = IframeWrapper(handlers, iframe, entry_point, bootstrap_text) return iframe, ans instance_numbers = {} class IframeClient: def __init__(self, handlers, name): self.encrypted_communications = False self.name = name if not instance_numbers[self.name]: instance_numbers[self.name] = 0 instance_numbers[self.name] += 1 self.instance_num = instance_numbers[self.name] self.handlers = {k: handlers[k] for k in handlers} self.initialize_handler = handlers.initialize self.handlers.initialize = self.initialize self.ready_sent = False window.addEventListener('message', self.handle_message, False) window.addEventListener('load', self.send_ready, {'once': True}) def send_ready(self): if not self.ready_sent: self.send_message('ready', {}) self.ready_sent = True def initialize(self, data): nonlocal print self.gcm_from_parent, self.gcm_to_parent = GCM(data.secret.subarray(0, 32)), GCM(data.secret.subarray(32)) self.encrypted_communications = True if data.translations: install(data.translations) print = self.print_to_parent if self.initialize_handler: self.initialize_handler(data) def print_to_parent(self, *args): self.send_message('print', string=' '.join(map(str, args))) def handle_message(self, event): if event.source is not window.parent: return msg = event.data data = msg.data if msg.encrypted: if not self.gcm_from_parent: print(f'the iframe {self.name}-{self.instance_num} got an encrypted message from its parent without being initialized') return # We cannot use self.encrypted_communications as the 'display' # message has to be unencrypted as it transports Blob objects try: data = JSON.parse(self.gcm_from_parent.decrypt(data)) except Exception as e: print('Could not process message from parent:') console.log(e) return if not data or not data.action: console.log('Got a null message from parent in iframe, ignoring') return func = self.handlers[data.action] if func: try: func(data) except Exception as e: console.log('Error in iframe message handler {}:'.format(data?.action)) console.log(e) details = traceback.format_exc() console.log(details) self.send_message('error', title='Error in message handler', details=details, msg=e.toString()) else: print('Unknown action in message to iframe from parent: ' + data.action) def send_message(self, action, data): data.action = action data.iframe_id = f'{self.name}-{self.instance_num}' if self.encrypted_communications: data = self.gcm_to_parent.encrypt(JSON.stringify(data)) window.parent.postMessage(data, '*')
9,084
Python
.py
221
31.809955
135
0.615855
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,480
prefs.pyj
kovidgoyal_calibre/src/pyj/book_list/prefs.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from dom import clear, ensure_id from elementmaker import E from widgets import create_button from gettext import gettext as _ from book_list.globals import get_session_data from book_list.top_bar import create_top_bar from book_list.router import back # from book_list.theme import get_font_size, get_color pp_counter = 0 widget_counter = 0 class ConfigItem: def __init__(self, item_data): nonlocal widget_counter widget_counter += 1 self.widget_id = 'pref-widget-' + widget_counter self.item_data = item_data self.ignore_ui_value_changed = False def initialize(self): self.ignore_ui_value_changed = True try: self.to_ui(self.from_storage()) finally: self.ignore_ui_value_changed = False return self @property def container(self): return document.getElementById(self.widget_id) @property def control(self): return self.container.lastChild def from_storage(self): val = get_session_data().get(self.item_data.name) if self.item_data.from_storage: val = self.item_data.from_storage(val) return val def to_storage(self, val): if self.item_data.to_storage: val = self.item_data.to_storage(val) get_session_data().set(self.item_data.name, val) def defval(self): val = get_session_data().defval(self.item_data.name) if self.item_data.from_storage: val = self.item_data.from_storage(val) return val def ui_value_changed(self): if self.ignore_ui_value_changed: return self.to_storage(self.from_ui()) def reset_to_default(self): self.to_ui(self.defval()) self.ui_value_changed() def to_ui(self, val): pass def from_ui(self): pass class Choices(ConfigItem): def __init__(self, item_data, container, onfocus): ConfigItem.__init__(self, item_data) div = E.div( id=self.widget_id, E.span(item_data.text + ': ', style='white-space:pre'), E.select(required='1') ) container.appendChild(div) select = div.lastChild for choice, text in item_data.choices: select.appendChild(E.option(text, value=choice)) select.addEventListener('change', self.ui_value_changed.bind(self)) select.addEventListener('focus', onfocus) div.addEventListener('click', onfocus) def to_ui(self, val): self.control.value = val def from_ui(self): return self.control.value class CheckBox(ConfigItem): def __init__(self, item_data, container, onfocus): ConfigItem.__init__(self, item_data) div = E.div( id=self.widget_id, E.input(type='checkbox'), E.span(' ' + item_data.text, style='white-space:pre') ) container.appendChild(div) control = div.firstChild control.addEventListener('change', self.ui_value_changed.bind(self)) control.addEventListener('focus', onfocus) div.addEventListener('click', onfocus) div.lastChild.addEventListener('click', self.toggle.bind(self)) @property def control(self): return self.container.firstChild def to_ui(self, val): self.control.checked = bool(val) def from_ui(self): return bool(self.control.checked) def toggle(self): self.to_ui(not self.from_ui()) self.ui_value_changed() class SpinBox(ConfigItem): def __init__(self, item_data, container, onfocus): ConfigItem.__init__(self, item_data) div = E.div( id=self.widget_id, E.span(item_data.text + ': ', style='white-space:pre'), E.input(type='number', step='any', min='1', max='100') ) container.appendChild(div) control = div.lastChild for attr in 'min max step'.split(' '): val = item_data[attr] if val is not undefined and val is not None: control.setAttribute(attr, '' + val) control.addEventListener('change', self.ui_value_changed.bind(self)) control.addEventListener('focus', onfocus) div.addEventListener('click', onfocus) def to_ui(self, val): self.control.value = val def from_ui(self): return self.control.value class LineEdit(ConfigItem): def __init__(self, item_data, container, onfocus): ConfigItem.__init__(self, item_data) div = E.div( id=self.widget_id, E.span(item_data.text + ': ', style='white-space:pre'), E.input(type='text') ) container.appendChild(div) control = div.lastChild control.addEventListener('change', self.ui_value_changed.bind(self)) control.addEventListener('focus', onfocus) div.addEventListener('click', onfocus) def to_ui(self, val): self.control.value = val or '' def from_ui(self): return self.control.value or '' state = {} def onfocus(name): return def(ev): c = document.getElementById(state.container_id) div = c.querySelector('div[data-name="{}"]'.format(name)) div.lastChild.style.display = 'block' def create_prefs_widget(container, prefs_data): nonlocal state state = {} state.container_id = ensure_id(container) state.widgets = [] clear(container) for item in prefs_data: div = E.div( style='margin-bottom:1ex; padding: 1ex 1em; border-bottom: solid 1px currentColor', title=item.tooltip, data_name=item.name, E.div(), E.div( item.tooltip or '', style='font-size:0.8rem; font-style: italic; margin-top:1ex; display:none' ) ) container.appendChild(div) val = get_session_data().get(item.name) if item.from_storage: val = item.from_storage(val) if item.choices: cls = Choices elif val is True or val is False: cls = CheckBox elif jstype(val) is 'number': cls = SpinBox else: cls = LineEdit state.widgets.push((new cls(item, div.firstChild, onfocus(item.name))).initialize()) if state.widgets.length: container.appendChild( E.div( style='margin:1rem;', create_button(_('Restore default settings'), 'refresh', reset_to_defaults) ) ) def reset_to_defaults(): for w in state.widgets: w.reset_to_default() def prefs_panel_handler(title_func, get_prefs_data, on_close=None, icon='close'): def onkeydown(container_id, close_action, ev): if ev.key is 'Escape': ev.preventDefault(), ev.stopPropagation() close_action() def close_action(): if on_close is not None: on_close() back() def init_prefs_panel(container_id): container = document.getElementById(container_id) container.addEventListener('keydown', onkeydown.bind(None, container_id, close_action), {'passive': False, 'capture': True}) container.setAttribute('tabindex', '0') create_top_bar(container, title=title_func(), action=close_action, icon=icon) container.appendChild(E.div()) create_prefs_widget(container.lastChild, get_prefs_data()) container.focus() return init_prefs_panel
7,670
Python
.py
203
29.339901
132
0.619272
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,481
search.pyj
kovidgoyal_calibre/src/pyj/book_list/search.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from ajax import ajax, absolute_path from complete import create_search_bar from dom import clear, set_css, build_rule, svgicon, add_extra_css, ensure_id from elementmaker import E from gettext import gettext as _ from widgets import create_button, create_spinner, Breadcrumbs from modals import show_modal, create_custom_dialog from utils import rating_to_stars, safe_set_inner_html, is_ios from session import get_interface_data from book_list.library_data import library_data, current_library_id, current_virtual_library from book_list.ui import show_panel from book_list.router import back, show_note from book_list.top_bar import create_top_bar, add_button from book_list.globals import get_session_data from book_list.theme import get_color, get_font_size from book_list.prefs import prefs_panel_handler apply_search = None def set_apply_search(func): nonlocal apply_search apply_search = func sp_counter = 0 CLASS_NAME = 'book-search-panel' add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = build_rule(sel + ' div.tag-name > span', word_break='break-all', hyphens='auto', padding_left='1ex') style += build_rule(sel + ' div.tag-name:hover', color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background')) style += build_rule(sel + ' div.tag-menu:hover', color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background')) style += build_rule(sel + ' div.tag-name:active', transform='scale(1.5)') style += build_rule(sel + ' div.tag-menu:active', transform='scale(2)') # search items list style += build_rule(sel + ' ul.search-items', margin_top='1ex', list_style_type='none', text_align='left') style += build_rule(sel + ' ul.search-items > li', display='inline-block', cursor='pointer', background_color=get_color('window-background2'), border_radius='10px', padding='0.5ex', margin_right='1em') style += build_rule(sel + ' ul.search-items > li:hover', color=get_color('window-hover-foreground')) style += build_rule(sel + ' ul.search-items > li:active', transform='scale(1.5)') # Actions popup style += build_rule('#modal-container ul.tb-action-list > li:hover', color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background')) style += build_rule('#modal-container ul.tb-action-list > li:active', color=get_color('window-hover-foreground'), color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background')) return style ) state = {} last_accepted_search = None def component(container, name): return container.querySelector(f'[data-component="{name}"]') def icon_for_node(node): interface_data = get_interface_data() ans = interface_data.icon_map[node.data.category] or 'column.png' return absolute_path(interface_data.icon_path + '/' + ans) def node_for_path(path): path = path or state.tag_path ans = state.tag_browser_data for child_index in path: ans = ans.children[child_index] return ans def execute_search(text): nonlocal last_accepted_search if state.tag_path and state.tag_path.length: last_accepted_search = {'library_id': current_library_id(), 'vl': current_virtual_library(), 'tag_path': list(state.tag_path)} apply_search(text) def ask_about_smart_quotes(text): create_custom_dialog(_('Search contains smart quotes'), def(parent, close_modal): def action(replace): nonlocal text close_modal() if replace: text = text.replace(/[“”«»„]/g, '"') execute_search(text) parent.appendChild(E.div( E.div(_('The search expression {} contains smart quotes. By default, Apple inserts smart quotes instead of normal quotes when tapping the quote button. This will prevent the search from working, if you intended to use normal quotes. You can type normal quotes by long-tapping the quotes button. Do you want to keep the smart quotes or replace them with normal quotes?').format(text)), E.div(class_='button-box', create_button(_('Replace'), None, action.bind(None, True), highlight=True), '\xa0', create_button(_('Keep'), None, action.bind(None, False)), ) )) ) def execute_search_interactive(text): if not text: container = document.getElementById(state.container_id) search_control = container.querySelector('input[name="search-books"]') text = search_control.value or '' if is_ios and /[“”«»„]/.test(text): ask_about_smart_quotes(text) else: execute_search(text) def search_expression_for_item(node, node_state): item = node.data if item.is_searchable is False or not node_state or node_state is 'clear': return '' search_state = {'plus':'true', 'plusplus':'.true', 'minus':'false', 'minusminus':'.false'}[node_state] stars = rating_to_stars(3, True) if item.is_category: category = item.category if item.is_first_letter: letters_seen = {} for child in node.children: if child.data.sort: letters_seen[child.data.sort[0]] = True letters_seen = Object.keys(letters_seen) if letters_seen.length: charclass = letters_seen.join('') if category is 'authors': expr = r'author_sort:"~(^[{0}])|(&\s*[{0}])"'.format(charclass) elif category is 'series': expr = r'series_sort:"~^[{0}]"'.format(charclass) else: expr = r'{0}:"~^[{1}]"'.format(category, charclass) else: expr = '{}:false'.format(category) elif category is 'news': expr = 'tags:"={}"'.format(item.name) else: return '{}:{}'.format(category, search_state) if 'false' in search_state: expr = '(not ' + expr + ')' return expr category = 'tags' if item.category is 'news' else item.category if item.name and item.name[0] in stars: # Assume ratings rnum = item.name.length if item.name.endswith(stars[-1]): rnum = '{}.5'.format(rnum - 1) expr = '{}:{}'.format(category, rnum) else: fm = library_data.field_metadata[item.category] suffix = ':' if fm and fm.is_csp else '' name = item.original_name or item.name or item.sort if not name: return '' name = str.replace(name, '"', r'\"') if name[0] is '.': name = '.' + name if search_state is '.true' or search_state is '.false': name = '.' + name expr = '{}:"={}{}"'.format(category, name, suffix) if 'false' in search_state: expr = '(not ' + expr + ')' return expr def node_clicked(i): node = node_for_path().children[i] if node.children and node.children.length: state.tag_path.append(i) render_tag_browser() else: expr = search_expression_for_item(node, 'plus') execute_search(expr) def add_to_search(node, search_type): anded = get_session_data().get('and_search_terms') state.active_nodes[node.id] = [search_type, anded] render_search_expression() def remove_expression(node_id): v'delete state.active_nodes[node_id]' render_search_expression() def render_search_expression(): parts = v'[]' container = document.getElementById(state.container_id) sic = component(container, 'search_expression') clear(sic) for node_id in Object.keys(state.active_nodes): search_type, anded = state.active_nodes[node_id] node = state.node_id_map[node_id] expr = search_expression_for_item(node, search_type) name = node.data.original_name or node.data.name or node.data.sort or '' if expr: c = E.li(svgicon('remove'), '\xa0' + name) sic.appendChild(c) c.addEventListener('click', remove_expression.bind(None, node_id)) if parts.length: expr = ('and' if anded else 'or') + ' ' + expr parts.push(expr) search_control = container.querySelector('input[name="search-books"]') search_control.value = parts.join(' ') def menu_clicked(i): def create_details(container, hide_modal): node = node_for_path().children[i] data = node.data name = data.original_name or data.name or data.sort title = E.h2( style='display:flex; align-items: center; border-bottom: solid 1px currentColor; font-weight:bold; font-size:' + get_font_size('title'), E.img(src=icon_for_node(node), style='height:2ex; margin-right: 0.5rem'), E.span(name) ) def edit_note(field, item_name): hide_modal() show_note(field, 0, item_name, panel='edit_note') if data.category and data.name and library_data.fields_that_support_notes.indexOf(data.category): title.appendChild(E.a(svgicon('pencil'), class_='blue-link', style='margin-left: 0.5em', href='javascript:void(0)', onclick=edit_note.bind(None, data.category, data.name), title=_('Edit or add notes for {}').format(data.name), )) container.appendChild(title) container.appendChild(E.div( style='margin-top:1ex; margin-bottom: 1ex', _('Search for books based on this category (a search term will be added to the search field)') )) ul = E.ul(style='list-style:none; overflow:hidden', class_='tb-action-list') container.appendChild(ul) items = [ (_('Books matching this category'), 'plus'), (_('Books that do not match this category'), 'minus'), ] if node.data.is_hierarchical is 5: items.extend([ (_('Books that match this category and all sub-categories'), 'plusplus'), (_('Books that do not match this category or any of its sub-categories'), 'minusminus'), ]) interface_data = get_interface_data() for text, search_type in items: li = E.li( style='display:flex; align-items: center; margin-bottom:0.5ex; padding: 0.5ex; cursor:pointer', E.img(src=absolute_path('{}/{}.png'.format(interface_data.icon_path, search_type)), style='max-height: 2.5ex; margin-right:0.5rem'), E.span(text) ) li.addEventListener('click', add_to_search.bind(None, node, search_type)) li.addEventListener('click', hide_modal) ul.appendChild(li) f = E.form( style='text-align:left; border-top: solid 1px currentColor; padding-top:1ex; margin-top:0.5ex; display:flex; align-items:center', E.span(_('Add to the search expression with:')), E.input(type='radio', name='expr_join', value='OR', checked=''), E.span('\xa0OR\xa0'), E.input(type='radio', name='expr_join', value='AND'), E.span('\xa0AND') ) and_control = f.lastChild.previousSibling and_control.checked = get_session_data().get('and_search_terms') container.appendChild(f) and_control.addEventListener('change', def(ev): get_session_data().set('and_search_terms', bool(ev.target.checked)) ) f.firstChild.nextSibling.addEventListener('change', def(ev): get_session_data().set('and_search_terms', not ev.target.checked) ) about_items = v'[]' if data.count is not undefined: about_items.push(_('Number of books: {}').format(data.count)) if data.avg_rating is not undefined: about_items.push(_('Average rating of books: {:.1f}').format(data.avg_rating)) footer = E.div( style='text-align:left; border-top: solid 1px currentColor; padding-top:1ex; margin-top:0.5ex;', ) if about_items.length: footer.appendChild(E.div(style='font-size: smaller', ' '.join(about_items))) if footer.firstChild: container.appendChild(footer) show_modal(create_details) def render_children(container, children): for i, node in enumerate(children): data = node.data tooltip = '' if data.count is not undefined: tooltip += '\n' + _('Number of books in this category: {}').format(data.count) if data.avg_rating is not undefined: tooltip += '\n' + _('Average rating for books in this category: {:.1f}').format(data.avg_rating) div = E.div( title=tooltip.lstrip(), style="display:flex; align-items: stretch", E.div(class_='tag-name', style='border-right:solid 1px currentColor; padding: 1ex; display:flex; align-items: center', E.img(src=icon_for_node(node), style='display:inline-block; max-height:2.5ex'), E.span(data.name), ), E.div(class_='tag-menu', style='padding: 1ex; display:flex; align-items:center', E.div(svgicon('angle-down')) ) ) set_css(div, max_width='95vw', border='solid 1px currentColor', border_radius='20px', margin='0.5rem', cursor='pointer', overflow='hidden', user_select='none') div.firstChild.addEventListener('click', node_clicked.bind(None, i)) div.lastChild.addEventListener('click', menu_clicked.bind(None, i)) container.appendChild(div) def render_breadcrumbs(): container = state.breadcrumbs.container if not state.tag_path.length: container.style.display = 'none' return container.style.display = 'inline-block' state.breadcrumbs.reset() def onclick(i): return def(ev): state.tag_path = state.tag_path[:i+1] render_tag_browser() ev.preventDefault() return True def create_breadcrumb(index=-1, item=None): li = state.breadcrumbs.add_crumb(onclick(index)) if item: li.appendChild(E.span(item.name)) else: li.appendChild(svgicon('home', '2.2ex', '2.2ex')) create_breadcrumb() parent = state.tag_browser_data for i, index in enumerate(state.tag_path): parent = parent.children[index] create_breadcrumb(i, parent.data) def render_tag_browser(): container = component(document.getElementById(state.container_id), "tag_browser") clear(container) set_css(container, padding='1ex 1em', display='flex', flex_wrap='wrap', margin_left='-0.5rem') try: node = node_for_path() except: # If a saved tag_path is no longer valid state.tag_path = [] node = node_for_path() render_children(container, node.children) render_breadcrumbs() def on_data_fetched(end_type, xhr, ev): state.currently_loading = None if end_type is 'abort': return container = document.getElementById(state.container_id) if not container: return loading_panel = component(container, 'loading') loading_panel.style.display = 'none' container = component(container, 'tag_browser') container.style.display = 'block' clear(container) def show_error(error_html): ediv = E.div() container.appendChild(ediv) safe_set_inner_html(ediv, '<h3>' + _('Failed to load Tag browser data') + '</h3>' + error_html) def process_node(node, item_map): state.node_id_map[node.id] = node node.data = item_map[node.id] for child in node.children: child.parent = node process_node(child, item_map) if end_type is 'load': try: tag_browser_data = JSON.parse(xhr.responseText) except Exception as err: show_error(err + '') return state.tag_browser_data = tag_browser_data.root state.node_id_map = {} state.active_nodes = {} process_node(state.tag_browser_data, tag_browser_data.item_map) if last_accepted_search and last_accepted_search.library_id is current_library_id() and last_accepted_search.vl is current_virtual_library(): if last_accepted_search.tag_path.length: state.tag_path = list(last_accepted_search.tag_path) render_tag_browser() else: show_error(xhr.error_html) def refresh(): if state.currently_loading is not None: state.currently_loading.abort() state.currently_loading = None sd = get_session_data() query = {'library_id': current_library_id(), 'vl':current_virtual_library()} for k in 'sort_tags_by partition_method collapse_at dont_collapse hide_empty_categories'.split(' '): query[k] = sd.get(k) + '' xhr = ajax('interface-data/tag-browser', on_data_fetched, query=query, bypass_cache=False) xhr.send() state.currently_loading = xhr def create_search_panel(container): nonlocal state state = {} container.classList.add(CLASS_NAME) # search input container container.appendChild(E.div( data_component='search', style="text-align:center; padding:1ex 1em; border-bottom: solid 1px currentColor; margin-bottom: 0.5ex" )) container.appendChild(E.div( E.div(data_component='loading'), E.ol(style="display:none", data_component='breadcrumbs'), E.div(style="display:none", data_component='tag_browser') )) # Build search input # We dont focus the search box because on mobile that will cause the # keyboard to popup and obscure the rest of the page search_container = component(container, 'search') search_button = create_button(_('Search'), icon='search', tooltip=_('Do the search')) search_bar = create_search_bar(execute_search_interactive, 'search-books', tooltip=_('Search for books'), placeholder=_('Enter the search query'), button=search_button) set_css(search_bar, flex_grow='10', margin_right='0.5em') search_container.appendChild(E.div(style="display: flex; width: 100%;", search_bar, search_button)) search_container.appendChild(E.div(style="text-align: left; padding-top: 1ex", E.a(class_="blue-link", svgicon("fts"), '\xa0', _('Search the full text of books instead'), href='javascript: void(0)', onclick=show_panel.bind(None, "fts")))) search_container.appendChild(E.ul(class_='search-items', data_component='search_expression')) # Build loading panel loading_panel = component(container, 'loading') loading_panel.appendChild(E.div( create_spinner(), '\xa0' + _('Fetching data for the Tag browser, please wait') + '…', style='margin-left:auto; margin-right:auto; font-size: 1.5rem; font-weight; bold; text-align:center; margin-top:30vh') ) # Build breadcrumbs state.breadcrumbs = Breadcrumbs(component(container, 'breadcrumbs')) # Init state state.currently_loading = None state.tag_browser_data = None state.node_id_map = {} state.active_nodes = {} state.tag_path = [] state.container_id = ensure_id(container) refresh() # Tag browser prefrences {{{ def get_prefs(): return [ { 'name': 'sort_tags_by', 'text': _('Sort tags by'), 'choices': [('name', _('Name')), ('popularity', _('Popularity (number of books)')), ('rating', _('Average rating'))], 'tooltip': _('Change how the tags/authors/etc. are sorted in the "Tag browser"'), }, { 'name':'partition_method', 'text':_('Category partitioning method'), 'choices':[('first letter', _('First Letter')), ('disable', _('Disable')), ('partition', _('Partition'))], 'tooltip':_('Choose how Tag browser subcategories are displayed when' ' there are more items than the limit. Select by first' ' letter to see an A, B, C list. Choose partitioned to' ' have a list of fixed-sized groups. Set to disabled' ' if you never want subcategories.'), }, { 'name':'collapse_at', 'text':_('Collapse when more items than'), 'min': 5, 'max':10000, 'step':5, 'from_storage':int, 'to_storage':int, 'tooltip': _('If a "Tag browser" category has more than this number of items, it is divided' ' up into subcategories. If the partition method is set to disable, this value is ignored.'), }, { 'name': 'dont_collapse', 'text': _('Categories not to partition'), 'tooltip': _('A comma-separated list of categories in which items containing' ' periods are displayed in the Tag browser trees. For example, if' " this box contains 'tags' then tags of the form 'Mystery.English'" " and 'Mystery.Thriller' will be displayed with English and Thriller" " both under 'Mystery'. If 'tags' is not in this box," ' then the tags will be displayed each on their own line.'), }, { 'name': 'hide_empty_categories', 'text': _('Hide empty categories (columns)'), 'from_storage': def(x): return x.toLowerCase() is 'yes';, 'to_storage': def(x): return 'yes' if x else 'no';, 'tooltip':_('When checked, calibre will automatically hide any category' ' (a column, custom or standard) that has no items to show. For example, some' ' categories might not have values when using Virtual libraries. Checking this' ' box will cause these empty categories to be hidden.'), }, ] def tb_config_panel_handler(): return prefs_panel_handler(def(): return _('Configure Tag browser');, get_prefs) # }}} def onkeydown(container_id, close_action, ev): if ev.key is 'Escape': ev.preventDefault(), ev.stopPropagation() close_action() def init(container_id): if not library_data.sortable_fields: show_panel('book_list', replace=True) return container = document.getElementById(container_id) container.setAttribute('tabindex', '0') container.addEventListener('keydown', onkeydown.bind(None, container_id, back), {'passive': False, 'capture': True}) create_top_bar(container, title=_('Search for books'), action=back, icon='close') add_button(container, icon='cogs', action=show_panel.bind(None, 'book_list^search^prefs'), tooltip=_('Configure Tag browser')) container.appendChild(E.div(class_=CLASS_NAME)) create_search_panel(container.lastChild) container.focus()
23,190
Python
.py
466
40.643777
396
0.623895
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,482
comments_editor.pyj
kovidgoyal_calibre/src/pyj/book_list/comments_editor.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from book_list.theme import color_scheme, get_color, get_color_as_rgba from dom import add_extra_css, build_rule, clear, ensure_id, svgicon from gettext import gettext as _ from iframe_comm import IframeClient, create_wrapped_iframe from image_popup import fit_image from modals import create_custom_dialog from utils import html_escape from uuid import short_uuid4 from widgets import create_button CLASS_NAME = 'comments-editor' TOOLBAR_CLASS = 'comments-editor-toolbar' add_extra_css(def(): sel = '.' + TOOLBAR_CLASS + ' ' style = '' style += build_rule(sel, display='flex', flex_wrap='wrap', padding_top='0.25ex', padding_bottom='0.25ex') sel += ' > div' style += build_rule(sel, padding='0.5ex', margin_right='0.5ex', cursor='pointer') style += build_rule(sel + ':hover', color='red') style += build_rule(sel + '.activated', color=get_color('window-background'), background=get_color('window-foreground')) sel += '.sep' style += build_rule(sel, border_left='solid 2px currentColor', cursor='auto') style += build_rule(sel + ':hover', color='currentColor') return style ) def choose_block_style(proceed): create_custom_dialog(_('Choose style'), def(parent, close_modal): def action(which): close_modal() proceed(which) def s(text, tag): ans = create_button(text, action=action.bind(None, tag)) ans.style.marginBottom = '1ex' return ans spc = '\xa0' parent.appendChild(E.div( E.div(_('Choose the block style you would like to use')), E.div(class_='button-box', style='flex-wrap: wrap', s(_('Normal'), 'div'), spc, s('H1', 'h1'), spc, s('H2', 'h2'), spc, s('H3', 'h3'), spc, s('H4', 'h4'), spc, s('H5', 'h5'), spc, s('H6', 'h6'), spc, s(_('Quote'), 'blockquote') ) )) ) def insert_heading(editor_id, cmd): editor = registry[editor_id] if cmd: editor.exec_command('formatBlock', f'<{cmd}>') editor.focus() def insert_image(editor): acceptable_image_types = v'["image/png", "image/jpeg", "image/gif", "image/webp"]' parent_id = '' accepted = False align_name = 'align-radio-button' def on_close(evt): parent = document.getElementById(parent_id) if parent: img = parent.querySelector('img') if img: if accepted and img.src: align = parent.querySelector(f'input[name="{align_name}"]:checked').value s = style_from_align(align) w = parseInt(parent.querySelector(f'input[name="width"]').value or '0') page_width = (0 if isNaN(w) else w) or 1000000000 h = parseInt(parent.querySelector(f'input[name="height"]').value or '0') page_height = (0 if isNaN(h) else h) or 1000000000 w, h = img.naturalWidth, img.naturalHeight resized, nw, nh = fit_image(w, h, page_width, page_height) if resized: markup = ( f'<img src="{img.src}" data-filename="{html_escape(img.dataset.filename)}"' + f' data-align="{html_escape(align)}" width="{nw}" height="{nh}" style="{s}"></img>' ) else: markup = ( f'<img src="{img.src}" data-filename="{html_escape(img.dataset.filename)}"' + f' data-align="{html_escape(align)}" style="{s}"></img>' ) editor.exec_command('insertHTML', markup) def dialog(parent, close_modal): nonlocal parent_id parent_id = ensure_id(parent) container = parent.closest('.modal_height_container') max_container_height = container.style.maxHeight def action(ok, evt): nonlocal accepted img = parent.getElementsByTagName('img')[0] if ok and not img.src: parent.querySelector('.no-image-selected').style.display = 'block' return accepted = ok close_modal() def handle_files(files): parent.querySelector('.no-image-selected').style.display = 'none' parent.querySelector('.image-alignment').style.display = 'none' parent.querySelector('.image-shrink').style.display = 'none' img = parent.getElementsByTagName('img')[0] img.src = '' img.dataset.filename = '' img.dataset.align = '' img.parentElement.style.display = 'none' for f in files: if acceptable_image_types.indexOf(f.type) > -1: r = new FileReader() r.onload = def(): img.src = r.result r.readAsDataURL(f) h = parent.querySelector('.button-box').offsetHeight img.parentElement.style.display = 'block' non_content_height = (container.offsetHeight - parent.offsetHeight) + 'px' img.style.maxHeight = f'calc({max_container_height} - {non_content_height} - {h}px - 1rem)' if f.name: img.dataset.filename = f.name parent.querySelector('.image-alignment').style.display = 'block' parent.querySelector('.image-shrink').style.display = 'block' return alert(_('No valid image file found')) parent.appendChild(E.div( ondragenter=def(e): e.stopPropagation(), e.preventDefault() , ondragover=def(e): e.stopPropagation(), e.preventDefault() , ondrop=def(e): e.stopPropagation(), e.preventDefault() handle_files(e.dataTransfer.files) , E.div( style='display: flex;', E.div( style='display: none; min-width: 40%; max-width: 40%; margin-right: 0.5rem', E.img(style='max-width: 100%'), ), E.div( E.input( type='file', accept=','.join(acceptable_image_types), onchange=def(e): handle_files(e.target.files);, style='display: none' ), E.p(E.a( _('Select an image from your files'), class_='blue-link', href='javascript:void(0)', onclick=def (): parent.querySelector('input[type=file]').click() ), E.span(_(' or drag and drop an image here.'))), E.div( style='display: none; margin-top: 0.5rem', class_='image-alignment', _('Place image:'), E.br(), E.label(E.input(type='radio', name=align_name, value='left'), _('Float left'), style='margin-right: 0.5rem'), ' ', E.label(E.input(type='radio', name=align_name, value='inline', checked=True), _('Inline'), title=_('Place the image inline with surrounding text'), style='margin-right: 0.5rem' ), ' ', E.label(E.input(type='radio', name=align_name, value='right'), _('Float right')), ), E.div( style='display: none; margin-top: 0.5rem', class_='image-shrink', _('Shrink image to fit (px):'), E.div(style='display: flex; flex-wrap: wrap', E.label(_('Width:') + '\xa0', E.input(type='number', min='0', max='10000', name='width'), style='margin-left: 0.5rem', title=_('A value of zero means no effect')), E.label(_('Height:') + '\xa0', E.input(type='number', min='0', max='10000', name='height'), style='margin-left: 0.5rem', title=_('A value of zero means no effect') )), ), E.p(_('No image selected!'), class_='no-image-selected', style='color:red; display:none'), ), ), E.div(class_='button-box', create_button(_('OK'), action=action.bind(None, True), highlight=True), '\xa0', create_button(_('Cancel'), action=action.bind(None, False), highlight=False), ), )) create_custom_dialog(_('Insert image'), dialog, on_close=on_close) def insert_link(title, msg, proceed): create_custom_dialog(title, def(parent, close_modal): def action(ok, evt): close_modal() c = evt.currentTarget.closest('.il-modal-container') url = c.querySelector('input[name="url"]').value name = c.querySelector('input[name="name"]').value proceed(ok, url, name) parent.appendChild(E.div(class_='il-modal-container', E.div(msg), E.table(style='width: 95%; margin-top: 1ex', E.tr(E.td('URL:'), E.td(style='padding-bottom: 1ex', E.input(type='url', name='url', style='width: 100%'))), E.tr(E.td(_('Name (optional):')), E.td(E.input(type='text', name='name', style='width: 100%'))), ), E.div(class_='button-box', create_button(_('OK'), action=action.bind(None, True), highlight=True), '\xa0', create_button(_('Cancel'), action=action.bind(None, False), highlight=False), ), )) ) def insert_link_or_image(editor_id, is_image, ok, url, title): editor = registry[editor_id] if ok: if title: markup = '<img src="{}" alt="{}"></img>' if is_image else '<a href="{}">{}</a>' editor.exec_command('insertHTML', markup.format(html_escape(url), html_escape(title))) else: cmd = 'insertImage' if is_image else 'createLink' editor.exec_command(cmd, url) editor.focus() def set_color(title, msg, proceed): create_custom_dialog(title, def(parent, close_modal): def action(ok, evt): close_modal() c = evt.currentTarget.closest('.sc-modal-container') color = c.querySelector('input[name="color"]').value proceed(ok, color) parent.appendChild(E.div(class_='sc-modal-container', E.div(msg), E.div(E.input(type='color', name='color')), E.div(class_='button-box', create_button(_('OK'), action=action.bind(None, True), highlight=True), '\xa0', create_button(_('Cancel'), action=action.bind(None, False), highlight=False), ), )) ) def change_color(editor_id, which, ok, color): editor = registry[editor_id] if ok: editor.exec_command(which, color) editor.focus() def all_editor_actions(): # {{{ if not all_editor_actions.ans: all_editor_actions.ans = { 'select-all': { 'icon': 'select-all', 'title': _('Select all'), 'execute': def (editor, activated): editor.exec_command('selectAll') }, 'remove-format': { 'icon': 'eraser', 'title': _('Remove formatting'), 'execute': def (editor, activated): editor.exec_command('removeFormat') }, 'undo': { 'icon': 'undo', 'title': _('Undo'), 'execute': def (editor, activated): editor.exec_command('undo') }, 'redo': { 'icon': 'redo', 'title': _('Redo'), 'execute': def (editor, activated): editor.exec_command('redo') }, 'bold': { 'icon': 'bold', 'title': _('Bold'), 'execute': def (editor, activated): editor.exec_command('bold') }, 'italic': { 'icon': 'italic', 'title': _('Italic'), 'execute': def (editor, activated): editor.exec_command('italic') }, 'underline': { 'icon': 'underline', 'title': _('Underline'), 'execute': def (editor, activated): editor.exec_command('underline') }, 'strikethrough': { 'icon': 'strikethrough', 'title': _('Strikethrough'), 'execute': def (editor, activated): editor.exec_command('strikeThrough') }, 'superscript': { 'icon': 'superscript', 'title': _('Superscript'), 'execute': def (editor, activated): editor.exec_command('superscript') }, 'subscript': { 'icon': 'subscript', 'title': _('Subscript'), 'execute': def (editor, activated): editor.exec_command('subscript') }, 'hr': { 'icon': 'hr', 'title': _('Insert separator'), 'execute': def (editor, activated): editor.exec_command('insertHorizontalRule') }, 'format-block': { 'icon': 'heading', 'title': _('Style the selected text block'), 'execute': def (editor, activated): choose_block_style(insert_heading.bind(None, editor.id)) }, 'ul': { 'icon': 'ul', 'title': _('Unordered list'), 'execute': def (editor, activated): editor.exec_command('insertUnorderedList') }, 'ol': { 'icon': 'ol', 'title': _('Ordered list'), 'execute': def (editor, activated): editor.exec_command('insertOrderedList') }, 'indent': { 'icon': 'indent', 'title': _('Increase indentation'), 'execute': def (editor, activated): editor.exec_command('indent') }, 'outdent': { 'icon': 'outdent', 'title': _('Decrease indentation'), 'execute': def (editor, activated): editor.exec_command('outdent') }, 'justify-left': { 'icon': 'justify-left', 'title': _('Align left'), 'execute': def (editor, activated): editor.exec_command('justifyLeft') }, 'justify-full': { 'icon': 'justify-full', 'title': _('Align justified'), 'execute': def (editor, activated): editor.exec_command('justifyFull') }, 'justify-center': { 'icon': 'justify-center', 'title': _('Align center'), 'execute': def (editor, activated): editor.exec_command('justifyCenter') }, 'justify-right': { 'icon': 'justify-right', 'title': _('Align right'), 'execute': def (editor, activated): editor.exec_command('justifyRight') }, 'insert-link': { 'icon': 'insert-link', 'title': _('Insert a link or linked image'), 'execute': def (editor, activated): insert_link(_('Insert a link'), _('Enter the link URL and optionally the link name'), insert_link_or_image.bind(None, editor.id, False)) }, 'insert-image': { 'icon': 'image', 'title': _('Insert an image'), 'execute': def (editor, activated): if editor.insert_image_files: insert_image(editor) else: insert_link(_('Insert an image'), _('Enter the image URL and optionally the image name'), insert_link_or_image.bind(None, editor.id, True)) }, 'fg': { 'icon': 'fg', 'title': _('Change the text color'), 'execute': def (editor, activated): set_color(_('Choose text color'), _('Choose the color below'), change_color.bind(None, editor.id, 'foreColor')) }, 'bg': { 'icon': 'bg', 'title': _('Change the highlight color'), 'execute': def (editor, activated): set_color(_('Choose highlight color'), _('Choose the color below'), change_color.bind(None, editor.id, 'hiliteColor')) }, } return all_editor_actions.ans # }}} def style_from_align(align): if align is 'left': return 'float: left; margin-right: 0.5em' if align is 'right': return 'float: right; margin-left: 0.5em' return '' class CommentsEditorBoss: def __init__(self): handlers = { 'initialize': self.initialize, 'set_html': self.set_html, 'get_html': self.get_html, 'exec_command': self.exec_command, 'focus': self.focus, } self.comm = IframeClient(handlers, 'comments-editor-iframe') def initialize(self, data): window.onerror = self.onerror clear(document.body) document.execCommand("defaultParagraphSeparator", False, "div") document.execCommand("styleWithCSS", False, False) document.body.style.margin = '0' document.body.style.padding = '0' document.body.style.fontFamily = window.default_font_family document.body.appendChild(E.style('div:focus { outline: none }')) document.body.appendChild(E.div(style='width: 100%; padding: 0.5rem; margin: 0; border-width: 0; box-sizing: border-box')) document.body.lastChild.contentEditable = True document.body.lastChild.addEventListener('keyup', self.update_state) document.body.lastChild.addEventListener('mouseup', self.update_state) document.body.lastChild.focus() self.update_state() def focus(self): document.body.lastChild.focus() def onerror(self, msg, script_url, line_number, column_number, error_object): if error_object is None: # This happens for cross-domain errors (probably javascript injected # into the browser via extensions/ userscripts and the like). It also # happens all the time when using Chrome on Safari console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}') else: console.log(error_object) def set_html(self, data): if data.color_scheme: document.documentElement.style.colorScheme = data.color_scheme document.body.style.color = data.color document.body.lastChild.innerHTML = data.html def get_html(self, data): c = document.body.lastChild.cloneNode(True) images = v'{}' if data.extract_images: for img in c.getElementsByTagName('img'): if img.src: key = short_uuid4() images[key] = {'data': img.src, 'filename': img.dataset.filename} if img.dataset.filename: # this is an added image s = style_from_align(img.dataset.align) if s: img.setAttribute('style', s) else: img.removeAttribute('style') img.src = key v'delete img.dataset.filename' v'delete img.dataset.align' self.comm.send_message('html', html=c.innerHTML, extra_data={'images': images, 'text': c.innerText}) def exec_command(self, data): document.execCommand(data.name, False, data.value) self.update_state() def update_state(self): state = {name: document.queryCommandState(name) for name in 'bold italic underline superscript subscript'.split(' ')} state.strikethrough = document.queryCommandState('strikeThrough') self.comm.send_message('update_state', state=state) registry = {} def destroy_removed_editors(): for k in Object.keys(registry): if not document.getElementById(k): registry[k].destroy() v'delete registry[k]' def add_editor(editor): destroy_removed_editors() registry[editor.id] = editor def destroy_editor(container): v'delete registry[container.querySelector("iframe").id]' class Editor: def __init__(self, iframe_kw, insert_image_files): handlers = { 'ready': self.on_iframe_ready, 'html': self.on_html_received, 'update_state': self.update_state, } iframe, self.iframe_wrapper = create_wrapped_iframe( handlers, _('Loading comments editor...'), 'book_list.comments_editor', iframe_kw) self.id = iframe.id self.ready = False self.pending_set_html = None self.pending_get_html = v'[]' self.get_html_callbacks = v'[]' self.iframe_obj = iframe self.insert_image_files = v'!!insert_image_files' def init(self): self.iframe_wrapper.init() def destroy(self): self.iframe_wrapper.destroy() self.get_html_callbacks = v'[]' def focus(self): self.iframe.contentWindow.focus() if self.ready: self.iframe_wrapper.send_message('focus') @property def iframe(self): return self.iframe_wrapper.iframe def on_iframe_ready(self, msg): self.ready = True return self.after_iframe_initialized def after_iframe_initialized(self): if self.pending_set_html is not None: self.set_html(self.pending_set_html) self.pending_set_html = None if self.pending_get_html.length > 0: for x in self.pending_get_html: self.get_html(x) def set_html(self, html): if not self.ready: self.pending_set_html = html return rgba = get_color_as_rgba('window-foreground') self.iframe_wrapper.send_message('set_html', html=html, color_scheme=color_scheme(), color=f'rgba({rgba[0]},{rgba[1]},{rgba[2]},{rgba[3]})') def get_html(self, proceed): self.get_html_callbacks.push(proceed) if self.ready: self.iframe_wrapper.send_message('get_html', extract_images=self.insert_image_files) else: self.pending_get_html.push(proceed) def on_html_received(self, data): if self.get_html_callbacks.length: for f in self.get_html_callbacks: f(data.html, data.extra_data) self.get_html_callbacks = v'[]' def exec_command(self, name, value=None): if self.ready: self.iframe_wrapper.send_message('exec_command', name=name, value=value) def update_state(self, data): c = self.iframe.closest('.' + CLASS_NAME) for name in Object.keys(data.state): div = c.querySelector(f'.{TOOLBAR_CLASS} > [name="{name}"]') if div: if data.state[name]: div.classList.add('activated') else: div.classList.remove('activated') def create_editor(insert_image_files): iframe_kw = { 'sandbox': 'allow-scripts', 'seamless': True, 'style': 'flex-grow: 10; border: solid 1px currentColor' } editor = Editor(iframe_kw, insert_image_files) iframe = editor.iframe_obj v'delete editor.iframe_obj' add_editor(editor) return iframe, editor def action_activated(editor_id, ac_name, evt): editor = registry[editor_id] if not editor: return action = all_editor_actions()[ac_name] if not action: return button = evt.currentTarget action.execute(editor, button.classList.contains('activated')) editor.focus() def add_action(toolbar, ac_name, action, editor_id): b = E.div(svgicon(action.icon), title=action.title, onclick=action_activated.bind(None, editor_id, ac_name), name=ac_name) toolbar.appendChild(b) def create_comments_editor(container, options): options = options or {} iframe, editor = create_editor(options.insert_image_files) toolbars = E.div(style='flex-grow: 0') toolbar1 = E.div(class_=TOOLBAR_CLASS) toolbar2 = E.div(class_=TOOLBAR_CLASS) toolbar3 = E.div(class_=TOOLBAR_CLASS) toolbars.appendChild(toolbar1), toolbars.appendChild(toolbar2), toolbars.appendChild(toolbar3) acmap = all_editor_actions() def add(toolbar, ac_name): if ac_name: if acmap[ac_name]: add_action(toolbar, ac_name, acmap[ac_name], editor.id) else: toolbar.appendChild(E.div(class_='sep')) for ac_name in 'undo redo select-all remove-format bold italic underline strikethrough'.split(' '): add(toolbar1, ac_name) for ac_name in 'hr superscript subscript format-block ul ol indent outdent'.split(' '): add(toolbar2, ac_name) for ac_name in 'justify-left justify-center justify-right justify-full insert-link insert-image fg bg'.split(' '): add(toolbar3, ac_name) container.setAttribute('style', (container.getAttribute('style') or '') + ';display: flex; flex-direction: column; align-items: stretch') container.appendChild(toolbars) container.appendChild(iframe) container.classList.add(CLASS_NAME) return editor def focus_comments_editor(container): iframe = container.querySelector('iframe') editor = registry[iframe.getAttribute('id')] if editor: editor.focus() def set_comments_html(container, html): iframe = container.querySelector('iframe') eid = iframe.getAttribute('id') editor = registry[eid] editor.set_html(html or '') def get_comments_html(container, proceed): iframe = container.querySelector('iframe') eid = iframe.getAttribute('id') editor = registry[eid] editor.get_html(proceed) def develop(container): container.setAttribute('style', 'width: 100%; min-height: 90vh; display: flex; flex-direction: column; align-items: stretch') editor = create_comments_editor(container) set_comments_html(container, '<p>Testing, <i>testing</i> 123...') focus_comments_editor(container) editor.init() def main(): main.boss = CommentsEditorBoss()
27,377
Python
.py
602
32.868771
191
0.543758
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,483
item_list.pyj
kovidgoyal_calibre/src/pyj/book_list/item_list.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals from dom import build_rule, svgicon, add_extra_css, clear from elementmaker import E from book_list.theme import get_font_size, get_color CLASS_NAME = 'generic-items-list' add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = '' style += build_rule(sel + 'li', padding='0', border_bottom='solid 1px ' + get_color('window-foreground'), border_top='solid 1px ' + get_color('window-background'), cursor='pointer', list_style='none') style += build_rule(sel + '.item-title', font_size=get_font_size('item-list-title')) style += build_rule(sel + ' .item-subtitle', font_size=get_font_size('item-list-subtitle'), font_style='italic') sel += ' li > div:nth-child(1)' style += build_rule(sel, padding='1rem') style += build_rule(sel + ':hover', color=get_color('list-hover-foreground'), background_color=get_color('list-hover-background'), border_top_color=get_color('list-hover-foreground')) style += build_rule(sel + ':active', transform='scale(1, 1.5)') return style ) def side_action(action, ev): ev.stopPropagation(), ev.preventDefault() if action: li = ev.currentTarget.closest('li') action(li) def build_list(container, items, subtitle): c = container clear(c) c.classList.add(CLASS_NAME) if subtitle: c.appendChild(E.p(subtitle, style="font-style:italic; padding: 1em 1ex; border-bottom: solid 1px currentColor")) ul = E.ul() c.appendChild(ul) has_icons = False for item in items: if item.icon: has_icons = True break for item in items: ic = '' if has_icons: if item.icon: ic = svgicon(item.icon) ic = E.span(ic, '\xa0') li = E.li(E.div(ic, item.title, class_='item-title')) ul.appendChild(li) if item.subtitle: li.firstChild.appendChild(E.div(item.subtitle, class_='item-subtitle', style='padding-top:1ex')) if item.action: li.addEventListener('click', item.action) if item.data: li.dataset.userData = item.data if item.side_actions?.length: s = li.style s.display = 'flex' s.alignItems = 'center' li.firstChild.style.flexGrow = '10' li.appendChild(E.div( style='display: flex; align-items: center; margin-left: 0.5rem' )) for x in item.side_actions: li.lastChild.appendChild(E.div( class_='simple-link', style='padding: 0.5rem', title=x.tooltip or '', onclick=side_action.bind(None, x.action), svgicon(x.icon) )) def create_side_action(icon, action=None, tooltip=None): return {'icon':icon, 'action': action, 'tooltip': tooltip} def create_item(title, action=None, subtitle=None, icon=None, data=None, side_actions=None): return {'title':title, 'action':action, 'subtitle':subtitle, 'icon':icon, 'data': data, 'side_actions': side_actions or v'[]'} def create_item_list(container, items, subtitle=None): build_list(container, items, subtitle)
3,323
Python
.py
73
37.136986
204
0.617929
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,484
theme.pyj
kovidgoyal_calibre/src/pyj/book_list/theme.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods DARK = '#39322B' LIGHT = '#F6F3E9' LIGHT_DARKER = '#b6b3a8' LIGHT_GRADIENT = 'linear-gradient(to bottom, {}, {})'.format(LIGHT, LIGHT_DARKER) DT_DARK = '#2d2d2d' DT_DARK_DARKER = 'black' DT_DARK_LIGHTER = '#777' DT_DARK_LIGTHER_CONTRAST = '#1d1d1d' DT_LIGHT = '#ddd' DARK_GRADIENT = 'linear-gradient(to bottom, {}, {})'.format(DT_DARK_LIGHTER, DT_DARK) def c(light, dark): return {'light': light, 'dark': dark or light} DEFAULT_COLORS = { # General colors 'window-background': c(LIGHT, DT_DARK), 'window-background2': c(LIGHT_DARKER, DT_DARK_LIGHTER), 'window-foreground': c(DARK, DT_LIGHT), 'window-error-foreground': c('red', '#C40233'), 'window-hover-foreground': c('red', '#C40233'), 'link-foreground': c('blue', '#6cb4ee'), 'faded-text': c('#666', '#7f7f7f'), # Top bar specific colors 'bar-background': c(DARK, DT_DARK_LIGHTER), 'bar-foreground': c(LIGHT, DT_DARK_LIGTHER_CONTRAST), 'bar-highlight': c('yellow'), 'heart': c('#B92111'), # Item list colors 'list-hover-background': c(DARK, DT_DARK_LIGHTER), 'list-hover-foreground': c(LIGHT, DT_DARK_LIGTHER_CONTRAST), # Tree colors 'tree-highlight-item': c(LIGHT_DARKER, DT_DARK_LIGHTER), # Button colors 'button-start': c(DARK, DT_LIGHT), 'button-end': c('#49423B', '#666'), 'button-text': c(LIGHT, DT_DARK), # Dialog colors 'dialog-background': c(LIGHT, DT_DARK), 'dialog-background-image': c(LIGHT_GRADIENT, DARK_GRADIENT), 'dialog-foreground': c(DARK, DT_LIGHT), # Native controls 'input-background': c('field', DT_DARK_DARKER), 'input-foreground': c('fieldtext', DT_LIGHT), 'input-focus-outline-color': c('#4D90FE', DT_LIGHT), } DEFAULT_SIZES = { 'title': '1.4rem', 'item-list-title': '1.1rem', 'item-list-subtitle': '0.8rem', } DEFAULT_FONTS = { 'main': 'sans-serif' } def set_ui_colors(is_dark_theme): attr = 'dark' if is_dark_theme else 'light' s = document.documentElement.style for k in DEFAULT_COLORS: val = DEFAULT_COLORS[k][attr] s.setProperty('--calibre-color-' + k, val) get_color_as_rgba.cache = {} cached_color_to_rgba.cache = {} document.documentElement.style.colorScheme = 'dark' if is_dark_theme else 'light' def browser_in_dark_mode(): return window.matchMedia('(prefers-color-scheme: dark)').matches def color_scheme(): return 'dark' if browser_in_dark_mode() or document.documentElement.style.colorScheme is 'dark' else 'light' def css_for_variables(): input_css = ''' input, textarea { color: var(--calibre-color-input-foreground); \ background-color: var(--calibre-color-input-background); \ } input:focus, textarea:focus { outline-color: var(--calibre-color-input-focus-outline-color); \ } ''' is_dark_theme = browser_in_dark_mode() attr = 'dark' if is_dark_theme else 'light' ans = v'[]' for k in DEFAULT_COLORS: val = DEFAULT_COLORS[k][attr] ans.push(f'--calibre-color-{k}: {val};') return f':root {{ color-scheme: {attr}; ' + ans.join('\n') + '}\n\n' + input_css def get_color(name): return f'var(--calibre-color-{name})' def color_to_rgba(color): # take an arbitrary color spec and return it as [r, g, b, a] cvs = document.createElement('canvas') cvs.height = 1 cvs.width = 1 if color.startsWith('var('): color = window.getComputedStyle(document.documentElement).getPropertyValue(color[4:-1]) ctx = cvs.getContext('2d') ctx.fillStyle = color ctx.fillRect(0, 0, 1, 1) return ctx.getImageData(0, 0, 1, 1).data def cached_color_to_rgba(color): cache = cached_color_to_rgba.cache if not cache[color]: cache[color] = color_to_rgba(color) return cache[color] cached_color_to_rgba.cache = {} def get_color_as_rgba(name): cache = get_color_as_rgba.cache if not cache[name]: cache[name] = color_to_rgba(get_color(name)) return cache[name] get_color_as_rgba.cache = {} def get_font_size(name): return DEFAULT_SIZES[name] def get_font_family(name): name = name or 'main' return DEFAULT_FONTS[name]
4,353
Python
.py
115
33.104348
112
0.653672
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,485
delete_book.pyj
kovidgoyal_calibre/src/pyj/book_list/delete_book.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from ajax import ajax from book_list.add import write_access_error from book_list.library_data import book_after, force_refresh_on_next_load, remove_book from book_list.router import back from book_list.ui import show_panel from dom import clear from modals import create_custom_dialog from read_book.db import get_db from utils import safe_set_inner_html from widgets import create_button def delete_from_cache(library_id, book_id, title): db = get_db() db.delete_books_matching(library_id, book_id) def refresh_after_delete(book_id, library_id): force_refresh_on_next_load() next_book_id = book_after(book_id) remove_book(book_id) if next_book_id: show_panel('book_details', {'book_id': str(next_book_id), 'library_id': library_id}, True) else: back() def do_delete_from_library(parent, close_modal, library_id, book_id, title): parent.appendChild(E.div(_('Deleting {0} from library, please wait...').format(title))) def oncomplete(end_type, xhr, ev): if end_type is 'load' or end_type is 'abort': close_modal() if end_type is 'load': refresh_after_delete(book_id, library_id) return clear(parent) msg = E.div() safe_set_inner_html(msg, write_access_error(_('Failed to delete {0}, with error:').format(title), xhr)) parent.appendChild(E.div( msg, E.div(class_='button-box', create_button(_('Close'), None, close_modal, True) ) )) ajax(f'cdb/delete-books/{book_id}/{library_id}', oncomplete, method='POST').send() def confirm_delete_from_library(library_id, book_id, title): create_custom_dialog(_('Are you sure?'), def(parent, close_modal): def action(doit): if doit: clear(parent) do_delete_from_library(parent, close_modal, library_id, book_id, title) else: close_modal() msg = _('This will <b>permanently delete</b> <i>{0}</i> from your calibre library. Are you sure?').format(title) m = E.div() safe_set_inner_html(m, msg) parent.appendChild(E.div( m, E.div(class_='button-box', create_button(_('OK'), None, action.bind(None, True)), '\xa0', create_button(_('Cancel'), None, action.bind(None, False), highlight=True), ) )) ) def choose_which_delete(library_id, book_id, title): create_custom_dialog(_('Delete from?'), def(parent, close_modal): def action(from_cache, from_library): close_modal() if from_cache: delete_from_cache(library_id, book_id, title) if from_library: confirm_delete_from_library(library_id, book_id, title) parent.appendChild(E.div( E.div(_('{0} is available both in the browser cache for offline reading and in' ' your calibre library. Where do you want to delete it from?').format(title)), E.div(class_='button-box', create_button(_('Cache'), None, action.bind(None, True, False)), '\xa0', create_button(_('Library and cache'), None, action.bind(None, True, True)), ) )) ) def delete_book_stage2(library_id, book_id, title, has_offline_copies): if has_offline_copies: choose_which_delete(library_id, book_id, title) else: confirm_delete_from_library(library_id, book_id, title) def start_delete_book(library_id, book_id, title): book_id = int(book_id) db = get_db() db.has_book_matching(library_id, book_id, delete_book_stage2.bind(None, library_id, book_id, title))
3,992
Python
.py
91
35.351648
120
0.622646
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,486
main.pyj
kovidgoyal_calibre/src/pyj/book_list/main.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods import traceback from elementmaker import E from ajax import ajax from dom import set_css, get_widget_css from modals import create_modal_container, error_dialog from session import get_interface_data, UserSessionData, update_interface_data, get_translations from gettext import gettext as _, install from popups import install_event_filters from utils import safe_set_inner_html from book_list.constants import book_list_container_id, read_book_container_id, INIT_ENDPOINT from book_list.home import update_recently_read_by_user from book_list.library_data import fetch_init_data, update_library_data, url_books_query from book_list.theme import get_color, get_font_family, css_for_variables from book_list.router import update_window_title, set_default_mode_handler, apply_url, set_mode_handler, on_pop_state from book_list.globals import get_db, set_session_data from book_list.ui import apply_url_state as book_list_mode_handler from read_book.ui import ReadUI # Register the various panels import book_list.home # noqa: unused-import import book_list.views # noqa: unused-import import book_list.local_books # noqa: unused-import import book_list.book_details # noqa: unused-import import book_list.edit_metadata # noqa: unused-import import book_list.convert_book # noqa: unused-import import book_list.fts # noqa: unused-import import book_list.show_note # noqa: unused-import def remove_initial_progress_bar(): p = document.getElementById('page_load_progress') if p: p.parentNode.removeChild(p) def onerror(msg, script_url, line_number, column_number, error_object): if error_object is None: # This happens for cross-domain errors (probably javascript injected # into the browser via extensions/ userscripts and the like). It also # happens all the time when using Chrom on Safari, so ignore this # type of error console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}') return console.log(error_object) try: fname = script_url.rpartition('/')[-1] or script_url msg = msg + '<br><span style="font-size:smaller">' + 'Error at {}:{}:{}'.format(fname, line_number, column_number or '') + '</span>' details = '' details = traceback.format_exception(error_object).join('') error_dialog(_('Unhandled error'), msg, details) return True except: console.log('There was an error in the unhandled exception handler') def init_ui(): document.body.style.fontFamily = get_font_family() install_event_filters() set_default_mode_handler(book_list_mode_handler) window.onerror = onerror setTimeout(def(): window.onpopstate = on_pop_state , 0) # We do this after event loop ticks over to avoid catching popstate events that some browsers send on page load translations = get_translations() install(translations) remove_initial_progress_bar() document.head.appendChild(E.style(css_for_variables() + '\n\n' + get_widget_css())) set_css(document.body, background_color=get_color('window-background'), color=get_color('window-foreground')) document.body.appendChild(E.div()) document.body.lastChild.appendChild(E.div(id=book_list_container_id, style='display: none')) document.body.lastChild.appendChild(E.div(id=read_book_container_id, style='display: none')) create_modal_container() update_window_title() read_ui = ReadUI() get_db(read_ui.db) set_mode_handler('read_book', read_ui.apply_url_state.bind(read_ui)) apply_url() def install_data_and_init_ui(raw_data): data = JSON.parse(raw_data) update_interface_data(data) update_recently_read_by_user(data.recently_read_by_user) update_library_data(data) interface_data = get_interface_data() sd = UserSessionData(interface_data.username, interface_data.user_session_data) set_session_data(sd) if data.translations?: get_translations(data.translations) init_ui() def on_data_loaded(end_type, xhr, ev): remove_initial_progress_bar() if end_type is 'load': install_data_and_init_ui(xhr.responseText) else: p = E.p(style='color:{}; font-weight: bold; font-size:1.5em'.format(get_color('window-error-foreground'))) if xhr.status is 401: msg = _('You are not authorized to view this site') else: msg = xhr.error_html safe_set_inner_html(p, msg) document.body.appendChild(p) def on_data_load_progress(loaded, total): p = document.querySelector('#page_load_progress > progress') if p: p.max = total p.value = loaded def load_interface_data(): idata = get_interface_data() query = {} if not idata.is_default: temp = UserSessionData(None, {}) # So that settings for anonymous users are preserved query = url_books_query(temp) ajax(INIT_ENDPOINT, on_data_loaded, on_data_load_progress, query=query).send() def do_update_interface_data(): t = get_translations() thash = t?.hash url = 'interface-data/update' if thash: url += '/' + thash ajax(url, def (end_type, xhr, ev): if end_type is 'load': data = JSON.parse(xhr.responseText) update_interface_data(data) update_recently_read_by_user(data.recently_read_by_user) if data.translations?: get_translations(data.translations) install(data.translations) else: update_recently_read_by_user() ).send() def main(): if document.createElement('iframe').srcdoc is undefined: document.body.innerHTML = '<p style="margin:1.5em; max-width: 40em">' + _( 'You are using a browser that does not have the iframe srcdoc attribute.' ' This is not supported. Use a better browser such as <b>Google Chrome</b> or <b>Mozilla' ' Firefox</b>, instead. You can also use the simplified <a href="mobile">/mobile</a>' ' interface if you do not have access to a modern browser.') return interface_data = get_interface_data() if interface_data.is_default or not interface_data.library_map: load_interface_data() else: sd = UserSessionData(interface_data.username, interface_data.user_session_data) set_session_data(sd) do_update_interface_data() fetch_init_data() init_ui()
6,610
Python
.py
142
40.669014
140
0.700016
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,487
details_list.pyj
kovidgoyal_calibre/src/pyj/book_list/details_list.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.theme import browser_in_dark_mode, css_for_variables, get_color from dom import build_rule, clear, set_css, svgicon from session import get_interface_data from utils import fmt_sidx, safe_set_inner_html, sandboxed_html DETAILS_LIST_CLASS = 'book-list-details-list' ITEM_CLASS = DETAILS_LIST_CLASS + '-item' def description(): return _('A list with thumbnails and some book details') THUMBNAIL_MAX_WIDTH = 35 * 3 THUMBNAIL_MAX_HEIGHT = 35 * 4 BORDER_RADIUS = 6 def details_list_css(): ans = '' sel = '.' + DETAILS_LIST_CLASS ans += build_rule(sel, cursor='pointer', user_select='none') ans += build_rule(sel + ' > div', margin='1ex 1em', padding_bottom='1ex', border_bottom='solid 1px currentColor') ans += build_rule(f'{sel} .{ITEM_CLASS}:hover .details-list-left', transform='scale(1.2)') ans += build_rule(f'{sel} .{ITEM_CLASS}:active .details-list-left', transform='scale(2)') s = sel + ' .details-list-left' ans += build_rule(s, margin_right='1em', min_width=f'{THUMBNAIL_MAX_WIDTH}px') ans += build_rule(s + ' > img', border_radius=BORDER_RADIUS+'px', max_height=f'{THUMBNAIL_MAX_HEIGHT}px', max_width=f'{THUMBNAIL_MAX_WIDTH}px') s = sel + ' .details-list-right' ans += build_rule(s, flex_grow='10', overflow='hidden', display='flex', flex_direction='column') top = s + ' > div:first-child' extra_data = top + ' > div:last-child' ans += f'{extra_data} {{ text-align: right }}' narrow_style = f'{s} iframe {{ display: none }} {top} {{ flex-direction: column }} {extra_data} {{ text-align: left; margin-top: 1ex }}' ans += f'@media (max-width: 450px) {{ {narrow_style} }}' s += ' iframe' # To enable clicking anywhere on the item to load book details to work, we # have to set pointer-events: none # That has the side effect of disabling text selection ans += build_rule(s, flex_grow='10', height='50px', cursor='pointer', pointer_events='none') return ans def init(container): clear(container) container.appendChild(E.div(class_=DETAILS_LIST_CLASS)) def on_img_load(img, load_type): div = img.parentNode if not div: return if load_type is not 'load': clear(div) div.appendChild(E.div( E.h2(img.dataset.title, style='text-align:center; font-size:larger; font-weight: bold'), E.div(_('by'), style='text-align: center'), E.h2(img.dataset.authors, style='text-align:center; font-size:larger; font-weight: bold') )) set_css(div, border='dashed 1px currentColor', border_radius=BORDER_RADIUS+'px') def sandbox_css(): is_dark_theme = browser_in_dark_mode() if not sandbox_css.ans or sandbox_css.is_dark_theme is not is_dark_theme: sandbox_css.ans = css_for_variables() + '\n\n' sandbox_css.ans += 'html {{ overflow: hidden; color: {} }}'.format(get_color('window-foreground')) sandbox_css.is_dark_theme = is_dark_theme return sandbox_css.ans def create_item(book_id, metadata, create_image, show_book_details, href): authors = metadata.authors.join(' & ') if metadata.authors else _('Unknown') img = create_image(book_id, THUMBNAIL_MAX_WIDTH, THUMBNAIL_MAX_HEIGHT, on_img_load) img.setAttribute('alt', _('{} by {}').format(metadata.title, authors)) img.dataset.title, img.dataset.authors = metadata.title, authors img_div = E.div(img, class_='details-list-left') extra_data = E.div() comments = sandboxed_html(metadata.comments, sandbox_css()) if not metadata.comments: comments.style.display = 'none' comments.style.marginTop = '1ex' interface_data = get_interface_data() if metadata.rating: stars = E.span(style='white-space:nowrap') for i in range(int(metadata.rating) // 2): stars.appendChild(svgicon('star')) extra_data.appendChild(stars), extra_data.appendChild(E.br()) if metadata.series: try: ival = float(metadata.series_index) except Exception: ival = 1.0 ival = fmt_sidx(ival, use_roman=interface_data.use_roman_numerals_for_series_number) extra_data.appendChild(safe_set_inner_html(E.span(), _('{0} of <i>{1}</i>').format(ival, metadata.series))) right = E.div( class_='details-list-right', E.div(style='display:flex; justify-content: space-between; overflow: hidden', E.div( E.b(metadata.title or _('Unknown')), E.br(), authors, ), extra_data ), comments, ) ans = E.div(E.a(img_div, right, href=href, style=f'height:{THUMBNAIL_MAX_HEIGHT}px; display: flex', class_=ITEM_CLASS, )) ans.addEventListener('click', show_book_details, True) return ans def append_item(container, item): container.lastChild.appendChild(item)
5,090
Python
.py
103
43.203883
147
0.65674
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,488
constants.pyj
kovidgoyal_calibre/src/pyj/book_list/constants.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods book_list_container_id = 'book-list-container' read_book_container_id = 'read-book-container' INIT_ENDPOINT = 'interface-data/init'
284
Python
.py
6
46
72
0.778986
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,489
local_books.pyj
kovidgoyal_calibre/src/pyj/book_list/local_books.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _, ngettext from book_list.globals import get_db from book_list.router import home, open_book from book_list.top_bar import add_button, create_top_bar from book_list.library_data import library_data from book_list.ui import set_panel_handler from book_list.views import DEFAULT_MODE, get_view_mode, setup_view_mode from dom import clear, ensure_id from modals import create_custom_dialog, error_dialog from utils import conditional_timeout, safe_set_inner_html from widgets import create_button, enable_escape_key CLASS_NAME = 'local-books-list' book_list_data = {} def component(name): return document.getElementById(book_list_data.container_id).querySelector(f'[data-component="{name}"]') def clear_grid(): container = document.getElementById(book_list_data.container_id) # We replace the div entirely so that any styles associated with it are also removed e = component('book_list') bl = E.div(data_component='book_list') container.insertBefore(bl, e) container.removeChild(e) book_list_data.init_grid(bl) def read_book(book, book_idx): library_id, book_id, fmt = book.key open_book(book_id, fmt, library_id) def delete_book(book, book_idx): db = get_db() db.delete_book(book, def(book, err_string): if err_string: error_dialog(_('Failed to delete book'), err_string) return books = [book_list_data.book_data[i] for i in book_list_data.books if i is not book_idx] show_recent_stage2.call(book_list_data.container_id, books) ) def confirm_delete_all(): num_of_books = book_list_data.books?.length if not num_of_books: return create_custom_dialog(_('Are you sure?'), def(parent, close_modal): def action(doit): if doit: clear(parent) delete_all(parent, close_modal) else: close_modal() msg = ngettext( 'This will remove the downloaded book from local storage. Are you sure?', 'This will remove all {} downloaded books from local storage. Are you sure?', num_of_books).format(num_of_books) m = E.div() safe_set_inner_html(m, msg) parent.appendChild(E.div( m, E.div(class_='button-box', create_button(_('OK'), None, action.bind(None, True)), '\xa0', create_button(_('Cancel'), None, action.bind(None, False), highlight=True), ) )) ) def delete_all(msg_parent, close_modal): db = get_db() books = list(book_list_data.books) def refresh(): show_recent_stage2.call(book_list_data.container_id, [book_list_data.book_data[i] for i in books]) def delete_one(): if not books.length: close_modal() refresh() return clear(msg_parent) safe_set_inner_html(msg_parent, ngettext( 'Deleting one book, please wait...', 'Deleting {} books, please wait...', books.length or 0).format(books.length) ) book_to_delete = books.pop() db.delete_book(book_list_data.book_data[book_to_delete], def(book, err_string): if err_string: close_modal() refresh() error_dialog(_('Failed to delete book'), err_string) else: delete_one() ) delete_one() def on_select(book, book_idx): title = this create_custom_dialog(title, def(parent, close_modal): def action(which): close_modal() which(book, book_idx) parent.appendChild(E.div( E.div(_('What would you like to do with this book?')), E.div(class_='button-box', create_button(_('Read'), 'book', action.bind(None, read_book)), '\xa0', create_button(_('Delete'), 'trash', action.bind(None, delete_book)), ) )) ) def show_cover(blob, name, mt, book): img = document.getElementById(this) if img: img.src = window.URL.createObjectURL(blob) def create_image(book_idx, max_width, max_height, on_load): img = new Image() img.onerror = def(): if this.src: window.URL.revokeObjectURL(this.src) on_load(this, 'error') img.onload = def(): if this.src: window.URL.revokeObjectURL(this.src) on_load(this, 'load') book = book_list_data.book_data[book_idx] if book?.metadata: authors = book.metadata.authors.join(' & ') if book.metadata.authors else _('Unknown') img.setAttribute('alt', _('{} by {}').format( book.metadata.title, authors)) if book?.cover_name: img_id = ensure_id(img, 'local-cover-') get_db().get_file(book, book.cover_name, show_cover.bind(img_id)) return img def render_book(book_idx): book = book_list_data.book_data[book_idx] return book_list_data.render_book(book_idx, book.metadata, create_image, on_select.bind(book.metadata.title, book, book_idx)) def render_books(books): div = component('book_list') books = books or book_list_data.books for book_idx in books: child = render_book(book_idx) if child is not None: book_list_data.append_item(div, child) def apply_view_mode(mode): mode = mode or DEFAULT_MODE if book_list_data.mode is mode: return setup_view_mode(mode, book_list_data) clear_grid() render_books() def create_books_list(container, books): clear(container) book_list_data.container_id = ensure_id(container) book_list_data.book_data = {i:book for i, book in enumerate(books)} book_list_data.books = list(range(books.length)) book_list_data.mode = None book_list_data.thumbnail_cache = {} if not books.length: container.appendChild(E.div( style='margin: 1rem 1rem', _('No downloaded books present') )) else: container.appendChild(E.div(data_component='book_list')) apply_view_mode(get_view_mode()) def show_recent_stage2(books): container = document.getElementById(this) if not container: return create_books_list(container, books) def show_recent(): container = this db = get_db() if not db.initialized or not library_data.field_metadata: conditional_timeout(container.id, 5, show_recent) return if db.is_ok: db.get_recently_read_books(show_recent_stage2.bind(container.id), 200) else: error_dialog(_('Database not initialized'), db.initialize_error_msg) def init(container_id): container = document.getElementById(container_id) on_close = home create_top_bar(container, title=_('Downloaded books'), action=on_close, icon='home') add_button(container, 'trash', confirm_delete_all, _('Delete all downloaded books')) # book list recent = E.div(class_=CLASS_NAME) recent_container_id = ensure_id(recent) container.appendChild(recent) recent.appendChild(E.div( style='margin: 1rem 1rem', _('Loading downloaded books from local storage, please wait...') )) conditional_timeout(recent_container_id, 5, show_recent) enable_escape_key(container, on_close) set_panel_handler('local_books', init)
7,587
Python
.py
193
31.823834
129
0.63994
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,490
cover_grid.pyj
kovidgoyal_calibre/src/pyj/book_list/cover_grid.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals, bound_methods from dom import clear, set_css, build_rule from elementmaker import E from gettext import gettext as _ COVER_GRID_CLASS = 'book-list-cover-grid' THUMBNAIL_MAX_WIDTH = 3 * 100 THUMBNAIL_MAX_HEIGHT = 4 * 100 THUMBNAIL_MIN_WIDTH = 3 * 35 THUMBNAIL_MIN_HEIGHT = 4 * 35 BORDER_RADIUS = 10 def description(): return _('A grid of book covers') def cover_grid_css(): sel = '.' + COVER_GRID_CLASS margin, margin_unit = 10, 'px' ans = build_rule(sel, display='flex', flex_wrap='wrap', justify_content='space-around', align_items='flex-end', align_content='flex-start', user_select='none', overflow='hidden', margin_top=f'{margin / 2}{margin_unit}') # Container for an individual cover sel += ' > a' ans += build_rule( sel, margin=f'{margin}{margin_unit}', display='flex', align_content='flex-end', align_items='center', justify_content='space-around', max_width=THUMBNAIL_MAX_WIDTH+'px', max_height=THUMBNAIL_MAX_HEIGHT+'px', cursor='pointer', min_width=THUMBNAIL_MIN_WIDTH+'px', min_height=THUMBNAIL_MIN_HEIGHT + 'px') mq = '@media all and (orientation: {orient}) {{ {sel} {{ width: 21{dim}; height: 28{dim} }} }}\n' for dim in 'vw', 'vh': ans += mq.format(sel=sel, dim=dim, orient='portrait' if dim is 'vw' else 'landscape') ans += build_rule(f'{sel}:hover', transform='scale(1.2)') ans += build_rule(f'{sel}:active', transform='scale(2)') ans += build_rule(sel + '.cover-grid-filler', height='0', max_height='0', min_height='0') # Container for cover failed to load message ans += build_rule(sel + ' > div', position='relative', top='-50%', transform='translateY(50%)', margin='0') # The actual cover sel += ' > img' ans += build_rule(sel, max_width='100%', max_height='100%', display='block', width='auto', height='auto', border_radius=BORDER_RADIUS+'px') return ans def init(container): clear(container) container.appendChild(E.div(class_=COVER_GRID_CLASS)) for i in range(12): container.lastChild.appendChild(E.div(class_='cover-grid-filler')) def on_img_load(img, load_type): div = img.parentNode if not div: return if load_type is not 'load': clear(div) div.appendChild(E.div( E.h2(img.dataset.title, style='text-align:center; font-size:larger; font-weight: bold'), E.div(_('by'), style='text-align: center'), E.h2(img.dataset.authors, style='text-align:center; font-size:larger; font-weight: bold') )) set_css(div, border='dashed 1px currentColor', border_radius=BORDER_RADIUS+'px') def create_item(book_id, metadata, create_image, show_book_details, href): authors = metadata.authors.join(' & ') if metadata.authors else _('Unknown') img = create_image(book_id, THUMBNAIL_MAX_WIDTH, THUMBNAIL_MAX_HEIGHT, on_img_load) tooltip = _('{} by {}').format(metadata.title, authors) img.setAttribute('alt', tooltip) img.dataset.title, img.dataset.authors = metadata.title, authors ans = E.a(img, onclick=show_book_details, title=tooltip, href=href) return ans def append_item(container, item): first_filler = container.lastChild.querySelector('.cover-grid-filler') container.lastChild.insertBefore(item, first_filler)
3,443
Python
.py
65
47.615385
143
0.670036
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,491
conversion_widgets.pyj
kovidgoyal_calibre/src/pyj/book_list/conversion_widgets.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from dom import add_extra_css, build_rule, clear, ensure_id from utils import safe_set_inner_html from widgets import create_button CLASS_NAME = 'conversion-option-group' indent = '↳\xa0' add_extra_css(def(): style = '' sel = '.' + CLASS_NAME + ' ' style += build_rule(sel + 'input[type="checkbox"]', margin_left='0') style += build_rule(sel + '[data-option-name]', margin_bottom='1ex', display='block', padding_bottom='0.5ex') style += build_rule(sel + '.simple-group > label', display='table-row') style += build_rule(sel + '.simple-group > label > *', display='table-cell', padding_bottom='1ex', padding_right='1rem') style += build_rule(sel + 'label.vertical', display='block') style += build_rule(sel + 'label.vertical > *', display='block', padding_bottom='1ex', padding_right='1rem') style += build_rule(sel + '[data-profile]', margin_left='2em', text_indent='-2em', font_size='smaller', margin_bottom='1ex') style += build_rule(sel + '.subset-choice label', display='block', margin_bottom='1ex') return style ) # globals {{{ container_id = None get_option_value = get_option_default_value = is_option_disabled = get_option_help = profiles = ui_data = None entry_points = {} registry = {} listeners = {} def ep(func): entry_points[func.name] = func return func def add_listener(name, callback): if not listeners[name]: listeners[name] = v'[]' listeners[name].push(callback) def on_change(name): if listeners[name]: for callback in listeners[name]: callback(name) def sanitize_accelerator(text): return text.replace('&', '') # }}} def subset_choice(name, choices, tooltip=None): # {{{ if get_option_default_value(name) is undefined: raise KeyError(f'{name} is not a known option') ans = E.div(data_option_name=name, class_='subset-choice') if tooltip is not None: ans.setAttribute('title', tooltip or get_option_help(name)) names = Object.keys(choices) for cname in names: ans.appendChild(E.label(E.input(type='checkbox', name=cname), '\xa0' + choices[cname])) ops = { 'get': def (container): ans = v'[]' for w in container.querySelectorAll('input'): if w.checked: ans.push(w.name) return ','.join(ans) , 'set': def (container, val): q = {x.strip():True for x in (val or '').split(',')} for w in container.querySelectorAll('input'): w.checked = bool(q[w.name]) , 'set_disabled': def (container, val): pass } registry[name] = ops ops.set(ans, get_option_value(name)) return ans # }}} def create_simple_widget(name, text, tooltip, input_widget_, getter, setter, suffix): # {{{ if get_option_default_value(name) is undefined: raise KeyError(f'{name} is not a known option') if not text.endswith(':'): text = text + ':' label = E.label(E.span(sanitize_accelerator(text)), E.span(input_widget_)) if suffix: label.lastChild.appendChild(document.createTextNode('\xa0' + suffix)) label.dataset.optionName = name label.setAttribute('title', tooltip or get_option_help(name)) def straight_input_widget(container): return container.lastChild.firstChild input_widget = straight_input_widget ops = { 'get': def (container): return getter(input_widget(container)) , 'set': def (container, val): setter(input_widget(container), val) , 'set_disabled': def (container, val): if val: container.classList.add('disabled') input_widget(container).setAttribute('disabled', 'disabled') else: container.classList.remove('disabled') input_widget(container).removeAttribute('disabled') } registry[name] = ops ops.set(label, get_option_value(name)) if is_option_disabled(name): ops.set_disabled(label, True) input_widget(label).addEventListener('change', on_change.bind(None, name)) if listeners[name]: window.setTimeout(on_change.bind(None, name), 0) return label # }}} def checkbox(name, text, tooltip): # {{{ return create_simple_widget(name, text, tooltip, E.input(type='checkbox'), def getter(w): # noqa: unused-local return bool(w.checked) , def setter(w, val): # noqa: unused-local w.checked = bool(val) , ) # }}} def lineedit(name, text, width=25, tooltip=None, suffix=None): # {{{ return create_simple_widget(name, text, tooltip, E.input(type='text', size=str(width)), def getter(w): # noqa: unused-local ans = w.value if ans and ans.strip(): return ans.strip() , def setter(w, val): # noqa: unused-local w.value = val or '' , suffix=suffix ) # }}} def float_spin(name, text, tooltip=None, step=0.1, min=0, max=100, unit=None): # {{{ f = E.input(type='number', step=str(step), min=str(min), max=str(max), required=True) defval = get_option_default_value(name) return create_simple_widget(name, text, tooltip, f, def getter(w): # noqa: unused-local try: return float(w.value) except: return defval , def setter(w, val): # noqa: unused-local w.value = str(float(val)) , suffix=unit ) # }}} def int_spin(name, text, tooltip=None, step=1, min=0, max=100, unit=None): # {{{ f = E.input(type='number', step=str(step), min=str(min), max=str(max), required=True) defval = get_option_default_value(name) return create_simple_widget(name, text, tooltip, f, def getter(w): # noqa: unused-local try: return int(w.value) except: return defval , def setter(w, val): # noqa: unused-local w.value = str(int(val)) , suffix=unit ) # }}} def choices(name, text, choices, tooltip): # {{{ f = E.select() if Array.isArray(choices): for key in choices: f.appendChild(E.option(key, value=key)) else: for key in choices: f.appendChild(E.option(choices[key], value=key)) return create_simple_widget(name, text, tooltip, f, def getter(w): # noqa: unused-local return w.value , def setter(w, val): # noqa: unused-local w.value = val ) # }}} def textarea(name, text, tooltip): # {{{ ans = create_simple_widget(name, text, tooltip, E.textarea(rows='30', cols='70'), def getter(w): # noqa: unused-local ans = w.value if ans and ans.strip(): return ans.strip() , def setter(w, val): # noqa: unused-local w.value = val or '' ) ans.classList.add('vertical') return ans # }}} def container_for_option(name): return document.getElementById(container_id).querySelector(f'[data-option-name="{name}"]') def get(name): return registry[name].get(container_for_option(name)) def set(name, val): registry[name].set(container_for_option(name), val) def set_disabled(name, val): registry[name].set_disabled(container_for_option(name), val) # Look & feel {{{ @ep def look_and_feel(container): def subhead(text): container.appendChild(E.div( style='border-bottom: solid 1px currentColor; margin-bottom: 1ex; max-width: 35em', E.b(sanitize_accelerator(text)))) subhead(_('&Fonts')) add_listener('disable_font_rescaling', def (name): disabled = get('disable_font_rescaling') for dname in 'font_size_mapping', 'base_font_size': set_disabled(dname, disabled) ) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('disable_font_rescaling', _('&Disable font size rescaling'))) g.appendChild(float_spin('base_font_size', _('Base font si&ze:'), max=50, unit='pt')) g.appendChild(lineedit('font_size_mapping', _('Font size &key:'))) g.appendChild(float_spin('minimum_line_height', _('Minim&um line height:'), max=900, unit='%')) g.appendChild(float_spin('line_height', _('Line hei&ght:'), unit='%')) g.appendChild(lineedit('embed_font_family', _('Embed font fami&ly:'))) g.appendChild(checkbox('embed_all_fonts', _('&Embed all fonts in document'))) g.appendChild(checkbox('subset_embedded_fonts', _('&Subset all embedded fonts'))) g.appendChild(checkbox('keep_ligatures', _('Keep &ligatures'))) subhead(_('Te&xt')) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(lineedit('input_encoding', _('I&nput character encoding:'))) g.appendChild(choices('change_justification', _('Text &justification:'), {'original': _('Original'), 'left': _('Left align'), 'justify': _('Justify text')} )) g.appendChild(checkbox('smarten_punctuation', _('Smarten &punctuation'))) g.appendChild(checkbox('unsmarten_punctuation', _('&Unsmarten punctuation'))) g.appendChild(checkbox('asciiize', _('&Transliterate Unicode characters to ASCII'))) subhead(_('Lay&out')) add_listener('remove_paragraph_spacing', def (name): disabled = get('remove_paragraph_spacing') set_disabled('remove_paragraph_spacing_indent_size', not disabled) ) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('remove_paragraph_spacing', _('Remove &spacing between paragraphs'))) g.appendChild(float_spin('remove_paragraph_spacing_indent_size', indent + _('I&ndent size:'), min=-0.1, unit='em')) g.appendChild(checkbox('insert_blank_line', _('Insert &blank line between paragraphs'))) g.appendChild(float_spin('insert_blank_line_size', indent + _('&Line size:'), unit='em')) g.appendChild(checkbox('linearize_tables', _('&Linearize tables'))) subhead(_('St&yling')) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(lineedit('filter_css', _('Filter style information'), 40)) container.appendChild(textarea('extra_css', 'E&xtra CSS')) # }}} # Heuristics {{{ @ep def heuristics(container): settings = v'[]' def add(func, name, text, **kw): g.appendChild(func(name, text, **kw)) settings.push(name) add_listener('enable_heuristics', def (name): disabled = not get('enable_heuristics') for dname in settings: set_disabled(dname, disabled) ) blurb = _( '<b>Heuristic processing</b> means that calibre will scan your book for common patterns and fix them.' ' As the name implies, this involves guesswork, which means that it could end up worsening the result' ' of a conversion, if calibre guesses wrong. Therefore, it is disabled by default. Often, if a conversion' ' does not turn out as you expect, turning on heuristics can improve matters. Read more about the various' ' heuristic processing options in the <a href="%s">User Manual</a>.''').replace( '%s', 'https://manual.calibre-ebook.com/conversion.html#heuristic-processing') container.appendChild(E.div(style='margin-bottom: 1ex')) safe_set_inner_html(container.lastChild, blurb) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('enable_heuristics', _('Enable &heuristic processing'))) add(checkbox, 'unwrap_lines', _('Unwrap lines')) add(float_spin, 'html_unwrap_factor', indent + _('Line &un-wrap factor:'), max=1, step=0.05) add(checkbox, 'markup_chapter_headings', _('Detect and markup unformatted chapter headings and sub headings')) add(checkbox, 'renumber_headings', _('Renumber sequences of <h1> or <h2> tags to prevent splitting')) add(checkbox, 'delete_blank_paragraphs', _('Delete blank lines between paragraphs')) add(checkbox, 'format_scene_breaks', _('Ensure scene breaks are consistently formatted')) add(lineedit, 'replace_scene_breaks', _('Rep&lace soft scene breaks:')) add(checkbox, 'dehyphenate', _('Remove unnecessary hyphens')) add(checkbox, 'italicize_common_cases', _('Italicize common words and patterns')) add(checkbox, 'fix_indents', _('Replace entity indents with CSS indents')) # }}} # Page setup {{{ @ep def page_setup(container): def show_profile_desc(name): profile = get(name) data = profiles.input if name is 'input_profile' else profiles.output profile = data[profile] container_for_option(name).parentNode.querySelector('[data-profile="{}"'.format( 'input' if name is 'input_profile' else 'output')).textContent = indent + profile.description add_listener('input_profile', show_profile_desc) add_listener('output_profile', show_profile_desc) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(float_spin('margin_left', _('Left page margin'), unit='pt', step=0.1, min=-1, max=200)) g.appendChild(float_spin('margin_top', _('Top page margin'), unit='pt', step=0.1, min=-1, max=200)) g.appendChild(float_spin('margin_right', _('Right page margin'), unit='pt', step=0.1, min=-1, max=200)) g.appendChild(float_spin('margin_bottom', _('Bottom page margin'), unit='pt', step=0.1, min=-1, max=200)) g.appendChild(choices('input_profile', _('&Input profile:'), {name: profiles.input[name].name for name in profiles.input})) g.appendChild(E.div(data_profile='input')) g.appendChild(choices('output_profile', _('&Output profile:'), {name: profiles.output[name].name for name in profiles.output})) g.appendChild(E.div(data_profile='output')) # }}} # Structure detection {{{ @ep def structure_detection(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(lineedit('chapter', _('Detect chapters at'), 50)) g.appendChild(choices('chapter_mark', _('Chap&ter mark:'), ['pagebreak', 'rule', 'both', 'none'])) g.appendChild(checkbox('remove_first_image', _('Remove first &image'))) g.appendChild(checkbox('remove_fake_margins', _('Remove &fake margins'))) g.appendChild(checkbox('add_alt_text_to_img', _('Add &alt text to images'))) g.appendChild(checkbox('insert_metadata', _('Insert metadata at start of book'))) g.appendChild(lineedit('page_breaks_before', _('Insert page breaks before'), 50)) g.appendChild(lineedit('start_reading_at', _('Start reading at'), 50)) # }}} # ToC {{{ @ep def toc(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('use_auto_toc', _('&Force use of auto-generated Table of Contents'))) g.appendChild(checkbox('no_chapters_in_toc', _('Do not add &detected chapters to the Table of Contents'))) g.appendChild(checkbox('duplicate_links_in_toc', _('Allow &duplicate links when creating the Table of Contents'))) g.appendChild(int_spin('max_toc_links', _('Number of &links to add to Table of Contents:'))) g.appendChild(int_spin('toc_threshold', _('Chapter &threshold:'))) g.appendChild(lineedit('toc_filter', _('TOC &filter:'))) g.appendChild(lineedit('level1_toc', _('Level &1 TOC (XPath expression):'))) g.appendChild(lineedit('level2_toc', _('Level &2 TOC (XPath expression):'))) g.appendChild(lineedit('level3_toc', _('Level &3 TOC (XPath expression):'))) # }}} # Search & replace {{{ @ep def search_and_replace(container): def add(val): c = container_for_option('search_replace') c.appendChild(E.div( class_='simple-group sr-instance', style='border-bottom: solid 1px currentColor; margin-bottom: 1ex', E.label( E.span(_('Search:')), E.input(type='text', name='search') ), E.label( E.span(_('Replace:')), E.input(type='text', name='replace') ), )) if val and val[0]: c.lastChild.querySelector('input[name="search"]').value = val[0] c.lastChild.querySelector('input[name="replace"]').value = val[1] return c.lastChild container.appendChild(E.div(data_option_name='search_replace')) ops = { 'get': def get(container): # noqa: unused-local ans = v'[]' for div in container.querySelectorAll('.sr-instance'): search, replace = div.querySelectorAll('input') if search.value: r = replace.value or '' # noqa: unused-local ans.push(v'[search.value, r]') return JSON.stringify(ans) , 'set': def set(container, encval): # noqa: unused-local try: vals = JSON.parse(encval) except: vals = v'[]' vals = vals or v'[]' clear(container) for val in vals: add(val) add() , 'set_disabled': def set_disabled(container, disabled): # noqa: unused-local pass } registry['search_replace'] = ops ops.set(container.lastChild, get_option_value('search_replace')) container.appendChild(E.div( create_button(_('Add'), 'plus', action=def(): add();) )) # }}} # Comic Input {{{ @ep def comic_input(container): settings = v'[]' def add(func, name, text, **kw): g.appendChild(func(name, text, **kw)) settings.push(name) add_listener('no_process', def (name): disabled = get('no_process') for dname in settings: set_disabled(dname, disabled) ) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('no_process', _('&Disable comic processing'))) add(checkbox, 'dont_grayscale', _('Disable conversion of images to &black and white')) add(checkbox, 'dont_add_comic_pages_to_toc', _('Don\'t add links to &pages to the Table of Contents for CBC files')) add(int_spin, 'colors', _('&Number of colors:'), max=256, step=8) add(lineedit, 'comic_image_size', _('Override image si&ze:')) add(checkbox, 'dont_normalize', _('Disable &normalize')) add(checkbox, 'keep_aspect_ratio', _('Keep &aspect ratio')) add(checkbox, 'dont_sharpen', _('Disable &sharpening')) add(checkbox, 'disable_trim', _('Disable &trimming')) add(checkbox, 'wide', _('&Wide')) add(checkbox, 'landscape', _('&Landscape')) add(checkbox, 'right2left', _('&Right to left')) add(checkbox, 'no_sort', _('Don\'t so&rt')) add(checkbox, 'despeckle', _('De&speckle')) g.appendChild(choices('output_format', _('O&utput format:'), v"['png', 'jpg']")) settings.push('output_format') # }}} # FB2 Input {{{ @ep def fb2_input(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('no_inline_fb2_toc', _('Do not insert a Table of Contents at the beginning of the book'))) # }}} # PDF Input {{{ @ep def pdf_input(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(float_spin('unwrap_factor', _('Line &un-wrapping factor:'), max=1, step=0.01)) g.appendChild(checkbox('no_images', _('No &images'))) g.appendChild(choices('pdf_engine', _('PDF &engine:'), {'calibre': 'calibre', 'pdftohtml': 'pdftohtml'})) g.appendChild(int_spin('pdf_header_skip', _('Remove headers at &top of page by:'), min=-1, max=999999, step=1)) g.appendChild(int_spin('pdf_footer_skip', _('Remove footers at &bottom of page by:'), min=-1, max=999999, step=1)) g.appendChild(lineedit('pdf_header_regex', _('Regular expression to remove &header at top of page:'))) g.appendChild(lineedit('pdf_footer_regex', _('Regular expression to remove &footer at bottom of page:'))) # }}} # RTF Input {{{ @ep def rtf_input(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('ignore_wmf', _('Ignore &WMF images in the RTF file'))) # }}} # DOCX Input {{{ @ep def docx_input(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('docx_no_cover', _('Do not try to autodetect a &cover from images in the document'))) g.appendChild(checkbox('docx_no_pagebreaks_between_notes', _('Do not add a page after every &endnote'))) g.appendChild(checkbox('docx_inline_subsup', _('Render &superscripts and subscripts so that they do not affect the line height'))) # }}} # TXT Input {{{ @ep def txt_input(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(choices('paragraph_type', _('Para&graph style:'), ui_data.paragraph_types)) g.appendChild(choices('formatting_type', _('Forma&tting style:'), ui_data.formatting_types)) g.appendChild(checkbox('preserve_spaces', _('Preserve &spaces'))) g.appendChild(checkbox('txt_in_remove_indents', _('Remove &indents at the beginning of lines'))) container.appendChild(E.div( style='margin-top: 1ex', _('Allowed Markdown extensions:'), E.div( style='margin-left: 1em; margin-top: 1ex', subset_choice('markdown_extensions', ui_data.md_extensions) ) )) # }}} # EPUB Output {{{ @ep def epub_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('dont_split_on_page_breaks', _('Do not &split on page breaks'))) g.appendChild(checkbox('no_default_epub_cover', _('No default &cover'))) g.appendChild(checkbox('epub_flatten', _('&Flatten EPUB file structure'))) g.appendChild(checkbox('no_svg_cover', _('No &SVG cover'))) g.appendChild(checkbox('preserve_cover_aspect_ratio', _('Preserve cover &aspect ratio'))) g.appendChild(checkbox('epub_inline_toc', _('Insert inline &Table of Contents'))) g.appendChild(checkbox('epub_toc_at_end', _('Put inserted Table of Contents at the &end of the book'))) g.appendChild(lineedit('toc_title', _('&Title for inserted ToC:'))) g.appendChild(int_spin('flow_size', _('Split files &larger than:'), unit='KB', max=1000000, step=20)) g.appendChild(lineedit('epub_max_image_size', _('Shrink &images larger than:'))) g.appendChild(choices('epub_version', _('EP&UB version:'), ui_data.versions)) # }}} # DOCX Output {{{ @ep def docx_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(choices('docx_page_size', _('Paper si&ze:'), ui_data.page_sizes)) g.appendChild(lineedit('docx_custom_page_size', _('&Custom size:'))) g.appendChild(float_spin('docx_page_margin_left', _('Page &left margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('docx_page_margin_top', _('Page &top margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('docx_page_margin_right', _('Page &right margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('docx_page_margin_bottom', _('Page &bottom margin'), unit='pt', min=-100, max=500)) g.appendChild(checkbox('docx_no_toc', _('Do not insert the &Table of Contents as a page at the start of the document'))) g.appendChild(checkbox('docx_no_cover', _('Do not insert &cover as image at start of document'))) g.appendChild(checkbox('preserve_cover_aspect_ratio', _('Preserve the aspect ratio of the image inserted as cover'))) # }}} # FB2 Output {{{ @ep def fb2_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(choices('sectionize', _('Sec&tionize:'), ui_data.sectionize)) g.appendChild(choices('fb2_genre', _('&Genre:'), ui_data.genres)) # }}} # LRF Output {{{ @ep def lrf_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('autorotation', _('Enable &auto-rotation of wide images'))) g.appendChild(float_spin('wordspace', _('&Wordspace:'), min=1, max=20, unit='pt')) g.appendChild(float_spin('minimum_indent', _('Minim&um para. indent:'), unit='pt')) g.appendChild(checkbox('render_tables_as_images', _('Render &tables as images'))) g.appendChild(float_spin( 'text_size_multiplier_for_rendered_tables', indent + _('Text size multiplier for text in rendered tables:'), step=0.01)) g.appendChild(checkbox('header', _('Add &header'))) g.appendChild(float_spin('header_separation', indent + _('Header &separation:'), unit='pt')) g.appendChild(lineedit('header_format', indent + _('Header &format:'))) g.appendChild(lineedit('serif_family', _('Serif fon&t family:'))) g.appendChild(lineedit('sans_family', _('Sans-serif font fami&ly:'))) g.appendChild(lineedit('mono_family', _('&Monospace font family:'))) # }}} # MOBI Output {{{ @ep def mobi_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('no_inline_toc', _('Do not add &Table of Contents to book'))) g.appendChild(lineedit('toc_title', indent + _('&Title for Table of Contents:'))) g.appendChild(checkbox('mobi_toc_at_start', _('Put generated Table of Contents at &start of book instead of end'))) g.appendChild(checkbox('mobi_ignore_margins', _('Ignore &margins'))) g.appendChild(checkbox('prefer_author_sort', _('Use author &sort for author'))) g.appendChild(checkbox('mobi_keep_original_images', _('Do not convert all images to &JPEG (may result in images not working in older viewers)'))) g.appendChild(checkbox('dont_compress', _('Disable &compression of the file contents'))) g.appendChild(choices('mobi_file_type', _('MOBI fi&le type:'), ui_data.file_types)) g.appendChild(lineedit('personal_doc', _('Personal Doc tag:'))) g.appendChild(checkbox('share_not_sync', _('Enable &sharing of book content via Facebook, etc. WARNING: Disables last read syncing'))) # }}} # AZW3 Output {{{ @ep def azw3_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('no_inline_toc', _('Do not add &Table of Contents to book'))) g.appendChild(lineedit('toc_title', indent + _('&Title for Table of Contents:'))) g.appendChild(checkbox('mobi_toc_at_start', _('Put generated Table of Contents at &start of book instead of end'))) g.appendChild(checkbox('prefer_author_sort', _('Use author &sort for author'))) g.appendChild(checkbox('dont_compress', _('Disable &compression of the file contents'))) g.appendChild(checkbox('share_not_sync', _('Enable &sharing of book content via Facebook, etc. WARNING: Disables last read syncing'))) # }}} # PDB Output {{{ @ep def pdb_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(choices('format', _('Forma&t:'), ui_data.formats)) g.appendChild(lineedit('pdb_output_encoding', _('O&utput encoding:'))) g.appendChild(checkbox('inline_toc', _('&Inline TOC'))) # }}} # PDF Output {{{ @ep def pdf_output(container): add_listener('use_profile_size', def (name): disabled = get('use_profile_size') for dname in 'paper_size', 'custom_size', 'unit': set_disabled(dname, disabled) ) add_listener('pdf_use_document_margins', def (name): disabled = get('pdf_use_document_margins') for dname in 'left', 'top', 'right', 'bottom': set_disabled(f'pdf_page_margin_{dname}', disabled) ) g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('use_profile_size', _('&Use the paper size set in output profile'))) g.appendChild(choices('paper_size', indent + _('&Paper size:'), ui_data.paper_sizes)) g.appendChild(lineedit('custom_size', indent + _('&Custom size:'))) g.appendChild(choices('unit', indent + _('Custom size unit:'), ui_data.units)) g.appendChild(checkbox('pdf_no_cover', _('Discard book &cover'))) g.appendChild(checkbox('preserve_cover_aspect_ratio', _('Preserve &aspect ratio of cover'))) g.appendChild(checkbox('pdf_page_numbers', _('Add page &numbers to the bottom of every page'))) g.appendChild(checkbox('pdf_hyphenate', _('&Break long words at the end of lines'))) g.appendChild(checkbox('pdf_add_toc', _('Add a printable &Table of Contents at the end'))) g.appendChild(lineedit('toc_title', indent + _('&Title for ToC:'))) g.appendChild(lineedit('pdf_serif_family', _('Serif famil&y:'))) g.appendChild(lineedit('pdf_sans_family', _('Sans fami&ly:'))) g.appendChild(lineedit('pdf_mono_family', _('&Monospace family:'))) g.appendChild(choices('pdf_standard_font', _('S&tandard font:'), ui_data.font_types)) g.appendChild(int_spin('pdf_default_font_size', _('Default font si&ze:'), unit='px')) g.appendChild(int_spin('pdf_mono_font_size', _('Default font si&ze:'), unit='px')) g.appendChild(lineedit('pdf_page_number_map', _('Page number &map:'))) g.appendChild(checkbox('pdf_use_document_margins', _('Use page margins from the &document being converted'))) g.appendChild(float_spin('pdf_page_margin_left', indent + _('Left page margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('pdf_page_margin_top', indent + _('Top page margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('pdf_page_margin_right', indent + _('Right page margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('pdf_page_margin_bottom', indent + _('Bottom page margin'), unit='pt', min=-100, max=500)) g.appendChild(float_spin('pdf_odd_even_offset', indent + _('Odd/even offset'), unit='pt', min=-500, max=500)) g.appendChild(lineedit('pdf_header_template', _('&Header template:'))) g.appendChild(lineedit('pdf_footer_template', _('&Footer template:'))) # }}} # PMLZ Output {{{ @ep def pml_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(lineedit('pml_output_encoding', _('O&utput encoding:'))) g.appendChild(checkbox('inline_toc', _('&Inline TOC'))) g.appendChild(checkbox('full_image_depth', _('Do not &reduce image size and depth'))) # }}} # RB Output {{{ @ep def rb_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('inline_toc', _('&Inline TOC'))) # }}} # TXT Output {{{ @ep def txt_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(lineedit('txt_output_encoding', _('O&utput encoding:'))) g.appendChild(choices('newline', _('&Line ending style:'), ui_data.newline_types)) g.appendChild(choices('txt_output_formatting', _('Forma&tting:'), ui_data.formatting_types)) g = E.div(E.div(_('Options for plain text output:')), E.div(class_='simple-group', style='margin-left: 1rem; margin-top: 1ex')) container.appendChild(g) g = g.lastChild g.appendChild(checkbox('inline_toc', _('&Inline TOC'))) g.appendChild(int_spin('max_line_length', _('&Maximum line length:'), max=1000)) g.appendChild(checkbox('force_max_line_length', _('Force maximum line &length'))) g = E.div(E.div(_('Options for Markdown and TexTile output:')), E.div(class_='simple-group', style='margin-left: 1rem; margin-top: 1ex')) container.appendChild(g) g = g.lastChild g.appendChild(checkbox('keep_links', _('Do not remove links (<a> tags) before processing'))) g.appendChild(checkbox('keep_image_references', _('Do not remove image &references before processing'))) g.appendChild(checkbox('keep_color', _('Keep text &color, when possible'))) @ep def txtz_output(container): return txt_output(container) # }}} # HTMLZ Output {{{ @ep def htmlz_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(choices('htmlz_css_type', _('How to handle &CSS'), ui_data.css_choices)) g.appendChild(choices('htmlz_class_style', _('How to handle &CSS'), ui_data.sheet_choices)) g.appendChild(checkbox('htmlz_title_filename', _('Use book title as the filename for the HTML file'))) # }}} # SNB Output {{{ @ep def snb_output(container): g = E.div(class_='simple-group') container.appendChild(g) g.appendChild(checkbox('snb_insert_empty_line', _('Insert &empty line between paragraphs'))) g.appendChild(checkbox('snb_dont_indent_first_line', _('Don\'t indent the &first line for each paragraph'))) g.appendChild(checkbox('snb_hide_chapter_name', _('Hide &chapter name'))) g.appendChild(checkbox('snb_full_screen', _('Optimize for full-&screen mode'))) # }}} def restore_defaults(): for setting in registry: set(setting, get_option_default_value(setting)) def create_option_group(group_name, ui_data_, profiles_, container, get_option_value_, get_option_default_value_, is_option_disabled_, get_option_help_, on_close): nonlocal get_option_value, get_option_default_value, is_option_disabled, container_id, registry, listeners, get_option_help, profiles, ui_data get_option_value, get_option_default_value, is_option_disabled, get_option_help = get_option_value_, get_option_default_value_, is_option_disabled_, get_option_help_ profiles, ui_data = profiles_, ui_data_ registry = {} listeners = {} container_id = ensure_id(container) container.classList.add(CLASS_NAME) entry_points[group_name](container) container.appendChild(E.div( style='margin-top: 2ex; padding-top: 2ex; border-top: solid 1px currentColor', create_button(_('Done'), action=on_close), '\xa0\xa0', create_button(_('Restore defaults'), action=restore_defaults), )) def commit_changes(set_option_value): for name in registry: set_option_value(name, get(name))
33,994
Python
.py
688
43.478198
169
0.65246
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,492
library_data.pyj
kovidgoyal_calibre/src/pyj/book_list/library_data.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from gettext import gettext as _ from ajax import absolute_path, ajax from book_list.globals import get_session_data from lru_cache import LRUCache from session import get_interface_data from utils import parse_url_params load_status = {'loading':True, 'ok':False, 'error_html':None, 'current_fetch': None, 'http_error_code': 0} library_data = {'metadata':{}, 'previous_book_ids': v'[]', 'force_refresh': False, 'bools_are_tristate': True} def current_library_id(): q = parse_url_params() return q.library_id or get_interface_data().default_library_id def all_libraries(): interface_data = get_interface_data() lids = sorted(interface_data.library_map, key=def(x): return interface_data.library_map[x];) return [(lid, interface_data.library_map[lid]) for lid in lids] def current_virtual_library(): q = parse_url_params() return q.vl or '' def last_virtual_library_for(library_id): if last_virtual_library_for.library_id is library_id: return last_virtual_library_for.vl or '' return '' def url_books_query(sd): q = parse_url_params() sd = sd or get_session_data() lid = current_library_id() return { 'library_id': lid, 'sort': q.sort or sd.get_library_option(lid, 'sort'), 'search': q.search, 'vl': current_virtual_library(), } def loaded_books_query(): sr = library_data.search_result sort = None if sr: sort = [s + '.' + o for s, o in zip(sr.sort.split(','), sr.sort_order.split(','))].join(',') return { 'library_id': sr.library_id if sr else None, 'sort': sort, 'search': sr?.query, 'vl':sr?.vl } def current_sorted_field(): if library_data.search_result: return library_data.search_result.sort, library_data.search_result.sort_order sort = url_books_query().sort.partition(',')[0] csf = sort.partition('.')[0] csfo = sort.partition('.')[2] or 'asc' return csf, csfo def all_virtual_libraries(): return library_data.virtual_libraries or {} def update_library_data(data): load_status.loading = False load_status.ok = True load_status.error_html = None load_status.http_error_code = 0 library_data.previous_book_ids = v'[]' if library_data.for_library is not current_library_id(): library_data.field_names = {} library_data.for_library = current_library_id() for key in 'search_result sortable_fields field_metadata metadata virtual_libraries book_display_fields bools_are_tristate book_details_vertical_categories fts_enabled fields_that_support_notes'.split(' '): library_data[key] = data[key] sr = library_data.search_result if sr: last_virtual_library_for.library_id = sr.library_id last_virtual_library_for.vl = sr.vl else: last_virtual_library_for.library_id = None last_virtual_library_for.vl = None def add_more_books(data): for key in data.metadata: library_data.metadata[key] = data.metadata[key] sr = library_data.search_result if sr and sr.book_ids and sr.book_ids.length > 0: library_data.previous_book_ids = library_data.previous_book_ids.concat(sr.book_ids) library_data.search_result = data.search_result def current_book_ids(): return library_data.previous_book_ids.concat(library_data.search_result.book_ids) def remove_from_array(array, item): while True: idx = array.indexOf(item) if idx < 0: break array.splice(idx, 1) def remove_book(book_id): book_id = int(book_id) if library_data.previous_book_ids: remove_from_array(library_data.previous_book_ids, book_id) if library_data.search_result?.book_ids: remove_from_array(library_data.search_result.book_ids, book_id) def book_after(book_id, delta): if not delta: delta = 1 ids = current_book_ids() idx = ids.indexOf(int(book_id)) if idx > -1: new_idx = (idx + ids.length + delta) % ids.length return ids[new_idx] def on_data_loaded(end_type, xhr, ev): load_status.current_fetch = None def bad_load(msg): load_status.ok = False load_status.loading = False load_status.error_html = msg or xhr.error_html load_status.http_error_code = xhr.status if end_type is 'load': data = JSON.parse(xhr.responseText) if data.bad_restriction: bad_load(_('The library restriction for the current user is invalid: {}').format(data.bad_restriction)) else: update_library_data(data) sd = get_session_data() q = loaded_books_query() sd.set_library_option(q.library_id, 'sort', q.sort) elif end_type is 'abort': pass else: bad_load() def fetch_init_data(): if load_status.current_fetch: load_status.current_fetch.abort() query = url_books_query() load_status.loading = True load_status.ok = False load_status.error_html = None load_status.http_error_code = 0 load_status.current_fetch = ajax('interface-data/books-init', on_data_loaded, query=query) load_status.current_fetch.send() def field_names_received(library_id, field, proceed, end_type, xhr, event): if library_id is not current_library_id(): return if end_type is not 'load': if end_type is not 'abort': proceed(False, field, xhr.error_html) return try: names = JSON.parse(xhr.responseText) except Exception: import traceback traceback.print_exc() proceed(False, field, 'Invalid JSON from server') return library_data.field_names[field] = { 'loading': False, 'loaded': True, 'last_updated_at': Date.now(), 'names': names } proceed(True, field, names) def field_names_for(field, proceed): if library_data.field_names[field] and library_data.field_names[field].loaded: proceed(True, field, library_data.field_names[field].names) if not library_data.field_names[field] or (not library_data.field_names[field].loading and Date.now() - library_data.field_names[field].last_updated_at > 3600 * 1000): ajax(f'interface-data/field-names/{encodeURIComponent(field)}', field_names_received.bind(None, current_library_id(), field, proceed), query={'library_id': current_library_id()}).send() if not library_data.field_names[field]: library_data.field_names[field] = {'last_updated_at': 0, 'loaded': False, 'names': v'[]'} library_data.field_names[field].loading = True def thumbnail_url(book_id, width, height): query = f'sz={Math.ceil(width * window.devicePixelRatio)}x{Math.ceil(height * window.devicePixelRatio)}' prefix = f'get/thumb/{book_id}' lid = loaded_books_query().library_id or current_library_id() if lid: prefix += f'/{lid}' return absolute_path(f'{prefix}?{query}') def cover_url(book_id): lid = current_library_id() return absolute_path(f'get/cover/{book_id}/{lid}') def download_url(book_id, fmt, content_disposition): lid = current_library_id() ans = absolute_path(f'get/{fmt}/{book_id}/{lid}') if content_disposition: ans += f'?content_disposition={content_disposition}' return ans def book_metadata(book_id): return library_data.metadata[book_id] def set_book_metadata(book_id, value): library_data.metadata[book_id] = value def loaded_book_ids(): return Object.keys(library_data.metadata) def force_refresh_on_next_load(): library_data.force_refresh = True def ensure_current_library_data(): fr = library_data.force_refresh library_data.force_refresh = False def is_same(a, b): if not a and not b: return True return a is b if fr: matches = False else: q = url_books_query() loaded = loaded_books_query() matches = True for key in q: if not is_same(q[key], loaded[key]): matches = False break if not matches: fetch_init_data() class ThumbnailCache: # Cache to prevent browser from issuing HTTP requests when thumbnails pages # are destroyed/rebuilt. def __init__(self, size=256): self.cache = LRUCache(size) def get(self, book_id, width, height, callback): url = thumbnail_url(book_id, width, height) item = self.cache.get(url) if not item: img = new Image() item = {'img':img, 'load_type':None, 'callbacks':v'[callback]'} img.onerror = self.load_finished.bind(None, item, 'error') img.onload = self.load_finished.bind(None, item, 'load') img.onabort = self.load_finished.bind(None, item, 'abort') img.dataset.bookId = book_id + '' img.src = url self.cache.set(url, item) return img if item.load_type is None: if item.callbacks.indexOf(callback) < 0: item.callbacks.push(callback) else: callback(item.img, item.load_type) return item.img def load_finished(self, item, load_type): item.load_type = load_type img = item.img img.onload = img.onerror = img.onabort = None for callback in item.callbacks: callback(img, load_type) thumbnail_cache = ThumbnailCache() def sync_library_books(library_id, to_sync, callback): url = f'book-get-annotations/{library_id}/' which = v'[]' lrmap = {} for key, last_read in to_sync: library_id, book_id, fmt = key fmt = fmt.upper() which.push(f'{book_id}-{fmt}') lrmap[f'{book_id}:{fmt}'] = last_read url += which.join('_') ajax(url, callback.bind(None, library_id, lrmap)).send()
10,003
Python
.py
246
33.898374
210
0.650872
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,493
router.pyj
kovidgoyal_calibre/src/pyj/book_list/router.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from ajax import absolute_path, encode_query from elementmaker import E from gettext import gettext as _ from book_list.constants import book_list_container_id, read_book_container_id from book_list.globals import get_current_query, get_session_data from book_list.library_data import current_library_id from modals import close_all_modals from utils import ( encode_query_with_path, parse_url_params, request_full_screen, safe_set_inner_html ) mode_handlers = {} default_mode_handler = None read_book_mode = 'read_book' def set_mode_handler(mode, handler): mode_handlers[mode] = handler def set_default_mode_handler(handler): nonlocal default_mode_handler default_mode_handler = handler def update_window_title(subtitle, title='calibre', sep=' :: '): extra = (sep + subtitle) if subtitle else '' document.title = title + extra def is_reading_book(): cq = get_current_query() return cq and cq.mode is read_book_mode def apply_mode(): divid = read_book_container_id if is_reading_book() else book_list_container_id for div in document.getElementById(divid).parentNode.childNodes: div.style.display = 'block' if div.id is divid else 'none' def apply_url(ignore_handler): close_all_modals() # needed to close any error dialogs, etc when clicking back or forward in the browser or using push_state() to go to a new page data = parse_url_params() data.mode = data.mode or 'book_list' get_current_query(data) apply_mode() if not ignore_handler: handler = mode_handlers[data.mode] or default_mode_handler handler(data) def request_full_screen_if_wanted(): opt = get_session_data().get('fullscreen_when_opening') has_touch = v'"ontouchstart" in window' at_left = window.screenLeft is 0 likely_wants_fullscreen = has_touch and at_left if (opt is 'auto' and likely_wants_fullscreen) or opt is 'always': # Note that full screen requests only succeed if they are in response to a # user action like clicking/tapping a button request_full_screen() def open_book(book_id, fmt, library_id=None, replace=False, extra_query=None): request_full_screen_if_wanted() library_id = library_id or current_library_id() q = {'book_id':book_id, 'fmt':fmt, 'library_id':library_id} if extra_query and jstype(extra_query) is 'object': Object.assign(q, extra_query) push_state(q, replace=replace, mode=read_book_mode) def open_book_url(book_id, fmt, extra_query): lid = current_library_id() ans = absolute_path('') q = {'book_id':book_id, 'fmt':fmt, 'mode': read_book_mode} if lid: q.library_id = lid if extra_query: Object.assign(q, extra_query) return ans + encode_query(q, '#') def show_note(field, item_id, item_value, replace=False, library_id=None, close_action='back', panel='show_note'): lid = library_id or current_library_id() q = {'field': field, 'item':item_value + '', 'item_id': (item_id or '')+ '', 'panel': panel} if panel is 'show_note': q.close_action = close_action if lid: q.library_id = lid push_state(q, replace=replace) def push_state(query, replace=False, mode='book_list', call_handler=True): query = {k:query[k] for k in query if query[k]} if mode is not 'book_list': query.mode = mode query = encode_query_with_path(query) if replace: window.history.replaceState(None, '', query) else: window.history.pushState(None, '', query) push_state.history_count += 1 apply_url(not call_handler) push_state.history_count = 0 def on_pop_state(ev): push_state.history_count = max(0, push_state.history_count - 1) apply_url() def back(): if push_state.history_count > 0: window.history.back() else: cq = get_current_query() handler = mode_handlers[cq.mode] or default_mode_handler if handler.back_from_current: q = handler.back_from_current(cq) else: q = {} push_state(q, replace=True) def home(replace=False): push_state({}) def report_a_load_failure(container, msg, error_html): err = E.div() safe_set_inner_html(err, error_html) container.appendChild(E.div( style='margin: 1ex 1em', E.div(msg), err, E.div( style='margin-top: 1em; border-top: solid 1px currentColor; padding-top: 1ex;', E.a(onclick=def(): home(replace=True);, href='javascript: void(0)', class_='blue-link', _('Go back to the home page'))) ), )
4,751
Python
.py
114
36.280702
151
0.678758
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,494
add.pyj
kovidgoyal_calibre/src/pyj/book_list/add.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from ajax import ajax_send_file from book_list.library_data import force_refresh_on_next_load, loaded_books_query from book_list.router import back from book_list.top_bar import create_top_bar from book_list.ui import query_as_href, show_panel from dom import clear, ensure_id from file_uploads import ( update_status_widget, upload_files_widget, upload_status_widget ) from session import get_interface_data from utils import safe_set_inner_html from widgets import create_button, enable_escape_key state = { 'in_progress': False, 'container_id': None, 'counter': 0, 'number': 0, 'fake_send': False, 'transfers': v'[]', } def cancel_in_progress(): for xhr in state.transfers: xhr.abort() state.transfers = v'[]' state.in_progress = False def on_close(): cancel_in_progress() back() def get_job_container(container_id, job_id): container = document.getElementById(container_id) if not container: return return container.querySelector(f'[data-job="{job_id}"]') def on_progress(container_id, job_id, loaded, total, xhr): container = get_job_container(container_id, job_id) if container is None: return if total: update_status_widget(container, loaded, total) def list_added_book(container, data): container.appendChild(E.h3(E.b(data.title), E.span(' ' + _('by') + ' '), E.i(' & '.join(data.authors)))) container.appendChild(E.span(_('Added successfully') + ' ')) q = {'book_id': data.book_id + ''} a = create_button(_('Open'), action=query_as_href(q, 'book_details')) if state.number > 1: a.setAttribute('target', '_blank') else: a.addEventListener('click', def(e): e.preventDefault() show_panel('book_details', {'book_id': data.book_id + ''}, True) ) container.appendChild(a) def list_duplicate_book(container, container_id, job_id, data, file): container.appendChild(E.div( style="padding: 1rem 1ex", _('A book with the title "{0}" already exists in the library.' ).format(data.title))) b = create_button(_('Add anyway'), action=def(): c = get_job_container(container_id, job_id) clear(c) w = upload_status_widget(file.name, job_id) c.appendChild(w) send_file(file, container_id, job_id, True) ) def list_duplicates(): ans = E.ol(style='margin-left: 2rem') for item in data.duplicates: ans.appendChild(E.li(_('{0} by {1}').format(item.title, ' & '.join(item.authors)))) return ans container.appendChild(b) container.appendChild(E.div( style='margin: 1rem 1ex; border-top: solid 1px currentColor; padding-top: 1ex', _('The book you are trying to add is:'), E.span(' ', E.b(data.title), ' ', _('by'), ' ', E.i(' & '.join(data.authors))), _('. Books already in the library with that title are:'), E.div(style='padding-top:1ex', list_duplicates()) )) def write_access_error(msg, xhr): html = msg + '<br>' if xhr.status is 403: un = get_interface_data().username if un: html += _('You are not allowed to make changes to the library') + '<hr>' else: html += _('You must be logged in to make changes to the library') + '<hr>' return html + '<br>' + xhr.error_html def on_complete(container_id, job_id, end_type, xhr, ev): idx = state.transfers.indexOf(xhr) if idx > -1: state.transfers.splice(idx, 1) container = get_job_container(container_id, job_id) if container is None: return clear(container) if end_type is 'load': data = JSON.parse(xhr.responseText) if data.book_id: list_added_book(container, data) force_refresh_on_next_load() else: list_duplicate_book(container, container_id, job_id, data, this) elif end_type is 'abort': return else: html = write_access_error(_('Failed to upload the file: {}').format(this.name), xhr) safe_set_inner_html(container, html) def fake_send(container_id, job_id): container = get_job_container(container_id, job_id) prev = parseInt(container.dataset.fake or '0') container.dataset.fake = prev + 10 update_status_widget(container, container.dataset.fake, 100) if parseInt(container.dataset.fake or '0') < 100: setTimeout(fake_send.bind(None, container_id, job_id), 1000) def send_file(file, container_id, job_id, add_duplicates): lid = loaded_books_query().library_id ad = 'y' if add_duplicates else 'n' xhr = ajax_send_file( f'cdb/add-book/{job_id}/{ad}/{encodeURIComponent(file.name)}/{lid}', file, on_complete.bind(file, container_id, job_id), on_progress.bind(None, container_id, job_id)) state.transfers.push(xhr) return xhr def files_chosen(container_id, files): container = document.getElementById(container_id) if not container: return state.number = 0 for file in files: state.counter += 1 state.number += 1 job_id = state.counter w = upload_status_widget(file.name, job_id) container.appendChild(w) w.style.borderBottom = 'solid 1px currentColor' if state.fake_send: setTimeout(fake_send.bind(None, container_id, job_id), 100) else: send_file(file, container_id, job_id) def add_books_panel(container_id): container = document.getElementById(container_id) create_top_bar(container, title=_('Add books'), action=on_close, icon='close') cancel_in_progress() state.in_progress = True state.container_id = container_id state.fake_send = False enable_escape_key(container, on_close) return upload_files_widget(container, files_chosen) def develop(container): add_books_panel(ensure_id(container))
6,117
Python
.py
152
34.171053
128
0.65487
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,495
fts.pyj
kovidgoyal_calibre/src/pyj/book_list/fts.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import ajax, ajax_send from book_list.cover_grid import THUMBNAIL_MAX_HEIGHT, THUMBNAIL_MAX_WIDTH from book_list.globals import get_current_query, get_session_data from book_list.library_data import current_library_id, download_url, library_data from book_list.router import back, home, open_book_url, push_state from book_list.top_bar import create_top_bar from book_list.ui import query_as_href, set_panel_handler from book_list.views import create_image from complete import create_search_bar from dom import add_extra_css, clear, set_css, svgicon from gettext import gettext as _ from modals import create_custom_dialog, error_dialog, info_dialog, question_dialog from widgets import create_button, create_spinner overall_container_id = '' current_fts_query = {} query_id_counter = 0 add_extra_css(def(): sel = '.fts-help-display ' style = f'{sel} ' + '{ padding-top: 0.5ex }\n' style += f'{sel} div' + ' { margin-top: 0.5ex }\n' style += f'{sel} .h' + ' { font-weight: bold; padding-bottom: 0.25ex }\n' style += f'{sel} .bq' + ' { margin-left: 1em; margin-top: 0.5ex; margin-bottom: 0.5ex; font-style: italic }\n' style += f'{sel} p' + ' { margin: 0}\n' style += '.fts-highlight-match { font-style: italic; font-weight: bold }\n' return style ) def component(name): c = document.getElementById(overall_container_id) if c: return c.querySelector(f'[data-component="{name}"]') def showing_search_panel(): c = component('search') return bool(c and c.style.display is 'block') def make_new_fts_query(q): nonlocal current_fts_query, query_id_counter query_id_counter += 1 current_fts_query = {'query_id': query_id_counter + ''} if current_library_id(): current_fts_query.library_id = current_library_id() Object.assign(current_fts_query, q) xhr = ajax('fts/search', on_initial_fts_fetched, query=current_fts_query, bypass_cache=True) xhr.send() def enable_indexing(): def on_response(end_type, xhr, ev): if end_type is 'abort' or not showing_search_panel(): return if end_type is not 'load': if xhr.status is 403: return error_dialog(_('Permission denied'), _( 'You do not have permission to enable indexing. Only logged in users with write permission are allowed.'), xhr.error_html) return error_dialog(_('Failed to enable indexing'), _('Enabling indexing failed. Click "Show details" for more information.'), xhr.error_html) library_data.fts_enabled = True info_dialog(_('Indexing enabled'), _('Indexing of this library has been enabled. Depending on library size it can take a long time to index all books.')) ajax_send(f'fts/indexing', True, on_response) def report_fts_not_enabled(): question_dialog(_('Full text searching disabled'), _( 'Full text search indexing has not been enabled for this library. Once enabled, indexing' ' will take some time to complete after which searching will work. Enable indexing?'), def (yes): if yes: enable_indexing() ) def on_initial_fts_fetched(end_type, xhr, ev): if end_type is 'abort' or not showing_search_panel(): return if end_type is not 'load': clear_to_waiting_for_results(_('No matches found')) if xhr.status is 428: return report_fts_not_enabled() return error_dialog(_('Failed to search'), _('The search failed. Click "Show details" for more information.'), xhr.error_html) try: results = JSON.parse(xhr.responseText) except Exception as err: return error_dialog(_('Server error'), _('Failed to parse search response from server.'), err + '') if results.query_id + '' is not current_fts_query.query_id: return current_fts_query.results = results show_initial_results() def execute_search_interactive(): nonlocal current_fts_query query = component('query').querySelector('input').value if not query or query.length < 1: error_dialog(_('No search query specified'), _('A search word/phrase must be specified before attempting to search')) clear_to_help() return q = get_current_query() q.fts_panel = 'search' q.fts_query = query q.fts_use_stemming = 'y' if component('related_words').checked else 'n' if q.restricted is 'y': q.restriction = component('restrict').querySelector('input').value current_fts_query = {} push_state(q, replace=True) def build_search_page(): # search input container container = component('search') clear(container) search_button = create_button(_('Search'), icon='search', tooltip=_('Do the search')) search_bar = create_search_bar(execute_search_interactive, 'search-books-fts', tooltip=_('Search for books'), placeholder=_('Enter words to search for'), button=search_button) set_css(search_bar, flex_grow='10', margin_right='0.5em') search_bar.dataset.component = 'query' container.appendChild(E.div(style="display: flex; width: 100%; align-items: center", svgicon('fts'), E.span('\xa0'), search_bar, search_button)) sd = get_session_data() related_words = E.label(E.input( type="checkbox", data_component="related_words", checked=bool(sd.get('fts_related_words'))), onchange=def(): sd = get_session_data() rw = bool(component('related_words').checked) if rw is not sd.get('fts_related_words'): get_session_data().set('fts_related_words', rw) , ' ' + _('Match on related words'), title=_( 'With this option searching for words will also match on any related words (supported in several languages). For' ' example, in the English language: {0} matches {1} and {2} as well').format( 'correction', 'correcting', 'corrected') ) container.appendChild(E.div(style="padding-top: 1ex;", related_words)) restrict_bar = create_search_bar(execute_search_interactive, 'search-books-fts-restrict', tooltip=_('Restrict the results to only books matching this query'), placeholder=_('Restrict to books matching...')) set_css(restrict_bar, flex_grow='10', margin_right='0.5em') restrict_bar.dataset.component = 'restrict' container.appendChild(E.div(style="padding-top: 1ex; display: flex; width: 100%; align-items: center", svgicon('search'), E.span('\xa0'), restrict_bar)) # Search help container.appendChild(E.div(style='border-top: 1px currentColor solid; margin-top: 1ex', data_component='results')) def clear_to_waiting_for_results(msg): container = component('results') if not container: return clear(container) msg = msg or (_('Searching, please wait') + '…') container.appendChild(E.div( style='margin: auto; width: 100%; text-align: center; margin-top: 4ex', create_spinner(), '\xa0' + msg )) def toggle_restrict(): container = component('restrict') if not container: return q = get_current_query() q.restricted = 'n' if q.restricted is 'y' else 'y' push_state(q, replace=True) def clear_to_help(): container = component('results') if not container: return clear(container) container.appendChild(E.div(class_='fts-help-display')) restrict = get_current_query().restricted is 'y' container.appendChild(E.div( style='margin-top: 1ex', E.a(_('Re-index all books in this library'), class_='blue-link', href='javascript:void(0)', onclick=reindex_all), E.span('\xa0\xa0'), E.a(_('Disable full text search'), class_='blue-link', href='javascript:void(0)', onclick=disable_fts), E.span('\xa0\xa0'), E.a( _('Search all books') if restrict else _('Search a subset of books'), class_='blue-link', href='javascript:void(0)', onclick=toggle_restrict ), )) container = container.firstChild fts_url = 'https://www.sqlite.org/fts5.html#full_text_query_syntax' html = _(''' <div class="h">Search for single words</div> <p>Simply type the word:</p> <div class="bq">awesome<br>calibre</div> <div class="h">Search for phrases</div> <p>Enclose the phrase in quotes:</p> <div class="bq">"early run"<br>"song of love"</div> <div class="h">Boolean searches</div> <div class="bq">(calibre AND ebook) NOT gun<br>simple NOT ("high bar" OR hard)</div> <div class="h">Phrases near each other</div> <div class="bq">NEAR("people" "in Asia" "try")<br>NEAR("Kovid" "calibre", 30)</div> <p>Here, 30 is the most words allowed between near groups. Defaults to 10 when unspecified.</p> <div style="margin-top: 1em"><a href="{fts_url}">Complete syntax reference</a></div> ''' + '</div>').format(fts_url=fts_url) container.innerHTML = html a = container.querySelector('a[href]') a.setAttribute('target', '_new') a.classList.add('blue-link') def apply_search_panel_state(): q = get_current_query() ftsq = {'query': q.fts_query or '', 'use_stemming': q.fts_use_stemming or 'y', 'restriction': q.restriction if q.restricted is 'y' else ''} component('query').querySelector('input').value = ftsq.query component('related_words').checked = ftsq.use_stemming is 'y' r = component('restrict') r.parentNode.style.display = 'flex' if ftsq.restriction is not '' else 'none' r.querySelector('input').value = q.restriction or '' if not ftsq.query: clear_to_help() return if current_fts_query.query is not ftsq.query or current_fts_query.use_stemming is not ftsq.use_stemming or current_fts_query.restriction is not ftsq.restriction: make_new_fts_query(ftsq) clear_to_waiting_for_results(_('Searching for {}, please wait…').format(ftsq.query)) return show_initial_results() def open_format(book_id, fmt): snippets = current_fts_query.results?.snippets if snippets: snippets = snippets[book_id] text = '' if snippets and fmt is not 'PDF': for s in snippets: if s.formats.indexOf(fmt) > -1: text = s.text break url = open_book_url(book_id, fmt) if fmt is 'PDF': url = download_url(book_id, fmt, 'inline') w = window.open(url, '_blank') if text: text = str.strip(text, '…').replaceAll('\x1c', '').replaceAll('\x1e', '') w.read_book_initial_open_search_text = {'text': text, 'query': current_fts_query.query} def reindex_book(book_id): def on_response(end_type, xhr, ev): if end_type is 'abort' or not showing_search_panel(): return if end_type is not 'load': if xhr.status is 403: return error_dialog(_('Permission denied'), _( 'You do not have permission to re-index books. Only logged in users with write permission are allowed to re-index'), xhr.error_html) return error_dialog(_('Failed to re-index'), _('Re-indexing the book failed. Click "Show details" for more information.'), xhr.error_html) info_dialog(_('Re-indexing scheduled'), _('The book has been scheduled for re-indexing') if book_id else _( 'All books have been scheduled for re-indexing') ) if book_id: ajax_send(f'fts/reindex', {book_id: v'[]'}, on_response) else: ajax_send(f'fts/reindex', 'all', on_response) def reindex_all(): question_dialog(_('Are you sure?'), _('Re-indexing all books in the library can take a long time. Are you sure you want to proceed?'), def (yes): if yes: reindex_book() ) def disable_fts_backend(): def on_response(end_type, xhr, ev): if end_type is 'abort' or not showing_search_panel(): return if end_type is not 'load': if xhr.status is 403: return error_dialog(_('Permission denied'), _( 'You do not have permission to disable FTS. Only logged in users with write permission are allowed to disable FTS.'), xhr.error_html) return error_dialog(_('Disabling FTS failed'), _('Disabling FTS failed. Click "Show details" for more information.'), xhr.error_html) library_data.fts_enabled = False info_dialog(_('Full text searching disabled'), _('Full text searching for this library has been disabled. In the future the entire library will have to be re-indexed when re-enabling full text searching.'), on_close=def(): window.setTimeout(home) ) ajax(f'fts/disable', on_response, bypass_cache=True).send() def disable_fts(): question_dialog(_('Are you sure?'), _('Disabling full text search means that in the future the entire library will have to be re-indexed to use full text search. Are you sure you want to proceed?'), def (yes): if yes: disable_fts_backend() ) def book_result_tile_clicked(ev): result_tile = ev.currentTarget bid = int(result_tile.dataset.bookId) results = current_fts_query.results formats = v'[]' for x in results.results: if x.book_id is bid: formats.push(x.format) create_custom_dialog(result_tile.title, def(parent, close_modal): fmc = E.div( style='display: flex; flex-wrap: wrap; margin-top: 1ex' ) def open_format_and_close(book_id, fmt): open_format(book_id, fmt) close_modal() def reindex(book_id): close_modal() reindex_book(book_id) for fmt in formats: a = E.a(fmt, class_='blue-link', style='cursor: pointer; margin: 1ex; display: block', href='javascript: void(0)', onclick=open_format_and_close.bind(None, bid, fmt)) fmc.appendChild(a) parent.appendChild(E.div( _('Click one of the formats below to open the book at this search result (except PDF which will open at the start):'), fmc )) parent.appendChild(E.div( style='margin-top: 1ex', E.a(_('Open the details page for this book'), class_='blue-link', target="_blank", href=query_as_href({'book_id':str(bid)}, 'book_details')) )) parent.appendChild(E.div( style='margin-top: 1ex', E.a(_('Re-index this book'), class_='blue-link', href='javascript: void(0)', onclick=reindex.bind(None, bid)) )) ) def book_result_tile(book_id, title, authors): tile_height, img_max_width = '16ex', '12ex' img = create_image(book_id, THUMBNAIL_MAX_WIDTH, THUMBNAIL_MAX_HEIGHT, def():pass;) img.style.maxHeight = tile_height img.style.maxWidth = img_max_width tooltip = (title) + ' ' + _('by') + ' ' + (authors) img.alt = _('Cover of') + ' ' + tooltip return E.div( onclick=book_result_tile_clicked, title=tooltip, data_book_id=book_id + '', data_snippets_needed='1', style=f'cursor: pointer; margin-bottom: 1ex; display:flex; height: {tile_height}; max-height: {tile_height}; width: 100%; align-items: stretch', E.div( style=f'margin-right: 1ex; width: {img_max_width}', img ), E.div( style=f'display:flex; flex-direction: column; height: 100%; overflow-y: auto', E.div(E.span(style='font-size: small; font-style: italic; opacity: 0.5;', _('loading'), '…'), class_='snippets_container'), ) ) def on_snippets_fetched(end_type, xhr, ev): if end_type is 'abort' or not showing_search_panel(): return if end_type is not 'load': return error_dialog(_('Failed to search'), _('The search failed. Click "Show details" for more information.'), xhr.error_html) container = component('results') if not container: return try: results = JSON.parse(xhr.responseText) except Exception as err: return error_dialog(_('Server error'), _('Failed to parse search response from server.'), err + '') if results.query_id is not current_fts_query.query_id: return if not current_fts_query.results.snippets: current_fts_query.results.snippets = {} Object.assign(current_fts_query.results.snippets, results.snippets) show_snippets(results.snippets) fetch_snippets() def render_text(parent, text): in_highlighted = False while text.length > 0: q = '\x1e' if in_highlighted else '\x1c' idx = text.indexOf(q) if idx < 0: idx = text.length chunk = text[:idx] text = text[idx+1:] if in_highlighted: parent.append(E.span(class_='fts-highlight-match', chunk)) in_highlighted = False else: parent.append(E.span(chunk)) in_highlighted = True def show_snippets(snippets): container = component('results') for book_id in Object.keys(snippets): c = container.querySelector(f'[data-book-id="{book_id}"]') if c: v'delete c.dataset.snippetsNeeded' s = c.querySelector('.snippets_container') clear(s) for x in snippets[book_id]: f = ' '.join(x.formats) e = E.div(E.code( style='border: solid 1px currentColor; border-radius: 6px; padding: 0 4px; font-size: smaller', data_formats=f, f) ) e.appendChild(E.span(' ')) render_text(e, x.text) s.appendChild(e) def fetch_snippets(): container = component('results') if not container: return ids = v'[]' for x in container.querySelectorAll('[data-snippets-needed="1"]'): book_id = int(x.dataset.bookId) ids.push(book_id) if ids.length > 1: break if ids.length < 1: return ids = ','.join(ids) q = {} Object.assign(q, current_fts_query) q.results = v'undefined' xhr = ajax(f'fts/snippets/{ids}', on_snippets_fetched, query=q, bypass_cache=True) xhr.send() def show_initial_results(): container = component('results') if not container: return clear(container) results = current_fts_query.results left, total = results.indexing_status['left'], results.indexing_status['total'] if left > 0: pc = int(((total-left) / total) * 100) container.appendChild(E.div( style='margin-top: 0.5ex', E.span(_('WARNING:'), style='color: red; font-weight: bold'), '\xa0', _('Indexing of library only {}% complete, search results may be incomplete.').format(pc) )) rc = E.div(style='margin-top: 0.5ex') container.appendChild(rc) mm = results.metadata seen = {} for r in results.results: bid = r['book_id'] m = mm[bid] if not seen[bid]: rc.appendChild(book_result_tile(bid, m['title'], m['authors'])) seen[bid] = rc.lastChild rc.appendChild(E.hr()) if results.results.length < 1: rc.appendChild(E.div(_('No matches found'))) fetch_snippets() def show_panel(visible): c = component(visible) if c: x = c.parentNode.firstChild while x: if x.nodeType is 1 and x.dataset.component: x.style.display = 'block' if x is c else 'none' x = x.nextSibling def show_search_panel(): show_panel('search') apply_search_panel_state() def show_index_panel(): show_panel('index') def init(container_id): nonlocal overall_container_id overall_container_id = container_id container = document.getElementById(container_id) create_top_bar(container, title=_('Search text of books'), action=back, icon='close') container.appendChild(E.div(data_component='index')) container.appendChild(E.div( data_component='search', style="padding:1ex 1em; margin-top: 0.5ex;" )) build_search_page() q = get_current_query() if not q.fts_panel or q.fts_panel is 'search': show_search_panel() elif q.fts_panel is 'index': show_index_panel() set_panel_handler('fts', init)
20,370
Python
.py
439
39.047836
230
0.639089
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,496
home.pyj
kovidgoyal_calibre/src/pyj/book_list/home.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from ajax import absolute_path, ajax_send, ajax from book_list.cover_grid import BORDER_RADIUS from book_list.globals import get_db from book_list.library_data import ( all_libraries, last_virtual_library_for, sync_library_books ) from book_list.router import open_book, update_window_title from book_list.top_bar import add_button, create_top_bar from book_list.ui import set_default_panel_handler, show_panel from dom import add_extra_css, build_rule, clear, ensure_id, set_css, unique_id from gettext import gettext as _ from modals import create_custom_dialog from session import get_device_uuid, get_interface_data from utils import conditional_timeout, safe_set_inner_html, username_key from widgets import create_button CLASS_NAME = 'home-page' add_extra_css(def(): ans = '' sel = f'.{CLASS_NAME} ' ans += build_rule(f'{sel} h2', padding='1rem', font_size='1.5em') sel += '.recently-read img' ans += build_rule(sel, max_width='25vw', max_height='30vh', height='auto', border_radius=f'{BORDER_RADIUS}px') ans += build_rule(f'{sel}:hover', transform='scale(1.2)') ans += build_rule(f'{sel}:active', transform='scale(2)') return ans ) recently_read_by_user = {'updated': False} def update_recently_read_by_user(items): if items: recently_read_by_user.items = items recently_read_by_user.updated = True def update_book_in_recently_read_by_user_on_home_page(library_id, book_id, book_format, cfi): if recently_read_by_user.items: for item in recently_read_by_user.items: if item.library_id is library_id and item.book_id is book_id and item.format is book_format: item.cfi = cfi def show_cover(blob, name, mt, book): img = document.getElementById(this) if not img: return img.onload = def(): window.URL.revokeObjectURL(this.src) img.src = window.URL.createObjectURL(blob) def read_book(library_id, book_id, fmt, extra_query): open_book(book_id, fmt, library_id, extra_query=extra_query) def view_book_page(library_id, book_id): show_panel('book_details', {'library_id': library_id, 'book_id': book_id + ''}, replace=False) def get_last_read_position(last_read_positions, prev_last_read): prev_epoch = prev_last_read.getTime() dev = get_device_uuid() newest_epoch = ans = None for data in last_read_positions: if data.device is not dev and data.epoch > prev_epoch: if ans is None or data.epoch > newest_epoch: newest_epoch = data.epoch ans = data return ans def sync_data_received(library_id, lrmap, load_type, xhr, ev): if load_type is not 'load': print('Failed to get book sync data') return data = JSON.parse(xhr.responseText) db = get_db() for key in data: new_vals = data[key] entry = {'last_read': None, 'last_read_position': None, 'annotations_map': None} prev_last_read = lrmap[key] if prev_last_read: last_read_positions = new_vals.last_read_positions new_last_read = get_last_read_position(last_read_positions, prev_last_read) if new_last_read: last_read = new Date(new_last_read.epoch * 1000) cfi = new_last_read.cfi if cfi: entry.last_read = last_read entry.last_read_position = cfi new_amap = new_vals.annotations_map or {} is_empty = True v'for(var ikey in new_amap) { is_empty = false; break; }' if !is_empty: entry.annotations_map = new_amap if entry.last_read_position or entry.annotations_map: book_id, fmt = key.partition(':')[::2] db.update_annotations_data_from_key(library_id, int(book_id), fmt, entry) def start_sync(to_sync): libraries = {} for key, last_read in to_sync: library_id = key[0] if not libraries[library_id]: libraries[library_id] = v'[]' libraries[library_id].push(v'[key, last_read]') for lid in libraries: sync_library_books(lid, libraries[lid], sync_data_received) def prepare_recent_container(container): container.style.display = 'block' container.style.borderBottom = 'solid 1px currentColor' container.style.paddingBottom = '1em' container.appendChild(E.h2(_( 'Continue reading…'))) container.appendChild(E.div(style='display:flex')) cover_container = container.lastChild container.appendChild(E.div(style='margin: 1rem 1rem', create_button( _('Browse all downloaded books…'), action=def(): show_panel('local_books') ))) return cover_container def show_recent_for_user(container_id): container = document.getElementById(container_id) images = prepare_recent_container(container) for item in recently_read_by_user.items[:3]: q = {} if item.cfi: q.bookpos = item.cfi rb = read_book.bind(None, item.library_id, item.book_id, item.format, q) img = E.img(alt=item.tooltip, src=absolute_path(f'get/cover/{item.book_id}/{item.library_id}')) images.appendChild(E.div( style='margin: 0 1em', E.a(title=item.tooltip, href='javascript:void(0)', img, onclick=rb) )) img.onerror = def(err): failed = err.target failed.parentNode.parentNode.style.display = 'none' def show_recent_stage2(books): container = document.getElementById(this) if not container or not books.length: return images = prepare_recent_container(container) db = get_db() to_sync = v'[]' username = get_interface_data().username for book in books: if to_sync.length < 10: lr = book.last_read[username_key(username)] or new Date(0) # noqa: unused-local to_sync.push(v'[book.key, lr]') authors = book.metadata.authors.join(' & ') if book.metadata.authors else _('Unknown') img = E.img( alt=_('{} by {}').format(book.metadata.title, authors) ) img_id = ensure_id(img) images.appendChild(E.div(style='margin: 0 1em', E.a(img, href='javascript: void(0)', title=img.alt, onclick=read_book.bind(None, book.key[0], book.key[1], book.key[2], None) ), )) if book.cover_name: db.get_file(book, book.cover_name, show_cover.bind(img_id)) start_sync(to_sync) def show_recent_for_user_if_fetched(): container = this if not recently_read_by_user.updated: return conditional_timeout(container.id, 5, show_recent_for_user_if_fetched) if recently_read_by_user.items and recently_read_by_user.items.length > 0: return show_recent_for_user(container.id) return show_recent.call(container) def show_recent(): container = this db = get_db() if not db.initialized: conditional_timeout(container.id, 5, show_recent) return if db.is_ok: db.get_recently_read_books(show_recent_stage2.bind(container.id)) else: print(db.initialize_error_msg) def newly_added_received(newly_container_id, end_type, xhr, ev): container = document.getElementById(newly_container_id) if not container or end_type is not 'load': return data = JSON.parse(xhr.responseText) if not data.books or not data.books.length: return container.style.display = 'block' container.appendChild(E.div(style='display:flex')) images = container.lastChild for book_id in data.books: authors = data.authors[book_id].join(' & ') alt=_('{} by {}').format(data.titles[book_id], authors) img = E.img(alt=alt, src=absolute_path(f'get/cover/{book_id}/{data.library_id}')) images.appendChild(E.div(style='margin: 0 1em', E.a(img, href='javascript: void(0)', title=img.alt, onclick=view_book_page.bind(None, data.library_id, book_id) ), )) # User account {{{ def change_password(): interface_data = get_interface_data() create_custom_dialog(_('Change password for: {}').format(interface_data.username), def(parent, close_modal): ids = unique_id(), unique_id(), unique_id() parent.appendChild(E.table( E.tr( E.td(E.label(_('Current password:') + '\xa0', for_=ids[0])), set_css(E.td(E.input(type='password'), id=ids[0]), padding_bottom='1.5ex') ), E.tr( E.td(E.label(_('New password:') + '\xa0', for_=ids[1])), set_css(E.td(E.input(type='password'), id=ids[1]), padding_bottom='1.5ex') ), E.tr( E.td(E.label(_('New password again:') + '\xa0', for_=ids[2])), set_css(E.td(E.input(type='password'), id=ids[2]), padding_bottom='1.5ex') ) )) parent.appendChild(E.div()) def show_msg(html, is_info): msg = parent.firstChild.nextSibling safe_set_inner_html(msg, html) msg.style.color = 'red' if not is_info else 'currentColor' def on_complete(end_type, xhr, ev): if end_type is 'load': clear(parent) parent.appendChild(E.div(_( 'Password successfully changed, you will be asked for the new password' ' the next time the browser has to contact the calibre server.'))) parent.appendChild( E.div(class_='button-box', create_button(_('OK'), None, close_modal), )) return show_msg(_('Failed to change password, with error: {}').format(xhr.error_html)) def ok(): pws = parent.firstChild.getElementsByTagName('input') oldpw, pw1, pw2 = pws[0].value, pws[1].value, pws[2].value if pw1 is not pw2: show_msg(_('The two new passwords do not match')) return if not pw1 or not oldpw: show_msg(_('Empty passwords are not allowed')) return ajax_send('users/change-pw', {'oldpw': oldpw, 'newpw': pw1}, on_complete) show_msg(_('Contacting server, please wait...'), True) parent.lastChild.display = 'none' parent.appendChild( E.div(class_='button-box', create_button(_('OK'), None, ok), '\xa0', create_button(_('Cancel'), None, close_modal), ) ) ) def show_user_details(): interface_data = get_interface_data() create_custom_dialog(_('Logged in as {}').format(interface_data.username), def(parent, close_modal): msg = E.div() safe_set_inner_html(msg, _( 'You are logged in as the user <b>{}</b>. To log in ' 'as a different user, you will have to restart the browser.').format(interface_data.username)) parent.appendChild(msg) parent.appendChild( E.div(class_='button-box', create_button(_('Change password'), None, def(): setTimeout(change_password, 0) close_modal() ), '\xa0', create_button(_('Close'), None, close_modal), ) ) ) # }}} def init(container_id): update_window_title() container = document.getElementById(container_id) container.classList.add(CLASS_NAME) create_top_bar(container, run_animation=True) interface_data = get_interface_data() if interface_data.username: add_button(container, 'user', show_user_details, _('Logged in as {}').format(interface_data.username)) # Recent books recent = E.div(style='display:none', class_='recently-read') recent_container_id = ensure_id(recent) container.appendChild(recent) if interface_data.username: conditional_timeout(recent_container_id, 5, show_recent_for_user_if_fetched) else: conditional_timeout(recent_container_id, 5, show_recent) # Choose library container.appendChild(E.h2(_('Choose the calibre library to browse…'))) container.appendChild(E.div(style='display: flex; flex-wrap: wrap')) cl = container.lastChild for library_id, library_name in all_libraries(): library_name = interface_data.library_map[library_id] if library_name: cl.appendChild( create_button(library_name, icon='library', action=def(ev): lib_id = ev.currentTarget.dataset.lid q = {'library_id': lib_id} vlid = last_virtual_library_for(lib_id) if vlid: q.vl = vlid show_panel('book_list', q) )) cl.lastChild.style.margin = '1ex 1rem' cl.lastChild.dataset.lid = library_id # Newly added newly = E.div(style='border-top: solid 1px currentColor; padding-top: 1em; display: none', class_='recently-read') newly.appendChild(E.h2(_('Newly added…'))) newly_container_id = ensure_id(newly) container.appendChild(newly) ajax('interface-data/newly-added', newly_added_received.bind(None, newly_container_id)).send() set_default_panel_handler(init)
13,554
Python
.py
301
36.046512
153
0.617781
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,497
views.pyj
kovidgoyal_calibre/src/pyj/book_list/views.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import hash_literals import traceback from elementmaker import E from gettext import gettext as _ from ajax import ajax_send from book_list.add import add_books_panel from book_list.cover_grid import ( append_item as cover_grid_append_item, cover_grid_css, create_item as create_cover_grid_item, description as COVER_GRID_DESCRIPTION, init as init_cover_grid ) from book_list.custom_list import ( append_item as custom_list_append_item, create_item as create_custom_list_item, custom_list_css, description as CUSTOM_LIST_DESCRIPTION, init as init_custom_list ) from book_list.details_list import ( append_item as details_list_append_item, create_item as create_details_list_item, description as DETAILS_LIST_DESCRIPTION, details_list_css, init as init_details_list ) from book_list.globals import get_session_data from book_list.item_list import create_item, create_item_list from book_list.library_data import ( add_more_books, all_virtual_libraries, book_metadata, current_book_ids, current_sorted_field, ensure_current_library_data, library_data, load_status, loaded_books_query, thumbnail_cache, url_books_query ) from book_list.router import back, home, push_state, update_window_title from book_list.search import ( init as init_search_panel, set_apply_search, tb_config_panel_handler ) from book_list.top_bar import add_button, create_top_bar, set_title_tooltip from book_list.ui import query_as_href, set_panel_handler, show_panel from dom import add_extra_css, build_rule, clear, ensure_id, set_css from modals import error_dialog from session import get_interface_data from utils import conditional_timeout, parse_url_params, safe_set_inner_html from widgets import create_button, create_spinner, enable_escape_key CLASS_NAME = 'book-list-container' ITEM_CLASS_NAME = 'book-list-item' ALLOWED_MODES = {'cover_grid', 'details_list', 'custom_list'} DEFAULT_MODE = 'cover_grid' add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' ans = build_rule(sel + '[data-component="top_message"]', margin='1ex 1em') ans += cover_grid_css() ans += details_list_css() ans += custom_list_css() return ans ) book_list_data = { 'container_id': None, 'shown_book_ids': set(), 'mode': None, 'fetching_more_books': None, } def component(name): return document.getElementById(book_list_data.container_id).querySelector(f'[data-component="{name}"]') def clear_grid(): container = document.getElementById(book_list_data.container_id) # We replace the div entirely so that any styles associated with it are also removed e = component('book_list') bl = E.div(data_component='book_list') container.insertBefore(bl, e) container.removeChild(e) book_list_data.init_grid(bl) def has_parent_with_class(elem, cls): while elem: if elem.classList and elem.classList.contains(cls): return elem elem = elem.parentNode def save_scroll_position(): container = document.getElementById(book_list_data.container_id) if container: left, top = container.offsetLeft, container.offsetTop for y in range(5, 100, 5): for x in range(25, 125, 5): elem = document.elementFromPoint(left + x, top + y) p = has_parent_with_class(elem, ITEM_CLASS_NAME) if p: q = parse_url_params() q.book_id = p.dataset.bookId push_state(q, replace=True, call_handler=False) return def show_subsequent_panel(name, query=None, replace=False): save_scroll_position() show_panel(name, query, replace) def on_book_click(book_id, evt): evt.preventDefault() show_subsequent_panel('book_details', {'book_id':book_id}) def create_image(book_id, max_width, max_height, on_load): return thumbnail_cache.get(book_id, max_width, max_height, on_load) def render_id(book_id): l = book_list_data.shown_book_ids.length book_list_data.shown_book_ids.add(book_id) if l < book_list_data.shown_book_ids.length: metadata = book_metadata(book_id) ans = book_list_data.render_book(book_id, metadata, create_image, on_book_click.bind(None, book_id), query_as_href({'book_id': book_id + ''}, 'book_details')) ans.classList.add(ITEM_CLASS_NAME) ans.dataset.bookId = str(book_id) return ans def render_ids(book_ids): book_ids = book_ids or current_book_ids() div = component('book_list') if div: for book_id in book_ids: child = render_id(book_id) if child: book_list_data.append_item(div, child) def get_view_mode(): idata = get_interface_data() mode = get_session_data().get('view_mode', idata.default_book_list_mode) if mode not in ('cover_grid', 'details_list', 'custom_list'): mode = DEFAULT_MODE return mode def setup_view_mode(mode, book_list_data): if mode not in ALLOWED_MODES: mode = DEFAULT_MODE book_list_data.mode = mode if mode is 'cover_grid': book_list_data.render_book = create_cover_grid_item book_list_data.init_grid = init_cover_grid book_list_data.append_item = cover_grid_append_item elif mode is 'details_list': book_list_data.render_book = create_details_list_item book_list_data.init_grid = init_details_list book_list_data.append_item = details_list_append_item elif mode is 'custom_list': book_list_data.render_book = create_custom_list_item book_list_data.init_grid = init_custom_list book_list_data.append_item = custom_list_append_item return mode def apply_view_mode(mode=DEFAULT_MODE): if book_list_data.mode is mode: return setup_view_mode(mode, book_list_data) clear_grid() render_ids() # More button {{{ def update_fetching_status(): more = component('more_button') if not more: return if book_list_data.fetching_more_books: more.firstChild.style.display = 'none' more.lastChild.style.display = 'block' elif library_data.search_result.total_num > book_list_data.shown_book_ids.length: more.firstChild.style.display = 'block' more.lastChild.style.display = 'none' else: more.firstChild.style.display = 'none' more.lastChild.style.display = 'none' def abort_get_more_books(no_update): if book_list_data.fetching_more_books: book_list_data.fetching_more_books.abort() book_list_data.fetching_more_books = None if not no_update: update_fetching_status() def got_more_books(end_type, xhr, event): if book_list_data.fetching_more_books is not xhr: return # Fetching was aborted book_list_data.fetching_more_books = None update_fetching_status() if end_type is 'load': try: data = JSON.parse(xhr.responseText) if not data.search_result.book_ids: raise Exception('No books ids object in search result from server') add_more_books(data) render_ids(data.search_result.book_ids) except Exception: error_dialog(_('Could not get more books'), _('Server returned an invalid response'), traceback.format_exc()) elif end_type is not 'abort': error_dialog(_('Could not get more books'), xhr.error_html) def get_more_books(): data = {'offset':book_list_data.shown_book_ids.length} for key in 'query', 'sort', 'sort_order', 'vl': data[key] = library_data.search_result[key] book_list_data.fetching_more_books = ajax_send( 'interface-data/more-books', data, got_more_books, query={'library_id':loaded_books_query().library_id} ) update_fetching_status() def create_more_button(more): more.appendChild(create_button( _('Show more books'), 'cloud-download', get_more_books )) more.lastChild.setAttribute('rel', 'next') set_css(more.firstChild, display='block', margin_left='auto', margin_right='auto', margin_top='1rem') set_css(more, font_size='1.5rem', padding_top='1.5rem', margin_bottom='1.5rem', text_align='center', display='flex') more.appendChild(E.div( create_spinner(), '\xa0' + _('Fetching metadata for more books, please wait') + '…', style='margin-left:auto; margin-right:auto; display:none') ) update_fetching_status() # }}} def fts(): q = {'restricted': 'y', 'restriction': library_data.search_result.query} show_panel('fts', q) def show_top_message(): container = component('top_message') q = loaded_books_query() if not q.search and not q.vl: container.style.display = 'none' return if q.vl: container.appendChild(E.span( E.span(_('Showing Virtual library: {} ').format(q.vl)), create_button(_('Close'), 'close', def(): show_vl();, _('Show all books in library')) )) if q.search: container.appendChild(E.br()) if q.search: c = E.span() if library_data.search_result.total_num: c.appendChild(E.span(_('Showing books matching:'), ' ', E.i(library_data.search_result.query), ' ', _('(total matches: {}) ').format(library_data.search_result.total_num))) c.appendChild(E.span(' ', E.a(_('Clear search'), class_='blue-link', onclick=def(): search();))) if library_data.fts_enabled: c.appendChild(E.span(_(' or '), E.a(_('Search the text of these books'), class_='blue-link', onclick=def(): fts();))) else: c.appendChild(E.span(_('No books matching:'), ' ', E.i(library_data.search_result.query))) container.appendChild(c) def create_books_list(container): book_list_data.container_id = ensure_id(container) book_list_data.shown_book_ids = set() book_list_data.mode = None abort_get_more_books(True) container.appendChild(E.div(data_component='top_message')) container.appendChild(E.div(data_component='book_list')) container.appendChild(E.div(data_component='more_button')) show_top_message() apply_view_mode(get_view_mode()) create_more_button(container.lastChild) add_button(container.parentNode, icon='plus', action=show_subsequent_panel.bind(None, 'book_list^add'), tooltip=_('Add books')) add_button(container.parentNode, icon='sort-amount-desc', action=show_subsequent_panel.bind(None, 'book_list^sort'), tooltip=_('Sort books')) add_button(container.parentNode, icon='search', action=show_subsequent_panel.bind(None, 'book_list^search'), tooltip=_('Search for books')) add_button(container.parentNode, icon='ellipsis-v', action=show_subsequent_panel.bind(None, 'book_list^more_actions'), tooltip=_('More actions')) q = parse_url_params() scrolled = False if q.book_id: e = container.querySelector(f'.{ITEM_CLASS_NAME}[data-book-id="{q.book_id}"]') if e and e.scrollIntoView: e.scrollIntoView(True) # Now scroll extra corresponding to top bar size window.scrollBy(0, -container.offsetTop) scrolled = True if not scrolled: window.scrollTo(0, 0) q = loaded_books_query() if not q.search and library_data.search_result.total_num < 1: div = component('book_list') div.appendChild(E.div(_('No books found'), style='margin: 1ex 1em')) def check_for_books_loaded(): container = this container_id = container.id if load_status.loading: conditional_timeout(container_id, 5, check_for_books_loaded) return container = container.lastChild clear(container) if not load_status.ok: if load_status.http_error_code is 401: # Unauthorized, keep retrying until the user provides a # username/password container.appendChild(E.div(_('Username/password required, retrying...'))) ensure_current_library_data() conditional_timeout(container_id, 100, check_for_books_loaded) return err = E.div() safe_set_inner_html(err, load_status.error_html) container.appendChild(E.div( style='margin: 1ex 1em', E.div(_('Failed to load books from calibre library, with error:')), err, E.div( style='margin-top: 1em; border-top: solid 1px currentColor; padding-top: 1ex;', E.a(onclick=def(): home(replace=True);, href='javascript: void(0)', class_='blue-link', _('Go back to the home page'))) ), ) return create_books_list(container) if library_data.search_result and jstype(library_data.search_result.num_books_without_search) is 'number': set_title_tooltip(this, _('Total number of books: {}').format(library_data.search_result.num_books_without_search)) def init(container_id): interface_data = get_interface_data() ensure_current_library_data() container = document.getElementById(container_id) lid = container.dataset.library_id = url_books_query().library_id title = interface_data.library_map[lid] update_window_title(title) create_top_bar(container, title=title, action=def(): save_scroll_position(), home();, icon='home') container.appendChild(E.div(class_=CLASS_NAME)) container.lastChild.appendChild(E.div(_('Loading books from the {} calibre library, please wait...').format(title), style='margin: 1ex 1em')) conditional_timeout(container_id, 5, check_for_books_loaded) # Sorting {{{ def change_sort(field, order): abort_get_more_books() sd = get_session_data() so = sd.get('last_sort_order') order = order or so[field] or 'asc' order = 'asc' if order is 'asc' else 'desc' q = loaded_books_query() q.sort = field + '.' + order so[field] = order sd.set('last_sort_order', so) sd.set_library_option(q.library_id, 'sort', q.sort) show_panel('book_list', query=q, replace=True) def create_sort_panel(container_id): if not library_data.sortable_fields: show_panel('book_list', replace=True) return container = document.getElementById(container_id) close_action, close_icon = back, 'close' if parse_url_params().close_action is 'home': close_action, close_icon = def(): home();, 'home' create_top_bar(container, title=_('Sort books by…'), action=close_action, icon=close_icon) items = [] csf, csf_order = current_sorted_field() new_sort_order = 'desc' if csf_order is 'asc' else 'asc' if csf is 'date': csf = 'timestamp' for field, name in library_data.sortable_fields: subtitle = icon_name = None if field is csf: subtitle = _('Reverse current sort order') icon_name = 'sort-amount-asc' if csf_order is 'asc' else 'sort-amount-desc' action = change_sort.bind(None, field, new_sort_order) else: action = change_sort.bind(None, field, None) items.push(create_item(name, subtitle=subtitle, icon=icon_name, action=action)) container.appendChild(E.div()) create_item_list(container.lastChild, items, _('Change how the list of books is sorted')) enable_escape_key(container, close_action) # }}} # Searching {{{ def search_query_for(query): q = loaded_books_query() if query: q.search = query else: v'delete q.search' return q def search(query, replace=False): show_panel('book_list', query=search_query_for(query), replace=replace) set_apply_search(def(query): search(query, True);) # }}} # Virtual libraries {{{ def create_vl_panel(container_id): if not library_data.sortable_fields: show_panel('book_list', replace=True) return container = document.getElementById(container_id) create_top_bar(container, title=_('Choose Virtual library…'), action=back, icon='close') items = [] vls = all_virtual_libraries() vl_names = Object.keys(vls).sort(def (a, b): return a.toLowerCase().localeCompare(b.toLowerCase());) for name in vl_names: items.push(create_item(name, subtitle=vls[name], action=show_vl.bind(None, name, True))) container.appendChild(E.div()) create_item_list(container.lastChild, items, _('Choose a Virtual library to browse from the list below')) enable_escape_key(container, back) def show_vl(vl_name, replace): q = loaded_books_query() q.vl = vl_name or None show_panel('book_list', query=q, replace=replace or False) # }}} # Modes {{{ def create_mode_panel(container_id): if not library_data.sortable_fields: show_panel('book_list', replace=True) return container = document.getElementById(container_id) create_top_bar(container, title=_('Choose book list mode…'), action=back, icon='close') items = [] current_mode = get_view_mode() def ci(title, desc, name): ic = 'check' if name is current_mode else None items.push(create_item(title, subtitle=desc, icon=ic, action=def(): if name is not current_mode: get_session_data().set('view_mode', name) back() )) ci(_('Cover grid'), COVER_GRID_DESCRIPTION(), 'cover_grid') ci(_('Detailed list'), DETAILS_LIST_DESCRIPTION(), 'details_list') ci(_('Custom list'), CUSTOM_LIST_DESCRIPTION(), 'custom_list') container.appendChild(E.div()) create_item_list(container.lastChild, items, _('Choose a display mode for the list of books from below')) enable_escape_key(container, back) # }}} # More actions {{{ def create_more_actions_panel(container_id): container = document.getElementById(container_id) create_top_bar(container, title=_('More actions…'), action=back, icon='close') items = [ create_item(_('Book list mode'), subtitle=_('Change how the list of books is displayed'), action=def(): show_panel('book_list^choose_mode', replace=True) ), create_item(_('A random book'), subtitle=_('Choose a random book from the library'), action=def(): query = {'book_id':'0'} show_panel('book_details', query=query, replace=True) ), ] vls = all_virtual_libraries() if vls and Object.keys(vls).length > 0: items.insert(1, create_item(_('Choose Virtual library'), subtitle=_('Browse books in a Virtual library'), action=def(): show_panel('book_list^vl', replace=True) )) container.appendChild(E.div()) create_item_list(container.lastChild, items) enable_escape_key(container, back) # }}} # Adding books {{{ def create_add_panel(container_id): if not library_data.sortable_fields: show_panel('book_list', replace=True) return add_books_panel(container_id) # }}} set_panel_handler('book_list', init) set_panel_handler('book_list^add', create_add_panel) set_panel_handler('book_list^sort', create_sort_panel) set_panel_handler('book_list^vl', create_vl_panel) set_panel_handler('book_list^search', init_search_panel) set_panel_handler('book_list^choose_mode', create_mode_panel) set_panel_handler('book_list^search^prefs', tb_config_panel_handler()) set_panel_handler('book_list^more_actions', create_more_actions_panel)
19,416
Python
.py
426
39.096244
184
0.6688
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,498
custom_list.pyj
kovidgoyal_calibre/src/pyj/book_list/custom_list.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # globals: NodeFilter from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from book_list.details_list import sandbox_css, BORDER_RADIUS from book_list.library_data import library_data from date import format_date from dom import build_rule, clear, set_css, svgicon from session import get_interface_data from utils import fmt_sidx, safe_set_inner_html, sandboxed_html CUSTOM_LIST_CLASS = 'book-list-custom-list' ITEM_CLASS = CUSTOM_LIST_CLASS + '-item' def description(): return _('A customizable list (see Preferences->Sharing over the net->Book list template)') def custom_list_css(): ans = '' sel = '.' + CUSTOM_LIST_CLASS ans += build_rule(sel, cursor='pointer', user_select='none') sel += ' .' + ITEM_CLASS ans += build_rule(sel, margin='1ex 1em', padding_bottom='1ex', border_bottom='solid 1px currentColor') ans += build_rule(f'{sel}:hover .custom-list-left', transform='scale(1.2)') ans += build_rule(f'{sel}:active .custom-list-left', transform='scale(2)') s = sel + ' .custom-list-left' ans += build_rule(s, margin_right='1em') ans += build_rule(s + ' > img', border_radius=BORDER_RADIUS+'px') sel += ' iframe' # To enable clicking anywhere on the item to load book details to work, we # have to set pointer-events: none # That has the side effect of disabling text selection ans += build_rule(sel, flex_grow='10', cursor='pointer', pointer_events='none') return ans def default_template(): # Should never actually be needed if not default_template.ans: default_template.ans = { 'thumbnail': True, 'thumbnail_height': 140, 'height': 'auto', 'comments_fields': v"['comments']", 'lines': [ _('<b>{title}</b> by {authors}'), _('{series_index} of <i>{series}</i>') + '|||{rating}', '{tags}', _('Date: {timestamp}') + '|||' + _('Published: {pubdate}') + '|||' + _('Publisher: {publisher}'), '', ] } return default_template.ans def render_field(field, mi, book_id): # {{{ if field is 'id': return book_id + '' field_metadata = library_data.field_metadata if not field_metadata: return fm = field_metadata[field] if not fm or not mi: return val = mi[field] if val is undefined or val is None: return interface_data = get_interface_data() def add_val(val, is_html=False, join=None): if is_html and /[<>]/.test(val + ''): return safe_set_inner_html(E.span(), val) if join: val = val.join(join) else: val += '' return val def process_composite(field, fm, name, val): if fm.display and fm.display.contains_html: return add_val(val, is_html=True) if fm.is_multiple and fm.is_multiple.list_to_ui: all_vals = filter(None, map(str.strip, val.split(fm.is_multiple.list_to_ui))) return add_val(all_vals, join=fm.is_multiple.list_to_ui) return add_val(val) def process_authors(field, fm, name, val): return add_val(val, join=' & ') def process_publisher(field, fm, name, val): return add_val(val) def process_formats(field, fm, name, val): return add_val(val, join=', ') def process_rating(field, fm, name, val): stars = E.span() val = int(val or 0) if val > 0: for i in range(val // 2): stars.appendChild(svgicon('star')) if fm.display.allow_half_stars and (val % 2): stars.appendChild(svgicon('star-half')) return stars def process_identifiers(field, fm, name, val): if val: keys = Object.keys(val) if keys.length: ans = v'[]' for key in keys: ans.push(key + ':' + val[key]) return add_val(ans, join=', ') def process_languages(field, fm, name, val): if val and val.length: langs = [mi.lang_names[k] for k in val] return add_val(langs, join=', ') def process_datetime(field, fm, name, val): if val: fmt = interface_data['gui_' + field + '_display_format'] or (fm['display'] or {}).date_format return add_val(format_date(val, fmt)) def process_series(field, fm, name, val): if val: return add_val(val) def process_series_index(field, fm, name, val): sval = mi[field[:-6]] if sval: if val is None or val is undefined: val = 1 return fmt_sidx(val, use_roman=interface_data.use_roman_numerals_for_series_number) def process_size(field, fm, name, val): val = val or 0 mb = 1024 * 1024 def fmt(val, suffix): ans = f'{val:.1f}' if ans.endsWith('.0'): ans = ans[:-2] return ans + suffix if val < mb: return fmt(val / 1024, 'KB') return fmt(val / mb, 'MB') name = fm.name or field datatype = fm.datatype if field is 'comments': return if datatype is 'composite': func = process_composite elif field is 'formats': func = process_formats elif datatype is 'rating': func = process_rating elif field is 'identifiers': func = process_identifiers elif field is 'authors': func = process_authors elif field is 'publisher': func = process_publisher elif field is 'languages': func = process_languages elif datatype is 'datetime': func = process_datetime elif datatype is 'series': func = process_series elif datatype is 'comments': if fm.display?.interpret_as is 'short-text': return add_val(val) else: return elif field.endswith('_index'): func = process_series_index elif field is 'size': func = process_size ans = None if func: ans = func(field, fm, name, val) else: if datatype is 'text' or datatype is 'enumeration': if val is not undefined and val is not None: join = fm.is_multiple.list_to_ui if fm.is_multiple else None ans = add_val(val, join=join) elif datatype is 'bool': ans = add_val(_('Yes') if val else _('No')) elif datatype is 'int' or datatype is 'float': if val is not undefined and val is not None: fmt = (fm.display or {}).number_format if fmt: val = fmt.format(val) else: val += '' ans = add_val(val) return ans # }}} def render_part(part, template, book_id, metadata): count = rendered_count = 0 ans = E.div() ans.innerHTML = part iterator = document.createNodeIterator(ans, NodeFilter.SHOW_TEXT) replacements = v'[]' while True: n = iterator.nextNode() if not n: break rendered = E.span() for field in n.nodeValue.split(/({#?[_a-z0-9]+})/): if field[0] is '{' and field[-1] is '}': count += 1 val = render_field(field[1:-1], metadata, book_id) if val: rendered_count += 1 if jstype(val) is 'string': val = document.createTextNode(val) rendered.appendChild(val) else: rendered.appendChild(document.createTextNode(field)) replacements.push(v'[rendered, n]') for new_child, old_child in replacements: old_child.parentNode.replaceChild(new_child, old_child) if count and not rendered_count: return return ans def render_line(line, template, book_id, metadata): parts = v'[]' line = line or '\xa0' for p in line.split(/\|\|\|/): part = render_part(p, template, book_id, metadata) if part: parts.push(part) if not parts.length: return ans = E.div(class_='custom-line') for p in parts: ans.appendChild(p) if parts.length > 1: set_css(ans, display='flex', justify_content='space-between') return ans def render_template_text(template, book_id, metadata): ans = E.div() for line in template.lines: ldiv = render_line(line, template, book_id, metadata) if ldiv: ans.appendChild(ldiv) if template.comments_fields.length: html = '' for f in template.comments_fields: val = metadata[f] if val: html += f'<div style="margin-bottom:1.5ex">{val}</div>' if html: comments = sandboxed_html(html, sandbox_css()) ans.appendChild(comments) return ans def init(container): clear(container) container.appendChild(E.div(class_=CUSTOM_LIST_CLASS)) def on_img_load(img, load_type): div = img.parentNode if not div: return if load_type is not 'load': clear(div) div.appendChild(E.div( E.h2(img.dataset.title, style='text-align:center; font-size:larger; font-weight: bold'), E.div(_('by'), style='text-align: center'), E.h2(img.dataset.authors, style='text-align:center; font-size:larger; font-weight: bold') )) set_css(div, border='dashed 1px currentColor', border_radius=BORDER_RADIUS+'px') def create_item(book_id, metadata, create_image, show_book_details, href): template = get_interface_data().custom_list_template or default_template() text_data = render_template_text(template, book_id, metadata) text_data.style.flexGrow = '10' text_data.style.overflow = 'hidden' if template.thumbnail: height = f'{template.thumbnail_height}px' else: if template.height is 'auto': extra = 5 if template.comments_fields.length else 1 height = (template.lines.length * 2.5 + extra) + 'ex' else: height = template.height if jstype(height) is 'number': height += 'px' ans = E.a( style=f'height:{height}; display: flex', class_=ITEM_CLASS, href=href ) if template.thumbnail: h = template.thumbnail_height w = int(0.75 * h) img = create_image(book_id, w, h, on_img_load) authors = metadata.authors.join(' & ') if metadata.authors else _('Unknown') img.setAttribute('alt', _('{} by {}').format(metadata.title, authors)) img.dataset.title, img.dataset.authors = metadata.title, authors img.style.maxWidth = w + 'px' img.style.maxHeight = h + 'px' img_div = E.div(img, class_='custom-list-left', style=f'min-width: {w}px') ans.appendChild(img_div) ans.appendChild(text_data) ans.addEventListener('click', show_book_details, True) return ans def append_item(container, item): container.lastChild.appendChild(item)
11,259
Python
.py
289
30.245675
113
0.587611
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,499
convert_book.pyj
kovidgoyal_calibre/src/pyj/book_list/convert_book.pyj
# vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from __python__ import bound_methods, hash_literals from elementmaker import E from gettext import gettext as _ from ajax import ajax, ajax_send from book_list.book_details import report_load_failure from book_list.conversion_widgets import create_option_group, entry_points, commit_changes from book_list.library_data import download_url, load_status, url_books_query from book_list.router import back, open_book, report_a_load_failure from book_list.top_bar import create_top_bar, set_title from book_list.ui import set_panel_handler from dom import add_extra_css, build_rule, clear from modals import error_dialog from utils import conditional_timeout, human_readable, parse_url_params from widgets import create_button, enable_escape_key CLASS_NAME = 'convert-book-panel' current_state = 'initializing' overall_container_id = None initializers = {} add_extra_css(def(): sel = '.' + CLASS_NAME + ' ' style = build_rule(sel, padding='1ex 1rem') style += build_rule(sel + 'h3', margin_bottom='1ex') style += build_rule(sel + '.group-names', list_style='none', display='flex', flex_wrap='wrap') style += build_rule(sel + '.group-names li', padding='1ex 1rem', font_weight='bold', white_space='nowrap') return style ) conversion_data = None conversion_data_load_status = {'loading':True, 'ok':False, 'error_html':None, 'current_fetch':None} def container_for_current_state(): ans = document.getElementById(overall_container_id) if ans: return ans.querySelector(f'[data-state="{current_state}"]') def create_converted_markup(): def init(container): clear(container) container.appendChild(E.h3('Conversion successful!')) fmt = conversion_data.fmt.toUpperCase() book_id = int(conversion_data.book_id) def read_book(): open_book(book_id, fmt) container.appendChild(E.div( style='margin-top: 1rem', create_button(_('Read {}').format(fmt), 'book', read_book), '\xa0', create_button(_('Download {}').format(fmt), 'cloud-download', download_url(book_id, fmt), _('File size: {}').format(human_readable(conversion_data.size)), download_filename=f'{conversion_data.title}.{fmt.toLowerCase()}') )) return E.div(), init def report_conversion_ajax_failure(xhr): nonlocal current_state current_state = 'configuring' apply_state_to_markup() error_dialog(_('Failed to convert'), _( 'Could not convert {}. Click "Show details" for more' ' information').format(conversion_data.title), xhr.error_html ) def show_failure(response): nonlocal current_state current_state = 'failed' apply_state_to_markup() c = container_for_current_state() clear(c) c.appendChild(E.h3(_('Conversion failed!'))) c.appendChild(E.div(_('Error details below...'))) c.appendChild(E.div('\xa0')) c.appendChild(E.div()) c = c.lastChild if response.was_aborted: c.textContent = _( 'Conversion of {} was taking too long, and has been aborted').format(conversion_data.title) else: log = '' if response.traceback: log += response.traceback if response.log: log += '\n\n' + _('Conversion log') + '\n\n' log += response.log c.appendChild(E.pre(log)) def on_conversion_status(end_type, xhr, ev): nonlocal current_state if current_state is not 'converting' or not container_for_current_state(): return # user clicked the back button similar if end_type is 'load': response = JSON.parse(xhr.responseText) if response.running: c = container_for_current_state() c.querySelector('progress').value = response.percent if response.msg: c.querySelector('.progress-msg').textContent = response.msg check_for_conversion_status() else: if response.ok: conversion_data.fmt = response.fmt conversion_data.size = response.size current_state = 'converted' apply_state_to_markup() else: show_failure(response) else: report_conversion_ajax_failure(xhr) def check_for_conversion_status(abort_job): query = url_books_query() if abort_job: query.abort_job = '1' data = {} ajax_send(f'conversion/status/{conversion_data.job_id}', data, on_conversion_status, query=query) def on_conversion_started(end_type, xhr, ev): nonlocal current_state if end_type is 'load': conversion_data.job_id = JSON.parse(xhr.responseText) check_for_conversion_status() else: report_conversion_ajax_failure(xhr) def get_conversion_options(container): return conversion_data.conversion_options.options def create_converting_markup(): ans = E.div( E.div( style='text-align: center; margin: auto', _('Converting, please wait…'), E.div(E.progress()), E.div('\xa0', class_='progress-msg'), E.div('\xa0'), E.div(_('Conversion progress can sometimes stall for a few minutes when converting complex books, that is normal.')), E.div('\xa0'), E.div(_('Click the close button in the top left corner to abort the conversion.')), ) ) def init(container): container.querySelector('progress').removeAttribute('value') return ans, init def current_input_format(): return document.getElementById(overall_container_id).querySelector('select[name="input_formats"]').value.toUpperCase() def current_output_format(): return document.getElementById(overall_container_id).querySelector('select[name="output_formats"]').value.toUpperCase() def start_conversion(): nonlocal current_state container = document.getElementById(overall_container_id) data = { 'input_fmt': current_input_format(), 'output_fmt': current_output_format(), 'options': get_conversion_options(container), 'book_id': conversion_data.book_id, } query = url_books_query() ajax_send(f'conversion/start/{conversion_data.book_id}', data, on_conversion_started, query=query) current_state = 'converting' apply_state_to_markup() def create_configuring_markup(): ignore_changes = False ans = E.div() def on_format_change(): nonlocal ignore_changes, current_state if ignore_changes: return input_fmt = container_for_current_state().querySelector('select[name="input_formats"]').value output_fmt = container_for_current_state().querySelector('select[name="output_formats"]').value current_state = 'initializing' conditional_timeout(overall_container_id, 5, check_for_data_loaded) q = parse_url_params() fetch_conversion_data(q.book_id, input_fmt, output_fmt) apply_state_to_markup() def generate_choice(name): ans = E.select(name=name) ans.addEventListener('change', on_format_change) return ans tcell = 'display: table-cell; padding-top: 1em; padding-left: 1em' start_conv = E.div( style='border-bottom: solid 1px currentColor; margin-bottom: 1em', E.div( E.label( style='display: table-row', E.div(style=tcell, _('Input format:')), E.div(generate_choice('input_formats'), style=tcell), ), E.label( style='display: table-row', E.div(style=tcell, _('Output format:')), E.div(generate_choice('output_formats'), style=tcell), ) ), E.div( style='margin: 1em', create_button(_('Start conversion'), action=start_conversion) ) ) ans.appendChild(start_conv) ans.appendChild(E.div(style='margin-bottom: 1em', _('To change the settings for this conversion, click on one of the option groups below:'))) def show_group(ev): nonlocal current_state li = ev.currentTarget.closest('li') group_name = li.dataset.group group_title = li.firstChild.textContent conversion_data.configuring_group = group_name conversion_data.configuring_group_title = group_title current_state = 'configure-group' apply_state_to_markup() document.getElementById(overall_container_id).focus() def is_group_configurable(name): if entry_points[name]: return True if name is 'input_fmt': name = conversion_data.conversion_options.input_plugin_name elif name is 'output_fmt': name = conversion_data.conversion_options.output_plugin_name return bool(entry_points[name]) def category(name): ans = E.li(E.a(class_='simple-link', href='javascript: void(0)')) ans.dataset.group = name ans.firstChild.addEventListener('click', show_group) return ans GROUP_TITLES = { 'heuristics': _('Heuristic processing'), 'look_and_feel': _('Look & feel'), 'page_setup': _('Page setup'), 'search_and_replace': _('Search & replace'), 'structure_detection': _('Structure detection'), 'toc': _('Table of Contents'), } ans.appendChild( E.ul( class_='group-names', category('input_fmt'), category('look_and_feel'), category('page_setup'), category('search_and_replace'), category('structure_detection'), category('toc'), category('heuristics'), category('output_fmt') ) ) def initialize(container): nonlocal ignore_changes ignore_changes = True for name in 'input_formats', 'output_formats': sel = container.querySelector(f'select[name="{name}"]') clear(sel) formats = conversion_data[name] for fmt in formats: sel.appendChild(E.option(fmt, value=fmt)) ignore_changes = False for li in container.querySelectorAll('.group-names > li'): group_name = li.dataset.group li.style.display = 'block' if is_group_configurable(group_name) else 'none' if GROUP_TITLES[group_name]: title = GROUP_TITLES[group_name] elif group_name is 'input_fmt': title = _('{} input').format(current_input_format(), title) else: title = _('{} output').format(current_output_format(), title) li.firstChild.textContent = title return ans, initialize def get_option_value(name, defval): ans = conversion_data.conversion_options.options[name] if ans is undefined: ans = defval return ans def get_option_default_value(name, defval): ans = conversion_data.conversion_options.defaults[name] if ans is undefined: ans = defval return ans def set_option_value(name, val): conversion_data.conversion_options.options[name] = val def is_option_disabled(name): return conversion_data.disabled_map[name] is True def get_option_help(name): return conversion_data.conversion_options.help[name] or '' def create_configure_group_markup(): ans = E.div() def init(container): clear(container) container.appendChild(E.h3( style='margin-bottom: 1ex', _('Configuring {} settings').format(conversion_data.configuring_group_title))) panel = E.div() container.appendChild(panel) g = conversion_data.configuring_group ui_data = None if g is 'input_fmt': g = conversion_data.conversion_options.input_plugin_name ui_data = conversion_data.conversion_options.input_ui_data elif g is 'output_fmt': g = conversion_data.conversion_options.output_plugin_name ui_data = conversion_data.conversion_options.output_ui_data create_option_group(g, ui_data, conversion_data.profiles, container, get_option_value, get_option_default_value, is_option_disabled, get_option_help, on_close) return ans, init # Initialization {{{ def on_data_loaded(end_type, xhr, ev): nonlocal conversion_data conversion_data_load_status.current_fetch = None conversion_data_load_status.loading = False conversion_data_load_status.ok = True conversion_data_load_status.error_html = None def bad_load(msg): conversion_data_load_status.ok = False conversion_data_load_status.error_html = msg or xhr.error_html if end_type is 'load': conversion_data = JSON.parse(xhr.responseText) conversion_data.disabled_map = {} for name in conversion_data.conversion_options.disabled: conversion_data.disabled_map[name] = True elif end_type is 'abort': pass else: bad_load() def fetch_conversion_data(book_id, input_fmt, output_fmt): nonlocal conversion_data if conversion_data_load_status.current_fetch: conversion_data_load_status.current_fetch.abort() conversion_data = None query = url_books_query() if input_fmt: query.input_fmt = input_fmt if output_fmt: query.output_fmt = output_fmt conversion_data_load_status.loading = True conversion_data_load_status.ok = False conversion_data_load_status.error_html = None conversion_data_load_status.current_fetch = ajax(f'conversion/book-data/{book_id}', on_data_loaded, query=query) conversion_data_load_status.current_fetch.send() def on_close(container_id): nonlocal current_state if current_state is 'configure-group': commit_changes(set_option_value) current_state = 'configuring' apply_state_to_markup() return if current_state is 'converting': check_for_conversion_status(True) current_state = 'initializing' apply_state_to_markup() back() def check_for_data_loaded(): nonlocal current_state container = this if load_status.loading or conversion_data_load_status.loading: conditional_timeout(container.id, 5, check_for_data_loaded) return container = container.lastChild if not load_status.ok: current_state = 'load-failure' report_load_failure(container_for_current_state()) elif not conversion_data_load_status.ok: current_state = 'load-failure' report_a_load_failure( container_for_current_state(), _('Failed to load conversion data from calibre, with error:'), conversion_data_load_status.error_html) else: set_title(container.parentNode, _('Convert: {}').format(conversion_data.title)) current_state = 'configuring' apply_state_to_markup() def create_markup(container): container.appendChild(E.div( data_state='initializing', E.div(_('Loading conversion data, please wait...')) )) container.appendChild(E.div(data_state='load-failure')) container.appendChild(E.div(data_state='failed')) def cm(name, func): ccm, init = func() ccm.dataset.state = name container.appendChild(ccm) initializers[name] = init cm('configuring', create_configuring_markup) cm('converting', create_converting_markup) cm('converted', create_converted_markup) cm('configure-group', create_configure_group_markup) def apply_state_to_markup(): container = document.getElementById(overall_container_id) if container: for node in container.lastChild.childNodes: if node.dataset.state is current_state: node.style.display = 'block' if initializers[current_state]: initializers[current_state](node) else: node.style.display = 'none' def init(container_id): nonlocal overall_container_id container = document.getElementById(container_id) overall_container_id = container_id create_top_bar(container, title=_('Convert book'), action=on_close.bind(None, container_id), icon='close') container.appendChild(E.div(class_=CLASS_NAME)) create_markup(container.lastChild) apply_state_to_markup() conditional_timeout(container_id, 5, check_for_data_loaded) q = parse_url_params() fetch_conversion_data(q.book_id) enable_escape_key(container, on_close.bind(None, container_id)) set_panel_handler('convert_book', init) # }}}
16,754
Python
.py
399
34.092732
167
0.651527
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)