def createClicked(self):
        print("Create Clicked")
        # Initialize tag objects
        cat_id = QUuid()
        cat_id = cat_id.createUuid()
        cat_id = cat_id.toString()
        self.cat = Category(cat_id)
        self.pattern = Pattern()
        self.template = Template()
        self.that = That()
        self.think = Think()
        self.oob = Oob()
        self.robot = Robot()
        self.image = Image()
        self.video = Video()
        self.videoFileName = Filename()
        self.imageFileName = Filename()
        self.condition = Condition()
        self.conItem = ConditionItem()
        self.random = Random()

        self.categoryCreation() # operates on self.cat

        # clear contents inside docker widget
        self.patternEdit.clear()
        self.thatEdit.clear()
        self.patternEdit.clear()
        self.thinkEdit.clear()
        self.templateEdit.clear()
        self.videoEdit.clear()
        self.imageEdit.clear()

        # emitting signal to EditorWindow to be sent to EditorWidget
        # Above comment is wrong. This sends self.cat to TabController slot
        self.catCreated.emit(self.cat)

        # clearing tag objects
        self.cat = None
        self.pattern = None
        self.that = None
        self.think = None
        self.oob = None
        self.robot = None
        self.image = None
        self.video = None
        self.mediaFileName = None
        self.conItem = None
        self.conditionTableHTML = None
        self.randomTableHTML = None
    def accept(self):
        """ do this for selected layers
        QgsProject.instance().readLayer(layers.item(3))
        """
        here = QDir.currentPath()
        QDir.setCurrent(
            str(QFileInfo(self.filePath).absoluteDir().canonicalPath()))

        for row in range(self.tableWidget.rowCount()):
            if self.tableWidget.item(row, 0).checkState():
                # index = self.tableWidget.item(row,0).data(QtCore.Qt.UserRole).toInt()[0]
                layerId = self.tableWidget.item(row, 0).data(Qt.UserRole)

                # noeud xml
                layerNode = self.getLayerNode(layerId)

                if layerNode:
                    # recherche id
                    idNode = layerNode.namedItem("id")
                    if idNode is not None:
                        newLayerId = QUuid.createUuid().toString()
                        idNode.firstChild().toText().setData(newLayerId)

                    QgsProject.instance().readLayer(layerNode)

        QDir.setCurrent(here)
        super(LayerDialog, self).accept()
    def __init__(self,
                 poly_src: vtkPolyDataAlgorithm,
                 parent: Optional['QObject'] = None) -> None:
        super().__init__(parent=parent)
        self._poly_src = poly_src
        self.id = QUuid.createUuid().toString()
        self.actor = vtkActor()

        mapper = vtkPolyDataMapper()
        mapper.SetInputConnection(poly_src.GetOutputPort())
        self.actor.SetMapper(mapper)

        user_transform = vtkTransform()
        user_transform.Identity()
        user_transform.PostMultiply()
        self.actor.SetUserTransform(user_transform)

        self.actor.ComputeMatrix()
        transform = vtkTransform()
        transform.SetMatrix(self.actor.GetMatrix())

        self._coord_converter = vtkTransformPolyDataFilter()
        self._coord_converter.SetTransform(transform)
        self._coord_converter.AddInputData(poly_src.GetOutput())
        self._coord_converter.Update()

        self._voxelizer = VoxelSlicer()
        self._voxelizer.SetInputConnection(
            self._coord_converter.GetOutputPort())

        self.results = vtkActor()
        self._init_input_id_key()
        self._init_output_id_key(self.results)
Exemple #4
0
 def __init__(self, cat_id=""):
     super().__init__("category", acceptable_tags=[
         Pattern, Template, Think, That, Comment])
     # id to distinguish categories within an AIML object
     if cat_id == "":
         newId = QUuid.createUuid()
         self.cat_id = newId.toString()
     else:
         self.cat_id = cat_id
Exemple #5
0
    def connectionPorts(self, portType, node, portIndex):
        self._id = QUuid.createUuid()

        self._outPortIndex = INVALID
        self._inPortIndex = INVALID
        self._connectionState = ConnectionState()

        self.setNodeToPort(node, portType, portIndex)
        self.setRequiredPort(oppositePort(portType))
Exemple #6
0
 def getRandomHex(self):
     """
     if user conf.json file have no named tags, random a tag name to panel
     if allow in/outbound(Detour) no tags will make this script complicated
     """
     import codecs
     from zlib import crc32  # Use crc32 in order to use the same character length
     # use [2:] remove '0x', i don't like the function hex() header '0x'
     return str(hex(crc32(codecs.encode(QUuid.createUuid().toString(), "utf-8"))))[5:]
Exemple #7
0
    def connectionNodes(self, nodeIn, portIndexIn, nodeOut, portIndexOut):
        self._id = QUuid.createUuid()

        self._outNode = (nodeOut)
        self._inNode = (nodeIn)
        self._outPortIndex = portIndexOut
        self._inPortIndex = portIndexIn
        self._connectionState = ConnectionState()

        self.setNodeToPort(nodeIn, PortType.In, portIndexIn)
        self.setNodeToPort(nodeOut, PortType.Out, portIndexOut)
Exemple #8
0
    def getData(self):
        """
        Public slot to retrieve the dialogs data.
        
        @return tuple of five values (string, string, boolean, string, string)
            giving the project name, the name of the project file, a flag
            telling whether the project shall be the main project, a short
            description for the project and the project category
        """
        if not self.uid:
            # new project entry
            from PyQt5.QtCore import QUuid
            self.uid = QUuid.createUuid().toString()

        filename = Utilities.toNativeSeparators(self.filenameEdit.text())
        if not os.path.isabs(filename):
            filename = Utilities.toNativeSeparators(
                os.path.join(self.startdir, filename))
        return (self.nameEdit.text(), filename,
                self.masterCheckBox.isChecked(),
                self.descriptionEdit.toPlainText(),
                self.categoryComboBox.currentText(), self.uid)
