Example #1
0
    def toPixmap(self, value: str) -> QtGui.QPixmap:
        """Create a QPixmap from a text."""

        from pineboolib.application.utils import xpm

        ret_ = QtGui.QPixmap()

        file_name = xpm.cache_xpm(value)
        if file_name:
            ret_ = QtGui.QPixmap(file_name)

        return ret_
Example #2
0
    def iconModule(self, id_module: str) -> "QtGui.QPixmap":
        """
        To obtain the icon associated with a module.

        @param id_moule Identifier of the module from which to obtain the icon
        @return QPixmap with the icon
        """

        pix = QtGui.QPixmap()
        mod_obj = self.dict_info_mods_.get(id_module.upper(), None)
        mod_icono = getattr(mod_obj, "icono", None)
        if mod_icono is not None:
            pix = QtGui.QPixmap(xpm.cache_xpm(mod_icono))

        return pix
Example #3
0
    def run(self) -> bool:
        """Run project. Connects to DB and loads data."""

        self.pending_conversion_list = []

        if self.actions:
            del self.actions

        if self.tables:
            del self.tables

        self.actions = {}
        self.tables = {}

        if self.dgi is None:
            raise Exception("DGI not loaded")

        if not self.conn_manager or "main_conn" not in self.conn_manager.connections_dict.keys(
        ):
            raise exceptions.NotConnectedError(
                "Cannot execute Pineboo Project without a connection in place")

        conn = self.conn_manager.mainConn()
        db_name = conn.DBName()
        # TODO: Refactorizar esta función en otras más sencillas
        # Preparar temporal

        if self.delete_cache and os.path.exists(path._dir(
                "cache/%s" % db_name)):

            self.message_manager().send("splash", "showMessage",
                                        ["Borrando caché ..."])
            LOGGER.debug("DEVELOP: delete_cache Activado\nBorrando %s",
                         path._dir("cache/%s" % db_name))
            for root, dirs, files in os.walk(path._dir("cache/%s" % db_name),
                                             topdown=False):
                for name in files:
                    os.remove(os.path.join(root, name))
                for name in dirs:
                    os.rmdir(os.path.join(root, name))

        else:
            keep_images = settings.config.value(
                "ebcomportamiento/keep_general_cache", False)
            if keep_images is False:
                for file_name in os.listdir(self.tmpdir):
                    if file_name.find(".") > -1 and not file_name.endswith(
                            "sqlite3"):
                        file_path = os.path.join(self.tmpdir, file_name)
                        try:
                            os.remove(file_path)
                        except Exception:
                            LOGGER.warning(
                                "No se ha podido borrar %s al limpiar la cache",
                                file_path)
                            pass

        if not os.path.exists(path._dir("cache")):
            os.makedirs(path._dir("cache"))

        if not os.path.exists(path._dir("cache/%s" % db_name)):
            os.makedirs(path._dir("cache/%s" % db_name))

        # Conectar:

        # Se verifica que existen estas tablas
        for table in (
                "flareas",
                "flmodules",
                "flfiles",
                "flgroups",
                "fllarge",
                "flserial",
                "flusers",
                "flvar",
                "flmetadata",
                "flsettings",
                "flupdates",
                "flmetadata",
                "flseqs",
                "flsettings",
        ):
            if not self.conn_manager.manager().existsTable(table):
                self.conn_manager.manager().createSystemTable(table)

        cursor_ = self.conn_manager.dbAux().cursor()
        self.areas = {}
        cursor_.execute(
            """ SELECT idarea, descripcion FROM flareas WHERE 1 = 1""")
        for idarea, descripcion in list(cursor_):
            self.areas[idarea] = AreaStruct(idarea=idarea,
                                            descripcion=descripcion)

        self.areas["sys"] = AreaStruct(idarea="sys",
                                       descripcion="Area de Sistema")

        # Obtener módulos activos
        cursor_.execute(
            """ SELECT idarea, idmodulo, descripcion, icono FROM flmodules WHERE bloqueo = %s """
            % conn.driver().formatValue("bool", "True", False))

        self.modules = {}

        for idarea, idmodulo, descripcion, icono in cursor_:
            icono = xpm.cache_xpm(icono)
            self.modules[idmodulo] = module.Module(idarea, idmodulo,
                                                   descripcion, icono)

        file_object = open(
            utils_base.filedir(utils_base.get_base_dir(), "system_module",
                               "sys.xpm"), "r")
        icono = file_object.read()
        file_object.close()
        # icono = clearXPM(icono)

        self.modules["sys"] = module.Module("sys", "sys", "Administración",
                                            icono)

        cursor_.execute(
            """ SELECT idmodulo, nombre, sha FROM flfiles WHERE NOT sha = '' ORDER BY idmodulo, nombre """
        )

        file_1 = open(path._dir("project.txt"), "w")
        self.files = {}

        count = 0

        list_files: List[str] = []

        for idmodulo, nombre, sha in list(cursor_):
            if not self.dgi.accept_file(nombre):
                continue

            count += 1
            if idmodulo not in self.modules:
                continue  # I
            fileobj = file.File(idmodulo, nombre, sha, db_name=db_name)
            if nombre in self.files:
                LOGGER.warning("run: file %s already loaded, overwritting..." %
                               nombre)
            self.files[nombre] = fileobj
            self.modules[idmodulo].add_project_file(fileobj)
            file_1.write(fileobj.filekey + "\n")

            fileobjdir = os.path.dirname(path._dir("cache", fileobj.filekey))
            file_name = path._dir("cache", fileobj.filekey)
            if not os.path.exists(fileobjdir):
                os.makedirs(fileobjdir)

            if os.path.exists(file_name):
                if file_name.endswith(".qs"):
                    folder_path = os.path.dirname(file_name)
                    static_flag = "%s/STATIC" % folder_path
                    file_name_py = "%s.py" % file_name[:-3]
                    if os.path.exists(static_flag):
                        os.remove(static_flag)
                        if os.path.exists(file_name):
                            os.remove(file_name)
                        if os.path.exists(file_name_py):
                            os.remove(file_name_py)

                    elif os.path.exists(file_name_py):
                        continue

                elif file_name.endswith(".mtd"):
                    if settings.config.value(
                            "ebcomportamiento/orm_enabled",
                            False) and not settings.config.value(
                                "ebcomportamiento/orm_parser_disabled", False):
                        if os.path.exists(
                                "%s_model.py" %
                                path._dir("cache", fileobj.filekey[:-4])):
                            continue
                else:
                    continue

            cur2 = self.conn_manager.useConn("dbAux").cursor()
            sql = (
                "SELECT contenido FROM flfiles WHERE idmodulo = %s AND nombre = %s AND sha = %s"
                % (
                    conn.driver().formatValue("string", idmodulo, False),
                    conn.driver().formatValue("string", nombre, False),
                    conn.driver().formatValue("string", sha, False),
                ))
            cur2.execute(sql)
            for (contenido, ) in list(cur2):

                encode_ = "utf-8" if str(nombre).endswith(
                    (".kut", ".ts", ".py")) else "ISO-8859-15"

                folder = path._dir(
                    "cache",
                    "/".join(
                        fileobj.filekey.split("/")
                        [:len(fileobj.filekey.split("/")) - 1]),
                )
                if os.path.exists(folder) and not os.path.exists(
                        file_name
                ):  # Borra la carpeta si no existe el fichero destino
                    for root, dirs, files in os.walk(folder):
                        for file_item in files:
                            os.remove(os.path.join(root, file_item))

                if contenido and not os.path.exists(file_name):
                    self.message_manager().send(
                        "splash", "showMessage",
                        ["Volcando a caché %s..." % nombre])
                    file_2 = open(file_name, "wb")
                    txt = contenido.encode(encode_, "replace")
                    file_2.write(txt)
                    file_2.close()

            if self.parse_project and nombre.endswith(".qs"):
                if os.path.exists(file_name):
                    list_files.append(file_name)

        file_1.close()
        self.message_manager().send("splash", "showMessage",
                                    ["Convirtiendo a Python ..."])

        if list_files:
            self.parse_script_list(list_files)

        # Cargar el núcleo común del proyecto

        for root, dirs, files in os.walk(
                utils_base.filedir(utils_base.get_base_dir(),
                                   "system_module")):
            # list_files = []
            for nombre in files:
                if root.find("modulos") == -1:
                    fileobj = file.File("sys",
                                        nombre,
                                        basedir=root,
                                        db_name=db_name)
                    self.files[nombre] = fileobj
                    self.modules["sys"].add_project_file(fileobj)

                    # if self.parse_project and nombre.endswith(".qs"):
                    # self.parseScript(path._dir(root, nombre))
                    #    list_files.append(path._dir(root, nombre))

            # self.parse_script_lists(list_files)

        if settings.config.value(
                "ebcomportamiento/orm_enabled",
                False) and not settings.config.value(
                    "ebcomportamiento/orm_load_disabled", False):
            self.message_manager().send("splash", "showMessage",
                                        ["Cargando objetos ..."])
            from pineboolib.application.parsers.mtdparser import pnormmodelsfactory

            pnormmodelsfactory.load_models()

        # FIXME: ACLs needed at this level?
        # self.acl_ = FLAccessControlLists()
        # self.acl_.init()

        return True
