示例#1
0
    def on_metadata(self, event, metadata):

        row = {
            "location":
            self.hints['location'],
            "cache_location":
            "",
            "title":
            gnomevfs.URI(self.hints['location'][:-4]).short_name
            or _("Unknown"),
            "artist":
            _("Unknow Artist"),
            "duration":
            int(metadata['duration']),
        }

        if metadata.has_key('title'):
            row['title'] = metadata['title']
        if metadata.has_key('artist'):
            row['artist'] = metadata['artist']

        if self.hints.has_key('title'):
            row['title'] = self.hints['title']
        if self.hints.has_key('artist'):
            row['artist'] = self.hints['artist']

        if self.insert is not None:
            self.music_list.insert(self.insert, row)
        else:
            self.music_list.append(row)
示例#2
0
 def check_mime(self, buffer_number):
     buff, fname = self.wins[buffer_number]
     manager = buff.get_data('languages-manager')
     if os.path.isabs(fname):
         path = fname
     else:
         path = os.path.abspath(fname)
     uri = gnomevfs.URI(path)
     mime_type = gnomevfs.get_mime_type(
         path)  # needs ASCII filename, not URI
     if mime_type:
         language = manager.get_language_from_mime_type(mime_type)
         if language:
             buff.set_highlight(True)
             buff.set_language(language)
         else:
             dlg = gtk.MessageDialog(
                 self.get_parent_window(), gtk.DIALOG_DESTROY_WITH_PARENT,
                 gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                 'No language found for mime type "%s"' % mime_type)
             buff.set_highlight(False)
     else:
         dlg = gtk.MessageDialog(
             self.get_parent_window(), gtk.DIALOG_DESTROY_WITH_PARENT,
             gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
             'Couldn\'t get mime type for file "%s"' % fname)
         buff.set_highlight(False)
     buff.set_data("save", False)
示例#3
0
    def start(self):
        if len(self.errors) == 0:
            e = operations.FinishedEvent(self, operations.SUCCESSFUL)
            for l in self.listeners:
                l.on_finished(e)
            return

        elif len(self.errors) > 1:
            title = _("Unsupported file types")
        else:
            title = _("Unsupported file type")

        filenames = []
        for e in self.errors:
            filenames.append(gnomevfs.URI(e.hints['location']).short_name)
        del self.__errors

        if len(filenames) == 1:
            msg = _("The following files were not added:") + "\n"
        else:
            msg = _("The following files were not added:") + "\n"

        msg += " " + filenames[0]

        for f in filenames[1:]:
            msg += ", " + f
        gtkutil.dialog_error(title, msg, self.parent)

        e = operations.FinishedEvent(self, operations.SUCCESSFUL)
        for l in self.listeners:
            l.on_finished(e)
示例#4
0
    def get_comment(self):
        if not self.get_is_mounted():
            # FIXME: Check if drive is set to auto-mount, and if not show "Not Mounted"
            return _("No disk inserted")
        else:
            comment = ""

            volumes = self.drive.get_mounted_volumes()
            if len(volumes) == 1:
                vol_name = volumes[0].get_display_name()
                if vol_name != self.get_name():
                    comment += volumes[0].get_display_name()

            # FIXME: If read-only drive, show allocated size instead
            try:
                space = gnomevfs.get_volume_free_space(gnomevfs.URI(self.get_uri()))
            except (TypeError, gnomevfs.Error):
                # When the URI or free space is unknown
                space = 0

            if space:
                if comment: comment += "\n"
                comment += _("Free space: %s") % gnomevfs.format_file_size_for_display(space)

            return comment
