Esempio n. 1
0
    def __init__(self, PropertiesXML, S2iBlockProperties):
        self.m_sDataDir = os.environ["HARPIA_DATA_DIR"]

        filename = self.m_sDataDir + "glade/equalizeHistogram.ui"
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = ["Properties", "BackgroundColor", "BorderColor", "HelpView"]

        handlers = [
            #  'on_EQUARadioAutomatic_pressed',
            #  'on_EQUARadioBand_pressed',
            "on_BackColorButton_clicked",
            "on_BorderColorButton_clicked",
            "on_cancel_clicked",
            "on_equalizeHistogram_confirm_clicked",
        ]

        top_window = "Properties"

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/equalizeHistogram" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets["HelpView"].set_buffer(t_oTextBuffer)
Esempio n. 2
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/sobel.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'SOBEXOrder',
            'SOBEYOrder',
            'SOBEMaskSize',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_sobel_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.OrderLimit = 6
        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:

            if Property.name == "xorder":
                self.widgets['SOBEXOrder'].set_value(int(Property.value))

            if Property.name == "yorder":
                self.widgets['SOBEYOrder'].set_value(int(Property.value))

            if Property.name == "masksize":
                if Property.value == "1":
                    self.widgets['SOBEMaskSize'].set_active(int(0))
                if Property.value == "3":
                    self.widgets['SOBEMaskSize'].set_active(int(1))
                if Property.value == "5":
                    self.widgets['SOBEMaskSize'].set_active(int(2))
                if Property.value == "7":
                    self.widgets['SOBEMaskSize'].set_active(int(3))

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/sobel" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 3
0
    def load(cls, file_name):
        """
        This method loads the port from XML file.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """
        # load the port
        if os.path.exists(file_name) is False:
            return
        parser = XMLParser(file_name)
        if parser.getTag("HarpiaPort") is None:
            return None

        port = Port()
        port.type = parser.getTagAttr("HarpiaPort", "type")
        port.language = parser.getTagAttr("HarpiaPort", "language")
        port.label = parser.getTagAttr("HarpiaPort", "label")
        port.color = parser.getTagAttr("HarpiaPort", "color")
        port.multiple = parser.getTagAttr("HarpiaPort", "multiple")
        port.source = parser.getTagAttr("HarpiaPort", "source")
        port.code = parser.getTag("HarpiaPort").getTag("code").getText()

        count = 0
        for code in port.input_codes:
            port.input_codes[count] = parser.getTag('HarpiaPort').getTag('input_code' + str(count)).getText()
            port.output_codes[count] = parser.getTag('HarpiaPort').getTag('output_code' + str(count)).getText()
            count = count + 1

        if port.type == "":
            return None
        return port
Esempio n. 4
0
    def __init__(self, PropertiesXML, S2iBlockProperties):
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/division.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_division_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/division" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 5
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/findSquares.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'BackgroundColor',
            'BorderColor',
            'HelpView',
            'minVal',
            'maxVal',
            'enMin',
            'enMax',
            'prop_confirm'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_prop_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_enMin_toggled',
            'on_enMax_toggled'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")

        for Property in self.block_properties:

            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "minVal":
                self.widgets['minVal'].set_value(int(float(value)))
            if name == "maxVal":
                self.widgets['maxVal'].set_value(int(float(value)))
            if name == "enMin":
                self.widgets['enMin'].set_active(value == 'True')
            if name == "enMax":
                self.widgets['enMax'].set_active(value == 'True')

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + 'help/findSquares' + _('_en.help'))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 6
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/erode.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'ERODMaskSize',
            'ERODIterations',
            'BackgroundColor',
            'BorderColor',
            'HelpView',
            'erode_confirm'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_erode_confirm_clicked',
            'on_BorderColorButton_clicked',
            'on_BackColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        # load properties values
        for Property in self.block_properties:

            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "masksize":
                if value == "3x3":
                    self.widgets['ERODMaskSize'].set_active(int(0))
                if value == "5x5":
                    self.widgets['ERODMaskSize'].set_active(int(1))
                if value == "7x7":
                    self.widgets['ERODMaskSize'].set_active(int(2))

            if name == "iterations":
                self.widgets['ERODIterations'].set_value(int(value))

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/erode" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
    def load(cls, file_name):
        """
        This method loads the code_template from XML file.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """
        # load the code_template
        if os.path.exists(file_name) is False:
            return
        parser = XMLParser(file_name)

        if parser.getTag("HarpiaCodeTemplate") is None:
            return None

        try:
            code_template = CodeTemplate()
            code_template.name = parser.getTagAttr("HarpiaCodeTemplate",  "name")
            code_template.type = parser.getTagAttr("HarpiaCodeTemplate",  "type")
            code_template.description = parser.getTagAttr("HarpiaCodeTemplate",  "description")
            code_template.language = parser.getTagAttr("HarpiaCodeTemplate",  "language")
            code_template.extension = parser.getTagAttr("HarpiaCodeTemplate",  "extension")
            code_template.source = parser.getTagAttr("HarpiaCodeTemplate",  "source")
            code_template.command = parser.getTag("HarpiaCodeTemplate").getTag("command").getText()
            code_template.code = parser.getTag("HarpiaCodeTemplate").getTag("code").getText()
        except:
            return None

        if code_template.name == "":
            return None
        return code_template
Esempio n. 8
0
    def load(cls, diagram):

        # load the diagram
        parser = XMLParser(diagram.file_name)

        zoom = parser.getTag("harpia").getTag("zoom").getAttr("value")
        diagram.zoom = float(zoom)
        try:
            language = parser.getTag("harpia").getTag(
                "language").getAttr("value")
            diagram.language = language
        except:
            pass

        # new version load
        blocks = parser.getTag("harpia").getTag(
            "blocks").getChildTags("block")
        for block in blocks:
            block_type = block.getAttr("type")
            if block_type not in System.plugins:
                continue
            block_id = int(block.getAttr("id"))
            position = block.getTag("position")
            x = position.getAttr("x")
            y = position.getAttr("y")
            properties = block.getChildTags("property")
            props = {}
            for prop in properties:
                try:
                    props[prop.key] = prop.value
                except:
                    pass
            new_block = System.plugins[block_type]
            new_block.set_properties(props)
            new_block.id = block_id
            new_block.x = float(x)
            new_block.y = float(y)
            diagram.add_block(new_block)

        connections = parser.getTag("harpia").getTag(
            "connections").getChildTags("connection")
        for conn in connections:
            try:
                from_block = diagram.blocks[
                    int(conn.getAttr("from_block"))]
                to_block = diagram.blocks[int(conn.getAttr("to_block"))]
            except:
                continue
            from_block_out = int(conn.getAttr("from_out"))
            to_block_in = int(conn.getAttr("to_in"))
            diagram.start_connection(from_block, int(from_block_out) - 1)
            diagram.end_connection(to_block, int(to_block_in) - 1)
        return True
Esempio n. 9
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/save.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'SAVEFilename',
            'SAVEType',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_SAVEButtonSearch_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_save_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:

            if Property.name == "filename":
                self.widgets['SAVEFilename'].set_text(Property.value);
                #           if Property.name == "filetype":
                #               if Property.value == "png":
                #                   self.widgets['SAVEType'].set_active( int(0) )
                #               if Property.value == "jpeg":
                #                   self.widgets['SAVEType'].set_active( int(1) )

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/save" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 10
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/runCmd.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'cmdString',
            'BackgroundColor',
            'BorderColor',
            'HelpView',
            'enIsntZero'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_prop_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)


        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:
            if Property.name == "cmdString":
                self.widgets['cmdString'].set_text(Property.value)
            if Property.name == "enIsntZero":
                self.widgets['enIsntZero'].set_active(Property.value == "True")

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/runCmd" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 11
0
    def __init__(self, PropertiesXML, S2iBlockProperties):
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/show.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'SHOWDisable',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_show_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)


        # load properties values
        # There is no properties

        # load block state
        t_bState = self.m_oS2iBlockProperties.GetState()

        self.widgets['SHOWDisable'].set_active(not t_bState)

        self.configure()


        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/show" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 12
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/stereoCorr.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'maxDist',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_prop_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)


        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:
            if Property.name == "maxDist":
                self.widgets['maxDist'].set_value(float(Property.value));

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + 'help/stereoCorr' + _('_en.help'))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 13
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ["HARPIA_DATA_DIR"]

        filename = self.m_sDataDir + "glade/resize.ui"
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = ["Properties", "method", "BackgroundColor", "BorderColor", "HelpView"]

        handlers = [
            "on_cancel_clicked",
            "on_prop_confirm_clicked",
            "on_BackColorButton_clicked",
            "on_BorderColorButton_clicked",
        ]

        top_window = "Properties"

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:
            if Property.name == "method":
                if Property.value == "CV_INTER_NN":
                    self.widgets["method"].set_active(int(0))
                if Property.value == "CV_INTER_LINEAR":
                    self.widgets["method"].set_active(int(1))
                if Property.value == "CV_INTER_AREA":
                    self.widgets["method"].set_active(int(2))
                if Property.value == "CV_INTER_CUBIC":
                    self.widgets["method"].set_active(int(3))

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/checkCir" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets["HelpView"].set_buffer(t_oTextBuffer)
Esempio n. 14
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/plotHistogram.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'HISTImageType',
            'HISTLabelChannel',
            'HISTRadioR',
            'HISTRadioG',
            'HISTRadioB',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            # 'on_HISTRadioR_pressed',
            # 'on_HISTRadioG_pressed',
            # 'on_HISTRadioB_pressed',
            'on_HISTImageType_changed',
            'on_cancel_clicked',
            'on_histogram_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:

            if Property.name == "type":
                if Property.value == "allcolors":
                    self.widgets['HISTImageType'].set_active(int(0))
                if Property.value == "color":
                    self.widgets['HISTImageType'].set_active(int(1))
                self.on_HISTImageType_changed()

            if Property.name == "channel":
                if Property.value == "R":
                    self.widgets['HISTRadioR'].set_active(True);
                if Property.value == "G":
                    self.widgets['HISTRadioG'].set_active(True);
                if Property.value == "B":
                    self.widgets['HISTRadioB'].set_active(True);

        self.configure()


        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/plotHistogram" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 15
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]
            #print "PROCESS CHAIN",t_oS2iDiagram.GetProcessChain()
            #t_oProcessXML = bt.bind_string("<harpia>" + \
            #                               str(t_oGcDiagram.GetProcessChain()) + \
            #                               "</harpia>")
            #print len(list(t_oProcessXML.harpia.properties.childNodes))


            t_oProcessXML = XMLParser("<harpia>" + \
                                           str(t_oGcDiagram.GetProcessChain()) + \
                                           "</harpia>", fromString=True)
            #print t_oProcessXML

            graph_size = len(list(t_oProcessXML.getTag("harpia").getTag("properties").getTagChildren()))

            if graph_size > 1:
                blocks = t_oProcessXML.getTag("harpia").getTag("properties").getChildTags("block")
                for t_oBlockProperties in blocks:
                    block_properties = t_oBlockProperties.getChildTags("property")
                    if int(t_oBlockProperties.type) == 00:  # 00 = acquisition block
                        inputType = 'file'
                        for t_oProperty in block_properties:
                            if t_oProperty.name == 'type':
                                print t_oProperty.name
                                inputType = t_oProperty.value

                            ###Just in case we need to know if we are dealing with a live feed or not this early
                            # if inputType == 'video' or inputType == 'live':
                            #	#if not t_bIsLive:
                            #		#t_bIsLive = True

                            # adoção do paradigma monolítico.. nada de ficar mandando imagens por sockets!!
                            if t_oProperty.name == 'filename' and inputType == 'file':
                                t_oProperty.value = os.path.expanduser(t_oProperty.value)
                                t_oProperty.value = os.path.realpath(t_oProperty.value)
                                if (not os.path.exists(t_oProperty.value)):
                                    errMsg = _("Bad Filename: ") + t_oProperty.value
                                    print(errMsg)
                                    self.SetStatusMessage(errMsg, 0)
                                    return

                    if int(t_oBlockProperties.type) == 01:  # 01 => save image
                        for t_oProperty in block_properties:
                            if t_oProperty.name == 'filename':
                                t_oProperty.value = os.path.realpath(t_oProperty.value)


                    # seguindo o paradigma de não mandar mais nada.. vamos testar com o haar =]
                    # não vamos mandar mais nada mas vamos traduzir o path do haarCascade pra algo real
                    if int(t_oBlockProperties.type) == 610:  # 610 => haar detector... passando a cascade .xml
                        for t_oProperty in block_properties:
                            if t_oProperty.name == 'cascade_name':
                                t_oProperty.value = os.path.realpath(t_oProperty.value)
                                if (not os.path.exists(t_oProperty.value)):
                                    errMsg = _("Bad Filename: ") + t_oProperty.value
                                    print(errMsg)
                                    self.SetStatusMessage(errMsg, 0)
                                    return

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

                t_Sm = s2iSessionManager.s2iSessionManager()

                ## pegando o novo ID (criado pela s2iSessionManager) e passando para o s2idiagram
                self.m_oGcDiagrams[t_nPage].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!
                self.m_oGcDiagrams[t_nPage].set_error_log('')
                t_bEverythingOk = True
                for step in t_Sm.NewInstance(t_lsProcessChain):
                    if len(step) > 1:
                        if step[1] != '' and step[1] != None:
                            self.m_oGcDiagrams[t_nPage].append_error_log(step[1])
                            t_bEverythingOk = False
                    self.SetStatusMessage(step[0], t_bEverythingOk)
                    # self.widgets['StatusLabel'].set_text()
                    # print t_bEverythingOk
                    print step[0]
                # yield step#util caso se resolva usar a interface "lenta" ou se descubra como atualizar rapidamente a GUI

        # falta pegar o retorno!!!!!!
        self.UpdateStatus(7)
