示例#1
0
	def start_convert(self, attrs):
		ctype = attrs["type"]

		# TODO: we need something better here
		if ctype[:4] == "web:": # for now
			self.converter = eval(ctype[4:])
		else:
			try:
				self.converter = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
			except ImportError:
				self.converter = my_import('.'.join(("Plugins", "Extensions", "WebInterface", "WebComponents", "Converter", ctype))).__dict__.get(ctype)
		self.sub = [ ]
示例#2
0
def woWebIf(session):
    try:
        modul = my_import('.'.join(['Plugins', 'Extensions', 'WebInterface', 'plugin']))
        myweb = getattr(modul, 'restartWebserver')
        myweb(session)
    except:
        print_exc()
示例#3
0
 def getInterfaceList(self):
     self.pluginlist = []
     global plugin_path,myname
     interfacepath = plugin_path+"/interface"
     for iface in os_listdir(interfacepath):
         if iface.endswith(".py") and not iface.startswith("_"):
             pluginp = '.'.join(["Plugins", "Extensions", myname, "interface",iface.replace(".py","")])
             plugin = my_import(pluginp)
             self.pluginlist.append(plugin.Interface(self.session,cbListLoaded=self.onStreamlistLoaded))
示例#4
0
文件: metrixTools.py 项目: HDMU/Skins
def skinPartIsCompatible(dom):
    isvalid = True
    try:
        for widget in dom.getElementsByTagName('widget'):
            isvalid = True
            renderer = None
            try:
                renderer = str(widget.getAttributeNode('render').nodeValue)
            except:
                pass

            if renderer is not None:
                try:
                    renderer_class = my_import('.'.join(('Components', 'Renderer', renderer))).__dict__.get(renderer)
                    for convert in dom.getElementsByTagName('convert'):
                        ctype = None
                        try:
                            ctype = str(convert.getAttributeNode('type').nodeValue)
                        except:
                            pass

                        if ctype is not None:
                            try:
                                converter_class = my_import('.'.join(('Components', 'Converter', ctype))).__dict__.get(ctype)
                            except:
                                isvalid = False
                                print "[MetrixGSP] Missing converter '" + ctype + "'"
                                break

                except:
                    print "[MetrixGSP] Missing renderer '" + renderer + "'"
                    isvalid = False

            if isvalid == False:
                dom.removeChild(widget)
                print '[MetrixGSP] Widget removed!'

    except:
        pass

    return dom
示例#5
0
    def readPluginList(self, directory):
        """enumerates plugins"""
        new_plugins = []
        for c in os.listdir(directory):
            directory_category = os.path.join(directory, c)
            if not os.path.isdir(directory_category):
                continue
            for pluginname in os.listdir(directory_category):
                path = os.path.join(directory_category, pluginname)
                if os.path.isdir(path):
                    profile("plugin " + pluginname)
                    try:
                        plugin = my_import(".".join(["Plugins", c, pluginname, "plugin"]))
                        plugins = plugin.Plugins(path=path)
                    except Exception, exc:
                        print "[PluginComponent] Plugin ", c + "/" + pluginname, "failed to load:", exc
                        # supress errors due to missing plugin.py* files (badly removed plugin)
                        for fn in ("plugin.py", "plugin.pyc", "plugin.pyo"):
                            if os.path.exists(os.path.join(path, fn)):
                                self.warnings.append((c + "/" + pluginname, str(exc)))
                                from traceback import print_exc

                                print_exc()
                                break
                        else:
                            if path.find("WebInterface") == -1:
                                print "[PluginComponent] Plugin probably removed, but not cleanly in", path
                                print "[PluginComponent] trying to remove:", path

                                # allow single entry not to be a list
                                if os.path.islink(path):
                                    rmtree(os.path.realpath(path))
                                    os.unlink(path)
                                else:
                                    rmtree(path)
                        continue

                        # allow single entry not to be a list
                    if not isinstance(plugins, list):
                        plugins = [plugins]

                    for p in plugins:
                        p.path = path
                        p.updateIcon(path)
                        new_plugins.append(p)

                    keymap = os.path.join(path, "keymap.xml")
                    if fileExists(keymap):
                        try:
                            keymapparser.readKeymap(keymap)
                        except Exception, exc:
                            print "[PluginComponent] keymap for plugin %s/%s failed to load: " % (c, pluginname), exc
                            self.warnings.append((c + "/" + pluginname, str(exc)))
示例#6
0
def skinPartIsCompatible(dom):
	isvalid = True
	try:
		for widget in dom.getElementsByTagName('widget'):
			isvalid = True
			#get_attr = widget.attrib.get
			renderer = None
			try:
				renderer = str(widget.getAttributeNode('render').nodeValue)
			except:
				pass
			if not renderer is None:
				try:
					renderer_class = my_import('.'.join(("Components", "Renderer", renderer))).__dict__.get(renderer)
					#try:
					for convert in dom.getElementsByTagName('convert'):
						ctype = None
						try:
							ctype = str(convert.getAttributeNode('type').nodeValue)
						except:
							pass
						if not ctype is None:
							try:
								converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
							except Exception, e:
								isvalid = False 
								log("Missing converter '"+ctype+"'",solution="MetrixGSP")
								break
					
				except Exception, e:
					log("Missing renderer '"+renderer+"'",solution="MetrixGSP")
					isvalid = False
			
			if isvalid == False:
				dom.removeChild(widget)	
	except:
		pass
	return dom
    def readPluginList(self, directory):
        """enumerates plugins"""

        categories = os_listdir(directory)

        new_plugins = []

        for c in categories:
            directory_category = directory + c
            if not os_path.isdir(directory_category):
                continue
            open(directory_category + "/__init__.py", "a").close()
            for pluginname in os_listdir(directory_category):
                path = directory_category + "/" + pluginname
                if os_path.isdir(path):
                    if (
                        fileExists(path + "/plugin.pyc")
                        or fileExists(path + "/plugin.pyo")
                        or fileExists(path + "/plugin.py")
                    ):
                        try:
                            plugin = my_import(".".join(["Plugins", c, pluginname, "plugin"]))

                            if not plugin.__dict__.has_key("Plugins"):
                                print "Plugin %s doesn't have 'Plugin'-call." % (pluginname)
                                continue

                            plugins = plugin.Plugins(path=path)
                        except Exception, exc:
                            print "Plugin ", c + "/" + pluginname, "failed to load:", exc
                            print_exc(file=stdout)
                            print "skipping plugin."
                            self.warnings.append((c + "/" + pluginname, str(exc)))
                            continue

                            # allow single entry not to be a list
                        if not isinstance(plugins, list):
                            plugins = [plugins]

                        for p in plugins:
                            p.updateIcon(path)
                            new_plugins.append(p)

                        if fileExists(path + "/keymap.xml"):
                            try:
                                keymapparser.readKeymap(path + "/keymap.xml")
                            except Exception, exc:
                                print "keymap for plugin %s/%s failed to load: " % (c, pluginname), exc
                                self.warnings.append((c + "/" + pluginname, str(exc)))
	def readPluginList(self, directory):
		"""enumerates plugins"""
		new_plugins = []
		for c in os.listdir(directory):
			directory_category = os.path.join(directory, c)
			if not os.path.isdir(directory_category):
				continue
			for pluginname in os.listdir(directory_category):
				path = os.path.join(directory_category, pluginname)
				if os.path.isdir(path):
						profile('plugin '+pluginname)
						try:
							plugin = my_import('.'.join(["Plugins", c, pluginname, "plugin"]))
							plugins = plugin.Plugins(path=path)
						except Exception, exc:
							print "Plugin ", c + "/" + pluginname, "failed to load:", exc
							# supress errors due to missing plugin.py* files (badly removed plugin)
							for fn in ('plugin.py', 'plugin.pyc', 'plugin.pyo'):
								if os.path.exists(os.path.join(path, fn)):
									self.warnings.append( (c + "/" + pluginname, str(exc)) )
									from traceback import print_exc
									print_exc()
									break
							else:
								print "Plugin probably removed, but not cleanly in", path
								try:
									os.rmdir(path)
								except:
								        pass
							continue

						# allow single entry not to be a list
						if not isinstance(plugins, list):
							plugins = [ plugins ]

						for p in plugins:
							p.path = path
							p.updateIcon(path)
							new_plugins.append(p)

						keymap = os.path.join(path, "keymap.xml")
						if fileExists(keymap):
							try:
								keymapparser.readKeymap(keymap)
							except Exception, exc:
								print "keymap for plugin %s/%s failed to load: " % (c, pluginname), exc
								self.warnings.append( (c + "/" + pluginname, str(exc)) )
