plugin_manager.py 13.9 KB
Newer Older
mathieui's avatar
mathieui committed
1
2
3
4
5
6
7
"""
Plugin manager module.
Define the PluginManager class, the one that glues all the plugins and
the API together. Defines also a bunch of variables related to the
plugin env.
"""

8
import os
mathieui's avatar
mathieui committed
9
from os import path
mathieui's avatar
mathieui committed
10
import logging
11

mathieui's avatar
mathieui committed
12
from poezio import tabs
13
from poezio.core.structs import Command
mathieui's avatar
mathieui committed
14
15
from poezio.plugin import PluginAPI
from poezio.config import config
mathieui's avatar
mathieui committed
16

mathieui's avatar
mathieui committed
17
18
log = logging.getLogger(__name__)

19
class PluginManager(object):
mathieui's avatar
mathieui committed
20
21
22
23
24
    """
    Plugin Manager
    Contains all the references to the plugins
    And keeps track of everything the plugin has done through the API.
    """
25
26
    def __init__(self, core):
        self.core = core
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
        # module name -> module object
        self.modules = {}
        # module name -> plugin object
        self.plugins = {}
        # module name -> dict of commands loaded for the module
        self.commands = {}
        # module name -> list of event_name/handler pairs loaded for the module
        self.event_handlers = {}
        # module name -> dict of tab types; tab type -> commands
        # loaded by the module
        self.tab_commands = {}
        # module name → dict of keys/handlers loaded for the module
        self.keys = {}
        # module name → dict of tab types; tab type → list of keybinds (tuples)
        self.tab_keys = {}
42
        self.roster_elements = {}
43

44
45
        from importlib import machinery
        self.finder = machinery.PathFinder()
46
47
48
49
50

        self.initial_set_plugins_dir()
        self.initial_set_plugins_conf_dir()
        self.fill_load_path()

51
        self.plugin_api = PluginAPI(core, self)
52

mathieui's avatar
mathieui committed
53
54
55
    def disable_plugins(self):
        for plugin in set(self.plugins.keys()):
            try:
56
                self.unload(plugin, notify=False)
mathieui's avatar
mathieui committed
57
58
59
            except:
                pass

60
    def load(self, name, notify=True):
mathieui's avatar
mathieui committed
61
62
63
        """
        Load a plugin.
        """
64
        if name in self.plugins:
65
            self.unload(name)
66
67

        try:
68
            module = None
69
70
71
72
73
            loader = self.finder.find_module(name, self.load_path)
            if not loader:
                self.core.information('Could not find plugin: %s' % name)
                return
            module = loader.load_module()
74
        except Exception as e:
75
            log.debug("Could not load plugin %s", name, exc_info=True)
76
77
            self.core.information("Could not load plugin %s: %s" % (name, e),
                                  'Error')
78
        finally:
79
80
            if not module:
                return
81
82
83

        self.modules[name] = module
        self.commands[name] = {}
mathieui's avatar
mathieui committed
84
        self.keys[name] = {}
85
        self.tab_keys[name] = {}
86
        self.tab_commands[name] = {}
87
        self.event_handlers[name] = []
88
89
        try:
            self.plugins[name] = None
90
91
            self.plugins[name] = module.Plugin(self.plugin_api, self.core,
                                               self.plugins_conf_dir)
92
93
94
        except Exception as e:
            log.error('Error while loading the plugin %s', name, exc_info=True)
            if notify:
95
96
                self.core.information('Unable to load the plugin %s: %s' %
                                      (name, e),
97
                                      'Error')
98
99
100
101
            self.unload(name, notify=False)
        else:
            if notify:
                self.core.information('Plugin %s loaded' % name, 'Info')
102

103
    def unload(self, name, notify=True):
104
105
        if name in self.plugins:
            try:
106
107
                for command in self.commands[name].keys():
                    del self.core.commands[command]
mathieui's avatar
mathieui committed
108
109
                for key in self.keys[name].keys():
                    del self.core.key_func[key]
110
                for tab in list(self.tab_commands[name].keys()):
111
                    for command in self.tab_commands[name][tab][:]:
112
113
                        self.del_tab_command(name, getattr(tabs, tab),
                                             command[0])
114
                    del self.tab_commands[name][tab]
115
                for tab in list(self.tab_keys[name].keys()):
116
                    for key in self.tab_keys[name][tab][:]:
117
118
                        self.del_tab_key(name, getattr(tabs, tab), key[0])
                    del self.tab_keys[name][tab]
119
                for event_name, handler in self.event_handlers[name][:]:
120
                    self.del_event_handler(name, event_name, handler)
121

122
123
                if self.plugins[name] is not None:
                    self.plugins[name].unload()
124
                del self.plugins[name]
125
                del self.commands[name]
mathieui's avatar
mathieui committed
126
                del self.keys[name]
127
                del self.tab_commands[name]
128
                del self.event_handlers[name]
129
130
                if notify:
                    self.core.information('Plugin %s unloaded' % name, 'Info')
