Ejemplo n.º 1
0
    def check_mime(self, buff):
        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 is not None:
                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)
Ejemplo n.º 2
0
    def do_reload(self):
        self._places = PlacesManager.static_places[:]
        try:
            for line in file(self._bookmarks_path):
                line = line.strip()

                if " " in line:
                    uri, name = line.split(" ", 1)
                else:
                    uri = line
                    path = urllib.splittype(uri)[1]
                    name = urllib.unquote(os.path.split(path)[1])

                try:
                    if not gnomevfs.exists(uri):
                        continue
                # Protect against a broken bookmarks file
                except TypeError:
                    continue

                mime = gnomevfs.get_mime_type(uri) or ""
                icon = gnome.ui.icon_lookup(icon_theme, thumb_factory, uri, mime, 0)[0]

                self._places.append((uri, name, mime, icon))
        except IOError, err:
            print "Error loading GTK bookmarks:", err
Ejemplo n.º 3
0
    def getMime(self, path):
        """
        @summary: Gets a tuple with mime type and mime description.
        @param path: Path to extract mime.
        @return: Tuple with two string, 
            the first with mime name and the second with mime description.  
        """
        # Check if path exist
        if not os.path.exists(path):
            return ("", "")
 
        mimeType = ""
        mimeDescription = ""
 
        if (GNOME):
            # get mime
            mimeType = gnomevfs.get_mime_type(path)
            mimeDescription = gnomevfs.mime_get_description(mimeType)
        elif (WINDOWS):
            info = self.__getWindowsInfo__(path)
            file, ext = os.path.splitext(path)
            mimeType = ext
            mimeDescription = info[4]
            if (mimeDescription == ""):
                mimeDescription = ("%s %s" % (_("File"), ext))
                
        return (mimeType, mimeDescription)
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def getSize(self, path):
        """
        @summary: Gets a tuple with size and size description with its units (bytes, Kbytes...)
        @param path: Path to calculate size.
        @return: Tuple with size and size description  
        """
        # Check if path exist
        if not os.path.exists(path):
            __log__.warning("Path does not exist. %s" % path)
            return (0, "")        
        if (os.path.isdir(path)):
            return (0, "")
        
        try:
            size = long(os.path.getsize(path))
        except:
            size = 0
        sizeDescription = ""
 
        
        if (GNOME):
            # get mime
            mime_type = gnomevfs.get_mime_type(path)
     
            uri = "file://%s" % urllib.pathname2url(path)
            fileInfo = gnomevfs.get_file_info(uri)
            
            if ((fileInfo.valid_fields & gnomevfs.FILE_INFO_FIELDS_SIZE) != 0):
                    size = fileInfo.size
                    sizeDescription = gnomevfs.format_file_size_for_display(size)
        else:
            sizeDescription = self.__getSizeDescription__(size) 
                
        return (size, sizeDescription)
	def filter_location (self, location):
	
		try:
			mime = gnomevfs.get_mime_type (location)
		except RuntimeError:
			return None
			
		if mime == "text/xml":
			if not os.path.exists (location):
				s = urlparse (location)
				scheme = s[0]
				# TODO: handle more urls
				if scheme == "file":
					location = urllib.unquote (s[2])
				else:
					return None
			hints_list = []
			p = xspf.Playlist()
			p.parse (location)
			for t in p.tracks:
				if t.location is None:
					continue
				r = {'location': t.location}
				if t.title is not None:
					r['title'] = t.title
				if t.creator is not None:
					r['artist'] = t.creator
				hints_list.append (r)
			return hints_list

		return None
 def filter_location (self, location):
     assert isinstance (location, StringType), "Location cannot be null"
     # TypeError is thrown when there is a problem with the supplied
     # location. See http://bugzilla.ubuntu.com/show_bug.cgi?id=11447
     assert "\0" not in location, "Malformed string ocation: %s" % location
     
     try:
         mime = gnomevfs.get_mime_type (location)
     except RuntimeError:
         # RuntimeError is thrown when there is an error reading the file
         return None
         
     if mime != "x-directory/normal":
         return None
         
     s = urlparse (location)
     scheme = s[0]
     # TODO: handle more urls
     if scheme == "file":
         location = urllib.unquote (s[2])
     elif scheme == "":
         location = s[2]
     else:
         return None
     hints_list = []
     for location in glob (os.path.join (location, "*")):
         hints_list.append ({"location": location})
     return hints_list