Esempio n. 16
0
    def __init__(self, Editor):
        """
            The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
        """

        self.m_oEditor = Editor
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        ## Imports the Glade file
        filename = self.m_sDataDir + 'glade/preferences.ui'

        # The widget list
        widget_list = ['preferences',
                       'PREFGridInt',
                       'PREFShowGrid',
                       'PREFServer',
                       'PREFPort']

        # Signal Handlers from the Buttons Confirm and Cancel
        handlers = ['on_preferences_confirm_clicked',
                    'on_preferences_cancel_clicked']

        # The Top window widget
        top_window = 'preferences'

        # Starts the GladeWindow, calling his __init__ method.
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # Set the preferences Icon
        self.widgets['preferences'].set_icon_from_file(self.m_sDataDir + "images/harpia_ave.png")

        ## The Homefolder where the preferences will be stored.
        if os.name == "nt":
            self.HomeFolder = os.path.join(os.path.expanduser("~"), "harpiaFiles\\")
        else:
            self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
        # self.HomeFolder = "/tmp/.harpia/"

        ## The Config File Path
        self.configfile = self.HomeFolder + "harpia.conf"

        # If the path do not exist, creates one.
        if not (os.path.exists(self.HomeFolder)):
            os.makedirs(self.HomeFolder, mode=0700)

        # If the path do not exist, creates one copyint the default harpia.conf.
        if not (os.path.exists(self.configfile)):
            shutil.copy("harpia.conf", self.HomeFolder)

        print "TESTE" + self.configfile
        ## A binderytool object, with the preferences stored
        self.m_oPreferencesXML = XMLParser(self.configfile)


        # ---------------------------------
        self.preferences = self.m_oPropertiesXML.getTag("harpia").getTag("editor").getChildTags("property")

        # Load Preferences
        for Preference in  self.preferences:

            if Preference.name == "show-grid":
                if Preference.value == "false":
                    state = "False"
                else:
                    state = "True"
                self.widgets['PREFShowGrid'].set_active(eval(state))

            if Preference.name == "grid-int":
                self.widgets['PREFGridInt'].set_value(int(Preference.value))

            if Preference.name == "server":
                self.widgets['PREFServer'].set_text(unicode(Preference.value))

            if Preference.name == "port":
                self.widgets['PREFPort'].set_value(int(Preference.value))
Esempio n. 17
0
    def __init__( self, PropertiesXML, S2iBlockProperties):
        
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']
        
        filename = self.m_sDataDir+'glade/fillRect.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'BackgroundColor',
            'BorderColor',
            'HelpView',
            'FILLFillColor'
            ]

        handlers = [
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_FILLFillColorButton_clicked',
            'on_cancel_clicked',
            'on_fill_confirm_clicked'
            ]

        top_window = 'Properties'

        self.m_oFillColor = [0,0,0]

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.configure()

        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")

        #load properties values
        for Property in self.block_properties:

            #self.widgets['FILLBackgroundColor'].modify_bg(gtk.STATE_NORMAL,t_oColor)
            name = Property.getAttr("name")
            value = Property.getAttr("value")
            
            if name == "red":
                self.m_oBackColor[0] = float(value)
                #self.widgets['FILLFillColor'].set_value( float(value) )
                self.m_oFillColor[0] = float(value)
                
            if name == "green":
                self.m_oBackColor[1] = float(value)
                self.m_oFillColor[1] = float(value)
                
            if name == "blue":
                self.m_oBackColor[2] = float(value)
                self.m_oFillColor[2] = float(value)

        t_nBackRed   = self.m_oBackColor[0] * 257
        t_nBackGreen = self.m_oBackColor[1] * 257
        t_nBackBlue  = self.m_oBackColor[2] * 257

        t_oBackColor = gtk.gdk.Color(red=int(t_nBackRed),green=int(t_nBackGreen),blue=int(t_nBackBlue))

        self.widgets['BackgroundColor'].modify_bg(gtk.STATE_NORMAL,t_oBackColor)
        
        #########################
        # Sets the Fill Color the same as the background color in inicialization
        self.widgets['FILLFillColor'].modify_bg(gtk.STATE_NORMAL,t_oBackColor)

        #load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir+"help/fillRect"+ _("_en.help"))
        
        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text( unicode( str( t_oS2iHelp.getTag("help").getTag("content").getTagContent()) ) )
    
        self.widgets['HelpView'].set_buffer( t_oTextBuffer )
Esempio n. 18
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/saveVideo.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'SAVEFilename',
            'SAVEType',
            'SAVEFrameRate',
            'BackgroundColor',
            'BorderColor',
            'codecSelection',
            'HelpView',
            'save_confirm'
        ]

        handlers = [
            'on_SAVEButtonSearch_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_save_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)


        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")

        for Property in self.block_properties:

            if Property.name == "filename":
                self.widgets['SAVEFilename'].set_text(os.path.expanduser(Property.value));
            if Property.name == "framerate":
                self.widgets['SAVEFrameRate'].set_value(float(Property.value));
            if Property.name == "codecSelection":
                if Property.value == "MPEG1":
                    self.widgets['codecSelection'].set_active(0)
                elif Property.value == "mjpeg":
                    self.widgets['codecSelection'].set_active(1)
                elif Property.value == "MPEG4.2":
                    self.widgets['codecSelection'].set_active(2)
                elif Property.value == "MPEG4.3":
                    self.widgets['codecSelection'].set_active(3)
                elif Property.value == "MPEG4":
                    self.widgets['codecSelection'].set_active(4)
                elif Property.value == "H263":
                    self.widgets['codecSelection'].set_active(5)
                elif Property.value == "H263I":
                    self.widgets['codecSelection'].set_active(6)
                elif Property.value == "FLV1":
                    self.widgets['codecSelection'].set_active(7)

                    #           if Property.name == "filetype":
                    #               if Property.value == "png":
                    #                   self.widgets['SAVEType'].set_active( int(0) )
                    #               if Property.value == "jpeg":
                    #                   self.widgets['SAVEType'].set_active( int(1) )

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/saveVideo" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 19
0
 def ReturnResponse(self):
     t_oResponse = XMLParser(self.HARPIARESPONSE, fromString=True)
     return t_oResponse
Esempio n. 20
0
def parseAndGenerate(dirName, XMLChain, installDirName):
    cleanGenerator()
    global g_bSaveVideo  # Passando todas as variaveis globais devolta ao default
    global g_bLive
    global g_bVideo
    global g_bCameras
    global g_bFrameRate
    global g_ShowCount
    g_ShowCount = 0
    g_bSaveVideo = []
    g_bVideo = []
    g_bCameras = []
    g_bFrameRate = 0.1
    g_bLive = False  # this shall be a list containing the "blockNumbers" for each live acquisition block; len(g_bLive) works just like it is now..
    yield [_("Starting Up Generator")]
    #doc = binderytools.bind_file(XMLChain)
    doc = XMLParser(XMLChain)
    ########################Create the blocks from XMLChain############################

    ##################################################################################
    #				in the future we may want to show some kind of progress bar..
    #							the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
    ##################################################################################
    # t_nBlockCount = 0.0
    # for block in (doc.harpia.properties.block):
    # t_nBlockCount += 1.0
    # t_nItCount = 0.0
    yield [_("Generating Code")]
    blocks = doc.getTag("harpia").getTag("properties").getChildTags("block")
    for blockIter in blocks:
        # print str(100.0*(t_nItCount/t_nBlockCount)) + "%"
        # t_nItCount += 1.0
        tmpBlock = blockTemplate()
        tmpBlock.blockType = blockIter.type
        tmpBlock.blockNumber = blockIter.id
        tmpBlock.properties = []
        tmpBlock.myConnections = []
        tmpBlock.outputsToSave = []
        try:
            block_properties = blockIter.getChildTags("property")
            for propIter in block_properties:
                tmpBlock.properties.append((propIter.name, propIter.value))
        except AttributeError:
            pass
        ID = tmpBlock.blockNumber
        tmpBlock.getBlockOutputTypes()

        net_blocks = doc.getTag("harpia").getTag("network").getChildTags("block")
        for block in net_blocks:
            if (block.id == ID and int(block.type) <> 10):
                portCount = -1
                outputs = block.getTag("outputs").getChildTags("output")
                for output in outputs:
                    tmpConnection = connection()
                    portCount += 1
                    if output.inBlock != '--':
                        tmpConnection.sourceOutput = output.id
                        tmpConnection.destinationInput = output.input
                        tmpConnection.destinationNumber = output.inBlock
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        # !!!!!!cpscotti type-oriented connections...!!!!!
                        tmpConnection.connType = tmpBlock.outTypes[int(tmpConnection.sourceOutput) - 1]
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        tmpBlock.myConnections.append(tmpConnection)
                    else:
                        tmpConnection.destinationNumber = '--'
                        tmpBlock.myConnections.append(tmpConnection)
                    try:
                        if output.grab == 'True':
                            tmpBlock.outputsToSave.append(output.id)
                    except:
                        pass
                    ###################################################################################
                    # ADDING TO EACH BLOCK OBJECT THE RESULTING CODE , THEN ADDING THE BLOCK IN A LIST #
                    ###################################################################################
                    ##Please, do not change the sequence
        tmpBlock.blockCodeWriter()
        tmpBlock.connectorCodeWriter()
        tmpBlock.saverCodeWriter()
        blockList.append(tmpBlock)
    ###################################################################################

    weights = []
    # Apply the weights on each connection of each block in listOfBlocks, then return a list with its connections
    def applyWeightsOnConnections(listOfBlocks):
        # def applyWeightsOnConnections(listOfBlocks,RollinList):
        ##For each block on listt:
        returnList = []
        for block in listOfBlocks:
            ##Put the connections on returnList
            for connection in block.myConnections:
                ##and apply the weight on this connection
                for tmpBlock in blockList:
                    if tmpBlock.blockNumber == connection.destinationNumber:
                        tmpBlock.weight += block.weight
                        if tmpBlock not in returnList:
                            # if tmpBlock not in RollinList:
                            returnList.append(tmpBlock)
                        # RollinList.append(tmpBlock)
        return returnList

    for block in blockList:
        # cpscotti..
        # if block.blockType == '00':
        if len(s2idirectory.block[int(block.blockType)]["InTypes"]) == 0 and s2idirectory.block[int(block.blockType)][
            "Outputs"] <> 0:
            tmpList = []
            # RollinPathList = []
            tmpList.append(block)
            # RollinPathList.append(block)
            organizedChain = applyWeightsOnConnections(tmpList)  # ,RollinPathList)
            while organizedChain <> []:
                organizedChain = applyWeightsOnConnections(organizedChain)  # ,RollinPathList)
            ###Recursive tests... future functionality
            # print "Start: "
            # for block in organizedChain:
            # print "\t"+str(block.blockNumber)

    biggestWeight = -1
    for block in blockList:
        if block.weight >= biggestWeight:
            biggestWeight = block.weight

    for activeWeight in range(biggestWeight):
        activeWeight += 1
        for block in blockList:
            if block.weight == activeWeight:
                arguments.append(block.functionArguments)
                images.append(block.imagesIO)
                functionCalls.append("//Weight: " + str(block.weight) + "\n")
                functionCalls.append(block.functionCall)
                deallocations.append(block.dealloc)
                outDeallocations.append(block.outDealloc)

    header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

#define PI 3.1415926535898
double rads(double degs)
{
	return (PI/180 * degs);
}
		"""
    global usesFindSquares
    if usesFindSquares == 1:
        header += r"""

//Routines to findSquares
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
{
		double dx1 = pt1->x - pt0->x;
		double dy1 = pt1->y - pt0->y;
		double dx2 = pt2->x - pt0->x;
		double dy2 = pt2->y - pt0->y;
		return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

CvSeq* findSquares4( IplImage* img, CvMemStorage* storage, int minArea, int maxArea)
{
		CvSeq* contours;
		int i, c, l, N = 11;
		int thresh = 50;
		CvSize sz = cvSize( img->width & -2, img->height & -2 );
		IplImage* timg = cvCloneImage( img ); // make a copy of input image
		IplImage* gray = cvCreateImage( sz, 8, 1 ); 
		IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
		IplImage* tgray;
		CvSeq* result;
		double s, t;

		if(minArea == -1)
			minArea = 0;
		if(maxArea == -1)
			maxArea = (img->width * img->height);

		CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
		

		cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
		
		// down-scale and upscale the image to filter out the noise
		cvPyrDown( timg, pyr, CV_GAUSSIAN_5x5 );
		cvPyrUp( pyr, timg, CV_GAUSSIAN_5x5 );
		tgray = cvCreateImage( sz, 8, 1 );
		
		// find squares in every color plane of the image
		for( c = 0; c < 3; c++ )



		{
				// extract the c-th color plane
				cvSetImageCOI( timg, c+1 );
				cvCopy( timg, tgray, 0 );
				for( l = 0; l < N; l++ )
				{
						if( l == 0 )
						{
								cvCanny( tgray, gray, 0, thresh, 5 );
								cvDilate( gray, gray, 0, 1 );
						}
						else
						{
								cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
						}
						cvFindContours( gray, storage, &contours, sizeof(CvContour),
								CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
						while( contours )
						{
								result = cvApproxPoly( contours, sizeof(CvContour), storage,
										CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
								if( result->total == 4 &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) > minArea &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) < maxArea &&
										cvCheckContourConvexity(result) )
								{
										s = 0;
										
										for( i = 0; i < 5; i++ )
										{
												if( i >= 2 )
												{
														t = fabs(angle(
														(CvPoint*)cvGetSeqElem( result, i ),
														(CvPoint*)cvGetSeqElem( result, i-2 ),
														(CvPoint*)cvGetSeqElem( result, i-1 )));
														s = s > t ? s : t;
												}
										}
										if( s < 0.3 )
												for( i = 0; i < 4; i++ )
														cvSeqPush( squares,
																(CvPoint*)cvGetSeqElem( result, i ));
								}
								contours = contours->h_next;
						}
				}
		}
		cvReleaseImage( &gray );
		cvReleaseImage( &pyr );
		cvReleaseImage( &tgray );
		cvReleaseImage( &timg );
		return squares;
}

double drawSquares( IplImage* cpy, CvSeq* squares )
{
		CvSeqReader reader;
		int i;
		cvStartReadSeq( squares, &reader, 0 );
		for( i = 0; i < squares->total; i += 4 )
		{
				CvPoint pt[4], *rect = pt;
				int count = 4;
				CV_READ_SEQ_ELEM( pt[0], reader );
				CV_READ_SEQ_ELEM( pt[1], reader );
				CV_READ_SEQ_ELEM( pt[2], reader );
				CV_READ_SEQ_ELEM( pt[3], reader );
				cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
		}
	return (double)squares->total;
}

//End of routines to findSquares

			"""
    global usesFindColor
    if usesFindColor == 1:
        header += r"""

int GetColor(IplImage * imagem, int x, int y)
{
	return   (int)(((uchar*)(imagem->imageData + imagem->widthStep*y))[x]);
}

void SetColor(IplImage * imagem, int x, int y, uchar color)
{
	((uchar*)(imagem->imageData + imagem->widthStep*y))[x] = color;
}


void CheckImg(IplImage * img, uchar c_value, uchar tolerance)
{
	uchar min,max;
	int y_It,x_It;
	if((int)c_value < (int)tolerance)
		tolerance = c_value;

	if(((int)c_value+(int)tolerance) > 255)
		tolerance = 255 - c_value;

	min = c_value - tolerance;
	max = c_value + tolerance;

	for(y_It=0;y_It<(img->height);y_It++)
		for(x_It=0;x_It<(img->width);x_It++)
		{
				uchar val;
				val = GetColor(img,x_It,y_It);
				if(val >= min && val <= max)
					SetColor(img,x_It,y_It,255);
				else
					SetColor(img,x_It,y_It,0);
		}
}

CvPoint GetCenter(IplImage * src, long int * nOfPts)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	long int posXsum;
	long int posYsum;
	int x_It, y_It;
	CvPoint Center;
	
	posXsum = 0;
	posYsum = 0;
	numOfMatchingPoints = 0;

	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				posXsum += x_It;
				posYsum += y_It;
				numOfMatchingPoints++;
			}

	if(numOfMatchingPoints > 0)
	{
		Center.x = (int)(posXsum/numOfMatchingPoints);
		Center.y = (int)(posYsum/numOfMatchingPoints);
	}
	else
		numOfMatchingPoints = -1;
// 	(*numOfPoints) = numOfMatchingPoints;
	if(nOfPts)
		*nOfPts = numOfMatchingPoints;

	return Center;
}


