Commit 1976a06b authored by Hartmut Goebel's avatar Hartmut Goebel
Browse files

Cleanup: pep8ifying sources.

This changes have been applied to all python files using
https://github.com/htgoebel/pep8ify and the result has been checked.
parent 5b3f6434
import platform
__version_info__ = (0,0,5)
__version_info__ = (0, 0, 5)
__version__ = '%d.%d.%d' % __version_info__[:3]
......@@ -3,7 +3,8 @@
# Copyright 2009 Frank Scholz <coherence@beebits.net>
import os,random
import os
import random
try:
_ = set()
......@@ -19,7 +20,6 @@ mimetypes.init()
from twisted.internet import defer, reactor
from twisted.python.filepath import FilePath
# Coherence
from coherence.base import Coherence
from coherence.upnp.devices.media_renderer import MediaRenderer
......@@ -31,11 +31,12 @@ from coherence.upnp.core.utils import means_true
from cadre.renderer import CadreRenderer
class Cadre(log.Loggable):
logCategory = 'renderer'
def __init__(self,config):
def __init__(self, config):
self.config = config
fullscreen = False
try:
......@@ -52,12 +53,12 @@ class Cadre(log.Loggable):
try:
overlays = self.config['overlay']
if not isinstance(overlays,list):
if not isinstance(overlays, list):
overlays = [overlays]
except:
overlays = []
map(self.canvas.add_overlay,overlays)
map(self.canvas.add_overlay, overlays)
coherence_config = {}
#coherence_config['version'] = '1'
......@@ -68,11 +69,10 @@ class Cadre(log.Loggable):
louie.connect(self.media_server_removed, 'Coherence.UPnP.ControlPoint.MediaServer.removed', louie.Any)
self.coherence = Coherence(coherence_config)
name = self.config.get('name','Cadre - Coherence Picture-Frame')
kwargs = {'version':1,
'no_thread_needed':True,
'name':name}
name = self.config.get('name', 'Cadre - Coherence Picture-Frame')
kwargs = {'version': 1,
'no_thread_needed': True,
'name': name}
kwargs['transition'] = 'NONE'
try:
......@@ -94,7 +94,7 @@ class Cadre(log.Loggable):
if uuid:
kwargs['uuid'] = uuid
print kwargs
self.renderer = MediaRenderer(self.coherence,CadreRenderer,**kwargs)
self.renderer = MediaRenderer(self.coherence, CadreRenderer, **kwargs)
if 'uuid' not in self.config:
self.config['uuid'] = str(self.renderer.uuid)[5:]
......@@ -102,10 +102,10 @@ class Cadre(log.Loggable):
self.config.save()
except AttributeError:
pass
reactor.callLater(0.5,self.start,name)
reactor.callLater(0.5, self.start, name)
def init_logging(self):
logmode = self.config.get('logging').get('level','warning')
logmode = self.config.get('logging').get('level', 'warning')
_debug = []
try:
......@@ -113,15 +113,15 @@ class Cadre(log.Loggable):
except KeyError:
subsystems = []
if isinstance(subsystems,dict):
if isinstance(subsystems, dict):
subsystems = [subsystems]
for subsystem in subsystems:
try:
if subsystem['active'] == 'no':
continue
except (KeyError,TypeError):
except (KeyError, TypeError):
pass
self.info( "setting log-level for subsystem %s to %s" % (subsystem['name'],subsystem['level']))
self.info("setting log-level for subsystem %s to %s" % (subsystem['name'], subsystem['level']))
_debug.append('%s:%d' % (subsystem['name'].lower(), log.human2level(subsystem['level'])))
if len(_debug) > 0:
......@@ -129,20 +129,20 @@ class Cadre(log.Loggable):
else:
_debug = '*:%d' % log.human2level(logmode)
logfile = self.config.get('logging').get('logfile',None)
logfile = self.config.get('logging').get('logfile', None)
if logfile != None:
logfile = unicode(logfile)
log.init(logfile, _debug)
def start(self,name):
def start(self, name):
self.canvas.set_title(name)
try:
self.content = self.config['content']
except:
self.content = []
if not isinstance( self.content, list):
if not isinstance(self.content, list):
self.content = [self.content]
tmp_l = []
......@@ -171,12 +171,12 @@ class Cadre(log.Loggable):
try:
if means_true(self.config['autostart']):
d = defer.maybeDeferred(self.get_next_item)
d.addCallback(lambda result: self.set_renderer_uri(self.renderer,result[0],result[1]))
d.addCallback(lambda result: self.set_renderer_uri(self.renderer, result[0], result[1]))
d.addErrback(self.got_error)
def get_next():
d = defer.maybeDeferred(self.get_next_item)
d.addCallback(lambda result: self.set_renderer_next_uri(self.renderer,result[0],result[1]))
d.addCallback(lambda result: self.set_renderer_next_uri(self.renderer, result[0], result[1]))
d.addErrback(self.got_error)
d.addCallback(lambda result: get_next())
......@@ -190,7 +190,7 @@ class Cadre(log.Loggable):
def quit(self):
reactor.stop()
def got_error(self,error):
def got_error(self, error):
self.warning("error %r" % error)
error.printTraceback()
......@@ -200,7 +200,7 @@ class Cadre(log.Loggable):
except:
return ['NONE']
def set_transition(self,transition):
def set_transition(self, transition):
if transition in self.get_available_transitions():
self.canvas.transition = transition
......@@ -215,19 +215,19 @@ class Cadre(log.Loggable):
try:
uri = "file://" + uri.path
return uri,''
return uri, ''
except:
if uri.startswith('http://'):
pass
raise
def set_renderer_uri(self,renderer,uri,meta=''):
def set_renderer_uri(self, renderer, uri, meta=''):
renderer.backend.stop()
renderer.backend.load(uri,meta)
renderer.backend.load(uri, meta)
renderer.backend.play()
def set_renderer_next_uri(self,renderer,uri,meta=''):
renderer.backend.upnp_SetNextAVTransportURI(InstanceID='0',NextURI=uri,NextURIMetaData=meta)
def set_renderer_next_uri(self, renderer, uri, meta=''):
renderer.backend.upnp_SetNextAVTransportURI(InstanceID='0', NextURI=uri, NextURIMetaData=meta)
def walk(self, path):
containers = []
......@@ -236,29 +236,29 @@ class Cadre(log.Loggable):
containers.append(filepath)
elif filepath.isfile():
self.items.append(FilePath(path))
while len(containers)>0:
while len(containers) > 0:
container = containers.pop()
try:
for child in container.children():
if child.isdir():
containers.append(child)
elif child.isfile() or child.islink():
mimetype,_ = mimetypes.guess_type(child.path, strict=False)
mimetype, _ = mimetypes.guess_type(child.path, strict=False)
if mimetype and mimetype.startswith("image/"):
self.items.append(child)
except UnicodeDecodeError:
self.warning("UnicodeDecodeError - there is something wrong with a file located in %r", container.get_path())
def media_server_found(self, client,udn):
def media_server_found(self, client, udn):
print "media_server_found", client.device.get_friendly_name()
def media_server_removed(self, udn):
print "media_server_removed", udn
def state_variable_change(self,variable):
self.warning("state_variable %r changed from %r -> %r" % (variable.name,variable.old_value,variable.value))
def state_variable_change(self, variable):
self.warning("state_variable %r changed from %r -> %r" % (variable.name, variable.old_value, variable.value))
if variable.name == 'NextAVTransportURI':
if variable.value == '' and self.renderer.av_transport_server.get_variable('TransportState').value == 'TRANSITIONING':
d = defer.maybeDeferred(self.get_next_item)
d.addCallback(lambda result: self.set_renderer_next_uri(self.renderer,result[0],result[1]))
d.addCallback(lambda result: self.set_renderer_next_uri(self.renderer, result[0], result[1]))
d.addErrback(self.got_error)
......@@ -31,7 +31,7 @@ loop. By default, pending calls are dealt with every 0.1 secs.
This frequency can be altered by passing a different 'call_interval'
to reactor.run(), e.g. the following:
reactor.run(call_interval=1/20.)
reactor.run(call_interval=1/20.)
will result in Twisted function calls being dealt with every
0.05 secs within the Pyglet event loop. If your code results in
......@@ -58,30 +58,31 @@ except ImportError:
# Pyglet 1.1
pyglet_event_loop = pyglet.app.EventLoop
class EventLoop(pyglet_event_loop):
def __init__(self, twisted_queue=None, call_interval=1/10.):
def __init__(self, twisted_queue=None, call_interval=1 / 10.):
"""Set up extra cruft to integrate Twisted calls."""
pyglet_event_loop.__init__(self)
if not hasattr(self, "clock"):
# This is not defined in Pyglet 1.1
self.clock = pyglet.clock.get_default()
if not twisted_queue is None:
self.register_twisted_queue(twisted_queue, call_interval)
self.register_twisted_queue(twisted_queue, call_interval)
def register_twisted_queue(self, twisted_queue, call_interval):
# The queue containing Twisted function references to call
self._twisted_call_queue = twisted_queue
# Schedule a method to deal with Twisted calls
self.clock.schedule_interval_soft(self._make_twisted_calls, call_interval)
def _make_twisted_calls(self, dt):
"""Check if we need to make function calls for Twisted."""
try:
# Deal with the next function call in the queue
f = self._twisted_call_queue.get(False)
......@@ -89,6 +90,7 @@ class EventLoop(pyglet_event_loop):
except Queue.Empty:
pass
class PygletReactor(_threadedselect.ThreadedSelectReactor):
"""
Pyglet reactor.
......@@ -102,12 +104,12 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
"""Register the pygletreactor.EventLoop instance
if necessary, i.e. if you need to subclass it.
"""
self.pygletEventLoop = eventloop
def stop(self):
"""Stop Twisted."""
if self._stopping:
return
self._stopping = True
......@@ -115,7 +117,7 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
def _runInMainThread(self, f):
"""Schedule Twisted calls within the Pyglet event loop."""
if hasattr(self, "pygletEventLoop"):
# Add the function to a queue which is called as part
# of the Pyglet event loop (see EventLoop above)
......@@ -127,11 +129,11 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
def _stopPyglet(self):
"""Stop the pyglet event loop."""
if hasattr(self, "pygletEventLoop"):
self.pygletEventLoop.exit()
def run(self, call_interval=1/10., installSignalHandlers=True):
def run(self, call_interval=1 / 10., installSignalHandlers=True):
"""Start the Pyglet event loop and Twisted reactor."""
# Create a queue to hold Twisted events that will be executed
......@@ -144,7 +146,7 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
self.registerPygletEventLoop(EventLoop(self._twistedQueue, call_interval))
else:
self.pygletEventLoop.register_twisted_queue(self._twistedQueue, call_interval)
# Start the Twisted thread.
self.interleave(self._runInMainThread,
installSignalHandlers=installSignalHandlers)
......@@ -153,14 +155,14 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
self.addSystemEventTrigger("after", "shutdown", self._stopPyglet)
self.addSystemEventTrigger("after", "shutdown",
lambda: self._postQueue.put(None))
self.pygletEventLoop.run()
# Now that the event loop has finished, remove
# it so that further Twisted events are added to
# the shutdown queue, and are dealt with below.
del self.pygletEventLoop
if not self._stopping:
# The Pyglet event loop is no longer running, so we monitor the
# queue containing Twisted events until all events are dealt with.
......@@ -178,7 +180,8 @@ class PygletReactor(_threadedselect.ThreadedSelectReactor):
f()
except:
log.err()
def install():
"""
Setup Twisted+Pyglet integration based on the Pyglet event loop.
......@@ -188,5 +191,4 @@ def install():
installReactor(reactor)
return reactor
__all__ = ['install']
This diff is collapsed.
......@@ -16,6 +16,7 @@ import pango
import clutter
from clutter import cogl
class TextureReflection (clutter.Clone):
# taken from the reflection.py example of pyclutter
......@@ -74,13 +75,13 @@ class TextureReflection (clutter.Clone):
# the upper left and the upper right at full opacity and
# the lower right and lower left and 0 opacity; OpenGL will
# do the gradient for us
color1 = cogl.color_premultiply((1, 1, 1, opacity/255.))
color1 = cogl.color_premultiply((1, 1, 1, opacity / 255.))
color2 = cogl.color_premultiply((1, 1, 1, 0))
vertices = ( \
( 0, 0, 0, 0.0, 1.0, color1), \
(width, 0, 0, 1.0, 1.0, color1), \
(width, r_height, 0, 1.0, 1.0-rty, color2), \
( 0, r_height, 0, 0.0, 1.0-rty, color2), \
(0, 0, 0, 0.0, 1.0, color1), \
(width, 0, 0, 1.0, 1.0, color1), \
(width, r_height, 0, 1.0, 1.0 - rty, color2), \
(0, r_height, 0, 0.0, 1.0 - rty, color2), \
)
cogl.push_matrix()
......@@ -106,14 +107,14 @@ class Canvas(log.Loggable):
self.stage.set_size(1200, 800)
size = self.stage.get_size()
print "%r" % (size,)
print "%r" % (size, )
display_width = size[0]*0.7
display_height = size[1]*0.7
display_width = size[0] * 0.7
display_height = size[1] * 0.7
self.stage.set_color(clutter.Color(0,0,0))
self.stage.set_color(clutter.Color(0, 0, 0))
if self.fullscreen == True:
self.stage.connect('button-press-event', lambda x,y: reactor.stop())
self.stage.connect('button-press-event', lambda x, y: reactor.stop())
self.stage.connect('destroy', lambda x: reactor.stop())
#self.stage.connect('key-press-event', self.process_key)
......@@ -123,21 +124,21 @@ class Canvas(log.Loggable):
self.texture_1 = clutter.Texture()
self.texture_1.set_opacity(0)
self.texture_1.set_keep_aspect_ratio(True)
self.texture_1.set_size(display_width,display_height)
self.texture_1.set_size(display_width, display_height)
self.texture_1.haz_image = False
self.texture_2 = clutter.Texture()
self.texture_2.set_opacity(0)
self.texture_2.set_keep_aspect_ratio(True)
self.texture_2.set_size(display_width,display_height)
self.texture_2.set_size(display_width, display_height)
self.texture_2.haz_image = False
self.texture_1.reflection = TextureReflection(self.texture_1)
self.texture_1.reflection.set_reflection_height(display_height/3)
self.texture_1.reflection.set_reflection_height(display_height / 3)
self.texture_1.reflection.set_opacity(100)
self.texture_2.reflection = TextureReflection(self.texture_2)
self.texture_2.reflection.set_reflection_height(display_height/3)
self.texture_2.reflection.set_reflection_height(display_height / 3)
self.texture_2.reflection.set_opacity(0)
x_pos = float((self.stage.get_width() - self.texture_1.get_width()) / 2)
......@@ -161,8 +162,8 @@ class Canvas(log.Loggable):
self.info("timeline_in_2_comleted")
self.texture_1.transition_fade_out_timeline = clutter.Timeline(2000)
self.texture_1.transition_fade_out_timeline.connect('completed',timeline_out_1_comleted)
alpha=clutter.Alpha(self.texture_1.transition_fade_out_timeline, clutter.EASE_OUT_SINE)
self.texture_1.transition_fade_out_timeline.connect('completed', timeline_out_1_comleted)
alpha = clutter.Alpha(self.texture_1.transition_fade_out_timeline, clutter.EASE_OUT_SINE)
self.fade_out_texture_behaviour_1 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=255, opacity_end=0)
self.fade_out_texture_behaviour_1.apply(self.texture_1)
self.fade_out_reflection_behaviour_1 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=100, opacity_end=0)
......@@ -170,16 +171,16 @@ class Canvas(log.Loggable):
self.texture_1.transition_fade_out_timeline.add_marker_at_time('out_nearly_finished', 500)
self.texture_1.transition_fade_in_timeline = clutter.Timeline(2000)
self.texture_1.transition_fade_in_timeline.connect('completed',timeline_in_1_comleted)
alpha=clutter.Alpha(self.texture_1.transition_fade_in_timeline, clutter.EASE_OUT_SINE)
self.texture_1.transition_fade_in_timeline.connect('completed', timeline_in_1_comleted)
alpha = clutter.Alpha(self.texture_1.transition_fade_in_timeline, clutter.EASE_OUT_SINE)
self.fade_in_texture_behaviour_1 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=0, opacity_end=255)
self.fade_in_texture_behaviour_1.apply(self.texture_1)
self.fade_in_reflection_behaviour_1 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=0, opacity_end=100)
self.fade_in_reflection_behaviour_1.apply(self.texture_1.reflection)
self.texture_2.transition_fade_out_timeline = clutter.Timeline(2000)
self.texture_2.transition_fade_out_timeline.connect('completed',timeline_out_2_comleted)
alpha=clutter.Alpha(self.texture_2.transition_fade_out_timeline, clutter.EASE_OUT_SINE)
self.texture_2.transition_fade_out_timeline.connect('completed', timeline_out_2_comleted)
alpha = clutter.Alpha(self.texture_2.transition_fade_out_timeline, clutter.EASE_OUT_SINE)
self.fade_out_texture_behaviour_2 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=255, opacity_end=0)
self.fade_out_texture_behaviour_2.apply(self.texture_2)
self.fade_out_reflection_behaviour_2 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=100, opacity_end=0)
......@@ -187,8 +188,8 @@ class Canvas(log.Loggable):
self.texture_2.transition_fade_out_timeline.add_marker_at_time('out_nearly_finished', 500)
self.texture_2.transition_fade_in_timeline = clutter.Timeline(2000)
self.texture_2.transition_fade_in_timeline.connect('completed',timeline_in_2_comleted)
alpha=clutter.Alpha(self.texture_2.transition_fade_in_timeline, clutter.EASE_OUT_SINE)
self.texture_2.transition_fade_in_timeline.connect('completed', timeline_in_2_comleted)
alpha = clutter.Alpha(self.texture_2.transition_fade_in_timeline, clutter.EASE_OUT_SINE)
self.fade_in_texture_behaviour_2 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=0, opacity_end=255)
self.fade_in_texture_behaviour_2.apply(self.texture_2)
self.fade_in_reflection_behaviour_2 = clutter.BehaviourOpacity(alpha=alpha, opacity_start=0, opacity_end=100)
......@@ -196,9 +197,11 @@ class Canvas(log.Loggable):
self.texture_1.fading_score = clutter.Score()
self.texture_1.fading_score.append(timeline=self.texture_2.transition_fade_out_timeline)
self.texture_1.fading_score.append_at_marker(timeline=self.texture_1.transition_fade_in_timeline,parent=self.texture_2.transition_fade_out_timeline,marker_name='out_nearly_finished')
self.texture_1.fading_score.append_at_marker(timeline=self.texture_1.transition_fade_in_timeline, parent=self.texture_2.transition_fade_out_timeline, marker_name='out_nearly_finished')
def score_1_started(x):
self.info("score_1_started")
def score_1_completed(x):
self.info("score_1_completed")
self.texture_1.fading_score.connect('started', score_1_started)
......@@ -206,9 +209,11 @@ class Canvas(log.Loggable):
self.texture_2.fading_score = clutter.Score()
self.texture_2.fading_score.append(timeline=self.texture_1.transition_fade_out_timeline)
self.texture_2.fading_score.append_at_marker(timeline=self.texture_2.transition_fade_in_timeline,parent=self.texture_1.transition_fade_out_timeline,marker_name='out_nearly_finished')
self.texture_2.fading_score.append_at_marker(timeline=self.texture_2.transition_fade_in_timeline, parent=self.texture_1.transition_fade_out_timeline, marker_name='out_nearly_finished')
def score_2_started(x):
self.info("score_2_started")
def score_2_completed(x):
self.info("score_2_completed")
self.texture_2.fading_score.connect('started', score_2_started)
......@@ -218,32 +223,32 @@ class Canvas(log.Loggable):
self.out_texture = self.texture_2
self.stage.show()
def set_title(self,title):
def set_title(self, title):
self.stage.set_title(title)
def process_key(self,stage,event):
print "process_key", stage,event
def process_key(self, stage, event):
print "process_key", stage, event
def get_available_transitions(self):
return [str(x.replace('_transition_','')) for x in dir(self) if x.startswith('_transition_')]
return [str(x.replace('_transition_', '')) for x in dir(self) if x.startswith('_transition_')]
def _transition_NONE(self):
self.in_texture.set_opacity(255)
self.in_texture.reflection.set_opacity(100)
self.out_texture.set_opacity(0)
self.out_texture.reflection.set_opacity(0)
self.out_texture,self.in_texture = self.in_texture,self.out_texture
self.out_texture, self.in_texture = self.in_texture, self.out_texture
def _transition_FADE(self):
if self.out_texture.haz_image == True:
self.texture_group.lower_child(self.out_texture)
self.texture_group.lower_child(self.out_texture.reflection)
self.in_texture.fading_score.start()
self.out_texture,self.in_texture = self.in_texture,self.out_texture
self.out_texture, self.in_texture = self.in_texture, self.out_texture
else:
self._transition_NONE()
def load_the_new_one(self,image,title):
def load_the_new_one(self, image, title):
self.warning("show image %r" % title)
if image.startswith("file://"):
filename = image[7:]
......@@ -251,8 +256,8 @@ class Canvas(log.Loggable):
#FIXME - we have the image as data already, there has to be
# a better way to get it into the texture
from tempfile import mkstemp
fp,filename = mkstemp()
os.write(fp,image)
fp, filename = mkstemp()
os.write(fp, image)
os.close(fp)
remove_file_after_loading = True
#self.texture.set_load_async(True)
......@@ -266,23 +271,23 @@ class Canvas(log.Loggable):
except:
pass
def show_image(self,image,title=''):
self.load_the_new_one(image,title)
def show_image(self, image, title=''):
self.load_the_new_one(image, title)
function = getattr(self, "_transition_%s" % self.transition, None)
if function:
function()
return
self._transition_NONE()
def add_overlay(self,overlay):
screen_width,screen_height = self.stage.get_size()
def add_overlay(self, overlay):
screen_width, screen_height = self.stage.get_size()
texture = clutter.Texture()
texture.set_keep_aspect_ratio(True)
texture.set_size(int(overlay['width']),int(overlay['height']))
texture.set_size(int(overlay['width']), int(overlay['height']))
print overlay['url']
texture.set_from_file(filename=overlay['url'])
def get_position(item_position,item_width):
def get_position(item_position, item_width):
p = float(str(item_position))
try:
orientation = item_position['orientation']
......@@ -293,7 +298,7 @@ class Canvas(log.Loggable):
except:
unit = 'px'
if unit in ['%']:
p = screen_width * (p/100.0)
p = screen_width * (p / 100.0)
else:
position = int(p)
......@@ -302,8 +307,8 @@ class Canvas(log.Loggable):
return p
position_x = get_position(overlay['position_x'],overlay['width'])
position_y = get_position(overlay['position_y'],overlay['width'])
position_x = get_position(overlay['position_x'], overlay['width'])
position_y = get_position(overlay['position_y'], overlay['width'])
print position_x, position_y
texture.set_position(position_x, position_y)
self.stage.add(texture)
\ No newline at end of file
self.stage.add(texture)
......@@ -9,17 +9,17 @@ import os
from twisted.internet import reactor
from coherence import log
# Pyglet
import pyglet
class Actor(object):
def __init__(self,drawable=None):