Ejemplo n.º 8
0
 def get_mimetype(self):
     self._get_file_info()
     try:
         return self.fileInfo.mime_type
     except ValueError:
         # Why is gnomevfs so stupid and must I do this for local URIs??
         return gnomevfs.get_mime_type(self.get_text_uri())
Ejemplo n.º 9
0
    def filter_location(self, location):

        try:
            mime = gnomevfs.get_mime_type(location)
        except RuntimeError:
            return None

        if mime == "text/xml":
            if not os.path.exists(location):
                s = urlparse(location)
                scheme = s[0]
                # TODO: handle more urls
                if scheme == "file":
                    location = urllib.unquote(s[2])
                else:
                    return None
            hints_list = []
            p = xspf.Playlist()
            p.parse(location)
            for t in p.tracks:
                if t.location is None:
                    continue
                r = {'location': t.location}
                if t.title is not None:
                    r['title'] = t.title
                if t.creator is not None:
                    r['artist'] = t.creator
                hints_list.append(r)
            return hints_list

        return None
Ejemplo n.º 10
0
 def on_treeview_row_activated(self, treeview, path, column):
     (model, iter) = treeview.get_selection().get_selected()
     filename = model.get(iter, 1)[0]
     application = gnomevfs.mime_get_default_application(
         gnomevfs.get_mime_type(gnomevfs.make_uri_from_input(filename)))
     if application:
         subprocess.Popen(str.split(application[2]) + [filename])
Ejemplo n.º 11
0
 def __set_language(self, file_uri):
     lm = gtksourceview2.LanguageManager()
     lang_id = Files.get_language_from_mime(gnomevfs.get_mime_type(file_uri))
     
     if lang_id != None:
         language = lm.get_language(lang_id)
         self.snippets.load(lang_id)
         self.buffer.set_language(language)
Ejemplo n.º 12
0
def create_thumbnail_via_gnome(uri):
    mimetype = gnomevfs.get_mime_type(uri)
    thumbFactory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_NORMAL)
    if thumbFactory.can_thumbnail(uri, mimetype,0):
        thumbnail = thumbFactory.generate_thumbnail(uri, mimetype)
        print "here"
        if thumbnail != None:
            thumbFactory.save_thumbnail(thumbnail, uri, 0)
            print "passed"
Ejemplo n.º 13
0
	def __init__(self, cur_dir=None, file_types=[],
				show_hidden=False, root=''):
		gtk.ListStore.__init__(self, gtk.gdk.Pixbuf, str)

		self.root = root

		if len(file_types) == 1 and file_types[0] == '*': file_types = []

		if not cur_dir:
			self.dirname = os.path.expanduser('~')
		else:
			self.dirname = os.path.abspath(cur_dir)
		if not os.path.lexists(self.dirname):
			self.dirname = os.path.expanduser('~')

		self.files = []
		self.dirs = []
		for file in os.listdir(self.dirname):
			if file[0] == '.' and not show_hidden:
				continue
			else:
				if os.path.isdir(os.path.join(self.dirname, file)):
					self.dirs.append(file)
				else:
					ext = os.path.splitext(file)[1]
					if ext: ext = ext[1:]
					if file_types and not ext in file_types:
						continue
					self.files.append(file)

		self.files.sort()
		self.dirs.sort()

		sorted_files = []
		for file in self.files:
			mime = gnomevfs.get_mime_type(os.path.join(self.dirname, file))
			sorted_files.append((get_image(mime), file))
		self.files = sorted_files

		sorted_dirs = []
		for dir in self.dirs:
			sorted_dirs.append((FOLDER_ICON, dir))
		self.dirs = sorted_dirs

		self.files = self.dirs + self.files
		if self.root:
			if self.dirname == root:
				pass
			else:
				self.files = [(FOLDER_ICON, '..'), ] + self.files
		else:
			if not self.dirname == os.path.abspath(os.path.join(self.dirname, '..')):
				self.files = [(FOLDER_ICON, '..'), ] + self.files
		for item in self.files:
			icon, text = item
			self.append((icon, text))
