def get_mime_type(self, path=None, data=None): """Get mime type for specified path""" result = None if path is not None: # detect content type based on file name result = gio.content_type_guess(filename=path) elif data is not None: # detect content type based on data result = gio.content_type_guess(data=data) return result
def capture_end_execute_panel(capture, exit_code, panel, view, output_type): panel['stop'].set_sensitive(False) if output_type in ('new-document','replace-document'): doc = view.get_buffer() start = doc.get_start_iter() end = start.copy() end.forward_chars(300) mtype = gio.content_type_guess(data=doc.get_text(start, end)) lmanager = cedit.get_language_manager() language = lmanager.guess_language(doc.get_uri(), mtype) if language is not None: doc.set_language(language) view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gdk.Cursor(gdk.XTERM)) view.set_cursor_visible(True) view.set_editable(True) if exit_code == 0: panel.write("\n" + _("Done.") + "\n", panel.italic_tag) else: panel.write("\n" + _("Exited") + ":", panel.italic_tag) panel.write(" %d\n" % exit_code, panel.bold_tag)
def on_drag_data_received(self, view, context, x, y, data, info, timestamp): if not (gtk.targets_include_uri(context.targets) and data.data and self.in_bounds(x, y)): return uris = drop_get_uris(data) uris.reverse() stop = False for uri in uris: try: mime = gio.content_type_guess(uri) except: mime = None if not mime: continue snippets = Library().from_drop_target(mime, self.language_id) if snippets: stop = True self.apply_uri_snippet(snippets[0], mime, uri) if stop: context.finish(True, False, timestamp) view.stop_emission('drag-data-received') view.get_toplevel().present() view.grab_focus()
def on_entry_drop_targets_drag_data_received(self, entry, context, x, y, selection_data, info, timestamp): if not gtk.targets_include_uri(context.targets): return uris = drop_get_uris(selection_data) if not uris: return if entry.get_text(): mimes = [entry.get_text()] else: mimes = [] for uri in uris: try: mime = gio.content_type_guess(uri) except: mime = None if mime: mimes.append(mime) entry.set_text(', '.join(mimes)) self.on_entry_drop_targets_focus_out(entry, None) context.finish(True, False, timestamp) entry.stop_emission('drag_data_received')
def guess(filepath, use_contents=True): data, is_file = None, False mime_type = APP_OCTET_STREAM #try: st = os.stat(filepath) st_mode = st.st_mode if stat.S_ISDIR(st_mode): mime_type = INODE_DIR elif stat.S_ISCHR(st_mode): mime_type = INODE_CHAR elif stat.S_ISBLK(st_mode): mime_type = INODE_BLOCK elif stat.S_ISFIFO(st_mode): mime_type = INODE_FIFO elif stat.S_ISLNK(st_mode): mime_type = INODE_SYMLINK elif stat.S_ISSOCK(st_mode): mime_type = INODE_SOCKET elif stat.S_ISREG(st_mode): is_file = True #except: #pass if is_file: if use_contents: try: with open(filepath, 'rb') as fp: data = fp.read(MIME_MAGIC_MAX_BUF_SIZE) except: pass # Removed in favor of gio, this was way too sloooow ! #mime_type = xdg.Mime.get_type(filepath) mime_type = gio.content_type_guess(filepath, data, False) return mime_type
def guess(filepath, use_contents=True): data, is_file = None, False mime_type = APP_OCTET_STREAM try: st = os.stat(filepath) st_mode = st.st_mode if stat.S_ISDIR(st_mode): mime_type = INODE_DIR elif stat.S_ISCHR(st_mode): mime_type = INODE_CHAR elif stat.S_ISBLK(st_mode): mime_type = INODE_BLOCK elif stat.S_ISFIFO(st_mode): mime_type = INODE_FIFO elif stat.S_ISLNK(st_mode): mime_type = INODE_SYMLINK elif stat.S_ISSOCK(st_mode): mime_type = INODE_SOCKET elif stat.S_ISREG(st_mode): is_file = True except: pass if is_file: if use_contents: try: with open(filepath, 'rb') as fp: data = fp.read(MIME_MAGIC_MAX_BUF_SIZE) except: pass # Removed in favor of gio, this was way too sloooow ! #mime_type = xdg.Mime.get_type(filepath) mime_type = gio.content_type_guess(filepath, data, False) return mime_type
def _thumbnail_wt(self): thumber = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_NORMAL) while True: uri, ref = type(self).__thumbnail_queue__.get() mime = gio.content_type_guess(uri) mtime = int(gio.File(uri) \ .query_info(gio.FILE_ATTRIBUTE_TIME_MODIFIED) \ .get_modification_time()) if (uri, mtime) in type(self).__thumbnail_cache__: t = type(self).__thumbnail_cache__[(uri, mtime)] else: t_uri = thumber.lookup(uri, mtime) if t_uri: t = gtk.gdk.pixbuf_new_from_file(t_uri) elif thumber.can_thumbnail(uri, mime, mtime): t = thumber.generate_thumbnail(uri, mime) if t != None: thumber.save_thumbnail(t, uri, mtime) type(self).__thumbnail_cache__[(uri, mtime)] = t if t != None: self._new_thumbnail(ref, t)
def get_file_type(text): if not pathexists(text): # FIXME: Real test for URL here return shortcuts.SHORTCUT_TYPE_URL if isdir(text): return shortcuts.SHORTCUT_TYPE_FOLDER if not isfile(text) and not islink(text): return shortcuts.SHORTCUT_TYPE_DOCUMENT filename = text # Sample file contents with open(filename, "r") as fd: sample = fd.read(128) # Guess if it's executable can_execute = False content_type = None try: content_type = gio.content_type_guess(filename, sample, want_uncertain=False) # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy can_execute = gio.content_type_can_be_executable(content_type) # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy except Exception as e: logging.error("Error guessing file type: %s", e) if not can_execute: if os.access(filename, os.X_OK): return shortcuts.SHORTCUT_TYPE_EXECUTABLE if can_execute and os.access(filename, os.X_OK): return shortcuts.SHORTCUT_TYPE_EXECUTABLE return shortcuts.SHORTCUT_TYPE_DOCUMENT
def on_item_activated(self, view, path): """Open selected items in a view.""" store = view.get_model() # If the same viewer is associated to multiple types, then merge the # associated URIs to be launched. # # This code is convoluted because the gtk.AppInfo type is not hashable. app_on_uris = [] for p in view.get_selected_items(): uri = store[p].uri mime = gio.content_type_guess(uri) app = gio.app_info_get_default_for_type(mime, True) l_apps = map(lambda x: x[0], app_on_uris) if app in l_apps: idx = l_apps.index(app) app_on_uris[idx][1].add(mime) app_on_uris[idx][2].append(uri) else: app_on_uris.append((app, set(mime), [uri,])) # Launch the associated viewers for all items. for app, mime, uris in app_on_uris: if app: if not app.launch_uris(uris): self.alert("Couldn't launch %s." % app.get_name()) else: self.alert("No associated viewer for type '%s'." % mime)
def StartViewer(entry, key, stringuri, parent=None, document=None): if not is_interactive(): return from Pyblio.GnomeUI import Utils uri = Fields.URL(stringuri) scheme, location, path, parameters, query, fragment = uri.url fileuri = uri.get_url() if uri.invalid or uri.inexact: message = Utils.Callback( _("Warning: This URL is marked as Invalid or Approximate: %s\nContinue?" ) % fileuri) if not message.answer(): return if document: document.statusbar.push(document.context_id, _(u"Determining Mime Type… ")) try: mimetype = gio.content_type_guess(fileuri) except RuntimeError, mesg: Utils.error_dialog( _("Cannot determine mime type for item %s ") % entry.key.key, _("URL in question is: %s\n" "You should check the url or path given for errors.\n" "Details: %s") % (fileuri, mesg)) if document: document.statusbar.pop(document.context_id) return
def capture_end_execute_panel(capture, exit_code, panel, view, output_type): panel['stop'].set_sensitive(False) if output_type in ('new-document','replace-document'): doc = view.get_buffer() start = doc.get_start_iter() end = start.copy() end.forward_chars(300) mtype = gio.content_type_guess(data=doc.get_text(start, end)) lmanager = gedit.get_language_manager() language = lmanager.guess_language(doc.get_uri(), mtype) if language is not None: doc.set_language(language) view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gdk.Cursor(gdk.XTERM)) view.set_cursor_visible(True) view.set_editable(True) if exit_code == 0: panel.write("\n" + _("Done.") + "\n", panel.italic_tag) else: panel.write("\n" + _("Exited") + ":", panel.italic_tag) panel.write(" %d\n" % exit_code, panel.bold_tag)
def getDefaultAppCommand(fpath): mime_type = gio.content_type_guess(fpath) try: app = gio.app_info_get_all_for_type(mime_type)[0] except IndexError: return return app.get_executable()
def os_check_is_audio(self): # FIXME need to use something else here # I think we must use video widget metadata but I don't found a way # to get this info from python filename = self.totem.get_current_mrl() if gio.content_type_guess(filename).split('/')[0] == 'audio': return True return False
def getDefaultAppCommand(fpath): import gio mime_type = gio.content_type_guess(fpath) try: app = gio.app_info_get_all_for_type(mime_type)[0] except IndexError: return return app.get_executable()
def get_mime(path_i, is_fil): ''' Получение mimetype ''' if is_fil: try: f = open(path_i) r = f.read(200) f.close() except: temp = 'empty' else: temp = str(gio.content_type_guess(None, r, True)[0]) else: temp = str(gio.content_type_guess(path_i, None, True)[0]) if temp: pass else: temp = 'empty' return temp
def guess_from_path(filepath, size=DEFAULT_SIZE): if os.path.isdir(filepath): return get_from_name('folder', size) try: mime_type = gio.content_type_guess(filepath, open(filepath).read(10)) return get_from_mime_type(mime_type, size) except Exception, e: print e return get_from_name(size=size)
def _on_attachment_chooser__file_set(self, button): filename = self.attachment_chooser.get_filename() data = open(filename, 'rb').read() mimetype = unicode(gio.content_type_guess(filename, data, False)) if self._attachment is None: self._attachment = Attachment(store=self.store) self._attachment.name = unicode(os.path.basename(filename)) self._attachment.mimetype = mimetype self._attachment.blob = data
def from_mime_type_or_extension(mimeType, extension): """ Return a file type object matching the given MIME type and/or extension. """ if not mimeType and not extension: raise ValueError("At least the MIME type or extension should be specified") elif not mimeType: type, confidence = gio.content_type_guess("foo" + extension, None, 0) return GnomeType(type) else: type = gio.content_type_from_mime_type(mimeType) return GnomeType(type)
def __get_mimetype(self, filepath): try: with open(filepath, 'rb') as f: header = f.read(256) size = len(header) except IOError: header = None size = 0 mimetype = gio.content_type_guess(filepath, header, size)[0] return mimetype
def on_button_pressed(self, treeview, event): if event.type == gtk.gdk._2BUTTON_PRESS: x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: return col = self.get_model_index(col) model = self.get_model() data = model.on_get_value(path[0], col + len(self.description) - 1) if data == None: return if not isinstance(data, buffer): self.on_view_data(None, data) elif isinstance(data, buffer) and HAVE_GIO: mime = gio.content_type_guess(None, data) default = gio.app_info_get_default_for_type(mime, False) if default is not None: self.on_open_blob(None, data, default, mime) elif event.button == 3: x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: return self.select_cell(path[0], col, not self.cell_is_selected(path[0], col)) treeview.grab_focus() treeview.set_cursor(path, col, 0) popup = self._get_popup_for_cell(path[0], col) if not popup: return popup.popup(None, None, None, event.button, time) elif event.button == 1: x = int(event.x) y = int(event.y) pthinfo = treeview.get_path_at_pos(x, y) if not pthinfo: return path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: self.select_row(path[0], not self.row_is_selected(path[0])) else: self.select_cell(path[0], col, not self.cell_is_selected(path[0], col))
def is_content_type(fileleaf, ctype): predicate = gio.content_type_is_a ctype_guess, uncertain = gio.content_type_guess(fileleaf.object, None, True) ret = predicate(ctype_guess, ctype) if ret or not uncertain: return ret content_attr = gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE gfile = gio.File(fileleaf.object) info = gfile.query_info(content_attr) content_type = info.get_attribute_string(content_attr) return predicate(content_type, ctype)
def add_recent(self, uri): manager = gtk.recent_manager_get_default() app_exec = "playitslowly \"%s\"" % uri mime_type, certain = gio.content_type_guess(uri, want_uncertain=True) if mime_type: manager.add_full(uri, { "app_name": "playitslowly", "app_exec": "playitslowly", "mime_type": mime_type }) print app_exec, mime_type
def from_file(path): """ Try to guess the type of a file. """ try: with open(path, "rb") as f: header = f.read(256) size = len(header) except IOError: header = None size = 0 type, confidence = gio.content_type_guess(path, header, size) return GnomeType(type)
def get_for_file(self, fname): mime = gio.content_type_guess(fname) if mime: icon_name = gio.content_type_get_icon(mime) icon = self.theme.choose_icon(icon_name.get_names(), 16, 0) if icon: return gtk.IconInfo.load_icon(icon) else: name = gtk.STOCK_FILE else: name = gtk.STOCK_FILE return self.theme.load_icon(name, 16, 0)
def add_recent(self, uri): manager = gtk.recent_manager_get_default() app_exec = "playitslowly \"%s\"" % uri mime_type, certain = gio.content_type_guess(uri, want_uncertain=True) if mime_type: manager.add_full( uri, { "app_name": "playitslowly", "app_exec": "playitslowly", "mime_type": mime_type }) print app_exec, mime_type
def on_button_pressed(self, treeview, event): if event.type == gtk.gdk._2BUTTON_PRESS: x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: return col = self.get_model_index(col) model = self.get_model() data = model.on_get_value(path[0], col+len(self.description)-1) if data == None: return if not isinstance(data, buffer): self.on_view_data(None, data) elif isinstance(data, buffer) and HAVE_GIO: mime = gio.content_type_guess(None, data) default = gio.app_info_get_default_for_type(mime, False) if default is not None: self.on_open_blob(None, data, default, mime) elif event.button == 3: x = int(event.x) y = int(event.y) time = event.time pthinfo = treeview.get_path_at_pos(x, y) if pthinfo is not None: path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: return self.select_cell(path[0], col, not self.cell_is_selected(path[0], col)) treeview.grab_focus() treeview.set_cursor( path, col, 0) popup = self._get_popup_for_cell(path[0], col) if not popup: return popup.popup( None, None, None, event.button, time) elif event.button == 1: x = int(event.x) y = int(event.y) pthinfo = treeview.get_path_at_pos(x, y) if not pthinfo: return path, col, cellx, celly = pthinfo if col == self.get_columns()[0]: self.select_row(path[0], not self.row_is_selected(path[0])) else: self.select_cell(path[0], col, not self.cell_is_selected(path[0], col))
def open_with(path): context = gtk.gdk.AppLaunchContext() path = os.path.abspath(path) if os.path.isdir(path): path += "/" mime_type = gio.content_type_guess(path) app_info = gio.app_info_get_default_for_type(mime_type, False) if app_info != None: app_info.launch([gio.File(path)], context) else: sys.stderr.write('no application related to "%s"\n' % mime_type)
def _listdir(self, path): dirs, files = [], [] for fn in os.listdir(path): fp = os.path.join(path, fn) if os.path.isdir(fp): dirs.append((fn, 'inode/directory')) elif self.show_files and os.path.isfile(fp): ft = gio.content_type_guess(fp) files.append((fn, ft)) dirs = sorted(dirs, key=self._sort) if self.show_files: return dirs + sorted(files, key=self._sort) return dirs
def _get_popup_for_cell(self, row, col): col = self.get_model_index(col) model = self.get_model() data = model.on_get_value(row, col + len(self.description) - 1) popup = gtk.Menu() if data != None: if not isinstance(data, buffer): item = gtk.MenuItem(_(u"Copy value to clipboard")) item.connect("activate", self.on_copy_value_to_clipboard, data) item.show() popup.append(item) sep = gtk.SeparatorMenuItem() sep.show() popup.append(sep) if isinstance(data, buffer) and HAVE_GIO: mime = gio.content_type_guess(None, data) item = gtk.MenuItem(_(u"Save as...")) item.connect("activate", self.on_save_blob, data, mime) item.show() popup.append(item) if mime: apps = gio.app_info_get_all_for_type(mime) if apps: default = gio.app_info_get_default_for_type( mime, False) if default is not None and default in apps: apps.remove(default) apps.insert(0, default) # make sure it's first item = gtk.MenuItem(_(u"Open with...")) smenu = gtk.Menu() item.set_submenu(smenu) item.show() popup.append(item) for app_info in apps: item = gtk.MenuItem(app_info.get_name()) item.connect("activate", self.on_open_blob, data, app_info, mime) item.show() smenu.append(item) else: item = gtk.MenuItem(_(u"View value")) item.connect("activate", self.on_view_data, data) item.show() popup.append(item) else: item = gtk.MenuItem(_(u"This cell contains a 'NULL' value.")) item.set_sensitive(False) item.show() popup.append(item) return popup
def _get_popup_for_cell(self, row, col): col = self.get_model_index(col) model = self.get_model() data = model.on_get_value(row, col+len(self.description)-1) popup = gtk.Menu() if data != None: if not isinstance(data, buffer): item = gtk.MenuItem(_(u"Copy value to clipboard")) item.connect("activate", self.on_copy_value_to_clipboard, data) item.show() popup.append(item) sep = gtk.SeparatorMenuItem() sep.show() popup.append(sep) if isinstance(data, buffer) and HAVE_GIO: mime = gio.content_type_guess(None, data) item = gtk.MenuItem(_(u"Save as...")) item.connect("activate", self.on_save_blob, data, mime) item.show() popup.append(item) if mime: apps = gio.app_info_get_all_for_type(mime) if apps: default = gio.app_info_get_default_for_type(mime, False) if default is not None and default in apps: apps.remove(default) apps.insert(0, default) # make sure it's first item = gtk.MenuItem(_(u"Open with...")) smenu = gtk.Menu() item.set_submenu(smenu) item.show() popup.append(item) for app_info in apps: item = gtk.MenuItem(app_info.get_name()) item.connect("activate", self.on_open_blob, data, app_info, mime) item.show() smenu.append(item) else: item = gtk.MenuItem(_(u"View value")) item.connect("activate", self.on_view_data, data) item.show() popup.append(item) else: item = gtk.MenuItem(_(u"This cell contains a 'NULL' value.")) item.set_sensitive(False) item.show() popup.append(item) return popup
def is_content_type(fileleaf, ctype): predicate = gio.content_type_is_a ctype_guess, uncertain = gio.content_type_guess(fileleaf.object, None, True) ret = predicate(ctype_guess, ctype) if ret or not uncertain: return ret content_attr = gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE gfile = gio.File(fileleaf.object) if not gfile.query_exists(None): return info = gfile.query_info(content_attr) content_type = info.get_attribute_string(content_attr) return predicate(content_type, ctype)
def _update_attachment(self): filters = get_filters_for_attachment() with selectfile(_("Select attachment"), filters=filters) as sf: rv = sf.run() filename = sf.get_filename() if rv != gtk.RESPONSE_OK or not filename: return data = open(filename, 'rb').read() mimetype = gio.content_type_guess(filename, data, False) if self.attachment is None: self.attachment = Attachment(store=self.store) self.attachment.name = unicode(os.path.basename(filename)) self.attachment.mimetype = unicode(mimetype) self.attachment.blob = data self._update_widget()
def _get_icon(self, name): theme = gtk.icon_theme_get_default() if name == "folder": name = gtk.STOCK_DIRECTORY else: mime = gio.content_type_guess(name) if mime: iconname = gio.content_type_get_icon(mime) icon = theme.choose_icon(iconname.get_names(), self.icon_size, 0) if icon: return gtk.IconInfo.load_icon(icon) else: name = gtk.STOCK_FILE else: name = gtk.STOCK_FILE return theme.load_icon(name, self.icon_size, 0)
def get_meta_info(filename): try: filetype = gio.content_type_guess(filename) info = gio.app_info_get_all_for_type(filetype) except: return False apps = [] for i in info: ret = {} ret['name'] = i.get_name() ret['description'] = i.get_description() ret['exec'] = i.get_executable() apps.append(ret) return apps
def __init__(self, file_path): stat = os.stat(file_path) metadata = { 'uid': file_path, 'title': os.path.basename(file_path), 'timestamp': stat.st_mtime, 'mime_type': gio.content_type_guess(filename=file_path), 'activity': '', 'activity_id': '', 'icon-color': get_color().to_string(), 'description': file_path, } self.object_id = file_path self._metadata = DSMetadata(metadata) self._file_path = None self._destroyed = False
def __init__(self, file_path): stat = os.stat(file_path) client = gconf.client_get_default() metadata = { 'uid': file_path, 'title': os.path.basename(file_path), 'timestamp': stat.st_mtime, 'mime_type': gio.content_type_guess(filename=file_path), 'activity': '', 'activity_id': '', 'icon-color': client.get_string('/desktop/sugar/user/color'), 'description': file_path, } self.object_id = file_path self._metadata = DSMetadata(metadata) self._file_path = None self._destroyed = False
def _get_icon_pixbuf(self, file_path): it = gtk.icon_theme_get_default() #short-circuit on folders, since it fails otherwise... strange. if os.path.isdir(file_path): return it.load_icon('folder', 16, gtk.ICON_LOOKUP_USE_BUILTIN) content_type = gio.content_type_guess(file_path) type_names = gio.content_type_get_icon(content_type).get_names() for stock_id in type_names: # jesus fscking christ. this is stoopid... for GTK's sake, I HOPE # this is the wrong way to do this try: pixbuf = it.load_icon(stock_id, 16, gtk.ICON_LOOKUP_USE_BUILTIN) return pixbuf except glib.GError: pass # FAIL. just return something completely generic. pixbuf = it.load_icon('text-x-generic', 16, gtk.ICON_LOOKUP_USE_BUILTIN) return pixbuf
def _get_markup_for_value(self, value, strip_length=True, markup=True): style = self.style if value == None: if markup: value = '<span foreground="%s"><NULL></span>' % style.dark[ gtk.STATE_PRELIGHT].to_string() else: value = 'null' elif isinstance(value, buffer): if markup: if HAVE_GIO: mime = gio.content_type_guess(None, value) else: mime = None if mime is None: mime = 'LOB' else: mime = ( '%s (%s)' # e.g. "Python-Skript (text/x-python)" % (gio.content_type_get_description(mime), mime)) value = ('<span foreground="%s"><%s></span>' % (style.dark[gtk.STATE_PRELIGHT].to_string(), mime)) else: value = str(buffer) else: if isinstance(value, str): value = unicode(value, self.coding_hint, 'replace') elif isinstance(value, unicode): pass else: value = unicode(value) value = value.splitlines() if value: if strip_length and len(value[0]) > GRID_LABEL_MAX_LENGTH: value = ('%s <span foreground="%s">[...]</span>' % (gobject.markup_escape_text( value[0][:GRID_LABEL_MAX_LENGTH]), style.dark[gtk.STATE_NORMAL].to_string())) else: value = gobject.markup_escape_text("\n".join(value)) else: value = "" return value
def _get_markup_for_value(self, value, strip_length=True, markup=True): style = self.style if value == None: if markup: value = '<span foreground="%s"><NULL></span>' % style.dark[gtk.STATE_PRELIGHT].to_string() else: value = 'null' elif isinstance(value, buffer): if markup: if HAVE_GIO: mime = gio.content_type_guess(None, value) else: mime = None if mime is None: mime = 'LOB' else: mime = ('%s (%s)' # e.g. "Python-Skript (text/x-python)" % (gio.content_type_get_description(mime), mime)) value = ('<span foreground="%s"><%s></span>' % (style.dark[gtk.STATE_PRELIGHT].to_string(), mime)) else: value = str(buffer) else: if isinstance(value, str): value = unicode(value, self.coding_hint, 'replace') elif isinstance(value, unicode): pass else: value = unicode(value) value = value.splitlines() if value: if strip_length and len(value[0]) > GRID_LABEL_MAX_LENGTH: value = ('%s <span foreground="%s">[...]</span>' % (gobject.markup_escape_text( value[0][:GRID_LABEL_MAX_LENGTH]), style.dark[gtk.STATE_NORMAL].to_string())) else: value = gobject.markup_escape_text("\n".join(value)) else: value = "" return value
def get_mime(path_i, is_fil): """ Получение mimetype """ if is_fil: try: f = open(path_i) r = f.read(200) f.close() except: temp = "empty" else: temp = str(gio.content_type_guess(None, r, True)[0]) else: temp = "application/octet-stream" if temp: pass else: temp = "empty" return temp
def create_thumbnail_pixbuf(self, path): mime = gio.content_type_guess(path) if mime == "application/pdf": pdf = path elif mime.startswith("image/"): return gtk.gdk.pixbuf_new_from_file(path) elif mime.startswith("text/"): pdf = self.topdf(path) elif mime.startswith("application/vnd.oasis.opendocument"): # openoffice documents pdf = self.topdf(path) elif mime.startswith("application/vnd.openxmlformats-officedocument"): # ooxml documents pdf = self.topdf(path) elif ( mime.startswith("application/vnd.ms-powerpoint") or mime.startswith("application/vnd.ms-excel") or mime.startswith("application/vnd.ms-word") ): # MS Office documents (non ooxml formats) pdf = self.topdf(path) else: m = commands.getstatusoutput("file %s" % path) if m[0] != 0 or not re.match(".* text.*", m[1]): print >>sys.stderr, "mime type: %s" % mime print >>sys.stderr, "magic: %s" % m[1] return None pdf = self.topdf(path) pix = None if pdf: ppm = self.pdftoppm(pdf) if pdf != path: os.unlink(pdf) if ppm: pix = gtk.gdk.pixbuf_new_from_file(ppm) os.unlink(ppm) return pix
def create_thumbnail_pixbuf(self, path): mime = gio.content_type_guess(path) if mime == "application/pdf": pdf = path elif mime.startswith("image/"): return gtk.gdk.pixbuf_new_from_file(path) elif mime.startswith("text/"): pdf = self.topdf(path) elif mime.startswith("application/vnd.oasis.opendocument"): #openoffice documents pdf = self.topdf(path) elif mime.startswith("application/vnd.openxmlformats-officedocument"): #ooxml documents pdf = self.topdf(path) elif (mime.startswith("application/vnd.ms-powerpoint") or mime.startswith("application/vnd.ms-excel") or mime.startswith("application/vnd.ms-word") ): #MS Office documents (non ooxml formats) pdf = self.topdf(path) else: m = commands.getstatusoutput("file %s" % path) if m[0] != 0 or not re.match(".* text.*", m[1]): print >> sys.stderr, "mime type: %s" % mime print >> sys.stderr, "magic: %s" % m[1] return None pdf = self.topdf(path) pix = None if pdf: ppm = self.pdftoppm(pdf) if pdf != path: os.unlink(pdf) if ppm: pix = gtk.gdk.pixbuf_new_from_file(ppm) os.unlink(ppm) return pix
def _get_file_metadata(path, stat, fetch_preview=True): """Return the metadata from the corresponding file. Reads the metadata stored in the json file or create the metadata based on the file properties. """ filename = os.path.basename(path) dir_path = os.path.dirname(path) metadata = _get_file_metadata_from_json(dir_path, filename, fetch_preview) if metadata: if 'filesize' not in metadata: metadata['filesize'] = stat.st_size return metadata return {'uid': path, 'title': os.path.basename(path), 'timestamp': stat.st_mtime, 'filesize': stat.st_size, 'mime_type': gio.content_type_guess(filename=path), 'activity': '', 'activity_id': '', 'icon-color': '#000000,#ffffff', 'description': path}
if scheme == 'file' and not location: filename = path elif mimetype in ['text/html', 'text/plain']: filename = fileuri else: filename, headers = urllib.urlretrieve(fileuri) if mimetype == 'application/x-gzip': try: tempname = os.tmpnam() os.system("gzip -d < %s >%s" % (filename, tempname)) filename = tempname mimetype = gio.content_type_guess(filename) except RuntimeError, mesg: Utils.error_dialog( _("IOError for item %s: cannot uncompress resource.") % entry.key.key, _("URL: %s\nDetails: %s") % (filename, mesg)) if document: document.statusbar.pop(document.context_id) return viewers = [ item[1] for item in Config.get(config_viewers).data if item[0] == mimetype ] or [ item[1] for item in Config.get(config_viewers).data if item[0].endswith('/*') and item[0][:-2] == mimetype1
def get_mime_type(self): return gio.content_type_guess(self.path)
def testFromContentsUncertain(self): mime_type, result_uncertain = gio.content_type_guess( data='<html></html>', want_uncertain=True) self.assertEquals('text/html', mime_type) self.assertEquals(bool, type(result_uncertain))
'description', 'tags']: if f in metadata and \ self._regex.match(metadata[f]): add_to_list = True break if not add_to_list: return if self._date_start is not None and stat.st_mtime < self._date_start: return if self._date_end is not None and stat.st_mtime > self._date_end: return if self._mime_types: mime_type = gio.content_type_guess(filename=full_path) if mime_type not in self._mime_types: return file_info = (full_path, stat, int(stat.st_mtime), stat.st_size, metadata) self._file_list.append(file_info) return def _scan_a_directory(self): dir_path = self._pending_directories.pop(0) try: entries = os.listdir(dir_path) except OSError, e: