summaryrefslogtreecommitdiff
path: root/portato/plugin.py
blob: a833696a9746e981fab968c09ba864b02a642390 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# -*- coding: utf-8 -*-
#
# File: portato/plugin.py
# This file is part of the Portato-Project, a graphical portage-frontend.
#
# Copyright (C) 2007 René 'Necoro' Neumann
# This is free software.  You may redistribute copies of it under the terms of
# the GNU General Public License version 2.
# There is NO WARRANTY, to the extent permitted by law.
#
# Written by René 'Necoro' Neumann <necoro@necoro.net>

"""A module containing the management of the plugin system."""

import os, os.path
from xml.dom.minidom import parse

from constants import PLUGIN_DIR
from helper import *

class ParseException (Exception):
	pass

class Options (object):
	"""The <options>-element."""

	__options = ("disabled", "blocking")

	def __init__ (self, options = None):

		self.disabled = False
		self.blocking = False

		if options:
			self.parse(options)

	def parse (self, options):
		for opt in options:
			if opt.hasChildNodes():
				nodes = opt.childNodes
			
				if len(nodes) > 1:
					raise ParseException, "Malformed option"
			
				if nodes[0].nodeType != nodes[0].TEXT_NODE:
					raise ParseException, "Malformed option"

				type = str(nodes[0].nodeValue.strip())

				if type in self.__options:
					self.set(type, True)
			else:
				raise ParseException, "Malformed option"

	def get (self, name):
		return self.__getattribute__(name)

	def set (self, name, value):
		return self.__setattr__(name, value)

class Menu:
	"""A single <menu>-element."""
	def __init__ (self, plugin, label, call):
		"""Constructor.

		@param plugin: the plugin this menu belongs to
		@type plugin: Plugin
		@param label: the label to show
		@type label: string
		@param call: the function to call relative to the import statement
		@type call: string

		@raises ParseException: on parsing errors"""

		if not label:
			raise ParseException, "label attribute missing"

		if not call:
			raise ParseException, "call attribute missing"

		self.label = label
		self.plugin = plugin

		if self.plugin.needs_import(): # get import
			imp = self.plugin.get_import()
			try:
				mod = __import__(imp, globals(), locals(), [call])
			except ImportError:
				raise ParseException, imp+" cannot be imported"

			try:
				self.call = eval("mod."+call) # build function
			except AttributeError:
				raise ParseException, call+" cannot be imported"
		else:
			try:
				self.call = eval(call)
			except AttributeError:
				raise ParseException, call+" cannot be imported"

class Connect:
	"""A single <connect>-element."""

	def __init__ (self, hook, type, depend_plugin):
		"""Constructor.

		@param hook: the parent Hook
		@type hook: Hook
		@param type: the type of the connect ("before", "after", "override")
		@type type: string
		@param depend_plugin: a plugin we are dependant on
		@type depend_plugin: string or None
		
		@raises ParseException: on parsing errors"""

		if not type in ["before", "after", "override"]:
			raise ParseException, "Unknown connect type %s" % type

		self.type = type
		self.hook = hook
		self.depend_plugin = depend_plugin

	def is_before_type (self):
		return self.type == "before"

	def is_after_type (self):
		return self.type == "after"

	def is_override_type (self):
		return self.type == "override"

class Hook:
	"""A single <hook>-element."""

	def __init__ (self, plugin, hook, call):
		"""Constructor.

		@param plugin: the parent Plugin
		@type plugin: Plugin
		@param hook: the hook to add to
		@type hook: string
		@param call: the call to make
		@type call: string

		@raises ParseException: on parsing errors"""

		if not hook: 
			raise ParseException, "hook attribute missing"

		if not call: 
			raise ParseException, "call attribute missing"
		
		self.plugin = plugin
		self.hook = hook
		self.call = call
		self.connects = []

	def parse_connects (self, connects):
		"""This gets a list of <connect>-elements and parses them.
		
		@param connects: the list of <connect>'s
		@type connects: NodeList
		
		@raises ParseException: on parsing errors"""
		
		if not connects:
			raise ParseException, "No connect elements in hook"

		for c in connects:
			type = c.getAttribute("type")
			if type == '': 
				type = "before"

			# get dep_plugin if available
			dep_plugin = None
			if c.hasChildNodes():
				nodes = c.childNodes
				if len(nodes) > 1:
					raise ParseException, "Malformed connect"
				
				if nodes[0].nodeType != nodes[0].TEXT_NODE:
					raise ParseException, "Malformed connect"

				dep_plugin = nodes[0].nodeValue.strip()

			connect = Connect(self, type, dep_plugin)
			self.connects.append(connect)
		