double dist22Points(CvPoint a, CvPoint b)
{
	int xD,yD;
	xD = a.x - b.x;
	yD = a.y - b.y;

	xD = (xD>0)?xD:-xD;
	yD = (yD>0)?yD:-yD;

	return (double)(xD*xD + yD*yD);
}

double GetVariance(IplImage * src,CvPoint center)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	double distSquaresSum;
	double variance;
	int x_It,y_It;

	numOfMatchingPoints = 0;
	distSquaresSum = 0.0;


	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				numOfMatchingPoints++;
				distSquaresSum += dist22Points(center,cvPoint(x_It,y_It));
			}

	if(numOfMatchingPoints)
		variance = distSquaresSum/numOfMatchingPoints;
	else
		variance = -1;


	return variance;
}

long int CheckForColor(IplImage * src, IplImage * dst, uchar * c_value, uchar * tolerance, CvPoint * pointCenter, double * variance)
{
	uchar B,B_T,G,G_T,R,R_T;
	int i;
	long int numOfPoints;
	CvPoint centro;
	IplImage * m_pChans[3] = {NULL,NULL,NULL};

	numOfPoints = 0;

	B = c_value[0];
	G = c_value[1];
	R = c_value[2];

	B_T = tolerance[0];
	G_T = tolerance[1];
	R_T = tolerance[2];

	for(i=0;i<3;i++)
		m_pChans[i] = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U, 1);

	cvSplit(src,m_pChans[0],m_pChans[1],m_pChans[2], NULL);

	CheckImg(m_pChans[0],B,B_T);
	CheckImg(m_pChans[1],G,G_T);
	CheckImg(m_pChans[2],R,R_T);

	cvAnd(m_pChans[0], m_pChans[1], dst, NULL );
	cvAnd(m_pChans[2], dst, dst, NULL );

	centro = GetCenter(dst,&numOfPoints);//,&numOfPoints);

	if(numOfPoints != -1)
		*variance = GetVariance(dst,centro);

	pointCenter->x = centro.x;
	pointCenter->y = centro.y;

	cvReleaseImage( &m_pChans[0] );
	cvReleaseImage( &m_pChans[1] );
	cvReleaseImage( &m_pChans[2] );

	return numOfPoints;
}
			"""
    header += "\nint main(int argc, char ** argv)\n{"

    declaration = "\n\t//declaration block\n"

    for x in arguments:
        declaration = declaration + x

    for x in images:
        declaration = declaration + x

    if g_bLive:
        declaration += \
            'int end;  end = 0; int key; \n'
        for aCapture in g_bVideo:
            declaration += 'CvCapture * block' + aCapture[0] + '_capture = NULL; \n IplImage * block' + aCapture[
                0] + '_frame = NULL; \n block' + aCapture[0] + '_capture = cvCreateFileCapture("' + aCapture[
                               1] + '"); \n'
        for aCamera in g_bCameras:
            declaration += 'CvCapture * block' + aCamera[0] + '_capture = NULL; \n IplImage * block' + aCamera[
                0] + '_frame = NULL; \n block' + aCamera[0] + '_capture = cvCaptureFromCAM(' + aCamera[1] + '); \n'
        declaration += 'while(!end) \n {\t \n'

        for aCapture in g_bVideo:
            declaration += 'cvGrabFrame (block' + aCapture[0] + '_capture); \n block' + aCapture[
                0] + '_frame = cvRetrieveFrame (block' + aCapture[0] + '_capture); \n'

        for aCamera in g_bCameras:
            declaration += 'cvGrabFrame (block' + aCamera[0] + '_capture); \n block' + aCamera[
                0] + '_frame = cvRetrieveFrame (block' + aCamera[0] + '_capture); \n'

    execution = "\n\t//execution block\n"
    for x in functionCalls:
        execution += x
    if g_ShowCount == 0:
        execution += '\n\tcvNamedWindow("Control Window",CV_WINDOW_AUTOSIZE );'
    if g_bLive:
        execution += '\n\tkey = cvWaitKey (' + str(int((1.0 / g_bFrameRate) * 1000.0)) + ');\n if(key != -1)\n end = 1;'

        deallocating = "\n\t//deallocation block\n"
        for x in deallocations:
            deallocating += x

        deallocating += "}"

    else:
        deallocating = "\n\t//deallocation block\n"

        for x in deallocations:
            deallocating += x

    closing = ""
    closing += "\n"
    for outDea in outDeallocations:
        closing += outDea
    if g_bLive:
        for aCapture in g_bVideo:
            closing += 'cvReleaseCapture(&block' + aCapture[0] + '_capture);\n'
        for aCamera in g_bCameras:
            closing += 'cvReleaseCapture(&block' + aCamera[0] + '_capture);\n'
    for vWriter in g_bSaveVideo:
        closing += 'cvReleaseVideoWriter(&block' + vWriter + '_vidWriter);\n'
    closing += "return 0;\n } //closing main()\n"


    # Final code assembly
    entireCode = header + declaration + execution + deallocating + closing

    yield [_("Saving Code")]
    # saving code file
    os.chdir(tmpDir + dirName)
    codeFilename = dirName + '.c'
    codeFile = open(codeFilename, 'w')
    codeFile.write(entireCode)
    codeFile.close()

    yield [_("Building Makefile")]
    # Assembly of "necessary" makefiles
    # ...windows..
    makeFilename = 'Makefile' + dirName + '.bat'
    makeFileEntry = '"' + installDirName + '\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[
                                                                                        :-2] + ".exe -lcv -lcxcore -lhighgui"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    # ...posix..
    makeFilename = 'Makefile.' + dirName
    makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:" + installDirName + "/lib/; export PKG_CONFIG_PATH=" + installDirName + "/lib/pkgconfig/;g++ " + codeFilename + " -o " + codeFilename[
                                                                                                                                                                                       :-2] + " `pkg-config --cflags --libs opencv`"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    yield [_("Compiling ...")]
    if os.name == "nt":
        i, o = os.popen4('Makefile' + dirName + '.bat')

        o.readlines()
        o.close()
        i.close()
        yield [_("Running ...")]
        i, o = os.popen4(codeFilename[:-2] + '.exe')

        ## ERROR LOG
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error = Error + element

        SetErrorLog(Error)

        o.readlines()
        o.close()
        i.close()
    else:
        i, o = os.popen4("sh " + makeFilename)

        ## appending compile errors too.. helps finding bugs! =]
        CompilingErrors = ''
        CerrorList = o.readlines()

        if len(CerrorList) <> 0:
            CompilingErrors += "Something was detected while compiling the source code.\n" + \
                               "There is a huge chance you've found a bug, please report to [email protected] \n" + \
                               "sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
                               "We appreciate your help!\n"
        for element in CerrorList:
            CompilingErrors += element

        o.close()
        i.close()
        if g_bLive:
            yield [_("Running, press any key (on the video output window) to terminate."), CompilingErrors]
        else:
            yield [_("Running ..."), CompilingErrors]

        # cpscotti, xunxo bunitinho pra nao travar a interface qndo tive rodando o live =]
        t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./" + codeFilename[:-2])
        t_oPrg.start()
        while t_oPrg.isAlive():
            t_oPrg.join(0.4)
            while gtk.events_pending():
                gtk.main_iteration(False)

        # fim do "xunx"

        ## ERROR LOG
        o = open("RunErrorLog", "r")
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error += element

        yield [_("Leaving.."), Error]
        SetErrorLog(CompilingErrors + Error)

        o.close()
        i.close()
Esempio n. 21
0
    def on_ProcessToolBar_clickedIneer(self):
        page = self.widgets['WorkArea'].get_current_page()
        if self.diagrams.has_key(page):
            self.UpdateStatus(0)

            diagram = self.diagrams[page]

            process_XML = XMLParser("<harpia>" + \
                                           str(DiagramControl(diagram).get_process_chain()) + \
                                           "</harpia>", fromString=True)

            graph_size = len(list(process_XML.getTag("harpia").getTag("properties").getTagChildren()))

            if graph_size > 1:
                blocks = process_XML.getTag("harpia").getTag("properties").getChildTags("block")
                for t_oBlockProperties in blocks:
                    block_properties = t_oBlockProperties.getChildTags("property")
                    if int(t_oBlockProperties.type) == 00:  # 00 = acquisition block
                        inputType = 'file'
                        for block_property in block_properties:
                            if block_property.name == 'type':
                                print block_property.name
                                inputType = block_property.value

                            # adoção do paradigma monolítico.. nada de ficar mandando imagens por sockets!!
                            if block_property.name == 'filename' and inputType == 'file':
                                block_property.value = os.path.expanduser(block_property.value)
                                block_property.value = os.path.realpath(block_property.value)
                                if (not os.path.exists(block_property.value)):
                                    errMsg = _("Bad Filename: ") + block_property.value
                                    print(errMsg)
                                    self.__set_status_message(errMsg, 0)
                                    return

                    if int(t_oBlockProperties.type) == 01:  # 01 => save image
                        for block_property in block_properties:
                            if block_property.name == 'filename':
                                block_property.value = os.path.realpath(block_property.value)


                    # seguindo o paradigma de não mandar mais nada.. vamos testar com o haar =]
                    # não vamos mandar mais nada mas vamos traduzir o path do haarCascade pra algo real
                    if int(t_oBlockProperties.type) == 610:  # 610 => haar detector... passando a cascade .xml
                        for block_property in block_properties:
                            if block_property.name == 'cascade_name':
                                block_property.value = os.path.realpath(block_property.value)
                                if (not os.path.exists(block_property.value)):
                                    errMsg = _("Bad Filename: ") + block_property.value
                                    print(errMsg)
                                    self.__set_status_message(errMsg, 0)
                                    return

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

                session_manager = s2iSessionManager.s2iSessionManager()

                ## pegando o novo ID (criado pela s2iSessionManager) e passando para o s2idiagram
                self.diagrams[page].set_session_id(session_manager.session_id)

                # step sempre sera uma lista.. primeiro elemento eh uma mensagem, segundo eh o erro.. caso exista erro.. passar para o s2idiagram tb!
                self.diagrams[page].set_error_log('')
                t_bEverythingOk = True
                for step in session_manager.new_instance(process_chain):
                    if len(step) > 1:
                        if step[1] != '' and step[1] != None:
                            self.diagrams[page].append_error_log(step[1])
                            t_bEverythingOk = False
                    self.__set_status_message(step[0], t_bEverythingOk)
                    # self.widgets['StatusLabel'].set_text()
                    # print t_bEverythingOk
                    print step[0]
                # yield step#util caso se resolva usar a interface "lenta" ou se descubra como atualizar rapidamente a GUI

        # falta pegar o retorno!!!!!!
        self.UpdateStatus(7)
Esempio n. 22
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/smooth.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'SMOOType',
            'SMOOParam1',
            'SMOOParam2',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_smooth_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values

        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")

        for Property in self.block_properties:
            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "type":
                if value == "CV_BLUR":
                    self.widgets['SMOOType'].set_active(int(0))
                if value == "CV_GAUSSIAN":
                    self.widgets['SMOOType'].set_active(int(1))
                if value == "CV_MEDIAN":
                    self.widgets['SMOOType'].set_active(int(2))
                    #   if Property.value == "CV_BILATERAL":
                    #       self.widgets['SMOOType'].set_active( int(4) )

            if name == "param1":
                self.widgets['SMOOParam1'].set_value(int(value))

            if name == "param2":
                self.widgets['SMOOParam2'].set_value(int(value))

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/smooth" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 23
0
def parseAndGenerate(dirName, XMLChain, installDirName):
    blockList = []
    outDeallocations = []
    functionCalls = []
    headers = []
    images = []
    deallocations = []
    global g_bLive
    g_bLive = []
    global g_bFrameRate
    g_bFrameRate = 0.1

    yield [_("Starting Up Generator")]
    doc = XMLParser(XMLChain)
    ########################Create the blocks from XMLChain############################
    ##################################################################################
    # in the future we may want to show some kind of progress bar..
    # the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
    ##################################################################################
    # t_nBlockCount = 0.0
    # for block in (doc.harpia.properties.block):
    # t_nBlockCount += 1.0
    # t_nItCount = 0.0
    yield [_("Generating Code")]
    blocks = doc.getTag("harpia").getTag("properties").getChildTags("block")
    for blockIter in blocks:
        tmpBlock = blockTemplate(blockIter.type, blockIter.id)
        try:
            block_properties = blockIter.getChildTags("property")
            for propIter in block_properties:
                tmpBlock.properties.append((propIter.name, propIter.value))
        except AttributeError:
            pass
        tmpBlock.getBlockOutputTypes()

        net_blocks = doc.getTag("harpia").getTag("network").getChildTags("block")
        for block in net_blocks:
            if (block.id != blockIter.id):
                continue
            outputs = block.getTag("outputs").getChildTags("output")
            for output in outputs:
                tmpConnection = connection()
                if output.inBlock != '--':
                    tmpConnection.sourceOutput = output.id
                    tmpConnection.destinationInput = output.input
                    tmpConnection.destinationNumber = output.inBlock
                    tmpConnection.connType = tmpBlock.outTypes[int(tmpConnection.sourceOutput) - 1]
                    tmpBlock.myConnections.append(tmpConnection)
                else:
                    tmpConnection.destinationNumber = '--'
                    tmpBlock.myConnections.append(tmpConnection)
        #######################################################################
        ##Please, do not change the sequence
        tmpBlock.blockCodeWriter()
        tmpBlock.connectorCodeWriter()
        blockList.append(tmpBlock)
        #######################################################################

    weights = []

    for block in blockList:
        if len(s2idirectory.block[int(block.blockType)]["InTypes"]) != 0:
            continue
        if len(s2idirectory.block[int(block.blockType)]["OutTypes"]) == 0:
            continue
        tmpList = []
        tmpList.append(block)
        organizedChain = __apply_weights_on_connections(tmpList, blockList)
        while organizedChain != []:
            organizedChain = __apply_weights_on_connections(organizedChain, blockList)

    biggestWeight = -1
    for block in blockList:
        if block.weight >= biggestWeight:
            biggestWeight = block.weight

    for activeWeight in range(biggestWeight):
        activeWeight += 1
        for block in blockList:
            if block.weight == activeWeight:
                headers.append(block.header)
                images.append(block.imagesIO)
                functionCalls.append("//Weight: " + str(block.weight) + "\n")
                functionCalls.append(block.functionCall)
                deallocations.append(block.dealloc)
                outDeallocations.append(block.outDealloc)

    header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

		"""

    # Adds only if it does not contains
    temp_header = []
    for header_code in headers:
        if header_code not in temp_header:
            temp_header.append(header_code)

    for header_code in temp_header:
        header += header_code

    header += "\nint main(int argc, char ** argv)\n{"

    declaration = "\n//declaration block\n"

    for image in images:
        declaration += image

    if len(g_bLive) > 0:
        declaration += 'int end = 0;\n'
        declaration += 'int key;\n'
        declaration += 'while(!end) \n {\t \n'

        for value in g_bLive:
            declaration += 'cvGrabFrame(block' + value[0] + '_capture);\n' + \
                'block' + value[0] + '_frame = cvRetrieveFrame (block' + value[0] + '_capture);\n'

    execution = "\n\t//execution block\n"
    for x in functionCalls:
        execution += x

    if len(g_bLive) > 0:
        execution += 'key = cvWaitKey (' + str(int((1.0 / g_bFrameRate) * 1000.0)) + ');\n'
        execution += 'if(key != -1)\n'
        execution += 'end = 1;\n'

    deallocating = "\n\t//deallocation block\n"
    for x in deallocations:
        deallocating += x

    if len(g_bLive) > 0:
        deallocating += "}"

    closing = ""
    closing += "\n"
    for outDea in outDeallocations:
        closing += outDea

    closing += "return 0;\n } //closing main()\n"


    # Final code assembly
    entireCode = header + declaration + execution + deallocating + closing


    yield [_("Saving Code")]
    # saving code file
    os.chdir(tmpDir + dirName)
    codeFilename = dirName + '.c'
    codeFile = open(codeFilename, 'w')
    codeFile.write(entireCode)
    codeFile.close()

    yield [_("Building Makefile")]
    # Assembly of "necessary" makefiles
    # ...windows..
    makeFilename = 'Makefile' + dirName + '.bat'
    makeFileEntry = '"' + installDirName + '\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[:-2] + ".exe -lcv -lcxcore -lhighgui"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    # ...posix..
    makeFilename = 'Makefile.' + dirName
    makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:" + installDirName + "/lib/;"
    makeFileEntry += "export PKG_CONFIG_PATH=" + installDirName + "/lib/pkgconfig/;"
    makeFileEntry += "g++ " + codeFilename + " -o " + codeFilename[:-2] + " `pkg-config --cflags --libs opencv`"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    yield [_("Compiling ...")]
    if os.name == "nt":
        i, o = os.popen4('Makefile' + dirName + '.bat')

        o.readlines()
        o.close()
        i.close()
        yield [_("Running ...")]
        i, o = os.popen4(codeFilename[:-2] + '.exe')

        ## ERROR LOG
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error = Error + element

        __set_error_log(Error)

        o.readlines()
        o.close()
        i.close()
    else:
        i, o = os.popen4("sh " + makeFilename)

        ## appending compile errors too.. helps finding bugs! =]
        CompilingErrors = ''
        CerrorList = o.readlines()

        if len(CerrorList) != 0:
            CompilingErrors += "Something was detected while compiling the source code.\n" + \
                               "There is a huge chance you've found a bug, please report to [email protected] \n" + \
                               "sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
                               "We appreciate your help!\n"
        for element in CerrorList:
            CompilingErrors += element

        o.close()
        i.close()

        if len(g_bLive) > 0:
            yield [_("Running, press any key (on the video output window) to terminate."), CompilingErrors]
        else:
            yield [_("Running ..."), CompilingErrors]

        t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./" + codeFilename[:-2])
        t_oPrg.start()
        while t_oPrg.isAlive():
            t_oPrg.join(0.4)
            while gtk.events_pending():
                gtk.main_iteration(False)

        ## ERROR LOG
        o = open("RunErrorLog", "r")
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error += element

        yield [_("Leaving.."), Error]
        __set_error_log(CompilingErrors + Error)

        o.close()
        i.close()