Exemple #9
0
 def setConfig(self, config):
     if "cropToGuides" in config.keys():
         self.chk_toOutmostGuides.setChecked(config["cropToGuides"])
     if "cropLeft" in config.keys():
         self.spn_marginLeft.setValue(config["cropLeft"])
     if "cropTop" in config.keys():
         self.spn_marginTop.setValue(config["cropTop"])
     if "cropRight" in config.keys():
         self.spn_marginRight.setValue(config["cropRight"])
     if "cropBottom" in config.keys():
         self.spn_marginBottom.setValue(config["cropBottom"])
     if "labelsToRemove" in config.keys():
         self.cmbLabelsRemove.setLabels(config["labelsToRemove"])
     self.CBZgroupResize.set_config(config)
     if "CBZactive" in config.keys():
         self.CBZactive.setChecked(config["CBZactive"])
     self.EPUBgroupResize.set_config(config)
     if "EPUBactive" in config.keys():
         self.EPUBactive.setChecked(config["EPUBactive"])
     self.TIFFgroupResize.set_config(config)
     if "TIFFactive" in config.keys():
         self.TIFFactive.setChecked(config["TIFFactive"])
     if "acbfAuthor" in config.keys():
         self.lnACBFAuthor.setText(config["acbfAuthor"])
     if "acbfSource" in config.keys():
         self.lnACBFSource.setText(config["acbfSource"])
     if "acbfID" in config.keys():
         self.lnACBFID.setText(config["acbfID"])
     else:
         self.lnACBFID.setText(QUuid.createUuid().toString())
     if "acbfVersion" in config.keys():
         self.spnACBFVersion.setValue(config["acbfVersion"])
     if "acbfHistory" in config.keys():
         for h in config["acbfHistory"]:
             item = QStandardItem()
             item.setText(h)
             self.ACBFhistoryModel.appendRow(item)
     self.CBZgroupResize.setEnabled(self.CBZactive.isChecked())
 def getData(self):
     """
     Public slot to retrieve the dialogs data.
     
     @return tuple of five values (string, string, boolean, string, string)
         giving the project name, the name of the project file, a flag
         telling whether the project shall be the main project, a short
         description for the project and the project category
     """
     if not self.uid:
         # new project entry
         from PyQt5.QtCore import QUuid
         self.uid = QUuid.createUuid().toString()
     
     filename = Utilities.toNativeSeparators(self.filenameEdit.text())
     if not os.path.isabs(filename):
         filename = Utilities.toNativeSeparators(
             os.path.join(self.startdir, filename))
     return (self.nameEdit.text(),
             filename,
             self.masterCheckBox.isChecked(),
             self.descriptionEdit.toPlainText(),
             self.categoryComboBox.currentText(),
             self.uid)
 def __readProject(self):
     """
     Private method to read the project info.
     """
     project = {}
     
     project["master"] = self.toBool(self.attribute("isMaster", "False"))
     uid = self.attribute("uid", "")
     if uid:
         project["uid"] = uid
     else:
         # upgrade from pre 5.1 format
         from PyQt5.QtCore import QUuid
         project["uid"] = QUuid.createUuid().toString()
     
     while not self.atEnd():
         self.readNext()
         if self.isEndElement() and self.name() == "Project":
             if 'category' not in project:
                 # upgrade from 4.2 format
                 project["category"] = ""
             self.multiProject.projects.append(project)
             break
         
         if self.isStartElement():
             if self.name() == "ProjectName":
                 project["name"] = self.readElementText()
             elif self.name() == "ProjectFile":
                 project["file"] = Utilities.absoluteUniversalPath(
                     self.readElementText(), self.path)
             elif self.name() == "ProjectDescription":
                 project["description"] = self.readElementText()
             elif self.name() == "ProjectCategory":
                 project["category"] = self.readElementText()
             else:
                 self.raiseUnexpectedStartTag(self.name())