131
            except Exception as e:
132
                log.debug("Could not unload plugin %s", name, exc_info=True)
133
134
                self.core.information("Could not unload plugin %s: %s" %
                                      (name, e),
135
                                      'Error')
136

137
138
    def add_command(self, module_name, name, handler, help,
                    completion=None, short='', usage=''):
mathieui's avatar
mathieui committed
139
140
141
142
        """
        Add a global command.
        """
        if name in self.core.commands:
143
            raise Exception("Command '%s' already exists" % (name,))
mathieui's avatar
mathieui committed
144
145

        commands = self.commands[module_name]
146
        commands[name] = Command(handler, help, completion, short, usage)
147
        self.core.commands[name] = commands[name]
mathieui's avatar
mathieui committed
148

149
    def del_command(self, module_name, name):
mathieui's avatar
mathieui committed
150
151
152
        """
        Remove a global command added through add_command.
        """
153
154
155
156
157
        if name in self.commands[module_name]:
            del self.commands[module_name][name]
            if name in self.core.commands:
                del self.core.commands[name]

158
159
    def add_tab_command(self, module_name, tab_type, name, handler, help,
                        completion=None, short='', usage=''):
mathieui's avatar
mathieui committed
160
161
162
        """
        Add a command only for a type of Tab.
        """
163
164
        commands = self.tab_commands[module_name]
        t = tab_type.__name__
mathieui's avatar
mathieui committed
165
166
        if name in tab_type.plugin_commands:
            return
167
168
169
        if not t in commands:
            commands[t] = []
        commands[t].append((name, handler, help, completion))
170
        tab_type.plugin_commands[name] = Command(handler, help,
171
                                                      completion, short, usage)
172
173
        for tab in self.core.tabs:
            if isinstance(tab, tab_type):
mathieui's avatar
mathieui committed
174
                tab.update_commands()
175
176

    def del_tab_command(self, module_name, tab_type, name):
mathieui's avatar
mathieui committed
177
178
179
        """
        Remove a command added through add_tab_command.
        """
180
181
182
183
184
185
186
187
188
189
190
191
        commands = self.tab_commands[module_name]
        t = tab_type.__name__
        if not t in commands:
            return
        for command in commands[t]:
            if command[0] == name:
                commands[t].remove(command)
                del tab_type.plugin_commands[name]
                for tab in self.core.tabs:
                    if isinstance(tab, tab_type) and name in tab.commands:
                        del tab.commands[name]

192
    def add_tab_key(self, module_name, tab_type, key, handler):
mathieui's avatar
mathieui committed
193
194
195
        """
        Associate a key binding to a handler only for a type of Tab.
        """
196
197
198
199
200
201
202
203
204
205
206
207
208
        keys = self.tab_keys[module_name]
        t = tab_type.__name__
        if key in tab_type.plugin_keys:
            return
        if not t in keys:
            keys[t] = []
        keys[t].append((key, handler))
        tab_type.plugin_keys[key] = handler
        for tab in self.core.tabs:
            if isinstance(tab, tab_type):
                tab.update_keys()

    def del_tab_key(self, module_name, tab_type, key):
mathieui's avatar
mathieui committed
209
210
211
        """
        Remove a key binding added through add_tab_key.
        """
212
213
214
215
216
217
218
219
220
221
222
223
        keys = self.tab_keys[module_name]
        t = tab_type.__name__
        if not t in keys:
            return
        for _key in keys[t]:
            if _key[0] == key:
                keys[t].remove(_key)
                del tab_type.plugin_keys[key]
                for tab in self.core.tabs:
                    if isinstance(tab, tab_type) and key in tab.key_func:
                        del tab.key_func[key]

mathieui's avatar
mathieui committed
224
    def add_key(self, module_name, key, handler):
mathieui's avatar
mathieui committed
225
226
227
228
        """
        Associate a global key binding to a handler, except if it
        already exists.
        """
mathieui's avatar
mathieui committed
229
        if key in self.core.key_func:
230
            raise Exception("Key '%s' already exists" % (key,))
mathieui's avatar
mathieui committed
231
232
233
234
235
        keys = self.keys[module_name]
        keys[key] = handler
        self.core.key_func[key] = handler

    def del_key(self, module_name, key):
mathieui's avatar
mathieui committed
236
237
238
        """
        Remove a global key binding added by a plugin.
        """
mathieui's avatar
mathieui committed
239
240
241
242
243
        if key in self.keys[module_name]:
            del self.keys[module_name][key]
            if key in self.core.key_func:
                del self.core.commands[key]

244
    def add_event_handler(self, module_name, event_name, handler, position=0):
mathieui's avatar
mathieui committed
245
246
        """
        Add an event handler. If event_name isn’t in the event list, assume
louiz’'s avatar
louiz’ committed
247
        it is a slixmpp event.
mathieui's avatar
mathieui committed
248
        """
249
250
        eh = self.event_handlers[module_name]
        eh.append((event_name, handler))