Ejemplo n.º 14
0
def generate_thumbnail(factory, uri):

    mime = gnomevfs.get_mime_type(uri)

    if factory.can_thumbnail(uri, mime, 0):
        thumbnail = factory.generate_thumbnail(uri, mime)
        if thumbnail != None:
            factory.save_thumbnail(thumbnail, uri, 0) 
            return thumbnail
    
    return None
Ejemplo n.º 15
0
	def get_icon( self, path ):
		if not os.path.exists(path):
			return gtk.STOCK_FILE

		#check if it is a special folder
		if path in self.special_folders:
			return self.special_folders[path]

		#get mime type
		mime_type = gnomevfs.get_mime_type( gnomevfs.escape_path_string( path ) )
		mime_type = mime_type.replace( '/', '-' )

		#search in the cache
		if mime_type in self.cache:
			return self.cache[mime_type]

		#print "path: " + path
		#print "mime: " + mime_type

		#try gnome mime
		items = mime_type.split('-')
		for aux in xrange(len(items)-1):
			icon_name = "gnome-mime-" + '-'.join(items[:len(items)-aux])
			if icon_name in self.all_icons:
				#print "icon: " + icon_name
				self.cache[mime_type] = icon_name
				return icon_name

		#try folder
		if os.path.isdir( path ):
			icon_name = 'folder'
			if icon_name in self.all_icons:
				#print "icon: " + icon_name
				self.cache[mime_type] = icon_name
				return icon_name

			#print "icon: " + icon_name
			icon_name = gtk.STOCK_DIRECTORY
			self.cache[mime_type] = icon_name
			return icon_name

		#try simple mime
		for aux in xrange(len(items)-1):
			icon_name = '-'.join(items[:len(items)-aux])
			if icon_name in self.all_icons:
				#print "icon: " + icon_name
				self.cache[mime_type] = icon_name
				return icon_name

		#file icon
		icon_name = gtk.STOCK_FILE
		self.cache[mime_type] = icon_name
		return icon_name
Ejemplo n.º 16
0
def get_mimetype(data, filename):
    """Try to get MIME type from data."""
    try:
        import gnomevfs
    except ImportError:
        from mimetypes import guess_type
        if filename:
            return guess_type(filename)[0]
    else:
        if filename:
            return gnomevfs.get_mime_type(os.path.abspath(filename))
        return gnomevfs.get_mime_type_for_data(data)
Ejemplo n.º 17
0
def get_mimetype(data, filename):
    """Try to get MIME type from data."""
    try:
        import gnomevfs
    except ImportError:
        from mimetypes import guess_type
        if filename:
            return guess_type(filename)[0]
    else:
        if filename:
            return gnomevfs.get_mime_type(os.path.abspath(filename))
        return gnomevfs.get_mime_type_for_data(data)
Ejemplo n.º 18
0
def is_file_media(filename):
    """Returns true if this is a media file (audio or video) and false if it is any other type of file"""
    if is_kde():
        mime_magic = kio.KMimeMagic()
        mimetype = str(mime_magic.findFileType(filename).mimeType())
    elif HAS_GNOMEVFS:
        mimetype = gnomevfs.get_mime_type(urllib.quote(filename))
    else:
        return False
    valid_mimes = ['video', 'audio', 'mp4', 'realmedia', 'm4v', 'mov']
    for mime in valid_mimes:
        if mime in mimetype:
            return True
    return False