Exemple #12
0
    def mqttConnect(self):

        self._logger.info(self.tr("May connect to MQTT server..."))

        if self._mqttSwitchingConnection and self._connectionState == ConnectionState.DISCONNECTED:
            self._mqttServerHost = self._host
            self._mqttServerPort = self._port
            self._mqttRootTopic = self._rootTopic

            if self._rootTopic:
                self._mqttSubTopic = self._rootTopic + '/#'
            else:
                self._mqttSubTopic = '#'

            cloud = self._mqttServerHost + ':' + str(self._mqttServerPort)

            if self._mqttRootTopic:
                cloud += '/' + self._mqttRootTopic + '/#'
            else:
                cloud += '/#'

            self._cloudLabel.setText(cloud)

            clientid = "Observer/" + QUuid.createUuid().toString()
            self._logger.debug("MQTT clientid %s", clientid)

            self._mqttClient.reinitialise(client_id=clientid,
                                          clean_session=True,
                                          userdata=None)

            self._logger.info(self.tr("MQTT client reinitialised"))
            self._logger.info("{0} : {1}".format(self.tr("MQTT server host"),
                                                 self._mqttServerHost))
            self._logger.info("{0} : {1}".format(self.tr("MQTT server port"),
                                                 self._mqttServerPort))
            self._logger.info("{0} : {1}".format(
                self.tr("MQTT clientid"),
                self._mqttClient._client_id.decode("latin1")))
            self._mqttClient.on_connect = self.mqttOnConnect
            self._mqttClient.on_disconnect = self.mqttOnDisconnect
            self._mqttClient.on_log = self.mqttOnLog
            self._mqttClient.on_message = self.mqttOnMessage
            self._mqttClient.on_publish = self.mqttOnPublish
            self._mqttClient.on_subscribe = self.mqttOnSubscribe
            self._mqttClient.on_unsubscribe = self.mqttOnUnsubscribe

            self._mqttSwitchingConnection = False
            self._mqttClient.loop_start()

        if self._connectionState == ConnectionState.CONNECTED or self._connectionState == ConnectionState.CONNECTING:
            self._logger.info(
                self.tr("MQTT connect ignored (already ongoing)"))
        else:
            self._logger.info(self.tr("Connect to MQTT server"))
            try:
                self._mqttClient.connect(self._mqttServerHost,
                                         port=self._mqttServerPort,
                                         keepalive=MQTT_KEEPALIVE)
                self.changeConnectionState(ConnectionState.CONNECTING)
                self._logger.info(self.tr("MQTT connecting"))
            except Exception as e:
                self.changeConnectionState(ConnectionState.DISCONNECTED)
                self._logger.warning(
                    self.tr("Failed to connect to MQTT server"))
                self._logger.debug(e)
                Timer(15.000, self.mqttConnect).start()

        self._logger.debug("Connection state = " + str(self._connectionState))
    def setConfig(self, config):
        if "cropToGuides" in config.keys():
            self.chk_toOutmostGuides.setChecked(config["cropToGuides"])
        if "cropLeft" in config.keys():
            self.spn_marginLeft.setValue(config["cropLeft"])
        if "cropTop" in config.keys():
            self.spn_marginTop.setValue(config["cropTop"])
        if "cropRight" in config.keys():
            self.spn_marginRight.setValue(config["cropRight"])
        if "cropBottom" in config.keys():
            self.spn_marginBottom.setValue(config["cropBottom"])
        if "labelsToRemove" in config.keys():
            self.cmbLabelsRemove.setLabels(config["labelsToRemove"])
        if "textLayerNames" in config.keys():
            self.ln_text_layer_name.setText(", ".join(
                config["textLayerNames"]))
        else:
            self.ln_text_layer_name.setText("text")
        if "panelLayerNames" in config.keys():
            self.ln_panel_layer_name.setText(", ".join(
                config["panelLayerNames"]))
        else:
            self.ln_panel_layer_name.setText("panels")
        self.CBZgroupResize.set_config(config)
        if "CBZactive" in config.keys():
            self.CBZactive.setChecked(config["CBZactive"])
        self.EPUBgroupResize.set_config(config)
        if "EPUBactive" in config.keys():
            self.EPUBactive.setChecked(config["EPUBactive"])
        self.TIFFgroupResize.set_config(config)
        if "TIFFactive" in config.keys():
            self.TIFFactive.setChecked(config["TIFFactive"])

        if "acbfAuthor" in config.keys():
            if isinstance(config["acbfAuthor"], list):
                for author in config["acbfAuthor"]:
                    listItems = []
                    listItems.append(QStandardItem(author.get("nickname", "")))
                    listItems.append(
                        QStandardItem(author.get("first-name", "")))
                    listItems.append(QStandardItem(author.get("initials", "")))
                    listItems.append(QStandardItem(author.get("last-name",
                                                              "")))
                    listItems.append(QStandardItem(author.get("email", "")))
                    listItems.append(QStandardItem(author.get("homepage", "")))
                    self.ACBFauthorModel.appendRow(listItems)
                pass
            else:
                listItems = []
                listItems.append(QStandardItem(
                    config["acbfAuthor"]))  # Nick name
                for i in range(0, 5):
                    listItems.append(QStandardItem())  # First name
                self.ACBFauthorModel.appendRow(listItems)

        if "uuid" in config.keys():
            self.lnACBFID.setText(config["uuid"])
        elif "acbfID" in config.keys():
            self.lnACBFID.setText(config["acbfID"])
        else:
            config["uuid"] = QUuid.createUuid().toString()
            self.lnACBFID.setText(config["uuid"])
        if "acbfVersion" in config.keys():
            self.spnACBFVersion.setValue(config["acbfVersion"])
        if "acbfHistory" in config.keys():
            for h in config["acbfHistory"]:
                item = QStandardItem()
                item.setText(h)
                self.ACBFhistoryModel.appendRow(item)
        if "acbfStyles" in config.keys():
            styleDict = config.get("acbfStyles", {})
            for key in self.acbfStylesList:
                keyDict = styleDict.get(key, {})
                style = QStandardItem(key.title())
                style.setCheckable(True)
                if key in styleDict.keys():
                    style.setCheckState(Qt.Checked)
                else:
                    style.setCheckState(Qt.Unchecked)
                fontOn = False
                if "font" in keyDict.keys() or "genericfont" in keyDict.keys():
                    fontOn = True
                style.setData(fontOn, role=styleEnum.FONT)
                if "font" in keyDict:
                    fontlist = keyDict["font"]
                    if isinstance(fontlist, list):
                        font = keyDict.get("font", QFont().family())
                        style.setData(font, role=styleEnum.FONTLIST)
                    else:
                        style.setData([fontlist], role=styleEnum.FONTLIST)
                else:
                    style.setData([QFont().family()], role=styleEnum.FONTLIST)
                style.setData(keyDict.get("genericfont", "sans-serif"),
                              role=styleEnum.FONTGENERIC)
                style.setData(keyDict.get("bold", False), role=styleEnum.BOLD)
                style.setData(keyDict.get("ital", False),
                              role=styleEnum.ITALIC)
                self.ACBFStylesModel.appendRow(style)
            keyDict = styleDict.get("general", {})
            self.regularColor.setCurrentColor(
                QColor(keyDict.get("color", "#000000")))
            square = QPixmap(32, 32)
            square.fill(self.regularColor.currentColor())
            self.btn_acbfRegColor.setIcon(QIcon(square))
            keyDict = styleDict.get("inverted", {})
            self.invertedColor.setCurrentColor(
                QColor(keyDict.get("color", "#FFFFFF")))
            square.fill(self.invertedColor.currentColor())
            self.btn_acbfInvColor.setIcon(QIcon(square))
        else:
            for key in self.acbfStylesList:
                style = QStandardItem(key.title())
                style.setCheckable(True)
                style.setCheckState(Qt.Unchecked)
                style.setData(False, role=styleEnum.FONT)
                style.setData(QFont().family(), role=styleEnum.FONTLIST)
                style.setData("sans-serif", role=styleEnum.FONTGENERIC)
                style.setData(False, role=styleEnum.BOLD)  #Bold
                style.setData(False, role=styleEnum.ITALIC)  #Italic
                self.ACBFStylesModel.appendRow(style)
        self.CBZgroupResize.setEnabled(self.CBZactive.isChecked())
        self.lnTranslatorHeader.setText(
            config.get("translatorHeader", "Translator's Notes"))
        self.chkIncludeTranslatorComments.setChecked(
            config.get("includeTranslComment", False))
    def setConfig(self, config):

        if "title" in config.keys():
            self.lnTitle.setText(config["title"])
        self.teSummary.clear()
        if "pages" in config.keys():
            self.cmbCoverPage.clear()
            for page in config["pages"]:
                self.cmbCoverPage.addItem(page)
            if "cover" in config.keys():
                if config["cover"] in config["pages"]:
                    self.cmbCoverPage.setCurrentText(config["cover"])
        if "summary" in config.keys():
            self.teSummary.appendPlainText(config["summary"])
        if "genre" in config.keys():
            genreList = []
            genreListConf = config["genre"]
            totalMatch = 100
            if isinstance(config["genre"], dict):
                genreListConf = config["genre"].keys()
                totalMatch = 0
            for genre in genreListConf:
                genreKey = genre
                if genre in self.acbfGenreList:
                    genreKey = self.acbfGenreList[genre]
                if isinstance(config["genre"], dict):
                    genreValue = config["genre"][genre]
                    if genreValue > 0:
                        genreKey = str(genreKey + "(" + str(genreValue) + ")")
                genreList.append(genreKey)
            self.lnGenre.setText(", ".join(genreList))
        if "characters" in config.keys():
            self.lnCharacters.setText(", ".join(config["characters"]))
        if "format" in config.keys():
            self.lnFormat.setText(", ".join(config["format"]))
        if "rating" in config.keys():
            self.cmbRating.setCurrentText(config["rating"])
        else:
            self.cmbRating.setCurrentText("")
        if "ratingSystem" in config.keys():
            self.cmbRatingSystem.setCurrentText(config["ratingSystem"])
        else:
            self.cmbRatingSystem.setCurrentText("")
        if "otherKeywords" in config.keys():
            self.lnOtherKeywords.setText(", ".join(config["otherKeywords"]))
        if "seriesName" in config.keys():
            self.lnSeriesName.setText(config["seriesName"])
        if "seriesVolume" in config.keys():
            self.spnSeriesVol.setValue(config["seriesVolume"])
        if "seriesNumber" in config.keys():
            self.spnSeriesNumber.setValue(config["seriesNumber"])
        if "language" in config.keys():
            code = config["language"]
            if "_" in code:
                self.cmbLanguage.setEntryToCode(code.split("_")[0])
                self.cmbCountry.setEntryToCode(code.split("_")[-1])
            elif "-" in code:
                self.cmbLanguage.setEntryToCode(code.split("-")[0])
                self.cmbCountry.setEntryToCode(code.split("-")[-1])
            else:
                self.cmbLanguage.setEntryToCode(code)
        if "readingDirection" in config.keys():
            if config["readingDirection"] is "leftToRight":
                self.cmbReadingMode.setCurrentIndex(int(Qt.LeftToRight))
            else:
                self.cmbReadingMode.setCurrentIndex(int(Qt.RightToLeft))
        else:
            self.cmbReadingMode.setCurrentIndex(QLocale(self.cmbLanguage.codeForCurrentEntry()).textDirection())
        if "publisherName" in config.keys():
            self.publisherName.setText(config["publisherName"])
        if "publisherCity" in config.keys():
            self.publishCity.setText(config["publisherCity"])
        if "publishingDate" in config.keys():
            self.publishDate.setDate(QDate.fromString(config["publishingDate"], Qt.ISODate))
        if "isbn-number" in config.keys():
            self.isbn.setText(config["isbn-number"])
        if "source" in config.keys():
            self.ln_source.setText(config["source"])
        elif "acbfSource" in config.keys():
            self.ln_source.setText(config["acbfSource"])
        if "uuid" in config.keys():
            self.label_uuid.setText(config["uuid"])
        else:
            uuid = str()
            if "acbfID" in config.keys():
                uuid = config["acbfID"]
                uuid = uuid.strip("{")
                uuid = uuid.strip("}")
                uuidVerify = uuid.split("-")
                if len(uuidVerify[0])!=8 or len(uuidVerify[1])!=4 or len(uuidVerify[2])!=4 or len(uuidVerify[3])!=4 or len(uuidVerify[4])!=12:
                    uuid = QUuid.createUuid().toString()
            self.label_uuid.setText(uuid)
            config["uuid"] = uuid
        if "license" in config.keys():
            self.license.setCurrentText(config["license"])
        else:
            self.license.setCurrentText("")  # I would like to keep it ambiguous whether the artist has thought about the license or not.
        if "authorList" in config.keys():
            authorList = config["authorList"]
            for i in range(len(authorList)):
                author = authorList[i]
                if len(author.keys()) > 0:
                    listItems = []
                    listItems = []
                    listItems.append(QStandardItem(author.get("nickname", "")))
                    listItems.append(QStandardItem(author.get("first-name", "")))
                    listItems.append(QStandardItem(author.get("initials", "")))
                    listItems.append(QStandardItem(author.get("last-name", "")))
                    role = author.get("role", "")
                    if role in self.acbfAuthorRolesList.keys():
                        role = self.acbfAuthorRolesList[role]
                    listItems.append(QStandardItem(role))
                    listItems.append(QStandardItem(author.get("email", "")))
                    listItems.append(QStandardItem(author.get("homepage", "")))
                    listItems.append(QStandardItem(author.get("language", "")))
                    self.authorModel.appendRow(listItems)
        else:
            self.slot_add_author()
        dbRef = config.get("databaseReference", {})
        self.ln_database_name.setText(dbRef.get("name", ""))
        self.ln_database_entry.setText(dbRef.get("entry", ""))
        stringCmbEntryType = self.cmb_entry_type.itemText(0)
        self.cmb_entry_type.setCurrentText(dbRef.get("type", stringCmbEntryType))