示例#9
0
	def runEarlyPlugins(self, directory):
		categories = os_listdir(directory)
		for c in categories:
			directory_category = directory + c
			if not os_path.isdir(directory_category):
				continue
			for pluginname in os_listdir(directory_category):
				path = directory_category + "/" + pluginname
				if os_path.isdir(path):
					if fileExists(path + "/earlyplugin.pyc") or fileExists(path + "/earlyplugin.pyo") or fileExists(path + "/earlyplugin.py"):
						try:
							plugin = my_import('.'.join(["Plugins", c, pluginname, "earlyplugin"]))
							if not plugin.__dict__.has_key("EarlyPlugins"):
								continue
							plugin.EarlyPlugins(path=path)
						except Exception, exc:
							print "EarlyPlugin ", c + "/" + pluginname, "failed to load:", exc
							print_exc(file=stdout)
							print "skipping early plugin."
							self.warnings.append( (c + "/" + pluginname, str(exc)) )
							continue
示例#10
0
		pass

	def getPageError(self, error=None):
		if error:
			print "[%s] Error: %s" % (self.name, error)

##################################################

def getPlugins():
	try:
		files = listdir(resolveFilename(SCOPE_PLUGINS)+"/Extensions/PornCenter/Additions")
		files.sort()
	except Exception, exc:
		print "[PornCenter] failed to search for plugins:", exc
		files = []
	plugins = []
	for file in files:
		if file.endswith(".py") and not file in ["__init__.py", "Plugin.py", "Podcast.py"]:
			try:
				plugin = my_import('.'.join(["Plugins", "Extensions", "PornCenter", "Additions", file[:-3]]))
				if not plugin.__dict__.has_key("getPlugin"):
					print "Plugin %s doesn't have 'getPlugin'-call." % file
					continue
				p = plugin.getPlugin()
				if p:
					plugins.append(p)
			except Exception, exc:
				print "Plugin %s failed to load: %s" % (file, exc)
				continue
	return plugins
示例#11
0
def readSkin(screen, skin, names, desktop):
	if not isinstance(names, list):
		names = [names]

	name = "<embedded-in-'%s'>" % screen.__class__.__name__

	# try all skins, first existing one have priority
	global dom_screens
	for n in names:
		myscreen, path = dom_screens.get(n, (None,None))
		if myscreen is not None:
			# use this name for debug output
			name = n
			break

	# otherwise try embedded skin
	if myscreen is None:
		myscreen = getattr(screen, "parsedSkin", None)

	# try uncompiled embedded skin
	if myscreen is None and getattr(screen, "skin", None):
		print "[SKIN] Parsing embedded skin"
		skin = screen.skin
		if (isinstance(skin, tuple)):
			for s in skin:
				candidate = xml.etree.cElementTree.fromstring(s)
				if candidate.tag == 'screen':
					sid = candidate.attrib.get('id', None)
					if (not sid) or (int(sid) == display_skin_id):
						myscreen = candidate 
						break;
			else:
				print "[SKIN] Hey, no suitable screen!"
		else:
			myscreen = xml.etree.cElementTree.fromstring(skin)
		if myscreen:
			screen.parsedSkin = myscreen

	#assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
	if myscreen is None:
		print "[SKIN] No skin to read..."
		emptySkin = "<screen></screen>"
		myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)

	screen.skinAttributes = [ ]

	skin_path_prefix = getattr(screen, "skin_path", path)

	collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])

	screen.additionalWidgets = [ ]
	screen.renderer = [ ]

	visited_components = set()

	# now walk all widgets
	for widget in myscreen.findall("widget"):
		get_attr = widget.attrib.get
		# ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
		# widgets (source->renderer).

		wname = get_attr('name')
		wsource = get_attr('source')

		if wname is None and wsource is None:
			print "widget has no name and no source!"
			continue

		if wname:
			#print "Widget name=", wname
			visited_components.add(wname)

			# get corresponding 'gui' object
			try:
				attributes = screen[wname].skinAttributes = [ ]
			except:
				raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
				#print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"

#			assert screen[wname] is not Source

			# and collect attributes for this
			collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
		elif wsource:
			# get corresponding source
			#print "Widget source=", wsource

			while True: # until we found a non-obsolete source

				# parse our current "wsource", which might specifiy a "related screen" before the dot,
				# for example to reference a parent, global or session-global screen.
				scr = screen

				# resolve all path components
				path = wsource.split('.')
				while len(path) > 1:
					scr = screen.getRelatedScreen(path[0])
					if scr is None:
						#print wsource
						#print name
						raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
					path = path[1:]

				# resolve the source.
				source = scr.get(path[0])
				if isinstance(source, ObsoleteSource):
					# however, if we found an "obsolete source", issue warning, and resolve the real source.
					print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
					print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
					if source.description:
						print source.description

					wsource = source.new_source
				else:
					# otherwise, use that source.
					break

			if source is None:
				raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")

			wrender = get_attr('render')

			if not wrender:
				raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))

			for converter in widget.findall("convert"):
				ctype = converter.get('type')
				assert ctype, "'convert'-tag needs a 'type'-attribute"
				#print "Converter:", ctype
				try:
					parms = converter.text.strip()
				except:
					parms = ""
				#print "Params:", parms
				converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)

				c = None

				for i in source.downstream_elements:
					if isinstance(i, converter_class) and i.converter_arguments == parms:
						c = i

				if c is None:
					c = converter_class(parms)
					c.connect(source)

				source = c

			renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)

			renderer = renderer_class() # instantiate renderer

			renderer.connect(source) # connect to source
			attributes = renderer.skinAttributes = [ ]
			collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])

			screen.renderer.append(renderer)

	from Components.GUIComponent import GUIComponent
	nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
	assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))

	# now walk additional objects
	for widget in myscreen.getchildren():
		w_tag = widget.tag

		if not w_tag:
			continue

		if w_tag == "widget":
			continue

		if w_tag == "applet":
			try:
				codeText = widget.text.strip()
			except:
				codeText = ""

			#print "Found code:"
			#print codeText
			widgetType = widget.attrib.get('type')

			code = compile(codeText, "skin applet", "exec")

			if widgetType == "onLayoutFinish":
				screen.onLayoutFinish.append(code)
				#print "onLayoutFinish = ", codeText
			else:
				raise SkinError("applet type '%s' unknown!" % widgetType)
				#print "applet type '%s' unknown!" % type

			continue

		w = additionalWidget()

		if w_tag == "eLabel":
			w.widget = eLabel
		elif w_tag == "ePixmap":
			w.widget = ePixmap
		else:
			raise SkinError("unsupported stuff : %s" % w_tag)
			#print "unsupported stuff : %s" % widget.tag

		w.skinAttributes = [ ]
		collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])

		# applyAttributes(guiObject, widget, desktop)
		# guiObject.thisown = 0
		screen.additionalWidgets.append(w)
