Пример #1
0
    def cut(self, source: str, output: str, frametime: str, duration: str, allstreams: bool = True, gifOutput: bool = False, mp4Output: bool = False) -> bool:
        self.checkDiskSpace(output)
        args = '-y -ss {0} -i "{1}" -t {2} -c:v libx264 -an -crf 22 -pix_fmt yuv420p ' + \
            '-vf "scale=iw*min(1\,min(1280/iw\,720/ih)):-2" -preset fast "{3}"'

        timestamp = int(time.time())
        file_path = QDir.fromNativeSeparators(output)
        file_dir = file_path.replace(QFileInfo(output).fileName(), "")
        png_frame = QFileInfo(output).fileName().replace(".mp4", "%3d.png")
        png_dir = file_dir + 'tmp' + str(timestamp) + '/'
        gif_dir = file_dir + QFileInfo(output).fileName().replace(".mp4", ".gif")
        cut_arg = '-ss {0} -i "{1}" -t {2} -vf "fps=24,scale=iw*min(1\,min(640/iw\,360/ih)):-2" "{3}"'
        merged_arg = '{0} --fps 24 --output "{1}"'

        if gifOutput and not os.path.exists(gif_dir):
            os.mkdir(png_dir)
            self.cmdExec(self.backend,
                         cut_arg.format(frametime, source, duration, png_dir + png_frame))
            self.cmdExec(self.gifski,
                         merged_arg.format(png_dir + '*.png', gif_dir))
            shutil.rmtree(png_dir)

        if mp4Output:
            self.cmdExec(self.backend, args.format(frametime, source, duration, QDir.fromNativeSeparators(output)))

        return True
Пример #2
0
                def copy_freeze(src, dst):
                    for skip in skip_dirs:
                        if skip in src:
                            break
                    else:
                        if dst.endswith('.py'):
                            src = QDir.fromNativeSeparators(src)
                            dst = QDir.fromNativeSeparators(dst)
                            rel_dst = dst[len(resources_dir) + 1:] + 'o'

                            self._freeze(job_writer, dst + 'o', src, rel_dst)

                            resource_contents.append(rel_dst)
Пример #3
0
                def copy_freeze(src, dst):
                    for skip in skip_dirs:
                        if skip in src:
                            break
                    else:
                        if dst.endswith('.py'):
                            src = QDir.fromNativeSeparators(src)
                            dst = QDir.fromNativeSeparators(dst)
                            rel_dst = dst[len(resources_dir) + 1:] + 'o'

                            self._freeze(job_writer, dst + 'o', src, rel_dst)

                            resource_contents.append(rel_dst)
Пример #4
0
 def openLocation(self, key):
     if not self.locationKey:
         print('file:///' +
               QDir.fromNativeSeparators(self.page + '?key=' + key))
         self.viewport.load(
             QUrl('file:///' +
                  QDir.fromNativeSeparators(self.page + '?key=' +
                                            key)))  #'file:///'+
     else:
         #js = 'this.key_param = "%s";this.mly.moveToKey(this.key_param).then(function() {},function(e) { console.error(e); })' % key
         js = 'this.changeImgKey("%s")' % key
         self.viewport.page().mainFrame().evaluateJavaScript(js)
     self.locationKey = key
Пример #5
0
    def __init__(self, parent=None):
        super(StartPage, self).__init__(parent)
        self._id = "Start Page"
        vbox = QVBoxLayout(self)
        self.view = QQuickWidget()
        self.view.setMinimumWidth(400)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        path_qml = QDir.fromNativeSeparators(
            os.path.join(resources.QML_FILES, "StartPage.qml"))
        path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file'))
        self.view.setSource(QUrl(path_qml))
        #self.view.show()
        self.root = self.view.rootObject()
        self.view.setMinimumSize(630, 400)
        vbox.addWidget(self.view)

        self.load_items()

        # self.root.openProject[str].connect(self._open_project)
        # self.root.removeProject[str].connect(self._on_click_on_delete)
        # self.root.markAsFavorite[str, bool].connect(self._on_click_on_favorite)
        # self.root.openPreferences.connect(self.openPreferences.emit)

        self.root.openProject.connect(self._open_project)
        self.root.removeProject.connect(self._on_click_on_delete)
        self.root.markAsFavorite.connect(self._on_click_on_favorite)
        self.root.openPreferences.connect(self.openPreferences.emit)
