def __init__(self, diagram, block_type, block_id=1): self.block_type = block_type self.diagram = diagram self.data_dir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(block_type): self.block_description = s2idirectory.block[block_type] else: self.block_description = s2idirectory.block[0] print "Bad block type.. assuming 00" self.block_id = block_id self.widgets = {} self.focus = False self.has_flow = False self.m_bTimeShifts = False self.m_bIsSource = False if self.block_description.has_key("IsSource"): #all data sources self.m_bIsSource = self.block_description["IsSource"] if self.block_description.has_key("TimeShifts"): #delay block self.m_bTimeShifts = self.block_description["TimeShifts"] self.m_oPropertiesXML = XMLParser( self.data_dir + str(self.block_description["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr( "id", str(self.block_id)) self.m_oBorderColor = [0, 0, 0, 255] self.m_oBackColor = [0, 0, 0, 150] self.input_port_centers = [] self.output_port_centers = [] self.width = WIDTH_DEFAULT t_nMaxIO = max(len(self.block_description["InTypes"]), len(self.block_description["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO - 1) * 5) #espacamento entre ports = 5 + (RADIUS * 2) #tirando a margem superior e inferior + (t_nMaxIO * INPUT_HEIGHT), #adicionando a altura de cada port HEIGHT_DEFAULT) self.__gobject_init__() self.group = self.diagram.root().add(self, x=0, y=0) self.group.connect("event", self.__group_event) self.group.set_flags(gtk.CAN_FOCUS) self.build()
def __init__( self, diagram, a_nBlockType, a_nBlockCountId=1):#a_nInputs, a_nOutputs, a_nBlockType ): self.m_nBlockType = a_nBlockType self.ParentDiagram = diagram self.m_sDataDir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(a_nBlockType): self.m_oDictBlock = s2idirectory.block[a_nBlockType] #a_oDictBlock else: self.m_oDictBlock = s2idirectory.block[0] #a_oDictBlock print "Bad block type.. assuming 00" self.m_nBlockCountId = a_nBlockCountId self.widgets = {} self.m_bFocus = False self.m_bHasFlow = False self.m_bTimeShifts = False self.m_bIsSource = False if self.m_oDictBlock.has_key("IsSource"): #all data sources self.m_bIsSource = self.m_oDictBlock["IsSource"] if self.m_oDictBlock.has_key("TimeShifts"): #delay block self.m_bTimeShifts = self.m_oDictBlock["TimeShifts"] self.m_oPropertiesXML = XMLParser(self.m_sDataDir+str(self.m_oDictBlock["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",str(self.m_nBlockCountId)) self.m_oBorderColor = [ 0, 0, 0, 255 ] self.m_oBackColor = [0,0,0,150] self.m_nRadius = 15 self.m_nInputHeight = 24 self.m_nInputWidth = 24 self.m_nOutputHeight = 24 self.m_nOutputWidth = 24 self.inputPortCenters = [] self.outputPortCenters = [] self.width = WIDTH_DEFAULT self.TextWidth = self.width - WIDTH_2_TEXT_OFFSET t_nMaxIO = max(len(self.m_oDictBlock["InTypes"]), len(self.m_oDictBlock["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO-1)* 5 ) #espacamento entre ports = 5 +(self.m_nRadius*2 ) #tirando a margem superior e inferior +(t_nMaxIO * self.m_nInputHeight),#adicionando a altura de cada port HEIGHT_DEFAULT) self.Label = self.m_oDictBlock["Label"] self.iconFile = self.m_sDataDir+self.m_oDictBlock["Icon"] self.__gobject_init__() self.wGroup = self.ParentDiagram.root().add(self,x=0,y=0) self.wGroup.connect("event", self.group_event) self.wGroup.set_flags(gtk.CAN_FOCUS) self.Build()
def __loadConfFile(self): if(not os.path.exists(os.path.expanduser(self.confFilePath))): self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) tipsOfTheDay = self.confFile.getTag("tipsOfTheDay") tips_ver = tipsOfTheDay.getAttr("version") if tips_ver != TIPS_VER: self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) show_tips = tipsOfTheDay.getAttr("show") if show_tips == "True": for tip in tipsOfTheDay.getChildTags("tip"): self.avTips[int(tip.getAttr("id"))]=(tip.getAttr("enabled") == "True") print self.avTips
def GenerateBlankConf(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":"True", "version":TIPS_VER}) for tipInstance in range(len(TIPS)): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":"True", "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close()
def __saveConfFile(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":str(self.showTips), "version":TIPS_VER}) for tipInstance in self.avTips.keys(): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":self.avTips[tipInstance], "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close()
def __init__( self, diagram, block_type, block_id=1): self.block_type = block_type self.diagram = diagram self.data_dir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(block_type): self.block_description = s2idirectory.block[block_type] else: self.block_description = s2idirectory.block[0] print "Bad block type.. assuming 00" self.block_id = block_id self.widgets = {} self.focus = False self.has_flow = False self.time_shifts = False self.is_source = False if self.block_description.has_key("IsSource"): #all data sources self.is_source = self.block_description["IsSource"] if self.block_description.has_key("TimeShifts"): #delay block self.time_shifts = self.block_description["TimeShifts"] self.m_oPropertiesXML = XMLParser(self.data_dir + str(self.block_description["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",str(self.block_id)) self.m_oBorderColor = [ 0, 0, 0, 255 ] self.m_oBackColor = [0,0,0,150] self.input_port_centers = [] self.output_port_centers = [] self.width = WIDTH_DEFAULT t_nMaxIO = max(len(self.block_description["InTypes"]), len(self.block_description["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO-1)* 5 ) #espacamento entre ports = 5 +(RADIUS*2 ) #tirando a margem superior e inferior +(t_nMaxIO * INPUT_HEIGHT),#adicionando a altura de cada port HEIGHT_DEFAULT) self.__gobject_init__() self.group = self.diagram.root().add(self,x=0,y=0) self.group.connect("event", self.__group_event) self.group.set_flags(gtk.CAN_FOCUS) self.build()
class GcdBlock( gnomecanvas.CanvasGroup): def __init__( self, diagram, a_nBlockType, a_nBlockCountId=1):#a_nInputs, a_nOutputs, a_nBlockType ): self.m_nBlockType = a_nBlockType self.ParentDiagram = diagram self.m_sDataDir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(a_nBlockType): self.m_oDictBlock = s2idirectory.block[a_nBlockType] #a_oDictBlock else: self.m_oDictBlock = s2idirectory.block[0] #a_oDictBlock print "Bad block type.. assuming 00" self.m_nBlockCountId = a_nBlockCountId self.widgets = {} self.m_bFocus = False self.m_bHasFlow = False self.m_bTimeShifts = False self.m_bIsSource = False if self.m_oDictBlock.has_key("IsSource"): #all data sources self.m_bIsSource = self.m_oDictBlock["IsSource"] if self.m_oDictBlock.has_key("TimeShifts"): #delay block self.m_bTimeShifts = self.m_oDictBlock["TimeShifts"] self.m_oPropertiesXML = XMLParser(self.m_sDataDir+str(self.m_oDictBlock["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",str(self.m_nBlockCountId)) self.m_oBorderColor = [ 0, 0, 0, 255 ] self.m_oBackColor = [0,0,0,150] self.m_nRadius = 15 self.m_nInputHeight = 24 self.m_nInputWidth = 24 self.m_nOutputHeight = 24 self.m_nOutputWidth = 24 self.inputPortCenters = [] self.outputPortCenters = [] self.width = WIDTH_DEFAULT self.TextWidth = self.width - WIDTH_2_TEXT_OFFSET t_nMaxIO = max(len(self.m_oDictBlock["InTypes"]), len(self.m_oDictBlock["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO-1)* 5 ) #espacamento entre ports = 5 +(self.m_nRadius*2 ) #tirando a margem superior e inferior +(t_nMaxIO * self.m_nInputHeight),#adicionando a altura de cada port HEIGHT_DEFAULT) self.Label = self.m_oDictBlock["Label"] self.iconFile = self.m_sDataDir+self.m_oDictBlock["Icon"] self.__gobject_init__() self.wGroup = self.ParentDiagram.root().add(self,x=0,y=0) self.wGroup.connect("event", self.group_event) self.wGroup.set_flags(gtk.CAN_FOCUS) self.Build() def IsInput(self,event):#checks whether distance from any input center to the event position is less than PORT_SENSITIVITY clickedPoint = (event.x - self.wGroup.get_property('x'),event.y - self.wGroup.get_property('y')) inputPortCenters = [] if len(self.inputPortCenters) == 0: #compute portCenters if they don't exist self.ComputeInputPorts() for pointIndex in range(len(self.inputPortCenters)): if Dist(self.inputPortCenters[pointIndex],clickedPoint) < PORT_SENSITIVITY: return pointIndex return -1 def IsOutput(self,event):#checks whether distance from any input center to the event position is less than PORT_SENSITIVITY clickedPoint = (event.x - self.wGroup.get_property('x'),event.y - self.wGroup.get_property('y')) if len(self.outputPortCenters) == 0: #compute portCenters if they don't exist self.ComputeOutputPorts() for pointIndex in range(len(self.outputPortCenters)): if Dist(self.outputPortCenters[pointIndex],clickedPoint) < PORT_SENSITIVITY: return pointIndex return -1 def ComputeOutputPorts(self): for outputPort in range(len(self.m_oDictBlock["OutTypes"])): self.outputPortCenters.append((self.width-(self.m_nInputWidth/2), (self.m_nRadius # upper border + (outputPort*5) # spacing betwen ports + outputPort*self.m_nInputHeight #previous ports + self.m_nInputHeight/2)))#going to the port's center def ComputeInputPorts(self): for inputPort in range(len(self.m_oDictBlock["InTypes"])): self.inputPortCenters.append((self.m_nInputWidth/2, (self.m_nRadius # upper border + (inputPort*5) # spacing betwen ports + inputPort*self.m_nInputHeight #previous ports + self.m_nInputHeight/2)))#going to the port's center def group_event(self, widget, event=None): if event.type == gtk.gdk.BUTTON_PRESS: if event.button == 1: # Remember starting position. # if event resolution got here, the diagram event resolution routine didn't matched with any ports.. so.. self.remember_x = event.x self.remember_y = event.y #Cascading event resolution: t_nInput = self.IsInput(event) if t_nInput <> -1: self.ParentDiagram.ClickedInput(self.m_nBlockCountId,t_nInput) return True else: t_nOutput = self.IsOutput(event) if t_nOutput <> -1: self.ParentDiagram.ClickedOutput(self.m_nBlockCountId,t_nOutput) return True else: self.wGroup.grab_focus() self.UpdateFocus() #self.SetFocusedState(True) #print("onBlock(" + str(event.x - self.wGroup.get_property('x')) + "," + str(event.y - self.wGroup.get_property('y')) + ")") #print("Since this event does nothing, we should warn GcDiagram that any current opperations were aborted! or just return False!") #self.ParentDiagram.AbortConnection() return False return False elif event.button == 3: print "right button at block" self.RightClick(event) return True #explicitly returns true so that diagram won't catch this event elif event.type == gtk.gdk.MOTION_NOTIFY: if event.state & gtk.gdk.BUTTON1_MASK: if self.ParentDiagram.m_oCurrConnector == None: if(widget == self.wGroup):#make sure we're not moving somebody else! # Get the new position and move by the difference new_x = event.x new_y = event.y widget.move(new_x - self.remember_x, new_y - self.remember_y) self.ParentDiagram.UpdateScrolling() self.remember_x = new_x self.remember_y = new_y return False elif event.type == gtk.gdk._2BUTTON_PRESS: GcdBlockMenu(self, event) return True elif event.type == gtk.gdk.ENTER_NOTIFY: # Make the outline wide. self.MouseOverState(True) return False #pode propagar p/ cima elif event.type == gtk.gdk.LEAVE_NOTIFY: # Make the outline thin. if not self.m_bFocus: self.MouseOverState(False) return False #pode passar p/ cima def __del__(self): print "GC: deleting GcdBlock:",self.m_nBlockCountId def _BbRect(self): p = [] m_oArc0 = MakeArc(radius=self.m_nRadius, edges=5, q=0) m_oArc1 = MakeArc(radius=self.m_nRadius, edges=5, q=1) m_oArc2 = MakeArc(radius=self.m_nRadius, edges=5, q=2) m_oArc3 = MakeArc(radius=self.m_nRadius, edges=5, q=3) pf = [] #cw #linha superior.. p/ referencia pf.append((self.m_nRadius,0)) pf.append((self.width-self.m_nRadius,0)) pf.extend(AlterArc(m_oArc3,self.width-self.m_nRadius,self.m_nRadius))##canto superior direito pf.extend(AlterArc(m_oArc0,self.width-self.m_nRadius,self.height-self.m_nRadius))##canto inferior direito pf.extend(AlterArc(m_oArc1,self.m_nRadius,self.height-self.m_nRadius))##canto inferior esquerdo pf.extend(AlterArc(m_oArc2,self.m_nRadius,self.m_nRadius))##canto superior esquerdo p = [] #takes a list of points(tuples)(pf) to produce a list of points in form [x1,y1,x2,y2,x3,y3....,xn,yn] (p) for n in pf: for e in n: p.append(e) #print self.m_oDictBlock["Color"].split(":") self.SetBackColor() w1 = self.wGroup.add(gnomecanvas.CanvasPolygon, points=p,# y1=y1, x2=x2, y2=y2, fill_color_rgba=ColorFromList(self.m_oBackColor), outline_color='black', width_units=1.0) #w1.set(dash=[1.0, 1, [0.1,0.1]])#set_dash( 1.0,(5.0,0.1) ) self.widgets["Rect"] = w1 def _BIcon(self): pb = gtk.gdk.pixbuf_new_from_file(self.m_sDataDir+self.m_oDictBlock["Icon"]) icon = self.wGroup.add(gnomecanvas.CanvasPixbuf, pixbuf=pb, x=(self.width/2), y=(self.height/2), anchor=gtk.ANCHOR_CENTER) self.widgets["pb"] = icon def _BInputs(self): inPWids = [] for x in range(len(self.m_oDictBlock["InTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file(self.m_sDataDir+s2idirectory.typeIconsIn[self.m_oDictBlock["InTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file(self.m_sDataDir+s2idirectory.icons["IconInput"]) t_Wid = self.wGroup.add(gnomecanvas.CanvasPixbuf, pixbuf=pb,x=0,y=(self.m_nRadius # upper border + (x*5) # spacing betwen ports + x*self.m_nInputHeight), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) inPWids.append(t_Wid) self.widgets["Inputs"] = inPWids def _BOutputs(self): outPWids = [] for x in range(len(self.m_oDictBlock["OutTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file(self.m_sDataDir+s2idirectory.typeIconsOut[self.m_oDictBlock["OutTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file(self.m_sDataDir+s2idirectory.icons["IconOutput"]) t_Wid = self.wGroup.add(gnomecanvas.CanvasPixbuf, pixbuf=pb,x=(self.width-self.m_nOutputWidth),y=(self.m_nRadius # upper border + (x*5) # spacing betwen ports + x*self.m_nOutputHeight), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) outPWids.append(t_Wid) self.widgets["Outputs"] = outPWids def _BLabels(self): label = self.wGroup.add(gnomecanvas.CanvasText, text=self.m_oDictBlock["Label"], fill_color='black', anchor=gtk.ANCHOR_CENTER, weight=pango.WEIGHT_BOLD, size_points=9, x=(self.width/2), y=(self.height-10)) self.TextWidth = label.get_property('text-width') oldX,oldY = ((self.width/2),(self.height-10)) self.width = max(self.TextWidth+WIDTH_2_TEXT_OFFSET,self.width) label.move((self.width/2)-oldX, (self.height-10)-oldY) self.widgets["Label"] = label def Build(self): self._BLabels()#must be called in this order! otherwise the box rect won't have the propper width self._BbRect() self._BInputs() self._BOutputs() self._BIcon() self.UpdateFlow() self.UpdateFlowDisplay() def UpdateFlow(self,a_bCheckTimeShifter=False): if self.m_bIsSource or (self.m_bTimeShifts and (not a_bCheckTimeShifter)):# #if all in connectors have flow #print "Block ",self.Label," id(",self.m_nBlockCountId,") has flow" self.m_bHasFlow = True else: sourceConnectors = self.ParentDiagram.GetConnectorsTo(self.m_nBlockCountId) if len(sourceConnectors) <> len(self.m_oDictBlock["InTypes"]): #print "Block ",self.Label," id(",self.m_nBlockCountId,") doesnt has flow" self.m_bHasFlow = False else: for connIdx in reversed(range(len(sourceConnectors))): if sourceConnectors[connIdx].m_bHasFlow: sourceConnectors.pop(connIdx) if len(sourceConnectors) <> 0: #print "Block ",self.Label," id(",self.m_nBlockCountId,") doesnt has flow" self.m_bHasFlow = False else: #print "Block ",self.Label," id(",self.m_nBlockCountId,") has flow" self.m_bHasFlow = True return self.m_bHasFlow def ClickedInput(self, a_nInput): print "Input(" + str(a_nInput) + ")" def ClickedOutput(self, a_nOutput): print "Output(" + str(a_nOutput) + ")" def GetInputPos(self, a_nInputID): if len(self.inputPortCenters) == 0: #compute portCenters if they don't exist self.ComputeInputPorts() i_x,i_y = 0+self.wGroup.get_property('x'),self.inputPortCenters[a_nInputID][1]+self.wGroup.get_property('y')#x=0, y=yc wPoint = self.i2w(i_x,i_y) return (wPoint[0],wPoint[1]) def GetOutputPos(self, a_nOutputID): if len(self.outputPortCenters) == 0: #compute portCenters if they don't exist self.ComputeOutputPorts() o_x,o_y = self.width+self.wGroup.get_property('x'),self.outputPortCenters[a_nOutputID][1]+self.wGroup.get_property('y')#x=0, y=yc wPoint = self.i2w(o_x,o_y) return (wPoint[0],wPoint[1]) def GetBlockPos(self): return (self.wGroup.get_property('x'),self.wGroup.get_property('y')) def UpdateFocus(self): if self.ParentDiagram.get_property('focused-item') == self.wGroup: self.MouseOverState(True) self.m_bFocus = True else: self.MouseOverState(False) self.m_bFocus = False def UpdateFlowDisplay(self): t_oFocusCorrectedColor = [self.m_oBackColor[0],self.m_oBackColor[1], self.m_oBackColor[2],self.m_oBackColor[3]] if self.m_bHasFlow: t_oFocusCorrectedColor[3] = self.m_oBackColor[3] #with focus: original colors self.widgets["Rect"].set(outline_color='black',fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) else: t_oFocusCorrectedColor[3] = 50 #without focus the block background will be much more transparent self.widgets["Rect"].set(outline_color='red',fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) def MouseOverState(self, a_bState): if a_bState: self.widgets["Rect"].set(width_units=3) else: self.widgets["Rect"].set(width_units=1) def RightClick(self, a_oEvent): GcdBlockMenu(self, a_oEvent) def GetState(self): return self.m_bHasFlow def SetPropertiesXML_nID( self, a_oPropertiesXML ): #myBlockId = self.m_oPropertiesXML.properties.block.id #storing this block's Block.Id myBlockId = self.m_oPropertiesXML.getTag("properties").getTag("block").getAttr("id") #storing this block's Block.Id self.m_oPropertiesXML = copy.deepcopy(a_oPropertiesXML) #self.m_oPropertiesXML.properties.block.id = myBlockId #restoring block.Id self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",myBlockId) def GetBorderColor(self,*args): return self.m_oBorderColor def GetBackColor(self,*args): return self.m_oBackColor def SetBackColor( self, a_nColors=None ):#RGBA if a_nColors == None: a_nColors = self.m_oDictBlock["Color"].split(":") t_nRed = int(a_nColors[0]) t_nGreen = int(a_nColors[1]) t_nBlue = int(a_nColors[2]) t_nAlpha = int(a_nColors[3]) self.m_oBackColor = [t_nRed, t_nGreen, t_nBlue, t_nAlpha] if self.widgets.has_key("Rect"): #rect already drawn self.widgets["Rect"].set(fill_color_rgba=ColorFromList(self.m_oBackColor)) def Move(self, x, y): self.wGroup.move(x,y) def Redraw(self): self.wGroup.move(0,0) def SetBorderColor(self, a_nColor=None): print "SetBorderColor is deprecated, fix this" self.m_oBackColor = a_nColor def ToggleState(self,*args): print "ToggleState is deprecated, fix this" def GetPropertiesXML(self): return self.m_oPropertiesXML def SetPropertiesXML(self, outerProps): self.m_oPropertiesXML = outerProps def GetId(self): return self.m_nBlockCountId def GetType(self): return self.m_nBlockType def GetPos(self): return self.wGroup.get_property('x'),self.wGroup.get_property('y')
def Load(self, a_sFilename=None): if a_sFilename <> None: self.SetFilename(a_sFilename) else: if self.m_sFilename == None: self.m_sFilename = "Cannot Load without filename" return False # reseting present diagram.. self.m_oBlocks, self.m_oConnectors, self.m_oCurrConnector, self.m_nSessionId = {}, [], None, 0 # this two must be updated at each block/conn insertion self.m_nBlockCountId = 1 # since block counts are kept, render this from the saved file self.m_nConnectorCountId = 1 # since connector Ids are generated from scratch, just reset it #t_oLoad = bt.bind_file(self.m_sFilename) # binding saved project #print t_oLoad.xml() t_oLoad = XMLParser(self.m_sFilename) # loading blocks on canvas #GcState_root = t_oLoad.getTagChild("harpia", "GcState") #blocks = t_oLoad.getChildTags(GcState_root, "block") blocks = t_oLoad.getTag("harpia").getTag("GcState").getChildTags("block") #for block in t_oLoad.harpia.GcState.block: for block in blocks: #block_id = t_oLoad.getTagAttr(block, "id") #block_type = t_oLoad.getTagAttr(block, "type") block_id = block.getAttr("id") block_type = block.getAttr("type") position = block.getTag("position") x = position.getAttr("x") y = position.getAttr("y") #self.InsertBlockPosId(int(block.type), float(block.position.x), float(block.position.y), int(block.id)) #self.m_nBlockCountId = max(self.m_nBlockCountId, int(block.id)) self.InsertBlockPosId(int(block_type), float(x), float(y), int(block_id)) self.m_nBlockCountId = max(self.m_nBlockCountId, int(block_id)) self.m_nBlockCountId += 1 blocks = t_oLoad.getTag("harpia").getTag("network").getChildTags("block") # loading connectors on canvas try: #for block in t_oLoad.harpia.network.block: for block in blocks: block_id = block.getAttr("id") outputs = block.getTag("outputs") #for connector in block.outputs.output: for connector in outputs.getChildTags("output"): conn_input = connector.getAttr("input") conn_inblock = connector.getAttr("inBlock") conn_id = connector.getAttr("id") print conn_input, conn_inblock, conn_id #if connector.inBlock <> "--" and connector.input <> "--": if conn_inblock <> "--" and conn_input <> "--": #self.InsertReadyConnector(int(block.id), (int(connector.id) - 1), int(connector.inBlock), #(int(connector.input) - 1)) self.InsertReadyConnector(int(block_id), (int(conn_id) - 1), int(conn_inblock), (int(conn_input) - 1)) # this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14) except AttributeError: pass # loading properties blocks = t_oLoad.getTag("harpia").getTag("properties").getChildTags("block") for block in blocks: block_xml = str(block) block_id = block.getAttr("id") #t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block.xml() + '\n</properties>\n' t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block_xml + '\n</properties>\n' #self.m_oBlocks[int(block.id)].SetPropertiesXML(bt.bind_string(t_sBlockProperties)) self.m_oBlocks[int(block_id)].SetPropertiesXML(XMLParser(t_sBlockProperties, fromString=True)) self.UpdateScrolling() self.GotoScrolling(0, 0); return True
def load(self, file_name=None): if file_name != None: self.diagram.set_file_name(file_name) else: if self.diagram.file_name == None: self.diagram.file_name = "Cannot Load without filename" return False # reseting present diagram.. self.diagram.blocks = {} self.diagram.connectors = [] self.diagram.curr_connector = None self.diagram.session_id = 0 # this two must be updated at each block/conn insertion self.diagram.block_id = 1 # since block counts are kept, render this from the saved file self.diagram.connector_id = 1 # since connector Ids are generated from scratch, just reset it t_oLoad = XMLParser(self.diagram.file_name) blocks = t_oLoad.getTag("harpia").getTag("GcState").getChildTags("block") #for block in t_oLoad.harpia.GcState.block: for block in blocks: block_id = block.getAttr("id") block_type = block.getAttr("type") position = block.getTag("position") x = position.getAttr("x") y = position.getAttr("y") self.diagram.insert_blockPosId(int(block_type), float(x), float(y), int(block_id)) self.diagram.block_id = max(self.diagram.block_id, int(block_id)) self.diagram.block_id += 1 blocks = t_oLoad.getTag("harpia").getTag("network").getChildTags("block") # loading connectors on canvas try: #for block in t_oLoad.harpia.network.block: for block in blocks: block_id = block.getAttr("id") outputs = block.getTag("outputs") #for connector in block.outputs.output: for connector in outputs.getChildTags("output"): conn_input = connector.getAttr("input") conn_inblock = connector.getAttr("inBlock") conn_id = connector.getAttr("id") print conn_input, conn_inblock, conn_id if conn_inblock != "--" and conn_input != "--": #(int(connector.input) - 1)) self.diagram.insert_ready_connector( int(block_id), (int(conn_id) - 1), int(conn_inblock), (int(conn_input) - 1)) except AttributeError: pass # loading properties blocks = t_oLoad.getTag("harpia").getTag("properties").getChildTags("block") for block in blocks: block_xml = str(block) block_id = block.getAttr("id") t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block_xml + '\n</properties>\n' self.diagram.blocks[int(block_id)].SetPropertiesXML(XMLParser(t_sBlockProperties, fromString=True)) self.diagram.update_scrolling() self.diagram.goto_scrolling(0, 0) return True
class GcdBlock(gnomecanvas.CanvasGroup): def __init__(self, diagram, block_type, block_id=1): self.block_type = block_type self.diagram = diagram self.data_dir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(block_type): self.block_description = s2idirectory.block[block_type] else: self.block_description = s2idirectory.block[0] print "Bad block type.. assuming 00" self.block_id = block_id self.widgets = {} self.focus = False self.has_flow = False self.m_bTimeShifts = False self.m_bIsSource = False if self.block_description.has_key("IsSource"): #all data sources self.m_bIsSource = self.block_description["IsSource"] if self.block_description.has_key("TimeShifts"): #delay block self.m_bTimeShifts = self.block_description["TimeShifts"] self.m_oPropertiesXML = XMLParser( self.data_dir + str(self.block_description["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr( "id", str(self.block_id)) self.m_oBorderColor = [0, 0, 0, 255] self.m_oBackColor = [0, 0, 0, 150] self.input_port_centers = [] self.output_port_centers = [] self.width = WIDTH_DEFAULT t_nMaxIO = max(len(self.block_description["InTypes"]), len(self.block_description["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO - 1) * 5) #espacamento entre ports = 5 + (RADIUS * 2) #tirando a margem superior e inferior + (t_nMaxIO * INPUT_HEIGHT), #adicionando a altura de cada port HEIGHT_DEFAULT) self.__gobject_init__() self.group = self.diagram.root().add(self, x=0, y=0) self.group.connect("event", self.__group_event) self.group.set_flags(gtk.CAN_FOCUS) self.build() def __is_input(self, event): clicked_point = (event.x - self.group.get_property('x'), event.y - self.group.get_property('y')) input_port_centers = [] #compute portCenters if they don't exist if len(self.input_port_centers) == 0: self.__compute_input_ports() for point_index in range(len(self.input_port_centers)): if Dist(self.input_port_centers[point_index], clicked_point) < PORT_SENSITIVITY: return point_index return -1 def __is_output(self, event): clicked_point = (event.x - self.group.get_property('x'), event.y - self.group.get_property('y')) if len(self.output_port_centers ) == 0: #compute portCenters if they don't exist self.__compute_output_ports() for point_index in range(len(self.output_port_centers)): if Dist(self.output_port_centers[point_index], clicked_point) < PORT_SENSITIVITY: return point_index return -1 def __compute_output_ports(self): for outputPort in range(len(self.block_description["OutTypes"])): self.output_port_centers.append(( self.width - (INPUT_WIDTH / 2), ( RADIUS # upper border + (outputPort * 5) # spacing betwen ports + outputPort * INPUT_HEIGHT #previous ports + INPUT_HEIGHT / 2))) #going to the port's center def __compute_input_ports(self): for inputPort in range(len(self.block_description["InTypes"])): self.input_port_centers.append(( INPUT_WIDTH / 2, ( RADIUS # upper border + (inputPort * 5) # spacing betwen ports + inputPort * INPUT_HEIGHT #previous ports + INPUT_HEIGHT / 2))) #going to the port's center def __group_event(self, widget, event=None): if event.type == gtk.gdk.BUTTON_PRESS: if event.button == 1: # Remember starting position. # if event resolution got here, the diagram event resolution routine didn't matched with any ports.. so.. self.remember_x = event.x self.remember_y = event.y #Cascading event resolution: input_event = self.__is_input(event) if input_event != -1: self.diagram.ClickedInput(self.block_id, input_event) return True else: output_event = self.__is_output(event) if output_event != -1: self.diagram.ClickedOutput(self.block_id, output_event) return True else: self.group.grab_focus() self.update_focus() return False return False elif event.button == 3: self.__right_click(event) return True #explicitly returns true so that diagram won't catch this event elif event.type == gtk.gdk.MOTION_NOTIFY: if event.state & gtk.gdk.BUTTON1_MASK: if self.diagram.curr_connector == None: if (widget == self.group ): #make sure we're not moving somebody else! # Get the new position and move by the difference new_x = event.x new_y = event.y widget.move(new_x - self.remember_x, new_y - self.remember_y) self.diagram.UpdateScrolling() self.remember_x = new_x self.remember_y = new_y return False elif event.type == gtk.gdk._2BUTTON_PRESS: GcdBlockMenu(self, event) return True elif event.type == gtk.gdk.ENTER_NOTIFY: # Make the outline wide. self.__mouse_over_state(True) return False #pode propagar p/ cima elif event.type == gtk.gdk.LEAVE_NOTIFY: # Make the outline thin. if not self.focus: self.__mouse_over_state(False) return False #pode passar p/ cima def __del__(self): print "GC: deleting GcdBlock:", self.block_id def _BbRect(self): p = [] arc0 = MakeArc(radius=RADIUS, edges=5, q=0) arc1 = MakeArc(radius=RADIUS, edges=5, q=1) arc2 = MakeArc(radius=RADIUS, edges=5, q=2) arc3 = MakeArc(radius=RADIUS, edges=5, q=3) pf = [] #cw #linha superior.. p/ referencia pf.append((RADIUS, 0)) pf.append((self.width - RADIUS, 0)) pf.extend(AlterArc(arc3, self.width - RADIUS, RADIUS)) ##canto superior direito pf.extend(AlterArc(arc0, self.width - RADIUS, self.height - RADIUS)) ##canto inferior direito pf.extend(AlterArc(arc1, RADIUS, self.height - RADIUS)) ##canto inferior esquerdo pf.extend(AlterArc(arc2, RADIUS, RADIUS)) ##canto superior esquerdo p = [] #takes a list of points(tuples)(pf) to produce a list of points in form [x1,y1,x2,y2,x3,y3....,xn,yn] (p) for n in pf: for e in n: p.append(e) self.SetBackColor() w1 = self.group.add( gnomecanvas.CanvasPolygon, points=p, # y1=y1, x2=x2, y2=y2, fill_color_rgba=ColorFromList(self.m_oBackColor), outline_color='black', width_units=1.0) self.widgets["Rect"] = w1 def _BIcon(self): pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + self.block_description["Icon"]) icon = self.group.add(gnomecanvas.CanvasPixbuf, pixbuf=pb, x=(self.width / 2), y=(self.height / 2), anchor=gtk.ANCHOR_CENTER) self.widgets["pb"] = icon def _BInputs(self): inPWids = [] for x in range(len(self.block_description["InTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file( self.data_dir + s2idirectory.typeIconsIn[ self.block_description["InTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file( self.data_dir + s2idirectory.icons["IconInput"]) t_Wid = self.group.add( gnomecanvas.CanvasPixbuf, pixbuf=pb, x=0, y=( RADIUS # upper border + (x * 5) # spacing betwen ports + x * INPUT_HEIGHT), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) inPWids.append(t_Wid) self.widgets["Inputs"] = inPWids def _BOutputs(self): outPWids = [] for x in range(len(self.block_description["OutTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file( self.data_dir + s2idirectory.typeIconsOut[ self.block_description["OutTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file( self.data_dir + s2idirectory.icons["IconOutput"]) t_Wid = self.group.add( gnomecanvas.CanvasPixbuf, pixbuf=pb, x=(self.width - OUTPUT_WIDTH), y=( RADIUS # upper border + (x * 5) # spacing betwen ports + x * OUTPUT_HEIGHT), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) outPWids.append(t_Wid) self.widgets["Outputs"] = outPWids def _BLabels(self): label = self.group.add(gnomecanvas.CanvasText, text=self.block_description["Label"], fill_color='black', anchor=gtk.ANCHOR_CENTER, weight=pango.WEIGHT_BOLD, size_points=9, x=(self.width / 2), y=(self.height - 10)) text_width = label.get_property('text-width') oldX, oldY = ((self.width / 2), (self.height - 10)) self.width = max(text_width + WIDTH_2_TEXT_OFFSET, self.width) label.move((self.width / 2) - oldX, (self.height - 10) - oldY) self.widgets["Label"] = label def build(self): self._BLabels( ) #must be called in this order! otherwise the box rect won't have the propper width self._BbRect() self._BInputs() self._BOutputs() self._BIcon() self.update_flow() self.__update_flow_display() def update_flow(self, a_bCheckTimeShifter=False): if self.m_bIsSource or (self.m_bTimeShifts and (not a_bCheckTimeShifter)): # #if all in connectors have flow self.has_flow = True else: sourceConnectors = self.diagram.GetConnectorsTo(self.block_id) if len(sourceConnectors) != len(self.block_description["InTypes"]): self.has_flow = False else: for connIdx in reversed(range(len(sourceConnectors))): if sourceConnectors[connIdx].has_flow: sourceConnectors.pop(connIdx) if len(sourceConnectors) != 0: self.has_flow = False else: self.has_flow = True self.__update_flow_display() return self.has_flow def __update_flow_display(self): t_oFocusCorrectedColor = [ self.m_oBackColor[0], self.m_oBackColor[1], self.m_oBackColor[2], self.m_oBackColor[3] ] if self.has_flow: #with focus: original colors t_oFocusCorrectedColor[3] = self.m_oBackColor[3] self.widgets["Rect"].set( outline_color='black', fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) else: #without focus the block background will be much more transparent t_oFocusCorrectedColor[3] = 50 self.widgets["Rect"].set( outline_color='red', fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) def get_input_pos(self, a_nInputID): if len(self.input_port_centers ) == 0: #compute portCenters if they don't exist self.__compute_input_ports() x = 0 + self.group.get_property('x') y = self.input_port_centers[a_nInputID][1] + self.group.get_property( 'y') point = self.i2w(x, y) return (point[0], point[1]) def get_output_pos(self, output_id): #compute portCenters if they don't exist if len(self.output_port_centers) == 0: self.__compute_output_ports() x = self.width + self.group.get_property('x') y = self.output_port_centers[output_id][1] + self.group.get_property( 'y') point = self.i2w(x, y) return (point[0], point[1]) def get_block_pos(self): return (self.group.get_property('x'), self.group.get_property('y')) def update_focus(self): if self.diagram.get_property('focused-item') == self.group: self.__mouse_over_state(True) self.focus = True else: self.__mouse_over_state(False) self.focus = False def __mouse_over_state(self, state): if state: self.widgets["Rect"].set(width_units=3) else: self.widgets["Rect"].set(width_units=1) def __right_click(self, a_oEvent): GcdBlockMenu(self, a_oEvent) def get_state(self): return self.has_flow def SetPropertiesXML_nID(self, a_oPropertiesXML): myBlockId = self.m_oPropertiesXML.getTag("properties").getTag( "block").getAttr("id") #storing this block's Block.Id self.m_oPropertiesXML = copy.deepcopy(a_oPropertiesXML) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr( "id", myBlockId) def GetBorderColor(self, *args): return self.m_oBorderColor def GetBackColor(self, *args): return self.m_oBackColor def SetBackColor(self, a_nColors=None): #RGBA if a_nColors == None: a_nColors = self.block_description["Color"].split(":") t_nRed = int(a_nColors[0]) t_nGreen = int(a_nColors[1]) t_nBlue = int(a_nColors[2]) t_nAlpha = int(a_nColors[3]) self.m_oBackColor = [t_nRed, t_nGreen, t_nBlue, t_nAlpha] if self.widgets.has_key("Rect"): #rect already drawn self.widgets["Rect"].set( fill_color_rgba=ColorFromList(self.m_oBackColor)) def move(self, x, y): self.group.move(x, y) def redraw(self): self.group.move(0, 0) def SetBorderColor(self, a_nColor=None): print "SetBorderColor is deprecated, fix this" self.m_oBackColor = a_nColor def GetPropertiesXML(self): return self.m_oPropertiesXML def SetPropertiesXML(self, outerProps): self.m_oPropertiesXML = outerProps def get_id(self): return self.block_id def get_type(self): return self.block_type def get_position(self): return self.group.get_property('x'), self.group.get_property('y')
class TipOfTheDay(gtk.MessageDialog): # , Observable): OBS_TIP = 0 OBS_TOGGLED = 1 def __init__(self): self.confFile = None self.confFilePath = "~/.harpiaConf.xml" self.confFile = None; self.showTips = True self.avTips = {} self.nOfOkTips = -1 self.__index = 0 self.__loadConfFile() self.__index = self.__getTipFromConf() if self.__index == -1: self.showTips = False return gtk.MessageDialog.__init__(self, None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, "Harpia") self.set_title(_("Tip of the Day")) self.connect("response", self.__on_closeBtn) self.__label = self.vbox.get_children()[ 0].get_children()[1] # HACK HACK HACK -- make it work with # gtk+-2.6.x if (not isinstance(self.__label, gtk.Label)): self.__label.remove(self.__label.get_children()[1]) self.__label = self.__label.get_children()[0] self.__checkbox = gtk.CheckButton( _("Show tips at startup")) self.__checkbox.set_active(True) self.__checkbox.connect( "toggled", self.__on_toggleAll) self.__checkbox.show() self.vbox.pack_end(self.__checkbox, 0, 0, 0) self.__thcheckbox = gtk.CheckButton( _("Never Show This Tip Again")) self.__thcheckbox.set_active(False) self.__thcheckbox.connect( "toggled", self.__on_toggleThis) self.__thcheckbox.show() self.vbox.pack_end(self.__thcheckbox, 0, 0, 0) self.btn_prev = gtk.Button( stock=gtk.STOCK_GO_BACK) self.btn_prev.connect("clicked", self.prev_tip) self.btn_prev.show() self.btn_next = gtk.Button( stock=gtk.STOCK_GO_FORWARD) self.btn_next.connect("clicked", self.next_tip) self.btn_next.show() btn_close = gtk.Button(stock=gtk.STOCK_CLOSE) btn_close.connect("clicked", self.__on_close) btn_close.show() self.action_area.add(self.btn_prev) self.action_area.add(self.btn_next) self.action_area.add(btn_close) # make the close button the default button btn_close.set_flags(gtk.CAN_DEFAULT) self.set_default(btn_close) self.set_focus(btn_close) self.__show_currTip() def run(self): if self.showTips: gtk.MessageDialog.run(self) def __show_currTip(self): self.__boundIndex2Dict() self.__getNofTips() self.__label.set_markup(_(TIPS[self.__index]).strip()) self.__thcheckbox.set_active( not self.avTips[self.__index]) self.__checkbox.set_active(self.showTips) if self.nOfOkTips <= 1: self.btn_next.set_sensitive(False) self.btn_prev.set_sensitive(False) def __on_close(self, src): self.__saveConfFile() self.hide() def __on_closeBtn(self, dialog, response): self.__saveConfFile() self.hide() def __boundIndex2Dict(self): if (self.__index >= len(TIPS)): self.__index = 0 if (self.__index < 0): self.__index = len(TIPS) - 1 def __getNofTips(self): self.nOfOkTips = 0 for tipInstance in self.avTips.keys(): if self.avTips[tipInstance]: self.nOfOkTips += 1 def __on_toggleThis(self, src): value = src.get_active() self.avTips[self.__index] = not value # self.__getNofTips() # self.update_observer(self.OBS_TOGGLED, value) def __on_toggleAll(self, src): value = src.get_active() self.showTips = value # self.update_observer(self.OBS_TOGGLED, value) def next_tip(self, *args): self.__index += 1 self.__boundIndex2Dict() while(not self.avTips[self.__index]): self.__index += 1 self.__boundIndex2Dict() self.__show_currTip() def prev_tip(self, *args): self.__index -= 1 self.__boundIndex2Dict() while(not self.avTips[self.__index]): self.__index -= 1 self.__boundIndex2Dict() self.__show_currTip() def __getTipFromConf(self): okTipList = [] for tipInstance in self.avTips.keys(): if self.avTips[tipInstance]: print tipInstance okTipList.append(tipInstance) if(len(okTipList) == 0): randTipId = -1 else: # next tip in the list randTipId = okTipList[0] return randTipId def __loadConfFile(self): if(not os.path.exists(os.path.expanduser(self.confFilePath))): self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) tipsOfTheDay = self.confFile.getTag("tipsOfTheDay") tips_ver = tipsOfTheDay.getAttr("version") if tips_ver != TIPS_VER: self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) show_tips = tipsOfTheDay.getAttr("show") if show_tips == "True": for tip in tipsOfTheDay.getChildTags("tip"): self.avTips[int(tip.getAttr("id"))]=(tip.getAttr("enabled") == "True") print self.avTips def __saveConfFile(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":str(self.showTips), "version":TIPS_VER}) for tipInstance in self.avTips.keys(): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":self.avTips[tipInstance], "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close() def GenerateBlankConf(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":"True", "version":TIPS_VER}) for tipInstance in range(len(TIPS)): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":"True", "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close()
class GcdBlock( gnomecanvas.CanvasGroup): #---------------------------------------------------------------------- def __init__( self, diagram, block_type, block_id=1): self.block_type = block_type self.diagram = diagram self.data_dir = os.environ['HARPIA_DATA_DIR'] if s2idirectory.block.has_key(block_type): self.block_description = s2idirectory.block[block_type] else: self.block_description = s2idirectory.block[0] print "Bad block type.. assuming 00" self.block_id = block_id self.widgets = {} self.focus = False self.has_flow = False self.time_shifts = False self.is_source = False if self.block_description.has_key("IsSource"): #all data sources self.is_source = self.block_description["IsSource"] if self.block_description.has_key("TimeShifts"): #delay block self.time_shifts = self.block_description["TimeShifts"] self.m_oPropertiesXML = XMLParser(self.data_dir + str(self.block_description["Path"]["Xml"])) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",str(self.block_id)) self.m_oBorderColor = [ 0, 0, 0, 255 ] self.m_oBackColor = [0,0,0,150] self.input_port_centers = [] self.output_port_centers = [] self.width = WIDTH_DEFAULT t_nMaxIO = max(len(self.block_description["InTypes"]), len(self.block_description["OutTypes"])) ## Generates the block size, based on the number of inputs,outputs # Comment block is too small... if not t_nMaxIO: t_nMaxIO = 1 self.height = max( ((t_nMaxIO-1)* 5 ) #espacamento entre ports = 5 +(RADIUS*2 ) #tirando a margem superior e inferior +(t_nMaxIO * INPUT_HEIGHT),#adicionando a altura de cada port HEIGHT_DEFAULT) self.__gobject_init__() self.group = self.diagram.root().add(self,x=0,y=0) self.group.connect("event", self.__group_event) self.group.set_flags(gtk.CAN_FOCUS) self.build() #---------------------------------------------------------------------- def __is_input(self,event): clicked_point = (event.x - self.group.get_property('x'), event.y - self.group.get_property('y')) input_port_centers = [] #compute portCenters if they don't exist if len(self.input_port_centers) == 0: self.__compute_input_ports() for point_index in range(len(self.input_port_centers)): if Dist(self.input_port_centers[point_index],clicked_point) < PORT_SENSITIVITY: return point_index return -1 #---------------------------------------------------------------------- def __is_output(self,event): clicked_point = (event.x - self.group.get_property('x'), event.y - self.group.get_property('y')) if len(self.output_port_centers) == 0: #compute portCenters if they don't exist self.__compute_output_ports() for point_index in range(len(self.output_port_centers)): if Dist(self.output_port_centers[point_index],clicked_point) < PORT_SENSITIVITY: return point_index return -1 #---------------------------------------------------------------------- def __compute_output_ports(self): for outputPort in range(len(self.block_description["OutTypes"])): self.output_port_centers.append((self.width-(INPUT_WIDTH/2), (RADIUS # upper border + (outputPort*5) # spacing betwen ports + outputPort*INPUT_HEIGHT #previous ports + INPUT_HEIGHT/2)))#going to the port's center #---------------------------------------------------------------------- def __compute_input_ports(self): for inputPort in range(len(self.block_description["InTypes"])): self.input_port_centers.append((INPUT_WIDTH/2, (RADIUS # upper border + (inputPort*5) # spacing betwen ports + inputPort*INPUT_HEIGHT #previous ports + INPUT_HEIGHT/2)))#going to the port's center #---------------------------------------------------------------------- def __group_event(self, widget, event=None): if event.type == gtk.gdk.BUTTON_PRESS: if event.button == 1: # Remember starting position. # if event resolution got here, the diagram event resolution routine didn't matched with any ports.. so.. self.remember_x = event.x self.remember_y = event.y #Cascading event resolution: input_event = self.__is_input(event) if input_event != -1: self.diagram.clicked_input(self.block_id,input_event) return True else: output_event = self.__is_output(event) if output_event != -1: self.diagram.clicked_output(self.block_id,output_event) return True else: self.group.grab_focus() self.update_focus() return False return False elif event.button == 3: self.__right_click(event) return True #explicitly returns true so that diagram won't catch this event elif event.type == gtk.gdk.MOTION_NOTIFY: if event.state & gtk.gdk.BUTTON1_MASK: if self.diagram.curr_connector == None: if(widget == self.group):#make sure we're not moving somebody else! # Get the new position and move by the difference new_x = event.x new_y = event.y widget.move(new_x - self.remember_x, new_y - self.remember_y) self.diagram.update_scrolling() self.remember_x = new_x self.remember_y = new_y return False elif event.type == gtk.gdk._2BUTTON_PRESS: GcdBlockMenu(self, event) return True elif event.type == gtk.gdk.ENTER_NOTIFY: # Make the outline wide. self.__mouse_over_state(True) return False #pode propagar p/ cima elif event.type == gtk.gdk.LEAVE_NOTIFY: # Make the outline thin. if not self.focus: self.__mouse_over_state(False) return False #pode passar p/ cima #---------------------------------------------------------------------- def __del__(self): print "GC: deleting GcdBlock:",self.block_id #---------------------------------------------------------------------- def _BbRect(self): p = [] arc0 = MakeArc(radius=RADIUS, edges=5, q=0) arc1 = MakeArc(radius=RADIUS, edges=5, q=1) arc2 = MakeArc(radius=RADIUS, edges=5, q=2) arc3 = MakeArc(radius=RADIUS, edges=5, q=3) pf = [] #cw #linha superior.. p/ referencia pf.append((RADIUS,0)) pf.append((self.width-RADIUS,0)) pf.extend(AlterArc(arc3,self.width-RADIUS,RADIUS))##canto superior direito pf.extend(AlterArc(arc0,self.width-RADIUS,self.height-RADIUS))##canto inferior direito pf.extend(AlterArc(arc1,RADIUS,self.height-RADIUS))##canto inferior esquerdo pf.extend(AlterArc(arc2,RADIUS,RADIUS))##canto superior esquerdo p = [] #takes a list of points(tuples)(pf) to produce a list of points in form [x1,y1,x2,y2,x3,y3....,xn,yn] (p) for n in pf: for e in n: p.append(e) self.SetBackColor() w1 = self.group.add(gnomecanvas.CanvasPolygon, points=p,# y1=y1, x2=x2, y2=y2, fill_color_rgba=ColorFromList(self.m_oBackColor), outline_color='black', width_units=1.0) self.widgets["Rect"] = w1 #---------------------------------------------------------------------- def _BIcon(self): pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + self.block_description["Icon"]) icon = self.group.add(gnomecanvas.CanvasPixbuf, pixbuf=pb, x=(self.width/2), y=(self.height/2), anchor=gtk.ANCHOR_CENTER) self.widgets["pb"] = icon #---------------------------------------------------------------------- def _BInputs(self): inPWids = [] for x in range(len(self.block_description["InTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + s2idirectory.typeIconsIn[self.block_description["InTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + s2idirectory.icons["IconInput"]) t_Wid = self.group.add(gnomecanvas.CanvasPixbuf, pixbuf=pb,x=0,y=(RADIUS # upper border + (x*5) # spacing betwen ports + x*INPUT_HEIGHT), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) inPWids.append(t_Wid) self.widgets["Inputs"] = inPWids #---------------------------------------------------------------------- def _BOutputs(self): outPWids = [] for x in range(len(self.block_description["OutTypes"])): try: pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + s2idirectory.typeIconsOut[ self.block_description["OutTypes"][x]]) except: pb = gtk.gdk.pixbuf_new_from_file(self.data_dir + s2idirectory.icons["IconOutput"]) t_Wid = self.group.add(gnomecanvas.CanvasPixbuf, pixbuf=pb, x=(self.width-OUTPUT_WIDTH), y=(RADIUS # upper border + (x*5) # spacing betwen ports + x*OUTPUT_HEIGHT), #previous ports anchor=gtk.ANCHOR_NORTH_WEST) outPWids.append(t_Wid) self.widgets["Outputs"] = outPWids #---------------------------------------------------------------------- def _BLabels(self): label = self.group.add(gnomecanvas.CanvasText, text=self.block_description["Label"], fill_color='black', anchor=gtk.ANCHOR_CENTER, weight=pango.WEIGHT_BOLD, size_points=9, x=(self.width/2), y=(self.height-10)) text_width = label.get_property('text-width') oldX,oldY = ((self.width/2),(self.height-10)) self.width = max(text_width + WIDTH_2_TEXT_OFFSET,self.width) label.move((self.width/2)-oldX, (self.height-10)-oldY) self.widgets["Label"] = label #---------------------------------------------------------------------- def build(self): self._BLabels()#must be called in this order! otherwise the box rect won't have the propper width self._BbRect() self._BInputs() self._BOutputs() self._BIcon() self.update_flow() self.__update_flow_display() #---------------------------------------------------------------------- def update_flow(self,a_bCheckTimeShifter=False): if self.is_source or (self.time_shifts and (not a_bCheckTimeShifter)):# self.has_flow = True else: sourceConnectors = self.diagram.get_connectors_to(self.block_id) if len(sourceConnectors) != len(self.block_description["InTypes"]): self.has_flow = False else: for connIdx in reversed(range(len(sourceConnectors))): if sourceConnectors[connIdx].has_flow: sourceConnectors.pop(connIdx) if len(sourceConnectors) != 0: self.has_flow = False else: self.has_flow = True self.__update_flow_display() return self.has_flow #---------------------------------------------------------------------- def __update_flow_display(self): t_oFocusCorrectedColor = [self.m_oBackColor[0], self.m_oBackColor[1], self.m_oBackColor[2], self.m_oBackColor[3]] if self.has_flow: #with focus: original colors t_oFocusCorrectedColor[3] = self.m_oBackColor[3] self.widgets["Rect"].set(outline_color='black', fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) else: #without focus the block background will be much more transparent t_oFocusCorrectedColor[3] = 50 self.widgets["Rect"].set(outline_color='red', fill_color_rgba=ColorFromList(t_oFocusCorrectedColor)) #---------------------------------------------------------------------- def get_input_pos(self, a_nInputID): if len(self.input_port_centers) == 0: #compute portCenters if they don't exist self.__compute_input_ports() x = 0 + self.group.get_property('x') y = self.input_port_centers[a_nInputID][1]+self.group.get_property('y') point = self.i2w(x,y) return (point[0],point[1]) #---------------------------------------------------------------------- def get_output_pos(self, output_id): #compute portCenters if they don't exist if len(self.output_port_centers) == 0: self.__compute_output_ports() x = self.width + self.group.get_property('x') y = self.output_port_centers[output_id][1] + self.group.get_property('y') point = self.i2w(x,y) return (point[0],point[1]) #---------------------------------------------------------------------- def get_block_pos(self): return (self.group.get_property('x'),self.group.get_property('y')) #---------------------------------------------------------------------- def update_focus(self): if self.diagram.get_property('focused-item') == self.group: self.__mouse_over_state(True) self.focus = True else: self.__mouse_over_state(False) self.focus = False #---------------------------------------------------------------------- def __mouse_over_state(self, state): if state: self.widgets["Rect"].set(width_units=3) else: self.widgets["Rect"].set(width_units=1) #---------------------------------------------------------------------- def __right_click(self, a_oEvent): GcdBlockMenu(self, a_oEvent) #---------------------------------------------------------------------- def get_state(self): return self.has_flow #---------------------------------------------------------------------- def move(self, x, y): self.group.move(x,y) #---------------------------------------------------------------------- def redraw(self): self.group.move(0,0) #---------------------------------------------------------------------- def get_id(self): return self.block_id #---------------------------------------------------------------------- def get_type(self): return self.block_type #---------------------------------------------------------------------- def get_position(self): return self.group.get_property('x'),self.group.get_property('y') # --------------------------------------- def SetBorderColor(self, a_nColor=None): print "SetBorderColor is deprecated, fix this" self.m_oBackColor = a_nColor #---------------------------------------------------------------------- def GetPropertiesXML(self): return self.m_oPropertiesXML #---------------------------------------------------------------------- def SetPropertiesXML(self, outerProps): self.m_oPropertiesXML = outerProps #---------------------------------------------------------------------- def SetPropertiesXML_nID( self, a_oPropertiesXML ): myBlockId = self.m_oPropertiesXML.getTag("properties").getTag("block").getAttr("id") #storing this block's Block.Id self.m_oPropertiesXML = copy.deepcopy(a_oPropertiesXML) self.m_oPropertiesXML.getTag("properties").getTag("block").setAttr("id",myBlockId) #---------------------------------------------------------------------- def GetBorderColor(self,*args): return self.m_oBorderColor #---------------------------------------------------------------------- def GetBackColor(self,*args): return self.m_oBackColor #---------------------------------------------------------------------- def SetBackColor( self, a_nColors=None ):#RGBA if a_nColors == None: a_nColors = self.block_description["Color"].split(":") t_nRed = int(a_nColors[0]) t_nGreen = int(a_nColors[1]) t_nBlue = int(a_nColors[2]) t_nAlpha = int(a_nColors[3]) self.m_oBackColor = [t_nRed, t_nGreen, t_nBlue, t_nAlpha] if self.widgets.has_key("Rect"): #rect already drawn self.widgets["Rect"].set(fill_color_rgba=ColorFromList(self.m_oBackColor))
class TipOfTheDay(gtk.MessageDialog): # , Observable): OBS_TIP = 0 OBS_TOGGLED = 1 #---------------------------------------------------------------------- def __init__(self): self.confFile = None self.confFilePath = "~/.harpiaConf.xml" self.confFile = None; self.showTips = True self.avTips = {} self.nOfOkTips = -1 self.__index = 0 self.__loadConfFile() self.__index = self.__getTipFromConf() if self.__index == -1: self.showTips = False return gtk.MessageDialog.__init__(self, None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, "Harpia") self.set_title(_("Tip of the Day")) self.connect("response", self.__on_closeBtn) self.__label = self.vbox.get_children()[ 0].get_children()[1] # HACK HACK HACK -- make it work with # gtk+-2.6.x if (not isinstance(self.__label, gtk.Label)): self.__label.remove(self.__label.get_children()[1]) self.__label = self.__label.get_children()[0] self.__checkbox = gtk.CheckButton( _("Show tips at startup")) self.__checkbox.set_active(True) self.__checkbox.connect( "toggled", self.__on_toggleAll) self.__checkbox.show() self.vbox.pack_end(self.__checkbox, 0, 0, 0) self.__thcheckbox = gtk.CheckButton( _("Never Show This Tip Again")) self.__thcheckbox.set_active(False) self.__thcheckbox.connect( "toggled", self.__on_toggleThis) self.__thcheckbox.show() self.vbox.pack_end(self.__thcheckbox, 0, 0, 0) self.btn_prev = gtk.Button( stock=gtk.STOCK_GO_BACK) self.btn_prev.connect("clicked", self.prev_tip) self.btn_prev.show() self.btn_next = gtk.Button( stock=gtk.STOCK_GO_FORWARD) self.btn_next.connect("clicked", self.next_tip) self.btn_next.show() btn_close = gtk.Button(stock=gtk.STOCK_CLOSE) btn_close.connect("clicked", self.__on_close) btn_close.show() self.action_area.add(self.btn_prev) self.action_area.add(self.btn_next) self.action_area.add(btn_close) # make the close button the default button btn_close.set_flags(gtk.CAN_DEFAULT) self.set_default(btn_close) self.set_focus(btn_close) self.__show_currTip() #---------------------------------------------------------------------- def run(self): if self.showTips: gtk.MessageDialog.run(self) #---------------------------------------------------------------------- def __show_currTip(self): self.__boundIndex2Dict() self.__getNofTips() self.__label.set_markup(_(TIPS[self.__index]).strip()) self.__thcheckbox.set_active( not self.avTips[self.__index]) self.__checkbox.set_active(self.showTips) if self.nOfOkTips <= 1: self.btn_next.set_sensitive(False) self.btn_prev.set_sensitive(False) #---------------------------------------------------------------------- def __on_close(self, src): self.__saveConfFile() self.hide() #---------------------------------------------------------------------- def __on_closeBtn(self, dialog, response): self.__saveConfFile() self.hide() #---------------------------------------------------------------------- def __boundIndex2Dict(self): if (self.__index >= len(TIPS)): self.__index = 0 if (self.__index < 0): self.__index = len(TIPS) - 1 #---------------------------------------------------------------------- def __getNofTips(self): self.nOfOkTips = 0 for tipInstance in self.avTips.keys(): if self.avTips[tipInstance]: self.nOfOkTips += 1 #---------------------------------------------------------------------- def __on_toggleThis(self, src): value = src.get_active() self.avTips[self.__index] = not value # self.__getNofTips() # self.update_observer(self.OBS_TOGGLED, value) #---------------------------------------------------------------------- def __on_toggleAll(self, src): value = src.get_active() self.showTips = value # self.update_observer(self.OBS_TOGGLED, value) #---------------------------------------------------------------------- def next_tip(self, *args): self.__index += 1 self.__boundIndex2Dict() while(not self.avTips[self.__index]): self.__index += 1 self.__boundIndex2Dict() self.__show_currTip() #---------------------------------------------------------------------- def prev_tip(self, *args): self.__index -= 1 self.__boundIndex2Dict() while(not self.avTips[self.__index]): self.__index -= 1 self.__boundIndex2Dict() self.__show_currTip() #---------------------------------------------------------------------- def __getTipFromConf(self): okTipList = [] for tipInstance in self.avTips.keys(): if self.avTips[tipInstance]: print tipInstance okTipList.append(tipInstance) if(len(okTipList) == 0): randTipId = -1 else: # next tip in the list randTipId = okTipList[0] return randTipId #---------------------------------------------------------------------- def __loadConfFile(self): if(not os.path.exists(os.path.expanduser(self.confFilePath))): self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) tipsOfTheDay = self.confFile.getTag("tipsOfTheDay") tips_ver = tipsOfTheDay.getAttr("version") if tips_ver != TIPS_VER: self.GenerateBlankConf() self.confFile = XMLParser(os.path.expanduser(self.confFilePath)) show_tips = tipsOfTheDay.getAttr("show") if show_tips == "True": for tip in tipsOfTheDay.getChildTags("tip"): self.avTips[int(tip.getAttr("id"))]=(tip.getAttr("enabled") == "True") print self.avTips #---------------------------------------------------------------------- def __saveConfFile(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":str(self.showTips), "version":TIPS_VER}) for tipInstance in self.avTips.keys(): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":self.avTips[tipInstance], "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close() #---------------------------------------------------------------------- def GenerateBlankConf(self): conf_file = XMLParser() conf_file.addTag("tipsOfTheDay", {"show":"True", "version":TIPS_VER}) for tipInstance in range(len(TIPS)): conf_file.appendToTag("tipsOfTheDay", "tip", {"enabled":"True", "id":tipInstance}) self.confFile = file(os.path.expanduser(self.confFilePath), 'w') self.confFile.write(conf_file.getXML()) self.confFile.close()
def Load(self, file_name=None): if file_name != None: self.set_file_name(file_name) else: if self.file_name == None: self.file_name = "Cannot Load without filename" return False # reseting present diagram.. self.blocks, self.connectors, self.curr_connector, self.session_id = {}, [], None, 0 # this two must be updated at each block/conn insertion self.block_id = 1 # since block counts are kept, render this from the saved file self.connector_id = 1 # since connector Ids are generated from scratch, just reset it #t_oLoad = bt.bind_file(self.file_name) # binding saved project #print t_oLoad.xml() t_oLoad = XMLParser(self.file_name) # loading blocks on canvas #GcState_root = t_oLoad.getTagChild("harpia", "GcState") #blocks = t_oLoad.getChildTags(GcState_root, "block") blocks = t_oLoad.getTag("harpia").getTag("GcState").getChildTags( "block") #for block in t_oLoad.harpia.GcState.block: for block in blocks: #block_id = t_oLoad.getTagAttr(block, "id") #block_type = t_oLoad.getTagAttr(block, "type") block_id = block.getAttr("id") block_type = block.getAttr("type") position = block.getTag("position") x = position.getAttr("x") y = position.getAttr("y") self.__insert_blockPosId(int(block_type), float(x), float(y), int(block_id)) self.block_id = max(self.block_id, int(block_id)) self.block_id += 1 blocks = t_oLoad.getTag("harpia").getTag("network").getChildTags( "block") # loading connectors on canvas try: #for block in t_oLoad.harpia.network.block: for block in blocks: block_id = block.getAttr("id") outputs = block.getTag("outputs") #for connector in block.outputs.output: for connector in outputs.getChildTags("output"): conn_input = connector.getAttr("input") conn_inblock = connector.getAttr("inBlock") conn_id = connector.getAttr("id") print conn_input, conn_inblock, conn_id #self.InsertReadyConnector(int(block.id), (int(connector.id) - 1), int(connector.inBlock), if conn_inblock != "--" and conn_input != "--": #(int(connector.input) - 1)) self.InsertReadyConnector(int(block_id), (int(conn_id) - 1), int(conn_inblock), (int(conn_input) - 1)) # this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14) except AttributeError: pass # loading properties blocks = t_oLoad.getTag("harpia").getTag("properties").getChildTags( "block") for block in blocks: block_xml = str(block) block_id = block.getAttr("id") #t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block.xml() + '\n</properties>\n' t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block_xml + '\n</properties>\n' #self.blocks[int(block.id)].SetPropertiesXML(bt.bind_string(t_sBlockProperties)) self.blocks[int(block_id)].SetPropertiesXML( XMLParser(t_sBlockProperties, fromString=True)) self.UpdateScrolling() self.GotoScrolling(0, 0) return True