示例#12
0
    def readPluginList(self, directory):
        """enumerates plugins"""

        categories = os_listdir(directory)

        new_plugins = []

        for c in categories:
            directory_category = directory + c
            if not os_path.isdir(directory_category):
                continue
            for pluginname in os_listdir(directory_category):
                path = directory_category + "/" + pluginname
                if os_path.isdir(path):
                    if fileExists(path + "/plugin.pyc") or fileExists(
                            path + "/plugin.pyo") or fileExists(path +
                                                                "/plugin.py"):
                        try:
                            plugin = my_import('.'.join(
                                ["Plugins", c, pluginname, "plugin"]))

                            if "Plugins" not in plugin.__dict__:
                                print("Plugin %s doesn't have 'Plugin'-call." %
                                      (pluginname))
                                continue

                            plugins = plugin.Plugins(path=path)
                        except Exception as exc:
                            print("Plugin ", c + "/" + pluginname,
                                  "failed to load:", exc)
                            print_exc(file=stdout)
                            print("skipping plugin.")
                            self.warnings.append(
                                (c + "/" + pluginname, str(exc)))
                            continue

                        # allow single entry not to be a list
                        if not isinstance(plugins, list):
                            plugins = [plugins]

                        for p in plugins:
                            p.path = path
                            p.updateIcon(path)
                            new_plugins.append(p)

                        if fileExists(path + "/keymap.xml"):
                            try:
                                keymapparser.readKeymap(path + "/keymap.xml")
                            except Exception as exc:
                                print(
                                    "keymap for plugin %s/%s failed to load: "
                                    % (c, pluginname), exc)
                                self.warnings.append(
                                    (c + "/" + pluginname, str(exc)))

        # build a diff between the old list of plugins and the new one
        # internally, the "fnc" argument will be compared with __eq__
        plugins_added = [p for p in new_plugins if p not in self.pluginList]
        plugins_removed = [
            p for p in self.pluginList
            if not p.internal and p not in new_plugins
        ]

        #ignore already installed but reloaded plugins
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False
                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#13
0
    def readPluginList(self, directory):
        new_plugins = []
        for c in os.listdir(directory):
            directory_category = os.path.join(directory, c)
            if not os.path.isdir(directory_category):
                continue
            for pluginname in os.listdir(directory_category):
                path = os.path.join(directory_category, pluginname)
                if os.path.isdir(path):
                    profile('plugin ' + pluginname)
                    try:
                        plugin = my_import('.'.join(
                            ['Plugins', c, pluginname, 'plugin']))
                        plugins = plugin.Plugins(path=path)
                    except Exception as exc:
                        print 'Plugin ', c + '/' + pluginname, 'failed to load:', exc
                        for fn in ('plugin.py', 'plugin.pyc', 'plugin.pyo'):
                            if os.path.exists(os.path.join(path, fn)):
                                self.warnings.append(
                                    (c + '/' + pluginname, str(exc)))
                                from traceback import print_exc
                                print_exc()
                                break
                        else:
                            if pluginname not in ('WebInterface', 'TubeLib'):
                                print 'Plugin probably removed, but not cleanly in', path
                                print 'trying to remove:', path
                                rmtree(path)

                        continue

                    if not isinstance(plugins, list):
                        plugins = [plugins]
                    for p in plugins:
                        p.path = path
                        p.updateIcon(path)
                        new_plugins.append(p)

                    keymap = os.path.join(path, 'keymap.xml')
                    if fileExists(keymap):
                        try:
                            keymapparser.readKeymap(keymap)
                        except Exception as exc:
                            print 'keymap for plugin %s/%s failed to load: ' % (
                                c, pluginname), exc
                            self.warnings.append(
                                (c + '/' + pluginname, str(exc)))

        plugins_added = [p for p in new_plugins if p not in self.pluginList]
        plugins_removed = [
            p for p in self.pluginList
            if not p.internal and p not in new_plugins
        ]
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False

                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#14
