示例#1
0
 def save(self, f: XFile):
     try:
         file = open(f.getPath(), "w", encoding="utf-8")
         file.write(self.text())
         file.close()
         f.unsavedData = ""
         self.pushAlert("Saved: " + f.getPath(),
                        Parapluie.Alert_Information)
         return f.getPath()
     except Exception as ex:
         logging.exception(ex)
         self.pushAlert(str(ex))
    def saveExistedInRequest(self, file: XFile, newData: tuple):
        # data
        text = Formatter.dumps(file.unsavedData.data, EditorType.JSON,
                               self.pushAlert)
        xash = XashHelp.path2Xash(file.getPath())

        if xash.getCategory() == newData[1] and xash.getName() == newData[0]:
            # replace existed description
            xashId = xash.getId()
            self.saveDescription(newData[2], xashId)

            if self.save(file, file.getPath(), text):
                self.loadFile()
        else:
            temp = self.dataSource.findMatchAll(newData[1],
                                                newData[0],
                                                "",
                                                sensitive=False)
            if len(temp) > 0:
                self.pushAlert("File was existed!!!")
            else:
                message = PMessage(
                    self,
                    QRect(QPoint(0, 0),
                          QApplication.focusWindow().screen().size()))
                message.initQuestion(
                    "File is saved, do you want to rename or create new file?",
                    [{
                        "text": "Rename",
                        'type': Parapluie.Button_Negative
                    }, {
                        "text": "New File",
                        'type': Parapluie.Button_Positive
                    }, {
                        "text": "Close",
                        'type': Parapluie.Button_Neutral
                    }], 'Save request')
                code = message.exec_()
                if code == 0:
                    # remove old description
                    xashId = xash.getId()
                    self.saveDescription(newData[2], xashId, True)

                    path = self.getSavePath(newData[0], newData[1], newData[2])

                    os.rename(file.getPath(), path)

                    if self.save(file, path, text):
                        self.loadFile()
                elif code == 1:
                    path = self.getSavePath(newData[0], newData[1], newData[2])
                    if self.save(file, path, text):
                        self.loadFile()
示例#3
0
    def setFile(self, file: XFile):
        # save data cũ
        if self.currentFile is not None:
            self.currentFile.unsavedData = self.text()
        # load data moi
        self.currentFile = file
        self.setTitle(file.name()[0])

        if file.name()[1].lower() == '.json':
            self.setEditorType(EditorType.JSON)
        elif file.name()[1].lower() == '.xml':
            self.setEditorType(EditorType.XML)
        elif file.name()[1].lower() == '.html':
            self.setEditorType(EditorType.HTML)
        elif file.name()[1].lower() == '.js':
            self.setEditorType(EditorType.Javascript)
        else:
            self.setEditorType(EditorType.Text)

        self.title.setEditable(not os.path.isfile(file.getPath()))
        if file.unsavedData != "":
            self.setText(file.unsavedData)
        else:
            if os.path.isfile(file.getPath()):
                d = open(file.getPath(), "r", encoding="utf-8").read()
                self.setText(d)
            else:
                self.setText("")
        self.syncJson()
 def removeFile(self, f: XFile):
     if os.path.isfile(Config.getViewerRecentFile()):
         file = open(Config.getViewerRecentFile(), 'r', encoding='utf-8')
         data = file.read().splitlines()
         file.close()
         if f.getPath() in data:
             data.remove(f.getPath())
             file = open(Config.getViewerRecentFile(),
                         'w',
                         encoding='utf-8')
             file.write("\n".join(data))
             file.close()
     else:
         file = open(Config.getViewerRecentFile(), 'a+', encoding='utf-8')
         file.close()
    def save(self, file: XFile, path, text) -> bool:
        try:
            f = open(path, 'w', encoding='utf-8')
            f.write(text)
            f.close()

            file.unsavedData = None
            file.setPath(path)
            file.data = XashHelp.path2Xash(path)

            self.pushAlert("Saved!!!", Parapluie.Alert_Success)
            return True
        except Exception as ex:
            logging.exception(ex)
            self.pushAlert(str(ex))
            return False
    def updateDataList(self, lstNew, lstSrc):
        self.dataList.clear()
        if len(lstNew):
            # header item
            item = ItemModel()
            item.file = "Recent File"
            item.selected = -1
            self.dataList.append(item)
            for data in lstNew:  # XFile
                item = ItemModel()
                item.file = data
                item.selected = 1 if self.currentFile == data else 0
                self.dataList.append(item)

        if len(lstSrc) > 0:
            # header item
            item = ItemModel()
            item.file = "Request Folder"
            item.selected = -1
            self.dataList.append(item)
            for data in lstSrc:  # Xash
                item = ItemModel()
                if data.getPath() in self.listFile:
                    inx = self.listFile.index(data.getPath())
                    file = self.listFile[inx]
                else:
                    file = XFile(data.getPath())
                    self.listFile.append(file)
                item.file = file
                item.selected = 1 if self.currentFile == file else 0
                self.dataList.append(item)
 def newFile(self):
     self.newCount += 1
     file = XFile("Unsaved/Untitled-" + str(self.newCount))
     self.dataTemp.insert(0, file)
     self.onItemSelected(file)
     self.updateDataList(self.dataTemp, self.dataSource.list)
     self.refresh()
 def newFile(self):
     self.newCount += 1
     json = XFile("Unsaved\\Untitled-" + str(self.newCount))
     self.currentFile = json
     self.dataTemp.insert(0, json)
     self.updateDataList(self.dataTemp, self.dataSource)
     self.listAdapter.refresh()
     self.currentChange.emit()
 def loadFile(self):
     if os.path.isfile(Config.getViewerRecentFile()):
         file = open(Config.getViewerRecentFile(), 'r', encoding='utf-8')
         data = file.read().splitlines()
         for d in data:
             if d not in self.dataSource:
                 self.dataSource.insert(0, XFile(d))
         self.updateDataList(self.dataTemp, self.dataSource)
         file.close()
     else:
         file = open(Config.getViewerRecentFile(), 'w', encoding='utf-8')
         file.close()
