def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.element_separator = "|" self.segment_terminator = "\n" self.id = Element(name="MOCK", description="Mock Segment ID", required=True, minLength=2, maxLength=3, content="MCK") self.fields.append(self.id) self.test01 = Element(name="TEST01", description="TEST 01 Segment", required=False, minLength=1, maxLength=4, content="TST1") self.fields.append(self.test01) self.test02 = Element(name="TEST02", description="TEST 02 Segment", required=False, minLength=1, maxLength=4, content="") self.fields.append(self.test02)
def __init__(self, name, version, key, block_paths, block_dtd, default_flow_graph, generator, license='', website=None, colors=[]): """ Make a platform from the arguments. @param name the platform name @param version the version string @param key the unique platform key @param block_paths the file paths to blocks in this platform @param block_dtd the dtd validator for xml block wrappers @param default_flow_graph the default flow graph file path @param generator the generator class for this platform @param colors a list of title, color_spec tuples @param license a multi-line license (first line is copyright) @param website the website url for this platform @return a platform object """ _Element.__init__(self) self._name = name self._version = version self._key = key self._license = license self._website = website self._block_paths = block_paths self._block_dtd = block_dtd self._default_flow_graph = default_flow_graph self._generator = generator self._colors = colors #create a dummy flow graph for the blocks self._flow_graph = _Element(self) #search for *.xml files in the given search path self.loadblocks();
def __init__(self): """ Block contructor. Add graphics related params to the block. """ #add the position param self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Coordinate', 'key': '_coordinate', 'type': 'raw', 'value': '(0, 0)', 'hide': 'all', }))) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Rotation', 'key': '_rotation', 'type': 'raw', 'value': '0', 'hide': 'all', }))) Element.__init__(self)
def readMeshFile(self, path, filename): count = 1 elementsList = [] # ---------------------------- # Read the existing elements file # ---------------------------- f = os.path.join(path, filename) print f with open(f, "rt") as fin: for line in fin: values = [int(s) for s in line.split() if s.isdigit()] # elementNumber = re.search('/^[^\d]*(\d+)/', line) #print values l = len(values) # number, body, typeNumber, nodesindex newElement = Element( values[0], values[1], values[1] / 10.0, values[2], values[3:l] ) # number, body, densityDesignVar, typeNumber, nodesindex): newElement.numberNodes = l - 3 # record the number of nodes #print g.nodes elementsList.append(newElement) count += 1 return elementsList
def _validate_words(self, line_num, i): #print("-- VALIDTE WORDS -- ") line = self._program_text.splitlines()[line_num] line_length = len(line) #print(" _validate_words line " + line) #print(" i " + str(i)) #print(" line_length " + str(line_length)) word = line[i] i += 1 while (i < line_length and (str.isalpha(line[i]) or str.isdigit(line[i]) or line[i] == '_')): word += line[i] i += 1 #checar se eh reservado ou se eh identificador ou operador (and e or) if (word in self._key_words): self._elements.append(Element(word, "Reserved Word", line_num)) #elif(word in self._operators): # self._elements.append(Element(word, "Operator", line_num)) else: self._elements.append(Element(word, "Indentifier", line_num)) return i
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.id = Element(name="IEA", description="Interchange Control Trailer Code", required=True, minLength=3, maxLength=3, content="") self.fields.append(self.id) self.iea01 = Element(name="IEA01", description="Number of Included Groups", required=True, minLength=1, maxLength=5, content="") self.fields.append(self.iea01) self.iea02 = Element(name="IEA02", description="Interchange Control Number", required=True, minLength=1, maxLength=9, content="") self.fields.append(self.iea02)
def __init__(self): """ Block contructor. Add graphics related params to the block. """ #add the position param self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Coordinate', 'key': '_coordinate', 'type': 'raw', 'value': '(0, 0)', 'hide': 'all', }) )) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Rotation', 'key': '_rotation', 'type': 'raw', 'value': '0', 'hide': 'all', }) )) Element.__init__(self)
def create_shapes(self): """Precalculate relative coordinates.""" Element.create_shapes(self) self._sink_rot = None self._source_rot = None self._sink_coor = None self._source_coor = None #get the source coordinate try: connector_length = self.get_source().get_connector_length() except: return self.x1, self.y1 = Utils.get_rotated_coordinate((connector_length, 0), self.get_source().get_rotation()) #get the sink coordinate connector_length = self.get_sink().get_connector_length() + CONNECTOR_ARROW_HEIGHT self.x2, self.y2 = Utils.get_rotated_coordinate((-connector_length, 0), self.get_sink().get_rotation()) #build the arrow self.arrow = [(0, 0), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), ] source_domain = self.get_source().get_domain() sink_domain = self.get_sink().get_domain() self.line_attributes[0] = 2 if source_domain != sink_domain else 0 self.line_attributes[1] = gtk.gdk.LINE_DOUBLE_DASH \ if not source_domain == sink_domain == GR_MESSAGE_DOMAIN \ else gtk.gdk.LINE_ON_OFF_DASH get_domain_color = lambda d: Colors.get_color(( self.get_parent().get_parent().get_domain(d) or {} ).get('color') or Colors.DEFAULT_DOMAIN_COLOR_CODE) self._color = get_domain_color(source_domain) self._bg_color = get_domain_color(sink_domain) self._arrow_color = self._bg_color if self.is_valid() else Colors.CONNECTION_ERROR_COLOR self._update_after_move()
def validate(self): """ Validate the connections. The ports must match in type. """ Element.validate(self) platform = self.get_parent().get_parent() source_domain = self.get_source().get_domain() sink_domain = self.get_sink().get_domain() if (source_domain, sink_domain) not in platform.get_connection_templates(): self.add_error_message('No connection known for domains "%s", "%s"' % (source_domain, sink_domain)) too_many_other_sinks = ( source_domain in platform.get_domains() and not platform.get_domain(key=source_domain)['multiple_sinks'] and len(self.get_source().get_enabled_connections()) > 1 ) too_many_other_sources = ( sink_domain in platform.get_domains() and not platform.get_domain(key=sink_domain)['multiple_sources'] and len(self.get_sink().get_enabled_connections()) > 1 ) if too_many_other_sinks: self.add_error_message( 'Domain "%s" can have only one downstream block' % source_domain) if too_many_other_sources: self.add_error_message( 'Domain "%s" can have only one upstream block' % sink_domain)
def create_shapes(self): """Precalculate relative coordinates.""" Element.create_shapes(self) self._sink_rot = None self._source_rot = None self._sink_coor = None self._source_coor = None #get the source coordinate try: connector_length = self.get_source().get_connector_length() except: return self.x1, self.y1 = Utils.get_rotated_coordinate((connector_length, 0), self.get_source().get_rotation()) #get the sink coordinate connector_length = self.get_sink().get_connector_length() + CONNECTOR_ARROW_HEIGHT self.x2, self.y2 = Utils.get_rotated_coordinate((-connector_length, 0), self.get_sink().get_rotation()) #build the arrow self.arrow = [(0, 0), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), ] self._update_after_move() if not self.get_enabled(): self._arrow_color = Colors.CONNECTION_DISABLED_COLOR elif not self.is_valid(): self._arrow_color = Colors.CONNECTION_ERROR_COLOR else: self._arrow_color = Colors.CONNECTION_ENABLED_COLOR
def __init__(self): """ FlowGraph contructor. Create a list for signal blocks and connections. Connect mouse handlers. """ Element.__init__(self) #when is the flow graph selected? (used by keyboard event handler) self.is_selected = lambda: bool(self.get_selected_elements()) #important vars dealing with mouse event tracking self.element_moved = False self.mouse_pressed = False self.unselect() self.press_coor = (0, 0) #selected ports self._old_selected_port = None self._new_selected_port = None #context menu self._context_menu = gtk.Menu() for action in [ Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE, Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_PARAM_MODIFY, ]: self._context_menu.append(action.create_menu_item())
def draw(self, gc, window): """ Draw the connection. @param gc the graphics context @param window the gtk window to draw on """ sink = self.get_sink() source = self.get_source() #check for changes if self._sink_rot != sink.get_rotation( ) or self._source_rot != source.get_rotation(): self.create_shapes() elif self._sink_coor != sink.get_coordinate( ) or self._source_coor != source.get_coordinate(): self._update_after_move() #cache values self._sink_rot = sink.get_rotation() self._source_rot = source.get_rotation() self._sink_coor = sink.get_coordinate() self._source_coor = source.get_coordinate() #draw if self.is_highlighted(): border_color = Colors.HIGHLIGHT_COLOR elif self.get_enabled(): border_color = Colors.CONNECTION_ENABLED_COLOR else: border_color = Colors.CONNECTION_DISABLED_COLOR Element.draw(self, gc, window, bg_color=None, border_color=border_color) #draw arrow on sink port gc.set_foreground(self._arrow_color) window.draw_polygon(gc, True, self._arrow)
def __init__(self, param, n): Element.__init__(self, param) self._name = n.find('name') self._key = n.find('key') self._opts = dict() opts = n.findall('opt') #test against opts when non enum try: assert self.get_parent().is_enum() or not opts except AssertionError: raise Exception, 'Options for non-enum types cannot have sub-options' #extract opts for opt in opts: #separate the key:value try: key, value = opt.split(':') except: raise Exception, 'Error separating "%s" into key:value' % opt #test against repeated keys try: assert not self._opts.has_key(key) except AssertionError: raise Exception, 'Key "%s" already exists in option' % key #store the option self._opts[key] = value
def create_labels(self): """Create the labels for the socket.""" Element.create_labels(self) self._bg_color = Colors.get_color(self.get_color()) # create the layout layout = gtk.DrawingArea().create_pango_layout('') layout.set_markup( Utils.parse_template(PORT_MARKUP_TMPL, port=self, font=PORT_FONT)) self.w, self.h = layout.get_pixel_size() self.W = 2 * PORT_LABEL_PADDING + self.w self.H = 2 * PORT_LABEL_PADDING + self.h * (3 if self.get_type() == 'bus' else 1) self.H += self.H % 2 # create the pixmap pixmap = self.get_parent().get_parent().new_pixmap(self.w, self.h) gc = pixmap.new_gc() gc.set_foreground(self._bg_color) pixmap.draw_rectangle(gc, True, 0, 0, self.w, self.h) pixmap.draw_layout(gc, 0, 0, layout) # create vertical and horizontal pixmaps self.horizontal_label = pixmap if self.is_vertical(): self.vertical_label = self.get_parent().get_parent().new_pixmap( self.h, self.w) Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label)
def create_labels(self): """Create the labels for the signal block.""" Element.create_labels(self) self._bg_color = self.is_dummy_block() and Colors.MISSING_BLOCK_BACKGROUND_COLOR or \ self.get_enabled() and Colors.BLOCK_ENABLED_COLOR or Colors.BLOCK_DISABLED_COLOR layouts = list() #create the main layout layout = gtk.DrawingArea().create_pango_layout('') layouts.append(layout) layout.set_markup(Utils.parse_template(BLOCK_MARKUP_TMPL, block=self)) self.label_width, self.label_height = layout.get_pixel_size() #display the params if self.is_dummy_block(): markups = [ '<span foreground="black" font_desc="Sans 7.5"><b>key: </b>{}</span>' .format(self._key) ] else: markups = [ param.get_markup() for param in self.get_params() if param.get_hide() not in ('all', 'part') ] if markups: layout = gtk.DrawingArea().create_pango_layout('') layout.set_spacing(LABEL_SEPARATION * pango.SCALE) layout.set_markup('\n'.join(markups)) layouts.append(layout) w, h = layout.get_pixel_size() self.label_width = max(w, self.label_width) self.label_height += h + LABEL_SEPARATION width = self.label_width height = self.label_height #setup the pixmap pixmap = self.get_parent().new_pixmap(width, height) gc = pixmap.new_gc() gc.set_foreground(self._bg_color) pixmap.draw_rectangle(gc, True, 0, 0, width, height) #draw the layouts h_off = 0 for i, layout in enumerate(layouts): w, h = layout.get_pixel_size() if i == 0: w_off = (width - w) / 2 else: w_off = 0 pixmap.draw_layout(gc, w_off, h_off, layout) h_off = h + h_off + LABEL_SEPARATION #create vertical and horizontal pixmaps self.horizontal_label = pixmap if self.is_vertical(): self.vertical_label = self.get_parent().new_pixmap(height, width) Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label) #calculate width and height needed self.W = self.label_width + 2 * BLOCK_LABEL_PADDING self.H = max(*( [self.label_height+2*BLOCK_LABEL_PADDING] + [2*PORT_BORDER_SEPARATION + \ sum([port.H + PORT_SEPARATION for port in ports]) - PORT_SEPARATION for ports in (self.get_sources_gui(), self.get_sinks_gui())] + [4*PORT_BORDER_SEPARATION + \ sum([(port.H) + PORT_SEPARATION for port in ports]) - PORT_SEPARATION for ports in ([i for i in self.get_sources_gui() if i.get_type() == 'bus'], [i for i in self.get_sinks_gui() if i.get_type() == 'bus'])] ))
def __init__(self, flow_graph, porta, portb): """ Make a new connection given the parent and 2 ports. @param flow_graph the parent of this element @param porta a port (any direction) @param portb a port (any direction) @throws Error cannot make connection @return a new connection """ Element.__init__(self, flow_graph) source = sink = None #separate the source and sink for port in (porta, portb): if port.is_source(): source = port if port.is_sink(): sink = port if not source: raise ValueError('Connection could not isolate source') if not sink: raise ValueError('Connection could not isolate sink') #ensure that this connection (source -> sink) is unique for connection in self.get_parent().get_connections(): if connection.get_source() is source and connection.get_sink( ) is sink: raise Exception( 'This connection between source and sink is not unique.') self._source = source self._sink = sink
def __init__(self, param, n): Element.__init__(self, param) self._name = n.find("name") self._key = n.find("key") self._opts = dict() opts = n.findall("opt") # test against opts when non enum try: assert self.get_parent().is_enum() or not opts except AssertionError: raise Exception, "Options for non-enum types cannot have sub-options" # extract opts for opt in opts: # separate the key:value try: key, value = opt.split(":") except: raise Exception, 'Error separating "%s" into key:value' % opt # test against repeated keys try: assert not self._opts.has_key(key) except AssertionError: raise Exception, 'Key "%s" already exists in option' % key # store the option self._opts[key] = value
def create_shapes(self): """Precalculate relative coordinates.""" Element.create_shapes(self) self._sink_rot = None self._source_rot = None self._sink_coor = None self._source_coor = None #get the source coordinate connector_length = self.get_source().get_connector_length() self.x1, self.y1 = Utils.get_rotated_coordinate( (connector_length, 0), self.get_source().get_rotation()) #get the sink coordinate connector_length = self.get_sink().get_connector_length( ) + CONNECTOR_ARROW_HEIGHT self.x2, self.y2 = Utils.get_rotated_coordinate( (-connector_length, 0), self.get_sink().get_rotation()) #build the arrow self.arrow = [ (0, 0), Utils.get_rotated_coordinate( (-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE / 2), self.get_sink().get_rotation()), Utils.get_rotated_coordinate( (-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE / 2), self.get_sink().get_rotation()), ] self._update_after_move() if not self.get_enabled(): self._arrow_color = Colors.CONNECTION_DISABLED_COLOR elif not self.is_valid(): self._arrow_color = Colors.CONNECTION_ERROR_COLOR else: self._arrow_color = Colors.CONNECTION_ENABLED_COLOR
def __init__(self): """ Port contructor. Create list of connector coordinates. """ Element.__init__(self) self.connector_coordinates = dict()
def __init__(self, title=_defaultTitle, sources=_defaultSources, dom=None): """Initialize this SourceLibrary. Parameters: self: This object. title: (string) Title for this SourceLibrary. sources: (list of Source) One or more Sources which define the SourceLibrary. dom: (xml.dom.minidom.Element) Object representing a <source_library> element to use when creating the new SourceLibrary. If this parameter is provided, the other parameters are ignored. """ # Initialize the parent class. Do not pass the dom argument, # since it will be used if needed when fromDom is called # below. Element.__init__(self, tagName=SourceLibrary._tagName) # Set attributes. if dom: if isinstance(dom, xml.dom.minidom.Element): self.fromDom(dom) else: raise TypeError, 'Not a DOM element (%s)!' % dom else: self.setXmlns(SourceLibrary._defaultXmlns) self.setTitle(title) if sources is None or len(sources) == 0: sources = [Source()] self.setSources(sources)
def readMeshFile(self, path, filename): count = 1 elementsList = [] # ---------------------------- # Read the existing elements file # ---------------------------- f = os.path.join(path, filename) print f with open(f, "rt") as fin: for line in fin: values = [int(s) for s in line.split() if s.isdigit()] # elementNumber = re.search('/^[^\d]*(\d+)/', line) #print values l = len(values) # number, body, typeNumber, nodesindex newElement = Element(values[0], values[1], values[1]/10.0, values[2], values[3:l]) # number, body, densityDesignVar, typeNumber, nodesindex): newElement.numberNodes = l - 3 # record the number of nodes #print g.nodes elementsList.append(newElement) count += 1 return elementsList
def __init__(self): Segment.__init__(self) self.fieldCount = 3 self.id = Element(name="ST", description="Transaction Set Header", required=True, minLength=2, maxLength=2, content="ST") self.fields.append(self.id) self.st01 = Element(name="ST01", description="Transaction Set ID Code", required=True, minLength=3, maxLength=3, content="") self.fields.append(self.st01) self.st02 = Element(name="ST02", description="Transaction Set Control Number", required=True, minLength=4, maxLength=9, content="") self.fields.append(self.st02) self.st03 = Element(name="ST03", description="Implementation Convention Reference", required=False, minLength=1, maxLength=35, content="") self.fields.append(self.st03)
def draw(self, gc, window): """ Draw the signal block with label and inputs/outputs. Args: gc: the graphics context window: the gtk window to draw on """ # draw ports for port in self.get_ports_gui(): port.draw(gc, window) # draw main block x, y = self.get_coordinate() Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or self.is_dummy_block() and Colors.MISSING_BLOCK_BORDER_COLOR or Colors.BORDER_COLOR, ) #draw label image if self.is_horizontal(): window.draw_drawable(gc, self.horizontal_label, 0, 0, x + BLOCK_LABEL_PADDING, y + (self.H - self.label_height) / 2, -1, -1) elif self.is_vertical(): window.draw_drawable(gc, self.vertical_label, 0, 0, x + (self.H - self.label_height) / 2, y + BLOCK_LABEL_PADDING, -1, -1)
def draw(self, gc, window): """ Draw the signal block with label and inputs/outputs. @param gc the graphics context @param window the gtk window to draw on """ x, y = self.get_coordinate() #draw main block # If the image path is NOT '' if self.image_path != '': self.new_pixbuf = gtk.gdk.pixbuf_new_from_file(self.image_path) Element.draw_image( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR_BLOCK or Colors.BORDER_COLOR, pixbuf = self.new_pixbuf ) else: Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR_BLOCK or Colors.BORDER_COLOR, ) #draw label image if self.is_horizontal(): window.draw_drawable(gc, self.horizontal_label, 0, 0, x+BLOCK_LABEL_PADDING, y+(self.H-self.label_height)/2, -1, -1) elif self.is_vertical(): window.draw_drawable(gc, self.vertical_label, 0, 0, x+(self.H-self.label_height)/2, y+BLOCK_LABEL_PADDING, -1, -1) #draw ports for port in self.get_ports(): port.draw(gc, window)
def draw(self, gc, window): """ Draw the socket with a label. Args: gc: the graphics context window: the gtk window to draw on """ Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or self.get_parent().is_dummy_block() and Colors.MISSING_BLOCK_BORDER_COLOR or Colors.BORDER_COLOR, ) X, Y = self.get_coordinate() (x, y), (w, h) = self._areas_list[ 0] #use the first area's sizes to place the labels if self.is_horizontal(): window.draw_drawable(gc, self.horizontal_label, 0, 0, x + X + (self.W - self.w) / 2, y + Y + (self.H - self.h) / 2, -1, -1) elif self.is_vertical(): window.draw_drawable(gc, self.vertical_label, 0, 0, x + X + (self.H - self.h) / 2, y + Y + (self.W - self.w) / 2, -1, -1)
def __init__(self): """ Block contructor. Add graphics related params to the block. """ # add the position param self.get_params().append( self.get_parent() .get_parent() .Param( block=self, n=odict( {"name": "GUI Coordinate", "key": "_coordinate", "type": "raw", "value": "(0, 0)", "hide": "all"} ), ) ) self.get_params().append( self.get_parent() .get_parent() .Param( block=self, n=odict({"name": "GUI Rotation", "key": "_rotation", "type": "raw", "value": "0", "hide": "all"}), ) ) Element.__init__(self)
def draw(self, gc, window): """ Draw the connection. Args: gc: the graphics context window: the gtk window to draw on """ sink = self.get_sink() source = self.get_source() #check for changes if self._sink_rot != sink.get_rotation() or self._source_rot != source.get_rotation(): self.create_shapes() elif self._sink_coor != sink.get_coordinate() or self._source_coor != source.get_coordinate(): try: self._update_after_move() except: return #cache values self._sink_rot = sink.get_rotation() self._source_rot = source.get_rotation() self._sink_coor = sink.get_coordinate() self._source_coor = source.get_coordinate() #draw if self.is_highlighted(): border_color = Colors.HIGHLIGHT_COLOR elif self.get_enabled(): border_color = Colors.CONNECTION_ENABLED_COLOR else: border_color = Colors.CONNECTION_DISABLED_COLOR Element.draw(self, gc, window, bg_color=None, border_color=border_color) #draw arrow on sink port try: gc.set_foreground(self._arrow_color) window.draw_polygon(gc, True, self._arrow) except: return
def create_shapes(self): """Update the block, parameters, and ports when a change occurs.""" Element.create_shapes(self) if self.is_horizontal(): self.add_area((0, 0), (self.W, self.H)) elif self.is_vertical(): self.add_area((0, 0), (self.H, self.W))
def draw(self, gc, window): """ Draw the signal block with label and inputs/outputs. @param gc the graphics context @param window the gtk window to draw on """ x, y = self.get_coordinate() # draw main block Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or Colors.BORDER_COLOR, ) # draw label image if self.is_horizontal(): window.draw_drawable( gc, self.horizontal_label, 0, 0, x + BLOCK_LABEL_PADDING, y + (self.H - self.label_height) / 2, -1, -1 ) elif self.is_vertical(): window.draw_drawable( gc, self.vertical_label, 0, 0, x + (self.H - self.label_height) / 2, y + BLOCK_LABEL_PADDING, -1, -1 ) # draw ports for port in self.get_ports(): port.draw(gc, window)
def draw(self, gc, window): """ Draw the socket with a label. Args: gc: the graphics context window: the gtk window to draw on """ Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or self.get_parent().is_dummy_block() and Colors.MISSING_BLOCK_BORDER_COLOR or Colors.BORDER_COLOR, ) if not self._areas_list or self._label_hidden(): return # this port is either hidden (no areas) or folded (no label) X, Y = self.get_coordinate() (x, y), (w, h) = self._areas_list[0] # use the first area's sizes to place the labels if self.is_horizontal(): window.draw_drawable( gc, self.horizontal_label, 0, 0, x + X + (self.W - self.w) / 2, y + Y + (self.H - self.h) / 2, -1, -1 ) elif self.is_vertical(): window.draw_drawable( gc, self.vertical_label, 0, 0, x + X + (self.H - self.h) / 2, y + Y + (self.W - self.w) / 2, -1, -1 )
def __init__(self): """ Block contructor. Add graphics related params to the block. """ self.W = 0 self.H = 0 #add the position param self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Coordinate', 'key': '_coordinate', 'type': 'raw', 'value': '(0, 0)', 'hide': 'all', }) )) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Rotation', 'key': '_rotation', 'type': 'raw', 'value': '0', 'hide': 'all', }) )) Element.__init__(self) self._comment_pixmap = None self.has_busses = [False, False] # source, sink
def __init__(self, flow_graph, porta, portb): """ Make a new connection given the parent and 2 ports. Args: flow_graph: the parent of this element porta: a port (any direction) portb: a port (any direction) @throws Error cannot make connection Returns: a new connection """ Element.__init__(self, flow_graph) source = sink = None #separate the source and sink for port in (porta, portb): if port.is_source(): source = port if port.is_sink(): sink = port if not source: raise ValueError('Connection could not isolate source') if not sink: raise ValueError('Connection could not isolate sink') #ensure that this connection (source -> sink) is unique for connection in self.get_parent().get_connections(): if connection.get_source() is source and connection.get_sink() is sink: raise Exception('This connection between source and sink is not unique.') self._source = source self._sink = sink
def __init__(self, id, name, label, help='', type='text', **kwds): Element.__init__(self, tag='input', cls="formfield", id=id, name=name, type=type, **kwds) self.label = label self.help = help return
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.id = Element(name="SE", description="Transaction Set Trailer", required=True, minLength=2, maxLength=2, content="SE") self.fields.append(self.id) self.se01 = Element(name="SE01", description="Number of Included Segments", required=True, minLength=1, maxLength=6, content="") self.fields.append(self.se01) self.se02 = Element(name="SE02", description="Transaction Set Control Number", required=True, minLength=4, maxLength=9, content="") self.fields.append(self.se02)
def create_shapes(self): """Create new areas and labels for the port.""" Element.create_shapes(self) if self.get_hide(): return # this port is hidden, no need to create shapes if self.get_domain() == GR_MESSAGE_DOMAIN: pass elif self.get_domain() != DEFAULT_DOMAIN: self.line_attributes[0] = 2 #get current rotation rotation = self.get_rotation() #get all sibling ports if self.is_source(): ports = self.get_parent().get_sources_gui() elif self.is_sink(): ports = self.get_parent().get_sinks_gui() #get the max width self.W = max([port.W for port in ports] + [PORT_MIN_WIDTH]) W = self.W if not self._label_hidden() else PORT_LABEL_HIDDEN_WIDTH #get a numeric index for this port relative to its sibling ports try: index = ports.index(self) except: if hasattr(self, '_connector_length'): del self._connector_length return length = len(filter(lambda p: not p.get_hide(), ports)) #reverse the order of ports for these rotations if rotation in (180, 270): index = length - index - 1 offset = (self.get_parent().H - (length - 1) * PORT_SEPARATION - self.H) / 2 #create areas and connector coordinates if (self.is_sink() and rotation == 0) or (self.is_source() and rotation == 180): x = -1 * W y = PORT_SEPARATION * index + offset self.add_area((x, y), (W, self.H)) self._connector_coordinate = (x - 1, y + self.H / 2) elif (self.is_source() and rotation == 0) or (self.is_sink() and rotation == 180): x = self.get_parent().W y = PORT_SEPARATION * index + offset self.add_area((x, y), (W, self.H)) self._connector_coordinate = (x + 1 + W, y + self.H / 2) elif (self.is_source() and rotation == 90) or (self.is_sink() and rotation == 270): y = -1 * W x = PORT_SEPARATION * index + offset self.add_area((x, y), (self.H, W)) self._connector_coordinate = (x + self.H / 2, y - 1) elif (self.is_sink() and rotation == 90) or (self.is_source() and rotation == 270): y = self.get_parent().W x = PORT_SEPARATION * index + offset self.add_area((x, y), (self.H, W)) self._connector_coordinate = (x + self.H / 2, y + 1 + W) #the connector length self._connector_length = CONNECTOR_EXTENSION_MINIMAL + CONNECTOR_EXTENSION_INCREMENT * index
def create_shapes(self): """Create new areas and labels for the port.""" Element.create_shapes(self) if self.get_hide(): return # this port is hidden, no need to create shapes if self.get_domain() == GR_MESSAGE_DOMAIN: pass elif self.get_domain() != DEFAULT_DOMAIN: self.line_attributes[0] = 2 #get current rotation rotation = self.get_rotation() #get all sibling ports if self.is_source(): ports = self.get_parent().get_sources_gui() elif self.is_sink(): ports = self.get_parent().get_sinks_gui() #get the max width self.W = max([port.W for port in ports] + [PORT_MIN_WIDTH]) W = self.W if not self._label_hidden() else PORT_LABEL_HIDDEN_WIDTH #get a numeric index for this port relative to its sibling ports try: index = ports.index(self) except: if hasattr(self, '_connector_length'): del self._connector_length return length = len(filter(lambda p: not p.get_hide(), ports)) #reverse the order of ports for these rotations if rotation in (180, 270): index = length-index-1 port_separation = PORT_SEPARATION \ if self.get_parent().has_busses[self.is_source()] \ else max([port.H for port in ports]) + PORT_SPACING offset = (self.get_parent().H - (length-1)*port_separation - self.H)/2 #create areas and connector coordinates if (self.is_sink() and rotation == 0) or (self.is_source() and rotation == 180): x = -W y = port_separation*index+offset self.add_area((x, y), (W, self.H)) self._connector_coordinate = (x-1, y+self.H/2) elif (self.is_source() and rotation == 0) or (self.is_sink() and rotation == 180): x = self.get_parent().W y = port_separation*index+offset self.add_area((x, y), (W, self.H)) self._connector_coordinate = (x+1+W, y+self.H/2) elif (self.is_source() and rotation == 90) or (self.is_sink() and rotation == 270): y = -W x = port_separation*index+offset self.add_area((x, y), (self.H, W)) self._connector_coordinate = (x+self.H/2, y-1) elif (self.is_sink() and rotation == 90) or (self.is_source() and rotation == 270): y = self.get_parent().W x = port_separation*index+offset self.add_area((x, y), (self.H, W)) self._connector_coordinate = (x+self.H/2, y+1+W) #the connector length self._connector_length = CONNECTOR_EXTENSION_MINIMAL + CONNECTOR_EXTENSION_INCREMENT*index
def validate(self): """ Validate the param. The value must be evaluated and type must a possible type. """ Element.validate(self) try: assert self.get_type() in self.get_types() except AssertionError: self.add_error_message('Type "%s" is not a possible type.'%self.get_type())
def test_is_valid_too_short(self): """Test an element that's content is too short""" element = Element(name="shorty", minLength=2, maxLength=4, content="1", required=True) report = ValidationReport() element.validate(report) self.assertFalse(report.is_document_valid()) self.assertEqual("Field shorty is too short. Found 1 characters, expected 2 characters.", report.error_list[0].msg)
def validate(self): """ Validate the param. The value must be evaluated and type must a possible type. """ Element.validate(self) if self.get_type() not in self.get_types(): self.add_error_message('Type "%s" is not a possible type.'%self.get_type())
def __init__(self, name, type, value, **kwds): Element.__init__(self, 'div', cls='formControls', **kwds) self.name = name self.type = type self.value = value return
def __init__(self, x, y): Element.__init__(self, x, y) self.name = "piece" self.up = BLANK self.left = BLANK self.down = BLANK self.right = BLANK self.upside = False
def validate(self): """ Validate the port. The port must be non-empty and type must a possible type. """ Element.validate(self) if self.get_type() not in self.get_types(): self.add_error_message('Type "%s" is not a possible type.'%self.get_type())
def test_is_valid_too_long(self): """Test an element that's content is too long""" element = Element(name="longer", minLength=2, maxLength=4, content="12345", required=True) report = ValidationReport() element.validate(report) self.assertFalse(report.is_document_valid()) self.assertEqual("Field longer is too long. Found 5 characters, expected 4 characters.", report.error_list[0].msg)
def __init__(self, name, value, **kwds): Element.__init__(self, tag='input', name=name, value=value, type='hidden', **kwds) return
def __init__(self, x, y): Element.__init__(self, x, y) self.name = "wall" self.up = BLANK self.left = BLANK self.down = BLANK self.right = BLANK self.color = BLANK
def validate(self): """ Validate the port. The port must be non-empty and type must a possible type. """ Element.validate(self) try: assert self.get_type() in self.get_types() except AssertionError: self.add_error_message('Type "%s" is not a possible type.'%self.get_type())
def __init__(self, id, name, label, value='', embeddedText='', help='', error='', type='checkbox', **kwds): Element.__init__(self, tag='checkbox', id=id, name=name, type=type, value=value, **kwds) self.label = label self.help = help self.error = error return
def validate(self): """ Validate the param. The value must be evaluated and type must a possible type. """ Element.validate(self) try: assert self.get_type() in self.TYPES except AssertionError: self.add_error_message('Type "%s" is not a possible type.'%self.get_type())
def create_labels(self): """Create the labels for the signal block.""" Element.create_labels(self) self._bg_color = self.get_enabled() and Colors.BLOCK_ENABLED_COLOR or Colors.BLOCK_DISABLED_COLOR layouts = list() #create the main layout layout = gtk.DrawingArea().create_pango_layout('') layouts.append(layout) layout.set_markup(Utils.parse_template(BLOCK_MARKUP_TMPL, block=self)) self.label_width, self.label_height = layout.get_pixel_size() height_rect = self.label_height #display the params markups = [param.get_markup() for param in self.get_params() if param.get_hide() not in ('all', 'part')] if markups: layout = gtk.DrawingArea().create_pango_layout('') layout.set_spacing(LABEL_SEPARATION*pango.SCALE) layout.set_markup('\n'.join(markups)) layouts.append(layout) w,h = layout.get_pixel_size() self.label_width = max(w, self.label_width) #print w,self.label_width self.label_height += h + LABEL_SEPARATION width = self.label_width height = self.label_height #setup the pixmap pixmap = self.get_parent().new_pixmap(width, height) gc = pixmap.new_gc() gc.set_foreground(self._bg_color) pixmap.draw_rectangle(gc, True, 0, 0, width, height) #draw the layouts # width_rect=width h_off = 0 for i,layout in enumerate(layouts): w,h = layout.get_pixel_size() if i == 0: w_off = (width-w)/2 else: w_off = 0 pixmap.draw_layout(gc, w_off, h_off, layout) h_off = h + h_off + LABEL_SEPARATION #create vertical and horizontal pixmaps gc.set_foreground(Colors.BORDER_COLOR) pixmap.draw_rectangle(gc,False,0,0,width-1,height_rect-1) gc.set_foreground(self._bg_color) self.horizontal_label = pixmap if self.is_vertical(): self.vertical_label = self.get_parent().new_pixmap(height, width) Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label) #calculate width and height needed self.W = self.label_width + 2*BLOCK_LABEL_PADDING self.H = max(*( [self.label_height+2*BLOCK_LABEL_PADDING] + [2*PORT_BORDER_SEPARATION + \ sum([port.H + PORT_SEPARATION for port in ports]) - PORT_SEPARATION for ports in (self.get_sources(), self.get_sinks())] ))
def __init__(self, flow_graph, n): """ Make a new block from nested data. @param flow graph the parent element @param n the nested odict @return block a new block """ # build the block Element.__init__(self, flow_graph) # grab the data params = n.findall("param") sources = n.findall("source") sinks = n.findall("sink") self._name = n.find("name") self._key = n.find("key") self._category = n.find("category") or "" self._grc_source = n.find("grc_source") or "" self._block_wrapper_path = n.find("block_wrapper_path") # create the param objects self._params = list() # add the id param self.get_params().append( self.get_parent().get_parent().Param(block=self, n=odict({"name": "ID", "key": "id", "type": "id"})) ) self.get_params().append( self.get_parent() .get_parent() .Param( block=self, n=odict({"name": "Enabled", "key": "_enabled", "type": "raw", "value": "True", "hide": "all"}), ) ) for param in map(lambda n: self.get_parent().get_parent().Param(block=self, n=n), params): key = param.get_key() # test against repeated keys if key in self.get_param_keys(): raise Exception, 'Key "%s" already exists in params' % key # store the param self.get_params().append(param) # create the source objects self._sources = list() for source in map(lambda n: self.get_parent().get_parent().Port(block=self, n=n, dir="source"), sources): key = source.get_key() # test against repeated keys if key in self.get_source_keys(): raise Exception, 'Key "%s" already exists in sources' % key # store the port self.get_sources().append(source) # create the sink objects self._sinks = list() for sink in map(lambda n: self.get_parent().get_parent().Port(block=self, n=n, dir="sink"), sinks): key = sink.get_key() # test against repeated keys if key in self.get_sink_keys(): raise Exception, 'Key "%s" already exists in sinks' % key # store the port self.get_sinks().append(sink)
def __init__(self, block, n): """ Make a new param from nested data. Args: block: the parent element n: the nested odict """ # if the base key is a valid param key, copy its data and overlay this params data base_key = n.find('base_key') if base_key and base_key in block.get_param_keys(): n_expanded = block.get_param(base_key)._n.copy() n_expanded.update(n) n = n_expanded # save odict in case this param will be base for another self._n = n # parse the data self._name = n.find('name') self._key = n.find('key') value = n.find('value') or '' self._type = n.find('type') or 'raw' self._hide = n.find('hide') or '' self._tab_label = n.find('tab') or block.get_param_tab_labels()[0] if not self._tab_label in block.get_param_tab_labels(): block.get_param_tab_labels().append(self._tab_label) #build the param Element.__init__(self, block) #create the Option objects from the n data self._options = list() for option in map(lambda o: Option(param=self, n=o), n.findall('option')): key = option.get_key() #test against repeated keys if key in self.get_option_keys(): raise Exception, 'Key "%s" already exists in options' % key #store the option self.get_options().append(option) #test the enum options if self.is_enum(): #test against options with identical keys if len(set(self.get_option_keys())) != len(self.get_options()): raise Exception, 'Options keys "%s" are not unique.' % self.get_option_keys( ) #test against inconsistent keys in options opt_keys = self.get_options()[0].get_opt_keys() for option in self.get_options(): if set(opt_keys) != set(option.get_opt_keys()): raise Exception, 'Opt keys "%s" are not identical across all options.' % opt_keys #if a value is specified, it must be in the options keys self._value = value if value or value in self.get_option_keys( ) else self.get_option_keys()[0] if self.get_value() not in self.get_option_keys(): raise Exception, 'The value "%s" is not in the possible values of "%s".' % ( self.get_value(), self.get_option_keys()) else: self._value = value or '' self._default = value
def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(), border=False, borderid=u'', borderclasses=()): """ @param title: The text of the title @type title: string @param subtitle: The text of the subtitle @type subtitle: string or None @param x: The x coordinate to draw the title element at @param y: The y coordinate to draw the title element at @param width: The width of the title element (used for centering) @param height: The height of the title element (used for centering) @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings @param titleid: The SVG document ID of the title text @type titleid: string @param titleclasses: Classnames to be applied to the title text @type titleclasses: string or sequence of strings @param subtitleid: The SVG document ID of the subtitle text @type subtitleid: string @param subtitleclasses: Classnames to be applied to the subtitle text @type subtitleclasses: string or sequence of strings @param border: Flag designating whether or not to draw a border @type border: boolean @param borderid: The SVG document ID of the title element's border @type borderid: string @param borderclasses: Classnames to be applied to the title element's border @type borderclasses: string or sequence of strings """ Element.__init__(self) self.title = title self.subtitle = subtitle self.x = x self.y = y self.width = width self.height = height self.id = id self.classes = classes self.titleid = titleid self.titleclasses = titleclasses self.subtitleid = subtitleid self.subtitleclasses = subtitleclasses self.border = border self.borderid = borderid self.borderclasses = borderclasses
def validate(self): """ Validate the connections. The ports must match in type. """ Element.validate(self) source_type = self.get_source().get_type() sink_type = self.get_sink().get_type() if source_type != sink_type: self.add_error_message('Source type "%s" does not match sink type "%s".'%(source_type, sink_type))
def __init__(self, platform): """ Make a flow graph from the arguments. @param platform a platforms with blocks and contrcutors @return the flow graph object """ #initialize Element.__init__(self, platform) #inital blank import self.import_data()