Exemplo n.º 1
0
 def _entry_iterator(self, path):
     for entry in _scandir.scandir(path):
         if entry.is_dir():
             for _entry in self._entry_iterator(entry.path):
                 yield _entry
         else:
             yield entry
Exemplo n.º 2
0
    def _entry_iterator(self, path):
        """We're using the saved keys to find and return the DirEntries
        corresponding to the saved favourites.

        """
        favourites = settings.local_settings.favourites()

        d = []

        for k in favourites:
            file_info = QtCore.QFileInfo(k)
            _path = file_info.path()

            if not QtCore.QFileInfo(_path).exists():
                continue

            for entry in _scandir.scandir(_path):
                path = entry.path.replace(u'\\', u'/').lower()
                if path == k:
                    d.append(entry)
                    continue
                _k = common.proxy_path(path)
                if k.lower() == _k.lower():
                    d.append(entry)

        for entry in d:
            yield entry
Exemplo n.º 3
0
    def _entry_iterator(self, path):
        """Yields DirEntry instances to be processed in __initdata__.

        """
        for entry in _scandir.scandir(path):
            if entry.name.startswith(u'.'):
                continue
            if not entry.is_dir():
                continue
            yield entry
Exemplo n.º 4
0
    def iterateFolderContent(self, segments):
        """
        See `ILocalFilesystem`.
        """
        path = self.getRealPathFromSegments(segments)
        path_encoded = self.getEncodedPath(path)

        virtual_members = self._getVirtualMembers(segments)
        if segments and virtual_members:
            # We only support mixing virtual folder names with real names
            # for the root folder.
            # For all the other paths, we ignore the real folders if they
            # overlay a virtual path.
            return iter(virtual_members)

        # We start with possible virtual folders as they should shadow the
        # real folders.
        firsts = virtual_members
        try:
            with self._impersonateUser():
                folder_iterator = scandir(path_encoded)

            # On Windows we need to iterate over the first element to get the
            # errors.
            # Otherwise just by opening the directory, we don't get any errors.
            # This is why we try to extract the first element, and yield it
            # later.
            try:
                first_member = next(folder_iterator)
            except StopIteration:
                # The folder is empty so just return an iterator with possible
                # virtual members.
                return iter(virtual_members)

            real_first_attributes = self._dirEntryToFileAttributes(
                first_member)
            first_names = [m.name for m in firsts]
            if real_first_attributes.name not in first_names:
                firsts.append(real_first_attributes)

        except Exception as error:
            # We fail to list the actual folder.
            if not virtual_members:
                # Since there are no virtual folder, we just raise the error.
                raise error

            # We have virtual folders.
            # No direct listing.
            folder_iterator = iter([])

        return self._iterateScandir(set(firsts), folder_iterator)
Exemplo n.º 5
0
def do_scandir(msgq, count, top):
    logger = Logger(name = 'scandir', queue = msgq)

    dirs = [top]
    try:
        while True:
            if event.shutdown():
                break

            try:
                root = dirs.pop()
            except IndexError:
                break

            try:
                scandir_it = _scandir.scandir(root)
            except OSError, e:
                logger.error('%s: %s', root, e)
                continue

            while True:
                try:
                    try:
                        entry = next(scandir_it)
                    except StopIteration:
                        break
                except OSError, e:
                    logger.error('%s: %s', root, e)
                    continue

                try:
                    is_dir = entry.is_dir()
                except OSError:
                    is_dir = False

                try:
                    is_symlink = entry.is_symlink()
                except OSError:
                    is_symlink = False

                pathname = os.path.join(root, entry.name)

                if not is_symlink:
                    if is_dir:
                        dirs.append(pathname)
                    else:
                        if not is_symlink:
                            logger.info(pathname)
Exemplo n.º 6
0
def count_assets(bookmark_path, ASSET_IDENTIFIER):
    n = 0
    for entry in _scandir.scandir(bookmark_path):
        if entry.name.startswith(u'.'):
            continue
        if not entry.is_dir():
            continue

        filepath = entry.path.replace(u'\\', u'/')

        if ASSET_IDENTIFIER:
            identifier = u'{}/{}'.format(filepath, ASSET_IDENTIFIER)
            if not QtCore.QFileInfo(identifier).exists():
                continue
        n += 1
    return n