示例#10
0
 def fileChanged(self, path: str):
     file = XFile(path)
     self.currentFile = file
     if path in self.dataTemp:
         self.dataTemp.remove(path)
     if path in self.dataSource:
         self.dataSource.remove(file)
     self.addRecentFile(file)
     self.loadFile()
     self.updateDataList(self.dataTemp, self.dataSource)
     self.listAdapter.refresh()
     self.currentChange.emit()
示例#11
0
 def saveData(self):
     if self.currentFile is None:
         init_dir = Config.getViewerConfig_LastOpen()
         file = os.path.join(init_dir, self.title.text())
         name = QFileDialog.getSaveFileName(self, 'Save file', file,
                                            self.getFileExtension())
         if name[0] != "":
             config = Config.getConfig()
             config["viewer"]["last_open"] = os.path.dirname(name[0])
             Config.updateConfig(config)
             self.currentFile = XFile(name[0])
             self.save(self.currentFile)
     else:
         if not os.path.isfile(self.currentFile.getPath()):
             name = QFileDialog.getSaveFileName(self, 'Save file',
                                                self.currentFile.getPath(),
                                                self.getFileExtension())
             if name[0] != "":
                 self.currentFile.setPath(name[0])
                 if self.save(self.currentFile) is not None:
                     self.saveDataDone.emit(name[0])
         else:
             if self.save(self.currentFile) is not None:
                 self.saveDataDone.emit(self.currentFile.getPath())
    def openFile(self):
        init_dir = Config.getRequestConfig_LastOpen()

        name = QFileDialog.getOpenFileName(
            self, 'Open file', init_dir,
            "XuCompa Request (*.xreq);; JSON files (*.json);; All files (*)")
        if name[0] != "":
            config = Config.getConfig()
            config["viewer"]["last_open"] = os.path.dirname(name[0])
            Config.updateConfig(config)

            file = XFile(name[0])
            self.dataTemp.insert(0, file)
            self.onItemSelected(file)
            self.updateDataList(self.dataTemp, self.dataSource.list)
            self.refresh()