Ejemplo n.º 19
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
Ejemplo n.º 20
0
def get_meta_info(filename):
	try:
		file_mimetype = gnomevfs.get_mime_type(filename)
	except:
		return False
	
	ret = {}
	ret['mime'] = file_mimetype
	ret['default_app'] = gnomevfs.mime_get_default_application(file_mimetype)
	ret['other_apps'] = gnomevfs.mime_get_all_applications(file_mimetype)
	if len(ret['other_apps']) > 0:
		del ret['other_apps'][0]
	ret ['description'] = gnomevfs.mime_get_description(file_mimetype)
	return ret
Ejemplo n.º 21
0
    def __getIconNameGnome__(self, path):
        """
        @summary: Gets an icon name from path, matching with its mime.
        @param path: Path to extract icon name.
        @return: string with icon name 
        """
        
        # Check if path exist
        if not os.path.exists(path):
            __log__.warning("Path %s does not exist." % path)
            return gtk.STOCK_DIALOG_AUTHENTICATION
 
        # get mime
        mime_type = gnomevfs.get_mime_type(path).replace('/', '-')
 
        # check if mime exists in the cache
        if mime_type in self.cache:
            return self.cache[mime_type]
 
        # try to get a gnome mime
        items = mime_type.split('-')
        for aux in xrange(len(items) - 1):
            icon_name = "gnome-mime-" + '-'.join(items[:len(items) - aux])
            if icon_name in self.icons:
                self.cache[mime_type] = icon_name
                return icon_name
 
        # check and try to get a folder
        if os.path.isdir(path):
            icon_name = 'folder'
            if icon_name in self.icons:
                self.cache[mime_type] = icon_name
                return icon_name
 
            icon_name = gtk.STOCK_DIRECTORY
            self.cache[mime_type] = icon_name
            return icon_name
 
        # try to get a simple mime
        for aux in xrange(len(items) - 1):
            icon_name = '-'.join(items[:len(items) - aux])
            if icon_name in self.icons:
                self.cache[mime_type] = icon_name
                return icon_name
 
        # if there isn't a mime for the path, get file icon
        __log__.debug("Icon name of %s not found." % path)
        icon_name = gtk.STOCK_FILE
        self.cache[mime_type] = icon_name
        return icon_name
Ejemplo n.º 22
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
			unique_id = self.unique_music_id (music)
			s = urlparse (unique_id)
			filename = s[2]
			self.cache[unique_id] = GstCacheEntry (filename, False)
			on_cache = True
		del uri
		return on_cache
Ejemplo n.º 23
0
def is_file_media(filename):
	"""Returns true if this is a media file (audio or video) and false if it is any other type of file"""
	if is_kde():
		mime_magic = kio.KMimeMagic()
		mimetype = str(mime_magic.findFileType(filename).mimeType())
	elif HAS_GNOMEVFS:
		mimetype = gnomevfs.get_mime_type(urllib.quote(filename))
	else:
		return False
	valid_mimes=['video','audio','mp4','realmedia','m4v','mov']
	for mime in valid_mimes:
		if mime in mimetype:
			return True
	return False
Ejemplo n.º 24
0
    def get_file_pixbuf(self, url, tam=48):
        mime = gnomevfs.get_mime_type(url)
        try:
            info = gnomevfs.get_file_info(url)
            icon_type, result = gnome.ui.icon_lookup(self.iconTheme, self.thumbFactory,
                                                url, "", self.icon_flags, mime, info)
        except:
            print "Error loading icon"
            icon_type = None

        try:
            pixbuf = self.iconTheme.load_icon(icon_type, tam, 0)
        except:
            return None
        return pixbuf
    def get_file_pixbuf(self, url, tam=48):
        try:
            mime = gnomevfs.get_mime_type(url)
            info = gnomevfs.get_file_info(url)
            icon_type, result = gnome.ui.icon_lookup(self.iconTheme, self.thumbFactory,
                                                url, "", self.icon_flags, mime, info)
        except:
            print "Error loading icon"
            icon_type = None

        try:
            pixbuf = self.iconTheme.load_icon(icon_type, tam, 0)
        except:
            return None
        return pixbuf