Exemplo n.º 7
0
def walk(path):
    """This is a custom generator expression using scandir's `walk`.
    We're using the C module for performance's sake without python-native
    fallbacks. The method yields each found DirEntry.

    The used _scandir module itself is customized to contain the addittional
    ``DirEntry.relativepath(unicode: basepath)`` method and ``DirEntry.dirpath``
    attribute.

    Yields:
        DirEntry:   A ctype class.

    """
    try:
        it = _scandir.scandir(path=path)
    except OSError:
        return

    while True:
        try:
            try:
                entry = next(it)
            except StopIteration:
                break
        except OSError:
            return

        try:
            is_dir = entry.is_dir()
        except OSError:
            is_dir = False

        if not is_dir:
            yield entry

        try:
            is_symlink = entry.is_symlink()
        except OSError:
            is_symlink = False
        if not is_symlink:
            for entry in walk(entry.path):
                yield entry
Exemplo n.º 8
0
    def dropEvent(self, event):
        """Event responsible for adding the dropped file to the favourites."""
        self.indicatorwidget.hide()

        if event.source() == self:
            return  # Won't allow dropping an item from itself

        mime = event.mimeData()
        if not mime.hasUrls():
            return

        event.accept()
        favourites = settings.local_settings.favourites()

        for url in mime.urls():
            file_info = QtCore.QFileInfo(url.toLocalFile())
            path = file_info.filePath().lower()

            if file_info.suffix().lower() == u'favourites':
                # This is a saved favourite template file
                common.import_favourites(source=path)
            else:
                # Here we should check if the dropped item is sequence.
                seq = common.get_sequence(path)
                if not seq:
                    k = path.lower()
                else:
                    frames = []
                    for entry in _scandir.scandir(file_info.dir().path()):
                        p = entry.path.replace('\\', '/').lower()
                        if seq.group(1) in p and seq.group(3) in p:
                            frames.append(p)
                    if len(frames) > 1:
                        k = common.proxy_path(path).lower()
                    else:
                        k = path.lower()
            favourites.append(k)
        settings.local_settings.setValue(
            u'favourites', sorted(list(set(favourites))))
        self.favouritesChanged.emit()
Exemplo n.º 9
0
    def add_custom_fonts(self):
        """Load the fonts used by Bookmarks to the font database.

        """
        if u'bmRobotoMedium' in self.families():
            return

        p = u'{}/../rsc/fonts'.format(__file__)
        p = os.path.normpath(os.path.abspath(p))

        if not os.path.isdir(p):
            raise OSError('{} could not be found'.format(p))

        for entry in _scandir.scandir(p):
            if not entry.name.endswith(u'ttf'):
                continue
            idx = self.addApplicationFont(entry.path)
            if idx < 0:
                raise RuntimeError(
                    u'Failed to add required font to the application')
            family = self.applicationFontFamilies(idx)
            if not family:
                raise RuntimeError(
                    u'Failed to add required font to the application')
Exemplo n.º 10
0
                        break
                except OSError, e:
                    logger.error('%s: %s', root, e)
                    continue

                try:
                    is_dir = entry.is_dir()
                except OSError:
                    is_dir = False

                try:
                    is_symlink = entry.is_symlink()
                except OSError:
                    is_symlink = False

                pathname = os.path.join(root, entry.name)

                if not is_symlink:
                    if is_dir:
                        dirs.append(pathname)
                    else:
                        if not is_symlink:
                            logger.info(pathname)
    finally:
        count.decr()


if __name__ == '__main__':
    for row in _scandir.scandir('.'):
        print row