Exemple #15
0
    def __init__(self,
                 summary,
                 priority=1,
                 filename="",
                 lineno=0,
                 completed=False,
                 _time=0,
                 isProjectTask=False,
                 taskType=TypeTodo,
                 project=None,
                 description="",
                 uid="",
                 parentUid=""):
        """
        Constructor
        
        @param summary summary text of the task (string)
        @param priority priority of the task (0=high, 1=normal, 2=low)
        @param filename filename containing the task (string)
        @param lineno line number containing the task (integer)
        @param completed flag indicating completion status (boolean)
        @param _time creation time of the task (float, if 0 use current time)
        @param isProjectTask flag indicating a task related to the current
            project (boolean)
        @param taskType type of the task (one of TypeFixme, TypeTodo,
            TypeWarning, TypeNote)
        @param project reference to the project object (Project)
        @param description explanatory text of the task (string)
        @param uid unique id of the task (string)
        @param parentUid unique id of the parent task (string)
        """
        super(Task, self).__init__()

        self.summary = summary
        self.description = description
        if priority in [0, 1, 2]:
            self.priority = priority
        else:
            self.priority = 1
        self.filename = filename
        self.lineno = lineno
        self.completed = completed
        self.created = _time and _time or time.time()
        self._isProjectTask = isProjectTask
        self.taskType = taskType
        self.project = project
        if uid:
            self.uid = uid
        else:
            self.uid = QUuid.createUuid().toString()
        self.parentUid = parentUid

        if isProjectTask:
            self.filename = self.project.getRelativePath(self.filename)

        self.setData(0, Qt.DisplayRole, "")
        self.setData(1, Qt.DisplayRole, "")
        self.setData(2, Qt.DisplayRole, self.summary)
        self.setData(3, Qt.DisplayRole, self.filename)
        self.setData(4, Qt.DisplayRole, self.lineno or "")

        if self.completed:
            self.setIcon(0, UI.PixmapCache.getIcon("taskCompleted.png"))
            strikeOut = True
        else:
            self.setIcon(0, UI.PixmapCache.getIcon("empty.png"))
            strikeOut = False
        for column in range(2, 5):
            f = self.font(column)
            f.setStrikeOut(strikeOut)
            self.setFont(column, f)

        if self.priority == 1:
            self.setIcon(1, UI.PixmapCache.getIcon("empty.png"))
        elif self.priority == 0:
            self.setIcon(1, UI.PixmapCache.getIcon("taskPrioHigh.png"))
        elif self.priority == 2:
            self.setIcon(1, UI.PixmapCache.getIcon("taskPrioLow.png"))
        else:
            self.setIcon(1, UI.PixmapCache.getIcon("empty.png"))

        if self.taskType == Task.TypeFixme:
            self.setIcon(2, UI.PixmapCache.getIcon("taskFixme.png"))
        elif self.taskType == Task.TypeWarning:
            self.setIcon(2, UI.PixmapCache.getIcon("taskWarning.png"))
        elif self.taskType == Task.TypeTodo:
            self.setIcon(2, UI.PixmapCache.getIcon("taskTodo.png"))
        else:
            self.setIcon(2, UI.PixmapCache.getIcon("taskNote.png"))

        self.colorizeTask()
        self.setTextAlignment(4, Qt.AlignRight)
    def showDialog(self):
        # Initialise the setup directory empty toavoid exceptions.
        self.setupDictionary = {}

        # ask for a project directory.
        self.projectDirectory = QFileDialog.getExistingDirectory(
            caption=i18n("Where should the comic project go?"),
            options=QFileDialog.ShowDirsOnly)
        if os.path.exists(self.projectDirectory) is False:
            return
        self.pagesDirectory = os.path.relpath(self.projectDirectory,
                                              self.projectDirectory)
        self.exportDirectory = os.path.relpath(self.projectDirectory,
                                               self.projectDirectory)

        wizard = QWizard()
        wizard.setWindowTitle(i18n("Comic Project Setup"))
        wizard.setOption(QWizard.IndependentPages, True)

        # Set up the UI for the wizard
        basicsPage = QWizardPage()
        basicsPage.setTitle(i18n("Basic Comic Project Settings"))
        formLayout = QFormLayout()
        basicsPage.setLayout(formLayout)
        projectLayout = QHBoxLayout()
        self.lnProjectName = QLineEdit()
        basicsPage.registerField("Project Name*", self.lnProjectName)
        self.lnProjectName.setToolTip(
            i18n(
                "A Project name. This can be different from the eventual title"
            ))
        btnRandom = QPushButton()
        btnRandom.setText(i18n("Generate"))
        btnRandom.setToolTip(
            i18n(
                "If you cannot come up with a project name, our highly sophisticated project name generator will serve to give a classy yet down to earth name."
            ))
        btnRandom.clicked.connect(self.slot_generate)
        projectLayout.addWidget(self.lnProjectName)
        projectLayout.addWidget(btnRandom)
        lnConcept = QLineEdit()
        lnConcept.setToolTip(
            i18n(
                "What is your comic about? This is mostly for your own convenience so do not worry about what it says too much."
            ))
        self.cmbLanguage = comics_metadata_dialog.language_combo_box()
        self.cmbLanguage.setToolTip(i18n("The main language the comic is in"))
        self.cmbLanguage.setEntryToCode(
            str(QLocale.system().name()).split("_")[0])
        self.cmbCountry = comics_metadata_dialog.country_combo_box()
        if QLocale.system() != QLocale.c():
            self.slot_update_countries()
            self.cmbCountry.setEntryToCode(
                str(QLocale.system().name()).split("_")[-1])
        else:
            self.cmbLanguage.setEntryToCode("en")
            self.slot_update_countries()
            self.cmbCountry.setEntryToCode("US")
        self.cmbLanguage.currentIndexChanged.connect(
            self.slot_update_countries)
        self.lnProjectDirectory = QLabel(self.projectDirectory)
        self.chkMakeProjectDirectory = QCheckBox()
        labelDirectory = QLabel(
            i18n("Make a new directory with the project name."))
        labelDirectory.setWordWrap(True)
        stringDirectoryTooltip = i18n(
            "This allows you to select a generic comics project directory, in which a new folder will be made for the project using the given project name."
        )
        self.chkMakeProjectDirectory.setToolTip(stringDirectoryTooltip)
        labelDirectory.setToolTip(stringDirectoryTooltip)
        self.chkMakeProjectDirectory.setChecked(True)
        self.lnPagesDirectory = QLineEdit()
        self.lnPagesDirectory.setText(i18n("pages"))
        self.lnPagesDirectory.setToolTip(
            i18n(
                "The name for the folder where the pages are contained. If it does not exist, it will be created."
            ))
        self.lnExportDirectory = QLineEdit()
        self.lnExportDirectory.setText(i18n("export"))
        self.lnExportDirectory.setToolTip(
            i18n(
                "The name for the folder where the export is put. If it does not exist, it will be created."
            ))
        self.lnTemplateLocation = QLineEdit()
        self.lnTemplateLocation.setText(i18n("templates"))
        self.lnTemplateLocation.setToolTip(
            i18n(
                "The name for the folder where the page templates are sought in."
            ))

        self.lnTranslationLocation = QLineEdit()
        self.lnTranslationLocation.setText(i18n("translations"))
        self.lnTranslationLocation.setToolTip(
            "This is the location that POT files will be stored to and PO files will be read from."
        )
        formLayout.addRow(i18n("Comic concept:"), lnConcept)
        formLayout.addRow(i18n("Project name:"), projectLayout)
        formLayout.addRow(i18n("Main language:"), self.cmbLanguage)
        formLayout.addRow("", self.cmbCountry)

        buttonMetaData = QPushButton(i18n("Meta Data"))
        buttonMetaData.clicked.connect(self.slot_edit_meta_data)

        wizard.addPage(basicsPage)

        foldersPage = QWizardPage()
        foldersPage.setTitle(i18n("Folder names and other."))
        folderFormLayout = QFormLayout()
        foldersPage.setLayout(folderFormLayout)
        folderFormLayout.addRow(i18n("Project directory:"),
                                self.lnProjectDirectory)
        folderFormLayout.addRow(self.chkMakeProjectDirectory, labelDirectory)
        folderFormLayout.addRow(i18n("Pages directory"), self.lnPagesDirectory)
        folderFormLayout.addRow(i18n("Export directory"),
                                self.lnExportDirectory)
        folderFormLayout.addRow(i18n("Template directory"),
                                self.lnTemplateLocation)
        folderFormLayout.addRow(i18n("Translation directory"),
                                self.lnTranslationLocation)
        folderFormLayout.addRow("", buttonMetaData)
        wizard.addPage(foldersPage)

        # Execute the wizard, and after wards...
        if (wizard.exec_()):

            # First get the directories, check if the directories exist, and otherwise make them.
            self.pagesDirectory = self.lnPagesDirectory.text()
            self.exportDirectory = self.lnExportDirectory.text()
            self.templateLocation = self.lnTemplateLocation.text()
            self.translationLocation = self.lnTranslationLocation.text()
            projectPath = Path(self.projectDirectory)
            # Only make a project directory if the checkbox for that has been checked.
            if self.chkMakeProjectDirectory.isChecked():
                projectPath = projectPath / self.lnProjectName.text()
                if projectPath.exists() is False:
                    projectPath.mkdir()
                self.projectDirectory = str(projectPath)
            if Path(projectPath / self.pagesDirectory).exists() is False:
                Path(projectPath / self.pagesDirectory).mkdir()
            if Path(projectPath / self.exportDirectory).exists() is False:
                Path(projectPath / self.exportDirectory).mkdir()
            if Path(projectPath / self.templateLocation).exists() is False:
                Path(projectPath / self.templateLocation).mkdir()
            if Path(projectPath / self.translationLocation).exists() is False:
                Path(projectPath / self.translationLocation).mkdir()

            # Then store the information into the setup diactionary.
            self.setupDictionary["projectName"] = self.lnProjectName.text()
            self.setupDictionary["concept"] = lnConcept.text()
            self.setupDictionary["language"] = str(
                self.cmbLanguage.codeForCurrentEntry())
            self.setupDictionary["pagesLocation"] = self.pagesDirectory
            self.setupDictionary["exportLocation"] = self.exportDirectory
            self.setupDictionary["templateLocation"] = self.templateLocation
            self.setupDictionary[
                "translationLocation"] = self.translationLocation
            self.setupDictionary["uuid"] = QUuid.createUuid().toString()

            # Finally, write the dictionary into the json file.
            self.writeConfig()