Ejemplo n.º 26
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
    def filter_location (self, location):
        
        try:
            mime = gnomevfs.get_mime_type (location)
        except RuntimeError:
            return
            
        if mime == "audio/x-mpegurl" or mime == "audio/x-scpls":
            hints_list = []
            p = plparser.Parser()
            p.connect("entry", self.__on_pl_entry, hints_list)
            p.parse(location, False)

            return hints_list
            
        return
Ejemplo n.º 28
0
    def filter_location(self, location):

        try:
            mime = gnomevfs.get_mime_type(location)
        except RuntimeError:
            return

        if mime == "audio/x-mpegurl" or mime == "audio/x-scpls":
            hints_list = []
            p = plparser.Parser()
            p.connect("entry", self.__on_pl_entry, hints_list)
            p.parse(location, False)

            return hints_list

        return
Ejemplo n.º 29
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
Ejemplo n.º 30
0
def desktop_has_file_handler(filename):
	"""Returns true if the desktop has a file handler for this
		filetype."""
	if is_kde():
		# If KDE can't handle the file, we'll use kfmclient exec to run the file,
		# and KDE will show a dialog asking for the program
		# to use anyway.
		return True
	else:
		if HAS_GNOMEVFS:
			# Otherwise, use GNOMEVFS to find the appropriate handler
			handler = gnomevfs.mime_get_default_application(gnomevfs.get_mime_type(urllib.quote(str(filename)))) #PA fix #Nerdist fix, urllib prefers strings over unicode
			if handler is not None:
				return True
			return False
		else: #FIXME: olpc doesn't know what the f**k... pretend yes and let error get caught later
			return True
    def getIcon( self, path ):
        if not os.path.exists(path):
            return gtk.STOCK_FILE

        #get mime type
        mime_type = gnomevfs.get_mime_type( path ).replace( '/', '-' )

        #search in the cache
        if mime_type in self.cache:
            return self.cache[mime_type]

        #try gnome mime
        items = mime_type.split('-')
        for aux in xrange(len(items)-1):
            icon_name = "gnome-mime-" + '-'.join(items[:len(items)-aux])
            if icon_name in self.all_icons:
                #print "icon: " + icon_name
                self.cache[mime_type] = icon_name
                return icon_name

        #try folder
        if os.path.isdir(path):
            icon_name = 'folder'
            if icon_name in self.all_icons:
                #print "icon: " + icon_name
                self.cache[mime_type] = icon_name
                return icon_name

            #print "icon: " + icon_name
            icon_name = gtk.STOCK_DIRECTORY
            self.cache[mime_type] = icon_name
            return icon_name

        #try simple mime
        for aux in xrange(len(items)-1):
            icon_name = '-'.join(items[:len(items)-aux])
            if icon_name in self.all_icons:
                #print "icon: " + icon_name
                self.cache[mime_type] = icon_name
                return icon_name

        #file icon
        icon_name = gtk.STOCK_FILE
        self.cache[mime_type] = icon_name
        return icon_name
    def getIconPixbuf(self, path):
        # if path is wrong
        if not os.path.exists(path):
            return self.icon_theme_icons.load_icon(gtk.STOCK_FILE,gtk.ICON_SIZE_MENU,0)


        #get mime type
        mime_type = gnomevfs.get_mime_type( path ).replace( '/', '-' )

        #search in the cache
        if mime_type in self.cache:
            #print self.cache[mime_type]
            return self.cache[mime_type]

        #try gnome mime
        items = mime_type.split('-')
        for aux in xrange(len(items)-1):
            icon_name = "gnome-mime-" + '-'.join(items[:len(items)-aux])
            if icon_name in self.all_icons:
#                print "icon: " + icon_name
                self.cache[mime_type] = self.icon_theme_icons.load_icon(icon_name,gtk.ICON_SIZE_MENU,0)

                return self.cache[mime_type]
        #try folder
        if os.path.isdir(path):
            icon_name = 'folder'
            self.cache[mime_type] = self.icon_theme_icons.load_icon(icon_name,gtk.ICON_SIZE_MENU,0)
            return self.cache[mime_type]

        #try simple mime
        for aux in xrange(len(items)-1):
            icon_name = '-'.join(items[:len(items)-aux])
            if icon_name in self.all_icons:
                #print "icon: " + icon_name
                self.cache[mime_type] = self.icon_theme_icons.load_icon(icon_name,gtk.ICON_SIZE_MENU,0)
                return self.cache[mime_type]

        #file icon
#        icon = gtk.Image()
#        icon.set_from_stock(gtk.STOCK_FILE, gtk.ICON_SIZE_MENU)
        icon_name = gtk.STOCK_FILE
        self.cache[mime_type] = self.icon_theme_icons.load_icon(icon_name,gtk.ICON_SIZE_MENU,0)
        
        return self.cache[mime_type]
Ejemplo n.º 33
0
def get_icon_for_uri(uri, icon_size=48):
	""" 
	Returns a pixbuf representing the file at
	the URI generally (mime-type based)
	
	@param icon_size: a pixel size of the icon 
	@type icon_size: an integer object.  
	 
	""" 
	from gtk import icon_theme_get_default, ICON_LOOKUP_USE_BUILTIN
	from gnomevfs import get_mime_type
	from gnome.ui import ThumbnailFactory, icon_lookup 

	mtype = get_mime_type(uri)
	icon_theme = icon_theme_get_default()
	thumb_factory = ThumbnailFactory(16)
	icon_name, num = icon_lookup(icon_theme, thumb_factory,  file_uri=uri, custom_icon="")
	icon = icon_theme.load_icon(icon_name, icon_size, ICON_LOOKUP_USE_BUILTIN)
	return icon
Ejemplo n.º 34
0
    def save_file(self, document_manager, document):

        self.actualLanguage = Files.get_language_from_mime(gnomevfs.get_mime_type(document.file_uri))

        #
        #   Why this codes three lines dont work, why they always return None ???
        #
        #print document.view.buffer.get_language()
        #print document_manager.get_active_document().view.buffer.get_language()
        #print self.document_manager.get_nth_page(self.document_manager.get_current_page()).view.buffer.get_language()
        #self.actualBuffer = document_manager.get_active_document().view.buffer

        # self.actualBuffer = self.document_manager.get_nth_page(self.document_manager.get_current_page()).view.buffer
        #if self.actualBuffer.get_language() != None:
        #    self.actualLanguage = self.actualBuffer.get_language().get_name().lower()
        #else:
        #    self.actualLanguage = None

        self.__put_snippets()
Ejemplo n.º 35
0
def desktop_has_file_handler(filename):
    """Returns true if the desktop has a file handler for this
		filetype."""
    if is_kde():
        # If KDE can't handle the file, we'll use kfmclient exec to run the file,
        # and KDE will show a dialog asking for the program
        # to use anyway.
        return True
    else:
        if HAS_GNOMEVFS:
            # Otherwise, use GNOMEVFS to find the appropriate handler
            handler = gnomevfs.mime_get_default_application(
                gnomevfs.get_mime_type(urllib.quote(str(filename)))
            )  #PA fix #Nerdist fix, urllib prefers strings over unicode
            if handler is not None:
                return True
            return False
        else:  #FIXME: olpc doesn't know what the f**k... pretend yes and let error get caught later
            return True
Ejemplo n.º 36
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()
Ejemplo n.º 37
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()
Ejemplo n.º 38
0
    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
Ejemplo n.º 39
0
    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
Ejemplo n.º 40
0
 def add_bookmark (self, name, url, connection_name, old_name=None):
     if url.startswith("file://") == True:
         mime = gnomevfs.get_mime_type(url)
         try:
             info = gnomevfs.get_file_info(url)
             icon, result = gnome.ui.icon_lookup(self.iconTheme, self.thumbFactory,
                                                 url, "", self.icon_flags, mime, info)
         except:
             icon = "text-x-generic"
     else:
         if "movistar.es" in url :
             icon = None
         else:
             icon = "stock_internet"
         
     if old_name == None:
         btime = time.time()
         self.conf["bookmarks"][name]=[url, connection_name, icon, btime]
     else:
         tmp = [url, connection_name, icon, self.get_bookmark_timestamp(old_name)]
         self.conf["bookmarks"].pop(old_name)
         self.conf["bookmarks"][name] = tmp