Esempio n. 24
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/threshold.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'THREThreshold',
            'THREThresholdType',
            'THRELabelMaxValue',
            'THREMaxValue',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_THREThresholdType_changed',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_threshold_confirm_clicked',
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        for Property in self.block_properties:

            if Property.name == "threshold":
                self.widgets['THREThreshold'].set_value(float(Property.value))

            if Property.name == "maxValue":
                self.widgets['THREMaxValue'].set_value(float(Property.value))

            if Property.name == "thresholdType":
                if Property.value == "CV_THRESH_BINARY":
                    self.widgets['THREThresholdType'].set_active(int(0))
                    self.on_THREThresholdType_changed()
                if Property.value == "CV_THRESH_BINARY_INV":
                    self.widgets['THREThresholdType'].set_active(int(1))
                    self.on_THREThresholdType_changed()
                if Property.value == "CV_THRESH_TRUNC":
                    self.widgets['THREThresholdType'].set_active(int(2))
                    self.on_THREThresholdType_changed()
                if Property.value == "CV_THRESH_TOZERO":
                    self.widgets['THREThresholdType'].set_active(int(3))
                    self.on_THREThresholdType_changed()
                if Property.value == "CV_THRESH_TOZERO_INV":
                    self.widgets['THREThresholdType'].set_active(int(4))
                    self.on_THREThresholdType_changed()

        self.configure()

        # load help text

        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/threshold" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 25