0
def readSkin(screen, skin, names, desktop):
    if not isinstance(names, list):
        names = [names]
    name = "<embedded-in-'%s'>" % screen.__class__.__name__
    style_id = desktop.getStyleID()
    for n in names:
        myscreen, path = lookupScreen(n, style_id)
        if myscreen is not None:
            name = n
            break

    if myscreen is None:
        myscreen = getattr(screen, 'parsedSkin', None)
    if myscreen is None and getattr(screen, 'skin', None):
        print 'Looking for embedded skin'
        skin_tuple = screen.skin
        if not isinstance(skin_tuple, tuple):
            skin_tuple = (skin_tuple,)
        for sskin in skin_tuple:
            parsedSkin = xml.etree.cElementTree.fromstring(sskin)
            screen_style_id = parsedSkin.attrib.get('id', '-1')
            if style_id != 2 and int(screen_style_id) == -1 or int(screen_style_id) == style_id:
                myscreen = screen.parsedSkin = parsedSkin
                break

    if myscreen is None:
        print 'No skin to read...'
        emptySkin = '<screen></screen>'
        myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
    screen.skinAttributes = []
    skin_path_prefix = getattr(screen, 'skin_path', path)
    collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=['name'])
    screen.additionalWidgets = []
    screen.renderer = []
    visited_components = set()
    for constant_widget in myscreen.findall('constant-widget'):
        get_attr = constant_widget.attrib.get
        wname = get_attr('name')
        if wname:
            try:
                cwvalue = constant_widgets[wname]
            except KeyError:
                print '[SKIN] ERROR - given constant-widget: %s not found in skin' % wname
                continue

        if cwvalue:
            for x in cwvalue:
                myscreen.append(x)

        try:
            myscreen.remove(constant_widget)
        except ValueError:
            pass

    for widget in myscreen.findall('widget'):
        get_attr = widget.attrib.get
        wname = get_attr('name')
        wsource = get_attr('source')
        if wname is None and wsource is None:
            print 'widget has no name and no source!'
            continue
        if wname:
            visited_components.add(wname)
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")

            collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
        elif wsource:
            while True:
                scr = screen
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
                    path = path[1:]

                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
                    print 'OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!' % source.removal_date
                    if source.description:
                        print source.description
                    wsource = source.new_source
                else:
                    break

            if source is None:
                raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
            wrender = get_attr('render')
            if not wrender:
                raise SkinError("you must define a renderer with render= for source '%s'" % wsource)
            for converter in widget.findall('convert'):
                ctype = converter.get('type')
                try:
                    parms = converter.text.strip()
                except:
                    parms = ''

                converter_class = my_import('.'.join(('Components', 'Converter', ctype))).__dict__.get(ctype)
                c = None
                for i in source.downstream_elements:
                    if isinstance(i, converter_class) and i.converter_arguments == parms:
                        c = i

                if c is None:
                    c = converter_class(parms)
                    c.connect(source)
                source = c

            renderer_class = my_import('.'.join(('Components', 'Renderer', wrender))).__dict__.get(wrender)
            renderer = renderer_class()
            renderer.connect(source)
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
            screen.renderer.append(renderer)

    from Components.GUIComponent import GUIComponent
    nonvisited_components = [ x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent) ]
    for widget in myscreen.getchildren():
        w_tag = widget.tag
        if w_tag == 'constant-widget':
            continue
        if w_tag == 'widget':
            continue
        if w_tag == 'applet':
            try:
                codeText = widget.text.strip()
            except:
                codeText = ''

            widgetType = widget.attrib.get('type')
            code = compile(codeText, 'skin applet', 'exec')
            if widgetType == 'onLayoutFinish':
                screen.onLayoutFinish.append(code)
            else:
                raise SkinError("applet type '%s' unknown!" % widgetType)
            continue
        w = additionalWidget()
        if w_tag == 'eLabel':
            w.widget = eLabel
        elif w_tag == 'ePixmap':
            w.widget = ePixmap
        else:
            raise SkinError('unsupported stuff : %s' % w_tag)
        w.skinAttributes = []
        collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
        screen.additionalWidgets.append(w)
示例#15
0
    def loadBasePlugins(self, directory):
        new_plugins = []
        for c in os.listdir(directory):
            directory_category = os.path.join(directory, c)
            if not os.path.isdir(directory_category):
                continue
            for pluginname in os.listdir(directory_category):
                path = os.path.join(directory_category, pluginname)
                if pluginname.endswith('Wizard') or pluginname in ('EGAMIPluginSpeedUp', 'OpenWebif', 'WeatherPlugin', 'WeatherComponentHandler', 'EGAMIPermanentClock', 'NumberZapExt', 'CamdMenager', 'EGAMIBoot'):
                    if os.path.isdir(path):
                        profile('plugin ' + pluginname)
                        try:
                            plugin = my_import('.'.join(['Plugins',
                             c,
                             pluginname,
                             'plugin']))
                            plugins = plugin.Plugins(path=path)
                        except Exception as exc:
                            print '[PluginComponent] Plugin ', c + '/' + pluginname, 'failed to load:', exc
                            for fn in ('plugin.py', 'plugin.pyc', 'plugin.pyo'):
                                if os.path.exists(os.path.join(path, fn)):
                                    self.warnings.append((c + '/' + pluginname, str(exc)))
                                    from traceback import print_exc
                                    print_exc()
                                    break
                            else:
                                if path.find('WebInterface') == -1:
                                    print '[PluginComponent] Plugin probably removed, but not cleanly in', path
                                    print '[PluginComponent] trying to remove:', path
                                    rmtree(path)

                            continue

                        if not isinstance(plugins, list):
                            plugins = [plugins]
                        for p in plugins:
                            p.path = path
                            p.updateIcon(path)
                            new_plugins.append(p)

                        keymap = os.path.join(path, 'keymap.xml')
                        if fileExists(keymap):
                            try:
                                keymapparser.readKeymap(keymap)
                            except Exception as exc:
                                print '[PluginComponent] keymap for plugin %s/%s failed to load: ' % (c, pluginname), exc
                                self.warnings.append((c + '/' + pluginname, str(exc)))

        plugins_added = [ p for p in new_plugins if p not in self.pluginList ]
        plugins_removed = [ p for p in self.pluginList if not p.internal and p not in new_plugins ]
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False

                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#16
0
文件: skin.py 项目: kingvuplus/boom2
    def process_widget(widget, context):
        get_attr = widget.attrib.get
        wname = get_attr('name')
        wsource = get_attr('source')
        if wname is None and wsource is None:
            print 'widget has no name and no source!'
            return
        if wname:
            visited_components.add(wname)
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")

            collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',))
        elif wsource:
            while True:
                scr = screen
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
                    path = path[1:]

                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
                    print 'OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!' % source.removal_date
                    if source.description:
                        print source.description
                    wsource = source.new_source
                else:
                    break

            if source is None:
                raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
            wrender = get_attr('render')
            if not wrender:
                raise SkinError("you must define a renderer with render= for source '%s'" % wsource)
            for converter in widget.findall('convert'):
                ctype = converter.get('type')
                try:
                    parms = converter.text.strip()
                except:
                    parms = ''

                converter_class = my_import('.'.join(('Components', 'Converter', ctype))).__dict__.get(ctype)
                c = None
                for i in source.downstream_elements:
                    if isinstance(i, converter_class) and i.converter_arguments == parms:
                        c = i

                if c is None:
                    c = converter_class(parms)
                    c.connect(source)
                source = c

            renderer_class = my_import('.'.join(('Components', 'Renderer', wrender))).__dict__.get(wrender)
            renderer = renderer_class()
            renderer.connect(source)
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source'))
            screen.renderer.append(renderer)
示例#17
0
    def process_widget(widget, context):
        get_attr = widget.attrib.get
        # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
        # widgets (source->renderer).
        wname = get_attr('name')
        wsource = get_attr('source')
        if wname is None and wsource is None:
            print "widget has no name and no source!"
            return
        if wname:
            #print "Widget name=", wname
            visited_components.add(wname)
            # get corresponding 'gui' object
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname +
                                "' was not found in skin of screen '" + name +
                                "'!")
            # assert screen[wname] is not Source
            collectAttributes(attributes,
                              widget,
                              context,
                              skin_path_prefix,
                              ignore=('name', ))
        elif wsource:
            # get corresponding source
            #print "Widget source=", wsource
            while True:  # until we found a non-obsolete source
                # parse our current "wsource", which might specifiy a "related screen" before the dot,
                # for example to reference a parent, global or session-global screen.
                scr = screen
                # resolve all path components
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        #print wsource
                        #print name
                        raise SkinError("specified related screen '" +
                                        wsource +
                                        "' was not found in screen '" + name +
                                        "'!")
                    path = path[1:]
                # resolve the source.
                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    # however, if we found an "obsolete source", issue warning, and resolve the real source.
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (
                        name, wsource, source.new_source)
                    print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % source.removal_date
                    if source.description:
                        print source.description
                    wsource = source.new_source
                else:
                    # otherwise, use that source.
                    break

            if source is None:
                raise SkinError("source '" + wsource +
                                "' was not found in screen '" + name + "'!")

            wrender = get_attr('render')
            if not wrender:
                raise SkinError(
                    "you must define a renderer with render= for source '%s'" %
                    wsource)
            for converter in widget.findall("convert"):
                ctype = converter.get('type')
                assert ctype, "'convert'-tag needs a 'type'-attribute"
                #print "Converter:", ctype
                try:
                    parms = converter.text.strip()
                except:
                    parms = ""
                #print "Params:", parms
                converter_class = my_import('.'.join(
                    ("Components", "Converter", ctype))).__dict__.get(ctype)
                c = None
                for i in source.downstream_elements:
                    if isinstance(i, converter_class
                                  ) and i.converter_arguments == parms:
                        c = i
                if c is None:
                    c = converter_class(parms)
                    c.connect(source)
                source = c

            renderer_class = my_import('.'.join(
                ("Components", "Renderer", wrender))).__dict__.get(wrender)
            renderer = renderer_class()  # instantiate renderer
            renderer.connect(source)  # connect to source
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes,
                              widget,
                              context,
                              skin_path_prefix,
                              ignore=('render', 'source'))
            screen.renderer.append(renderer)
