def updateDB(self, itmWid):
        row = int(itmWid.row())
        column = int(itmWid.column())
        co_compteur = int(self.componentTable.item(row,0).text())
        value = str(itmWid.text())
        cell = "row " + str(itmWid.row()) + " | col " + str(itmWid.column())
        print_debug("Updating Cell : {}, with value : {}".format(cell, value))
        self.componentTable.setSortingEnabled(True)

        if column == 1:
            value = self.cat_name_list.index(value) + 1
            sql = ''' UPDATE Composant
                      SET CO_FAMILLE = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 2:
            sql = ''' UPDATE Composant
                      SET CO_NOM = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 3:
            sql = ''' UPDATE Composant
                      SET CO_FORME = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 4:
            sql = ''' UPDATE Composant
                      SET CO_LARGEUR = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 5:
            sql = ''' UPDATE Composant
                      SET CO_EPAISSEUR = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 6:
            sql = ''' UPDATE Composant
                      SET CO_LONGUEUR = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 7:
            value = ""
            comma = 0
            #print_debug(itmWid.backgroundColor().getRgb())
            for c in itmWid.backgroundColor().getRgb()[0:3]:
                value += str(c)
                if comma < 2:
                    value += ","
                    comma += 1
            sql = ''' UPDATE Composant
                      SET CO_COULEUR = ?
                      WHERE CO_COMPTEUR = ?'''

        if column == 8:
            sql = ''' UPDATE Composant
                      SET CO_MASSE = ?
                      WHERE CO_COMPTEUR = ?'''

        self.cur.execute(sql, (value, co_compteur))
        self.con.commit()
    def duplicateComponent(self):
        """
        Delete a component row by co_compteur
        :return:
        """
        row = self.componentTable.currentRow()
        if row > -1:
            co_compteur = self.componentTable.item(row,0).text()
            self.cur.execute("SELECT * FROM Composant WHERE CO_COMPTEUR = {}".format(co_compteur))
            data = self.cur.fetchall()
            data = data[0]
            # ['1', 'Composant', '1', '0', '100', '22', 'R', '203,193,124', '350']
            des = data[1]
            cat = data[2]
            length = data[3]
            width = data[4]
            height = data[5]
            section = data[6]
            color = data[7]
            mass = data[8]

            data = (des, cat, length, width, height, section, color, mass)
            self.addComponent(data)
        else:
            print_debug("Select a component in the table first!")
            QtGui.QMessageBox.warning(None,"Pas de composant sélectionné.","Veuillez sélectionner un composant dans le tableau avant de cliquer sur Dupliquer.")
    def setDirection(self):
        print_debug(["", "Start setDirection :"])
        directions = ['+x', '+y', '+z', '-x', '-y', '-z', 'line']
        idx = self.direction_cb.currentIndex()
        print_debug("setDirection : idx={}, str={}".format(
            idx, directions[idx]))
        self.params.SetString("BeamDirection", directions[idx])
        self.direction = directions[idx]
        if self.direction == 'line':
            if self.fixed_component == True:
                self.direction = directions[0]
                self.direction_cb.setCurrentIndex(0)

        if self.fixed_length == False and self.fixed_component == False:
            print_debug("self.fixed_length is False")
            if 'x' in self.direction:
                self.Length = self.product[0]
                self.length_input.setText(
                    App.Units.Quantity(self.Length,
                                       App.Units.Length).UserString)
            elif 'y' in self.direction:
                self.Length = self.product[1]
                self.length_input.setText(
                    App.Units.Quantity(self.Length,
                                       App.Units.Length).UserString)
            elif 'z' in self.direction:
                self.Length = self.product[2]
                self.length_input.setText(
                    App.Units.Quantity(self.Length,
                                       App.Units.Length).UserString)
        else:
            print_debug("self.fixed_length is True")
        print_debug(["End setDirection", ""])
    def restoreParams(self):
        print_debug("Panel restoreParams")
        stored_composant = self.p.GetInt("PanelPreset", 0)
        stored_wp = wp = self.p.GetInt("PanelWP", 0)

        if stored_composant != 0:
            if DEBUG:
                App.Console.PrintMessage("restore composant \n")
            comp = g3d_connect_db.getComposant(id=stored_composant)
            cat = comp[2]
            got_panel_cat = False
            n = 0
            for x in self.categories:
                if x[0] == cat:
                    self.categories_cb.setCurrentIndex(n)
                    got_panel_cat = True
                n += 1
            if got_panel_cat == False:
                self.setCategory(i=0)
                return
            self.composant_items = g3d_connect_db.getComposants(categorie=cat)
            self.composant_cb.clear()
            self.composant_cb.addItems([x[1] for x in self.composant_items])
            n = 0
            for x in self.composant_items:
                if x[0] == stored_composant:
                    self.composant_cb.setCurrentIndex(n)
                n += 1
        else:
            self.setCategory(i=0)

        if stored_wp:
            self.wp_cb.setCurrentIndex(wp)
        self.setWorkingPlane()
 def Combo_indexchanged2(self, idx):
     combo = self.sender()
     row = combo.property('row')
     column = combo.property('column')
     index = combo.currentIndex()
     print_debug('Index Changed : combo row %d column %d indexChanged to %d' % (row, column, index))
     if column == 1: # CATEGORY
         text = combo.currentText()
         if text != "Ajouter...":
             cat = QtGui.QTableWidgetItem(text)
             self.componentTable.removeCellWidget(row,column)
             self.componentTable.setItem(row, column, cat)
         else:
             (fc_nom, bool_cat) = QtGui.QInputDialog.getText(None,"Categorie", "Nom de la nouvelle catégorie :")
             if bool_cat:
                 (fc_type, bool_type) =  QtGui.QInputDialog.getItem(None,"Categorie", "Choisir BO pour des composants de type Bois Massif, choisir PX pour les composants de type Panneaux.", ["BO","PX"])
                 if bool_type:
                     self.cat_name_list.insert(-1, fc_nom)
                     #data = (index+1,fc_nom,fc_type)
                     data = (fc_nom,fc_type)
                     sql = ''' INSERT INTO Famille_Composant(FC_NOM, FC_TYPE)
                               VALUES(?,?)'''
                     self.cur.execute(sql, data)
                     self.con.commit()
                     self.componentTable.removeCellWidget(row,column)
                     cat = QtGui.QTableWidgetItem(fc_nom)
                     self.componentTable.setItem(row, column, cat)
     elif column == 3: #Shape type
         text = combo.currentText()
         self.componentTable.removeCellWidget(row,column)
         shape_type = QtGui.QTableWidgetItem(text)
         self.componentTable.setItem(row, column, shape_type)
 def SpinBox_valuechanged(self, value):
     spinbox = self.sender()
     row = spinbox.property('row')
     column = spinbox.property('column')
     print_debug('Spinbox value changed : row %d column %d value changed to %d' % (row, column, value))
     itm = QtGui.QTableWidgetItem()
     itm.setData(QtCore.Qt.EditRole, value)
     self.componentTable.setItem(row, column, itm)
 def cellSimpleClick(self, row, col):
     print_debug("Cell simple clicked : row {} column {} value {}".format(row, col,self.componentTable.item(row,col).text()))
     if self.lastEditItem["row"] != None:
         if row != self.lastEditItem["row"] or col != self.lastEditItem["column"]:
             print_debug("Click outside edited cell")
             self.componentTable.removeCellWidget(self.lastEditItem["row"], self.lastEditItem["column"])
             self.componentTable.setSortingEnabled(True)
     self.lastEditItem["row"] = row
     self.lastEditItem["column"] = col
     self.lastEditItem["value"] = self.componentTable.item(row,col).text()
 def cancelAndClose(self):
     """
     Cancel all operations previously done and close window...or not.
     FIX ME : Make a backup of the db
     :return:
     """
     g3d_connect_db.restore_backup()
     if self.con:
         self.con.close()
     self.form.close()
     print_debug("cancelAndClose done")
Beispiel #9
0
def getComposant(id=1):
    con = sql_connection()
    cursorObj = con.cursor()
    cursorObj.execute("SELECT * FROM Composant WHERE CO_COMPTEUR = " + str(id))
    rows = cursorObj.fetchall()
    if rows:
        component = rows[0]
    else:
        component = ['1', 'Composant', '1', '0', '100', '22', 'R', '203,193,124', '350']
    print_debug(["", "g3d_connect_db.getComposant :", component, ""])
    
    return component
 def getpoint(self, point=None, obj=None):
     "this function is called by the snapper when it has a 3D point"
     # no point
     if point is None:
         print_debug("no point : finalize panel tracker")
         self.TrackerRect.finalize()
         return
     # first clic : pick rectangle origin
     if self.basepoint is None:
         print_debug("first point : set origin panel tracker")
         self.setWorkingPlane(point=point)
         self.TrackerRect.setorigin(point)
         self.basepoint = point
         Gui.Snapper.getPoint(
             last=point,
             callback=self.getpoint,
             movecallback=self.update,
             extradlg=[self.taskbox()],
             title=translate("Arch", "Next point") + ":",
             mode="rectangle",
         )
         return
     # second clic : make panel
     print_debug("second point : finalize panel tracker")
     self.TrackerRect.finalize()
     print_debug("second point : make panel transaction")
     self.makeTransaction(point)
 def setFillingMode(self, state):
     print_debug(['filling cb state: {}'.format(state)])
     if state == 2:
         self.pattern = "filling"
         self.filling_input.setDisabled(False)
         self.distribution_input.setDisabled(True)
         self.distribution_start.setDisabled(True)
         self.distribution_end.setDisabled(True)
         self.distribution_cb.setChecked(False)
     else:
         self.filling_input.setDisabled(True)
         if not self.distribution_cb.isChecked():
             self.pattern = 'none'
     self.params.SetString("BeamPattern", str(self.pattern))
 def deleteComponent(self):
     """
     Delete a component row by co_compteur
     :return:
     """
     row = self.componentTable.currentRow()
     if row > -1:
         co_compteur = int(self.componentTable.item(row,0).text())
         sql = 'DELETE FROM Composant WHERE co_compteur=?'
         self.cur.execute(sql, (co_compteur,))
         self.con.commit()
         self.populate()
     else:
         print_debug("Select a component in the table first!")
         QtGui.QMessageBox.warning(None,"Pas de composant sélectionné.","Veuillez sélectionner un composant dans le tableau avant de cliquer sur Supprimer.")