示例#5
0
def vfs_walk(uri):
    """in the style of os.path.walk, but using gnomevfs.
	
	uri -- the base folder uri.
	return a list of uri.
	"""
    if not isinstance(uri, gnomevfs.URI):
        uri = gnomevfs.URI(uri)
    if str(uri)[-1] != '/':
        uri = uri.append_string("/")
    filelist = []
    try:
        dirlist = gnomevfs.open_directory(uri)
    except:
        log(_("skipping: '%s'") % uri)
        return filelist

    for file_info in dirlist:
        if file_info.name[0] == ".":
            continue

        if file_info.type == gnomevfs.FILE_TYPE_DIRECTORY:
            filelist.extend(vfs_walk(uri.append_path(file_info.name)))

        if file_info.type == gnomevfs.FILE_TYPE_REGULAR:
            filelist.append(str(uri.append_file_name(file_info.name)))
    return filelist
示例#6
0
 def islocal(self, uri):
     local = True
     try:
         if not gnomevfs.URI(uri).is_local:
             local = False
     except:
         pass
     return local
示例#7
0
def filename_to_uri(filename):
    """Convert a filename to a valid uri.
    Filename can be a relative or absolute path, or an uri.
    """
    if '://' not in filename:
        # convert local filename to uri
        filename = urllib.pathname2url(os.path.abspath(filename))
    filename = str(gnomevfs.URI(filename))
    return filename
示例#8
0
def vfs_clean_uri(uri):
    """return an uri from an uri or a local path"""
    try:
        gnomevfs.URI(uri)
        gnomevfs.Handle(uri)
    except:  #gnomevfs.InvalidURIError:
        try:
            uri_ = uri.replace('%5C', '/')  # convert backslashes
            gnomevfs.URI(uri_)
            gnomevfs.Handle(uri_)
            uri = uri_
        except:  #gnomevfs.InvalidURIError:
            # maybe a local path ?
            local = os.path.abspath(uri)
            if os.path.exists(local):
                uri = gnomevfs.get_uri_from_local_path(local)
            uri = gnomevfs.escape_host_and_path_string(uri)
    return uri
示例#9
0
 def add_volume(self, volume):
     uri = volume.get_activation_uri()
     if volume.handles_trash() and uri not in self.trash_dirs:
         gnomevfs. async .find_directory(near_uri_list=[gnomevfs.URI(uri)],
                                         kind=gnomevfs.DIRECTORY_KIND_TRASH,
                                         create_if_needed=False,
                                         find_if_needed=True,
                                         permissions=0777,
                                         callback=self._find_directory,
                                         user_data=uri)
示例#10
0
def vfs_open(uri, mode="r"):
    """return a file() compatible object from an uri"""
    try:
        uri = vfs_clean_uri(uri)
        uri = gnomevfs.URI(uri)
        f = gnomevfs.Handle(uri)
        return f
    except:
        log("Cannot load '%s'" % str(uri))
        return None
示例#11
0
def vfs_clean_uri(uri):
    """return an uri from an uri or a local path"""
    try:
        gnomevfs.URI(uri)
        gnomevfs.Handle(uri)
    except:  #gnomevfs.InvalidURIError:
        # maybe a local path ?
        local = os.path.abspath(uri)
        if os.path.exists(local):
            uri = gnomevfs.get_uri_from_local_path(local)
        uri = gnomevfs.escape_host_and_path_string(uri)
    return uri
示例#12
0
    def handle_drag_data_received(self, selection, target_type):
        uri_list = []
        for uri in selection.get_uris():
            uri_list.append(gnomevfs.URI(uri))

        gnomevfs. async .find_directory(near_uri_list=uri_list,
                                        kind=gnomevfs.DIRECTORY_KIND_TRASH,
                                        create_if_needed=True,
                                        find_if_needed=False,
                                        permissions=0777,
                                        callback=self._find_directory,
                                        user_data=uri_list)
示例#13
0
 def empty(self):
     source_uris = [
         gnomevfs.URI(dir.get_uri()) for dir in self.trash_dirs.values()
     ]
     gnomevfs. async .xfer(
         source_uri_list=source_uris,
         target_uri_list=[],
         xfer_options=gnomevfs.XFER_EMPTY_DIRECTORIES,
         error_mode=gnomevfs.XFER_ERROR_MODE_ABORT,
         overwrite_mode=gnomevfs.XFER_OVERWRITE_MODE_REPLACE,
         progress_update_callback=self._empty_progress,
         update_callback_data=None)
示例#14
0
 def ensure_file_info(self):
     if not self.vfs_info and not self.vfs_info_job_id:
         try:
             vfs_uri = gnomevfs.URI(self.get_uri())
             self.vfs_info_job_id = \
                     gnomevfs.async.get_file_info(vfs_uri,
                                                  self._file_info_callback,
                                                  gnomevfs.FILE_INFO_GET_MIME_TYPE)
         except (TypeError, gnomevfs.Error):
             # GnomeVFS cannot handle the URI, or it doesn't exist
             return None
     return self.vfs_info
示例#15
0
        def before_music_fetched(self, evt, music):
            print music
            prog_txt = "Converting "
            prog_txt += gnomevfs.URI(music['location']).short_path_name

            self.prog.sub_progress_text = prog_txt
            self.prog.progress_fraction = self.oper.progress

            if self.music:
                print "Fetched", self.music['cache_location']

            print "Fetching", music['location']
            self.music = music
示例#16
0
 def is_available(self, music):
     on_cache = GstMusicPool.is_available(self, music)
     uri = gnomevfs.URI(music)
     if not on_cache and \
                 uri.is_local and \
                 gnomevfs.get_mime_type (music) == "audio/x-wav":
         # convert to native filename
         s = UrlParse(unique_id)
         unique_id = self.unique_music_id(music)
         filename = s.path
         self.cache[unique_id] = GstCacheEntry(s.path, False)
         on_cache = True
     del uri
     return on_cache
示例#17
0
def vfs_rename(original, newname):
    """Rename a gnomevfs file"""

    uri = gnomevfs.URI(newname)
    dirname = uri.parent
    if dirname and not gnomevfs.exists(dirname):
        log('Creating folder: \'%s\'' % dirname)
        if not vfs_makedirs(str(dirname)):
            show_error(_('Cannot create folder!'),
                       unquote_filename(dirname.path))
            return 'cannot-create-folder'

    try:
        gnomevfs.xfer_uri(gnomevfs.URI(original), uri,
                          gnomevfs.XFER_REMOVESOURCE,
                          gnomevfs.XFER_ERROR_MODE_ABORT,
                          gnomevfs.XFER_OVERWRITE_MODE_ABORT)
    except Exception as error:
        # TODO: maybe we need a special case here. If dest folder is unwritable. Just stop.
        # or an option to stop all processing.
        show_error(_('Error while renaming file!'),
                   '%s: %s' % (beautify_uri(newname), error))
        return 'cannot-rename-file'
示例#18
0
    def __init__(self):
        VfsDirectoryBase.__init__(self)

        print 'RootDirectoryHandle()'

        self.uri = gnomevfs.URI('bluetooth:///')

        VfsCache.store(self.uri, self)

        self.basename = self.uri.path

        self.mgr = bluetool.get_manager(sys_bus)

        self.devs = self.mgr.ListDevices()
示例#19
0
    def _download(self, row):
        self.active_downloads += 1
        track = self._get_track(row)

        def started():
            self.model.set_value(row, ICON_COLUMN, icons['started'])

        def progress(rate_estimator):
            self.model.set_value(row, PROGRESS_COLUMN,
                                 100 * rate_estimator.fraction_read())
            self.model.set_value(row, PROGRESS_TIME_COLUMN,
                                 format_time(rate_estimator.remaining_time()))

        def complete(result):
            if track.status != 'aborted':
                self.model.set_value(row, PROGRESS_COLUMN, 100)
                self.model.set_value(row, ICON_COLUMN, icons['completed'])
                track.completed()
            self._download_done()

        def error(failure):
            print failure.getErrorMessage()
            self.model.set_value(row, ICON_COLUMN, icons['error'])
            track.error(failure)
            self._download_done()

        url = str('http://dl.emusic.com/dl/%(trackid)s/%(filename)s' %
                  track.tags)
        if self.base_uri is None:
            dir_uri = gnomevfs.get_uri_from_local_path(os.path.expanduser('~'))
        else:
            dir_uri = self.base_uri
        pathname = track.fill_pattern(self.path_pattern, self.strip_special)
        dir_uri = gnomevfs.URI(dir_uri).append_path(pathname)

        filename = track.fill_pattern(self.file_pattern,
                                      self.strip_special) + '.mp3'

        vfs_makedirs(dir_uri)
        openfile = open_for_write(dir_uri.append_file_name(filename))
        if self.save_cover:
            cover_dest = dir_uri.append_file_name(self.cover_filename)
            track.cover_image.add_dest(cover_dest)

        scheme, host, path, _, _, _ = urlparse(url)
        factory = ProgressDownloader(url, openfile, started, progress)
        reactor.connectTCP(host, 80, factory)
        factory.deferred.addCallback(complete).addErrback(error)
        track.start(factory)