示例#18
0
文件: skin.py 项目: OpenSH4/old-sh4
def readSkin(screen, skin, names, desktop):
    if not isinstance(names, list):
        names = [names]

    name = "<embedded-in-'%s'>" % screen.__class__.__name__

    style_id = desktop.getStyleID()

    # try all skins, first existing one have priority
    for n in names:
        myscreen, path = lookupScreen(n, style_id)
        if myscreen is not None:
            # use this name for debug output
            name = n
            break

    # otherwise try embedded skin
    if myscreen is None:
        myscreen = getattr(screen, "parsedSkin", None)

    # try uncompiled embedded skin
    if myscreen is None and getattr(screen, "skin", None):
        print "Looking for embedded skin"
        skin_tuple = screen.skin
        if not isinstance(skin_tuple, tuple):
            skin_tuple = (skin_tuple, )
        for sskin in skin_tuple:
            parsedSkin = xml.etree.cElementTree.fromstring(sskin)
            screen_style_id = parsedSkin.attrib.get('id', '-1')
            if (style_id != 2 and int(screen_style_id)
                    == -1) or int(screen_style_id) == style_id:
                myscreen = screen.parsedSkin = parsedSkin
                break

    #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
    if myscreen is None:
        print "No skin to read..."
        emptySkin = "<screen></screen>"
        myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(
            emptySkin)

    screen.skinAttributes = []

    skin_path_prefix = getattr(screen, "skin_path", path)

    collectAttributes(screen.skinAttributes,
                      myscreen,
                      skin_path_prefix,
                      ignore=["name"])

    screen.additionalWidgets = []
    screen.renderer = []

    visited_components = set()

    # now walk all widgets
    for widget in myscreen.findall("widget"):
        get_attr = widget.attrib.get
        # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
        # widgets (source->renderer).

        wname = get_attr('name')
        wsource = get_attr('source')

        if wname is None and wsource is None:
            print "widget has no name and no source!"
            continue

        if wname:
            #print "Widget name=", wname
            visited_components.add(wname)

            # get corresponding 'gui' object
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname +
                                "' was not found in skin of screen '" + name +
                                "'!")
                #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"

#			assert screen[wname] is not Source

# and collect attributes for this
            collectAttributes(attributes,
                              widget,
                              skin_path_prefix,
                              ignore=['name'])
        elif wsource:
            # get corresponding source
            #print "Widget source=", wsource

            while True:  # until we found a non-obsolete source

                # parse our current "wsource", which might specifiy a "related screen" before the dot,
                # for example to reference a parent, global or session-global screen.
                scr = screen

                # resolve all path components
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        #print wsource
                        #print name
                        raise SkinError("specified related screen '" +
                                        wsource +
                                        "' was not found in screen '" + name +
                                        "'!")
                    path = path[1:]

                # resolve the source.
                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    # however, if we found an "obsolete source", issue warning, and resolve the real source.
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (
                        name, wsource, source.new_source)
                    print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (
                        source.removal_date)
                    if source.description:
                        print source.description

                    wsource = source.new_source
                else:
                    # otherwise, use that source.
                    break

            if source is None:
                raise SkinError("source '" + wsource +
                                "' was not found in screen '" + name + "'!")

            wrender = get_attr('render')

            if not wrender:
                raise SkinError(
                    "you must define a renderer with render= for source '%s'" %
                    (wsource))

            for converter in widget.findall("convert"):
                ctype = converter.get('type')
                assert ctype, "'convert'-tag needs a 'type'-attribute"
                #print "Converter:", ctype
                try:
                    parms = converter.text.strip()
                except:
                    parms = ""
                #print "Params:", parms
                converter_class = my_import('.'.join(
                    ("Components", "Converter", ctype))).__dict__.get(ctype)

                c = None

                for i in source.downstream_elements:
                    if isinstance(i, converter_class
                                  ) and i.converter_arguments == parms:
                        c = i

                if c is None:
                    print "allocating new converter!"
                    c = converter_class(parms)
                    c.connect(source)
                else:
                    print "reused converter!"

                source = c

            renderer_class = my_import('.'.join(
                ("Components", "Renderer", wrender))).__dict__.get(wrender)

            renderer = renderer_class()  # instantiate renderer

            renderer.connect(source)  # connect to source
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes,
                              widget,
                              skin_path_prefix,
                              ignore=['render', 'source'])

            screen.renderer.append(renderer)

    from Components.GUIComponent import GUIComponent
    nonvisited_components = [
        x for x in set(screen.keys()) - visited_components
        if isinstance(x, GUIComponent)
    ]
    assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (
        name, ', '.join(nonvisited_components))

    # now walk additional objects
    for widget in myscreen.getchildren():
        w_tag = widget.tag

        if w_tag == "widget":
            continue

        if w_tag == "applet":
            try:
                codeText = widget.text.strip()
            except:
                codeText = ""

            #print "Found code:"
            #print codeText
            widgetType = widget.attrib.get('type')

            code = compile(codeText, "skin applet", "exec")

            if widgetType == "onLayoutFinish":
                screen.onLayoutFinish.append(code)
                #print "onLayoutFinish = ", codeText
            else:
                raise SkinError("applet type '%s' unknown!" % widgetType)
                #print "applet type '%s' unknown!" % type

            continue

        w = additionalWidget()

        if w_tag == "eLabel":
            w.widget = eLabel
        elif w_tag == "ePixmap":
            w.widget = ePixmap
        else:
            raise SkinError("unsupported stuff : %s" % w_tag)
            #print "unsupported stuff : %s" % widget.tag

        w.skinAttributes = []
        collectAttributes(w.skinAttributes,
                          widget,
                          skin_path_prefix,
                          ignore=['name'])

        # applyAttributes(guiObject, widget, desktop)
        # guiObject.thisown = 0
        screen.additionalWidgets.append(w)