0
def parseAndGenerate(dirName, XMLChain, installDirName):
    cleanGenerator()
    global g_bSaveVideo  # Passando todas as variaveis globais devolta ao default
    global g_bLive
    global g_bVideo
    global g_bCameras
    global g_bFrameRate
    global g_ShowCount
    g_ShowCount = 0
    g_bSaveVideo = []
    g_bVideo = []
    g_bCameras = []
    g_bFrameRate = 0.1
    g_bLive = False  # this shall be a list containing the "blockNumbers" for each live acquisition block; len(g_bLive) works just like it is now..
    yield [_("Starting Up Generator")]
    #doc = binderytools.bind_file(XMLChain)
    doc = XMLParser(XMLChain)
    ########################Create the blocks from XMLChain############################

    ##################################################################################
    #				in the future we may want to show some kind of progress bar..
    #							the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
    ##################################################################################
    # t_nBlockCount = 0.0
    # for block in (doc.harpia.properties.block):
    # t_nBlockCount += 1.0
    # t_nItCount = 0.0
    yield [_("Generating Code")]
    blocks = doc.getTag("harpia").getTag("properties").getChildTags("block")
    for blockIter in blocks:
        # print str(100.0*(t_nItCount/t_nBlockCount)) + "%"
        # t_nItCount += 1.0
        tmpBlock = blockTemplate()
        tmpBlock.blockType = blockIter.type
        tmpBlock.blockNumber = blockIter.id
        tmpBlock.properties = []
        tmpBlock.myConnections = []
        tmpBlock.outputsToSave = []
        try:
            block_properties = blockIter.getChildTags("property")
            for propIter in block_properties:
                tmpBlock.properties.append((propIter.name, propIter.value))
        except AttributeError:
            pass
        ID = tmpBlock.blockNumber
        tmpBlock.getBlockOutputTypes()

        net_blocks = doc.getTag("harpia").getTag("network").getChildTags(
            "block")
        for block in net_blocks:
            if (block.id == ID and int(block.type) <> 10):
                portCount = -1
                outputs = block.getTag("outputs").getChildTags("output")
                for output in outputs:
                    tmpConnection = connection()
                    portCount += 1
                    if output.inBlock != '--':
                        tmpConnection.sourceOutput = output.id
                        tmpConnection.destinationInput = output.input
                        tmpConnection.destinationNumber = output.inBlock
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        # !!!!!!cpscotti type-oriented connections...!!!!!
                        tmpConnection.connType = tmpBlock.outTypes[
                            int(tmpConnection.sourceOutput) - 1]
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        tmpBlock.myConnections.append(tmpConnection)
                    else:
                        tmpConnection.destinationNumber = '--'
                        tmpBlock.myConnections.append(tmpConnection)
                    try:
                        if output.grab == 'True':
                            tmpBlock.outputsToSave.append(output.id)
                    except:
                        pass
                    ###################################################################################
                    # ADDING TO EACH BLOCK OBJECT THE RESULTING CODE , THEN ADDING THE BLOCK IN A LIST #
                    ###################################################################################
                    ##Please, do not change the sequence
        tmpBlock.blockCodeWriter()
        tmpBlock.connectorCodeWriter()
        tmpBlock.saverCodeWriter()
        blockList.append(tmpBlock)
    ###################################################################################

    weights = []

    # Apply the weights on each connection of each block in listOfBlocks, then return a list with its connections
    def applyWeightsOnConnections(listOfBlocks):
        # def applyWeightsOnConnections(listOfBlocks,RollinList):
        ##For each block on listt:
        returnList = []
        for block in listOfBlocks:
            ##Put the connections on returnList
            for connection in block.myConnections:
                ##and apply the weight on this connection
                for tmpBlock in blockList:
                    if tmpBlock.blockNumber == connection.destinationNumber:
                        tmpBlock.weight += block.weight
                        if tmpBlock not in returnList:
                            # if tmpBlock not in RollinList:
                            returnList.append(tmpBlock)
                        # RollinList.append(tmpBlock)
        return returnList

    for block in blockList:
        # cpscotti..
        # if block.blockType == '00':
        if len(s2idirectory.block[int(
                block.blockType)]["InTypes"]) == 0 and len(
                    s2idirectory.block[int(block.blockType)]["OutTypes"]) <> 0:
            tmpList = []
            # RollinPathList = []
            tmpList.append(block)
            # RollinPathList.append(block)
            organizedChain = applyWeightsOnConnections(
                tmpList)  # ,RollinPathList)
            while organizedChain <> []:
                organizedChain = applyWeightsOnConnections(
                    organizedChain)  # ,RollinPathList)
            ###Recursive tests... future functionality
            # print "Start: "
            # for block in organizedChain:
            # print "\t"+str(block.blockNumber)

    biggestWeight = -1
    for block in blockList:
        if block.weight >= biggestWeight:
            biggestWeight = block.weight

    for activeWeight in range(biggestWeight):
        activeWeight += 1
        for block in blockList:
            if block.weight == activeWeight:
                arguments.append(block.functionArguments)
                images.append(block.imagesIO)
                functionCalls.append("//Weight: " + str(block.weight) + "\n")
                functionCalls.append(block.functionCall)
                deallocations.append(block.dealloc)
                outDeallocations.append(block.outDealloc)

    header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

#define PI 3.1415926535898
double rads(double degs)
{
	return (PI/180 * degs);
}
		"""
    global usesFindSquares
    if usesFindSquares == 1:
        header += r"""

//Routines to findSquares
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
{
		double dx1 = pt1->x - pt0->x;
		double dy1 = pt1->y - pt0->y;
		double dx2 = pt2->x - pt0->x;
		double dy2 = pt2->y - pt0->y;
		return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

CvSeq* findSquares4( IplImage* img, CvMemStorage* storage, int minArea, int maxArea)
{
		CvSeq* contours;
		int i, c, l, N = 11;
		int thresh = 50;
		CvSize sz = cvSize( img->width & -2, img->height & -2 );
		IplImage* timg = cvCloneImage( img ); // make a copy of input image
		IplImage* gray = cvCreateImage( sz, 8, 1 ); 
		IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
		IplImage* tgray;
		CvSeq* result;
		double s, t;

		if(minArea == -1)
			minArea = 0;
		if(maxArea == -1)
			maxArea = (img->width * img->height);

		CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
		

		cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
		
		// down-scale and upscale the image to filter out the noise
		cvPyrDown( timg, pyr, CV_GAUSSIAN_5x5 );
		cvPyrUp( pyr, timg, CV_GAUSSIAN_5x5 );
		tgray = cvCreateImage( sz, 8, 1 );
		
		// find squares in every color plane of the image
		for( c = 0; c < 3; c++ )



		{
				// extract the c-th color plane
				cvSetImageCOI( timg, c+1 );
				cvCopy( timg, tgray, 0 );
				for( l = 0; l < N; l++ )
				{
						if( l == 0 )
						{
								cvCanny( tgray, gray, 0, thresh, 5 );
								cvDilate( gray, gray, 0, 1 );
						}
						else
						{
								cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
						}
						cvFindContours( gray, storage, &contours, sizeof(CvContour),
								CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
						while( contours )
						{
								result = cvApproxPoly( contours, sizeof(CvContour), storage,
										CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
								if( result->total == 4 &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) > minArea &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) < maxArea &&
										cvCheckContourConvexity(result) )
								{
										s = 0;
										
										for( i = 0; i < 5; i++ )
										{
												if( i >= 2 )
												{
														t = fabs(angle(
														(CvPoint*)cvGetSeqElem( result, i ),
														(CvPoint*)cvGetSeqElem( result, i-2 ),
														(CvPoint*)cvGetSeqElem( result, i-1 )));
														s = s > t ? s : t;
												}
										}
										if( s < 0.3 )
												for( i = 0; i < 4; i++ )
														cvSeqPush( squares,
																(CvPoint*)cvGetSeqElem( result, i ));
								}
								contours = contours->h_next;
						}
				}
		}
		cvReleaseImage( &gray );
		cvReleaseImage( &pyr );
		cvReleaseImage( &tgray );
		cvReleaseImage( &timg );
		return squares;
}

double drawSquares( IplImage* cpy, CvSeq* squares )
{
		CvSeqReader reader;
		int i;
		cvStartReadSeq( squares, &reader, 0 );
		for( i = 0; i < squares->total; i += 4 )
		{
				CvPoint pt[4], *rect = pt;
				int count = 4;
				CV_READ_SEQ_ELEM( pt[0], reader );
				CV_READ_SEQ_ELEM( pt[1], reader );
				CV_READ_SEQ_ELEM( pt[2], reader );
				CV_READ_SEQ_ELEM( pt[3], reader );
				cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
		}
	return (double)squares->total;
}

//End of routines to findSquares

			"""
    global usesFindColor
    if usesFindColor == 1:
        header += r"""

int GetColor(IplImage * imagem, int x, int y)
{
	return   (int)(((uchar*)(imagem->imageData + imagem->widthStep*y))[x]);
}

void SetColor(IplImage * imagem, int x, int y, uchar color)
{
	((uchar*)(imagem->imageData + imagem->widthStep*y))[x] = color;
}


void CheckImg(IplImage * img, uchar c_value, uchar tolerance)
{
	uchar min,max;
	int y_It,x_It;
	if((int)c_value < (int)tolerance)
		tolerance = c_value;

	if(((int)c_value+(int)tolerance) > 255)
		tolerance = 255 - c_value;

	min = c_value - tolerance;
	max = c_value + tolerance;

	for(y_It=0;y_It<(img->height);y_It++)
		for(x_It=0;x_It<(img->width);x_It++)
		{
				uchar val;
				val = GetColor(img,x_It,y_It);
				if(val >= min && val <= max)
					SetColor(img,x_It,y_It,255);
				else
					SetColor(img,x_It,y_It,0);
		}
}

CvPoint GetCenter(IplImage * src, long int * nOfPts)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	long int posXsum;
	long int posYsum;
	int x_It, y_It;
	CvPoint Center;
	
	posXsum = 0;
	posYsum = 0;
	numOfMatchingPoints = 0;

	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				posXsum += x_It;
				posYsum += y_It;
				numOfMatchingPoints++;
			}

	if(numOfMatchingPoints > 0)
	{
		Center.x = (int)(posXsum/numOfMatchingPoints);
		Center.y = (int)(posYsum/numOfMatchingPoints);
	}
	else
		numOfMatchingPoints = -1;
// 	(*numOfPoints) = numOfMatchingPoints;
	if(nOfPts)
		*nOfPts = numOfMatchingPoints;

	return Center;
}


double dist22Points(CvPoint a, CvPoint b)
{
	int xD,yD;
	xD = a.x - b.x;
	yD = a.y - b.y;

	xD = (xD>0)?xD:-xD;
	yD = (yD>0)?yD:-yD;

	return (double)(xD*xD + yD*yD);
}

double GetVariance(IplImage * src,CvPoint center)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	double distSquaresSum;
	double variance;
	int x_It,y_It;

	numOfMatchingPoints = 0;
	distSquaresSum = 0.0;


	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				numOfMatchingPoints++;
				distSquaresSum += dist22Points(center,cvPoint(x_It,y_It));
			}

	if(numOfMatchingPoints)
		variance = distSquaresSum/numOfMatchingPoints;
	else
		variance = -1;


	return variance;
}