示例#20
0
 def extract_partial(self, action, window):
     doc = window.get_active_document()
     view = window.get_active_view()
     buf = view.get_buffer()
     language = buf.get_language()
     # Only RHTML
     if language.get_id() != 'rhtml' and language.get_id() != 'haml': return
     str_uri = doc.get_uri()
     if buf.get_has_selection():
         if str_uri:
             uri = gnomevfs.URI(str_uri)
             if uri:
                 path = uri.scheme + '://' + uri.dirname
                 dialog = gtk.Dialog(
                     "Enter partial Name", window,
                     gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                     (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK,
                      gtk.RESPONSE_ACCEPT))
                 dialog.set_alternative_button_order(
                     [gtk.RESPONSE_ACCEPT, gtk.RESPONSE_CANCEL])
                 dialog.vbox.pack_start(
                     gtk.Label(
                         "Don't use _ nor extension(html.erb/erb/rhtml)"))
                 entry = gtk.Entry()
                 entry.connect('key-press-event', self.__dialog_key_press,
                               dialog)
                 dialog.vbox.pack_start(entry)
                 dialog.show_all()
                 response = dialog.run()
                 if response == gtk.RESPONSE_ACCEPT:
                     partial_name = entry.get_text()
                     doc_name = doc.get_short_name_for_display()
                     extension = self.__get_file_extension(doc_name)
                     itstart, itend = doc.get_selection_bounds()
                     partial_text = doc.get_slice(itstart, itend, True)
                     if language.get_id() == 'haml':
                         partial_render = '= render :partial => "%s"' % partial_name
                     else:
                         partial_render = '<%%= render :partial => "%s" %%>' % partial_name
                     doc.begin_user_action()
                     doc.delete(itstart, itend)
                     doc.insert_interactive(itstart, partial_render, True)
                     doc.end_user_action()
                     file_name = "%s/_%s%s" % (path, partial_name,
                                               extension)
                     self.create_file(window, file_name, partial_text)
                 dialog.destroy()
     else:
         return
示例#21
0
 def check_mime(self, fname):
     try:
         buff, fn = self.editor.get_current()
         manager = buff.get_data('languages-manager')
         if os.path.isabs(fname):
             path = fname
         else:
             path = os.path.abspath(fname)
         uri = gnomevfs.URI(path)
         mime_type = gnomevfs.get_mime_type(path) # needs ASCII filename, not URI
         if mime_type:
             language = manager.get_language_from_mime_type(mime_type)
             if language:
                 return language.get_name().lower()
     except Exception, e:
         pass
示例#22
0
    def init(self):
        self.encoders = {
            'audio/x-vorbis': self.add_oggvorbis_encoder,
            'audio/x-flac': self.add_flac_encoder,
            'audio/x-wav': self.add_wav_encoder,
            'audio/mpeg': self.add_mp3_encoder,
            'audio/x-m4a': self.add_aac_encoder,
            'audio/ogg; codecs=opus': self.add_opus_encoder,
            'gst-profile': self.add_audio_profile,
        }
        self.add_command('audiorate tolerance=10000000')
        self.add_command('audioconvert')
        self.add_command('audioresample')

        # audio resampling support
        if self.output_resample:
            self.add_command('audio/x-raw-int,rate=%d' % self.resample_rate)
            self.add_command('audioconvert')
            self.add_command('audioresample')

        if self.force_mono:
            self.add_command('audio/x-raw-int,channels=1')
            self.add_command('audioconvert')

        encoder = self.encoders[self.output_type]()
        if not encoder:
            # TODO: is this used ?
            # TODO: add proper error management when an encoder cannot be created
            show_error(
                _('Error', "Cannot create a decoder for \'%s\' format.") %
                self.output_type)
            return

        self.add_command(encoder)

        uri = gnomevfs.URI(self.output_filename)
        dirname = uri.parent
        if dirname and not gnomevfs.exists(dirname):
            log('Creating folder: \'%s\'' % dirname)
            if not vfs_makedirs(str(dirname)):
                show_error('Error',
                           _("Cannot create \'%s\' folder.") % dirname)
                return

        self.add_command(
            '%s location="%s"' %
            (gstreamer_sink, encode_filename(self.output_filename)))
示例#23
0
    def _async_progress(self, handle, info, xfer_opts):
        if info.status == gnomevfs.XFER_PROGRESS_STATUS_VFSERROR:
            uri = gnomevfs.URI(info.source_name)

            if xfer_opts & gnomevfs.XFER_REMOVESOURCE:
                msg = _("Error while moving.")
                msg2 = _(
                    'Cannot move "%s" to the trash because you do not have permissions to change it or its parent folder.'
                    % uri.short_name)
            elif xfer_opts & gnomevfs.XFER_DELETE_ITEMS:
                msg = _("Error while deleting.")
                msg2 = _(
                    '"%s" cannot be deleted because you do not have permissions to modify its parent folder.'
                ) % uri.short_name
            else:
                msg = _("Error while performing file operation.")
                msg2 = _('Cannot perform file operation %d on "%s".') % (
                    xfer_opts, uri.short_name)

            dialog = gtk.MessageDialog(type=gtk.MESSAGE_ERROR,
                                       message_format=msg)
            dialog.format_secondary_text(msg2)

            if info.files_total > 1:
                button = gtk.Button(label=_("_Skip"))
                button.show()
                dialog.add_action_widget(button, gtk.RESPONSE_REJECT)

            dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)

            button = gtk.Button(label=_("_Retry"))
            button.set_property("can-default", True)
            button.show()
            dialog.add_action_widget(button, gtk.RESPONSE_ACCEPT)
            dialog.set_default_response(gtk.RESPONSE_ACCEPT)

            response = dialog.run()
            dialog.destroy()

            if response == gtk.RESPONSE_ACCEPT:
                return gnomevfs.XFER_ERROR_ACTION_RETRY
            elif response == gtk.RESPONSE_REJECT:
                return gnomevfs.XFER_ERROR_ACTION_SKIP

            return gnomevfs.XFER_ERROR_ACTION_ABORT

        return 1
示例#24
0
 def drag_data_received_cb(self, widget, context, x, y, sel, type, time):
     uri_list = sel.data.split("\r\n")[:-1]
     print "TransferWindow received", len(uri_list), "URIs:"
     for uri in uri_list:
         path = gnomevfs.URI(uri).path
         print uri, "(" + path + ")"
         new_ft = FileTransfer(path, 'localhost', 3000,
                               self.transfer_update)
         self.active_transfers[path] = new_ft
         pb = gtk.ProgressBar()
         pb.set_text(path)
         new_ft.prog_ctrl = pb
         pb.show()
         self.table.resize(len(self.active_transfers), 1)
         self.table.attach(pb, 0, 1,
                           len(self.active_transfers) - 1,
                           len(self.active_transfers))
示例#25
0
def vfs_makedirs(uri, mode=0777):
    """Similar to os.makedirs, but with gnomevfs"""

    if isinstance(uri, basestring):
        uri = gnomevfs.URI(uri)
    path = uri.path

    # start at root
    uri = uri.resolve_relative("/")

    for folder in path.split("/"):
        if not folder:
            continue
        uri = uri.append_string(folder)
        try:
            gnomevfs.make_directory(uri, mode)
        except gnomevfs.FileExistsError:
            pass
