#!/usr/bin/env python # -*- coding:UTF-8 -*- import os import commands from gi.repository import Gtk from gi.repository import GdkPixbuf from gi.repository import GObject IMAGENES = os.listdir(os.path.join(os.path.dirname(__file__), 'Iconos/')) DIRECCION = os.path.join(os.path.dirname(__file__), 'Iconos/') AUDIO = os.path.join(DIRECCION, 'audio.svg') VIDEO = os.path.join(DIRECCION, 'video.svg') DESCONOCIDO = os.path.join(DIRECCION, 'desconocido.svg') DOCUMENTO = os.path.join(DIRECCION, 'documento.svg') TEXTO = os.path.join(DIRECCION, 'texto.svg') PENDRIVE = os.path.join(DIRECCION, 'pendrive.svg') DIR_SIN_PER = os.path.join(DIRECCION, 'directory_dennied.svg') FILE_SIN_PER = os.path.join(DIRECCION, 'file_dennied.svg') images = ['svg', 'png', 'gif', 'jpg', 'jpeg', 'xmp', 'ico'] videos = ['flv', '.mp4', '.mpa', '.mpe', '.mpeg', '.mpg'] PAPELERA = os.path.expanduser('~/.local/share/Trash/files') def intentar_abrir(direccion): """Abre el archivo con el programa predeterminado""" if ' ' in direccion: direccion = direccion.replace(' ', '\ ') comando = commands.getoutput('gnome-open %s' % direccion) return comando def crear_papelera(): """Crea los directorios de la papelera""" os.makedirs(PAPELERA) def get_tamanio(direccion): """Obtiene una dirección y devuelve su tamanio, si es que hay permisos para leerla""" lectura, escritura, ejecucion = get_permisos(direccion) if lectura: if os.path.isfile(direccion): numero = os.path.getsize(direccion) if numero < 1024: tamanio = numero tipo = 'B' elif numero >= 1024 and numero < 1024 ** 2: tamanio = numero / 1024 tipo = 'KB' elif numero >= 1024 ** 2 and numero < 1024 ** 3: tamanio = numero / 1024 / 1024 tipo = 'MB' elif numero >= 1024 ** 3 and numero < 1024 ** 4: tamanio = numero / 1024 / 1024 / 1024 tipo = 'GB' elif numero >= 1024 ** 4: tamanio = numero / 1024 / 1024 / 1024 / 1024 tipo = 'TB' string = 'Pesa ' + str(tamanio) + ' ' + tipo elif os.path.isdir(direccion): archivos = len(os.listdir(direccion)) if archivos == 1: texto = ' archivo' else: texto = ' archivos' string = 'Contiene ' + str(archivos) + texto else: string = 'No tiene permisos para leerla.' return string def get_carpetas_del_usuario(): escritorio = '' descargas = '' plantillas = '' publico = '' documentos = '' musica = '' imagenes = '' videos = '' archivo = os.path.expanduser('~/.config/user-dirs.dirs') if os.path.exists(archivo): texto = open(archivo).read() for linea in texto.splitlines(): if 'DESKTOP' in linea: escritorio = linea.split('XDG_DESKTOP_DIR="$HOME/')[1] escritorio = os.path.join(os.path.expanduser('~'), escritorio) elif 'DOWNLOAD' in linea: descargas = linea.split('XDG_DOWNLOAD_DIR="$HOME/')[1] descargas = os.path.join(os.path.expanduser('~'), descargas) elif 'TEMPLATES' in linea: plantillas = linea.split('XDG_TEMPLATES_DIR="$HOME/')[1] plantillas = os.path.join(os.path.expanduser('~'), plantillas) elif 'PUBLICSHARE' in linea: publico = linea.split('XDG_PUBLICSHARE_DIR="$HOME/')[1] publico = os.path.join(os.path.expanduser('~'), publico) elif 'DOCUMENTS' in linea: documentos = linea.split('XDG_DOCUMENTS_DIR="$HOME/')[1] documentos = os.path.join(os.path.expanduser('~'), documentos) elif 'MUSIC' in linea: musica = linea.split('XDG_MUSIC_DIR="$HOME/')[1] musica = os.path.join(os.path.expanduser('~'), musica) elif 'VIDEOS' in linea: videos = linea.split('XDG_VIDEOS_DIR="$HOME/')[1] videos = os.path.join(os.path.expanduser('~'), videos) return escritorio, descargas, plantillas, publico, documentos, musica, imagenes, videos def get_permisos(direccion): """Obtiene una dirección, y devuelve sí tiene permisos de lectura, escritura y ejecucución""" if os.path.exists(direccion): lectura = os.access(direccion, os.R_OK) escritura = os.access(direccion, os.W_OK) ejecucion = os.access(direccion, os.X_OK) return lectura, escritura, ejecucion else: return False, False, False def get_pixbuf(direccion): """Obtiene una dirección, inspecciona el tipo de archivo o si es un directorio, y devuelve un pixbuf con la imagen apropiada""" pixbuf = None lectura, escritura, ejecucacion = get_permisos(direccion) if lectura and escritura: if os.path.isdir(direccion): tipo = 'inode/directory' if os.path.ismount(direccion): tipo = 'montaje' else: tipo = commands.getoutput('file %s --mime-type -b' % (direccion)) if 'x-' in tipo: tipo = tipo.replace('x-', '') if '/' in tipo: tipo = tipo.split('/')[1] extension = direccion.split('.')[-1] extension += '.svg' if extension.split('.svg')[0] in images: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(direccion, 64, 64) if 'video' in tipo or extension in videos: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(VIDEO, 64, 64) tipo += '.svg' if tipo in IMAGENES: imagen = DIRECCION + tipo pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(imagen, 64, 64) if extension in IMAGENES: extension = DIRECCION + extension pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(extension, 64, 64) if 'montaje' in tipo: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(PENDRIVE, 64, 64) if not pixbuf: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(DESCONOCIDO, 64, 64) else: if os.path.isdir(direccion): pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(DIR_SIN_PER, 64, 64) elif os.path.isfile(direccion): pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(FILE_SIN_PER, 64, 64) return pixbuf def get_carpeta_contenedora(direccion): """Devuelve la carpeta contenedara a la introducida, a menos que se esté en el directorio raíz, en ese caso simplemente devuelve el directorio raíz""" lista = direccion.split('/') try: direccion = '/' numero = len(lista) - 1 while not bool(lista[numero]): numero -= 1 for directorio in lista[:numero]: if directorio: direccion = direccion + directorio + '/' except IndexError: direccion = '/' return direccion class Archivos(): """Clase para gestionar archivos""" def __init__(self): self.origen_cortar = None self.origen_copiar = None self.accion = None def get_origen_copiar(self): return self.origen_copiar def get_origen_cortar(self): return self.origen_cortar def set_origen_cortar(self, widget, direccion): if os.path.exists(direccion): self.origen_cortar = direccion self.accion = 'cortar' def set_origen_copiar(self, widget, direccion): if os.path.exists(direccion): self.origen_copiar = direccion self.accion = 'copiar' def pegar(self, widget, direccion): copiar = self.origen_copiar cortar = self.origen_cortar if os.path.exists(direccion): if self.accion == 'copiar' and os.path.exists(copiar): if os.path.isdir(copiar) or os.path.ismount(copiar): os.system('cp -r %s %s' % (copiar, direccion)) elif os.path.isfile(copiar): os.system('cp %s %s' % (copiar, direccion)) elif self.accion == 'cortar' and os.path.exists(cortar): os.system('mv %s %s' % (cortar, direccion)) def borrar(self, archivo): if os.path.exists(archivo): Borrar(archivo) def crear_directorio(self, direccion): os.mkdir(direccion) def crear_archivo(self, direccion, contenido=None): if not os.path.exists(direccion): archivo = open(direccion, 'w') if contenido: archivo.write(contenido) archivo.close() def mover_a_la_papelera(self, direccion): if os.path.exists(direccion): crear_papelera() os.system('mv %s %s' % (direccion, PAPELERA)) class CrearDirectorio(Gtk.Dialog): __gsignals__ = { 'creado': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, [])} def __init__(self, direccion): Gtk.Dialog.__init__(self) self.set_title('Crear Carpeta') self.direccion = direccion if list(self.direccion)[-1] != '/': self.direccion += '/' label = Gtk.Label(direccion) self.entry = Gtk.Entry() self.entry.connect('activate', self.crear_directorio) self.hbox = Gtk.HBox() self.vbox.pack_start(self.hbox, False, False, 0) boton_cerrar = Gtk.Button(None, Gtk.STOCK_CANCEL) boton_cerrar.connect('clicked', self.cerrar) self.action_area.add(boton_cerrar) boton_aceptar = Gtk.Button(None, Gtk.STOCK_OK) boton_aceptar.connect('clicked', self.clicked) self.action_area.add(boton_aceptar) self.hbox.add(label) self.hbox.add(self.entry) self.show_all() def crear_directorio(self, widget): self.direccion += self.entry.get_text() if not os.path.exists(self.direccion): os.mkdir(self.direccion) self.emit('creado') self.cerrar() def clicked(self, widget): self.entry.activate() def cerrar(self, *args): self.destroy() class Propiedades(Gtk.Dialog): """Un diálogo que muestra las propiedades de un archivo""" __gsignals__ = { 'cambio-de-propiedades': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, [])} def __init__(self, direccion): Gtk.Dialog.__init__(self) self.direccion = direccion nombre = direccion.split('/')[-1] lectura, escritura, ejecucion = get_permisos(self.direccion) self.set_title('Propiedades') self.set_border_width(5) self.vbox.set_spacing(2) hbox1 = Gtk.HBox() hbox2 = Gtk.HBox() hbox3 = Gtk.HBox() hbox4 = Gtk.HBox() hbox5 = Gtk.HBox() hbox6 = Gtk.HBox() hbox7 = Gtk.HBox() self.vbox.pack_start(hbox1, False, False, 2) self.vbox.pack_start(hbox2, False, False, 2) self.vbox.pack_start(hbox3, False, False, 2) self.vbox.pack_start(hbox4, False, False, 2) self.vbox.pack_start(hbox5, False, False, 2) self.vbox.pack_start(hbox6, False, False, 2) self.vbox.pack_start(hbox7, False, False, 2) tipo = commands.getoutput('file %s --mime-type -b' % (self.direccion)) tamanio = get_tamanio(self.direccion) ubicacion = get_carpeta_contenedora(self.direccion) label_nombre = Gtk.Label('Nombre:') label_tipo = Gtk.Label('Tipo:') label_tamanio = Gtk.Label('Tamaño:') label_ubicacion = Gtk.Label('Ubicación:') label_accedido = Gtk.Label('Accedido:') label_modificado = Gtk.Label('Modificado:') self.entry_nombre = Gtk.Entry() self.label_tipo = Gtk.Label(tipo) self.label_tamanio = Gtk.Label(tamanio) self.label_ubicacion = Gtk.Label(ubicacion) self.label_accedido = Gtk.Label() self.label_modificado = Gtk.Label() self.agregar(hbox1, label_nombre) self.agregar(hbox1, self.entry_nombre) self.agregar(hbox2, label_tipo) self.agregar(hbox2, self.label_tipo) self.agregar(hbox3, label_tamanio) self.agregar(hbox3, self.label_tamanio) self.agregar(hbox4, label_ubicacion) self.agregar(hbox4, self.label_ubicacion) self.agregar(hbox5, label_accedido) self.agregar(hbox5, self.label_accedido) self.agregar(hbox6, label_modificado) self.agregar(hbox6, self.label_modificado) self.frame = Gtk.Frame() self.treeview = Gtk.TreeView() self.treeview.modelo = Gtk.ListStore() self.crear_celdas() self.vbox.pack_start(Gtk.HSeparator(), False, False, 0) self.vbox.pack_start(self.treeview, True, True, 0) self.entry_nombre.set_text(nombre) self.entry_nombre.set_editable(lectura and escritura) self.entry_nombre.connect('activate', self.rename) def agregar(self, box, widget): box.pack_start(widget, True, True, 2) def crear_celdas(self): columna1 = Gtk.TreeViewColumn('Usuario') columna2 = Gtk.TreeViewColumn('Lectura') columna3 = Gtk.TreeViewColumn('Escritura') columna4 = Gtk.TreeViewColumn('Ejecución') render1 = Gtk.CellRendererText() render2 = Gtk.CellRendererToggle() render3 = Gtk.CellRendererToggle() render4 = Gtk.CellRendererToggle() columna1.pack_start(render1, True) columna2.pack_start(render2, True) columna3.pack_start(render3, True) columna4.pack_start(render4, True) columna1.set_attributes(render1, text=0) columna2.set_attributes(render2, active=1) columna3.set_attributes(render3, active=2) columna4.set_attributes(render4, active=3) self.treeview.append_column(columna1) self.treeview.append_column(columna2) self.treeview.append_column(columna3) self.treeview.append_column(columna4) def rename(self, widget): texto = widget.get_text() list = self.direccion.split('/') try: direccion = '/' numero = len(list) - 1 while not bool(list[numero]): numero -= 1 for directorio in list[:numero]: if directorio: direccion = direccion + directorio + '/' except IndexError: direccion = '/' nombre = direccion + texto os.rename(self.direccion, nombre) self.direccion = nombre self.emit('cambio-de-propiedades') """ self.direccion = direccion nombre = direccion.split('/')[-1] if os.path.isdir(self.direccion): texto = 'la carpeta' texto2 = 'borrarla' elif os.path.isfile(self.direccion): texto = 'el archivo' texto2 = 'borrarlo' lectura, escritura, ejecucion = get_permisos(self.direccion) self.set_title('Propedades de %s' % nombre) tipo = os.system('file %s --mime-type -b' % direccion) label_tipo = Gtk.Label('Tipo: %s' % tipo) hbox1 = Gtk.HBox() label_nombre = Gtk.Label('Nombre de %s:' % texto) self.entrada = Gtk.Entry() self.entrada.set_text(nombre) self.entrada.connect('activate', self.rename) hbox1.pack_start(label_nombre, False, False, 5) hbox1.pack_start(self.entrada, False, False, 5) self.vbox.pack_start(hbox1, False, False, 0) ejecutar = Gtk.CheckButton('Permitir ejecutar como un programa') ejecutar.connect('clicked', self.permitir_ejecutar) self.vbox.pack_start(ejecutar, False, False, 0) boton_cerrar = Gtk.Button(None, Gtk.STOCK_OK) boton_cerrar.connect('clicked', self.cerrar) self.action_area.add(boton_cerrar) self.entrada.set_sensitive(escritura) ejecutar.set_sensitive(escritura) ejecutar.set_active(ejecucion) self.show_all() def cerrar(self, widget): self.destroy() def permitir_ejecutar(self, widget): os.chmod(self.direccion, widget.get_active()) self.emit('cambio-de-propiedades') """ class Borrar(Gtk.MessageDialog): __gsignals__ = { 'borrado': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, [])} def __init__(self, direccion, type=Gtk.MessageType(2)): Gtk.MessageDialog.__init__(self) self.direccion = direccion if os.path.isdir(self.direccion): texto = 'la carpeta' texto2 = 'borrarla' elif os.path.isfile(self.direccion): texto = 'el archivo' texto2 = 'borrarlo' self.set_markup('%s' % '¿Estas seguro que quieres borrar %s?' % texto) self.format_secondary_text( 'Sí borras %s, se perderá para siempre' % texto) boton_no = Gtk.Button('_No quiero %s' % texto2) boton_no.connect('clicked', self.cerrar) self.action_area.add(boton_no) boton_si = Gtk.Button('_Si quiero %s' % texto2) boton_si.connect('clicked', self.borrar) self.action_area.add(boton_si) boton_no.set_use_underline(True) boton_si.set_use_underline(True) self.show_all() def borrar(self, widget): if os.path.exists(self.direccion): if os.path.isdir(self.direccion): os.removedirs(self.direccion) elif os.path.isfile(self.direccion): os.remove(self.direccion) self.emit('borrado') self.destroy() def cerrar(self, widget): self.destroy()