Пример #1
0
 def __installEric6Doc(self, engine):
     """
     Private method to install/update the eric6 help documentation.
     
     @param engine reference to the help engine (QHelpEngineCore)
     @return flag indicating success (boolean)
     """
     versionKey = "eric6_ide"
     info = engine.customValue(versionKey, "")
     lst = info.split('|')
     
     dt = QDateTime()
     if len(lst) and lst[0]:
         dt = QDateTime.fromString(lst[0], Qt.ISODate)
     
     qchFile = ""
     if len(lst) == 2:
         qchFile = lst[1]
     
     docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help")
     
     files = docsPath.entryList(["*.qch"])
     if not files:
         engine.setCustomValue(
             versionKey, QDateTime().toString(Qt.ISODate) + '|')
         return False
     
     for f in files:
         if f == "source.qch":
             fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
             if dt.isValid() and \
                fi.lastModified().toString(Qt.ISODate) == \
                 dt.toString(Qt.ISODate) and \
                qchFile == fi.absoluteFilePath():
                 return False
             
             namespace = QHelpEngineCore.namespaceName(
                 fi.absoluteFilePath())
             if not namespace:
                 continue
             
             if namespace in engine.registeredDocumentations():
                 engine.unregisterDocumentation(namespace)
             
             if not engine.registerDocumentation(fi.absoluteFilePath()):
                 self.errorMessage.emit(
                     self.tr(
                         """<p>The file <b>{0}</b> could not be"""
                         """ registered. <br/>Reason: {1}</p>""")
                     .format(fi.absoluteFilePath, engine.error())
                 )
                 return False
             
             engine.setCustomValue(
                 versionKey,
                 fi.lastModified().toString(Qt.ISODate) + '|' +
                 fi.absoluteFilePath())
             return True
     
     return False
Пример #2
0
    def __installEric6Doc(self, engine):
        """
        Private method to install/update the eric6 help documentation.
        
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "eric6_ide"
        info = engine.customValue(versionKey, "")
        lst = info.split('|')

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help")

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey,
                                  QDateTime().toString(Qt.ISODate) + '|')
            return False

        for f in files:
            if f == "source.qch":
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(
                    fi.absoluteFilePath())
                if not namespace:
                    continue

                if (dt.isValid()
                        and namespace in engine.registeredDocumentations()
                        and (fi.lastModified().toString(Qt.ISODate)
                             == dt.toString(Qt.ISODate))
                        and qchFile == fi.absoluteFilePath()):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be"""
                            """ registered. <br/>Reason: {1}</p>""").format(
                                fi.absoluteFilePath, engine.error()))
                    return False

                engine.setCustomValue(
                    versionKey,
                    fi.lastModified().toString(Qt.ISODate) + '|' +
                    fi.absoluteFilePath())
                return True

        return False
Пример #3
0
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False):
    dir = QDir()
    dir.setPath(from_dir)

    from_dir += QDir.separator()
    to_dir += QDir.separator()

    if not os.path.exists(to_dir):
        os.makedirs(to_dir)

    for file_ in dir.entryList(QDir.Files):
        from_ = from_dir + file_
        to_ = to_dir + file_

        if os.path.exists(to_):
            if replace_on_conflict:
                if not QFile.remove(to):
                    return False
            else:
                continue

        if not QFile.copy(from_, to_):
            return False

    for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot):
        from_ = from_dir + dir_
        to_ = to_dir + dir_

        if not os.path.exists(to_):
            os.makedirs(to_)

        if not copy_dir_recursive(from_, to_, replace_on_conflict):
            return False

    return True
Пример #4
0
def main():
    """ Main loop to run test
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    print('home_dir:', home_dir)
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    print('stdPwlDict:', stdPwlDict)
Пример #5
0
def get(name):
    """ Retrieve setting and convert result
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    settings = QSettings("Davide Setti", "Lector")
    if name == 'scanner:height':
        return int(settings.value(name, 297))
    elif name == 'scanner:width':
        return int(settings.value(name, 210))
    elif name == 'scanner:resolution':
        return int(settings.value(name, 300))
    elif name == 'scanner:mode':
        return str(settings.value(name, "Color"))
    elif name == 'scanner:device':
        return str(settings.value(name, ""))
    elif name == 'editor:font':
        return settings.value(name, QFont(QFont("Courier New", 10)))
    elif name == 'editor:symbols':
        return settings.value(name)
    elif name in ('editor:clear', 'editor:spell', 'editor:whiteSpace',
                  'spellchecker:pwlLang',):
        return str(settings.value(name, "true")).lower() == "true"
    elif name in ('log:errors'):
        return str(settings.value(name, "false")).lower() == "true"
    elif name == 'spellchecker:pwlDict':
        return str(settings.value(name, stdPwlDict))
    else:
        return str(settings.value(name, ""))