示例#26
0
 def check_mime(self, fname):
     try:
         buff = self.editor.get_current()
         manager = buff.languages_manager
         if os.path.isabs(buff.filename):
             path = buff.filename
         else:
             path = os.path.abspath(buff.filename)
         uri = gnomevfs.URI(path)
         mime_type = gnomevfs.get_mime_type(path) # needs ASCII filename, not URI
         if mime_type:
             language = manager.get_language_from_mime_type(mime_type)
             if language:
                 return language.get_name().lower()
     except RuntimeError:
         pass
         # The file was not found
     except Exception, e:
         import traceback
         traceback.print_exc()
示例#27
0
def vfs_makedirs(path_to_create):
    """Similar to os.makedirs, but with gnomevfs"""

    uri = gnomevfs.URI(path_to_create)
    path = uri.path

    # start at root
    uri = uri.resolve_relative("/")

    for folder in path.split("/"):
        if not folder:
            continue
        uri = uri.append_string(folder)
        try:
            gnomevfs.make_directory(uri, 0777)
        except gnomevfs.FileExistsError:
            pass
        except:
            return False
    return True
    def is_available(self, music):
        on_cache = GstMusicPool.is_available(self, music)
        uri = gnomevfs.URI(music)

        # XXX: when there is no gnomevfdssrc we have a problem because
        #      we are using URI's
        unique_id = self.unique_music_id(music)
        is_pcm = audio.IsWavPcm(self.get_source(unique_id))

        if not on_cache and \
                    uri.is_local and \
                    gnomevfs.get_mime_type (music) == "audio/x-wav" and \
                    operations.syncOperation (is_pcm).id == operations.SUCCESSFUL:

            # convert to native filename
            filename = urlutil.get_path(unique_id)
            self.cache[unique_id] = GstCacheEntry(filename, False)
            on_cache = True
        del uri

        return on_cache
示例#29
0
    def __stat(self, file):
        self.cwd = gnomevfs.URI(os.getcwd())
        if str(self.cwd)[-1] != '/': self.cwd = self.cwd.append_string('/')
        file_uri = self.cwd.resolve_relative(file)
        try:
            file_info = gnomevfs.get_file_info(
                file_uri, gnomevfs.FILE_INFO_GET_MIME_TYPE)
        except:

            class file_info:
                name = file
                file_type = ""
                file_size = 0
                mime = ""
#            print 'Name:      ', file_info.name

        file_type = '(none)'
        try:
            file_type = ('unknown', 'regular', 'directory', 'fifo', 'socket',
                         'chardev', 'blockdev', 'symlink')[file_info.type]
        except:
            pass
        #            print 'Type:      ', file_type

        file_size = '(unknown)'
        try:
            file_size = file_info.size
        except:
            file_size = 0


#            print 'Size:      ', file_size

        mime_type = '(none)'
        try:
            mime_type = file_info.mime_type
        except:
            pass
        #print 'Mime type: ', mime_type
        return file_uri, file_info.name, file_type, file_size, mime_type
示例#30
0
    def drag_data_received_cb(self, widget, context, x, y, sel, type, time):
        uri_list = sel.data.split("\r\n")[:-1]
        print "TransferWindow received", len(uri_list), "URIs:"
        for uri in uri_list:
            path = gnomevfs.URI(uri).path
            print uri, "(" + path + ")"
            base = os.path.basename(path)
            dir = os.path.dirname(path)
            print "dir:", dir
            print "base:", base

            pb = gtk.ProgressBar()
            pb.show()
            self.table.resize(len(self.active_transfers) + 1, 1)
            self.table.attach(pb, 0, 1, len(self.active_transfers),
                              len(self.active_transfers) + 1)
            pb.set_text("Initializing...")

            new_ft = FileTransfer(dir, base, 'localhost', 3000,
                                  self.transfer_update)
            self.active_transfers[new_ft] = (new_ft, pb)
            new_ft.start()