Exemple #17
0
    QApplication.setStyle(QStyleFactory.create("Windows"))

app.setApplicationDisplayName("MQTT Observer")
app.setApplicationName("MQTT Observer")
app.setOrganizationDomain("xcape.io")
app.setOrganizationName("xcape.io")

if platform.system() == 'Windows':
    app.setAttribute(Qt.AA_EnableHighDpiScaling)  # for 4K display

translator = QTranslator()
if args['french']:
    if translator.load(":/Observer.fr_FR.qm", QDir.currentPath()):
        app.installTranslator(translator)

clientid = "Observer/" + QUuid.createUuid().toString()
logger.debug("MQTT clientid %s", clientid)

mqtt_client = mqtt.Client(clientid, clean_session=True, userdata=None)

dlg = ObserverWindow(mqtt_client, logger)
dlg.show()

mqtt_client.loop_start()

rc = app.exec_()

try:
    mqtt_client.disconnect()
    mqtt_client.loop_stop()
except:
Exemple #18
0
 def __init__(self, summary, priority=1, filename="", lineno=0,
              completed=False, _time=0, isProjectTask=False,
              taskType=TypeTodo, project=None, description="",
              uid="", parentUid=""):
     """
     Constructor
     
     @param summary summary text of the task (string)
     @param priority priority of the task (0=high, 1=normal, 2=low)
     @param filename filename containing the task (string)
     @param lineno line number containing the task (integer)
     @param completed flag indicating completion status (boolean)
     @param _time creation time of the task (float, if 0 use current time)
     @param isProjectTask flag indicating a task related to the current
         project (boolean)
     @param taskType type of the task (one of TypeFixme, TypeTodo,
         TypeWarning, TypeNote)
     @param project reference to the project object (Project)
     @param description explanatory text of the task (string)
     @param uid unique id of the task (string)
     @param parentUid unique id of the parent task (string)
     """
     super(Task, self).__init__()
     
     self.summary = summary
     self.description = description
     if priority in [0, 1, 2]:
         self.priority = priority
     else:
         self.priority = 1
     self.filename = filename
     self.lineno = lineno
     self.completed = completed
     self.created = _time and _time or time.time()
     self._isProjectTask = isProjectTask
     self.taskType = taskType
     self.project = project
     if uid:
         self.uid = uid
     else:
         self.uid = QUuid.createUuid().toString()
     self.parentUid = parentUid
     
     if isProjectTask:
         self.filename = self.project.getRelativePath(self.filename)
         
     self.setData(0, Qt.DisplayRole, "")
     self.setData(1, Qt.DisplayRole, "")
     self.setData(2, Qt.DisplayRole, self.summary)
     self.setData(3, Qt.DisplayRole, self.filename)
     self.setData(4, Qt.DisplayRole, self.lineno or "")
     
     if self.completed:
         self.setIcon(0, UI.PixmapCache.getIcon("taskCompleted.png"))
         strikeOut = True
     else:
         self.setIcon(0, UI.PixmapCache.getIcon("empty.png"))
         strikeOut = False
     for column in range(2, 5):
         f = self.font(column)
         f.setStrikeOut(strikeOut)
         self.setFont(column, f)
     
     if self.priority == 1:
         self.setIcon(1, UI.PixmapCache.getIcon("empty.png"))
     elif self.priority == 0:
         self.setIcon(1, UI.PixmapCache.getIcon("taskPrioHigh.png"))
     elif self.priority == 2:
         self.setIcon(1, UI.PixmapCache.getIcon("taskPrioLow.png"))
     else:
         self.setIcon(1, UI.PixmapCache.getIcon("empty.png"))
     
     if self.taskType == Task.TypeFixme:
         self.setIcon(2, UI.PixmapCache.getIcon("taskFixme.png"))
     elif self.taskType == Task.TypeWarning:
         self.setIcon(2, UI.PixmapCache.getIcon("taskWarning.png"))
     elif self.taskType == Task.TypeTodo:
         self.setIcon(2, UI.PixmapCache.getIcon("taskTodo.png"))
     else:
         self.setIcon(2, UI.PixmapCache.getIcon("taskNote.png"))
     
     self.colorizeTask()
     self.setTextAlignment(4, Qt.AlignRight)
Exemple #19
0
    def __readTask(self):
        """
        Private method to read the task info.
        """
        task = {
            "summary": "",
            "priority": 1,
            "completed": False,
            "created": 0,
            "filename": "",
            "linenumber": 0,
            "type": Task.TypeTodo,
            "description": "",
            "uid": "",
        }
        task["priority"] = int(self.attribute("priority", "1"))
        task["completed"] = self.toBool(self.attribute("completed", "False"))
        if self.version in ["4.2", "5.0"]:
            isBugfix = self.toBool(self.attribute("bugfix", "False"))
            if isBugfix:
                task["type"] = Task.TypeFixme
        else:
            task["type"] = int(self.attribute("type", str(Task.TypeTodo)))
        uid = self.attribute("uid", "")
        if uid:
            task["uid"] = uid
        else:
            # upgrade from pre 6.0 format
            from PyQt5.QtCore import QUuid

            task["uid"] = QUuid.createUuid().toString()
        parentUid = self.attribute("parent_uid", "")
        expanded = self.toBool(self.attribute("expanded", "True"))

        while not self.atEnd():
            self.readNext()
            if self.isEndElement() and self.name() == "Task":
                parentTask = self.viewer.findParentTask(parentUid)
                addedTask = self.viewer.addTask(
                    task["summary"],
                    priority=task["priority"],
                    filename=task["filename"],
                    lineno=task["linenumber"],
                    completed=task["completed"],
                    _time=task["created"],
                    isProjectTask=self.forProject,
                    taskType=task["type"],
                    description=task["description"],
                    uid=task["uid"],
                    parentTask=parentTask,
                )
                self.tasks.append((addedTask, expanded))
                break

            if self.isStartElement():
                if self.name() == "Summary":
                    task["summary"] = self.readElementText()
                elif self.name() == "Description":
                    task["description"] = self.readElementText()
                elif self.name() == "Created":
                    task["created"] = time.mktime(time.strptime(self.readElementText(), "%Y-%m-%d, %H:%M:%S"))
                elif self.name() == "Resource":
                    continue  # handle but ignore this tag
                elif self.name() == "Filename":
                    task["filename"] = Utilities.toNativeSeparators(self.readElementText())
                elif self.name() == "Linenumber":
                    try:
                        task["linenumber"] = int(self.readElementText())
                    except ValueError:
                        pass
                else:
                    self.raiseUnexpectedStartTag(self.name())