Пример #6
0
 def on_mainscriptButton_clicked(self):
     """
     Private slot to display a file selection dialog.
     """
     dir = self.dirEdit.text()
     if not dir:
         dir = QDir.currentPath()
     patterns = []
     for pattern, filetype in list(self.project.pdata["FILETYPES"].items()):
         if filetype == "SOURCES":
             patterns.append(pattern)
     filters = self.tr("Source Files ({0});;All Files (*)")\
         .format(" ".join(patterns))
     fn = E5FileDialog.getOpenFileName(
         self,
         self.tr("Select main script file"),
         dir,
         filters)
     
     if fn:
         ppath = self.dirEdit.text()
         if ppath:
             ppath = QDir(ppath).absolutePath() + QDir.separator()
             fn = fn.replace(ppath, "")
         self.mainscriptEdit.setText(Utilities.toNativeSeparators(fn))
Пример #7
0
    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QProcess.Running:
            app = QLibraryInfo.location(
                QLibraryInfo.BinariesPath) + QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QMessageBox.critical(None, "PyQt Demo",
                                     "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'
Пример #8
0
 def __init__(self, executable_path):
     super(Ui, self).__init__()
     ui_file = executable_path + QDir.separator() + 'Serial.ui'
     uic.loadUi(ui_file, self)
     self.serial = Serial()
     self.__signals()
     self.show()
Пример #9
0
 def data(self, index, role=Qt.DisplayRole):
     if (role == Qt.DisplayRole and index.column() == 0):
         path = QDir.toNativeSeparators(self.filePath(index))
         if path.endsWith(QDir.separator()):
             path.chop(1)
         return path
     return QDirModel.data(self, index, role)
Пример #10
0
 def on_mainscriptButton_clicked(self):
     """
     Private slot to display a file selection dialog.
     """
     dir = self.dirEdit.text()
     if not dir:
         dir = QDir.currentPath()
     patterns = []
     for pattern, filetype in list(self.project.pdata["FILETYPES"].items()):
         if filetype == "SOURCES":
             patterns.append(pattern)
     filters = self.tr("Source Files ({0});;All Files (*)")\
         .format(" ".join(patterns))
     fn = E5FileDialog.getOpenFileName(
         self,
         self.tr("Select main script file"),
         dir,
         filters)
     
     if fn:
         ppath = self.dirEdit.text()
         if ppath:
             ppath = QDir(ppath).absolutePath() + QDir.separator()
             fn = fn.replace(ppath, "")
         self.mainscriptEdit.setText(Utilities.toNativeSeparators(fn))
Пример #11
0
def main():
    """ Main loop to run test
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    print('home_dir:', home_dir)
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    print('stdPwlDict:', stdPwlDict)
Пример #12
0
def get(name):
    """ Retrieve setting and convert result
    """
    home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]
    stdPwlDict = home_dir + QDir.separator() + "my-dict.txt"
    settings = QSettings("Davide Setti", "Lector")
    if name == 'scanner:height':
        return int(settings.value(name, 297))
    elif name == 'scanner:width':
        return int(settings.value(name, 210))
    elif name == 'scanner:resolution':
        return int(settings.value(name, 300))
    elif name == 'scanner:mode':
        return str(settings.value(name, "Color"))
    elif name == 'scanner:device':
        return str(settings.value(name, ""))
    elif name == 'editor:font':
        return settings.value(name, QFont(QFont("Courier New", 10)))
    elif name == 'editor:symbols':
        return settings.value(name)
    elif name in (
            'editor:clear',
            'editor:spell',
            'editor:whiteSpace',
            'spellchecker:pwlLang',
    ):
        return str(settings.value(name, "true")).lower() == "true"
    elif name in ('log:errors'):
        return str(settings.value(name, "false")).lower() == "true"
    elif name == 'spellchecker:pwlDict':
        return str(settings.value(name, stdPwlDict))
    else:
        return str(settings.value(name, ""))
Пример #13
0
    def unzipdownloadFile(self, downladFile, latestVersion):
        import zipfile
        fileInfo = None
        self.newV2rayPath = None
        if QFile.exists(downladFile):
            fileInfo = QFileInfo(QFile(downladFile))
        else:
            return False

        def checkFilesize(file):
            v2rayFile = QFile(file.absoluteFilePath())
            # check file size need open the file
            v2rayFile.open(QIODevice.ReadOnly | QIODevice.Text)
            if v2rayFile.error() == v2rayFile.NoError:
                if v2rayFile.size() > 600000:
                    v2rayFile.close()
                    return True
            else:
                v2rayFile.close()
                return False

        if (fileInfo):
            with zipfile.ZipFile(fileInfo.absoluteFilePath(), "r") as zip_ref:
                for i in zip_ref.namelist():
                    absoluteFilePath = fileInfo.absolutePath(
                    ) + QDir.separator() + i
                    if re.search("/v2ray.exe$",
                                 absoluteFilePath):  # ## windows
                        self.newV2rayPath = None
                        self.newV2rayPath = QFileInfo(QFile(absoluteFilePath))
                        if self.newV2rayPath and checkFilesize(
                                self.newV2rayPath):
                            break
                    if re.search("/v2ray$", absoluteFilePath):  # ## other
                        self.newV2rayPath = None
                        self.newV2rayPath = QFileInfo(QFile(absoluteFilePath))
                        if self.newV2rayPath and checkFilesize(
                                self.newV2rayPath):
                            break
                try:
                    zip_ref.extractall(fileInfo.absolutePath())
                except PermissionError:
                    return
                if sys.platform.startswith('win'): pass
                else:
                    os.chmod(self.newV2rayPath.absoluteFilePath(), 0o755)
                    os.chmod(
                        self.newV2rayPath.absoluteFilePath()[:-5] + "v2ctl",
                        0o755)
            if self.newV2rayPath:
                if (self.stopV2ray): self.stopV2ray.emit()
                self.bridgetreasureChest.setV2raycoreFilePath(
                    self.newV2rayPath.absoluteFilePath())
                self.bridgetreasureChest.setV2raycoreVersion(latestVersion)
                self.bridgetreasureChest.save.emit()
                if (self.startV2ray): self.startV2ray.emit()
                return True
            else:
                return False
Пример #14
0
    def rename(self, item: QModelIndex, name: str) -> None:
        """Renames a file or a directory at a given ModelIndex to given name"""

        directory = QDir(self.root_path)
        old_path = self.FsModel.filePath(item)
        new_path = old_path[:old_path.rfind(directory.separator())] + "/" + name
        try:
            directory.rename(old_path, new_path)
        except OSError:
            raise ProjectError("Error renaming file or directory")
Пример #15
0
    def dropMimeData(self, data, action, row, column, parent):

        if not parent.isValid() or self.isReadOnly():
            return False

        if action == Qt.IgnoreAction:
            return True

        elif action == Qt.MoveAction:
            # print 'dropMimeData %s %s %s %s' % (data.data('text/uri-list'), action, row, parent)

            # print data.text()
            # print data.formats()
            # print data.data('text/uri-list')
            # print row, "row"
            # print column, "col"
            # print action, "action"
            # print parent, "parent"
            # print parent.data(Qt.DisplayRole),"parent"
            # print data.urls()

            #
            # filePath = data.data('text/uri-list').data()[7:]
            # filesFolderPath = filePath #canonical , os path parent falan
            #
            # fileName = os.path.basename(filePath)
            # fileName = ""
            # print type(filePath.data())
            # print fileName

            # os.path.normpath(self.model().fileInfo(self.selectedIndexes()[0]).absoluteFilePath())

            # dfolder = self.fileInfo(parent).absoluteFilePath()
            # destFinalPath = os.path.normpath("%s/%s" % (self.filePath(parent), fileName))

            # ya da emit.fileMoved filepath move to destFolder+filename
            # self.fileDraggedAndMoved.emit("%s -------->   %s" % (filePath, destFinalPath), 0)
            # self.fileDraggedAndMoved.emit(self.tr("%s has sent to trash" % filePath), 0)

            # success = True
            to = "%s%s" % (self.filePath(parent), QDir.separator())
            # print to
            for url in data.urls():
                path = url.toLocalFile()
                destFinalPath = "%s%s" % (to, QFileInfo(path).fileName())
                # if QFileInfo(destFinalPath).exists()
                return self.send_to_trash(path, destFinalPath)

            #     success = QFile.copy(path, destFinalPath) & QFile.remove(path) & success
            # return success
            # return QFileSystemModel.dropMimeData(self, data, action, row, column, parent)
        else:
            # return QFileSystemModel.dropMimeData(self, data, action, row, column, parent)
            return False
Пример #16
0
 def on_mainscriptPicker_pathSelected(self, script):
     """
     Private slot to check the selected main script name.
     
     @param script name of the main script
     @type str
     """
     if script:
         ppath = self.dirPicker.text()
         if ppath:
             ppath = QDir(ppath).absolutePath() + QDir.separator()
             script = script.replace(ppath, "")
         self.mainscriptPicker.setText(script)
Пример #17
0
 def on_mainscriptPicker_pathSelected(self, script):
     """
     Private slot to check the selected main script name.
     
     @param script name of the main script
     @type str
     """
     if script:
         ppath = self.dirPicker.text()
         if ppath:
             ppath = QDir(ppath).absolutePath() + QDir.separator()
             script = script.replace(ppath, "")
         self.mainscriptPicker.setText(script)
Пример #18
0
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False):
    dir = QDir()
    dir.setPath(from_dir)

    from_dir += QDir.separator()
    to_dir += QDir.separator()

    if not os.path.exists(to_dir):
        os.makedirs(to_dir)

    for file_ in dir.entryList(QDir.Files):
        from_ = from_dir + file_
        to_ = to_dir + file_
        if str(to_).endswith(".src"):
            to_ = str(to_).replace(".src", "")

        if os.path.exists(to_):
            if replace_on_conflict:
                if not QFile.remove(to_):
                    return False
            else:
                continue

        if not QFile.copy(from_, to_):
            return False

    for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot):
        from_ = from_dir + dir_
        to_ = to_dir + dir_

        if not os.path.exists(to_):
            os.makedirs(to_)

        if not copy_dir_recursive(from_, to_, replace_on_conflict):
            return False

    return True
Пример #19
0
 def saveToPDF(self):
     # early return se nao tiver item selecionado
     if(not self.hasSelectedItem()): return
     # obtendo item atual
     item = self.listWidget.currentItem()
     # pegando nome do arquivo pdf e salvando o pdf
     filename = QFileDialog.getSaveFileName(self, 'Save to PDF', self.path+QDir.separator()+item.text()+"-"+item.modified.replace(":","-"), "PDF File (*.pdf)")
     if filename[0]:
         printer = QPrinter(QPrinter.HighResolution)
         printer.setPageSize(QPrinter.A4)
         printer.setColorMode(QPrinter.Color)
         printer.setOutputFormat(QPrinter.PdfFormat)
         printer.setFullPage(True)
         printer.setOrientation(QPrinter.Portrait)
         printer.setOutputFileName(filename[0])
         self.textEdit.print_(printer)
Пример #20
0
    def displayLabeledImage(self, labeledImage, folder):
        #Cleanup
        self.clear()

        imageFileName = folder + QDir.separator() + labeledImage.fileName

        image = QImage(imageFileName)

        if image.isNull():
            print("Cannot load file {}".format(labeledImage.fileName))
            return

        pix = QPixmap.fromImage(image)

        self.pixmapItem = self.addPixmap(pix)
        self.pixmapItem.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
        self.pixmapItem.setPos(QPointF(0.0, 0.0))

        #Load labels
        for label in labeledImage.labels:
            r = RectangleLabelItem(rect=label.rectangle,
                                   parent=self.pixmapItem,
                                   label=label.classLabel)
Пример #21
0
    def showDocInAssistant(self, name):
        url = self.resolveDocUrl(name)
        Colors.debug("Sending URL to Assistant:", url)

        # Start assistant if it's not already running.
        if self.assistantProcess.state() != QProcess.Running:
            app = QLibraryInfo.location(QLibraryInfo.BinariesPath) + QDir.separator()

            if sys.platform == 'darwin':
                app += 'Assistant.app/Contents/MacOS/Assistant'
            else:
                app += 'assistant'

            args = ['-enableRemoteControl']
            self.assistantProcess.start(app, args)
            if not self.assistantProcess.waitForStarted():
                QMessageBox.critical(None, "PyQt Demo",
                        "Could not start %s." % app)
                return

        # Send command through remote control even if the process was just
        # started to activate assistant and bring it to the front.
        cmd_str = QTextStream(self.assistantProcess)
        cmd_str << 'SetSource ' << url << '\n'
Пример #22
0
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split("|")

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath) + QDir.separator() + "qch")
        elif version == 5:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath))
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + "|")
            return False

        for f in files:
            if f.startswith(name):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(fi.absoluteFilePath())
                if not namespace:
                    continue

                if (
                    dt.isValid()
                    and namespace in engine.registeredDocumentations()
                    and fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate)
                    and qchFile == fi.absoluteFilePath()
                ):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>"""
                        ).format(fi.absoluteFilePath, engine.error())
                    )
                    return False

                engine.setCustomValue(versionKey, fi.lastModified().toString(Qt.ISODate) + "|" + fi.absoluteFilePath())
                return True

        return False