Beispiel #13
0
 def getSource(self, obj):
     print_debug("Looking for source of %s." % obj.Name)
     src = obj.Source
     print_debug("Current source is %s." % src.Name)
     while src.TypeId == "Part::Mirroring":
         print_debug("Source is a Part::Mirror object.")
         src = src.Source
     print_debug("Source is : %s." % src.Name)
     return src
    def __init__(self, parent=None):
        super(ComponentManager, self).__init__()

        ui_file = os.path.join(UIPATH,'component_manager-gespal3d.ui')
        self.form = Gui.PySideUic.loadUi(ui_file)

        self.database_path_edit = self.form.findChild(QtGui.QLineEdit, "lineEdit")
        #self.p = App.ParamGet(str(PARAMPATH))
        #no_database = "true"
        #self.dbPath = self.p.GetString("sqlitedb", no_database)
        
        
        #self.database_path_edit.setText(self.dbPath)

        self.dbPathButton = self.form.findChild(QtGui.QPushButton, "pushButton_chooseDB")
        self.dbPathButton.clicked.connect(self.chooseDatabasePath)

        self.dbCreateButton = self.form.findChild(QtGui.QPushButton, "pushButton_createDB")
        self.dbCreateButton.clicked.connect(self.createNewDatabase)
        
        self.componentTable =  self.form.findChild(QtGui.QTableWidget, "tableWidget")
        self.componentTable.itemChanged.connect(self.updateDB)
        self.componentTable.itemDoubleClicked.connect(self.doubleClick)
        self.componentTable.cellClicked.connect(self.cellSimpleClick)

        self.addButton = self.form.findChild(QtGui.QPushButton, "pushButtonAdd")
        self.addButton.clicked.connect(self.addComponent)

        self.duplicateButton = self.form.findChild(QtGui.QPushButton, "pushButtonDuplicate")
        self.duplicateButton.clicked.connect(self.duplicateComponent)

        self.delButton = self.form.findChild(QtGui.QPushButton, "pushButtonDel")
        self.delButton.clicked.connect(self.deleteComponent)

        self.cancelButton = self.form.findChild(QtGui.QPushButton, "pushButtonRej")
        self.cancelButton.clicked.connect(self.cancelAndClose)

        self.validateButton = self.form.findChild(QtGui.QPushButton, "pushButtonVal")
        self.validateButton.clicked.connect(self.acceptAndClose)
        print_debug("end setupUi")

        self.lastEditItem = {"row" : None, "column" : None, "value" : None}

        self.init_pop()
        self.form.show()
        print_debug("show dialog")
Beispiel #15
0
def getComposants(categorie=None):
    if categorie:
        con = sql_connection()
        cursorObj = con.cursor()
        cursorObj.execute(
            "SELECT * FROM Composant WHERE CO_FAMILLE = "
            + str(categorie)
            + " ORDER BY CO_NOM"
        )
        rows = cursorObj.fetchall()
        if DEBUG_DB:
            messages = ["", "g3d_connect_db.getComposants :"]
            messages.append(rows)
            messages.append("")
            print_debug(messages)
        
        return rows
Beispiel #16
0
def getCategories(include=[], exclude=[]):
    categories_list = []
    con = sql_connection()
    cursorObj = con.cursor()
    cursorObj.execute("SELECT * FROM Famille_Composant")
    rows = cursorObj.fetchall()
    if len(include) > 0:
        for row in rows:
            if row[2] in include:
                categories_list.append(row)
    if len(exclude) > 0:
        for row in rows:
            if not row[2] in exclude:
                categories_list.append(row)
    if DEBUG_DB:
        messages = ["g3d_connect_db.getCategories :"]
        messages.append(categories_list)
        print_debug(messages)

    return categories_list
    def setComposant(self, i=0):
        print_debug(["", "Start setComposant :"])
        self.Profile = None
        idx = self.composant_items[i][0]
        comp = g3d_connect_db.getComposant(id=idx)

        if comp:
            print_debug("composant : w = {} ; h = {} ; l = {}".format(
                float(comp[5]), float(comp[4]), float(comp[3])))
            self.Profile = comp
            # width
            if float(comp[5]) > 0.0:
                self.width_input.setText(
                    App.Units.Quantity(float(comp[5]),
                                       App.Units.Length).UserString)
                self.width_input.setDisabled(True)
            else:
                self.width_input.setDisabled(False)

            # height
            if float(comp[4]) > 0.0:
                self.height_input.setText(
                    App.Units.Quantity(float(comp[4]),
                                       App.Units.Length).UserString)
                self.height_input.setDisabled(True)
            else:
                self.height_input.setDisabled(False)

            # length
            if float(comp[3]) > 0.0:
                self.fixed_component = True
                self.length_input.setText(
                    App.Units.Quantity(float(comp[3]),
                                       App.Units.Length).UserString)
                self.length_input.setDisabled(True)
                self.fixlength_checkbox.setDisabled(True)
                self.fixlength_checkbox.setChecked(False)
                self.setFixedLength(0)
            else:
                self.fixed_component = False
                self.length_input.setDisabled(False)
                self.fixlength_checkbox.setDisabled(False)
                self.length_input.setText(
                    App.Units.Quantity(self.Length,
                                       App.Units.Length).UserString)

            self.params.SetInt("BeamPreset", comp[0])
            self.setDirection()
        else:
            print_debug("no composant")
        print_debug(["End setComposant", ""])
    def Activated(self):

        "When the tool is clicked"

        print_debug(["", "---------", "Beam Creator Activated"])

        # Reads preset profiles and categorizes them
        self.categories = g3d_connect_db.getCategories(include=["BO"])

        self.params = App.ParamGet(str(PARAMPATH))

        product = App.ActiveDocument.getObject("Product")
        if hasattr(product, "Length"):
            self.product = [
                product.Length.Value,
                product.Width.Value,
                product.Height.Value,
            ]
        else:
            product = App.ActiveDocument.getObject("Box")
            self.product = [
                product.Length.Value,
                product.Width.Value,
                product.Height.Value,
            ]

        self.clicked_points = []

        self.tracker = g3d_tracker.beamTracker(shaded=False)

        title = translate("Gespal3D", "Point de départ du composant") + ":"

        Gui.Snapper.getPoint(
            callback=self.getPoint,
            movecallback=self.update,
            extradlg=[self.taskbox()],
            title=title,
        )