class Plugin:
	"""A complete plugin."""

	def __init__ (self, file, name, author):
		"""Constructor.

		@param file: the file name of the plugin.xml
		@type file: string
		@param name: the name of the plugin
		@type name: string
		@param author: the author of the plugin
		@type author: string"""

		self.file = file
		self.name = name
		self.author = author
		self._import = None
		self.hooks = []
		self.menus = []
		self.options = Options()

	def parse_hooks (self, hooks):
		"""Gets a list of <hook>-elements and parses them.

		@param hooks: the list of elements
		@type hooks: NodeList
		
		@raises ParseException: on parsing errors"""

		for h in hooks:
			hook = Hook(self, str(h.getAttribute("hook")), str(h.getAttribute("call")))
			hook.parse_connects(h.getElementsByTagName("connect"))
			self.hooks.append(hook)

	def parse_menus (self, menus):
		"""Gets a list of <menu>-elements and parses them.

		@param menus: the list of elements
		@type menus: NodeList

		@raises ParseException: on parsing errors"""

		for m in menus:
			menu = Menu(self, str(m.getAttribute("label")), str(m.getAttribute("call")))
			self.menus.append(menu)

	def parse_options (self, options):
		if options:
			for o in options:
				self.options.parse(o.getElementsByTagName("option"))
	
	def set_import (self, imports):
		"""This gets a list of imports and parses them - setting the import needed to call the plugin.

		@param imports: list of imports
		@type imports: NodeList
		
		@raises ParseException: on parsing errors"""

		if len(imports) > 1:
			raise ParseException, "More than one import statement."

		if imports[0].hasChildNodes():
			nodes = imports[0].childNodes
			
			if len(nodes) > 1:
				raise ParseException, "Malformed import"
			
			if nodes[0].nodeType != nodes[0].TEXT_NODE:
				raise ParseException, "Malformed import"

			self._import = str(nodes[0].nodeValue.strip())

			try: # try loading
				mod = __import__(self._import)
				del mod
			except ImportError:
				raise ParseException, self._import+" cannot be imported"
		else:
			raise ParseException, "Malformed import"

	def needs_import (self):
		"""Returns True if an import is required prior to calling the plugin.
		@rtype: bool"""
		return self._import is not None

	def get_import (self):
		"""Returns the module to import.
		@rtype: string"""
		return self._import

	def get_option(self, name):
		return self.options.get(name)

	def set_option (self, name, value):
		return self.options.set(name, value)

	def is_enabled (self):
		return not self.get_option("disabled")