Пример #6
0
 def mpegtsJoin(self, inputs: list, output: str) -> bool:
     result = False
     try:
         self.checkDiskSpace(output)
         outfiles = list()
         video_bsf, audio_bsf = self.getBSF(inputs[0])
         # 1. transcode to mpeg transport streams
         for file in inputs:
             name, _ = os.path.splitext(file)
             outfile = '%s.ts' % name
             outfiles.append(outfile)
             if os.path.isfile(outfile):
                 os.remove(outfile)
             args = '-i "%s" -c copy -map 0 %s -f mpegts -v 16 "%s"' % (
                 file, video_bsf, outfile)
             if not self.cmdExec(self.backend, args):
                 return result
         # 2. losslessly concatenate at the file level
         if len(outfiles):
             if os.path.isfile(output):
                 os.remove(output)
             args = '-i "concat:%s" -c copy %s -v 16 "%s"' % (
                 '|'.join(map(str, outfiles)), audio_bsf,
                 QDir.fromNativeSeparators(output))
             result = self.cmdExec(self.backend, args)
             # 3. cleanup mpegts files
             [QFile.remove(file) for file in outfiles]
     except:
         self.logger.exception('Exception in VideoService.mpegtsJoin()',
                               exc_info=True)
         result = False
     return result
Пример #7
0
def fromNativeSeparators(path):
    """
    Function returning a path, that is using "/" separator characters.
    
    @param path path to be converted (QString)
    @return path with converted separator characters (QString)
    """
    return QDir.fromNativeSeparators(path)
Пример #8
0
def fromNativeSeparators(path):
    """
    Function returning a path, that is using "/" separator characters.
    
    @param path path to be converted (QString)
    @return path with converted separator characters (QString)
    """
    return QDir.fromNativeSeparators(path)
Пример #9
0
 def on_pathButton_clicked(self):
     """
     Private slot called to open a directory selection dialog.
     """
     path = E5FileDialog.getExistingDirectory(
         self, self.tr("Select source directory"),
         QDir.fromNativeSeparators(self.pathnameEdit.text()))
     if path:
         self.pathnameEdit.setText(QDir.toNativeSeparators(path))
Пример #10
0
 def on_pathButton_clicked(self):
     """
     Private slot called to open a directory selection dialog.
     """
     path = E5FileDialog.getExistingDirectory(
         self, self.tr("Select source directory"), QDir.fromNativeSeparators(self.pathnameEdit.text())
     )
     if path:
         self.pathnameEdit.setText(QDir.toNativeSeparators(path))
Пример #11
0
def get_qml_resource(qmlpath):
    path_qml = QDir.fromNativeSeparators(
        os.path.join(resources.QML_FILES, qmlpath))
    print("get_qml_resource:1:",path_qml, urlparse(path_qml))
    try:
        import virtualenv
        path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file'))
    except ImportError:
        # path_qml = "file:///"+path_qml
        pass
    print("get_qml_resource:2:",path_qml)
    return QUrl.fromLocalFile(path_qml)
Пример #12
0
    def show_add_directory_dialog(self):
        directory = get_existing_directory(get_main_window(), 'Add Directory',
                                           self.last_directory)

        if len(directory) == 0:
            return

        self.last_directory = directory

        if len(
                self.list_files.findItems(os.path.join(directory, '*'),
                                          Qt.MatchFixedString)) > 0:
            return

        uploads = []

        progress = ExpandingProgressDialog(self)
        progress.set_progress_text_visible(False)
        progress.setWindowTitle('New Program')
        progress.setLabelText(u"Collecting content of {0}".format(directory))
        progress.setModal(True)
        progress.setRange(0, 0)
        progress.show()

        for root, directories, files in os.walk(directory):
            if progress.wasCanceled():
                break

            for filename in files:
                source = os.path.join(root, filename)
                target = QDir.fromNativeSeparators(
                    os.path.relpath(source, directory))
                uploads.append(Upload(source, target))

                # ensure that the UI stays responsive
                QApplication.processEvents()

                if progress.wasCanceled():
                    break

        if progress.wasCanceled():
            return

        progress.cancel()

        # FIXME: maybe add a warning if the directory contains very many files or large amounts of data

        item = QListWidgetItem(os.path.join(directory, '*'))
        item.setData(Qt.UserRole, uploads)
        item.setData(Qt.DecorationRole, self.folder_icon)
        self.list_files.addItem(item)

        self.completeChanged.emit()
Пример #13
0
def setLibraryPaths():
    """
    Module function to set the Qt library paths correctly for windows systems.
    """
    if Globals.isWindowsPlatform():
        libPath = os.path.join(Globals.getPyQt5ModulesDirectory(), "plugins")
        if os.path.exists(libPath):
            libPath = QDir.fromNativeSeparators(libPath)
            libraryPaths = QApplication.libraryPaths()
            if libPath not in libraryPaths:
                libraryPaths.insert(0, libPath)
                QApplication.setLibraryPaths(libraryPaths)
