Debian Codegraph @

manual/creating_plugins.rst

raw
1 .. _pluginstutorial:
2
3 Writing your own plugins to extend calibre's functionality
4 ====================================================================
5
6 calibre has a very modular design. Almost all functionality in calibre comes in the form of plugins. Plugins are used for conversion, for downloading news (though these are called recipes), for various components of the user interface, to connect to different devices, to process files when adding them to calibre and so on. You can get a complete list of all the built-in plugins in calibre by going to :guilabel:`Preferences->Advanced->Plugins`.
7
8 Here, we will teach you how to create your own plugins to add new features to calibre.
9
10
11 .. contents:: Contents
12 :depth: 2
13 :local:
14
15 .. note:: This only applies to calibre releases >= 0.8.60
16
17 Anatomy of a calibre plugin
18 ---------------------------
19
20 A calibre plugin is very simple, it's just a ZIP file that contains some Python code
21 and any other resources like image files needed by the plugin. Without further ado,
22 let's see a basic example.
23
24 Suppose you have an installation of calibre that you are using to self publish various e-documents in EPUB and MOBI
25 formats. You would like all files generated by calibre to have their publisher set as "Hello world", here's how to do it.
26 Create a file named :file:`__init__.py` (this is a special name and must always be used for the main file of your plugin)
27 and enter the following Python code into it:
28
29 .. literalinclude:: plugin_examples/helloworld/__init__.py
30 :lines: 9-
31
32 That's all. To add this code to calibre as a plugin, simply run the following in
33 the folder in which you created :file:`__init__.py`::
34
35 calibre-customize -b .
36
37 .. note::
38 On macOS, the command line tools are inside the calibre bundle, for example,
39 if you installed calibre in :file:`/Applications` the command line tools
40 are in :file:`/Applications/calibre.app/Contents/MacOS/`.
41
42 You can download the Hello World plugin from
43 :download_file:`helloworld_plugin.zip`.
44
45 Every time you use calibre to convert a book, the plugin's :meth:`run` method will be called and the
46 converted book will have its publisher set to "Hello World". This is a trivial plugin, let's move on to
47 a more complex example that actually adds a component to the user interface.
48
49 A User Interface plugin
50 -------------------------
51
52 This plugin will be spread over a few files (to keep the code clean). It will show you how to get resources
53 (images or data files) from the plugin ZIP file, allow users to configure your plugin,
54 how to create elements in the calibre user interface and how to access
55 and query the books database in calibre.
56
57 You can download this plugin from :download_file:`interface_demo_plugin.zip`
58
59 .. _import_name_txt:
60
61 The first thing to note is that this ZIP file has a lot more files in it, explained below, pay particular attention to
62 ``plugin-import-name-interface_demo.txt``.
63
64 **plugin-import-name-interface_demo.txt**
65 An empty text file used to enable the multi-file plugin magic. This file must be present in all plugins that use
66 more than one .py file. It should be empty and its filename must be of the form: ``plugin-import-name-**some_name**.txt``.
67 The presence of this file allows you to import code from the .py files present inside the ZIP file, using a statement like::
68
69 from calibre_plugins.some_name.some_module import some_object
70
71 The prefix ``calibre_plugins`` must always be present. ``some_name`` comes from the filename of the empty text file.
72 ``some_module`` refers to :file:`some_module.py` file inside the ZIP file. Note that this importing is just as
73 powerful as regular Python imports. You can create packages and subpackages of .py modules inside the ZIP file,
74 just like you would normally (by defining __init__.py in each sub-folder), and everything should "just work".
75
76 The name you use for ``some_name`` enters a global namespace shared by all plugins, **so make it as unique as possible**.
77 But remember that it must be a valid Python identifier (only alphabets, numbers and the underscore).
78
79 **__init__.py**
80 As before, the file that defines the plugin class
81
82 **main.py**
83 This file contains the actual code that does something useful
84
85 **ui.py**
86 This file defines the interface part of the plugin
87
88 **images/icon.png**
89 The icon for this plugin
90
91 **about.txt**
92 A text file with information about the plugin
93
94 **translations**
95 A folder containing .mo files with the translations of the user
96 interface of your plugin into different languages. See below for
97 details.
98
99 Now let's look at the code.
100
101 __init__.py
102 ^^^^^^^^^^^^^
103
104 First, the obligatory ``__init__.py`` to define the plugin metadata:
105
106 .. literalinclude:: plugin_examples/interface_demo/__init__.py
107 :lines: 8-
108
109 The only noteworthy feature is the field :attr:`actual_plugin`. Since calibre has both command line and GUI interfaces,
110 GUI plugins like this one should not load any GUI libraries in __init__.py. The actual_plugin field does this for you,
111 by telling calibre that the actual plugin is to be found in another file inside your ZIP archive, which will only be loaded
112 in a GUI context.
113
114 Remember that for this to work, you must have a plugin-import-name-some_name.txt file in your plugin ZIP file,
115 as discussed above.
116
117 Also there are a couple of methods for enabling user configuration of the plugin. These are discussed below.
118
119 ui.py
120 ^^^^^^^^
121
122 Now let's look at ui.py which defines the actual GUI plugin. The source code is heavily commented and should be self explanatory:
123
124 .. literalinclude:: plugin_examples/interface_demo/ui.py
125 :lines: 15-
126
127 main.py
128 ^^^^^^^^^
129
130 The actual logic to implement the Interface Plugin Demo dialog.
131
132 .. literalinclude:: plugin_examples/interface_demo/main.py
133 :lines: 14-
134
135 Getting resources from the plugin ZIP file
136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
137
138 calibre's plugin loading system defines a couple of built-in functions that allow you to conveniently get files from the plugin ZIP file.
139
140 **get_resources(name_or_list_of_names)**
141 This function should be called with a list of paths to files inside the
142 ZIP file. For example to access the file :file:`icon.png` in the folder
143 images in the ZIP file, you would use: ``images/icon.png``. Always use
144 a forward slash as the path separator, even on Windows. When you pass
145 in a single name, the function will return the raw bytes of that file
146 or None if the name was not found in the ZIP file. If you pass in more
147 than one name then it returns a dictionary mapping the names to bytes. If a
148 name is not found, it will not be present in the returned dictionary.
149
150 **get_icons(name_or_list_of_names, plugin_name='')**
151 A wrapper for get_resources() that creates QIcon objects
152 from the raw bytes returned by get_resources. If a name is not found
153 in the ZIP file the corresponding QIcon will be null. In order to
154 support icon theme-ing, pass in the human friendly name of your plugin
155 as ``plugin_name``. If the user is using an icon theme with icons for
156 your plugin, they will be loaded preferentially.
157
158
159 Enabling user configuration of your plugin
160 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
161
162 To allow users to configure your plugin, you must define three methods in your base plugin class, **is_customizable**, **config_widget** and **save_settings** as shown below:
163
164 .. literalinclude:: plugin_examples/interface_demo/__init__.py
165 :pyobject: InterfacePluginDemo.is_customizable
166
167 .. literalinclude:: plugin_examples/interface_demo/__init__.py
168 :pyobject: InterfacePluginDemo.config_widget
169
170 .. literalinclude:: plugin_examples/interface_demo/__init__.py
171 :pyobject: InterfacePluginDemo.save_settings
172
173 calibre has many different ways to store configuration data (a legacy of its long history). The recommended way is to use the **JSONConfig** class, which stores your configuration information in a .json file.
174
175 The code to manage configuration data in the demo plugin is in config.py:
176
177 .. literalinclude:: plugin_examples/interface_demo/config.py
178 :lines: 8-
179
180 The ``prefs`` object is now available throughout the plugin code by a simple::
181
182 from calibre_plugins.interface_demo.config import prefs
183
184
185 You can see the ``prefs`` object being used in main.py:
186
187 .. literalinclude:: plugin_examples/interface_demo/main.py
188 :lines: 142-
189
190
191 Edit book plugins
192 ------------------------------------------
193
194 Now let's change gears for a bit and look at creating a plugin to add tools to
195 the calibre book editor. The plugin is available here:
196 :download_file:`editor_demo_plugin.zip`.
197
198 The first step, as for all plugins is to create the
199 import name empty txt file, as described :ref:`above <import_name_txt>`.
200 We shall name the file ``plugin-import-name-editor_plugin_demo.txt``.
201
202 Now we create the mandatory ``__init__.py`` file that contains metadata about
203 the plugin -- its name, author, version, etc.
204
205 .. literalinclude:: plugin_examples/editor_demo/__init__.py
206 :lines: 7-
207
208 A single editor plugin can provide multiple tools each tool corresponds to a
209 single button in the toolbar and entry in the :guilabel:`Plugins` menu in the
210 editor. These can have sub-menus in case the tool has multiple related actions.
211
212 The tools must all be defined in the file ``main.py`` in your plugin. Every
213 tool is a class that inherits from the
214 :class:`calibre.gui2.tweak_book.plugin.Tool` class. Let's look at ``main.py``
215 from the demo plugin, the source code is heavily commented and should be
216 self-explanatory. Read the API documents of the
217 :class:`calibre.gui2.tweak_book.plugin.Tool` class for more details.
218
219 main.py
220 ^^^^^^^^^
221
222 Here we will see the definition of a single tool that will multiply all font
223 sizes in the book by a number provided by the user. This tool demonstrates
224 various important concepts that you will need in developing your own plugins,
225 so you should read the (heavily commented) source code carefully.
226
227 .. literalinclude:: plugin_examples/editor_demo/main.py
228 :lines: 7-
229
230 Let's break down ``main.py``. We see that it defines a single tool, named
231 *Magnify fonts*. This tool will ask the user for a number and multiply all font
232 sizes in the book by that number.
233
234 The first important thing is the tool name which you must set to some
235 relatively unique string as it will be used as the key for this tool.
236
237 The next important entry point is the
238 :meth:`calibre.gui2.tweak_book.plugin.Tool.create_action`. This method creates
239 the QAction objects that appear in the plugins toolbar and plugin menu.
240 It also, optionally, assigns a keyboard shortcut that the user can customize.
241 The triggered signal from the QAction is connected to the ask_user() method
242 that asks the user for the font size multiplier, and then runs the
243 magnification code.
244
245 The magnification code is well commented and fairly simple. The main things to
246 note are that you get a reference to the editor window as ``self.gui`` and the
247 editor *Boss* as ``self.boss``. The *Boss* is the object that controls the editor
248 user interface. It has many useful methods, that are documented in the
249 :class:`calibre.gui2.tweak_book.boss.Boss` class.
250
251 Finally, there is ``self.current_container`` which is a reference to the book
252 being edited as a :class:`calibre.ebooks.oeb.polish.container.Container`
253 object. This represents the book as a collection of its constituent
254 HTML/CSS/image files and has convenience methods for doing many useful things.
255 The container object and various useful utility functions that can be reused in
256 your plugin code are documented in :ref:`polish_api`.
257
258 Adding translations to your plugin
259 --------------------------------------
260
261 You can have all the user interface strings in your plugin translated and
262 displayed in whatever language is set for the main calibre user interface.
263
264 The first step is to go through your plugin's source code and mark all user
265 visible strings as translatable, by surrounding them in _(). For example::
266
267 action_spec = (_('My plugin'), None, _('My plugin is cool'), None)
268
269 Then use some program to generate .po files from your plugin source code. There
270 should be one .po file for every language you want to translate into. For
271 example: de.po for German, fr.po for French and so on. You can use the
272 `Poedit <https://poedit.net/>`_ program for this.
273
274 Send these .po files to your translators. Once you get them back, compile them
275 into .mo files. You can again use Poedit for that, or just do::
276
277 calibre-debug -c "from calibre.translations.msgfmt import main; main()" filename.po
278
279 Put the .mo files into the ``translations`` folder in your plugin.
280
281 The last step is to simply call the function `load_translations()` at the top
282 of your plugin's .py files. For performance reasons you should only call this
283 function in those .py files that actually have translatable strings. So in a
284 typical User Interface plugin you would call it at the top of ``ui.py`` but not
285 ``__init__.py``.
286
287 You can test the translations of your plugins by changing the user interface
288 language in calibre under :guilabel:`Preferences->Interface->Look & feel` or by running calibre
289 with the ``CALIBRE_OVERRIDE_LANG`` environment variable set. For example::
290
291 CALIBRE_OVERRIDE_LANG=de
292
293 Replace ``de`` with the language code of the language you want to test.
294
295 For translations with plurals, use the ``ngettext()`` function instead of
296 ``_()``. For example::
297
298 ngettext('Delete a book', 'Delete {} books', num_books).format(num_books)
299
300 The plugin API
301 --------------------------------
302
303 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.
304 Details on each class, including the base class of all plugins can be found in :ref:`plugins`.
305
306 Your plugin is almost certainly going to use code from calibre. To learn
307 how to find various bits of functionality in the
308 calibre code base, read the section on the calibre :ref:`code_layout`.
309
310 Debugging plugins
311 -------------------
312
313 The first, most important step is to run calibre in debug mode. You can do this from the command line with::
314
315 calibre-debug -g
316
317 Or from within calibre by right-clicking the :guilabel:`Preferences` button or using the :kbd:`Ctrl+Shift+R` keyboard shortcut.
318
319 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.
320
321 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.
322
323 You can quickly test changes to your plugin by using the following command
324 line::
325
326 calibre-debug -s; calibre-customize -b /path/to/your/plugin/folder; calibre
327
328 This will shutdown a running calibre, wait for the shutdown to complete, then update your plugin in calibre and relaunch calibre.
329
330 More plugin examples
331 ----------------------
332
333 You can find a list of many sophisticated calibre plugins `here <https://www.mobileread.com/forums/showthread.php?t=118764>`_.
334
335 Sharing your plugins with others
336 ----------------------------------
337
338 If you would like to share the plugins you have created with other users of calibre, post your plugin in a new thread in the
339 `calibre plugins forum <https://www.mobileread.com/forums/forumdisplay.php?f=237>`_.