Commit 1ea3a2bb authored by Maxime Perrotin's avatar Maxime Perrotin
Browse files

flake8 fixes

parent 559ba8be
......@@ -95,8 +95,8 @@ def generate(ast):
raise TypeError('[AdaGenerator] Unsupported AST construct')
return [], []
# Processing of the AST
# Processing of the AST
@generate.register(ogAST.Process)
def _process(process):
''' Generate the code for a complete process (AST Top level) '''
......@@ -133,7 +133,6 @@ def _process(process):
t=var_type.ReferencedTypeName.replace('-', '_'),
default=u' := ' + dstr if def_value else u''))
# Add the process states list to the process-level variables
statelist = ', '.join(name for name in process.mapping.iterkeys()
if not name.endswith(u'START')) or 'No_State'
......@@ -150,7 +149,7 @@ def _process(process):
# Add function allowing to trace current state as a string
#process_level_decl.append('function get_state return String;')
#process_level_decl.append('pragma export(C, get_state, "{}_state");'
# .format(process_name))
# .format(process_name))
# Add the declaration of the runTransition procedure
process_level_decl.append('procedure runTransition(Id: Integer);')
......@@ -162,7 +161,6 @@ def _process(process):
start_transition = ['begin',
'runTransition(0);']
# Generate the TASTE template
try:
asn1_modules = '\n'.join(['with {dv};\nuse {dv};'.format(
......@@ -245,7 +243,7 @@ package {process_name} is'''.format(process_name=process_name,
# Check for nested states to call optional exit procedure
sep = u'\u00dc'
state_tree = state.split(sep)
context=process
context = process
exitlist = []
current = ''
trans = input_def and process.transitions[input_def.transition_id]
......@@ -309,7 +307,8 @@ package {process_name} is'''.format(process_name=process_name,
par=param, partype=typename))
if params:
ri_header += u'(' + u';'.join(params) + ')'
ads_template.append(u'-- Sync required interface "' + proc.inputString)
ads_template.append(
u'-- Sync required interface "' + proc.inputString)
ads_template.append(ri_header + u';')
ads_template.append(u'pragma import(C, {sig}, "{proc}_RI_{sig}");'
.format(sig=proc.inputString, proc=process_name))
......@@ -348,7 +347,6 @@ package {process_name} is'''.format(process_name=process_name,
code_transitions.append(code_tr)
local_decl_transitions.extend(tr_local_decl)
# Generate code for the floating labels
code_labels = []
for label in process.content.floating_labels:
......@@ -403,7 +401,6 @@ package {process_name} is'''.format(process_name=process_name,
#taste_template.append('end get_state;')
#taste_template.append('\n')
taste_template.extend(start_transition)
taste_template.append('end {process_name};'
.format(process_name=process_name))
......@@ -412,12 +409,12 @@ package {process_name} is'''.format(process_name=process_name,
.format(process_name=process_name))
with open(process_name + '.adb', 'w') as ada_file:
ada_file.write \
(u'\n'.join(format_ada_code(taste_template)).encode('latin1'))
ada_file.write(
u'\n'.join(format_ada_code(taste_template)).encode('latin1'))
with open(process_name + '.ads', 'w') as ada_file:
ada_file.write \
(u'\n'.join(format_ada_code(ads_template)).encode('latin1'))
ada_file.write(
u'\n'.join(format_ada_code(ads_template)).encode('latin1'))
def write_statement(param, newline):
......@@ -618,8 +615,8 @@ def _task_forloop(task):
if loop['range']:
start_str, stop_str = '0', ''
if loop['range']['start']:
start_stmt, start_str, start_local = expression\
(loop['range']['start'])
start_stmt, start_str, start_local = expression(
loop['range']['start'])
local_decl.extend(start_local)
stmt.extend(start_stmt)
# ASN.1 Integers are 64 bits - we need to convert to 32 bits
......@@ -697,6 +694,7 @@ def expression(expr):
raise TypeError('Unsupported expression: ' + str(expr))
return [], '', []
@expression.register(ogAST.PrimVariable)
def _primary_variable(prim):
''' Single variable reference '''
......@@ -882,6 +880,7 @@ def _basic_operators(expr):
local_decl.extend(right_local)
return code, ada_string, local_decl
@expression.register(ogAST.ExprOr)
@expression.register(ogAST.ExprAnd)
@expression.register(ogAST.ExprXor)
......@@ -1082,6 +1081,7 @@ def _mantissa_base_exp(primary):
_ = primary
return [], '', []
@expression.register(ogAST.PrimIfThenElse)
def _if_then_else(ifThenElse):
''' Return string and statements for ternary operator '''
......@@ -1264,6 +1264,7 @@ def _decision(dec):
code.append('end if;')
return code, local_decl
@generate.register(ogAST.Label)
def _label(lab):
''' Transition following labels are generated in a separate section
......@@ -1325,8 +1326,8 @@ def _transition(tr):
string = ''
if tr.terminator.next_id == -1:
if tr.terminator.return_expr:
stmts, string, local = expression\
(tr.terminator.return_expr)
stmts, string, local = expression(
tr.terminator.return_expr)
code.extend(stmts)
local_decl.extend(local)
code.append('return{};'
......@@ -1509,6 +1510,7 @@ def traceability(symbol):
trace.extend(traceability(symbol.comment))
return trace
def format_ada_code(stmts):
''' Indent properly the Ada code '''
indent = 0
......@@ -1517,7 +1519,7 @@ def format_ada_code(stmts):
elems = line.strip().split()
if elems and elems[0].startswith(('when', 'end', 'elsif', 'else')):
indent = max(indent - 1, 0)
if elems and elems[-1] == 'case;': # Corresponds to end case;
if elems and elems[-1] == 'case;': # Corresponds to end case;
indent = max(indent - 1, 0)
if line:
yield indent_pattern * indent + line
......
......@@ -37,6 +37,7 @@ except ImportError:
__all__ = ['ASN1', 'parse_asn1']
__version__ = '0.1'
class ASN1(Enum):
''' Flags used to control the compiler options '''
NoParameterizedTypes = 1
......@@ -52,7 +53,7 @@ def parse_asn1(*files, **options):
global AST
ast_version = options.get('ast_version', ASN1.UniqueEnumeratedNames)
flags = options.get('flags' , [ASN1.AstOnly])
flags = options.get('flags', [ASN1.AstOnly])
assert isinstance(ast_version, ASN1)
assert isinstance(flags, list)
......@@ -72,7 +73,11 @@ def parse_asn1(*files, **options):
'-customStg', tmp_stg + ':' + filepath] + list(*files)
LOG.debug('Calling: ' + ' '.join(args))
ret = subprocess.check_call(args)
try:
ret = subprocess.check_call(args)
except subprocess.CalledProcessError as err:
LOG.debug(str(err))
raise TypeError('asn1.exe execution failed')
sys.path.append(tempdir)
if ret == 0:
if filename in AST.viewkeys():
......@@ -97,9 +102,3 @@ if __name__ == '__main__':
except TypeError as err:
print(str(err))
sys.exit(1)
......@@ -34,6 +34,7 @@ COPY_PASTE = []
# Actual scene clipboard
CLIPBOARD = None
def copy(selection):
''' Create a copy (duplicate) of the selected symbols in AST form '''
# Clear the copy paste buffer
......@@ -99,6 +100,7 @@ def copy_branch(top_level_item):
res_terminators.extend(term_inators)
return branch, res_terminators
def paste(parent, scene):
'''
Paste previously copied symbols at selection point
......@@ -130,7 +132,7 @@ def paste_floating_objects(scene):
new_item = Renderer.render(state, scene=CLIPBOARD,
terminators=terminators, states=states)
except TypeError as err:
LOG.debug('No paste "'+ state.inputString + '" -' + str(err))
LOG.debug('No paste "' + state.inputString + '" -' + str(err))
# Discard terminators (explanation given in Renderer._state)
pass
else:
......@@ -155,7 +157,7 @@ def paste_floating_objects(scene):
def paste_below_item(parent, scene):
''' Paste items under a selected symbol '''
LOG.debug('Pasting below item ' + repr(parent)[slice(0,20)])
LOG.debug('Pasting below item ' + repr(parent)[slice(0, 20)])
symbols = []
for item_list, _ in COPY_PASTE:
states = [i for i in item_list if isinstance(i, ogAST.State)]
......
......@@ -15,11 +15,8 @@
Contact: maxime.perrotin@esa.int
"""
import os
import sys
import math
import logging
from collections import namedtuple
from PySide.QtCore import Qt, QPointF, QLineF
......@@ -27,6 +24,9 @@ from PySide.QtGui import QGraphicsPathItem, QPainterPath, QGraphicsItem, QPen,\
QPainter, QFont, QGraphicsTextItem, QColor, \
QFontMetrics
LOG = logging.getLogger(__name__)
# pylint: disable=R0904
class Connection(QGraphicsPathItem, object):
''' Connection between two symbols (top-level class) '''
......@@ -39,7 +39,7 @@ class Connection(QGraphicsPathItem, object):
super(Connection, self).__init__(parent)
self.parent = parent
self.child = child
self._start_point = None
self._start_point = None
self._end_point = None
self._middle_points = []
pen = QPen()
......@@ -91,14 +91,13 @@ class Connection(QGraphicsPathItem, object):
angle = math.pi * 2 - angle
arrow_size = 10.0
arrow_p1 = end_point + QPointF(
math.sin(angle - math.pi/3) * arrow_size,
math.cos(angle - math.pi/3) * arrow_size)
math.sin(angle - math.pi / 3) * arrow_size,
math.cos(angle - math.pi / 3) * arrow_size)
arrow_p2 = end_point + QPointF(
math.sin(angle - math.pi + math.pi/3) * arrow_size,
math.cos(angle - math.pi + math.pi/3) * arrow_size)
math.sin(angle - math.pi + math.pi / 3) * arrow_size,
math.cos(angle - math.pi + math.pi / 3) * arrow_size)
return (arrow_p1, arrow_p2)
def draw_arrow_head(self, shape, origin='head', kind='simple'):
''' Generic function to draw a simple arrow '''
if kind == 'simple':
......@@ -301,7 +300,6 @@ class Connectionpoint(Controlpoint):
# Symbol actually owning the connection point
self.symbol = symbol
def update_position(self):
'''
Update the position of the end point so that it is always
......
......@@ -105,7 +105,7 @@ def flatten(process, sep=u'_'):
set_terminator_states(state, prefix)
set_transition_states(state, prefix)
state.mapping = {prefix + key:state.mapping.pop(key)
state.mapping = {prefix + key: state.mapping.pop(key)
for key in state.mapping.keys()}
process.transitions.extend(state.transitions)
......@@ -252,6 +252,7 @@ def rename_everything(ast, from_name, to_name):
'''
_, _, _ = ast, from_name, to_name
@rename_everything.register(ogAST.Automaton)
def _rename_automaton(ast, from_name, to_name):
''' Renaming at Automaton top level (content of digragrams) '''
......@@ -297,6 +298,7 @@ def _rename_label(ast, from_name, to_name):
ast.inputString = to_name
rename_everything(ast.transition, from_name, to_name)
@rename_everything.register(ogAST.Decision)
def _rename_decision(ast, from_name, to_name):
''' Rename elements in decision '''
......@@ -312,7 +314,7 @@ def _rename_answer(ast, from_name, to_name):
if ast.kind in ('constant', 'open_range'):
rename_everything(ast.constant, from_name, to_name)
elif ast.kind == 'closed_range':
pass # TODO when supported
pass # TODO when supported
rename_everything(ast.transition, from_name, to_name)
......@@ -323,6 +325,7 @@ def _rename_transition(ast, from_name, to_name):
# Label, output, task, decision, terminators
rename_everything(each, from_name, to_name)
@rename_everything.register(ogAST.Terminator)
def _rename_terminator(ast, from_name, to_name):
''' Rename terminators: join/labels, next_state '''
......@@ -338,6 +341,7 @@ def _rename_task_assign(ast, from_name, to_name):
for each in ast.elems:
rename_everything(each, from_name, to_name)
@rename_everything.register(ogAST.TaskForLoop)
def _rename_forloop(ast, from_name, to_name):
''' List of FOR loops '''
......@@ -347,6 +351,7 @@ def _rename_forloop(ast, from_name, to_name):
rename_everything(each['range']['stop'], from_name, to_name)
rename_everything(each['transition'], from_name, to_name)
@rename_everything.register(ogAST.ExprPlus)
@rename_everything.register(ogAST.ExprMul)
@rename_everything.register(ogAST.ExprMinus)
......@@ -371,6 +376,7 @@ def _rename_expr(ast, from_name, to_name):
rename_everything(ast.left, from_name, to_name)
rename_everything(ast.right, from_name, to_name)
@rename_everything.register(ogAST.PrimPath)
@rename_everything.register(ogAST.PrimVariable)
def _rename_path(ast, from_name, to_name):
......@@ -378,12 +384,14 @@ def _rename_path(ast, from_name, to_name):
if ast.value[0].lower() == from_name.lower():
ast.value[0] = to_name
@rename_everything.register(ogAST.PrimIfThenElse)
def _rename_ifhthenelse(ast, from_name, to_name):
''' Rename expressions in If-Then-Else-Fi construct '''
for expr in ('if', 'then', 'else'):
rename_everything(ast.value[expr], from_name, to_name)
def find_labels(trans):
'''
Yield a list of transition actions whenever a label is found
......@@ -404,7 +412,8 @@ def find_labels(trans):
new_trans = ogAST.Transition()
# Create a floating label
flab = ogAST.Floating_label(label=action)
new_trans.actions = trans.actions[slice(idx+1, len(trans.actions))]
new_trans.actions = \
trans.actions[slice(idx + 1, len(trans.actions))]
new_trans.terminator = trans.terminator
new_trans.terminators = trans.terminators
flab.transition = new_trans
......@@ -423,8 +432,7 @@ def find_labels(trans):
for new_fl in find_labels(answer.transition):
# Append the remaining actions of the transition
if not new_fl.transition.terminator:
new_fl.transition.actions.extend(
trans.actions[slice(idx+1, len(trans.actions))])
new_fl.transition.actions.extend(trans.actions
[slice(idx + 1, len(trans.actions))])
new_fl.transition.terminator = trans.terminator
yield new_fl
......@@ -22,7 +22,7 @@ import math
import random
from PySide import QtGui, QtCore
from PySide.QtCore import QPointF, QLineF
from PySide.QtCore import QPointF
from PySide.QtGui import QPainterPath
try:
......@@ -36,6 +36,7 @@ import icons
LOG = logging.getLogger(__name__)
# pylint: disable=R0904
class Rocket(genericSymbols.Symbol, object):
''' An Opengeode rocket '''
......@@ -54,24 +55,24 @@ class Rocket(genericSymbols.Symbol, object):
def set_shape(self, width, height):
''' Define the polygon shape from width and height '''
path = QtGui.QPainterPath()
path.moveTo(width/2, 0)
path.lineTo(width/3, height/6)
path.lineTo(width/3, height-height/6)
path.lineTo(width-width/3, height-height/6)
path.lineTo(width-width/3, height/6)
path.lineTo(width/2, 0)
path.moveTo(width/3, height/2)
path.lineTo(0, height/2)
path.moveTo(width / 2, 0)
path.lineTo(width / 3, height / 6)
path.lineTo(width / 3, height - height / 6)
path.lineTo(width - width / 3, height - height / 6)
path.lineTo(width - width / 3, height / 6)
path.lineTo(width / 2, 0)
path.moveTo(width / 3, height / 2)
path.lineTo(0, height / 2)
path.lineTo(0, height)
path.lineTo(width/6, height-height/6)
path.lineTo(width/3, height)
path.lineTo(width/3, height-height/6)
path.moveTo(width-width/3, height/2)
path.lineTo(width, height/2)
path.lineTo(width / 6, height - height / 6)
path.lineTo(width / 3, height)
path.lineTo(width / 3, height - height / 6)
path.moveTo(width - width / 3, height / 2)
path.lineTo(width, height / 2)
path.lineTo(width, height)
path.lineTo(width-width/6, height-height/6)
path.lineTo(width-width/3, height)
path.lineTo(width-width/3, height-height/6)
path.lineTo(width - width / 6, height - height / 6)
path.lineTo(width - width / 3, height)
path.lineTo(width - width / 3, height - height / 6)
self.setPath(path)
super(Rocket, self).set_shape(width, height)
......@@ -95,13 +96,14 @@ class Rocket(genericSymbols.Symbol, object):
' bounding rect = ' + str(self.boundingRect()))
def mouse_move(self, event):
''' Discard mouse move '''
''' Discard mouse move '''
pass
def mouse_release(self, _):
''' Mouse has no effect on the rocket '''
pass
class Lander(object):
''' Rocket Lander '''
def __init__(self, scene):
......@@ -126,7 +128,7 @@ class Lander(object):
path = QPainterPath(p1)
slope = (p2.y() - p1.y()) / (p2.x() - p1.x())
sign = 3
for point in range(int((p2.x() - p1.x())/5)):
for point in range(int((p2.x() - p1.x()) / 5)):
sign = -sign
x = p1.x() + point * 5
path.lineTo(x, slope * x + sign)
......@@ -186,7 +188,7 @@ class Lander(object):
# Up key action depends on current speed and angle
self.animation.stop()
end_value = self.animation.endValue()
remaining_time =(self.animation.totalDuration() -
remaining_time = (self.animation.totalDuration() -
self.animation.currentTime())
if 90 < abs(self.rocket.angle) < 270:
# If the rocket nose is towards Earth
......@@ -220,7 +222,7 @@ class Lander(object):
elif evt.key() == QtCore.Qt.Key_Down:
# Down key has no effect
pass
pass
else:
pass
......@@ -252,7 +254,6 @@ class Lander(object):
else:
print 'GAME OVER'
def quit_scene(self):
''' Redefinition of the quit_scene: Stop the game and the music '''
try:
......@@ -262,4 +263,4 @@ class Lander(object):
if __name__ == '__main__':
print 'What do you expect?'
print('What do you expect?')
......@@ -49,6 +49,7 @@ def add_to_scene(item, scene):
else:
raise TypeError('This symbol does not fit the current scene')
@singledispatch
def render(ast, scene, parent, states, terminators=None):
''' Render a transition action symbol on the scene '''
......@@ -128,12 +129,10 @@ def _automaton(ast, scene):
new_state = render(state, scene=scene, states=ast.states,
terminators=ast.parent.terminators)
if new_state.nested_scene:
if str(new_state).lower() in nested_states: #.viewkeys():
if str(new_state).lower() in nested_states:
new_state.nested_scene = None
else:
nested_states.append(str(new_state).lower())
#nested_states[str(new_state).lower()] = \
# new_state.nested_scene
except TypeError:
# Discard terminators (see _state function for explanation)
pass
......@@ -197,7 +196,7 @@ def _start(ast, scene, states, parent=None):
@render.register(ogAST.CompositeState_start)
def _start(ast, scene, states, parent=None):
def _composite_start(ast, scene, states, parent=None):
''' Add an editable start symbol to a scene (in composite states) '''
_ = parent
start_symbol = sdlSymbols.StateStart(ast)
......@@ -265,7 +264,7 @@ def _output(ast, scene, parent, states):
@render.register(ogAST.ProcedureCall)
def _output(ast, scene, parent, states):
def _procedure_call(ast, scene, parent, states):
''' Create an OUTPUT or PROCEDURE CALL symbol '''
_, _ = scene, states
return sdlSymbols.ProcedureCall(parent, ast=ast)
......@@ -310,7 +309,7 @@ def _terminator(ast, scene, parent, states):
''' Create a TERMINATOR symbol '''
if ast.label:
# pylint: disable=E1111
parent = render(ast.label,scene=scene, parent=parent, states=states)
parent = render(ast.label, scene=scene, parent=parent, states=states)
if ast.kind == 'next_state':
LOG.debug('ADDING NEXT_STATE ' + ast.inputString)
# Create a new state symbol
......@@ -352,6 +351,7 @@ def _input(ast, scene, parent, states):
states=states)
return inp
@render.register(ogAST.Connect)
def _connect(ast, scene, parent, states):
''' Add connect symbol from the AST to the scene '''
......
......@@ -20,9 +20,7 @@
"""
import logging
import math
import re
from itertools import chain
from PySide import QtGui, QtCore
try:
......@@ -174,6 +172,7 @@ class Diamond(genericSymbols.HorizontalSymbol, object):
#update(self.scene())
pass
def edges(scene, node):
''' Return all edges of a given node '''
for item in scene.items():
......@@ -256,7 +255,7 @@ def preprocess_nodes(my_graph, bounding_rect, dpi):
shape=each.graph_attr['shape'],
label=each.graph_attr['label'],
style=each.graph_attr['style'],
name='cluster_'+each.graph_attr['label'],
name='cluster_' + each.graph_attr['label'],
kind='cluster')
attrs.append(attr)
for node in my_graph.nodes_iter():
......@@ -337,13 +336,12 @@ def update(scene):
for edge in EDGES:
graph.add_edge(edge, label=edge.attr.get('label') or '')
#print graph.to_string()
if nodes:
before = scene.itemsBoundingRect().center()
before_pos = graph.get_node(nodes[0]['name']).attr['pos']
#before_pos = graph.get_node(nodes[0]['name']).attr['pos']
render_statechart(scene, graph, keep_pos=True)
after_pos = graph.get_node(nodes[0]['name']).attr['pos']
#after_pos = graph.get_node(nodes[0]['name']).attr['pos']
#print before_pos,after_pos
delta = scene.itemsBoundingRect().center() - before
# graphviz translates the graph to pos (0, 0) -> move it back
......@@ -425,7 +423,7 @@ def create_dot_graph(root_ast):
# this will have to be recursive
subnodes = (name for name in graph.iternodes()
if name.startswith(each.statename.lower() + '_'))
graph.add_subgraph(subnodes, name='cluster_'+each.statename.lower(),
graph.add_subgraph(subnodes, name='cluster_' + each.statename.lower(),
label=each.statename.lower(),
style='rounded', shape='record')
for state, inputs in root_ast.mapping.viewitems():
......
......@@ -50,20 +50,17 @@
__all__ = ['Symbol', 'VerticalSymbol', 'HorizontalSymbol', 'Comment']
import os
import sys
import logging
from PySide.QtCore import(Qt, QPoint, QPointF, QRect, Slot, QRegExp, QFile,
QObject, Property)
from PySide import QtSvg
from PySide.QtGui import(QGraphicsTextItem, QGraphicsPathItem,
QGraphicsPolygonItem, QPainterPath, QGraphicsItem,
QCompleter, QGraphicsProxyWidget, QListWidget,
QListWidgetItem, QTextCursor, QSyntaxHighlighter, QTextCharFormat,
QFont, QPen, QColor, QMenu, QFileDialog, QImage, QPainter,
QLineEdit, QBrush, QTextBlockFormat, QPrinter, QStringListModel)
QFont, QPen, QColor, QMenu, QFileDialog, QPainter,
QLineEdit, QTextBlockFormat, QStringListModel)
from PySide.QtUiTools import QUiLoader
......@@ -87,7 +84,6 @@ class Completer(QGraphicsProxyWidget, object):
self.string_list = QStringListModel()
self._completer = QCompleter()
self.completion_list = parent.parentItem().completion_list
#self._completer = QCompleter(list(parent.parentItem().completion_list))
self._completer.setCaseSensitivity(Qt.CaseInsensitive)
# For some reason the default minimum size is (61,61)
# Set it to 0 so that the size of the box is not taken
......@@ -397,7 +393,7 @@ class EditableText(QGraphicsTextItem, object):
# Set width to auto-expand, and disables alignment, while editing: