Пример #1
0
    def on_ProcessToolBar_clickedIneer(self):
        t_nPage = self.widgets['WorkArea'].get_current_page()
        t_bIsLive = False
        if self.m_oGcDiagrams.has_key(t_nPage):
            self.UpdateStatus(0)

            t_oGcDiagram = self.m_oGcDiagrams[t_nPage]
            t_oProcessXML = xmltree.xmlTree()
            t_oProcessXML.fromString("<harpia>" +
                                     str(t_oGcDiagram.GetProcessChain()) +
                                     "</harpia>")
            assert t_oProcessXML.isValid(), 'invalid process chain: %r'

            if t_oProcessXML.findAttributes('./properties/block'):
                # if harpia/properties is not empty

                #cpscotti standalone!!!
                t_lsProcessChain = [
                ]  #lista pra n precisar ficar copiando prum lado e pro otro o xml inteiro
                t_lsProcessChain.append(t_oProcessXML.toString())

                workingDir = t_oGcDiagram.getDirName()
                t_Sm = s2iSessionManager.s2iSessionManager(workingDir)

                ## pegando o novo ID (criado pela s2iSessionManager) e passando para o s2idiagram
                t_oGcDiagram.SetSessionManager(t_Sm)
                t_oGcDiagram.SetIDBackendSession(t_Sm.m_sSessionId)

                #step sempre sera uma lista.. primeiro elemento eh uma mensagem, segundo eh o erro.. caso exista erro.. passar para o s2idiagram tb!
                t_oGcDiagram.SetErrorLog('')
                t_bEverythingOk = True
                t_Sm.NewInstance(self.batchModeOn, t_lsProcessChain)

        #falta pegar o retorno!!!!!!
        self.UpdateStatus(7)
Пример #2
0
 def loadFromString(self, xmlString):
     if xmlString is None:
         return
     # reset diagram
     self.reset()
     # load .hrp project file
     t_oLoad = xmltree.xmlTree()
     t_oLoad.fromString(xmlString)
     assert t_oLoad.isValid(), 'failed to load from xml string ' + xmlString
     undoState = self.enableUndo(False)
     self.loadFromXml(t_oLoad)
     self.enableUndo(undoState)
Пример #3
0
	def loadFromString(self, xmlString):
		if xmlString is None:
			return
		# reset diagram
		self.reset()
		# load .hrp project file
		t_oLoad = xmltree.xmlTree()
		t_oLoad.fromString(xmlString)
		assert t_oLoad.isValid(), 'failed to load from xml string ' + xmlString
		undoState = self.enableUndo(False)
		self.loadFromXml(t_oLoad)
		self.enableUndo(undoState)
Пример #4
0
		def __loadConfFile(self):
			if(not os.path.exists(os.path.expanduser(self.confFilePath))):
				self.GenerateBlankConf()
			self.btXML = xmltree.xmlTree()
			self.btXML.load(os.path.expanduser(self.confFilePath))
			if self.btXML.getAttribute('.', 'version') != TIPS_VER:
				self.btXML = None
				self.GenerateBlankConf()

			self.showTips = (self.btXML.getAttribute('.', 'show') == "True")
			if self.showTips:
				for tip in self.btXML.findAttributes('./tip'):
					self.avTips[int(tip['id'])] = (tip['enabled'] == "True")
Пример #5
0
    def __loadConfFile(self):
        if (not os.path.exists(os.path.expanduser(self.confFilePath))):
            self.GenerateBlankConf()
        self.btXML = xmltree.xmlTree()
        self.btXML.load(os.path.expanduser(self.confFilePath))
        if self.btXML.getAttribute('.', 'version') != TIPS_VER:
            self.btXML = None
            self.GenerateBlankConf()

        self.showTips = (self.btXML.getAttribute('.', 'show') == "True")
        if self.showTips:
            for tip in self.btXML.findAttributes('./tip'):
                self.avTips[int(tip['id'])] = (tip['enabled'] == "True")
Пример #6
0
		def GenerateBlankConf(self):
			# create blank conf string
			newConf = '<?xml version="1.0" encoding="UTF-8"?>'
			newConf += '\n<tipsOfTheDay version="' + unicode(TIPS_VER) + '" show="True">'
			for tipId in range(len(TIPS)):
				newConf += '\n\t<tip enabled="True" id="' + unicode(tipId) + '"/>'
			newConf += '\n</tipsOfTheDay>'

			# create blank conf xml structure
			self.btXML = xmltree.xmlTree()
			self.btXML.fromString(newConf)
			assert self.btXML.isValid, 'invalid configuration string: %r'

			# write newconf to file
			self.confFile = file(os.path.expanduser(self.confFilePath), 'w')
			self.confFile.write(newConf)
			self.confFile.close()
Пример #7
0
    def GenerateBlankConf(self):
        # create blank conf string
        newConf = '<?xml version="1.0" encoding="UTF-8"?>'
        newConf += '\n<tipsOfTheDay version="' + unicode(
            TIPS_VER) + '" show="True">'
        for tipId in range(len(TIPS)):
            newConf += '\n\t<tip enabled="True" id="' + unicode(tipId) + '"/>'
        newConf += '\n</tipsOfTheDay>'

        # create blank conf xml structure
        self.btXML = xmltree.xmlTree()
        self.btXML.fromString(newConf)
        assert self.btXML.isValid, 'invalid configuration string: %r'

        # write newconf to file
        self.confFile = file(os.path.expanduser(self.confFilePath), 'w')
        self.confFile.write(newConf)
        self.confFile.close()
Пример #8
0
    def loadFromXml(self, t_oLoad):
        #loading blocks on canvas
        blocks = t_oLoad.findSubTrees('./GcState/block')
        assert blocks != [], 'no ./GcState/block structure: %r'
        for block in blocks:
            id = int(block.getAttribute('.', 'id'))
            type = int(block.getAttribute('.', 'type'))
            posx = float(block.getAttribute('./position', 'x'))
            posy = float(block.getAttribute('./position', 'y'))
            self.InsertBlockPosId(type, posx, posy, id)
            self.m_nBlockCountId = max(self.m_nBlockCountId, id)
        self.m_nBlockCountId += 1

        #loading connectors on canvas
        blocks = t_oLoad.findSubTrees('./network/block')
        assert blocks != [], 'no ./network/block structure: %r'
        for block in blocks:
            blockId = int(block.getAttribute('.', 'id'))
            outputs = block.findAttributes('./outputs/output')
            for output in outputs:
                outputId = int(output['id'])
                inBlock = output['inBlock']
                input = output['input']
                if inBlock <> "--" and input <> "--":
                    self.InsertReadyConnector(blockId, outputId - 1,
                                              int(inBlock),
                                              int(input) - 1)
                    #this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14)

        #loading properties
        blocks = t_oLoad.findSubTrees('./properties/block')
        assert blocks != [], 'no ./properties/block structure: %r'
        for block in blocks:
            blockId = int(block.getAttribute('.', 'id'))
            t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n' + block.toString(
            ) + '\n'
            blockProperties = xmltree.xmlTree()
            blockProperties.fromString(t_sBlockProperties)
            assert blockProperties.isValid(), 'invalid block properties: %r'
            self.m_oBlocks[blockId].SetPropertiesXML(blockProperties)

        return True
Пример #9
0
    def loadFromFile(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

        # reset diagram
        self.reset()
        self.initUndo()
        # load .hrp project file
        t_oLoad = xmltree.xmlTree()
        t_oLoad.load(self.m_sFilename)
        assert t_oLoad.isValid(), 'failed to load file ' + self.m_sFilename
        undoState = self.enableUndo(False)
        result = self.loadFromXml(t_oLoad)
        self.savedXml = self.ToXml()  # capture the current state
        self.enableUndo(undoState)
        self.setUndoSlot()
        return result
Пример #10
0
	def loadFromFile(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
		
		# reset diagram 
		self.reset()
		self.initUndo()
		# load .hrp project file
		t_oLoad = xmltree.xmlTree()
		t_oLoad.load(self.m_sFilename)
		assert t_oLoad.isValid(), 'failed to load file ' + self.m_sFilename
		undoState = self.enableUndo(False)
		result = self.loadFromXml(t_oLoad)
		self.savedXml = self.ToXml() # capture the current state
		self.enableUndo(undoState)
		self.setUndoSlot()
		return result
Пример #11
0
def loadConfiguration():
    global opencvIncludeDirs
    global opencvLibrariesDirs
    global opencvDllDirs
    global opencvLibraries
    global otherIncludeDirs
    global otherLibrariesDirs
    global otherDllDirs
    global otherLibraries
    global compilerOptions
    global linkerOptions
    global localBlocksDirs
    global workingDirsPlace

    if not os.path.exists(configurationFileName):
        return  # do nothing

    # read configuration file

    print 'Configuration file \'' + configurationFileName + '\' found, loading preferences...'

    tree = xmltree.xmlTree()
    tree.load(configurationFileName)

    opencvIncludeDirs = tree.getText('./opencvIncludeDirs') or ''
    opencvLibrariesDirs = tree.getText('./opencvLibrariesDirs') or ''
    opencvDllDirs = tree.getText('./opencvDllDirs') or ''
    opencvLibraries = tree.getText('./opencvLibraries') or ''

    otherIncludeDirs = tree.getText('./otherIncludeDirs') or ''
    otherLibrariesDirs = tree.getText('./otherLibrariesDirs') or ''
    otherDllDirs = tree.getText('./otherDllDirs') or ''
    otherLibraries = tree.getText('./otherLibraries') or ''

    compilerOptions = tree.getText('./compilerOptions') or ''
    linkerOptions = tree.getText('./linkerOptions') or ''

    localBlocksDirs = tree.getText('./localBlocksDirs') or ''
    workingDirsPlace = tree.getText('./workingDirsPlace') or ''
Пример #12
0
	def loadFromXml(self, t_oLoad):
		#loading blocks on canvas
		blocks = t_oLoad.findSubTrees('./GcState/block')
		assert blocks != [], 'no ./GcState/block structure: %r'
		for block in blocks:
			id = int(block.getAttribute('.', 'id'))
			type = int(block.getAttribute('.', 'type'))
			posx = float(block.getAttribute('./position', 'x'))
			posy = float(block.getAttribute('./position', 'y'))
			self.InsertBlockPosId(type, posx, posy, id)
			self.m_nBlockCountId = max(self.m_nBlockCountId, id)
		self.m_nBlockCountId += 1
			
		#loading connectors on canvas
		blocks = t_oLoad.findSubTrees('./network/block')
		assert blocks != [], 'no ./network/block structure: %r'
		for block in blocks:
			blockId = int(block.getAttribute('.', 'id'))
			outputs = block.findAttributes('./outputs/output')
			for output in outputs:
				outputId = int(output['id'])
				inBlock = output['inBlock']
				input = output['input']
				if inBlock <> "--" and input <> "--":
					self.InsertReadyConnector(blockId, outputId-1, int(inBlock), int(input)-1) 
					#this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14)
		
		#loading properties
		blocks = t_oLoad.findSubTrees('./properties/block')
		assert blocks != [], 'no ./properties/block structure: %r'
		for block in blocks:
			blockId = int(block.getAttribute('.', 'id'))
			t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n' + block.toString() + '\n'
			blockProperties = xmltree.xmlTree()
			blockProperties.fromString(t_sBlockProperties)
			assert blockProperties.isValid(), 'invalid block properties: %r'
			self.m_oBlocks[blockId].SetPropertiesXML(blockProperties)

		return True
Пример #13
0
def loadConfiguration():
	global opencvIncludeDirs
	global opencvLibrariesDirs
	global opencvDllDirs
	global opencvLibraries
	global otherIncludeDirs
	global otherLibrariesDirs
	global otherDllDirs
	global otherLibraries
	global compilerOptions
	global linkerOptions
	global localBlocksDirs
	global workingDirsPlace

	if not os.path.exists(configurationFileName):
		print 'Failed to read configuration file \'' + configurationFileName + '\'.'
		return # do nothing

	# read configuration file
	
	tree = xmltree.xmlTree()
	tree.load(configurationFileName)

	opencvIncludeDirs = tree.getText('./opencvIncludeDirs') or ''
	opencvLibrariesDirs = tree.getText('./opencvLibrariesDirs') or ''
	opencvDllDirs = tree.getText('./opencvDllDirs') or ''
	opencvLibraries = tree.getText('./opencvLibraries') or ''

	otherIncludeDirs = tree.getText('./otherIncludeDirs') or ''
	otherLibrariesDirs = tree.getText('./otherLibrariesDirs') or ''
	otherDllDirs = tree.getText('./otherDllDirs') or ''
	otherLibraries = tree.getText('./otherLibraries') or ''

	compilerOptions = tree.getText('./compilerOptions') or ''
	linkerOptions = tree.getText('./linkerOptions') or ''

	localBlocksDirs = tree.getText('./localBlocksDirs') or ''
	workingDirsPlace = tree.getText('./workingDirsPlace') or ''
Пример #14
0
    def __init__(self,
                 diagram,
                 a_nBlockType,
                 a_nBlockCountId=1):  #a_nInputs, a_nOutputs, a_nBlockType ):

        #initialize all members

        #if len(a_oDictBlock) == 0:
        #a_oDictBlock["Label"] = "Unknown Block"
        #a_oDictBlock["Icon"] = 'haarDetect.png'
        #a_oDictBlock["Color"] = "150:20:40:150"
        #a_oDictBlock["Inputs"] = 0
        #a_oDictBlock["Outputs"] = 0

        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", a_nBlockType, "... assuming 0"

        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['Inputs'] == 0:
            self.m_bIsSource = True

        if self.m_oDictBlock.has_key("TimeShifts"):  #delay block
            self.m_bTimeShifts = self.m_oDictBlock["TimeShifts"]

        # self.m_oPropertiesXML contains something like:
        # <block id="1" type="0">
        #   <property name="state" value="true" />
        #   <property name="_PARAM1_" type="filename" value="resource/lena.jpg" />
        # </block>
        self.m_oPropertiesXML = xmltree.xmlTree()
        self.m_oPropertiesXML.load(str(self.m_oDictBlock["Path"]["Xml"]))
        self.m_oPropertiesXML = self.m_oPropertiesXML.findSubTrees(
            './block')[0]
        self.m_oPropertiesXML.setAttribute('.', 'id',
                                           unicode(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 = 14

        self.inputPortCenters = []
        self.outputPortCenters = []

        self.width = WIDTH_DEFAULT
        self.TextWidth = self.width - WIDTH_2_TEXT_OFFSET

        t_nMaxIO = max(self.m_oDictBlock["Inputs"],
                       self.m_oDictBlock["Outputs"])

        ## 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)  # space between 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.wGroup = GooCanvas.CanvasGroup(can_focus=True)
        self.ParentDiagram.root_add(self.wGroup)
        self.wGroup.connect("button-press-event", self.group_event)
        self.wGroup.connect("button-release-event", self.group_event)
        self.wGroup.connect("key-press-event", self.group_event)
        self.wGroup.connect("motion-notify-event", self.group_event)
        self.wGroup.connect("enter-notify-event", self.group_event)
        self.wGroup.connect("leave-notify-event", self.group_event)
        self.wGroup.connect("focus-in-event", self.onFocusIn)
        self.wGroup.connect("focus-out-event", self.onFocusOut)

        self.Build()
        self.isMoving = False  # is the block being moved ?
Пример #15
0
def addBlockFromFile(blocks, fileName):
    """add one block entirely defined in xml configuration file"""
    """alternative way of hardcoded one in s2idirectory.py"""
    tree = xmltree.xmlTree()
    tree.load(fileName)
    #print 'DBG fileName=', fileName
    #print 'DBG tree=', tree.toString()

    # parse file

    blockType = int(tree.getAttribute('./block', 'type'))

    # get default properties
    properties = {}
    for prop in tree.findAttributes('./block/property'):
        propName = prop['name']
        prop.pop('name')
        properties[propName] = prop
    #print 'DBG in', __file__, '.addBlockFromFile(), properties=', properties

    label = tree.getText('./label')
    xmlpath = fileName
    inputs = {}
    for input in tree.findAttributes('./input'):
        # each input is a dictionnary of input attributes
        inputs[int(input['id'])] = input

    outputs = {}
    for output in tree.findAttributes('./output'):
        # each output is a dictionnary of output attributes
        outputs[int(output['id'])] = output

    icon = tree.getText('./icon')
    color = tree.getText('./color')
    description = tree.getText('./description')
    treegroup = tree.getText('./treegroup')
    isstream = False
    if tree.getText('./isstream') == 'true':
        isstream = True

    # get compilation informations

    includePaths = []
    for inclPath in tree.findAttributes('./includepath'):
        try:
            pathStr = inclPath['path']
            if pathStr:
                # do not append empty string !
                includePaths.append(pathStr)
        except:
            pass

    libraries = []
    for elem in tree.findAttributes('./library'):
        try:
            libStr = elem['name']
            if libStr:
                # do not append empty string !
                libraries.append(libStr)
        except:
            pass

    libraryPaths = []
    for elem in tree.findAttributes('./librarypath'):
        try:
            pathStr = elem['path']
            if pathStr:
                # do not append empty string !
                libraryPaths.append(pathStr)
        except:
            pass

    # get code and remove unwanted characters
    includes = tree.getText('./includes')
    includes = cleanCode(includes)

    functions = tree.getText('./functions')
    functions = cleanCode(functions)

    initializations = tree.getText('./initializations')
    initializations = cleanCode(initializations)

    processings = tree.getText('./processings')
    processings = cleanCode(processings)

    cleanings = tree.getText('./cleanings')
    cleanings = cleanCode(cleanings)

    # add new block to block list
    blocks[blockType] = {
        "Defaultprops": properties,
        "Label": label,
        "Path": {
            "Xml": xmlpath
        },
        "Inputs": len(inputs),
        "Outputs": len(outputs),
        "Icon": icon,
        "Color": color,
        "InTypes": inputs,
        "OutTypes": outputs,
        "Description": description,
        "TreeGroup": treegroup,
        "IsStream": isstream,
        "includes": includes,
        "includePaths": includePaths,
        "libraries": libraries,
        "libraryPaths": libraryPaths,
        "functions": functions,
        "initializations": initializations,
        "processings": processings,
        "cleanings": cleanings,
        "help": tree.getText('./help')
    }
Пример #16
0
#    PURPOSE.  See the GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    For further information, check the COPYING file distributed with this software.
#
#----------------------------------------------------------------------

#
# Test xml parser.
#

import xmltree

doc = xmltree.xmlTree()
print doc.toString()

doc.load('../app_data/blocks.public/read_image.xml')
print doc.toString()
print doc.toString('./block')


print 'block attrib=', doc.findAttributes('./block')
print 'property attrib=', doc.findAttributes('./block/property')
print 'input attrib=', doc.findAttributes('./input')
print 'output attrib=', doc.findAttributes('./output')
print 'label attrib=', doc.findAttributes('./label')

print 'block text=', doc.findTexts('./block')
print 'label text=', doc.findTexts('./label')
Пример #17
0
#    PURPOSE.  See the GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    For further information, check the COPYING file distributed with this software.
#
#----------------------------------------------------------------------

#
# Test xml parser.
#

import xmltree

doc = xmltree.xmlTree()
print doc.toString()

doc.load('../app_data/blocks.public/read_image.xml')
print doc.toString()
print doc.toString('./block')

print 'block attrib=', doc.findAttributes('./block')
print 'property attrib=', doc.findAttributes('./block/property')
print 'input attrib=', doc.findAttributes('./input')
print 'output attrib=', doc.findAttributes('./output')
print 'label attrib=', doc.findAttributes('./label')

print 'block text=', doc.findTexts('./block')
print 'label text=', doc.findTexts('./label')
Пример #18
0
def addBlockFromFile( blocks, fileName):
	"""add one block entirely defined in xml configuration file"""
	"""alternative way of hardcoded one in s2idirectory.py"""
	tree = xmltree.xmlTree()
	tree.load(fileName)
	#print 'DBG fileName=', fileName
	#print 'DBG tree=', tree.toString()

	# parse file

	blockType = int(tree.getAttribute('./block', 'type'))

	# get default properties
	properties = {}
	for prop in tree.findAttributes('./block/property'):
		propName = prop['name']
		prop.pop('name')
		properties[propName] = prop
	#print 'DBG in', __file__, '.addBlockFromFile(), properties=', properties

	label = tree.getText('./label')
	xmlpath = fileName
	inputs = {}
	for input in tree.findAttributes('./input'):
		# each input is a dictionnary of input attributes
		inputs[int(input['id'])] = input

	outputs = {}
	for output in tree.findAttributes('./output'):
		# each output is a dictionnary of output attributes
		outputs[int(output['id'])] = output

	icon =  tree.getText('./icon')
	color =  tree.getText('./color')
	description =  tree.getText('./description')
	treegroup =  tree.getText('./treegroup')
	isstream = False
	if tree.getText('./isstream') == 'true':
		isstream = True

	# get compilation informations

	includePaths = []
	for inclPath in tree.findAttributes('./includepath'):
		try:
			pathStr = inclPath['path']
			if pathStr:
				# do not append empty string !
				includePaths.append(pathStr)
		except:
			pass

	libraries = []
	for elem in tree.findAttributes('./library'):
		try:
			libStr = elem['name']
			if libStr:
				# do not append empty string !
				libraries.append(libStr)
		except:
			pass

	libraryPaths = []
	for elem in tree.findAttributes('./librarypath'):
		try:
			pathStr = elem['path']
			if pathStr:
				# do not append empty string !
				libraryPaths.append(pathStr)
		except:
			pass

	# get code and remove unwanted characters
	includes = tree.getText('./includes')
	includes = cleanCode(includes)

	functions = tree.getText('./functions')
	functions = cleanCode(functions)

	initializations = tree.getText('./initializations')
	initializations = cleanCode(initializations)

	processings = tree.getText('./processings')
	processings = cleanCode(processings)

	cleanings = tree.getText('./cleanings')
	cleanings = cleanCode(cleanings)

	# add new block to block list
	blocks[blockType] = { 
		"Defaultprops":properties,
		"Label":label,
		"Path":{ "Xml":xmlpath },
		"Inputs":len(inputs),
		"Outputs":len(outputs),
		"Icon":icon,
		"Color":color,
		"InTypes":inputs,
		"OutTypes":outputs,
		"Description":description,
		"TreeGroup":treegroup,
		"IsStream":isstream,
		"includes":includes,
		"includePaths":includePaths,
		"libraries":libraries,
		"libraryPaths":libraryPaths,
		"functions":functions,
		"initializations":initializations,
		"processings":processings,
		"cleanings":cleanings,
		"help":tree.getText('./help')
	}
Пример #19
0
def generateCode(processingChainFileName):
	global includePaths
	global libraries
	global libraryPaths
	global includes
	global functions
	global initializations
	global processings
	global cleanings

	# reset global variables
	includePaths = []
	libraries = []
	libraryPaths = []
	includes = []
	functions = []
	initializations = []
	processings = []
	cleanings = []

	# batch mode indicator
	inBatchMode = False

	# load blocks graph from file
	xmlChain = xmltree.xmlTree()
	xmlChain.load(processingChainFileName)
	assert xmlChain.isValid(), 'failed to parse xml file: %r'
	
	# build blocks graph
	graph = blocksgraph.blocksGraph()
	graph.buildFromXml(xmlChain)
	#print graph.graph

	# produce code by parsing graph by rank (depth) order
	for blockId in graph.getSortedBlocks():
		generateBlockCode(blockId, graph.getBlock(blockId))

	# remove duplicates from some sections
	includePaths = uniq(includePaths)
	libraries = uniq(libraries)
	libraryPaths = uniq(libraryPaths)
	includes = uniq(includes)
	functions = uniq(functions)
	initializations = uniq(initializations)

	# check if one source is a stream
	isStream = False
	for block in graph.getBlocksList().values():
		isStream = getBlockIsStream(block)
		if isStream:
			break  # there is one stream, no need to continue

	# check if there is a 'show' block
	isShow = False
	for block in graph.getBlocksList().values():
		if block['type'] == 2:
			isShow = True
			break

	# headers
	sourceCode = '''
#include <opencv2/opencv.hpp>
#include <stdio.h>

#ifdef WIN32
	// unix to win porting
	#define	  __func__   __FUNCTION__
	#define	  __PRETTY_FUNCTION__   __FUNCTION__
	#define   snprintf   _snprintf
	#define	  sleep(n_seconds)   Sleep((n_seconds)*1000)
	#define   round(d)   floor((d) + 0.5)
#endif
'''

	# add include section
	sourceCode += '\n\n'
	sourceCode += formatCode(['// includes section'], afterCode='\n')
	sourceCode += formatCode(includes, afterCode='\n')

	# add function definition section
	sourceCode += formatCode(['// functions section'], afterCode='\n')
	sourceCode += formatCode(functions, afterEach='\n\n')

	sourceCode += '''
int main(void)
{
	// disable buffer on stdout to make 'printf' outputs
	// immediately displayed in GUI-console
	setbuf(stdout, NULL);

'''

	# add initialization section
	tabs = '\t'
	sourceCode += formatCode(['// initializations section'], tabs, afterCode='\n')
	sourceCode += formatCode(initializations, tabs, afterCode='\n')

	# if one source is a stream, add a loop
	if isStream:
		sourceCode += formatCode(['int key = 0;'], tabs)
		sourceCode += formatCode(['bool paused = false;'], tabs)
		sourceCode += formatCode(['bool goOn = true;'], tabs)
		sourceCode += formatCode(['while( goOn )'], tabs)
		sourceCode += formatCode(['{'], tabs)
		tabs = '\t\t'

	# add processing section
	sourceCode += formatCode(['// processings section'], tabs, afterCode='\n')
	sourceCode += formatCode(processings, tabs, afterCode='\n')

	# add minimal user interaction, but not in batch mode
	if not inBatchMode:
		if isStream: 
			# pause/unpause when space key pressed
			sourceCode += formatCode(['if( paused )'], tabs)
			sourceCode += formatCode(['\tkey = cv::waitKey(0);'], tabs)
			sourceCode += formatCode(['else'], tabs)
			sourceCode += formatCode(['\tkey = cv::waitKey(25);'], tabs)
			sourceCode += formatCode(['if( (key & 255) == \' \' )'], tabs)
			sourceCode += formatCode(['\tpaused = ! paused;'], tabs)
			sourceCode += formatCode(['else if( key != -1 )'], tabs)
			sourceCode += formatCode(['\tgoOn = false;'], tabs)
		elif isShow:
			sourceCode += formatCode(['cv::waitKey(0);'], tabs, afterCode='\n')

	# if one source is a stream, close loop
	if isStream: 
		tabs = '\t'
		sourceCode += formatCode(['}'], tabs, afterCode='\n')
		
	# add cleaning section
	sourceCode += formatCode(['// cleanings section'], tabs, afterCode='\n')
	sourceCode += formatCode(cleanings, tabs, afterCode='\n')

	# end of code
	sourceCode += formatCode(['return 0;'], tabs)
	sourceCode += formatCode(['}'], afterCode='\n')


	#print 'processings=', processings
	#print 'cleanings=', cleanings
	#print sourceCode
	return sourceCode
Пример #20
0
	def __init__( self, diagram, a_nBlockType, a_nBlockCountId=1):#a_nInputs, a_nOutputs, a_nBlockType ):
		
		#initialize all members
		
		#if len(a_oDictBlock) == 0:
			#a_oDictBlock["Label"] = "Unknown Block"
			#a_oDictBlock["Icon"] = 'haarDetect.png'
			#a_oDictBlock["Color"] = "150:20:40:150"
			#a_oDictBlock["Inputs"] = 0
			#a_oDictBlock["Outputs"] = 0
		
		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", a_nBlockType, "... assuming 0"
		
		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['Inputs'] == 0:
			self.m_bIsSource = True
		
		if self.m_oDictBlock.has_key("TimeShifts"): #delay block
			self.m_bTimeShifts = self.m_oDictBlock["TimeShifts"]
		

		# self.m_oPropertiesXML contains something like:
		# <block id="1" type="0">
		#   <property name="state" value="true" />
		#   <property name="_PARAM1_" type="filename" value="resource/lena.jpg" />
		# </block>
		self.m_oPropertiesXML = xmltree.xmlTree()
		self.m_oPropertiesXML.load(str(self.m_oDictBlock["Path"]["Xml"]))
		self.m_oPropertiesXML = self.m_oPropertiesXML.findSubTrees('./block')[0]
		self.m_oPropertiesXML.setAttribute('.', 'id', unicode(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 = 14
		
		self.inputPortCenters = []
		self.outputPortCenters = []
		
		self.width = WIDTH_DEFAULT
		self.TextWidth = self.width - WIDTH_2_TEXT_OFFSET
		
		
		t_nMaxIO = max(self.m_oDictBlock["Inputs"],self.m_oDictBlock["Outputs"])
		
		## 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 ) # space between 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.wGroup = goocanvas.Group(can_focus=True)
		self.ParentDiagram.root_add(self.wGroup)
		self.wGroup.connect("button-press-event", self.group_event)
		self.wGroup.connect("button-release-event", self.group_event)
		self.wGroup.connect("key-press-event", self.group_event)
		self.wGroup.connect("motion-notify-event", self.group_event)
		self.wGroup.connect("enter-notify-event", self.group_event)
		self.wGroup.connect("leave-notify-event", self.group_event)
		self.wGroup.connect("focus-in-event", self.onFocusIn)
		self.wGroup.connect("focus-out-event", self.onFocusOut)
		
		self.Build()
		self.isMoving = False  # is the block being moved ?