Ejemplo n.º 41
0
def get_play_command_for(filename):
	known_players={ 'totem':'--enqueue',
					'xine':'--enqueue',
					'mplayer': '-enqueue',
					'banshee': '--enqueue'}

	if is_kde():
		try:
			mime_magic = kio.KMimeMagic()
			mimetype = str(mime_magic.findFileType(filename).mimeType())
			#mimetype = str(kio.KMimeType.findByPath(filename).defaultMimeType())
			service = kio.KServiceTypeProfile.preferredService(mimetype,"Application")
			if service is None: #no service, so we use kfmclient and kde should launch a helper window
				logging.info("unknown type, using kfmclient")
				return "kfmclient exec "
			full_qual_prog = str(service.exec_()).replace("%U","").strip()
		except:
			logging.info("error getting type, using kfmclient")
			return "kfmclient exec "
	else: #GNOME -- notice how short and sweet this is in comparison :P
		if HAS_GNOMEVFS:
			try:
				mimetype = gnomevfs.get_mime_type(urllib.quote(filename)) #fix for penny arcade filenames
				full_qual_prog = gnomevfs.mime_get_default_application(mimetype)[2]
			except:
				logging.info("unknown type, using gnome-open")
				return "gnome-open "
		else:
			# :(
			return "echo "
	try:
		path, program = os.path.split(full_qual_prog)
	except:
		program = full_qual_prog

	if known_players.has_key(program):
		return full_qual_prog+" "+known_players[program]
	return full_qual_prog
Ejemplo n.º 42
0
 def check_mime(self, fname):
     buffer, text, model = self.wins[fname]
     manager = buffer.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:
             buffer.set_highlight(True)
             buffer.set_language(language)
         else:
             print 'No language found for mime type "%s"' % mime_type
             buffer.set_highlight(False)
     else:
         print 'Couldn\'t get mime type for file "%s"' % fname
         buffer.set_highlight(False)
     buffer.place_cursor(buffer.get_start_iter())
     model = self.list_classes(fname=fname)
     buffer.set_data("save", False)
Ejemplo n.º 43
0
##  any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.

import gnome.ui
import gnomevfs
import time
import os
import os.path
import sys

dir = sys.argv[1]

thumbFactory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_LARGE)
for subdir, dirs, files in os.walk(dir):
	for file in files:
		path = os.path.join(subdir, file)
		uri = gnomevfs.get_uri_from_local_path(path)
		mime = gnomevfs.get_mime_type(path)
		mtime = int(os.path.getmtime(path))
		if not os.path.exists(gnome.ui.thumbnail_path_for_uri(uri, gnome.ui.THUMBNAIL_SIZE_LARGE)) and thumbFactory.can_thumbnail(uri, mime, 0):
			print "Generating for %s" % uri
			thumbnail = thumbFactory.generate_thumbnail(uri, mime)
			if thumbnail is not None:
				thumbFactory.save_thumbnail(thumbnail, uri, mtime)
		else:
			print "Skip %s" % uri
Ejemplo n.º 44
0
 def get_mime_type(path):
     return gnomevfs.get_mime_type(gnomevfs.get_uri_from_local_path(path))
Ejemplo n.º 45
0
##  Public License as published by the Free Software Foundation;
##  either version 2, or (at your option)
##  any later version.
##  
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.

import gnome.ui
import gnomevfs
import time
import os
import os.path
import sys

dir=sys.argv[1]