class PluginQueue:
	"""Class managing and loading the plugins."""

	def __init__ (self, frontend, load = True):
		"""Constructor.
		
		@param frontend: the frontend used
		@type frontend: string
		@param load: if False nothing is loaded
		@type load: bool"""

		self.frontend = frontend
		self.list = []
		self.hooks = {}
		if load:
			self._load()

	def get_plugins (self, list_disabled = True):
		return [x for x in self.list if (x.is_enabled() or list_disabled)]

	def get_plugin_data (self, list_disabled = False):
		return [(x.name, x.author) for x in self.list if (x.is_enabled() or list_disabled)]

	def get_plugin_menus (self, list_disabled = False):
		return flatten([x.menus for x in self.list if (x.is_enabled() or list_disabled)])

	def hook (self, hook, *hargs, **hkwargs):
		"""This is a method taking care of calling the plugins.
		
		B{Example}::
			
			@pluginQueue.hook("some_hook", data)
			def function (a, b, c):
				orig_call(b,c,data)
			
			def function (a, b, c):
				hook = pluginQueue.hook("some_hook", data)
				hook(orig_call)(b,c,data)

		@param hook: the name of the hook
		@type hook: string"""
			
		def call (cmd):
			"""Convienience function for calling a connect.
			@param cmd: the actual Connect
			@type cmd: Connect"""

			imp = ""
			if cmd.hook.plugin.needs_import(): # get import
				imp = cmd.hook.plugin.get_import()
				try:
					mod = __import__(imp, globals(), locals(), [cmd.hook.call])
				except ImportError:
					error("%s cannot be imported.", imp)
					return

				try:
					f = eval("mod."+cmd.hook.call) # build function
				except AttributeError:
					error("%s cannot be imported.", cmd.hook.call)
			else:
				try:
					f = eval(cmd.hook.call)
				except AttributeError:
					error("%s cannot be imported", cmd.hook.call)

			return f(*hargs, **hkwargs) # call function

		def hook_decorator (func):
			"""This is the real decorator."""
			
			if hook in self.hooks:
				list = self.hooks[hook]
			else:
				list = ([],[],[])

			# remove disabled
			_list = ([],[],[])
			for i in range(len(list)):
				for cmd in list[i]:
					if cmd.hook.plugin.is_enabled():
						_list[i].append(cmd)
			
			list = _list

			def wrapper (*args, **kwargs):
				
				ret = None

				# before
				for cmd in list[0]:
					debug("Accessing hook '%s' of plugin '%s' (before).", hook, cmd.hook.plugin.name)
					call(cmd)
				
				if list[1]: # override
					info("Overriding hook '%s' with plugin '%s'.", hook, list[1][0].hook.plugin.name)
					ret = call(list[1][0])
				else: # normal
					ret = func(*args, **kwargs)

				# after
				for cmd in list[2]:
					debug("Accessing hook '%s' of plugin '%s' (after).", hook, cmd.hook.plugin.name)
					call(cmd)

				return ret

			return wrapper

		return hook_decorator

	def _load (self):
		"""Load the plugins."""
		plugins = filter(lambda x: x.endswith(".xml"), os.listdir(PLUGIN_DIR))
		plugins = map(lambda x: os.path.join(PLUGIN_DIR, x), plugins)

		for p in plugins:
			doc = parse(p)
			
			try:
				try:
					list = doc.getElementsByTagName("plugin")
					if len(list) != 1:
						raise ParseException, "Number of plugin elements unequal to 1."
					
					elem = list[0]

					frontendOK = None
					for f in elem.getElementsByTagName("frontend"):
						if f.hasChildNodes():
							nodes = f.childNodes
							if len(nodes) > 1:
								raise ParseException, "Malformed frontend"
				
							if nodes[0].nodeType != nodes[0].TEXT_NODE:
								raise ParseException, "Malformed frontend"

							fValue = nodes[0].nodeValue.strip()
							if fValue == self.frontend:
								frontendOK = True # one positive is enough
								break
							elif frontendOK is None: # do not make negative if we already have a positive
								frontendOK = False

					if frontendOK is None or frontendOK == True:
						plugin = Plugin(p, elem.getAttribute("name"), elem.getAttribute("author"))
						plugin.parse_hooks(elem.getElementsByTagName("hook"))
						plugin.set_import(elem.getElementsByTagName("import"))
						plugin.parse_menus(elem.getElementsByTagName("menu"))
						plugin.parse_options(elem.getElementsByTagName("options"))
					
						self.list.append(plugin)

				except ParseException, e:
					error("Malformed plugin \"%s\". Reason: %s", p, e[0])
			finally:
				doc.unlink()

		self._organize()

	def _organize (self):
		"""Creates the lists of connects in a way, that all dependencies are fullfilled."""
		unresolved_before = {} 
		unresolved_after = {}
		star_before = {} # should be _before_ all other
		star_after = {} # should be _after_ all other

		for plugin in self.list: # plugins
			for hook in plugin.hooks: # hooks in plugin
				if not hook.hook in self.hooks:
					self.hooks[hook.hook] = ([], [], [])

				for connect in hook.connects: # connects in hook
					
					# type="before"
					if connect.is_before_type():
						if connect.depend_plugin is None: # no dependency -> straight add
							self.hooks[hook.hook][0].append(connect)
						elif connect.depend_plugin == "*":
							self.hooks[hook.hook][0][0:0] = [connect]
						elif connect.depend_plugin == "-*":
							if not hook.hook in star_before:
								star_before[hook.hook] = []

							star_before[hook.hook].append(connect)
						else:
							named = [x.plugin.name for x in self.hooks[hook.hook][0]]
							if connect.depend_plugin in named:
								self.hooks[hook.hook][0].insert(named.index(connect.depend_plugin), connect)
							else:
								if not hook.hook in unresolved_before:
									unresolved_before[hook.hook] = []
								
								unresolved_before[hook.hook].append(connect)

					# type = "after"
					elif connect.is_after_type():
						if connect.depend_plugin is None: # no dependency -> straight add
							self.hooks[hook.hook][2].append(connect)
						elif connect.depend_plugin == "*":
							if not hook.hook in star_after:
								star_after[hook.hook] = []

							star_after[hook.hook].append(connect)
						elif connect.depend_plugin == "-*":
							self.hooks[hook.hook][2][0:0] = [connect]
						else:
							named = [x.plugin.name for x in self.hooks[hook.hook][2]]
							if connect.depend_plugin in named:
								self.hooks[hook.hook][2].insert(named.index(connect.depend_plugin)+1, connect)
							else:
								if not hook.hook in unresolved_after:
									unresolved_after[hook.hook] = []
								
								unresolved_after[hook.hook].append(connect)
					
					# type = "override"
					elif connect.is_override_type():
						if self.hooks[hook.hook][1]:
							warn("For hook '%s' an override is already defined by plugin '%s'!", hook.hook, self.hooks[hook.hook][1][0])
						
						self.hooks[hook.hook][1][:1] = [connect]
						continue
		
		self._resolve_unresolved(unresolved_before, unresolved_after)

		for hook in star_before:
			self.hooks[hook][0].extend(star_before[hook]) # append the list

		for hook in star_after:
			self.hooks[hook][2].extend(star_after[hook]) # append the list


	def _resolve_unresolved (self, before, after):
		def resolve(hook, list, idx, add):
			if not list: 
				return
			
			changed = False
			for connect in list[:]:
				named = [x.plugin.name for x in self.hooks[hook][idx]]
				if connect.depend_plugin in named:
					changed = True
					self.hooks[hook][idx].insert(named.index(connect.depend_plugin)+add, connect)
					list.remove(connect)

			if changed:
				resolve(hook, list, idx, add)

			for l in list:
				warn("Command for hook '%s' in plugin '%s' could not be added due to missing dependant: '%s'!", hook, l.hook.plugin.name, l.depend_plugin)

		for hook in before:
			resolve(hook, before[hook], 0, 0)
		
		for hook in after:
			resolve(hook, after[hook], 2, 1)


__plugins = None

def load_plugins(frontend):
	"""Loads the plugins for a given frontend.
	@param frontend: The frontend. See L{constants.FRONTENDS} for the correct list of values.
	@type frontend: string"""

	global __plugins
	if __plugins is None or __plugins.frontend != frontend:
		__plugins = PluginQueue(frontend)

def get_plugin_queue():
	"""Returns the actual L{PluginQueue}. If it is C{None}, they are not being loaded yet.

	@returns: the actual L{PluginQueue} or C{None}
	@rtype: PluginQueue"""
	return __plugins

def hook(hook, *args, **kwargs):
	if __plugins is None:
		def pseudo_decorator(f):
			return f
		return pseudo_decorator
	else:
		return __plugins.hook(hook, *args, **kwargs)