long int CheckForColor(IplImage * src, IplImage * dst, uchar * c_value, uchar * tolerance, CvPoint * pointCenter, double * variance)
{
	uchar B,B_T,G,G_T,R,R_T;
	int i;
	long int numOfPoints;
	CvPoint centro;
	IplImage * m_pChans[3] = {NULL,NULL,NULL};

	numOfPoints = 0;

	B = c_value[0];
	G = c_value[1];
	R = c_value[2];

	B_T = tolerance[0];
	G_T = tolerance[1];
	R_T = tolerance[2];

	for(i=0;i<3;i++)
		m_pChans[i] = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U, 1);

	cvSplit(src,m_pChans[0],m_pChans[1],m_pChans[2], NULL);

	CheckImg(m_pChans[0],B,B_T);
	CheckImg(m_pChans[1],G,G_T);
	CheckImg(m_pChans[2],R,R_T);

	cvAnd(m_pChans[0], m_pChans[1], dst, NULL );
	cvAnd(m_pChans[2], dst, dst, NULL );

	centro = GetCenter(dst,&numOfPoints);//,&numOfPoints);

	if(numOfPoints != -1)
		*variance = GetVariance(dst,centro);

	pointCenter->x = centro.x;
	pointCenter->y = centro.y;

	cvReleaseImage( &m_pChans[0] );
	cvReleaseImage( &m_pChans[1] );
	cvReleaseImage( &m_pChans[2] );

	return numOfPoints;
}
			"""
    header += "\nint main(int argc, char ** argv)\n{"

    declaration = "\n\t//declaration block\n"

    for x in arguments:
        declaration = declaration + x

    for x in images:
        declaration = declaration + x

    if g_bLive:
        declaration += \
            'int end;  end = 0; int key; \n'
        for aCapture in g_bVideo:
            declaration += 'CvCapture * block' + aCapture[
                0] + '_capture = NULL; \n IplImage * block' + aCapture[
                    0] + '_frame = NULL; \n block' + aCapture[
                        0] + '_capture = cvCreateFileCapture("' + aCapture[
                            1] + '"); \n'
        for aCamera in g_bCameras:
            declaration += 'CvCapture * block' + aCamera[
                0] + '_capture = NULL; \n IplImage * block' + aCamera[
                    0] + '_frame = NULL; \n block' + aCamera[
                        0] + '_capture = cvCaptureFromCAM(' + aCamera[
                            1] + '); \n'
        declaration += 'while(!end) \n {\t \n'

        for aCapture in g_bVideo:
            declaration += 'cvGrabFrame (block' + aCapture[
                0] + '_capture); \n block' + aCapture[
                    0] + '_frame = cvRetrieveFrame (block' + aCapture[
                        0] + '_capture); \n'

        for aCamera in g_bCameras:
            declaration += 'cvGrabFrame (block' + aCamera[
                0] + '_capture); \n block' + aCamera[
                    0] + '_frame = cvRetrieveFrame (block' + aCamera[
                        0] + '_capture); \n'

    execution = "\n\t//execution block\n"
    for x in functionCalls:
        execution += x
    if g_ShowCount == 0:
        execution += '\n\tcvNamedWindow("Control Window",CV_WINDOW_AUTOSIZE );'
    if g_bLive:
        execution += '\n\tkey = cvWaitKey (' + str(
            int((1.0 / g_bFrameRate) *
                1000.0)) + ');\n if(key != -1)\n end = 1;'

        deallocating = "\n\t//deallocation block\n"
        for x in deallocations:
            deallocating += x

        deallocating += "}"

    else:
        deallocating = "\n\t//deallocation block\n"

        for x in deallocations:
            deallocating += x

    closing = ""
    closing += "\n"
    for outDea in outDeallocations:
        closing += outDea
    if g_bLive:
        for aCapture in g_bVideo:
            closing += 'cvReleaseCapture(&block' + aCapture[0] + '_capture);\n'
        for aCamera in g_bCameras:
            closing += 'cvReleaseCapture(&block' + aCamera[0] + '_capture);\n'
    for vWriter in g_bSaveVideo:
        closing += 'cvReleaseVideoWriter(&block' + vWriter + '_vidWriter);\n'
    closing += "return 0;\n } //closing main()\n"

    # Final code assembly
    entireCode = header + declaration + execution + deallocating + closing

    yield [_("Saving Code")]
    # saving code file
    os.chdir(tmpDir + dirName)
    codeFilename = dirName + '.c'
    codeFile = open(codeFilename, 'w')
    codeFile.write(entireCode)
    codeFile.close()

    yield [_("Building Makefile")]
    # Assembly of "necessary" makefiles
    # ...windows..
    makeFilename = 'Makefile' + dirName + '.bat'
    makeFileEntry = '"' + installDirName + '\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[:
                                                                                                     -2] + ".exe -lcv -lcxcore -lhighgui"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    # ...posix..
    makeFilename = 'Makefile.' + dirName
    makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:" + installDirName + "/lib/; export PKG_CONFIG_PATH=" + installDirName + "/lib/pkgconfig/;g++ " + codeFilename + " -o " + codeFilename[:
                                                                                                                                                                                                    -2] + " `pkg-config --cflags --libs opencv`"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    yield [_("Compiling ...")]
    if os.name == "nt":
        i, o = os.popen4('Makefile' + dirName + '.bat')

        o.readlines()
        o.close()
        i.close()
        yield [_("Running ...")]
        i, o = os.popen4(codeFilename[:-2] + '.exe')

        ## ERROR LOG
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error = Error + element

        SetErrorLog(Error)

        o.readlines()
        o.close()
        i.close()
    else:
        i, o = os.popen4("sh " + makeFilename)

        ## appending compile errors too.. helps finding bugs! =]
        CompilingErrors = ''
        CerrorList = o.readlines()

        if len(CerrorList) <> 0:
            CompilingErrors += "Something was detected while compiling the source code.\n" + \
                               "There is a huge chance you've found a bug, please report to [email protected] \n" + \
                               "sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
                               "We appreciate your help!\n"
        for element in CerrorList:
            CompilingErrors += element

        o.close()
        i.close()
        if g_bLive:
            yield [
                _("Running, press any key (on the video output window) to terminate."
                  ), CompilingErrors
            ]
        else:
            yield [_("Running ..."), CompilingErrors]

        # cpscotti, xunxo bunitinho pra nao travar a interface qndo tive rodando o live =]
        t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./" +
                        codeFilename[:-2])
        t_oPrg.start()
        while t_oPrg.isAlive():
            t_oPrg.join(0.4)
            while gtk.events_pending():
                gtk.main_iteration(False)

        # fim do "xunx"

        ## ERROR LOG
        o = open("RunErrorLog", "r")
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error += element

        yield [_("Leaving.."), Error]
        SetErrorLog(CompilingErrors + Error)

        o.close()
        i.close()
Esempio n. 26
0
def parseAndGenerate(dirName, XMLChain, installDirName):
    blockList = []
    outDeallocations = []
    functionCalls = []
    headers = []
    images = []
    deallocations = []
    global g_bLive
    g_bLive = []
    global g_bFrameRate
    g_bFrameRate = 0.1

    yield [_("Starting Up Generator")]
    doc = XMLParser(XMLChain)
    ########################Create the blocks from XMLChain############################
    ##################################################################################
    # in the future we may want to show some kind of progress bar..
    # the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
    ##################################################################################
    # t_nBlockCount = 0.0
    # for block in (doc.harpia.properties.block):
    # t_nBlockCount += 1.0
    # t_nItCount = 0.0
    yield [_("Generating Code")]
    blocks = doc.getTag("harpia").getTag("properties").getChildTags("block")
    for blockIter in blocks:
        tmpBlock = blockTemplate(blockIter.type, blockIter.id)
        try:
            block_properties = blockIter.getChildTags("property")
            for propIter in block_properties:
                tmpBlock.properties.append((propIter.name, propIter.value))
        except AttributeError:
            pass
        tmpBlock.getBlockOutputTypes()

        net_blocks = doc.getTag("harpia").getTag("network").getChildTags(
            "block")
        for block in net_blocks:
            if (block.id != blockIter.id):
                continue
            outputs = block.getTag("outputs").getChildTags("output")
            for output in outputs:
                tmpConnection = connection()
                if output.inBlock != '--':
                    tmpConnection.sourceOutput = output.id
                    tmpConnection.destinationInput = output.input
                    tmpConnection.destinationNumber = output.inBlock
                    tmpConnection.connType = tmpBlock.outTypes[
                        int(tmpConnection.sourceOutput) - 1]
                    tmpBlock.myConnections.append(tmpConnection)
                else:
                    tmpConnection.destinationNumber = '--'
                    tmpBlock.myConnections.append(tmpConnection)
        #######################################################################
        ##Please, do not change the sequence
        tmpBlock.blockCodeWriter()
        tmpBlock.connectorCodeWriter()
        blockList.append(tmpBlock)
        #######################################################################

    weights = []

    for block in blockList:
        if len(s2idirectory.block[int(block.blockType)]["InTypes"]) != 0:
            continue
        if len(s2idirectory.block[int(block.blockType)]["OutTypes"]) == 0:
            continue
        tmpList = []
        tmpList.append(block)
        organizedChain = __apply_weights_on_connections(tmpList, blockList)
        while organizedChain != []:
            organizedChain = __apply_weights_on_connections(
                organizedChain, blockList)

    biggestWeight = -1
    for block in blockList:
        if block.weight >= biggestWeight:
            biggestWeight = block.weight

    for activeWeight in range(biggestWeight):
        activeWeight += 1
        for block in blockList:
            if block.weight == activeWeight:
                headers.append(block.header)
                images.append(block.imagesIO)
                functionCalls.append("//Weight: " + str(block.weight) + "\n")
                functionCalls.append(block.functionCall)
                deallocations.append(block.dealloc)
                outDeallocations.append(block.outDealloc)

    header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

		"""

    # Adds only if it does not contains
    temp_header = []
    for header_code in headers:
        if header_code not in temp_header:
            temp_header.append(header_code)

    for header_code in temp_header:
        header += header_code

    header += "\nint main(int argc, char ** argv)\n{"

    declaration = "\n//declaration block\n"

    for image in images:
        declaration += image

    if len(g_bLive) > 0:
        declaration += 'int end = 0;\n'
        declaration += 'int key;\n'
        declaration += 'while(!end) \n {\t \n'

        for value in g_bLive:
            declaration += 'cvGrabFrame(block' + value[0] + '_capture);\n' + \
                'block' + value[0] + '_frame = cvRetrieveFrame (block' + value[0] + '_capture);\n'

    execution = "\n\t//execution block\n"
    for x in functionCalls:
        execution += x

    if len(g_bLive) > 0:
        execution += 'key = cvWaitKey (' + str(
            int((1.0 / g_bFrameRate) * 1000.0)) + ');\n'
        execution += 'if(key != -1)\n'
        execution += 'end = 1;\n'

    deallocating = "\n\t//deallocation block\n"
    for x in deallocations:
        deallocating += x

    if len(g_bLive) > 0:
        deallocating += "}"

    closing = ""
    closing += "\n"
    for outDea in outDeallocations:
        closing += outDea

    closing += "return 0;\n } //closing main()\n"

    # Final code assembly
    entireCode = header + declaration + execution + deallocating + closing

    yield [_("Saving Code")]
    # saving code file
    os.chdir(tmpDir + dirName)
    codeFilename = dirName + '.c'
    codeFile = open(codeFilename, 'w')
    codeFile.write(entireCode)
    codeFile.close()

    yield [_("Building Makefile")]
    # Assembly of "necessary" makefiles
    # ...windows..
    makeFilename = 'Makefile' + dirName + '.bat'
    makeFileEntry = '"' + installDirName + '\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[:
                                                                                                     -2] + ".exe -lcv -lcxcore -lhighgui"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    # ...posix..
    makeFilename = 'Makefile.' + dirName
    makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:" + installDirName + "/lib/;"
    makeFileEntry += "export PKG_CONFIG_PATH=" + installDirName + "/lib/pkgconfig/;"
    makeFileEntry += "g++ " + codeFilename + " -o " + codeFilename[:-2] + " `pkg-config --cflags --libs opencv`"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    yield [_("Compiling ...")]
    if os.name == "nt":
        i, o = os.popen4('Makefile' + dirName + '.bat')

        o.readlines()
        o.close()
        i.close()
        yield [_("Running ...")]
        i, o = os.popen4(codeFilename[:-2] + '.exe')

        ## ERROR LOG
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error = Error + element

        __set_error_log(Error)

        o.readlines()
        o.close()
        i.close()
    else:
        i, o = os.popen4("sh " + makeFilename)

        ## appending compile errors too.. helps finding bugs! =]
        CompilingErrors = ''
        CerrorList = o.readlines()

        if len(CerrorList) != 0:
            CompilingErrors += "Something was detected while compiling the source code.\n" + \
                               "There is a huge chance you've found a bug, please report to [email protected] \n" + \
                               "sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
                               "We appreciate your help!\n"
        for element in CerrorList:
            CompilingErrors += element

        o.close()
        i.close()

        if len(g_bLive) > 0:
            yield [
                _("Running, press any key (on the video output window) to terminate."
                  ), CompilingErrors
            ]
        else:
            yield [_("Running ..."), CompilingErrors]

        t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./" +
                        codeFilename[:-2])
        t_oPrg.start()
        while t_oPrg.isAlive():
            t_oPrg.join(0.4)
            while gtk.events_pending():
                gtk.main_iteration(False)

        ## ERROR LOG
        o = open("RunErrorLog", "r")
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error += element

        yield [_("Leaving.."), Error]
        __set_error_log(CompilingErrors + Error)

        o.close()
        i.close()