Exemplo n.º 11
0
def launch_ffmpeg_command(input,
                          preset,
                          server=None,
                          job=None,
                          root=None,
                          asset=None,
                          task_folder=None):
    """Calls FFMpeg to process an input using the given preset.

    """
    w = common_ui.MessageBox(u'Converting...', u'Should take a few minutes...')
    try:
        FFMPEG_BIN = settings.local_settings.value(u'preferences/ffmpeg_path')
        if not FFMPEG_BIN:
            raise RuntimeError(
                u'The path to FFMpeg has not yet been set.\nYou can set the path in the General > External Applications section.'
            )
        if not QtCore.QFileInfo(FFMPEG_BIN):
            raise RuntimeError('FFMpeg was not found!')

        server = server if server else settings.ACTIVE['server']
        job = job if job else settings.ACTIVE['job']
        root = root if root else settings.ACTIVE['root']
        asset = asset if asset else settings.ACTIVE['asset']
        task_folder = task_folder if task_folder else settings.ACTIVE[
            'task_folder']

        input = input.replace(u'\\', '/').lower()

        # We want to get the first item  of any sequence
        if common.is_collapsed(input):
            input = common.get_sequence_startpath(input)
        else:
            seq = common.get_sequence(input)
            if not seq:
                raise RuntimeError(u'{} is not a sequence.'.format(input))
            _dir = QtCore.QFileInfo(input).dir().path()
            if not QtCore.QFileInfo(_dir):
                raise RuntimeError(u'{} does not exists.'.format(_dir))

            f = []
            for entry in _scandir.scandir(_dir):
                _path = entry.path.replace(u'\\', u'/').lower()
                if not seq.group(1) in _path:
                    continue
                _seq = common.get_sequence(_path)
                if not _seq:
                    continue
                f.append(int(_seq.group(2)))
            if not f:
                raise RuntimeError(
                    u'Could not find the first frame of the sequence.')

        startframe = min(f)
        endframe = max(f)

        # Framerate
        db = bookmark_db.get_db(server, job, root)
        framerate = db.value(1, 'framerate', table=u'properties')
        if not framerate:
            framerate = 24

        input = seq.group(1) + '%0{}d'.format(len(
            seq.group(2))) + seq.group(3) + '.' + seq.group(4)
        output = seq.group(1).rstrip(u'.').rstrip(u'_').rstrip() + u'.mp4'

        # Add informative label
        label = u''
        if job:
            label += job
            label += u'_'
        if asset:
            label += asset
            label += u'_'
        if task_folder:
            label += task_folder
            label += u' \\| '
        vseq = common.get_sequence(output)
        if vseq:
            label += 'v' + vseq.group(2) + u' '
            label += datetime.now().strftime('(%a %d/%m/%Y) \\| ')
        label += u'{}-{} \\| '.format(startframe, endframe)

        w.open()
        QtWidgets.QApplication.instance().processEvents()

        cmd = preset.format(
            BIN=FFMPEG_BIN,
            FRAMERATE=framerate,
            STARTFRAME=startframe,
            INPUT=os.path.normpath(input),
            OUTPUT=os.path.normpath(output),
            FONT=get_font_path(),
            LABEL=label,
        )
        subprocess.check_output(cmd, shell=True)

        w.close()
        log.success('Successfully saved {}'.format(output))
        common_ui.OkBox(u'Finished converting',
                        'Saved to {}'.format(output)).open()
    except Exception as e:
        w.close()
        log.error(u'Conversion failed.')
        common_ui.ErrorBox(u'Conversion failed', unicode(e)).open()
Exemplo n.º 12
0
    def __initdata__(self):
        """Bookmarks and assets are static. But files will be any number of """
        reset_monitor()

        self.INTERNAL_MODEL_DATA[0] = common.DataDict({
            common.FileItem:
            common.DataDict(),
            common.SequenceItem:
            common.DataDict()
        })

        flags = (QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
                 | QtCore.Qt.ItemIsDropEnabled | QtCore.Qt.ItemIsEditable)
        data = self.model_data()

        if not self.parent_path:
            return
        if not all(self.parent_path):
            return

        # Thumbnail image
        default_thumbnail = images.ImageCache.get_rsc_pixmap(
            u'folder_sm', common.SECONDARY_TEXT, self.ROW_SIZE.height())
        default_thumbnail = default_thumbnail.toImage()

        parent_path = u'/'.join(self.parent_path)
        MONITOR.addPath(parent_path)
        entries = sorted(([f for f in _scandir.scandir(parent_path)]),
                         key=lambda x: x.name)

        for entry in entries:
            if entry.name.startswith(u'.'):
                continue
            if not entry.is_dir():
                continue
            idx = len(data)
            data[idx] = common.DataDict({
                QtCore.Qt.DisplayRole:
                entry.name,
                QtCore.Qt.EditRole:
                entry.name,
                QtCore.Qt.StatusTipRole:
                entry.path.replace(u'\\', u'/'),
                QtCore.Qt.ToolTipRole:
                u'',
                QtCore.Qt.ToolTipRole:
                defaultpaths.get_description(entry.name),
                QtCore.Qt.SizeHintRole:
                self.ROW_SIZE,
                #
                common.FlagsRole:
                flags,
                common.ParentPathRole:
                self.parent_path,
                #
                common.FileInfoLoaded:
                False,
                common.ThumbnailLoaded:
                True,
                common.TodoCountRole:
                0,
                #
                common.IdRole:
                idx,
            })
            thread = self.threads[common.InfoThread][0]
            thread.add_to_queue(weakref.ref(data[idx]))