Beispiel #19
0
def sql_connection():
    p = App.ParamGet(str(PARAMPATH))
    no_database = "true"
    sqlite_db = p.GetString("sqlitedb", no_database)
    if sqlite_db == "true":
        print_debug(["define database path in BaseApp/Preferences/Mod/Gespal3D"])
        g3d_component_manager.G3D_ComponentsManager.Activated()
        #return
    try:
        con = sqlite3.connect(sqlite_db)
        if DEBUG_DB:
            print_debug(["DB Connection is established."])
    except Error:
        print_debug(["sql_connection got an error", Error])

    return con
 def createNewDatabase(self):
     """
     when user click on change button a file dialog pop up to him
     :return:
     """
     print_debug("user clicked on create a new db button")
     dbPath = QtGui.QFileDialog.getExistingDirectory(
         None,
         "Choisir le dossier où sera créé la base de données.",
         None,)
     if len(dbPath) > 0:
         if not self.con is None:
             self.con.close()
         dbPath = os.path.join(dbPath, "g3d_component.sqdb")
         self.database_path_edit.setText(dbPath)
         self.dbPath = self.p.SetString("sqlitedb", dbPath)
         print_debug("new db path is : {}".format(self.dbPath))
         sqliteCon = g3d_connect_db.sql_connection()
         g3d_connect_db.create_new_db(sqliteCon)
         self.init_pop()
     else:
         print_debug("user cancel creating a new db")
    def init_pop(self):
        self.p = App.ParamGet(str(PARAMPATH))
        self.dbPath = self.p.GetString("sqlitedb", "no_db")
        print_debug("db path : {}".format(self.dbPath))
        if self.dbPath == "no_db":
            self.con = None
            QtGui.QMessageBox.warning(
                None,
                "Pas de base de données !",
                "Veuillez définir le chemin de la base de donnée de composants en cliquant sur le bouton Choisir ou Créer dans le gestionnaire de composant.")
        else:
            self.database_path_edit.setText(self.dbPath)
            if self.componentTable.rowCount() > 0:
                for row in reversed(range(self.componentTable.rowCount())):
                    self.componentTable.removeRow(row)

            self.con = g3d_connect_db.sql_connection()
            g3d_connect_db.make_backup()
            self.cur = self.con.cursor()
            print_debug("connecting db")

            self.populate()
            print_debug("populate table")
    def Activated(self):
        print_debug("G3D PANEL ACTIVATED")
        # parameters
        self.p = App.ParamGet(str(PARAMPATH))

        self.continueCmd = self.p.GetBool("PanelContinue", False)

        # fetch data from sqlite database
        self.categories = g3d_connect_db.getCategories(include=["PX"])
        print_debug("self.categories = ")
        print_debug([cat for cat in self.categories])

        self.wp = App.DraftWorkingPlane
        self.basepoint = None
        self.TrackerRect = g3d_tracker.rectangleTracker()
        self.TrackerRect.setPlane(self.wp.axis)
        title = translate("Gespal3D", "Premier coin du panneau ") + ":"
        Gui.Snapper.getPoint(
            callback=self.getpoint,
            movecallback=self.update,
            extradlg=[self.taskbox()],
            title=title,
        )
