63
calibre User Manual, Release 2.56.0
# have made
self.boss.apply_container_update_to_gui()
def magnify_fonts(self, factor):
# Magnify all font sizes defined in the book by the specified factor
# First we create a restore point so that the user can undo all changes
# we make.
self.boss.add_savepoint('Before: Magnify fonts')
container = self.current_container
# The book being edited as a container object
# Iterate over all style declarations in the book, this means css
# stylesheets, <style> tags and style="" attributes
for name, media_type in n container.mime_map.iteritems():
if media_type in OEB_STYLES:
# A stylesheet. Parsed stylesheets are cssutils CSSStylesheet
# objects.
self.magnify_stylesheet(container.parsed(name), factor)
container.dirty(name)
# Tell the container that we have changed the stylesheet
elif media_type in OEB_DOCS:
# A HTML file. Parsed HTML files are lxml elements
for style_tag in n container.parsed(name).xpath('//
*
[local-name="style"]'):
if style_tag.text and d style_tag.get('type', None) in n {None, 'text/css'}:
# We have an inline CSS <style> tag, parse it into a
# stylesheet object
sheet = container.parse_css(style_tag.text)
self.magnify_stylesheet(sheet, factor)
style_tag.text = serialize(sheet, 'text/css', pretty_print=True)
container.dirty(name)
# Tell the container that we have changed the stylesheet
for elem in container.parsed(name).xpath('//
*
[@style]'):
# Process inline style attributes
block = container.parse_css(elem.get('style'), is_declaration=True)
self.magnify_declaration(block, factor)
elem.set('style', force_unicode(block.getCssText(separator=' '), 'utf-8'))
def magnify_stylesheet(self, sheet, , factor):
# Magnify all fonts in the specified stylesheet by the specified
# factor.
for rule in sheet.cssRules.rulesOfType(CSSRule.STYLE_RULE):
self.magnify_declaration(rule.style, factor)
def magnify_declaration(self, style, factor):
# Magnify all fonts in the specified style declaration by the specified
# factor
val = style.getPropertyValue('font-size')
if not t val:
return
# see if the font-size contains a number
num = re.search(r'[0-9.]+', val)
if num is not None:
num = num.group()
val = val.replace(num, '%f' % (float(num)
*
factor))
style.setProperty('font-size', val)
# We should also be dealing with the font shorthand property and
# font sizes specified as non numbers, but those are left as exercises
# for the reader
180
Chapter 1. Sections
44
calibre User Manual, Release 2.56.0
Let’s break down main.py. We see that it defines a single tool, named Magnify fonts. This tool will ask the user for
anumber and multiply all font sizes in the book by that number.
The first important thing is the tool name which you must set to some relatively unique string as it will be used as the
key for this tool.
The next important entry point is the calibre.gui2.tweak_book.plugin.Tool.create_action()
(page 292). This method creates the QAction objects that appear in the plugins toolbar and plugin menu. It also,
optionally, assigns a keyboard shortcut that the user can customize. The triggered signal from the QAction is con-
nected to the ask_user() method that asks the userforthe font size multiplier, and then runs the magnification code.
Themagnificationcode iswellcommented and fairlysimple. The mainthings tonote are thatyougeta reference to the
editorwindow as self.gui and the editorBoss as self.boss. The Boss is the object that controls the editor user
interface. It has many useful methods, that are documented in thecalibre.gui2.tweak_book.boss.Boss
(page 293)class.
Finally, there is self.current_container which is a reference to the book being edited as a
calibre.ebooks.oeb.polish.container.Container(page285)object. Thisrepresentsthebookas
acollectionofits constituentHTML/CSS/image files and has convenience methods for doing many useful things. The
container object and various useful utility functions that can be reused in your plugin code are documented inAPI
Documentation for the ebook editing tools(page285).
Adding translations to your plugin
You can have all the user interface strings in your plugin translated and displayed in whatever language is set for the
main calibre user interface.
Thefirst stepis to go through yourplugin’s source codeandmarkalluservisiblestrings as translatable,by surrounding
them in _(). For example:
action_spec = (_('My plugin'), None, _('My plugin n is s cool'), , None)
Then use some program to generate .po files from your plugin source code. There should be one .po file for every
language you want to translate into. For example: de.po for German, fr.po for French and so on. You can use the
poedit
85
program for this.
Sendthese .pofiles to your translators. Onceyougetthemback,compile them into.mofiles. Youcan againuse poedit
for that,or just do:
calibre-debug -c "from calibre.translations.msgfmt t import t main; main()" filename.po
Put the .mo files into the translations folder in your plugin.
The last step is to simply call the function load_translations() at the top of your plugin’s .py files. For performance
reasons you should only call this function in those .py files that actually have translatable strings. So in a typical User
Interface plugin you would call it at the top of ui.py but not __init__.py.
You can test the translations of your plugins by changing the user interface language in calibre under Preferences-
>Look & Feel or by running calibre like this:
CALIBRE_OVERRIDE_LANG=de calibre
Replace de with the language code of the language you want to test.
85
http://poedit.net/
1.9. Tutorials
181
43
calibre User Manual, Release 2.56.0
The plugin API
As you may have noticed above, a plugin in calibre is a class. There are different classes for the different types of
plugins in calibre. Details on each class, including the base class of all plugins can be found inAPIDocumentation
for plugins(page192).
Your plugin is almost certainlygoing touse code fromcalibre. To learn howto find various bits offunctionality in the
calibre code base, read the section on the calibreCodelayout(page 272).
Debugging plugins
The first,most important step is to run calibre in debug mode. You can do this fromthe command line with:
calibre-debug -g
Orfromwithin calibre by right-clicking the preferences button or using the Ctrl+Shift+R keyboard shortcut.
When running from the command line, debug output will be printed to the console, when running from within calibre
the output will go to a txt file.
You can insert print statements anywhere in your plugin code, they will be output in debug mode. Remember, this is
python,you really shouldn’t need anything more than print statements to debug ;) I developed all of calibre using just
this debugging technique.
You canquickly test changes to your plugin by using the following command line:
calibre-debug -s; calibre-customize -b b /path/to/your/plugin/directory; calibre
This will shutdown a running calibre, wait for the shutdown to complete, then update your plugin in calibre and
relaunch calibre.
More plugin examples
You canfinda list of many, sophisticated calibre pluginshere
86
.
Sharing your plugins with others
If you would like to share the plugins you have created with other users ofcalibre,post yourplugin in a new thread in
thecalibrepluginsforum
87
.
1.9.7 Typesetting Math in ebooks
The calibre ebookviewerhas the ability todisplay mathembedded inebooks (ePub and HTML files). You cantypeset
the math directly with TeX or MathML or AsciiMath. The calibre viewer uses the excellentMathJax
88
library to do
this. This is a brieftutorial on creating ebooks with math in them that work well with the calibre viewer.
86
http://www.mobileread.com/forums/showthread.php?t=118764
87
http://www.mobileread.com/forums/forumdisplay.php?f=237
88
http://www.mathjax.org
182
Chapter 1. Sections
39
calibre User Manual, Release 2.56.0
Asimple HTML file with mathematics
You can write mathematics inline inside a simple HTML file and the calibre viewerwill render itinto properlytypeset
mathematics. In the example below, we use TeX notation for mathematics. You will see that you can use normal TeX
commands, with the small caveat that ampersands and less than and greater than signs have to be written as &
< and > respectively.
The first step is to tell calibre that this will contains maths. You do this by adding the following snippet of code to the
<head>section of the HTML file:
<script type="text/x-mathjax-config"></script>
That’s it, nowyou can type mathematics just as you would in a .tex file. For example, here are Lorentz’s equations:
<h2>The Lorenz z Equations</h2>
<p>
\begin{align}
\dot{x} & = \sigma(y-x) \\
\dot{y} & = \rho x x - y y - xz \\
\dot{z} & = -\beta z + xy
\end{align}
</p>
This snippet looks like the following screen shot in the calibre viewer.
Fig. 1.2: The Lorenz Equations
The complete HTML file, with more equations and inline mathematics is reproduced below. You can convert this
HTML file to EPUB in calibre to end up with an ebook you can distribute easily to otherpeople.
<!DOCTYPE html>
<html>
<!-- Copyright (c) 2012 Design Science, Inc. -->
<head>
<title>Math Test Page</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<!-- This script tag is needed to make calibre's ebook-viewer recpgnize that this file needs math typesetting -->
<script type="text/x-mathjax-config">
// This line adds numbers to all equations automatically, unless explicitly suppressed.
MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: "all"} } });
</script>
<style>
h1 {text-align:center}
h2 {
font-weight: bold;
1.9. Tutorials
183
49
calibre User Manual, Release 2.56.0
background-color: #DDDDDD;
padding: .2em .5em;
margin-top: 1.5em;
border-top: 3px solid #666666;
border-bottom: 2px solid #999999;
}
</style>
</head>
<body>
<h1>Sample Equations</h1>
<h2>The Lorenz Equations</h2>
<p>
\begin{align}
\dot{x} & = \sigma(y-x) \label{lorenz}\\
\dot{y} & = \rho x - y - xz \\
\dot{z} & = -\beta z + xy
\end{align}
</p>
<h2>The Cauchy-Schwarz Inequality</h2>
<p>\[
\left( \sum_{k=1}^n a_k b_k \right)^{\!\!2} \leq
\left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)
\]</p>
<h2>A Cross Product Formula</h2>
<p>\[
\mathbf{V}_1 \times \mathbf{V}_2 =
\begin{vmatrix}
\mathbf{i} & \mathbf{j} & \mathbf{k} \\
\frac{\partial X}{\partial u} & \frac{\partial Y}{\partial u} } & 0 \\
\frac{\partial X}{\partial v} & \frac{\partial Y}{\partial v} } & 0 \\
\end{vmatrix}
\]</p>
<h2>The probability of getting \(k\) heads when flipping \(n\) coins is:</h2>
<p>\[P(E) = {n \choose k} p^k (1-p)^{ n-k} \]</p>
<h2>An Identity of Ramanujan</h2>
<p>\[
\frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} =
1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}}
{1+\frac{e^{-8\pi}} {1+\ldots} } } }
\]</p>
<h2>A Rogers-Ramanujan Identity</h2>
<p>\[
1 +
\frac{q^2}{(1-q)}+\frac{q^6}{(1-q)(1-q^2)}+\cdots =
\prod_{j=0}^{\infty}\frac{1}{(1-q^{5j+2})(1-q^{5j+3})},
\quad\quad \text{for $|q|<1$}.
184
Chapter 1. Sections
43
calibre User Manual, Release 2.56.0
\]</p>
<h2>Maxwell's Equations</h2>
<p>
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} } & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} } & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
</p>
<h2>In-line Mathematics</h2>
<p>While display equations look good for a page of samples, the
ability to mix math and text in a paragraph is also important.
This
expression \(\sqrt{3x-1}+(1+x)^2\) is an example of an inline equation.
As
you see, equations can be used this way as well, without unduly
disturbing the spacing between lines.</p>
<h2>References to equations</h2>
<p>Here is a reference to the Lorenz Equations (\ref{lorenz}). Clicking on the equation number will take you back to the equation.</p>
</body>
</html>
More information
Since the calibre vieweruses the MathJax library to rendermathematics, the best place to find out more about math in
ebooks and get help is theMathJaxwebsite
89
.
1.9.8 Creating AZW3 • EPUB • MOBI Catalogs
calibre’s Create catalog feature enables you to create a catalog of your library in a variety of formats. This help file
describes cataloging options when generating a catalog in AZW3,EPUB and MOBI formats.
• Selectingbookstocatalog (page 186)
• Includedsections (page 186)
• Prefixes(page 187)
• Excludedbooks(page 187)
• Excludedgenres(page 188)
• Otheroptions(page 188)
• Customcatalogcovers(page 189)
• Additionalhelpresources(page 189)
89
http://www.mathjax.org
1.9. Tutorials
185
24
calibre User Manual, Release 2.56.0
Selecting books to catalog
If you want all of your library cataloged, remove any search or filtering criteria in the main window. With a single
book selected, all books in yourlibrarywill becandidates forinclusion in the generated catalog. Individualbooks may
be excluded by various criteria; see theExcludedgenres(page 188)section below for more information.
If you want only some ofyour library cataloged,you have two options:
• Create a multiple selection ofthe books youwant cataloged. Withmorethanone book selectedin calibre’s main
window,only the selected books will be cataloged.
• Use theSearchfield ortheTagBrowsertofilterthe displayedbooks. Onlythedisplayed books will be cataloged.
To begin catalog generation, select the menu item Convert books > Create a catalog of the books in your calibre
library. Youmayalso add a Create Catalogbutton toa toolbarinPreferences > Interface > Toolbars foreasieraccess
to the Generate catalog dialog.
In Catalog options, select AZW3, EPUB or MOBI as the Catalog format. In the Catalog title field, provide a name
that will be usedforthe generated catalog. Ifa catalog of the same name and format already exists, it will be replaced
with the newly-generated catalog.
Enabling Send catalog to device automatically will download the generated catalog to a connected device upon com-
pletion.
Included sections
Sections enabled by a checkmark will be included in the generatedcatalog:
• Authors - all books,sorted by author,presented in a list format. Non-series books are listedbefore series books.
• Titles - all books, sorted by title, presented in a list format.
• Series - all books that are part of a series, sorted by series, presented in a list format.
186
Chapter 1. Sections
Documents you may be interested
Documents you may be interested