for subdir, dirs, files in os.walk(dir):
 for file in files:
  uri=gnomevfs.get_uri_from_local_path(subdir+"/"+file)  
  mime=gnomevfs.get_mime_type(subdir+"/"+file)
  mtime=int(time.strftime("%s",time.localtime(os.path.getmtime(subdir+"/"+file))))
  thumbFactory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_LARGE)
  if not os.path.exists(gnome.ui.thumbnail_path_for_uri(uri, gnome.ui.THUMBNAIL_SIZE_LARGE)) and thumbFactory.can_thumbnail(uri ,mime, 0):
      print "Generating for "+uri
      thumbnail=thumbFactory.generate_thumbnail(uri, mime)
      if thumbnail != None:                    
          thumbFactory.save_thumbnail(thumbnail, uri, mtime) 
  else:
      print "Skip "+uri
Ejemplo n.º 46
0
def open_file_watch(f):
    """ Open a file with the correct application (mime). """
    mime_type = gnomevfs.get_mime_type(f)
    application = gnomevfs.mime_get_default_application(mime_type)
    os.system(application[2] + " \"" + f + "\" &")
Ejemplo n.º 47
0
	def on_treeview_row_activated (self, treeview, path, column):
		(model, iter) = treeview.get_selection ().get_selected ()
		filename = model.get (iter, 1)[0]
		application = gnomevfs.mime_get_default_application (gnomevfs.get_mime_type(gnomevfs.make_uri_from_input(filename)))
		if application:
			subprocess.Popen (str.split (application[2]) + [filename])
Ejemplo n.º 48
0
def get_type(file):
    """Return the mime type of the specified file."""
    try:
        return get_mime_type(file)
    except:
        return _('unknown')
Ejemplo n.º 49
0
    def __init__(self,
                 cur_dir=None,
                 file_types=[],
                 show_hidden=False,
                 root=''):
        gtk.ListStore.__init__(self, gtk.gdk.Pixbuf, str)

        self.root = root

        if len(file_types) == 1 and file_types[0] == '*': file_types = []

        if not cur_dir:
            self.dirname = os.path.expanduser('~')
        else:
            self.dirname = os.path.abspath(cur_dir)
        if not os.path.lexists(self.dirname):
            self.dirname = os.path.expanduser('~')

        self.files = []
        self.dirs = []
        for file in os.listdir(self.dirname):
            if file[0] == '.' and not show_hidden:
                continue
            else:
                if os.path.isdir(os.path.join(self.dirname, file)):
                    self.dirs.append(file)
                else:
                    ext = os.path.splitext(file)[1]
                    if ext: ext = ext[1:]
                    if file_types and not ext in file_types:
                        continue
                    self.files.append(file)

        self.files.sort()
        self.dirs.sort()

        sorted_files = []
        for file in self.files:
            mime = gnomevfs.get_mime_type(os.path.join(self.dirname, file))
            sorted_files.append((get_image(mime), file))
        self.files = sorted_files

        sorted_dirs = []
        for dir in self.dirs:
            sorted_dirs.append((FOLDER_ICON, dir))
        self.dirs = sorted_dirs

        self.files = self.dirs + self.files
        if self.root:
            if self.dirname == root:
                pass
            else:
                self.files = [
                    (FOLDER_ICON, '..'),
                ] + self.files
        else:
            if not self.dirname == os.path.abspath(
                    os.path.join(self.dirname, '..')):
                self.files = [
                    (FOLDER_ICON, '..'),
                ] + self.files
        for item in self.files:
            icon, text = item
            self.append((icon, text))
Ejemplo n.º 50
0
def get_mime_type(path):
    return gnomevfs.get_mime_type(path) if gnomevfs else gtk.STOCK_FILE
Ejemplo n.º 51
0
 def get_mime_type(self):
     return gnomevfs.get_mime_type(gnomevfs.make_uri_from_input(self.path))
Ejemplo n.º 52
0
 def on_current_file_button_clicked(self, widget):
     application = gnomevfs.mime_get_default_application(
         gnomevfs.get_mime_type(gnomevfs.make_uri_from_input(
             self.filename)))
     if application:
         subprocess.Popen(str.split(application[2]) + [self.filename])