Exemple #20
0
    def __readTask(self):
        """
        Private method to read the task info.
        """
        task = {
            "summary": "",
            "priority": 1,
            "completed": False,
            "created": 0,
            "filename": "",
            "linenumber": 0,
            "type": Task.TypeTodo,
            "description": "",
            "uid": "",
        }
        task["priority"] = int(self.attribute("priority", "1"))
        task["completed"] = self.toBool(self.attribute("completed", "False"))
        if self.version in ["4.2", "5.0"]:
            isBugfix = self.toBool(self.attribute("bugfix", "False"))
            if isBugfix:
                task["type"] = Task.TypeFixme
        else:
            task["type"] = int(self.attribute("type", str(Task.TypeTodo)))
        uid = self.attribute("uid", "")
        if uid:
            task["uid"] = uid
        else:
            # upgrade from pre 6.0 format
            from PyQt5.QtCore import QUuid
            task["uid"] = QUuid.createUuid().toString()
        parentUid = self.attribute("parent_uid", "")
        expanded = self.toBool(self.attribute("expanded", "True"))

        while not self.atEnd():
            self.readNext()
            if self.isEndElement() and self.name() == "Task":
                parentTask = self.viewer.findParentTask(parentUid)
                addedTask = self.viewer.addTask(
                    task["summary"],
                    priority=task["priority"],
                    filename=task["filename"],
                    lineno=task["linenumber"],
                    completed=task["completed"],
                    _time=task["created"],
                    isProjectTask=self.forProject,
                    taskType=task["type"],
                    description=task["description"],
                    uid=task["uid"],
                    parentTask=parentTask)
                self.tasks.append((addedTask, expanded))
                break

            if self.isStartElement():
                if self.name() == "Summary":
                    task["summary"] = self.readElementText()
                elif self.name() == "Description":
                    task["description"] = self.readElementText()
                elif self.name() == "Created":
                    task["created"] = time.mktime(
                        time.strptime(self.readElementText(),
                                      "%Y-%m-%d, %H:%M:%S"))
                elif self.name() == "Resource":
                    continue  # handle but ignore this tag
                elif self.name() == "Filename":
                    task["filename"] = \
                        Utilities.toNativeSeparators(self.readElementText())
                elif self.name() == "Linenumber":
                    try:
                        task["linenumber"] = int(self.readElementText())
                    except ValueError:
                        pass
                else:
                    self.raiseUnexpectedStartTag(self.name())
