Exemple #1
0
    def load_ts(self, file_name: str) -> bool:
        """Load a translation file from a path."""

        try:
            from pineboolib.core.utils.utils_base import load2xml

            root_ = load2xml(file_name)
            for context in root_.findall("context"):
                name_elem = context.find("name")
                if name_elem is None:
                    self.logger.warning("load_ts: <name> not found, skipping")
                    continue
                context_dict_key = name_elem.text
                if not context_dict_key:
                    continue
                if context_dict_key not in self._ts_translation_contexts.keys(
                ):
                    self._ts_translation_contexts[context_dict_key] = {}
                for message in context.findall("message"):
                    translation_elem, source_elem = (
                        message.find("translation"),
                        message.find("source"),
                    )
                    translation_text = translation_elem is not None and translation_elem.text
                    source_text = source_elem is not None and source_elem.text
                    if translation_text and source_text:
                        self._ts_translation_contexts[context_dict_key][
                            source_text] = translation_text

            return True
        except Exception:
            return False
    def loadKut(self, data: str) -> ElementTree:
        """
        Parse KUT xml from text.

        @param data. Input text (kut sources)
        @return xml.
        """
        return load2xml(data)
    def test_parser_tools_1(self) -> None:
        """Test parser tools."""
        from pineboolib.application.parsers.kugarparser import kparsertools
        from pineboolib.core.utils.utils_base import load2xml
        from pineboolib.application.database import pnsqlquery, pnsqlcursor
        from pineboolib.qsa import qsa
        import datetime
        import os

        qry = pnsqlquery.PNSqlQuery()
        qry.setTablesList("paises")
        qry.setSelect("codpais, bandera")
        qry.setFrom("paises")
        qry.setWhere("1=1")
        self.assertTrue(qry.exec_())
        self.assertTrue(qry.first())
        data = qsa.sys.toXmlReportData(qry)
        parser_tools = kparsertools.KParserTools()
        xml_data = load2xml(data.toString()).getroot()

        child = xml_data.findall("Row")[0]
        element = parser_tools.convertToNode(child)
        self.assertTrue(element)
        fecha_ = str(
            datetime.date.__format__(datetime.date.today(), "%d.%m.%Y"))

        self.assertEqual(parser_tools.getSpecial("Fecha"), fecha_)
        self.assertEqual(parser_tools.getSpecial("[Date]"), fecha_)
        self.assertEqual(parser_tools.getSpecial("NúmPágina", 1), "1")
        self.assertEqual(parser_tools.getSpecial("PageNo", 6), "6")
        self.assertEqual(parser_tools.getSpecial("[NúmPágina]", 12), "12")
        from PyQt5 import QtCore

        ret_ = QtCore.QLocale.system().toString(float("11.22"), "f", 2)

        self.assertEqual(parser_tools.calculated("11.22", 2, 2), ret_)
        self.assertEqual(parser_tools.calculated("2019-01-31T00:01:02", 3),
                         "31-01-2019")
        self.assertEqual(parser_tools.calculated("codpais", 1, None, child),
                         "ES")

        cur = pnsqlcursor.PNSqlCursor("paises")
        cur.select("1=1")
        cur.first()
        buffer = cur.buffer()
        if buffer:
            bandera = buffer.value("bandera")

            self.assertEqual(
                parser_tools.parseKey(str(bandera)),
                os.path.abspath("%s/%s.png" %
                                (application.PROJECT.tmpdir, bandera)),
            )
    def load(self) -> None:
        """Load module actions into project."""
        # Ojo: Almacena un arbol con los módulos cargados
        from pineboolib.application.qsadictmodules import QSADictModules

        tree = load2xml(self.path)
        self.root = tree.getroot()

        action = XMLAction(project=self.project, name=self.mod.name)
        if action is None:
            raise Exception("action is empty!")

        action.mod = self
        action.alias = self.mod.name
        # action.form = self.mod.name
        action.form = None
        action.table = None
        action.scriptform = self.mod.name
        self.project.actions[
            action.name
        ] = action  # FIXME: Actions should be loaded to their parent, not the singleton
        QSADictModules.save_action_for_root_module(action)

        for xmlaction in self.root:
            action_xml = XMLAction(xmlaction, project=self.project)
            action_xml.mod = self
            name = action_xml.name
            if not name or name == "unnamed":
                continue

            if QSADictModules.save_action_for_mainform(action_xml):

                self.project.actions[
                    name
                ] = action_xml  # FIXME: Actions should be loaded to their parent, not the singleton

            QSADictModules.save_action_for_formrecord(action_xml)