Esempio n. 27
0
    def load(cls):
        """
        This method loads the diagram.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """
        prefs = Preferences()
        from harpia.system import System
        file_name = System.get_user_dir() + "/" + prefs.conf_file_path
        file_name = os.path.expanduser(file_name)
        if os.path.exists(file_name) is False:
            return prefs
        parser = XMLParser(file_name)

        if parser.getTag("HarpiaProperties") is None:
            return prefs

        try:
            prefs.default_directory = parser.getTagAttr("HarpiaProperties",
                        "default_directory")
            prefs.default_filename = parser.getTagAttr("HarpiaProperties",
                        "default_filename")
            prefs.grid = int(parser.getTagAttr("HarpiaProperties","grid"))
            prefs.width = int(parser.getTagAttr("HarpiaProperties","width"))
            prefs.height = int(parser.getTagAttr("HarpiaProperties",
                        "height"))
            prefs.hpaned_work_area = int(parser.getTagAttr("HarpiaProperties",
                        "hpaned_work_area"))
            prefs.vpaned_bottom = int(parser.getTagAttr("HarpiaProperties",
                        "vpaned_bottom"))
            prefs.vpaned_left = int(parser.getTagAttr("HarpiaProperties",
                        "vpaned_left"))

            files = parser.getTag("HarpiaProperties").getTag(
                        "recent_files").getChildTags("name")
            for file_name in files:
                prefs.recent_files.append(file_name.getAttr("value"))
        except:
            pass
        return prefs
Esempio n. 28
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/findColor.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            '_R',
            '_G',
            '_B',
            '_R_T',
            '_G_T',
            '_B_T',
            'BackgroundColor',
            'BorderColor',
            'HelpView',
            'prop_confirm'
        ]

        handlers = [
            'on_cancel_clicked',
            'on_prop_confirm_clicked',
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")

        for Property in self.block_properties:
            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "_R":
                self.widgets['_R'].set_value(float(value));
            if name == "_G":
                self.widgets['_G'].set_value(float(value));
            if name == "_B":
                self.widgets['_B'].set_value(float(value));
            if name == "_R_T":
                self.widgets['_R_T'].set_value(float(value));
            if name == "_G_T":
                self.widgets['_G_T'].set_value(float(value));
            if name == "_B_T":
                self.widgets['_B_T'].set_value(float(value));

                # if Property.name == "isFilling":
                # if Property.value == "true":
                # self.widgets['isFilling'].set_active( True );
                # else:
                # self.widgets['isFilling'].set_active( False );

                # if Property.name == "isScalling":
                # if Property.value == "true":
                # self.widgets['isScalling'].set_active( True );
                # else:
                # self.widgets['isScalling'].set_active( False );

                # if Property.name == "isCenter":
                # if Property.value == "true":
                # self.widgets['isAtCenter'].set_active( True );
                # else:
                # self.widgets['isAtPoint'].set_active( True );

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + 'help/findColor' + _('_en.help'))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 29
0
    def save(cls, prefs):
        """
        This method save the diagram.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """
        parser = XMLParser()
        parser.addTag('HarpiaProperties')
        parser.setTagAttr('HarpiaProperties','default_directory',
                prefs.default_directory)
        parser.setTagAttr('HarpiaProperties','default_filename',
                prefs.default_filename)
        parser.setTagAttr('HarpiaProperties','grid', prefs.grid)
        parser.setTagAttr('HarpiaProperties','width', prefs.width)
        parser.setTagAttr('HarpiaProperties','height', prefs.height)
        parser.setTagAttr('HarpiaProperties','hpaned_work_area',
                prefs.hpaned_work_area)
        parser.setTagAttr('HarpiaProperties','vpaned_bottom',
                prefs.vpaned_bottom)
        parser.setTagAttr('HarpiaProperties','vpaned_left',
                prefs.vpaned_left)

        parser.appendToTag('HarpiaProperties', 'recent_files')
        for key in prefs.recent_files:
            parser.appendToTag('recent_files', 'name', value=key)

        try:
            from harpia.system import System
            file_name = System.get_user_dir() + "/" + prefs.conf_file_path
            confFile = file(os.path.expanduser(file_name), 'w')
            confFile.write(parser.prettify())
            confFile.close()
        except IOError as e:
            return False
        return True