Exemple #21
0
    def __init__(self, args):
        super(PhotoSeries, self).__init__()

        self.uuid = QUuid.createUuid()
        self.photoItems = []
        self.addPhotoItems(args)
Exemple #22
0
def uuid():
    sUid = QUuid().createUuid().toString()
    return sUid
Exemple #23
0
import os, sys, platform, signal

from PluginApplet import PluginApplet
from Singleton import Singleton, SingletonException

me = None
try:
    me = Singleton()
except SingletonException:
    sys.exit(-1)
except BaseException as e:
    print(e)

os.chdir(os.path.dirname(os.path.abspath(__file__)))

clientid = "Xcape/Plugin/" + QUuid.createUuid().toString()

mqtt_client = mqtt.Client(clientid, clean_session=True, userdata=None)

applet = PluginApplet(sys.argv, mqtt_client, debugging_mqtt=True)

applet.setApplicationDisplayName("Room")
applet.setWindowIcon(QIcon('./teletext-on.svg'))

if applet.logger:
    applet.logger.info(applet.tr("Session started"))

# Assign handler for process exit (shows not effect on Windows in debug here)
signal.signal(signal.SIGTERM, applet.quit)
signal.signal(signal.SIGINT, applet.quit)
if platform.system() != 'Windows':
Exemple #24
0
	def newUUID(self):
		return QUuid.createUuid().toString()