251
252
253
254
        if event_name in self.core.events.events:
            self.core.events.add_event_handler(event_name, handler, position)
        else:
            self.core.xmpp.add_event_handler(event_name, handler)
255
256

    def del_event_handler(self, module_name, event_name, handler):
mathieui's avatar
mathieui committed
257
258
259
        """
        Remove an event handler if it exists.
        """
260
261
262
263
        if event_name in self.core.events.events:
            self.core.events.del_event_handler(None, handler)
        else:
            self.core.xmpp.del_event_handler(event_name, handler)
264
        eh = self.event_handlers[module_name]
265
        eh = [e for e in eh if e != (event_name, handler)]
266
267
268
269
270
271
272

    def completion_load(self, the_input):
        """
        completion function that completes the name of the plugins, from
        all .py files in plugins_dir
        """
        try:
mathieui's avatar
mathieui committed
273
            names = set()
274
            for path in self.load_path:
mathieui's avatar
mathieui committed
275
276
277
278
279
                try:
                    add = set(os.listdir(path))
                    names |= add
                except:
                    pass
280
        except OSError as e:
281
            self.core.information('Completion failed: %s' % e, 'Error')
282
            return False
mathieui's avatar
mathieui committed
283
284
285
        plugins_files = [name[:-3] for name in names if name.endswith('.py')
                and name != '__init__.py' and not name.startswith('.')]
        plugins_files.sort()
286
        position = the_input.get_argument_position(quoted=False)
287
288
        return the_input.new_completion(plugins_files, position, '',
                                        quotify=False)
289
290
291

    def completion_unload(self, the_input):
        """
292
        completion function that completes the name of loaded plugins
293
        """
294
        position = the_input.get_argument_position(quoted=False)
295
296
        return the_input.new_completion(sorted(self.plugins.keys()), position,
                                        '', quotify=False)
297
298

    def on_plugins_dir_change(self, new_value):
299
300
301
        self.plugins_dir = new_value
        self.check_create_plugins_dir()
        self.fill_load_path()
mathieui's avatar
mathieui committed
302
303

    def on_plugins_conf_dir_change(self, new_value):
304
305
306
307
308
309
310
        self.plugins_conf_dir = new_value
        self.check_create_plugins_conf_dir()

    def initial_set_plugins_conf_dir(self):
        """
        Create the plugins_conf_dir
        """
311
        plugins_conf_dir = config.get('plugins_conf_dir')
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
        if not plugins_conf_dir:
            config_home = os.environ.get('XDG_CONFIG_HOME')
            if not config_home:
                config_home = os.path.join(os.environ.get('HOME'), '.config')
            plugins_conf_dir = os.path.join(config_home, 'poezio', 'plugins')
        self.plugins_conf_dir = os.path.expanduser(plugins_conf_dir)
        self.check_create_plugins_conf_dir()

    def check_create_plugins_conf_dir(self):
        """
        Create the plugins config directory if it does not exist.
        Returns True on success, False on failure.
        """
        if not os.access(self.plugins_conf_dir, os.R_OK | os.X_OK):
            try:
                os.makedirs(self.plugins_conf_dir)
            except OSError:
                log.error('Unable to create the plugin conf dir: %s',
330
                        self.plugins_conf_dir, exc_info=True)
331
332
333
334
335
336
337
                return False
        return True

    def initial_set_plugins_dir(self):
        """
        Set the plugins_dir on start
        """
338
        plugins_dir = config.get('plugins_dir')
339
340
        plugins_dir = plugins_dir or\
            os.path.join(os.environ.get('XDG_DATA_HOME') or\
341
342
                             os.path.join(os.environ.get('HOME'),
                                          '.local', 'share'),
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
                         'poezio', 'plugins')
        self.plugins_dir = os.path.expanduser(plugins_dir)
        self.check_create_plugins_dir()

    def check_create_plugins_dir(self):
        """
        Create the plugins directory if it does not exist.
        Returns True on success, False on failure.
        """
        if not os.access(self.plugins_dir, os.R_OK | os.X_OK):
            try:
                os.makedirs(self.plugins_dir, exist_ok=True)
            except OSError:
                log.error('Unable to create the plugins dir: %s',
                        self.plugins_dir, exc_info=True)
                return False
        return True

    def fill_load_path(self):
        """
        Append the global packages and the source directory if available
        """

        self.load_path = []

368
369
        default_plugin_path = path.join(path.dirname(path.dirname(__file__)),
                                        'plugins')
370
371
372
373
374
375
376
377

        if os.access(default_plugin_path, os.R_OK | os.X_OK):
            self.load_path.insert(0, default_plugin_path)

        if os.access(self.plugins_dir, os.R_OK | os.X_OK):
            self.load_path.append(self.plugins_dir)

        try:
mathieui's avatar
mathieui committed
378
            from poezio import poezio_plugins
379
380
381
382
383
384
        except:
            pass
        else:
            if poezio_plugins.__path__:
                self.load_path.append(list(poezio_plugins.__path__)[0])