Esempio n. 30
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/findColor.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties', '_R', '_G', '_B', '_R_T', '_G_T', '_B_T',
            'BackgroundColor', 'BorderColor', 'HelpView', 'prop_confirm'
        ]

        handlers = [
            'on_cancel_clicked', 'on_prop_confirm_clicked',
            'on_BackColorButton_clicked', 'on_BorderColorButton_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # load properties values
        self.block_properties = self.m_oPropertiesXML.getTag(
            "properties").getTag("block").getChildTags("property")

        for Property in self.block_properties:
            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "_R":
                self.widgets['_R'].set_value(float(value))
            if name == "_G":
                self.widgets['_G'].set_value(float(value))
            if name == "_B":
                self.widgets['_B'].set_value(float(value))
            if name == "_R_T":
                self.widgets['_R_T'].set_value(float(value))
            if name == "_G_T":
                self.widgets['_G_T'].set_value(float(value))
            if name == "_B_T":
                self.widgets['_B_T'].set_value(float(value))

                # if Property.name == "isFilling":
                # if Property.value == "true":
                # self.widgets['isFilling'].set_active( True );
                # else:
                # self.widgets['isFilling'].set_active( False );

                # if Property.name == "isScalling":
                # if Property.value == "true":
                # self.widgets['isScalling'].set_active( True );
                # else:
                # self.widgets['isScalling'].set_active( False );

                # if Property.name == "isCenter":
                # if Property.value == "true":
                # self.widgets['isAtCenter'].set_active( True );
                # else:
                # self.widgets['isAtPoint'].set_active( True );

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + 'help/findColor' +
                               _('_en.help'))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(
            unicode(
                str(
                    t_oS2iHelp.getTag("help").getTag(
                        "content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 31
0
    def on_ProcessToolBar_clickedIneer(self):
        page = self.widgets['WorkArea'].get_current_page()
        if self.diagrams.has_key(page):
            self.UpdateStatus(0)

            diagram = self.diagrams[page]

            process_XML = XMLParser("<harpia>" + \
                                           str(DiagramControl(diagram).get_process_chain()) + \
                                           "</harpia>", fromString=True)

            graph_size = len(list(process_XML.getTag("harpia").getTag("properties").getTagChildren()))

            if graph_size > 1:
                blocks = process_XML.getTag("harpia").getTag("properties").getChildTags("block")
                for t_oBlockProperties in blocks:
                    block_properties = t_oBlockProperties.getChildTags("property")
                    if int(t_oBlockProperties.type) == 00:  # 00 = acquisition block
                        inputType = 'file'
                        for block_property in block_properties:
                            if block_property.name == 'type':
                                print block_property.name
                                inputType = block_property.value

                            # adoção do paradigma monolítico.. nada de ficar mandando imagens por sockets!!
                            if block_property.name == 'filename' and inputType == 'file':
                                block_property.value = os.path.expanduser(block_property.value)
                                block_property.value = os.path.realpath(block_property.value)
                                if (not os.path.exists(block_property.value)):
                                    errMsg = _("Bad Filename: ") + block_property.value
                                    print(errMsg)
                                    self.SetStatusMessage(errMsg, 0)
                                    return

                    if int(t_oBlockProperties.type) == 01:  # 01 => save image
                        for block_property in block_properties:
                            if block_property.name == 'filename':
                                block_property.value = os.path.realpath(block_property.value)


                    # seguindo o paradigma de não mandar mais nada.. vamos testar com o haar =]
                    # não vamos mandar mais nada mas vamos traduzir o path do haarCascade pra algo real
                    if int(t_oBlockProperties.type) == 610:  # 610 => haar detector... passando a cascade .xml
                        for block_property in block_properties:
                            if block_property.name == 'cascade_name':
                                block_property.value = os.path.realpath(block_property.value)
                                if (not os.path.exists(block_property.value)):
                                    errMsg = _("Bad Filename: ") + block_property.value
                                    print(errMsg)
                                    self.SetStatusMessage(errMsg, 0)
                                    return

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

                session_manager = s2iSessionManager.s2iSessionManager()

                ## pegando o novo ID (criado pela s2iSessionManager) e passando para o s2idiagram
                self.diagrams[page].set_session_id(session_manager.session_id)

                # step sempre sera uma lista.. primeiro elemento eh uma mensagem, segundo eh o erro.. caso exista erro.. passar para o s2idiagram tb!
                self.diagrams[page].set_error_log('')
                t_bEverythingOk = True
                for step in session_manager.new_instance(process_chain):
                    if len(step) > 1:
                        if step[1] != '' and step[1] != None:
                            self.diagrams[page].append_error_log(step[1])
                            t_bEverythingOk = False
                    self.SetStatusMessage(step[0], t_bEverythingOk)
                    # self.widgets['StatusLabel'].set_text()
                    # print t_bEverythingOk
                    print step[0]
                # yield step#util caso se resolva usar a interface "lenta" ou se descubra como atualizar rapidamente a GUI

        # falta pegar o retorno!!!!!!
        self.UpdateStatus(7)
    def save(cls, code_template):
        """
        This method save the code_template in user space.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """
        from harpia.system import System
        code_template.source = "xml"
        parser = XMLParser()
        parser.addTag('HarpiaCodeTemplate')
        parser.setTagAttr('HarpiaCodeTemplate','name', code_template.name)
        parser.setTagAttr('HarpiaCodeTemplate','type', code_template.type)
        parser.setTagAttr('HarpiaCodeTemplate','description', code_template.description)
        parser.setTagAttr('HarpiaCodeTemplate','language', code_template.language)
        parser.setTagAttr('HarpiaCodeTemplate','extension', code_template.extension)
        parser.setTagAttr('HarpiaCodeTemplate','source', code_template.source)
        parser.appendToTag('HarpiaCodeTemplate','command').string = str(code_template.command)
        parser.appendToTag('HarpiaCodeTemplate','code').string = str(code_template.code)

        try:
            data_dir = System.get_user_dir() + "/extensions/"
            data_dir = data_dir + code_template.language + "/"
            if not os.path.isdir(data_dir):
                try:
                    os.makedirs(data_dir)
                except:
                    pass
            file_name = data_dir + code_template.type + ".xml"
            code_template_file = file(os.path.expanduser(file_name), 'w')
            code_template_file.write(parser.prettify())
            code_template_file.close()
        except IOError as e:
            return False
        return True
Esempio n. 33
0
class Preferences(GladeWindow):
    """
        This class shows the preferences, and handles the signals.
        Is derived from GladeWindow and allows the user to edit their preferences.
        The preferences are stored in a harpia.conf file and this file is loaded when harpia is initialized.
    """

    # The s2iharpiafrontend object (Editor)

    # ----------------------------------------------------------------------

    def __init__(self, Editor):
        """
            The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
        """

        self.m_oEditor = Editor
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        ## Imports the Glade file
        filename = self.m_sDataDir + 'glade/preferences.ui'

        # The widget list
        widget_list = [
            'preferences', 'PREFGridInt', 'PREFShowGrid', 'PREFServer',
            'PREFPort'
        ]

        # Signal Handlers from the Buttons Confirm and Cancel
        handlers = [
            'on_preferences_confirm_clicked', 'on_preferences_cancel_clicked'
        ]

        # The Top window widget
        top_window = 'preferences'

        # Starts the GladeWindow, calling his __init__ method.
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # Set the preferences Icon
        self.widgets['preferences'].set_icon_from_file(self.m_sDataDir +
                                                       "images/harpia_ave.png")

        ## The Homefolder where the preferences will be stored.
        if os.name == "nt":
            self.HomeFolder = os.path.join(os.path.expanduser("~"),
                                           "harpiaFiles\\")
        else:
            self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
        # self.HomeFolder = "/tmp/.harpia/"

        ## The Config File Path
        self.configfile = self.HomeFolder + "harpia.conf"

        # If the path do not exist, creates one.
        if not (os.path.exists(self.HomeFolder)):
            os.makedirs(self.HomeFolder, mode=0700)

        # If the path do not exist, creates one copyint the default harpia.conf.
        if not (os.path.exists(self.configfile)):
            shutil.copy("harpia.conf", self.HomeFolder)

        print "TESTE" + self.configfile
        ## A binderytool object, with the preferences stored
        self.m_oPreferencesXML = XMLParser(self.configfile)

        # ---------------------------------
        self.preferences = self.m_oPropertiesXML.getTag("harpia").getTag(
            "editor").getChildTags("property")

        # Load Preferences
        for Preference in self.preferences:

            if Preference.name == "show-grid":
                if Preference.value == "false":
                    state = "False"
                else:
                    state = "True"
                self.widgets['PREFShowGrid'].set_active(eval(state))

            if Preference.name == "grid-int":
                self.widgets['PREFGridInt'].set_value(int(Preference.value))

            if Preference.name == "server":
                self.widgets['PREFServer'].set_text(unicode(Preference.value))

            if Preference.name == "port":
                self.widgets['PREFPort'].set_value(int(Preference.value))

#----------------------------------------------------------------------

    def __del__(self):
        pass

    # ----------------------------------------------------------------------
    # Confirm Button handler function
    def on_preferences_confirm_clicked(self, *args):
        """
        This function is called whenever the confirm button on the preferences window is clicked.
        It stores the preferences in the configfile.
        """
        for Preference in self.preferences:
            if Preference.name == "show-grid":
                if self.widgets['PREFShowGrid'].get_active():
                    Preference.value = unicode("true")
                    self.m_oEditor.ShowGrid(True)
                else:
                    Preference.value = unicode("false")
                    self.m_oEditor.ShowGrid(False)

            if Preference.name == "grid-int":
                Preference.value = unicode(
                    str(int(self.widgets['PREFGridInt'].get_value())))
                self.m_oEditor.SetGridInterval(int(Preference.value))

            if Preference.name == "server":
                Preference.value = unicode(
                    self.widgets['PREFServer'].get_text())

            if Preference.name == "port":
                Preference.value = unicode(
                    str(int(self.widgets['PREFPort'].get_value())))

                # -------------------------------------------

                #         Editor = "\n<editor>" + "\n</editor>\n"
                #         Block = "\n<block>" + "\n</block>\n"
                #         Connector = "\n<connector>" + "\n</connector>\n"
                #         Harpia = "<harpia>" + Editor + Block + Connector + "</harpia>"

        # Opens the configFile for writing
        FileHandle = open(self.configfile, "w")
        # Writes the preferences
        FileHandle.write(self.m_oPreferencesXML.xml())
        # Close the FIle
        FileHandle.close()

        # -------------------------------------------
        # Destroy the preferences window
        self.widgets['preferences'].destroy()

    # ----------------------------------------------------------------------
    # Cancel Button handler function
    def on_preferences_cancel_clicked(self, *args):
        """
        This function is called whenever the cancel button on the preferences window is clicked.
        It just exits the window without saving any changes.
        """
        # Just destroy the window, without savind the changes
        self.widgets['preferences'].destroy()
Esempio n. 34
0
    def save(cls, diagram):
        """
        This method save a file.

        Returns:

            * **Types** (:class:`boolean<boolean>`)
        """

        parser = XMLParser()
        parser.addTag('harpia')
        parser.appendToTag('harpia', 'version', value=System.VERSION)
        parser.appendToTag('harpia', 'zoom', value=diagram.zoom)
        parser.appendToTag('harpia', 'language', value=diagram.language)

        parser.appendToTag('harpia', 'blocks')
        for block_id in diagram.blocks:
            block_type = diagram.blocks[block_id].type
            pos = diagram.blocks[block_id].get_position()
            parser.appendToTag('blocks', 'block', type=block_type, id=block_id)
            parser.appendToLastTag('block', 'position', x=pos[0], y=pos[1])
            props = diagram.blocks[block_id].get_properties()
            for prop in props:
                parser.appendToLastTag('block',
                                       'property',
                                       key=str(prop["name"]),
                                       value=str(prop["value"])
                                       )

        parser.appendToTag('harpia', 'connections')
        for connector in diagram.connectors:
            parser.appendToTag('connections', 'connection',
                               from_block=connector.source.id,
                               from_out=int(connector.source_port) + 1,
                               to_block=connector.sink.id,
                               to_in=int(connector.sink_port) + 1)

        try:
            save_file = open(str(diagram.file_name), "w")
            save_file.write(parser.prettify())
            save_file.close()
        except IOError as e:
            System.log(e.strerror)
            return False, e.strerror

        diagram.set_modified(False)
        return True, "Success"
Esempio n. 35
0
    def __init__(self, Editor):
        """
            The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
        """

        self.m_oEditor = Editor
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        ## Imports the Glade file
        filename = self.m_sDataDir + 'glade/preferences.ui'

        # The widget list
        widget_list = [
            'preferences', 'PREFGridInt', 'PREFShowGrid', 'PREFServer',
            'PREFPort'
        ]

        # Signal Handlers from the Buttons Confirm and Cancel
        handlers = [
            'on_preferences_confirm_clicked', 'on_preferences_cancel_clicked'
        ]

        # The Top window widget
        top_window = 'preferences'

        # Starts the GladeWindow, calling his __init__ method.
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # Set the preferences Icon
        self.widgets['preferences'].set_icon_from_file(self.m_sDataDir +
                                                       "images/harpia_ave.png")

        ## The Homefolder where the preferences will be stored.
        if os.name == "nt":
            self.HomeFolder = os.path.join(os.path.expanduser("~"),
                                           "harpiaFiles\\")
        else:
            self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
        # self.HomeFolder = "/tmp/.harpia/"

        ## The Config File Path
        self.configfile = self.HomeFolder + "harpia.conf"

        # If the path do not exist, creates one.
        if not (os.path.exists(self.HomeFolder)):
            os.makedirs(self.HomeFolder, mode=0700)

        # If the path do not exist, creates one copyint the default harpia.conf.
        if not (os.path.exists(self.configfile)):
            shutil.copy("harpia.conf", self.HomeFolder)

        print "TESTE" + self.configfile
        ## A binderytool object, with the preferences stored
        self.m_oPreferencesXML = XMLParser(self.configfile)

        # ---------------------------------
        self.preferences = self.m_oPropertiesXML.getTag("harpia").getTag(
            "editor").getChildTags("property")

        # Load Preferences
        for Preference in self.preferences:

            if Preference.name == "show-grid":
                if Preference.value == "false":
                    state = "False"
                else:
                    state = "True"
                self.widgets['PREFShowGrid'].set_active(eval(state))

            if Preference.name == "grid-int":
                self.widgets['PREFGridInt'].set_value(int(Preference.value))

            if Preference.name == "server":
                self.widgets['PREFServer'].set_text(unicode(Preference.value))

            if Preference.name == "port":
                self.widgets['PREFPort'].set_value(int(Preference.value))
Esempio n. 36
0
    def __init__(self, PropertiesXML, S2iBlockProperties):

        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        filename = self.m_sDataDir + 'glade/colorConversion.ui'
        self.m_oPropertiesXML = PropertiesXML
        self.m_oS2iBlockProperties = S2iBlockProperties

        widget_list = [
            'Properties',
            'COLOConversionType',
            'BackgroundColor',
            'BorderColor',
            'HelpView'
        ]

        handlers = [
            'on_BackColorButton_clicked',
            'on_BorderColorButton_clicked',
            'on_cancel_clicked',
            'on_colorConversion_confirm_clicked'
        ]

        top_window = 'Properties'

        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        self.block_properties = self.m_oPropertiesXML.getTag("properties").getTag("block").getChildTags("property")
        #load properties values
        for Property in self.block_properties:

            name = Property.getAttr("name")
            value = Property.getAttr("value")

            if name == "type":
                if value == "RGB -> GRAY":
                    self.widgets['COLOConversionType'].set_active(int(0))
                if value == "RGB -> YCrCb":
                    self.widgets['COLOConversionType'].set_active(int(1))
                if value == "YCrCb -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(2))
                if value == "RGB -> HSV":
                    self.widgets['COLOConversionType'].set_active(int(3))
                if value == "HSV -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(4))
                if value == "RGB -> HLS":
                    self.widgets['COLOConversionType'].set_active(int(5))
                if value == "HLS -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(6))
                if value == "RGB -> CIE.XYZ":
                    self.widgets['COLOConversionType'].set_active(int(7))
                if value == "CIE.XYZ -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(8))
                if value == "RGB -> CIE.LAB":
                    self.widgets['COLOConversionType'].set_active(int(9))
                if value == "CIE.LAB -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(10))
                if value == "RGB -> CIE.LUV":
                    self.widgets['COLOConversionType'].set_active(int(11))
                if value == "CIE.LUV -> RGB":
                    self.widgets['COLOConversionType'].set_active(int(12))

        self.configure()

        # load help text
        t_oS2iHelp = XMLParser(self.m_sDataDir + "help/colorConversion" + _("_en.help"))

        t_oTextBuffer = gtk.TextBuffer()

        t_oTextBuffer.set_text(unicode(str(t_oS2iHelp.getTag("help").getTag("content").getTagContent())))

        self.widgets['HelpView'].set_buffer(t_oTextBuffer)
Esempio n. 37
0
class Preferences(GladeWindow):
    """
        This class shows the preferences, and handles the signals.
        Is derived from GladeWindow and allows the user to edit their preferences.
        The preferences are stored in a harpia.conf file and this file is loaded when harpia is initialized.
    """

    # The s2iharpiafrontend object (Editor)


    # ----------------------------------------------------------------------

    def __init__(self, Editor):
        """
            The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
        """

        self.m_oEditor = Editor
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        ## Imports the Glade file
        filename = self.m_sDataDir + 'glade/preferences.ui'

        # The widget list
        widget_list = ['preferences',
                       'PREFGridInt',
                       'PREFShowGrid',
                       'PREFServer',
                       'PREFPort']

        # Signal Handlers from the Buttons Confirm and Cancel
        handlers = ['on_preferences_confirm_clicked',
                    'on_preferences_cancel_clicked']

        # The Top window widget
        top_window = 'preferences'

        # Starts the GladeWindow, calling his __init__ method.
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # Set the preferences Icon
        self.widgets['preferences'].set_icon_from_file(self.m_sDataDir + "images/harpia_ave.png")

        ## The Homefolder where the preferences will be stored.
        if os.name == "nt":
            self.HomeFolder = os.path.join(os.path.expanduser("~"), "harpiaFiles\\")
        else:
            self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
        # self.HomeFolder = "/tmp/.harpia/"

        ## The Config File Path
        self.configfile = self.HomeFolder + "harpia.conf"

        # If the path do not exist, creates one.
        if not (os.path.exists(self.HomeFolder)):
            os.makedirs(self.HomeFolder, mode=0700)

        # If the path do not exist, creates one copyint the default harpia.conf.
        if not (os.path.exists(self.configfile)):
            shutil.copy("harpia.conf", self.HomeFolder)

        print "TESTE" + self.configfile
        ## A binderytool object, with the preferences stored
        self.m_oPreferencesXML = XMLParser(self.configfile)


        # ---------------------------------
        self.preferences = self.m_oPropertiesXML.getTag("harpia").getTag("editor").getChildTags("property")

        # Load Preferences
        for Preference in  self.preferences:

            if Preference.name == "show-grid":
                if Preference.value == "false":
                    state = "False"
                else:
                    state = "True"
                self.widgets['PREFShowGrid'].set_active(eval(state))

            if Preference.name == "grid-int":
                self.widgets['PREFGridInt'].set_value(int(Preference.value))

            if Preference.name == "server":
                self.widgets['PREFServer'].set_text(unicode(Preference.value))

            if Preference.name == "port":
                self.widgets['PREFPort'].set_value(int(Preference.value))


#----------------------------------------------------------------------
    def __del__(self):
        pass

    # ----------------------------------------------------------------------
    # Confirm Button handler function
    def on_preferences_confirm_clicked(self, *args):
        """
        This function is called whenever the confirm button on the preferences window is clicked.
        It stores the preferences in the configfile.
        """
        for Preference in  self.preferences:
            if Preference.name == "show-grid":
                if self.widgets['PREFShowGrid'].get_active():
                    Preference.value = unicode("true")
                    self.m_oEditor.ShowGrid(True)
                else:
                    Preference.value = unicode("false")
                    self.m_oEditor.ShowGrid(False)

            if Preference.name == "grid-int":
                Preference.value = unicode(str(int(self.widgets['PREFGridInt'].get_value())))
                self.m_oEditor.SetGridInterval(int(Preference.value))

            if Preference.name == "server":
                Preference.value = unicode(self.widgets['PREFServer'].get_text())

            if Preference.name == "port":
                Preference.value = unicode(str(int(self.widgets['PREFPort'].get_value())))


                # -------------------------------------------

                #         Editor = "\n<editor>" + "\n</editor>\n"
                #         Block = "\n<block>" + "\n</block>\n"
                #         Connector = "\n<connector>" + "\n</connector>\n"
                #         Harpia = "<harpia>" + Editor + Block + Connector + "</harpia>"

        # Opens the configFile for writing
        FileHandle = open(self.configfile, "w")
        # Writes the preferences
        FileHandle.write(self.m_oPreferencesXML.xml())
        # Close the FIle
        FileHandle.close()

        # -------------------------------------------
        # Destroy the preferences window
        self.widgets['preferences'].destroy()

    # ----------------------------------------------------------------------
    # Cancel Button handler function
    def on_preferences_cancel_clicked(self, *args):
        """
        This function is called whenever the cancel button on the preferences window is clicked.
        It just exits the window without saving any changes.
        """
        # Just destroy the window, without savind the changes
        self.widgets['preferences'].destroy()