示例#19
0
    def readPluginList(self, directory):
        categories = os_listdir(directory)
        new_plugins = []
        for c in categories:
            directory_category = directory + c
            if not os_path.isdir(directory_category):
                continue
            for pluginname in os_listdir(directory_category):
                path = directory_category + '/' + pluginname
                if os_path.isdir(path):
                    if fileExists(path + '/plugin.pyc') or fileExists(
                            path + '/plugin.pyo') or fileExists(path +
                                                                '/plugin.py'):
                        try:
                            plugin = my_import('.'.join(
                                ['Plugins', c, pluginname, 'plugin']))
                            if not plugin.__dict__.has_key('Plugins'):
                                print "Plugin %s doesn't have 'Plugin'-call." % pluginname
                                continue
                            plugins = plugin.Plugins(path=path)
                        except Exception as exc:
                            print 'Plugin ', c + '/' + pluginname, 'failed to load:', exc
                            print_exc(file=stdout)
                            print 'skipping plugin.'
                            self.warnings.append(
                                (c + '/' + pluginname, str(exc)))
                            continue

                        if not isinstance(plugins, list):
                            plugins = [plugins]
                        for p in plugins:
                            p.path = path
                            p.updateIcon(path)
                            new_plugins.append(p)

                        if fileExists(path + '/keymap.xml'):
                            try:
                                keymapparser.readKeymap(path + '/keymap.xml')
                            except Exception as exc:
                                print 'keymap for plugin %s/%s failed to load: ' % (
                                    c, pluginname), exc
                                self.warnings.append(
                                    (c + '/' + pluginname, str(exc)))

        plugins_added = [p for p in new_plugins if p not in self.pluginList]
        plugins_removed = [
            p for p in self.pluginList
            if not p.internal and p not in new_plugins
        ]
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False

                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#20
0
    def readPluginList(self, directory):
        categories = os_listdir(directory)
        new_plugins = []
        for c in categories:
            directory_category = directory + c
            if not os_path.isdir(directory_category):
                continue
            for pluginname in os_listdir(directory_category):
                path = directory_category + '/' + pluginname
                if os_path.isdir(path):
                    if fileExists(path + '/plugin.pyc') or fileExists(path + '/plugin.pyo') or fileExists(path + '/plugin.py') or fileExists(path + '/plugin.so'):
                        try:
                            plugin = my_import('.'.join(['Plugins',
                             c,
                             pluginname,
                             'plugin']))
                            if not plugin.__dict__.has_key('Plugins'):
                                print "Plugin %s doesn't have 'Plugin'-call." % pluginname
                                continue
                            plugins = plugin.Plugins(path=path)
                        except Exception as exc:
                            print 'Plugin ', c + '/' + pluginname, 'failed to load:', exc
                            print_exc(file=stdout)
                            print 'skipping plugin.'
                            self.warnings.append((c + '/' + pluginname, str(exc)))
                            continue

                        if not isinstance(plugins, list):
                            plugins = [plugins]
                        for p in plugins:
                            p.path = path
                            p.updateIcon(path)
                            new_plugins.append(p)

                        if fileExists(path + '/keymap.xml'):
                            try:
                                keymapparser.readKeymap(path + '/keymap.xml')
                            except Exception as exc:
                                print 'keymap for plugin %s/%s failed to load: ' % (c, pluginname), exc
                                self.warnings.append((c + '/' + pluginname, str(exc)))

        plugins_added = [ p for p in new_plugins if p not in self.pluginList ]
        plugins_removed = [ p for p in self.pluginList if not p.internal and p not in new_plugins ]
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False

                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#21
0
文件: skin.py 项目: kingvuplus/ops
    def process_widget(widget, context):
        get_attr = widget.attrib.get
        wname = get_attr('name')
        wsource = get_attr('source')
        if wname is None and wsource is None:
            print 'widget has no name and no source!'
            return
        if wname:
            visited_components.add(wname)
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")

            collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',))
        elif wsource:
            while True:
                scr = screen
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
                    path = path[1:]

                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
                    print 'OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!' % source.removal_date
                    if source.description:
                        print source.description
                    wsource = source.new_source
                else:
                    break

            if source is None:
                raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
            wrender = get_attr('render')
            if not wrender:
                raise SkinError("you must define a renderer with render= for source '%s'" % wsource)
            for converter in widget.findall('convert'):
                ctype = converter.get('type')
                try:
                    parms = converter.text.strip()
                except:
                    parms = ''

                converter_class = my_import('.'.join(('Components', 'Converter', ctype))).__dict__.get(ctype)
                c = None
                for i in source.downstream_elements:
                    if isinstance(i, converter_class) and i.converter_arguments == parms:
                        c = i

                if c is None:
                    c = converter_class(parms)
                    c.connect(source)
                source = c

            renderer_class = my_import('.'.join(('Components', 'Renderer', wrender))).__dict__.get(wrender)
            renderer = renderer_class()
            renderer.connect(source)
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source'))
            screen.renderer.append(renderer)