Exemple #5
0
    def createUI(
        file_name: str,
        connection: Optional["iconnection.IConnection"] = None,
        parent: Optional["QtWidgets.QWidget"] = None,
    ) -> "QtWidgets.QWidget":
        """
        Create a form from its description file.

        Use the FLManagerModules :: contentCached () method to get the XML text it describes the formula.

        @param file_name Name of the file that contains the description of the form.
        @param parent. Parent widget
        @return QWidget corresponding to the built form.
        """

        if ".ui" not in file_name:
            file_name += ".ui"

        form_path = file_name if os.path.exists(file_name) else path._path(
            file_name)
        conn_manager = application.PROJECT.conn_manager

        if "main_conn" in conn_manager.connections_dict.keys():
            mng_modules = conn_manager.managerModules()
            if mng_modules.static_db_info_ and mng_modules.static_db_info_.enabled_:
                ret_ui = mng_modules.contentStatic(file_name, True)

                if ret_ui is not None:
                    form_path = ret_ui

        if form_path is None:
            # raise AttributeError("File %r not found in project" % n)
            logger.debug("createUI: No se encuentra el fichero %s", file_name)

            return QtWidgets.QWidget()

        tree = utils_base.load2xml(form_path)

        if not tree:
            return parent or QtWidgets.QWidget()

        root_ = tree.getroot()

        UIVersion = root_.get("version")
        if UIVersion is None:
            UIVersion = "1.0"
        if parent is None:

            wid = root_.find("widget")
            if wid is None:
                raise Exception(
                    "No parent provided and also no <widget> found")
            xclass = wid.get("class")
            if xclass is None:
                raise Exception("class was expected")

            if UIVersion < "4.0":
                if xclass == "QMainWindow":
                    parent = qmainwindow.QMainWindow()
                elif xclass in ["QDialog", "QWidget"]:
                    parent = qdialog.QDialog()
            else:
                if xclass == "QMainWindow":
                    parent = QtWidgets.QMainWindow()
                elif xclass in ["QDialog", "QWidget"]:
                    parent = QtWidgets.QDialog()

            if parent is None:
                raise Exception("xclass not found %s" % xclass)

        if hasattr(parent, "widget"):
            w_ = parent.widget  # type: ignore [attr-defined] # noqa F821
        else:
            w_ = parent

        logger.info("Procesando %s (v%s)", file_name, UIVersion)
        if UIVersion < "4.0":
            qt3ui.load_ui(form_path, w_)
        else:
            from PyQt5 import uic  # type: ignore

            qtWidgetPlugings = utils_base.filedir("plugins/custom_widgets")
            if qtWidgetPlugings not in uic.widgetPluginPath:
                logger.warning("Añadiendo path %s a uic.widgetPluginPath",
                               qtWidgetPlugings)
                uic.widgetPluginPath.append(qtWidgetPlugings)
            uic.loadUi(form_path, w_)

        return w_