Example #4
0
    def data(self, index: QtCore.QModelIndex, role: int = QtCore.Qt.DisplayRole) -> Any:
        """
        Retrieve information about a record.

        (overload of QAbstractTableModel)
        Could return alignment, backgroun color, value... depending on role.

        @param index. Register position
        @param role. information type required
        @return solicited data
        """

        row = index.row()
        col = index.column()
        field = self.metadata().indexFieldObject(col)
        _type = field.type()
        res_color_function: List[str] = []
        if _type != "check":

            # r = [x for x in self._data[row]]
            # self._data[row] = r
            # d = r[col]
            # self.seekRow(row)
            # d = self._current_row_data[col]
            # d = self._data[row][col]
            result: Any = None
            if row not in self.grid_row_tmp.keys():
                self.grid_row_tmp = {}
                self.grid_row_tmp[row] = self.driver_sql().getRow(
                    row, self._curname, self.cursorDB()
                )
                if not self.grid_row_tmp[row]:  # refresh grid if cursor is deleted.
                    self.refresh()
                    return

            tuple = self.grid_row_tmp[row]
            if tuple:
                result = tuple[col]

        else:
            primary_key = str(self.value(row, self.metadata().primaryKey()))
            if primary_key not in self._check_column.keys():
                result = QtWidgets.QCheckBox()
                self._check_column[primary_key] = result

        if self.parent_view and role in [QtCore.Qt.BackgroundRole, QtCore.Qt.ForegroundRole]:
            fun_get_color, iface = self.parent_view.functionGetColor()
            if fun_get_color is not None:
                context_ = None
                fun_name_ = None
                if fun_get_color.find(".") > -1:
                    list_ = fun_get_color.split(".")
                    from pineboolib.application.safeqsa import SafeQSA

                    qsa_widget = SafeQSA.get_any(list_[0])
                    fun_name_ = list_[1]
                    if qsa_widget:
                        context_ = qsa_widget.iface
                else:
                    context_ = iface
                    fun_name_ = fun_get_color

                function_color = getattr(context_, fun_name_, None)
                if function_color is not None:
                    field_name = field.name()
                    field_value = result
                    cursor = self._parent
                    selected = False
                    res_color_function = function_color(
                        field_name, field_value, cursor, selected, _type
                    )
                else:
                    raise Exception(
                        "No se ha resuelto functionGetColor %s desde %s" % (fun_get_color, context_)
                    )
        # print("Data ", index, role)
        # print("Registros", self.rowCount())
        # roles
        # 0 QtCore.Qt.DisplayRole
        # 1 QtCore.Qt.DecorationRole
        # 2 QtCore.Qt.EditRole
        # 3 QtCore.Qt.ToolTipRole
        # 4 QtCore.Qt.StatusTipRole
        # 5 QtCore.Qt.WhatThisRole
        # 6 QtCore.Qt.FontRole
        # 7 QtCore.Qt.TextAlignmentRole
        # 8 QtCore.Qt.BackgroundRole
        # 9 QtCore.Qt.ForegroundRole

        if role == QtCore.Qt.CheckStateRole and _type == "check":
            if primary_key in self._check_column.keys():
                if self._check_column[primary_key].isChecked():
                    return QtCore.Qt.Checked

            return QtCore.Qt.Unchecked

        elif role == QtCore.Qt.TextAlignmentRole:
            result = QtCore.Qt.AlignVCenter
            if _type in ("int", "double", "uint"):
                result = result | QtCore.Qt.AlignRight
            elif _type in ("bool", "date", "time"):
                result = result | QtCore.Qt.AlignCenter
            elif _type in ("unlock", "pixmap"):
                result = result | QtCore.Qt.AlignHCenter

            return result

        elif role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
            if not field.visible():
                result = None
            # r = self._vdata[row]
            elif _type == "bool":
                if result in (True, "1"):
                    result = "Sí"
                else:
                    result = "No"

            elif _type in ("unlock", "pixmap"):

                result = None

            elif _type in ("string", "stringlist", "timestamp") and not result:
                result = ""

            elif _type == "time" and result:
                result = str(result)

            elif _type == "date":
                # Si es str lo paso a datetime.date
                if isinstance(result, str):
                    if len(result.split("-")[0]) == 4:
                        result = date_conversion.date_amd_to_dma(result)

                    if result:
                        list_ = result.split("-")
                        result = datetime.date(int(list_[2]), int(list_[1]), int(list_[0]))

                if isinstance(result, datetime.date):
                    # Cogemos el locale para presentar lo mejor posible la fecha
                    try:
                        locale.setlocale(locale.LC_TIME, "")
                        if os.name == "nt":
                            date_format = "%%d/%%m/%%y"
                        else:
                            date_format = locale.nl_langinfo(locale.D_FMT)
                        date_format = date_format.replace("y", "Y")  # Año con 4 dígitos
                        date_format = date_format.replace("/", "-")  # Separadores
                        result = result.strftime(date_format)
                    except AttributeError:
                        import platform

                        self.logger.warning(
                            "locale specific date format is not yet implemented for %s",
                            platform.system(),
                        )

            elif _type == "check":
                return

            elif _type == "double":
                if result is not None:
                    # d = QtCore.QLocale.system().toString(float(d), "f", field.partDecimal())
                    result = utils_base.format_double(
                        result, field.partInteger(), field.partDecimal()
                    )
            elif _type in ("int", "uint"):
                if result is not None:
                    result = QtCore.QLocale.system().toString(int(result))
            if self.parent_view is not None:
                self.parent_view.resize_column(col, result)

            return result

        elif role == QtCore.Qt.DecorationRole:
            pixmap = None
            if _type in ("unlock", "pixmap") and self.parent_view:
                row_height = self.parent_view.rowHeight(row)  # Altura row
                row_width = self.parent_view.columnWidth(col)

                if _type == "unlock":
                    if result in (True, "1"):
                        pixmap = QtGui.QPixmap(
                            utils_base.filedir("./core/images/icons", "unlock.png")
                        )
                    else:
                        pixmap = QtGui.QPixmap(
                            utils_base.filedir("./core/images/icons", "lock.png")
                        )
                else:
                    if not self._parent.private_cursor._is_system_table:
                        data = self.db().connManager().manager().fetchLargeValue(result)
                    else:
                        data = xpm.cache_xpm(result)

                    pixmap = QtGui.QPixmap(data)
                    if not pixmap.isNull():
                        new_size = row_height - 1
                        if new_size > row_width:
                            new_size = row_width

                        pixmap = pixmap.scaled(new_size, new_size)

                if self.parent_view.showAllPixmap() or row == self.parent_view.cur.at():
                    if pixmap and not pixmap.isNull() and self.parent_view:
                        new_pixmap = QtGui.QPixmap(row_width, row_height)  # w , h
                        center_width = (row_width - pixmap.width()) / 2
                        center_height = (row_height - pixmap.height()) / 2
                        new_pixmap.fill(QtCore.Qt.transparent)
                        painter = Qt.QPainter(new_pixmap)
                        painter.drawPixmap(
                            center_width, center_height, pixmap.width(), pixmap.height(), pixmap
                        )

                        pixmap = new_pixmap

            return pixmap

        elif role == QtCore.Qt.BackgroundRole:
            if _type == "bool":
                if result in (True, "1"):
                    result = QtGui.QBrush(QtCore.Qt.green)
                else:
                    result = QtGui.QBrush(QtCore.Qt.red)

            elif _type == "check":
                obj_ = self._check_column[primary_key]
                result = (
                    QtGui.QBrush(QtCore.Qt.green)
                    if obj_.isChecked()
                    else QtGui.QBrush(QtCore.Qt.white)
                )

            else:
                if res_color_function and len(res_color_function) and res_color_function[0] != "":
                    color_ = QtGui.QColor(res_color_function[0])
                    style_ = getattr(QtCore.Qt, res_color_function[2], None)
                    result = QtGui.QBrush(color_)
                    result.setStyle(style_)
                else:
                    result = None

            return result

        elif role == QtCore.Qt.ForegroundRole:
            if _type == "bool":
                if result in (True, "1"):
                    result = QtGui.QBrush(QtCore.Qt.black)
                else:
                    result = QtGui.QBrush(QtCore.Qt.white)
            else:
                if res_color_function and len(res_color_function) and res_color_function[1] != "":
                    color_ = QtGui.QColor(res_color_function[1])
                    style_ = getattr(QtCore.Qt, res_color_function[2], None)
                    result = QtGui.QBrush(color_)
                    result.setStyle(style_)
                else:
                    result = None

            return result

        # else:
        #    print("role desconocido", role)

        return None