示例#13
0
class TextEditWidget(PWidget):
    alert = pyqtSignal(str, str, object, object)
    syncRequest = pyqtSignal(object)
    editorTypeChanged = pyqtSignal(object)
    saveDataDone = pyqtSignal(str)

    def __init__(self,
                 editType: EditorType = EditorType.Manual,
                 save: bool = True,
                 sync: bool = True):
        super().__init__()
        self.editor = TextEditor()
        self.editor.keyEvent.connect(self.editorEvent)

        tool = QHBoxLayout()

        if save:
            iconSize = 36
        else:
            iconSize = 24

        if save:
            self.title = PLabelEdit()
            self.title.setMaximumWidth(300)
            self.title.setFixedHeight(iconSize)
            self.title.setMaximumHeight(iconSize)
            self.title.setStyleSheet("QLabel{color:#424242; font-size:16px}")
            self.title.setText("Untitled")
            tool.addWidget(self.title)

        tool.addStretch()

        if editType == EditorType.Manual:
            self.editorTypeBox = PComboBox()
            self.editorTypeBox.setView(MiniView.listView())
            self.editorTypeBox.addItems(["Text", "JSON", "XML", "HTML"])
            self.editorTypeBox.currentIndexChanged.connect(
                self.editorTypeChange)
            tool.addWidget(self.editorTypeBox)

        self.wrapButton = QToolButton()
        self.wrapButton.setCheckable(True)
        self.wrapButton.setText("Wrap")
        self.wrapButton.setToolTip("Wrap/Unwrap (Ctrl+W)")
        self.wrapButton.setIcon(
            PResource.defaultIcon(Parapluie.Icon_Wrap_Text_Svg))
        self.wrapButton.setFixedSize(iconSize, iconSize)
        self.wrapButton.pressed.connect(self.wrapText)
        tool.addWidget(self.wrapButton)

        formatButton = QToolButton()
        formatButton.setText("Format")
        formatButton.setToolTip("Format Code (Ctrl+F)")
        formatButton.setIcon(
            PResource.defaultIcon(Parapluie.Icon_Clean_Code_Svg))
        formatButton.setFixedSize(iconSize, iconSize)
        formatButton.pressed.connect(self.formatText)
        tool.addWidget(formatButton)

        if save:
            saveButton = QToolButton()
            saveButton.setText("Save")
            saveButton.setToolTip("Save (Ctrl+S)")
            saveButton.setIcon(PResource.defaultIcon(Parapluie.Icon_Save_Svg))
            saveButton.setFixedSize(iconSize, iconSize)
            saveButton.pressed.connect(self.saveData)
            tool.addWidget(saveButton)

        if sync:
            syncButton = QToolButton()
            syncButton.setText("Sync")
            syncButton.setToolTip("Sync (Ctrl+B)")
            syncButton.setIcon(
                PResource.defaultIcon(Parapluie.Icon_Double_Right_Chevron_Svg))
            syncButton.setFixedSize(iconSize, iconSize)
            syncButton.pressed.connect(self.syncJson)
            tool.addWidget(syncButton)

        widget = QWidget()
        widget.setLayout(tool)
        widget.layout().setContentsMargins(8, 0, 8, 0)
        widget.setObjectName(Parapluie.Object_Editor_Header)
        widget.setMaximumHeight(iconSize)

        layout = QVBoxLayout()
        layout.addWidget(widget)
        layout.addWidget(self.editor)

        self.setLayout(layout)
        self.layout().setContentsMargins(5, 5, 5, 5)
        self.setObjectName(Parapluie.Object_Editor)

        self.currentFile = None

        self.editType = EditorType.Text
        self.setEditorType(EditorType.Text)

    def formatText(self, key: bool = False, sync=True):
        text = self.editor.text()
        if text != "":
            new_text = Formatter.dumps(text, self.editType,
                                       self.pushAlert if not key else None)
            if new_text:
                self.editor.setText(new_text)
                if sync:
                    self.syncJson(key)

    def syncJson(self, key: bool = False):
        obj = self.getData(key)
        if self.editType == EditorType.JSON or self.editType == EditorType.XML:
            self.syncRequest.emit(obj)
            self.formatText(key, False)

    def pushAlert(self, text, tpe=Parapluie.Alert_Error):
        self.alert.emit(text, tpe, None, None)

    def setData(self, obj):
        text = Formatter.dumps(obj, self.editType,
                               self.pushAlert if obj is None else None)
        self.editor.setText(text)

    def getData(self, key: bool = False):
        text = self.editor.text()
        if text != "":
            if self.editType == EditorType.JSON:
                try:
                    obj = json.loads(text)
                    return obj
                except Exception as ex:
                    logging.exception(ex)
                    if not key:
                        self.pushAlert(str(ex))
                    return None
            elif self.editType == EditorType.XML:
                try:
                    obj = Et.fromstring(text)
                    return obj
                except Exception as ex:
                    logging.exception(ex)
                    if not key:
                        self.pushAlert(str(ex))
                    return None
        else:
            if self.editType == EditorType.JSON:
                return {}
            elif self.editType == EditorType.XML:
                return None
        return text

    def setText(self, text):
        self.editor.setText(text)

    def text(self):
        return self.editor.text()

    def wrapText(self):
        if self.wrapButton.isChecked():
            self.editor.setWrapMode(Qsci.QsciScintilla.WrapNone)
        else:
            self.editor.setWrapMode(Qsci.QsciScintilla.WrapWord)

    def editorEvent(self, key):
        if key == "ENTER":
            self.syncJson(True)
        elif key == "B":
            self.syncJson()
        elif key == "F":
            self.formatText()

    def setTitle(self, title):
        self.title.setText(title)

    def setEditorType(self, tpe: EditorType, inner=False):
        self.editType = tpe
        if not inner:
            self.editorTypeBox.setCurrentIndex(tpe.value)

        if tpe == EditorType.JSON:
            self.editor.changeLexer(Qsci.QsciLexerJSON(self.editor), 'JSON')
        elif tpe == EditorType.XML:
            self.editor.changeLexer(Qsci.QsciLexerXML(self.editor), 'XML')
        elif tpe == EditorType.HTML:
            self.editor.changeLexer(Qsci.QsciLexerHTML(self.editor), 'HTML')
        elif tpe == EditorType.Javascript:
            self.editor.changeLexer(Qsci.QsciLexerJavaScript(self.editor),
                                    'Javascript')
        else:
            self.editor.changeLexer(Qsci.QsciLexerMarkdown(self.editor),
                                    'Text<')

        self.editorTypeChanged.emit(tpe.value)

    def blockEditorType(self, block):
        self.editorTypeBox.setVisible(not block)

    # ["Text", "JSON", "XML", "HTML"]
    def editorTypeChange(self, index):
        if index == 0:
            self.setEditorType(EditorType.Text, True)
        elif index == 1:
            self.setEditorType(EditorType.JSON, True)
        elif index == 2:
            self.setEditorType(EditorType.XML, True)
        elif index == 3:
            self.setEditorType(EditorType.HTML, True)

    def setFile(self, file: XFile):
        # save data cũ
        if self.currentFile is not None:
            self.currentFile.unsavedData = self.text()
        # load data moi
        self.currentFile = file
        self.setTitle(file.name()[0])

        if file.name()[1].lower() == '.json':
            self.setEditorType(EditorType.JSON)
        elif file.name()[1].lower() == '.xml':
            self.setEditorType(EditorType.XML)
        elif file.name()[1].lower() == '.html':
            self.setEditorType(EditorType.HTML)
        elif file.name()[1].lower() == '.js':
            self.setEditorType(EditorType.Javascript)
        else:
            self.setEditorType(EditorType.Text)

        self.title.setEditable(not os.path.isfile(file.getPath()))
        if file.unsavedData != "":
            self.setText(file.unsavedData)
        else:
            if os.path.isfile(file.getPath()):
                d = open(file.getPath(), "r", encoding="utf-8").read()
                self.setText(d)
            else:
                self.setText("")
        self.syncJson()

    def saveData(self):
        if self.currentFile is None:
            init_dir = Config.getViewerConfig_LastOpen()
            file = os.path.join(init_dir, self.title.text())
            name = QFileDialog.getSaveFileName(self, 'Save file', file,
                                               self.getFileExtension())
            if name[0] != "":
                config = Config.getConfig()
                config["viewer"]["last_open"] = os.path.dirname(name[0])
                Config.updateConfig(config)
                self.currentFile = XFile(name[0])
                self.save(self.currentFile)
        else:
            if not os.path.isfile(self.currentFile.getPath()):
                name = QFileDialog.getSaveFileName(self, 'Save file',
                                                   self.currentFile.getPath(),
                                                   self.getFileExtension())
                if name[0] != "":
                    self.currentFile.setPath(name[0])
                    if self.save(self.currentFile) is not None:
                        self.saveDataDone.emit(name[0])
            else:
                if self.save(self.currentFile) is not None:
                    self.saveDataDone.emit(self.currentFile.getPath())

    def save(self, f: XFile):
        try:
            file = open(f.getPath(), "w", encoding="utf-8")
            file.write(self.text())
            file.close()
            f.unsavedData = ""
            self.pushAlert("Saved: " + f.getPath(),
                           Parapluie.Alert_Information)
            return f.getPath()
        except Exception as ex:
            logging.exception(ex)
            self.pushAlert(str(ex))

    def getFileExtension(self):
        if self.editType == EditorType.JSON:
            return "JSON files (*.json);; All files (*)"
        elif self.editType == EditorType.XML:
            return "XML files (*.xml);; All files (*)"
        elif self.editType == EditorType.HTML:
            return "HTML files (*.html);; All files (*)"
        elif self.editType == EditorType.Javascript:
            return "Javascript files (*.js);; All files (*)"
        else:
            return "All files (*)"
 def saveData(self, file: XFile, newData):
     if file.unsavedData is not None:  # has data unsaved
         if inRequestFolder(file.getPath()):
             self.saveExistedInRequest(file, newData)
         else:
             self.saveNewFile(file, newData)