def makeG3DBeam(
    g3d_profile=None,
    p1=[0.0, 0.0, 0.0],
    p2=[1000.0, 0.0, 0.0],
    anchor=4,
    inclination=0.0,
):
    """
    Create a G3D Beam (Arch Structure) from a given profile, with sprecified length, color and description.
    :param g3d_profile: list
    :param p1: list[float]
    :param p2: list[float]
    :param anchor: int
    :param inclination: float
    :param description: str
    :return: object
    """

    print_debug([
        "",
        "makeG3DBeam called with :",
        "g3d_profile : {}, type : {}".format(g3d_profile, type(g3d_profile)),
        "p1 : {}, type : {}".format(p1, type(p1)),
        "p2 : {}, type : {}".format(p2, type(p2)),
        "anchor : {}, type : {}".format(anchor, type(anchor)),
        "inclination : {}, type : {}".format(inclination, type(inclination)),
        "",
    ])

    p1 = App.Vector(p1[0], p1[1], p1[2])
    p2 = App.Vector(p2[0], p2[1], p2[2])

    if g3d_profile is None:
        section = g3d_profiles_parser.makeProfile()
    else:
        section = g3d_profiles_parser.makeProfile(profile=g3d_profile)

    if g3d_profile[6] == 'R':
        height = section.Height
        width = section.Width
    elif g3d_profile[6] == 'C':
        height = width = section.Diameter

    length = DraftVecUtils.dist(p1, p2)

    delta_list = [
        App.Vector(height / 2, -width / 2, 0),
        App.Vector(0, -width / 2, 0),
        App.Vector(-height / 2, -width / 2, 0),
        App.Vector(height / 2, 0, 0),
        App.Vector(0, 0, 0),
        App.Vector(-height / 2, 0, 0),
        App.Vector(height / 2, width / 2, 0),
        App.Vector(0, width / 2, 0),
        App.Vector(-height / 2, width / 2, 0),
    ]
    delta = delta_list[anchor]

    pl = App.Placement()  # objet Placement
    pl.Base = p1  # base est coordonnée p1
    zaxis = p2.sub(p1)  # zaxis = soustraction de p2 - p1
    inclination = inclination * -1
    if zaxis.x == 0 and zaxis.y == 0:  # orientation verticale
        up = App.Vector(0, -1, 0)
        yaxis = up.cross(zaxis)  # yaxis = produit vectoriel entre Z et zaxis
        xaxis = zaxis.cross(
            yaxis)  # xaxis = produit vectoriel entre zaxis et yaxis
        pl.Rotation = App.Rotation(xaxis, yaxis, zaxis, "ZXY")
        #inclination = inclination + 180.0
        inclination = inclination + 90.0
        pl.Rotation = App.Rotation(pl.Rotation.multVec(App.Vector(0, 0, 1)),
                                   inclination).multiply(pl.Rotation)
    else:
        up = App.Vector(0, 0, 1)  # vector up = Z
        yaxis = up.cross(zaxis)  # yaxis = produit vectoriel entre Z et zaxis
        xaxis = zaxis.cross(
            yaxis)  # xaxis = produit vectoriel entre zaxis et yaxis
        pl.Rotation = App.Rotation(xaxis, yaxis, zaxis, "ZXY")
        inclination = inclination + 90.0
        pl.Rotation = App.Rotation(pl.Rotation.multVec(App.Vector(0, 0, 1)),
                                   inclination).multiply(pl.Rotation)

    delta = pl.Rotation.multVec(delta)
    pl.Base = p1.add(delta)

    section.Placement = pl

    beam = Arch.makeStructure(section, length=length)

    beam.Profile = g3d_profile[1]
    # Set color
    color = g3d_profile[7].split(",")
    r = float(color[0]) / 255.0
    g = float(color[1]) / 255.0
    b = float(color[2]) / 255.0
    beam.ViewObject.ShapeColor = (r, g, b)

    beam.Label = g3d_profile[1]
    beam.IfcType = u"Transport Element"
    beam.PredefinedType = u"NOTDEFINED"
    beam.Tag = u"Gespal"
    beam.Description = str(g3d_profile[0])
    beam.MoveBase = True
    App.activeDocument().recompute(None, True, True)
    return beam
    def makeTransaction(self, point):
        p1 = self.basepoint
        p3 = point
        diagonal = p3.sub(p1)
        p2 = p1.add(DraftVecUtils.project(diagonal, self.wp.v))
        p4 = p1.add(DraftVecUtils.project(diagonal, self.wp.u))
        length = p4.sub(p1).Length
        a = abs(DraftVecUtils.angle(p4.sub(p1), self.wp.u, self.wp.axis))
        if a > 1:
            length = -length
        height = p2.sub(p1).Length
        a = abs(DraftVecUtils.angle(p2.sub(p1), self.wp.v, self.wp.axis))
        if a > 1:
            height = -height
        base = p1
        p = self.wp.getRotation()
        qr = p.Rotation.Q
        qr = ("(" + str(qr[0]) + "," + str(qr[1]) + "," + str(qr[2]) + "," +
              str(qr[3]) + ")")
        warn = False
        if (length > 0) and (height > 0):
            print_debug("length > 0) and (height > 0)")
            base = base.add(diagonal.scale(0.5, 0.5, 0.5))

        elif (length == 0) or (height == 0):
            print_debug("(length == 0) or (height == 0)")
            print_debug("Abort")
            warn = True

        elif (length < 0) and (height < 0):
            print_debug("(length < 0) and (height < 0)")
            length = -length
            height = -height
            base = base.add(diagonal.scale(0.5, 0.5, 0.5))

        elif length < 0:
            print_debug("length < 0")
            length = -length
            base = base.add(diagonal.scale(0.5, 0.5, 0.5))

        elif height < 0:
            print_debug("height < 0")
            height = -height
            base = base.add(diagonal.scale(0.5, 0.5, 0.5))

        else:
            print_debug("Situation inconnue. Veuillez contacter le support.")
            print_debug("Abort")
            warn = True

        print_debug("Start Panel transaction")
        if warn == False:
            print_debug("The if condition is True")
            App.ActiveDocument.openTransaction(
                translate("Gespal3D", "Ajouter un panneau"))
            print_debug("open transaction : Ok")
            Gui.addModule("Arch")
            print_debug("addModule Arch : Ok")
            # Create panel wit Arch Tool
            Gui.doCommand("p = Arch.makePanel(" + "length=" + str(length) +
                          "," + "width=" + str(height) + "," + "thickness=" +
                          str(self.thickness) + ")")

            Gui.doCommand("pl = App.Placement()")
            Gui.doCommand("pl.Rotation.Q = " + qr)
            Gui.doCommand("pl.Base = " + DraftVecUtils.toString(base))
            Gui.doCommand("p.Placement = pl")

            # Info Gespal
            Gui.doCommand('p.Label = "' + self.Profile[1] + '"')
            Gui.doCommand('p.IfcType = u"Transport Element"')
            Gui.doCommand('p.PredefinedType = u"NOTDEFINED"')
            Gui.doCommand('p.Tag = u"Gespal"')
            Gui.doCommand('p.Description = "' + str(self.Profile[0]) + '"')

            color = self.Profile[-2].split(",")
            r = str(int(color[0]) / 255)
            g = str(int(color[1]) / 255)
            b = str(int(color[2]) / 255)
            Gui.doCommand("p.ViewObject.ShapeColor = (" + r + "," + g + "," +
                          b + ")")

            print_debug("all doCommand : Ok")
            App.ActiveDocument.commitTransaction()
            print_debug("commitTransaction : Ok")
            App.ActiveDocument.recompute()
            print_debug("activeDoc recompute : Ok")

        else:
            App.Console.PrintWarning(u"Annulation de la commande")
            App.Console.PrintWarning(
                u"La sélection des points est incompatible avec le plan choisi."
            )
            #msg = QtGui.QMessageBox.information(Gui.getMainWindow(), u"Annulation de la commande", u"La sélection des points est incompatible avec le plan choisi.")

        if self.continueCmd:
            self.Activated()
 def acceptAndClose(self):
     self.con.close()
     self.form.close()
     print_debug("acceptAndClose done")
    def makeTransaction(self, point=None):
        """g3d beam makeTransaction"""
        msg = ["", "----------", "makeTransaction"]
        msg.append("la direction est : {}".format(str(self.direction)))
        msg.append("le mode de pattern est : {}".format(str(self.pattern)))
        msg.append("Détails de la liste des points cliqués :")
        msg.append("longueur = {}".format(len(self.clicked_points)))
        for p in self.clicked_points:
            msg.append(str(p))
        print_debug(msg)

        commands = []
        if self.pattern == 'none':
            transaction_name = "Create G3DBeam from 1 points"
            command = "freecad.workbench_gespal3d.g3d_beam.makeG3DBeam(" \
            + "g3d_profile={}, ".format(str(self.Profile)) \
            + "p1={}, ".format(str(DraftVecUtils.tup(self.clicked_points[0],True))) \
            + "p2={}, ".format(str(DraftVecUtils.tup(self.clicked_points[1],True))) \
            + "anchor={}, ".format(self.anchor_idx) \
            + "inclination={}, ".format(self.inclination) \
            + ")"
            commands.append(command)

        elif self.pattern == 'distribution':
            transaction_name = "Création d'une répartition de composants."
            length = DraftVecUtils.dist(self.clicked_points[0],
                                        self.clicked_points[2])
            space = length / (self.distribution_qty + 1)
            vec = self.clicked_points[2].sub(self.clicked_points[0])
            vec_norm = vec.normalize()
            vec_axe = vec_norm.multiply(space)
            p1 = self.clicked_points[0]
            p2 = self.clicked_points[1]
            qty = self.distribution_qty
            if self.distribution_start.isChecked():
                p1 = p1.sub(vec_axe)
                p2 = p2.sub(vec_axe)
                qty += 1
            if self.distribution_end.isChecked():
                qty += 1
            for distri in range(qty):
                #if not self.distribution_start.isChecked():
                p1 = p1.add(vec_axe)
                p2 = p2.add(vec_axe)
                command = "freecad.workbench_gespal3d.g3d_beam.makeG3DBeam(" \
                + "g3d_profile={}, ".format(str(self.Profile)) \
                + "p1={}, ".format(str(DraftVecUtils.tup(p1, True))) \
                + "p2={}, ".format(str(DraftVecUtils.tup(p2, True))) \
                + "anchor={}, ".format(self.anchor_idx) \
                + "inclination={}, ".format(self.inclination) \
                + ")"
                commands.append(command)

        elif self.pattern == 'filling':
            transaction_name = "Création d'un remplissage de composants."
            length = DraftVecUtils.dist(self.clicked_points[0],
                                        self.clicked_points[2])
            space = length / (self.distribution_qty + 1)
            vec = self.clicked_points[2].sub(self.clicked_points[0])
            vec_norm = vec.normalize()
            vec_axe = vec_norm.multiply(space)
            p1 = self.clicked_points[0]
            p2 = self.clicked_points[1]
            for qty in range(self.distribution_qty):
                p1 = p1.add(vec_axe)
                p2 = p2.add(vec_axe)
                command = "freecad.workbench_gespal3d.g3d_beam.makeG3DBeam(" \
                + "g3d_profile={}, ".format(str(self.Profile)) \
                + "p1={}, ".format(str(DraftVecUtils.tup(p1, True))) \
                + "p2={}, ".format(str(DraftVecUtils.tup(p2, True))) \
                + "anchor={}, ".format(self.anchor_idx) \
                + "inclination={}, ".format(self.inclination) \
                + ")"
                commands.append(command)

        else:
            App.Console.PrintWarning("This mode is not implemented")
            return

        App.ActiveDocument.openTransaction(
            translate("Gespal3D", transaction_name))
        Gui.addModule("freecad.workbench_gespal3d.g3d_beam")
        for command in commands:
            Gui.doCommand(command)
        App.ActiveDocument.commitTransaction()
        App.ActiveDocument.recompute()

        if self.continueCmd:
            self.Activated()
            return
        else:
            return
 def doubleClick(self, itm):
     row = int(itm.row())
     column = int(itm.column())
     oldvalue = itm.text()
     print_debug("Double Click : enter edit mode cell row {} column {} with value : {}".format(row, column, oldvalue))
     self.lastEditItem["row"] = row
     self.lastEditItem["column"] = column
     self.lastEditItem["value"] = oldvalue
     self.componentTable.setSortingEnabled(False)
     if column == 1: # Category
         self.componentTable.blockSignals(True)
         cat_des = oldvalue
         #cat = QtGui.QTableWidgetItem(str(""))
         comboBox = QtGui.QComboBox()
         #comboBox.setEditable(True)
         comboBox.addItems(self.cat_name_list)
         index = comboBox.findText(cat_des, QtCore.Qt.MatchFixedString)
         comboBox.setCurrentIndex(index)
         comboBox.setProperty('row', row)
         comboBox.setProperty('column', column)
         self.componentTable.blockSignals(False)
         #comboBox.currentIndexChanged.connect(self.Combo_indexchanged)
         comboBox.activated.connect(self.Combo_indexchanged2)
         #comboBox.currentTextChanged.connect(self.categoryCB_textChanged)
         self.componentTable.setCellWidget(row, column, comboBox)
     elif column == 3: # Section Shape
         self.componentTable.blockSignals(True)
         shape_type_name = oldvalue
         shape_type = QtGui.QTableWidgetItem(str(shape_type_name))
         self.componentTable.setItem(row, column, shape_type)
         comboBox = QtGui.QComboBox()
         comboBox.setEditable(False)
         comboBox.addItems(['R','C'])
         index = comboBox.findText(shape_type_name, QtCore.Qt.MatchFixedString)
         comboBox.setCurrentIndex(index)
         comboBox.setProperty('row', row)
         comboBox.setProperty('column', column)
         self.componentTable.blockSignals(False)
         comboBox.currentIndexChanged.connect(self.Combo_indexchanged)
         #comboBox.currentTextChanged.connect(self.categoryCB_textChanged)
         self.componentTable.setCellWidget(row, column, comboBox)
     elif column == 4 or column == 5 or column == 6: # WIDTH or HEIGHT or LENGTH
         self.componentTable.blockSignals(True)
         value = oldvalue
         self.componentTable.removeCellWidget(row, column)
         spinbox = QtGui.QSpinBox()
         spinbox.setProperty('row', row)
         spinbox.setProperty('column', column)
         spinbox.setMinimum(0)
         spinbox.setMaximum(100000)
         spinbox.setValue(int(value))
         spinbox.valueChanged.connect(self.SpinBox_valuechanged)
         self.componentTable.blockSignals(False)
         self.componentTable.setCellWidget(row, column, spinbox)
     elif column == 7:
         print_debug(["checkState",itm.isSelected()])
         couleur = QtGui.QColorDialog.getColor()
         if couleur.isValid():
             red   = int(str(couleur.name()[1:3]),16)    # decode hexadecimal to int()
             green = int(str(couleur.name()[3:5]),16)    # decode hexadecimal to int()
             blue  = int(str(couleur.name()[5:7]),16)    # decode hexadecimal to int()
             self.componentTable.item(row, column).setBackground(QtGui.QColor(red, green, blue,))
     elif column == 8: # Mass Vol
         self.componentTable.blockSignals(True)
         value = oldvalue
         self.componentTable.removeCellWidget(row, column)
         spinbox = QtGui.QSpinBox()
         spinbox.setProperty('row', row)
         spinbox.setProperty('column', column)
         spinbox.setMinimum(0)
         spinbox.setMaximum(100000)
         spinbox.setValue(int(value))
         spinbox.valueChanged.connect(self.SpinBox_valuechanged)
         self.componentTable.blockSignals(False)
         self.componentTable.setCellWidget(row, column, spinbox)
 def closeEvent(self, event):
     print_debug(["closeEvent", event])
     self.con.close()
    def restoreParams(self):
        print_debug(["", "Start restoreParams"])

        self.composant = self.params.GetInt("BeamPreset", 1)
        self.Width = self.params.GetFloat("BeamWidth", 100)
        self.Height = self.params.GetFloat("BeamHeight", 22)
        self.Length = self.params.GetFloat("BeamLength", 1200)
        self.Profile = None
        self.anchor_idx = self.params.GetInt("BeamAnchor", 0)
        self.inclination = self.params.GetFloat("BeamDev", 0.0)
        self.continueCmd = self.params.GetBool("BeamContinue", True)
        self.fill_space = self.params.GetFloat("BeamFillingSpace", 0.0)
        self.distribution_qty = self.params.GetInt("BeamDistributionQty", 1)
        self.direction = self.params.GetString(
            "BeamDirection",
            '+x')  # direction could be line, +x, -x, +y, -y, +z, -z
        self.pattern = self.params.GetString(
            "BeamPattern",
            'none')  # pattern could be 'none', 'distribution', 'filling'
        self.fixed_length = self.params.GetBool("BeamFixLength", 0)
        self.fixed_component = False

        if self.Width is not None:
            print_debug("restore beam width")
            self.width_input.setText(
                App.Units.Quantity(self.Width, App.Units.Length).UserString)

        if self.Height is not None:
            print_debug("restore beam height")
            self.height_input.setText(
                App.Units.Quantity(self.Height, App.Units.Length).UserString)

        if self.Length is not None:
            print_debug("restore beam length")
            self.length_input.setText(
                App.Units.Quantity(self.Length, App.Units.Length).UserString)

        if self.direction is not None:
            print_debug("restore direction")
            directions = ['+x', '+y', '+z', '-x', '-y', '-z', 'line']
            idx = directions.index(self.direction)
            self.direction_cb.setCurrentIndex(idx)

        if self.composant is not None:
            print_debug("restore composant")
            comp = g3d_connect_db.getComposant(id=self.composant)
            cat = comp[2]
            n = 0
            for x in self.categories:
                if x[0] == cat:
                    self.categories_cb.setCurrentIndex(n)
                    break
                n += 1
            self.composant_items = g3d_connect_db.getComposants(categorie=cat)
            self.composant_cb.blockSignals(True)
            self.composant_cb.clear()
            self.composant_cb.addItems([x[1] for x in self.composant_items])
            self.composant_cb.blockSignals(False)
            n = 0
            for x in self.composant_items:
                if x[0] == self.composant:
                    self.composant_cb.setCurrentIndex(n)
                    self.setComposant(n)
                    break
                n += 1

        if self.inclination is not None:
            print_debug("restore inclination")
            self.inclination_input.setText(
                App.Units.Quantity(self.inclination,
                                   App.Units.Angle).UserString)

        if self.anchor_idx is not None:
            print_debug("restore anchor")
            anchor_button = self.insert_group.buttons()[self.anchor_idx]
            anchor_button.setChecked(True)

        if self.pattern is not None:
            print_debug("restore pattern")
            if len(self.clicked_points) > 0:
                #print_debug("len clicked point > 0")
                if self.pattern == 'distribution':
                    self.distribution_cb.setChecked(True)
                    if self.params.GetBool("BeamDistributionStart", False):
                        self.distribution_start.setChecked(True)
                    if self.params.GetBool("BeamDistributionEnd", False):
                        self.distribution_end.setChecked(True)
                elif self.pattern == 'filling':
                    self.filling_cb.setChecked(True)
            else:
                #print_debug("len clicked point <= 0")
                self.filling_cb.setChecked(False)
                self.distribution_cb.setChecked(False)
                self.params.SetBool("BeamDistributionStart", False)
                self.params.SetBool("BeamDistributionEnd", False)
                self.pattern = 'none'
                self.params.SetString("BeamPattern", 'none')
            print_debug(self.pattern)

        if self.distribution_qty is not None:
            print_debug("restore array_qty")
            self.distribution_input.setValue(self.distribution_qty)

        if self.fill_space is not None:
            print_debug("restore fillspace")
            self.filling_input.setText(
                App.Units.Quantity(self.fill_space,
                                   App.Units.Length).UserString)

        if self.fixed_length is not None:
            print_debug("restore fixlength")
            self.fixlength_checkbox.setChecked(bool(self.fixed_length))

        if self.continueCmd is not None:
            print_debug("restore continue mode")
            self.continue_cb.setChecked(self.continueCmd)

        if self.direction != 'line':
            if len(self.clicked_points) == 0:
                self.tracker.on()

        if DEBUG:
            messages = ["", "End of restore params :"]
            messages.append("détails de la liste des points cliqués :")
            messages.append("longueur = {}".format(len(self.clicked_points)))
            for p in self.clicked_points:
                messages.append(str(p))
            messages.append("Profile = {}".format(self.Profile))
            messages.append("Width = {}".format(self.Width))
            messages.append("Height = {}".format(self.Height))
            messages.append("Length = {}".format(self.Length))
            messages.append("Anchor index = {}".format(self.anchor_idx))
            messages.append("direction = {}".format(self.direction))
            messages.append("Inclination = {}".format(self.inclination))
            messages.append("Pattern = {}".format(self.pattern))
            messages.append("FillSpace = {}".format(self.fill_space))
            messages.append("array_qty = {}".format(self.distribution_qty))
            messages.append("continueCmd = {}".format(self.continueCmd))
            messages.append("fixed = {}".format(str(self.fixed_length)))
            messages.append("")
            print_debug(messages)
    def populate(self):
        self.componentTable.blockSignals(True)
        self.cur.execute("SELECT * FROM Famille_Composant")
        cat_list = self.cur.fetchall()
        if len(cat_list) > 0:
            self.cat_name_list = [x[1] for x in cat_list]
        else:
            self.cat_name_list = []
        self.cat_name_list.append("Ajouter...")
        self.cur.execute("SELECT * FROM Composant")
        data = self.cur.fetchall()
        count = len(data)
        self.componentTable.setRowCount(count)
        for i, item in enumerate(data):
            index_item = QtGui.QTableWidgetItem()
            index_item.setData(QtCore.Qt.EditRole, int(item[0]))
            # EDITABLE = QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled
            # NONEDITABLE = QtCore.Qt.ItemIsEnabled
            index_item.setFlags(QtCore.Qt.ItemIsEnabled)
            self.componentTable.setItem(i, 0, index_item)
            
            # Categorie
            if len(cat_list) > 0 :
                cat_des = cat_list[int(item[2])-1][1]
            else:
                cat_des = "Ajouter..."
            cat = QtGui.QTableWidgetItem(str(cat_des))
            self.componentTable.setItem(i, 1, cat)
            
            # Component name
            name = QtGui.QTableWidgetItem(str(item[1]))
            self.componentTable.setItem(i, 2, name)

            # Shape
            shape = QtGui.QTableWidgetItem(str(item[6]))
            self.componentTable.setItem(i, 3, shape)
            
            # Width
            width = QtGui.QTableWidgetItem()
            width.setData(QtCore.Qt.EditRole, int(item[4]))
            self.componentTable.setItem(i, 4, width)

            # Height
            height = QtGui.QTableWidgetItem()
            height.setData(QtCore.Qt.EditRole, int(item[5]))
            self.componentTable.setItem(i, 5, height)

            # Length
            length = QtGui.QTableWidgetItem()
            length.setData(QtCore.Qt.EditRole, int(item[3]))
            self.componentTable.setItem(i, 6, length)

            # Color
            color = [int(x) for x in item[7].split(',')]
            self.componentTable.setItem(i, 7, QtGui.QTableWidgetItem())
            if len(color) == 3:
                self.componentTable.item(i, 7).setBackground(QtGui.QColor(color[0], color[1], color[2],))
            else:
                self.componentTable.item(i, 7).setBackground(QtGui.QColor(0, 0, 0,))
            self.componentTable.item(i, 7).setFlags(QtCore.Qt.ItemIsEnabled)
            
            # Mass volumique
            massvol = QtGui.QTableWidgetItem(str(item[8]))
            self.componentTable.setItem(i, 8, massvol)
        
        self.componentTable.blockSignals(False)
        print_debug("populate done")