Пример #23
0
def getConfDir():
    genConfDir = QStandardPaths.writableLocation(
            QStandardPaths.GenericConfigLocation)
    confDir = genConfDir + QDir.separator() + "libretrader" 

    return confDir
Пример #24
0
def getLockfileName(path):
    fi = QFileInfo(path)
    return fi.path() + QDir.separator() + ".#" + fi.fileName()
Пример #25
0
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split('|')

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(
                QLibraryInfo.location(QLibraryInfo.DocumentationPath) +
                QDir.separator() + "qch")
        elif version == 5:
            docsPath = QLibraryInfo.location(QLibraryInfo.DocumentationPath)
            if (not os.path.isdir(docsPath)
                    or len(QDir(docsPath).entryList(["*.qch"])) == 0):
                # Qt installer is a bit buggy; it's missing a symbolic link
                docsPathList = QDir.fromNativeSeparators(docsPath).split("/")
                docsPath = os.sep.join(
                    docsPathList[:-3] +
                    ["Docs", "Qt-{0}.{1}".format(*qVersionTuple())])
            docsPath = QDir(docsPath)
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey,
                                  QDateTime().toString(Qt.ISODate) + '|')
            return False

        for f in files:
            if f.startswith(name + "."):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(
                    fi.absoluteFilePath())
                if not namespace:
                    continue

                if (dt.isValid()
                        and namespace in engine.registeredDocumentations()
                        and (fi.lastModified().toString(Qt.ISODate)
                             == dt.toString(Qt.ISODate))
                        and qchFile == fi.absoluteFilePath()):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be"""
                            """ registered. <br/>Reason: {1}</p>""").format(
                                fi.absoluteFilePath, engine.error()))
                    return False

                engine.setCustomValue(
                    versionKey,
                    fi.lastModified().toString(Qt.ISODate) + '|' +
                    fi.absoluteFilePath())
                return True

        return False
Пример #26
0
def getFilePath(fileName):
    return getConfDir() + QDir.separator() + fileName
Пример #27
0
    def __init__(self):
        super(TileImages, self).__init__()
        self.images_list = []
        self.images_number = False
        self.images_panda = False
        self.images_folder = IMG_FOLDER_NAME + QDir.separator()

        path_dir = QDir()
        if path_dir.exists(IMG_FOLDER_NAME):
            self.images_number = True
            file_list = []
            for idx in range(16):
                file_path = self.images_folder + "number_" + str(idx) + ".png"
                if not QFile(file_path).exists():
                    self.images_number = False
                    file_list = []
                    break
                try:
                    img = Image.open(file_path)
                    image_width, image_height = img.size  # Get image dimensions
                    if image_width != IMG_SIZE or image_height != IMG_SIZE:
                        resize_slice = Image.open(file_path)
                        resize_slice = resize_slice.resize(
                            (IMG_SIZE, IMG_SIZE), Image.ANTIALIAS)
                        resize_slice.save(os.path.join(os.getcwd(), file_path))
                    file_list.append(file_path)
                except IOError:
                    self.images_number = False
                    file_list = []
                    break
            self.images_list.append(file_list)
            if self.images_number:
                self.tile_images = True
                self.images_in_use = []
                for img in self.images_list[0]:
                    self.images_in_use.append(img)

            self.images_panda = True
            file_list = []
            for idx in range(16):
                file_path = self.images_folder + "panda_" + str(idx) + ".png"
                if not QFile(file_path).exists():
                    self.images_panda = False
                    file_list = []
                    break
                try:
                    img = Image.open(file_path)
                    image_width, image_height = img.size  # Get image dimensions
                    if image_width != IMG_SIZE or image_height != IMG_SIZE:
                        resize_slice = Image.open(file_path)
                        resize_slice = resize_slice.resize(
                            (IMG_SIZE, IMG_SIZE), Image.ANTIALIAS)
                        resize_slice.save(os.path.join(os.getcwd(), file_path))
                    file_list.append(file_path)
                except IOError:
                    self.images_panda = False
                    file_list = []
                    break
            self.images_list.append(file_list)
        else:
            path_dir.mkpath(IMG_FOLDER_NAME)
            self.actionPandaBabies.setEnabled(False)
Пример #28
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Left Browser tabs
        self.ui.tabWidgetBrowser.removeTab(1)
        self.ui.tabWidgetBrowser.removeTab(1)
        self.ui.tabWidgetBrowser.setTabsClosable(True)
        self.ui.tabWidgetBrowser.tabCloseRequested.connect(self.closeBrowserTab)
        self.ui.tabWidgetBrowser.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetBrowser))

        # Left tree views
        self.fileTreeModel = QFileSystemModel(self)
        self.fileTreeModel.setRootPath(QDir.currentPath() + QDir.separator() + 'test')
        self.ui.treeViewFile.setModel(self.fileTreeModel)
        self.ui.treeViewFile.setRootIndex(self.fileTreeModel.index(QDir.currentPath() + QDir.separator() + 'test'))
        self.ui.treeViewFile.hideColumn(1)
        self.ui.treeViewFile.hideColumn(2)
        self.ui.treeViewFile.hideColumn(3)
        self.ui.treeViewFile.doubleClicked.connect(self.openFileFromTree)

        self.ui.treeViewFile.setAnimated(True)
        self.ui.treeViewSyntax.setAnimated(True)
        self.ui.treeViewToken.setAnimated(True)

        self.ui.treeViewFile.setHeaderHidden(True)
        self.ui.treeViewSyntax.setHeaderHidden(True)
        self.ui.treeViewToken.setHeaderHidden(True)

        # Editor tabs
        self.currentEditor = self.ui.codeEditor
        self.currentEditor.file = None
        self.currentEditorTab = self.ui.tabEditor
        self.openedEditors = [self.currentEditor]
        self.openedEditorTabs = [self.currentEditorTab]
        self.currentEditor.setFocus()  # set focus
        self.ui.tabWidgetEditor.tabCloseRequested.connect(self.closeEditorTab)
        self.ui.tabWidgetEditor.tabBarClicked.connect(self.switchEditorTab)
        self.ui.tabWidgetEditor.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetEditor))

        # Bottom console
        font = QFont()
        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.ui.console.setFont(font)
        self.ui.console.setReadOnly(True)
        self.waitInputCond = QWaitCondition()
        self.oldConsoleText = None

        # Bottom output tabs
        self.ui.tabWidgetOutput.hide()
        self.ui.tabWidgetOutput.tabCloseRequested.connect(self.closeOutputTab)
        self.ui.tabWidgetOutput.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetOutput))
        self.ui.tabWidgetOutput.setTabText(0, 'Console')

        # Previous opened tabs,for maximizing
        self.preOpenedTabs = None

        # Initial size of inner splitter
        self.ui.splitterInner.setSizes([180, 459 * 2 - 180])

        # Menu "File"
        self.ui.actionOpen.triggered.connect(self.openFile)
        self.ui.actionNew.triggered.connect(self.newFile)
        self.ui.actionSave.triggered.connect(self.saveFile)
        self.ui.actionSaveAs.triggered.connect(self.saveFileAs)
        self.ui.actionQuit.triggered.connect(self.close)

        # Menu "Edit"
        self.connectMenuEditSlots()

        # Menu "View"
        self.ui.menuView.triggered.connect(self.manageMenuView)
        self.ui.actionAboutQt.triggered.connect(QApplication.aboutQt)

        # Menu "Run"
        self.ui.actionRun.triggered.connect(self.run)
        self.ui.actionBuild.triggered.connect(self.runCompile)
        self.ui.actionShowStable.triggered.connect(self.runSemantic)
        self.ui.actionRunParser.triggered.connect(self.runParser)
        self.ui.actionRunLexer.triggered.connect(self.runLexer)
Пример #29
0
    def __init__(self):
        super(Cards, self).__init__()
        load_success = False
        dir_path = QDir()
        if dir_path.exists(IMG_FOLDER_NAME):
            load_success = True
            prefix = IMG_FOLDER_NAME + QDir.separator()
        else:
            print("falied 1")

        img_extension = ".png"

        if load_success:
            self.backcard_file = prefix + "backcard" + img_extension
            if not QFile(self.backcard_file).exists():
                load_success = False
                print("falied 2")
            else:
                try:
                    Image.open(self.backcard_file)
                except IOError:
                    load_success = False
                    print("falied 3")

        if load_success:
            card_prefix = prefix + "card"
            self.card_files = (prefix + "empty" + img_extension,
                            card_prefix + "01" + img_extension, card_prefix + "02" + img_extension,
                            card_prefix + "03" + img_extension, card_prefix + "04" + img_extension,
                            card_prefix + "05" + img_extension, card_prefix + "06" + img_extension,
                            card_prefix + "07" + img_extension, card_prefix + "08" + img_extension,
                            card_prefix + "09" + img_extension, card_prefix + "10" + img_extension,
                            card_prefix + "11" + img_extension, card_prefix + "12" + img_extension,
                            card_prefix + "13" + img_extension, card_prefix + "14" + img_extension,
                            card_prefix + "15" + img_extension, card_prefix + "16" + img_extension,
                            card_prefix + "17" + img_extension, card_prefix + "18" + img_extension,
                            card_prefix + "19" + img_extension, card_prefix + "20" + img_extension,
                            card_prefix + "21" + img_extension, card_prefix + "22" + img_extension,
                            card_prefix + "23" + img_extension, card_prefix + "24" + img_extension,
                            card_prefix + "25" + img_extension, card_prefix + "26" + img_extension,
                            card_prefix + "27" + img_extension, card_prefix + "28" + img_extension,
                            card_prefix + "29" + img_extension, card_prefix + "30" + img_extension,
                            card_prefix + "31" + img_extension, card_prefix + "32" + img_extension,
                            card_prefix + "33" + img_extension, card_prefix + "34" + img_extension,
                            card_prefix + "35" + img_extension, card_prefix + "36" + img_extension,
                            card_prefix + "37" + img_extension, card_prefix + "38" + img_extension,
                            card_prefix + "39" + img_extension, card_prefix + "40" + img_extension,
                            card_prefix + "41" + img_extension, card_prefix + "42" + img_extension,
                            card_prefix + "43" + img_extension, card_prefix + "44" + img_extension,
                            card_prefix + "45" + img_extension, card_prefix + "46" + img_extension,
                            card_prefix + "47" + img_extension, card_prefix + "48" + img_extension,
                            card_prefix + "49" + img_extension, card_prefix + "50" + img_extension,
                            card_prefix + "51" + img_extension, card_prefix + "52" + img_extension,
                            card_prefix + "53" + img_extension, card_prefix + "54" + img_extension,
                            card_prefix + "55" + img_extension, card_prefix + "56" + img_extension,
                            card_prefix + "57" + img_extension, card_prefix + "58" + img_extension,
                            card_prefix + "59" + img_extension, card_prefix + "60" + img_extension)

            for idx in range(61):
                if not QFile(self.card_files[idx]).exists():
                    load_success = False
                    print("falied 4 " + str(idx))
                    break
                try:
                    Image.open(self.card_files[idx])
                except IOError:
                    load_success = False
                    print("falied 5 " + str(idx))
                    break

        if not load_success:
            print("Missing required card images, exit program.")