Exemple #6
0
    def _createBarcode(self) -> None:
        """Create barcode."""
        if self.barcode["value"] == "":
            return
        if self.barcode["type"] == BARCODE_ANY:
            logger.warning("Usando %s por defecto" %
                           self.typeToName(BARCODE_128))
            self.barcode["type"] = BARCODE_128

        type_ = self.typeToName(self.barcode["type"])
        value_ = self.barcode["value"]
        bg_ = self.barcode["bg"]
        fg_ = self.barcode["fg"]
        if not isinstance(self.barcode["bg"], str):
            bg_ = QtGui.QColor(self.barcode["bg"]).name()

        if not isinstance(self.barcode["fg"], str):
            fg_ = QtGui.QColor(self.barcode["fg"]).name()

        margin_ = self.barcode["margin"] / 10

        render_options: Dict[str, Any] = {}
        render_options["module_width"] = 0.6
        render_options["module_height"] = 10
        render_options["background"] = bg_.lower()
        render_options["foreground"] = fg_.lower()
        render_options["font_size"] = 8
        render_options["write_text"] = self.barcode["text"]
        render_options["text_distance"] = 35
        render_options["quiet_zone"] = margin_
        if self.barcode["text"]:
            render_options["text"] = value_
        else:
            render_options["text"] = " "

        barC = barcode.get_barcode_class(type_.lower())
        try:
            bar_ = barC(u"%s" % value_)
        except Exception:
            bar_ = barC("000000000000")

        svg = bar_.render(render_options)
        xml_svg = load2xml(svg.decode("utf-8")).getroot()
        xwidth, xheight = xml_svg.get("width"), xml_svg.get("height")
        if xwidth and xheight:
            svg_w = 3.779 * float(xwidth[0:6])
            svg_h = 3.779 * float(xheight[0:6])
        else:
            logger.warning("width or height missing")
            svg_w = 0.0
            svg_h = 0.0
        self.p = QtGui.QPixmap(int(svg_w), int(svg_h))
        render = QtSvg.QSvgRenderer(svg)
        self.p.fill(QtCore.Qt.transparent)
        painter = Qt.QPainter(self.p)
        render.render(painter, Qt.QRectF(0, 0, svg_w * 3.4, svg_h * 3.4))

        if self.p.isNull():
            self.barcode["valid"] = False
        else:

            if self.barcode["scale"] != 1.0:
                wS_ = self.barcode["x"] * self.barcode["scale"]
                hS_ = self.barcode["y"] * self.barcode["scale"]
                self.p = self.p.scaled(wS_, hS_)

            self.barcode["x"] = self.p.width()
            self.barcode["y"] = self.p.height()

            self.barcode["valid"] = True
Exemple #7
0
    def parse(self,
              name: str,
              kut: str,
              data: str,
              report: "FPDF" = None,
              flags: List[int] = []) -> Optional[str]:
        """
        Parse string containing ".kut" file into a pdf and return its file path.

        @param name. Filename path for ".kut".
        @param kut. String with ".kut" file contents.
        @param data. String with data to be used in the report.
        @return Path to PDF file.
        """
        try:
            self._xml = self._parser_tools.loadKut(kut).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar %s.kut", name)
            return None
        try:
            self._xml_data = load2xml(data).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar xml_data")
            return None

        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "create",
            ["Pineboo", len(self._xml_data), "kugar"])
        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "setLabelText",
            ["Creando informe ...", "kugar"])

        self.name_ = name
        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =
        if report is None:
            from fpdf import FPDF  # type: ignore

            self._actual_append_page_no = 0
            self._document = FPDF(self._page_orientation, "pt",
                                  self._page_size)
            for font in self._document.core_fonts:
                LOGGER.debug("KUT2FPDF :: Adding font %s", font)
                self._avalible_fonts.append(font)
        else:
            self._document = report
        # Seteamos rutas a carpetas con tipos de letra ...

        if not hasattr(self._document, "set_stretching"):
            raise Exception("incorrect pyfpdf versión , you need <= 1.7.3")

        # Cargamos las fuentes disponibles
        next_page_break = (flags[2] == 1) if len(flags) == 3 else True
        page_append = (flags[1] == 1) if len(flags) > 1 else False
        page_display = (flags[0] == 1) if len(flags) > 0 else False

        if page_append:
            self.prev_level = -1
            self.last_detail = False

        page_break = False
        if self.new_page:
            page_break = True
            self.new_page = False

        if self.reset_page_count:
            self.reset_page_no()
            self.reset_page_count = False

        if self.design_mode:
            print("Append", page_append)
            print("Display", page_display)
            print("Page break", next_page_break)

        if next_page_break:
            self.reset_page_count = True

        if page_display:
            self.new_page = True

        self.processDetails(not page_break)

        # FIXME:Alguno valores no se encuentran
        for pages in self._document.pages.keys():
            page_content = self._document.pages[pages]["content"]
            for header in self.draws_at_header.keys():
                page_content = page_content.replace(
                    header, str(self.draws_at_header[header]))

            self._document.pages[pages]["content"] = page_content

        # print(self.draws_at_header.keys())
        self._document.set_title(self.name_)
        self._document.set_author("Pineboo - kut2fpdf plugin")

        return self._document