示例#22
0
	def processWidget(widget, context):
		# Okay, we either have 1:1-mapped widgets ("old style"), or 1:n-mapped
		# widgets (source->renderer).
		wname = widget.attrib.get("name")
		wsource = widget.attrib.get("source")
		if wname is None and wsource is None:
			raise SkinError("The widget has no name and no source")
			return
		if wname:
			# print("[Skin] DEBUG: Widget name='%s'." % wname)
			usedComponents.add(wname)
			try:  # Get corresponding "gui" object.
				attributes = screen[wname].skinAttributes = []
			except Exception:
				raise SkinError("Component with name '%s' was not found in skin of screen '%s'" % (wname, name))
			# assert screen[wname] is not Source
			collectAttributes(attributes, widget, context, skinPath, ignore=("name",))
		elif wsource:
			# print("[Skin] DEBUG: Widget source='%s'." % wsource)
			while True:  # Get corresponding source until we found a non-obsolete source.
				# Parse our current "wsource", which might specify a "related screen" before the dot,
				# for example to reference a parent, global or session-global screen.
				scr = screen
				path = wsource.split(".")  # Resolve all path components.
				while len(path) > 1:
					scr = screen.getRelatedScreen(path[0])
					if scr is None:
						# print("[Skin] DEBUG: wsource='%s', name='%s'." % (wsource, name))
						raise SkinError("Specified related screen '%s' was not found in screen '%s'" % (wsource, name))
					path = path[1:]
				source = scr.get(path[0])  # Resolve the source.
				if isinstance(source, ObsoleteSource):
					# If we found an "obsolete source", issue warning, and resolve the real source.
					print("[skin] WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.newSource))
					print("[skin] OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % source.removalDate)
					if source.description:
						print("[skin] Source description: '%s'." % source.description)
					wsource = source.new_source
				else:
					break  # Otherwise, use the source.
			if source is None:
				raise SkinError("The source '%s' was not found in screen '%s'" % (wsource, name))
			wrender = widget.attrib.get("render")
			if not wrender:
				raise SkinError("For source '%s' a renderer must be defined with a 'render=' attribute" % wsource)
			for converter in widget.findall("convert"):
				ctype = converter.get("type")
				assert ctype, "[Skin] The 'convert' tag needs a 'type' attribute!"
				# print("[Skin] DEBUG: Converter='%s'." % ctype)
				try:
					parms = converter.text.strip()
				except Exception:
					parms = ""
				# print("[Skin] DEBUG: Params='%s'." % parms)
				try:
					converterClass = my_import(".".join(("Components", "Converter", ctype))).__dict__.get(ctype)
				except ImportError as e:
					raise SkinError("Converter '%s' not found" % ctype)
				c = None
				for i in source.downstream_elements:
					if isinstance(i, converterClass) and i.converter_arguments == parms:
						c = i
				if c is None:
					c = converterClass(parms)
					c.connect(source)
				source = c
			try:
				rendererClass = my_import(".".join(("Components", "Renderer", wrender))).__dict__.get(wrender)
			except ImportError as e:
				raise SkinError("Renderer '%s' not found" % wrender)
			renderer = rendererClass()  # Instantiate renderer.
			renderer.connect(source)  # Connect to source.
			attributes = renderer.skinAttributes = []
			collectAttributes(attributes, widget, context, skinPath, ignore=("render", "source"))
			screen.renderer.append(renderer)
示例#23
0
def getPlugins():
    try:
        files = listdir(
            resolveFilename(SCOPE_PLUGINS) +
            "/Extensions/PornCenter/Additions")
        files.sort()
    except Exception, exc:
        print "[PornCenter] failed to search for plugins:", exc
        files = []
    plugins = []
    for file in files:
        if file.endswith(".py") and not file in [
                "__init__.py", "Plugin.py", "Podcast.py"
        ]:
            try:
                plugin = my_import('.'.join([
                    "Plugins", "Extensions", "PornCenter", "Additions",
                    file[:-3]
                ]))
                if not plugin.__dict__.has_key("getPlugin"):
                    print "Plugin %s doesn't have 'getPlugin'-call." % file
                    continue
                p = plugin.getPlugin()
                if p:
                    plugins.append(p)
            except Exception, exc:
                print "Plugin %s failed to load: %s" % (file, exc)
                continue
    return plugins
示例#24
0
	def process_widget(widget, context):
		get_attr = widget.attrib.get
		# ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
		# widgets (source->renderer).
		wname = get_attr('name')
		wsource = get_attr('source')
		if wname is None and wsource is None:
			print "widget has no name and no source!"
			return
		if wname:
			#print "Widget name=", wname
			visited_components.add(wname)
			# get corresponding 'gui' object
			try:
				attributes = screen[wname].skinAttributes = [ ]
			except:
				raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
			# assert screen[wname] is not Source
			collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',))
		elif wsource:
			# get corresponding source
			#print "Widget source=", wsource
			while True: # until we found a non-obsolete source
				# parse our current "wsource", which might specifiy a "related screen" before the dot,
				# for example to reference a parent, global or session-global screen.
				scr = screen
				# resolve all path components
				path = wsource.split('.')
				while len(path) > 1:
					scr = screen.getRelatedScreen(path[0])
					if scr is None:
						#print wsource
						#print name
						raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
					path = path[1:]
				# resolve the source.
				source = scr.get(path[0])
				if isinstance(source, ObsoleteSource):
					# however, if we found an "obsolete source", issue warning, and resolve the real source.
					print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
					print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
					if source.description:
						print source.description
					wsource = source.new_source
				else:
					# otherwise, use that source.
					break

			if source is None:
				raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")

			wrender = get_attr('render')
			if not wrender:
				raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
			for converter in widget.findall("convert"):
				ctype = converter.get('type')
				assert ctype, "'convert'-tag needs a 'type'-attribute"
				#print "Converter:", ctype
				try:
					parms = converter.text.strip()
				except:
					parms = ""
				#print "Params:", parms
				converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
				c = None
				for i in source.downstream_elements:
					if isinstance(i, converter_class) and i.converter_arguments == parms:
						c = i
				if c is None:
					c = converter_class(parms)
					c.connect(source)
				source = c

			renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
			renderer = renderer_class() # instantiate renderer
			renderer.connect(source) # connect to source
			attributes = renderer.skinAttributes = [ ]
			collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source'))
			screen.renderer.append(renderer)
示例#25
0
    def readPluginList(self, directory):
        """enumerates plugins"""
        new_plugins = []
        for c in os.listdir(directory):
            directory_category = os.path.join(directory, c)
            if not os.path.isdir(directory_category):
                continue
            for pluginname in os.listdir(directory_category):
                if pluginname == "__pycache__" or pluginname == "WebInterface":
                    continue
                path = os.path.join(directory_category, pluginname)
                if os.path.isdir(path):
                    profile('plugin ' + pluginname)
                    try:
                        plugin = my_import('.'.join(
                            ["Plugins", c, pluginname, "plugin"]))
                        plugins = plugin.Plugins(path=path)
                    except Exception as exc:
                        print("[PluginComponent] Plugin ",
                              c + "/" + pluginname, "failed to load:", exc)
                        # supress errors due to missing plugin.py* files (badly removed plugin)
                        for fn in ('plugin.py', 'plugin.pyo'):
                            if os.path.exists(os.path.join(path, fn)):
                                self.warnings.append(
                                    (c + "/" + pluginname, str(exc)))
                                from traceback import print_exc
                                print_exc()
                                break
                        else:
                            print(
                                "[PluginComponent] Plugin probably removed, but not cleanly in",
                                path)
                            try:
                                os.rmdir(path)
                            except:
                                pass
                        continue

                    # allow single entry not to be a list
                    if not isinstance(plugins, list):
                        plugins = [plugins]

                    for p in plugins:
                        p.path = path
                        p.updateIcon(path)
                        new_plugins.append(p)

                    keymap = os.path.join(path, "keymap.xml")
                    if fileExists(keymap):
                        try:
                            keymapparser.readKeymap(keymap)
                        except Exception as exc:
                            print(
                                "[PluginComponent] keymap for plugin %s/%s failed to load: "
                                % (c, pluginname), exc)
                            self.warnings.append(
                                (c + "/" + pluginname, str(exc)))

        # build a diff between the old list of plugins and the new one
        # internally, the "fnc" argument will be compared with __eq__
        plugins_added = [p for p in new_plugins if p not in self.pluginList]
        plugins_removed = [
            p for p in self.pluginList
            if not p.internal and p not in new_plugins
        ]

        #ignore already installed but reloaded plugins
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False
                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#26
0
    def readPluginList(self, directory):
        new_plugins = []
        for c in os.listdir(directory):
            directory_category = os.path.join(directory, c)
            if not os.path.isdir(directory_category):
                continue
            for pluginname in os.listdir(directory_category):
                path = os.path.join(directory_category, pluginname)
                if os.path.isdir(path):
                    profile('plugin ' + pluginname)
                    try:
                        plugin = my_import('.'.join(['Plugins',
                         c,
                         pluginname,
                         'plugin']))
                        plugins = plugin.Plugins(path=path)
                    except Exception as exc:
                        print 'Plugin ', c + '/' + pluginname, 'failed to load:', exc
                        for fn in ('plugin.py', 'plugin.pyc', 'plugin.pyo'):
                            if os.path.exists(os.path.join(path, fn)):
                                self.warnings.append((c + '/' + pluginname, str(exc)))
                                from traceback import print_exc
                                print_exc()
                                break
                        else:
                            if pluginname not in ('WebInterface', 'TubeLib'):
                                print 'Plugin probably removed, but not cleanly in', path
                                print 'trying to remove:', path
                                rmtree(path)

                        continue

                    if not isinstance(plugins, list):
                        plugins = [plugins]
                    for p in plugins:
                        p.path = path
                        p.updateIcon(path)
                        new_plugins.append(p)

                    keymap = os.path.join(path, 'keymap.xml')
                    if fileExists(keymap):
                        try:
                            keymapparser.readKeymap(keymap)
                        except Exception as exc:
                            print 'keymap for plugin %s/%s failed to load: ' % (c, pluginname), exc
                            self.warnings.append((c + '/' + pluginname, str(exc)))

        plugins_added = [ p for p in new_plugins if p not in self.pluginList ]
        plugins_removed = [ p for p in self.pluginList if not p.internal and p not in new_plugins ]
        for p in plugins_removed:
            for pa in plugins_added:
                if pa.path == p.path and pa.where == p.where:
                    pa.needsRestart = False

        for p in plugins_removed:
            self.removePlugin(p)

        for p in plugins_added:
            if self.firstRun or p.needsRestart is False:
                self.addPlugin(p)
            else:
                for installed_plugin in self.installedPluginList:
                    if installed_plugin.path == p.path:
                        if installed_plugin.where == p.where:
                            p.needsRestart = False

                self.addPlugin(p)

        if self.firstRun:
            self.firstRun = False
            self.installedPluginList = self.pluginList
示例#27
0
def readSkin(screen, skin, names, desktop):
    if not isinstance(names, list):
        names = [names]
    name = "<embedded-in-'%s'>" % screen.__class__.__name__
    style_id = desktop.getStyleID()
    for n in names:
        myscreen, path = lookupScreen(n, style_id)
        if myscreen is not None:
            name = n
            break

    if myscreen is None:
        myscreen = getattr(screen, 'parsedSkin', None)
    if myscreen is None and getattr(screen, 'skin', None):
        print 'Looking for embedded skin'
        skin_tuple = screen.skin
        if not isinstance(skin_tuple, tuple):
            skin_tuple = (skin_tuple, )
        for sskin in skin_tuple:
            parsedSkin = xml.etree.cElementTree.fromstring(sskin)
            screen_style_id = parsedSkin.attrib.get('id', '-1')
            if style_id != 2 and int(screen_style_id) == -1 or int(
                    screen_style_id) == style_id:
                myscreen = screen.parsedSkin = parsedSkin
                break

    if myscreen is None:
        print 'No skin to read...'
        emptySkin = '<screen></screen>'
        myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(
            emptySkin)
    screen.skinAttributes = []
    skin_path_prefix = getattr(screen, 'skin_path', path)
    collectAttributes(screen.skinAttributes,
                      myscreen,
                      skin_path_prefix,
                      ignore=['name'])
    screen.additionalWidgets = []
    screen.renderer = []
    visited_components = set()
    for constant_widget in myscreen.findall('constant-widget'):
        get_attr = constant_widget.attrib.get
        wname = get_attr('name')
        if wname:
            try:
                cwvalue = constant_widgets[wname]
            except KeyError:
                print '[SKIN] ERROR - given constant-widget: %s not found in skin' % wname
                continue

        if cwvalue:
            for x in cwvalue:
                myscreen.append(x)

        try:
            myscreen.remove(constant_widget)
        except ValueError:
            pass

    for widget in myscreen.findall('widget'):
        get_attr = widget.attrib.get
        wname = get_attr('name')
        wsource = get_attr('source')
        if wname is None and wsource is None:
            print 'widget has no name and no source!'
            continue
        if wname:
            visited_components.add(wname)
            try:
                attributes = screen[wname].skinAttributes = []
            except:
                raise SkinError("component with name '" + wname +
                                "' was not found in skin of screen '" + name +
                                "'!")

            collectAttributes(attributes,
                              widget,
                              skin_path_prefix,
                              ignore=['name'])
        elif wsource:
            while True:
                scr = screen
                path = wsource.split('.')
                while len(path) > 1:
                    scr = screen.getRelatedScreen(path[0])
                    if scr is None:
                        raise SkinError("specified related screen '" +
                                        wsource +
                                        "' was not found in screen '" + name +
                                        "'!")
                    path = path[1:]

                source = scr.get(path[0])
                if isinstance(source, ObsoleteSource):
                    print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (
                        name, wsource, source.new_source)
                    print 'OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!' % source.removal_date
                    if source.description:
                        print source.description
                    wsource = source.new_source
                else:
                    break

            if source is None:
                raise SkinError("source '" + wsource +
                                "' was not found in screen '" + name + "'!")
            wrender = get_attr('render')
            if not wrender:
                raise SkinError(
                    "you must define a renderer with render= for source '%s'" %
                    wsource)
            for converter in widget.findall('convert'):
                ctype = converter.get('type')
                try:
                    parms = converter.text.strip()
                except:
                    parms = ''

                converter_class = my_import('.'.join(
                    ('Components', 'Converter', ctype))).__dict__.get(ctype)
                c = None
                for i in source.downstream_elements:
                    if isinstance(i, converter_class
                                  ) and i.converter_arguments == parms:
                        c = i

                if c is None:
                    c = converter_class(parms)
                    c.connect(source)
                source = c

            renderer_class = my_import('.'.join(
                ('Components', 'Renderer', wrender))).__dict__.get(wrender)
            renderer = renderer_class()
            renderer.connect(source)
            attributes = renderer.skinAttributes = []
            collectAttributes(attributes,
                              widget,
                              skin_path_prefix,
                              ignore=['render', 'source'])
            screen.renderer.append(renderer)

    from Components.GUIComponent import GUIComponent
    nonvisited_components = [
        x for x in set(screen.keys()) - visited_components
        if isinstance(x, GUIComponent)
    ]
    for widget in myscreen.getchildren():
        w_tag = widget.tag
        if w_tag == 'constant-widget':
            continue
        if w_tag == 'widget':
            continue
        if w_tag == 'applet':
            try:
                codeText = widget.text.strip()
            except:
                codeText = ''

            widgetType = widget.attrib.get('type')
            code = compile(codeText, 'skin applet', 'exec')
            if widgetType == 'onLayoutFinish':
                screen.onLayoutFinish.append(code)
            else:
                raise SkinError("applet type '%s' unknown!" % widgetType)
            continue
        w = additionalWidget()
        if w_tag == 'eLabel':
            w.widget = eLabel
        elif w_tag == 'ePixmap':
            w.widget = ePixmap
        else:
            raise SkinError('unsupported stuff : %s' % w_tag)
        w.skinAttributes = []
        collectAttributes(w.skinAttributes,
                          widget,
                          skin_path_prefix,
                          ignore=['name'])
        screen.additionalWidgets.append(w)