Example #5
0
    def parseKey(self, ref_key: Optional[str] = None) -> Optional[str]:
        """
        Get filename of .png file cached on tempdata. If it does not exist it is created.

        @param. String of related tuple in fllarge.
        @return. Path to the file in tempdata.
        """

        ret = None
        table_name = "fllarge"
        if ref_key is not None:
            from PyQt5.QtGui import QPixmap

            value = None
            tmp_dir = config.value("ebcomportamiento/temp_dir")
            img_file = "%s/%s.png" % (tmp_dir, ref_key)

            if not os.path.exists(img_file) and ref_key[0:3] == "RK@":

                single_query = pnsqlquery.PNSqlQuery()
                single_query.exec_(
                    "SELECT valor FROM flsettings WHERE flkey='FLLargeMode'")
                one_fllarge = True

                if single_query.next():
                    if single_query.value(0) == "True":
                        one_fllarge = False

                if (
                        not one_fllarge
                ):  # Si no es FLLarge modo único añadimos sufijo "_nombre" a fllarge
                    table_name += "_%s" % ref_key.split("@")[1]

                qry = pnsqlquery.PNSqlQuery()
                qry.exec_("SELECT contenido FROM %s WHERE refkey='%s'" %
                          (table_name, ref_key))
                if qry.next():
                    value = xpm.cache_xpm(qry.value(0))

                if value:
                    ret = img_file
                    pix = QPixmap(value)
                    if not pix.save(img_file):
                        self.logger.warning(
                            "%s:refkey2cache No se ha podido guardar la imagen %s"
                            % (__name__, img_file))
                        ret = None
                    else:
                        ret = img_file
            elif ref_key.endswith(".xpm"):
                pix = QPixmap(ref_key)
                img_file = ref_key.replace(".xpm", ".png")
                if not pix.save(img_file):
                    self.logger.warning(
                        "%s:refkey2cache No se ha podido guardar la imagen %s"
                        % (__name__, img_file))
                    ret = None
                else:
                    ret = img_file

            else:

                ret = img_file

        return ret