Пример #14
0
def preprocess_stylesheet(qss, abs_theme_dir):
    qss = qss.replace('<IDADIR>', QDir.fromNativeSeparators(IDA_DIR))
    qss = qss.replace('<SKINDIR>', QDir.fromNativeSeparators(abs_theme_dir))

    def replace_keyword(x, keyword, kind):
        cfg = IdaFontConfig(kind)
        prefix = '<{}_FONT_'.format(keyword)

        x = x.replace(prefix + 'FAMILY>', cfg.family)
        x = x.replace(prefix + 'STYLE>', ' italic' if cfg.italic else '')
        x = x.replace(prefix + 'WEIGHT>', ' bold' if cfg.bold else '')
        x = x.replace(prefix + 'SIZE>', '{} pt'.format(cfg.size))

        return x

    qss = replace_keyword(qss, 'DISASSEMBLY', 'disas')
    qss = replace_keyword(qss, 'HEXVIEW', 'hexview')
    qss = replace_keyword(qss, 'DEBUG_REGISTERS', 'debug_regs')
    qss = replace_keyword(qss, 'TEXT_INPUT', 'text_input')
    qss = replace_keyword(qss, 'OUTPUT_WINDOW', 'output_wnd')
    return qss
Пример #15
0
def setLibraryPaths():
    """
    Module function to set the Qt library paths correctly for windows systems.
    """
    if Globals.isWindowsPlatform():
        libPath = os.path.join(Globals.getPyQt5ModulesDirectory(), "plugins")
        if os.path.exists(libPath):
            libPath = QDir.fromNativeSeparators(libPath)
            libraryPaths = QApplication.libraryPaths()
            if libPath not in libraryPaths:
                libraryPaths.insert(0, libPath)
                QApplication.setLibraryPaths(libraryPaths)
Пример #16
0
    def preprocess_stylesheet(self, qss, abs_theme_dir):
        qss = qss.replace('<IDADIR>', QDir.fromNativeSeparators(IDA_DIR))
        qss = qss.replace('<SKINDIR>', QDir.fromNativeSeparators(abs_theme_dir))

        def replace_keyword(x, keyword, kind):
            cfg = IdaFontConfig(kind)
            prefix = '<{}_FONT_'.format(keyword)

            x = x.replace(prefix + 'FAMILY>', cfg.family)
            x = x.replace(prefix + 'STYLE>', ' italic' if cfg.italic else '')
            x = x.replace(prefix + 'WEIGHT>', ' bold' if cfg.bold else '')
            x = x.replace(prefix + 'SIZE>', '{} pt'.format(cfg.size))

            return x

        qss = replace_keyword(qss, 'DISASSEMBLY', 'disas')
        qss = replace_keyword(qss, 'HEXVIEW', 'hexview')
        qss = replace_keyword(qss, 'DEBUG_REGISTERS', 'debug_regs')
        qss = replace_keyword(qss, 'TEXT_INPUT', 'text_input')
        qss = replace_keyword(qss, 'OUTPUT_WINDOW', 'output_wnd')

        return qss
Пример #17
0
 def join(self, inputs: list, output: str, allstreams: bool = True) -> bool:
     self.checkDiskSpace(output)
     filelist = os.path.normpath(os.path.join(os.path.dirname(inputs[0]), '_vidcutter.list'))
     fobj = open(filelist, 'w')
     [fobj.write('file \'%s\'\n' % file.replace("'", "\\'")) for file in inputs]
     fobj.close()
     if allstreams:
         args = '-f concat -safe 0 -i "{0}" -c copy -copyinkf -map 0 -v 16 -y "{1}"'
     else:
         args = '-f concat -safe 0 -i "{0}" -c copy -copyinkf -v 16 -y "{1}"'
     result = self.cmdExec(self.backend, args.format(filelist, QDir.fromNativeSeparators(output)))
     os.remove(filelist)
     return result
Пример #18
0
 def cut(self,
         source: str,
         output: str,
         frametime: str,
         duration: str,
         allstreams: bool = True) -> bool:
     self.checkDiskSpace(output)
     if allstreams:
         args = '-ss {0} -i "{1}" -t {2} -vcodec libx264 -an -sn -crf 22 -pix_fmt yuv420p ' + \
                '-filter_complex "scale=iw*min(1\,min(1280/iw\,720/ih)):-2" -map 0 -v 16 -y "{3}"'
     else:
         args = '-ss {0} -i "{1}" -t {2} -vcodec libx264 -an -sn -crf 22 -pix_fmt yuv420p ' + \
                '-filter_complex "scale=iw*min(1\,min(1280/iw\,720/ih)):-2" -v 16 -y "{3}"'
     return self.cmdExec(
         self.backend,
         args.format(frametime, source, duration,
                     QDir.fromNativeSeparators(output)))
Пример #19
0
 def join(self, filelist: list, output: str) -> bool:
     args = '-f concat -safe 0 -i "%s" -c copy -y "%s"' % (
         filelist, QDir.fromNativeSeparators(output))
     return self.cmdExec(self.backend, args)
Пример #20
0
 def cut(self, source: str, output: str, frametime: str,
         duration: str) -> bool:
     args = '-i "%s" -ss %s -t %s -vcodec copy -acodec copy -y "%s"' \
            % (source, frametime, duration, QDir.fromNativeSeparators(output))
     return self.cmdExec(self.backend, args)
Пример #21
0
def get_qml_resource(qmlpath):
    path_qml = QDir.fromNativeSeparators(
        os.path.join(resources.QML_FILES, qmlpath))
    path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file'))
    return QUrl(path_qml)
Пример #22
0
def get_qml_resource(qmlpath):
    path_qml = QDir.fromNativeSeparators(
        os.path.join(resources.QML_FILES, qmlpath))
    path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file'))
    return QUrl(path_qml)
Пример #23
0
def get_filename(f):
    return f.split(QDir.fromNativeSeparators(os.path.sep))[-1]
Пример #24
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):
             # 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}".format(qVersion()[:3])])
         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
Пример #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
# -*- coding: utf-8 -*-
Пример #27
0
 def __showPathPickerDialog(self):
     """
     Private slot to show the path picker dialog.
     """
     if self.__mode == E5PathPickerModes.NoMode:
         return
     
     if self.__mode == E5PathPickerModes.CustomMode:
         self.pickerButtonClicked.emit()
         return
     
     self.aboutToShowPathPickerDialog.emit()
     
     windowTitle = self.__windowTitle
     if not windowTitle:
         if self.__mode == E5PathPickerModes.OpenFileMode:
             windowTitle = self.tr("Choose a file to open")
         elif self.__mode == E5PathPickerModes.OpenFilesMode:
             windowTitle = self.tr("Choose files to open")
         elif self.__mode in [
             E5PathPickerModes.SaveFileMode,
                 E5PathPickerModes.SaveFileEnsureExtensionMode,
                 E5PathPickerModes.SaveFileOverwriteMode]:
             windowTitle = self.tr("Choose a file to save")
         elif self.__mode == E5PathPickerModes.DirectoryMode:
             windowTitle = self.tr("Choose a directory")
     
     directory = self._editorText()
     if not directory and self.__defaultDirectory:
         directory = self.__defaultDirectory
     if self.__mode == E5PathPickerModes.OpenFilesMode:
         directory = os.path.expanduser(directory.split(";")[0])
     else:
         directory = os.path.expanduser(directory)
     if not os.path.isabs(directory) and self.__defaultDirectory:
         directory = os.path.join(self.__defaultDirectory, directory)
     directory = QDir.fromNativeSeparators(directory)
     
     if self.__mode == E5PathPickerModes.OpenFileMode:
         path = E5FileDialog.getOpenFileName(
             self,
             windowTitle,
             directory,
             self.__filters)
         path = QDir.toNativeSeparators(path)
     elif self.__mode == E5PathPickerModes.OpenFilesMode:
         paths = E5FileDialog.getOpenFileNames(
             self,
             windowTitle,
             directory,
             self.__filters)
         path = ";".join([QDir.toNativeSeparators(path)
                          for path in paths])
     elif self.__mode == E5PathPickerModes.SaveFileMode:
         path = E5FileDialog.getSaveFileName(
             self,
             windowTitle,
             directory,
             self.__filters,
             E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
         path = QDir.toNativeSeparators(path)
     elif self.__mode == E5PathPickerModes.SaveFileEnsureExtensionMode:
         path, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
             self,
             windowTitle,
             directory,
             self.__filters,
             None,
             E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
         path = QDir.toNativeSeparators(path)
         if path:
             ext = QFileInfo(path).suffix()
             if not ext:
                 ex = selectedFilter.split("(*")[1].split(")")[0]
                 if ex:
                     path += ex
     elif self.__mode == E5PathPickerModes.SaveFileOverwriteMode:
         path = E5FileDialog.getSaveFileName(
             self,
             windowTitle,
             directory,
             self.__filters)
         path = QDir.toNativeSeparators(path)
     elif self.__mode == E5PathPickerModes.DirectoryMode:
         path = E5FileDialog.getExistingDirectory(
             self,
             windowTitle,
             directory,
             E5FileDialog.Options(E5FileDialog.ShowDirsOnly))
         path = QDir.toNativeSeparators(path)
         while path.endswith(os.sep):
             path = path[:-1]
     elif self.__mode == E5PathPickerModes.DirectoryShowFilesMode:
         path = E5FileDialog.getExistingDirectory(
             self,
             windowTitle,
             directory,
             E5FileDialog.Options(E5FileDialog.DontUseNativeDialog))
         path = QDir.toNativeSeparators(path)
         while path.endswith(os.sep):
             path = path[:-1]
     
     if path:
         self._setEditorText(path)
         self.pathSelected.emit(path)