def OnEditConflicts(self, menuitem, window, files): """ Edit Conflicts menu handler. """ file = files[0] path = gnomevfs.get_local_path_from_uri(file.get_uri()) rabbitvcs.util.helper.launch_diff_tool(path + ".mine", path)
def OnProperties(self, menuitem, window, files): """ Properties menu handler. """ file = files[0] path = gnomevfs.get_local_path_from_uri(file.get_uri()) pid = rabbitvcs.util.helper.launch_ui_window("property_editor", [path]) self.RescanFilesAfterProcess(pid)
def get_menu(self, model, path): """ The context menu is expanded if the python tools plugin and bicyclerepairman are available. """ menuitems = [] try: tok = model.get_value(model.get_iter(path), 0) except: tok = None pt = self.geditwindow.get_data("PythonToolsPlugin") tagposition = self.get_tag_position(model, path) if pt and tok and tagposition: filename, line = tagposition # unpack the location of the token if tok.type in ["def", "class"] and filename[:7] == "file://": print tok.original # trunkate to local filename #filename = filename[7:] filename = gnomevfs.get_local_path_from_uri(filename) column = tok.original.find( tok.name) # find beginning of function definition print filename, line, column item = gtk.MenuItem("Find References") menuitems.append(item) item.connect( "activate", lambda w: pt.brm.findReferencesDialog( filename, line, column)) return menuitems
def drag_data_received(self, textview, context, xcord, ycord, selection_data, info, timestamp): """ Handles callback when a drop operation finishes. """ if not ("text/uri-list" in context.targets): return False else: if info != 1: return False # Load file uri_list = list(selection_data.get_uris()) for i in uri_list: filepatch = gnomevfs.get_local_path_from_uri(i) if os.path.getsize(filepatch) > 5120000: dialog = gtk.MessageDialog(tf.app.main_window.main_window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, (constants.MESSAGE_0030) % filepatch) choice = dialog.run() dialog.destroy() if choice == gtk.RESPONSE_YES: self.open_tab(filepatch) else: self.open_tab(filepatch) context.finish(True, False, timestamp) return True
def get_background_items(self, window, file): """ Menu activated on window background """ if file.get_uri() == "x-nautilus-desktop:///": return path = gnomevfs.get_local_path_from_uri(file.get_uri()) window.set_data("base_dir", os.path.realpath(six.text_type(path))) if not os.path.isdir(os.path.join(path,".svn")): items = [ ('NautilusPython::svncheckout_file_item', 'Checkout' , 'Checkout code from an SVN repository', self.OnCheckout, "rabbitvcs-checkout") ] else: items = [ ('NautilusPython::svnlog_file_item', 'Log' , 'SVN Log of %s' % file.get_name(), self.OnShowLog, "rabbitvcs-show_log"), ('NautilusPython::svncommit_file_item', 'Commit' , 'Commit %s back to the repository.' % file.get_name(), self.OnCommit, "rabbitvcs-commit"), ('NautilusPython::svnrepo_file_item', 'Repository Browser' , 'View Repository Sources', self.OnRepoBrowser, gtk.STOCK_FIND), ('NautilusPython::svnupdate_file_item', 'Update' , 'Get the latest code from the repository.', self.OnUpdate, "rabbitvcs-update"), ('NautilusPython::svnrefreshstatus_file_item', 'Refresh', 'Refresh the display status of %s.'%file.get_name(), self.OnRefreshStatus, "rabbitvcs-refresh"), ('NautilusPython::svnmkdiffdir_file_item', 'Patch', 'Create a patch of %s from the repository version'%file.get_name(), self.OnMkDiffDir, "rabbitvcs-diff"), ('NautilusPython::svnproperties_file_item', 'Properties', 'File properties for %s.'%file.get_name(), self.OnProperties, "rabbitvcs-properties") ] return self.create_menu(window, items, [file])
def get_menu(self, model, path): """ The context menu is expanded if the python tools plugin and bicyclerepairman are available. """ menuitems = [] try: tok = model.get_value( model.get_iter(path), 0 ) except: tok = None pt = self.geditwindow.get_data("PythonToolsPlugin") tagposition = self.get_tag_position(model,path) if pt and tok and tagposition: filename, line = tagposition # unpack the location of the token if tok.type in ["def","class"] and filename[:7] == "file://": print tok.original # trunkate to local filename #filename = filename[7:] filename = gnomevfs.get_local_path_from_uri(filename) column = tok.original.find(tok.name) # find beginning of function definition print filename, line, column item = gtk.MenuItem("Find References") menuitems.append(item) item.connect("activate",lambda w: pt.brm.findReferencesDialog(filename,line,column)) return menuitems
def on_snapopen_action( self ): self._init_glade() fbroot = self.get_filebrowser_root() if fbroot != "" and fbroot is not None: self._rootdir = fbroot self._snapopen_window.set_title(app_string + " (File Browser root)") else: eddtroot = self.get_eddt_root() if eddtroot != "" and eddtroot is not None: self._rootdir = eddtroot self._snapopen_window.set_title(app_string + " (EDDT integration)") else: self._snapopen_window.set_title(app_string + " (Working dir): " + self._rootdir) # cache the file list in the background #modify lines below as needed, these defaults work pretty well imagefilter = " ! -iname '*.jpg' ! -iname '*.jpeg' ! -iname '*.gif' ! -iname '*.png' ! -iname '*.psd' ! -iname '*.tif' ! -iname '*.pyc' " dirfilter = " ! -path '*.svn*' ! -path '*.git*' " rootpath = gnomevfs.get_local_path_from_uri(self._rootdir) if os.name == 'nt': cwd = os.getcwd() try: os.chdir(rootpath) os.popen('gfind . -type f %s > "%s"' % (imagefilter + dirfilter, self._tmpfile)) finally: os.chdir(cwd) else: os.popen("cd %s; find . -type f %s > %s 2> /dev/null &" % (rootpath, imagefilter + dirfilter, self._tmpfile)) self._snapopen_window.show() self._glade_entry_name.select_region(0,-1) self._glade_entry_name.grab_focus()
def get_mount_path_from_device_name(self,unix_device_name): for m in self.vm.get_mounted_volumes(): if m.get_device_type() not in [gnomevfs.DEVICE_TYPE_CAMERA,gnomevfs.DEVICE_TYPE_MEMORY_STICK]: continue if m.get_drive().get_device_path() == unix_device_name: path=gnomevfs.get_local_path_from_uri(m.get_activation_uri()) return path
def _reopen_tabs(self, window): log('ACTION load tabs') # Get list of open documents open_docs = [d.get_uri() for d in window.get_documents() if d.get_uri()] # Get saved active document active = self._config.get("common", "active_document") # Get document list docs = self._config.options("documents") log(str(docs)) empty_tab = None active_tab = None # Check if active document is untitled (there is empty tab) if window.get_active_document().is_untitled(): # Remember empty tab to close it later empty_tab = window.get_active_tab() # Check if document list is not empty if len(docs) > 0: # Process the rest documents for d in docs: # Get document uri uri = self._config.get("documents", d) # Check if document is not already opened if open_docs.count(uri) > 0: continue # Check if document exists #if not os.path.exists(uri.replace('file://', '', 1)): continue if not os.path.exists(gnomevfs.get_local_path_from_uri(uri)): continue # Create new tab log('ACTION: restore tab "%s"' % uri) tab = window.create_tab_from_uri(uri, None, 0, True, False) # Check if document was active (and there is NOT file in command line) if d == active and empty_tab != None: active_tab = tab # Connect handler that switches saved active document tab log('empty tab: ' + str(empty_tab)) log('activ tab: ' + str(active_tab)) if active_tab: def on_doc_loaded(doc, arg): window.set_active_tab(active_tab) if empty_tab and empty_tab.get_state() == gedit.TAB_STATE_NORMAL: log('ACTION: closing empty tab') _state = self._state self._state = RELOADER_STATE_CLOSING window.close_tab(empty_tab) self._state = _state active_tab.get_document().connect("loaded", on_doc_loaded) if empty_tab == None: self._save_tabs()
def get_mount_info(self): ''' returns a list of tuples (name,icon_data,fuse path) ''' mdict = {} mounts = [] for m in self.vm.get_mounted_volumes(): if m.get_device_type() not in [ gnomevfs.DEVICE_TYPE_CAMERA, gnomevfs.DEVICE_TYPE_MEMORY_STICK ]: continue path = gnomevfs.get_local_path_from_uri(m.get_activation_uri()) name = m.get_display_name() icon_names = [m.get_icon()] print m.get_device_type(), name, path if path not in mdict: vals = [name, icon_names, path] mdict[path] = vals mounts.append(vals) else: if len(icon_names) > len(mdict[path][1]): mdict[path][1] = icon_names if len(name) > len(mdict[path][0]): mdict[path][0] = name return mounts
def get_active_document_directory(self): doc = self._window.get_active_document() if doc is None: return None uri = doc.get_uri() if uri is not None and gedit_utils.uri_has_file_scheme(uri): return os.path.dirname(gnomevfs.get_local_path_from_uri(uri)) return None
def get_local_path_from_uri(uri): if uri != None and uri != "": try: local_path = gnomevfs.get_local_path_from_uri(uri) #print "converting URI to local_path" return local_path except Exception, e: print e print "Cannot convert URI: \"%s\"to local path" % uri print "URI calss: %s" % uri.__class__ try: unicodeUri = unicode(str(uri), 'utf-8') local_path = gnomevfs.get_local_path_from_uri(uri) return local_path except Exception, e: print e print "Cannot convert unicoded URI: \"%s\"to local path" % uri
def on_widget_drag_data_received(self, wid, context, x, y, selection_data, info, time): if len(selection_data.get_uris()) != 0: paths = [ gnomevfs.get_local_path_from_uri(u) for u in selection_data.get_uris() ] self.open_paths(paths) return True
def data_received_callback(self, widget, drag_context, x, y, selection_data, target_type, time): if target_type == self.TARGET_TYPE_TEXT: data = selection_data.get_text() filename = gnomevfs.get_local_path_from_uri(data) filename = filename[0:-1] self.script_open(filename = filename) else: print "could not load file"
def get_background_items(self, window, item): if not self.valid_uri(item.get_uri()): return path = unicode(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") self.nautilusVFSFile_table[path] = item # log.debug("get_background_items() called") window.set_data("base_dir", path) return NautilusMainContextMenu(self, path, [path]).get_menu()
def get_filebrowser_root(self): base = u'/apps/gedit-2/plugins/filebrowser/on_load' client = gconf.client_get_default() client.add_dir(base, gconf.CLIENT_PRELOAD_NONE) path = os.path.join(base, u'virtual_root') val = client.get(path) if val is not None: return gnomevfs.get_local_path_from_uri(val.get_string()) else: return ''
def filebrowser_root(self): """ Get path to current filebrowser root. """ base = u'/apps/%s/plugins/filebrowser/on_load' % APP_KEY client = gconf.client_get_default() client.add_dir(base, gconf.CLIENT_PRELOAD_NONE) path = base + u'/virtual_root' val = client.get(path) if val is not None: return gnomevfs.get_local_path_from_uri(val.get_string())
def get_mount_path_from_device_name(self, unix_device_name): for m in self.vm.get_mounted_volumes(): if m.get_device_type() not in [ gnomevfs.DEVICE_TYPE_CAMERA, gnomevfs.DEVICE_TYPE_MEMORY_STICK ]: continue if m.get_drive().get_device_path() == unix_device_name: path = gnomevfs.get_local_path_from_uri( m.get_activation_uri()) return path
def is_supported_uri(uri): if not uri: return False uri = gnomevfs.make_uri_from_shell_arg(uri) scheme = gnomevfs.get_uri_scheme(uri) # If the scheme is a file check if the file exists if scheme == "file": try: local_path = gnomevfs.get_local_path_from_uri(uri) return os.path.isfile(local_path) except Exception, e: return False
def read(self, uri, progress = None, recursive = None): pos = 0; files = []; dirs = []; """ La primera vez que se llama """ try: path = gnomevfs.get_local_path_from_uri(uri) except: path = uri if not recursive: self.progress_bar = progress self.clear_progress_bar() self._cancel_import_disk = False self.count_files = 1; self.position = 0; self.root = path """ Creamos un nuevo disco """ self.disk = fstypes.Disk(utils.get_label(path), path, None, None, 0, utils.get_drive_icon(str(path))) """ Contamos los archivos primero, para luego poder poner el progreso """ self.count_files = self.dir_count(uri) # self.count_files = sum((len(f) for _, _, f in os.walk(path))) # don't count correctly gobject.timeout_add(500, self.update_progress_bar) for info in gnomevfs.DirectoryHandle(uri): if(self._cancel_import_disk): return None """ Insertamos el archivo, si no es un archivo oculto """ if info.name == '.' or info.name == '..' or info.name[0] == ".": continue self.position += 1 pathfile = uri + "/" + urllib.pathname2url(info.name) self.path = pathfile file = fstypes.File(pathfile, self.disk) if info.type and info.type == 2: file.add_files(self.read(pathfile, None, True)) # Directory files.append(file) if not recursive: self.disk.add(file) if(self._cancel_import_disk): return None if not recursive: self.progress_bar = None return self.disk else: return files
def read(self, uri, progress=None, recursive=None): pos = 0 files = [] dirs = [] """ La primera vez que se llama """ try: path = gnomevfs.get_local_path_from_uri(uri) except: path = uri if not recursive: self.progress_bar = progress self.clear_progress_bar() self._cancel_import_disk = False self.count_files = 1 self.position = 0 self.root = path """ Creamos un nuevo disco """ self.disk = fstypes.Disk(utils.get_label(path), path, None, None, 0, utils.get_drive_icon(str(path))) """ Contamos los archivos primero, para luego poder poner el progreso """ self.count_files = self.dir_count(uri) # self.count_files = sum((len(f) for _, _, f in os.walk(path))) # don't count correctly gobject.timeout_add(500, self.update_progress_bar) for info in gnomevfs.DirectoryHandle(uri): if (self._cancel_import_disk): return None """ Insertamos el archivo, si no es un archivo oculto """ if info.name == '.' or info.name == '..' or info.name[0] == ".": continue self.position += 1 pathfile = uri + "/" + urllib.pathname2url(info.name) self.path = pathfile file = fstypes.File(pathfile, self.disk) if info.type and info.type == 2: file.add_files(self.read(pathfile, None, True)) # Directory files.append(file) if not recursive: self.disk.add(file) if (self._cancel_import_disk): return None if not recursive: self.progress_bar = None return self.disk else: return files
def __verify_permissions(self): if self.__uri.startswith("file:///"): local_path = get_local_path_from_uri(self.__uri) if access(local_path, R_OK): if not access(local_path, W_OK): self.__readonly = True else: raise PermissionError else: scheme = get_uri_scheme(self.__uri) if not scheme in self.__writable_vfs_schemes: self.__readonly = True return
def get_file_items(self, window, items): paths = [] for item in items: if self.valid_uri(item.get_uri()): path = unicode(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") paths.append(path) self.nautilusVFSFile_table[path] = item if len(paths) == 0: return [] # log.debug("get_file_items() called") return NautilusMainContextMenu(self, window.get_data("base_dir"), paths).get_menu()
def get_file_items_full(self, provider, window, items): """ Menu activated with items selected. Nautilus also calls this function when rendering submenus, even though this is not needed since the entire menu has already been returned. Note that calling C{nautilusVFSFile.invalidate_extension_info()} will also cause get_file_items to be called. @type window: NautilusNavigationWindow @param window: @type items: list of NautilusVFSFile @param items: @rtype: list of MenuItems @return: The context menu entries to add to the menu. """ paths = [] for item in items: if self.valid_uri(item.get_uri()): path = six.text_type( gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") paths.append(path) self.nautilusVFSFile_table[path] = item if len(paths) == 0: return [] # log.debug("get_file_items_full() called") paths_str = "-".join(paths) conditions_dict = None if paths_str in self.items_cache: conditions_dict = self.items_cache[paths_str] if conditions_dict and conditions_dict != "in-progress": conditions = NautilusMenuConditions(conditions_dict) menu = NautilusMainContextMenu(self, window.get_data("base_dir"), paths, conditions).get_menu() return menu if conditions_dict != "in-progress": self.status_checker.generate_menu_conditions_async( provider, window.get_data("base_dir"), paths, self.update_file_items) self.items_cache[path] = "in-progress" return ()
def __runtest(self, widget, tab=None): print "running tests" self.check_lines.clear() filepath = self.__active_document.get_uri() if filepath.startswith('file://'): #filepath = filepath[7:] try: import gnomevfs except: import matevfs as gnomevfs filepath = gnomevfs.get_local_path_from_uri(filepath) doc = self.__active_document command_lines = [] extension = path.splitext(filepath)[1] if extension in self.extensions: for command in self.extensions[extension]: command_os = self.commands[command] print "--> Running test: %s" % (command_os % filepath) command_out = os.popen(command_os % filepath) command_lines = command_out.readlines() self.check_lines.append( (-1, -1, "--> Running test: %s" % (command_os % filepath))) for line in command_lines: if ':' in line: line = line.strip() splitted_line = line.split(":") if len(splitted_line) >= 3: col_number = -1 row_number = -1 filename = splitted_line[0] startcol = 0 if os.name == 'nt': startcol = 1 # c:\...: filename = splitted_line[ 0] + ":" + splitted_line[1] if splitted_line[startcol + 1].strip().isdigit(): row_number = splitted_line[startcol + 1].strip() if splitted_line[startcol + 2].strip().isdigit(): col_number = splitted_line[startcol + 2].strip() show_text = ':'.join(splitted_line[startcol + 1:]) self.check_lines.append( (row_number, col_number, show_text)) else: self.check_lines.append((-1, -1, line))
def save_rating(self, menu_item, rating, files): for file in files: if self.is_image_type(file): path = gnomevfs.get_local_path_from_uri(file.get_uri()) try: image = pyexiv2.Image(path) image.readMetadata() image[self.RATING_KEY] = rating image.writeMetadata() file.invalidate_extension_info() except IOError, e: print e
def get_filebrowser_root(self): base = u'/apps/gedit-2/plugins/filebrowser/on_load' if is_mate: base = u'/apps/pluma/plugins/filebrowser/on_load' client = gconf.client_get_default() client.add_dir(base, gconf.CLIENT_PRELOAD_NONE) path = base + u'/virtual_root' val = client.get(path) if val != None: path_string = val.get_string() #idx = path_string.find('://') + 3 #return val.get_string()[idx:] return gnomevfs.get_local_path_from_uri(path_string) return None
def path(self): """The base directory to traverse set by the user.""" path_ = self.path_comboentry.get_active_text() self.update_comboentry(self.path_comboentry, path_) if path_ in (self.WORKING_DIRECTORY, '', None): path_ = '.' elif (path_ == self.CURRENT_FILE) or (path_ == self.CURRENT_FILE_DIR): document = self.active_document path_ = os.path.dirname(document.get_uri_for_display()) elif path_ == self.FILE_BROWSER_ROOT: key = u'/apps/%s/plugins/filebrowser/on_load/virtual_root' % APP_KEY root_uri = gconf.client_get_default().get_string(key) path_ = gnomevfs.get_local_path_from_uri(root_uri) return path_
def get_local_path_from_uri(uri): if uri != None and uri != "": if not isinstance(uri, basestring): unicodeUri = unicode(str(uri), 'utf-8') match = pattern.match(uri) if match: try: local_path = gnomevfs.get_local_path_from_uri(uri) #print "converting URI to local_path" return local_path except Exception, e: print "Converting URI: \"%s\"to local path failed" % uri traceback.print_exc() print "URI calss: %s" % uri.__class__
def __launch_vfsmimeapp(self, app, uri, cwd=None): if uri.startswith('file://'): uri = gnomevfs.get_local_path_from_uri(uri) if hasattr(gnomevfs, 'mime_application_launch'): gnomevfs.mime_application_launch(app, uri) else: exec_components = app[2].split(' ') replaced_f = False for i,component in enumerate(exec_components): if component == '%f': exec_components[i] = uri replaced_f = True if not replaced_f: exec_components.append(uri) subprocess.Popen(exec_components, stdout=sys.stdout, stderr=sys.stderr, cwd=cwd)
def on_drag_data_received(self, widget, dc, x, y, sel_data, info, timestamp): print sel_data content = sel_data.get_text() print content if content.startswith("file:///"): import gnomevfs print content path = gnomevfs.get_local_path_from_uri(content) print path f = open(path.strip(), "r") lyrics = f.read() f.close() else: lyrics = content self.setUnsynchLyrics(lyrics)
def update_file_info(self, file): rating = "" if self.is_image_type(file): path = gnomevfs.get_local_path_from_uri(file.get_uri()) try: image = pyexiv2.Image(path) image.readMetadata() if self.RATING_KEY in image.exifKeys(): rating = image[self.RATING_KEY] file.add_emblem("photorate-%s" % int(rating)) except IOError, e: print e
def get_background_items_profile(self, window, item): import cProfile import rabbitvcs.util.helper path = six.text_type(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8").replace("/", ":") profile_data_file = os.path.join( rabbitvcs.util.helper.get_home_folder(), "checkerservice_%s.stats" % path) prof = cProfile.Profile() retval = prof.runcall(self.get_background_items_real, window, item) prof.dump_stats(profile_data_file) log.debug("Dumped: %s" % profile_data_file) return retval
def get_background_items_profile(self, window, item): import cProfile import rabbitvcs.util.helper path = unicode(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8").replace("/", ":") profile_data_file = os.path.join( rabbitvcs.util.helper.get_home_folder(), "checkerservice_%s.stats" % path) prof = cProfile.Profile() retval = prof.runcall(self.get_background_items_real, window, item) prof.dump_stats(profile_data_file) log.debug("Dumped: %s" % profile_data_file) return retval
def get_file_items_full(self, provider, window, items): """ Menu activated with items selected. Nautilus also calls this function when rendering submenus, even though this is not needed since the entire menu has already been returned. Note that calling C{nautilusVFSFile.invalidate_extension_info()} will also cause get_file_items to be called. @type window: NautilusNavigationWindow @param window: @type items: list of NautilusVFSFile @param items: @rtype: list of MenuItems @return: The context menu entries to add to the menu. """ paths = [] for item in items: if self.valid_uri(item.get_uri()): path = unicode(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") paths.append(path) self.nautilusVFSFile_table[path] = item if len(paths) == 0: return [] # log.debug("get_file_items_full() called") paths_str = "-".join(paths) conditions_dict = None if paths_str in self.items_cache: conditions_dict = self.items_cache[paths_str] if conditions_dict and conditions_dict != "in-progress": conditions = NautilusMenuConditions(conditions_dict) menu = NautilusMainContextMenu(self, window.get_data("base_dir"), paths, conditions).get_menu() return menu if conditions_dict != "in-progress": self.status_checker.generate_menu_conditions_async(provider, window.get_data("base_dir"), paths, self.update_file_items) self.items_cache[path] = "in-progress" return ()
def open_file(self, document, uri, encoding, readonly=False): try: self.__encoding = encoding self.__document = document self.__uri = uri self.__filename = get_local_path_from_uri(uri) self.__readonly = readonly self.__handle = None self.__temp_buffer = "" self.__writable_vfs_schemes = ["ssh", "sftp", "smb", "dav", "davs", "ftp"] self.__get_file_info() self.__verify_permissions() self.__get_mime_type() self.__load_uri() self.__create_backup() self.__set_document_configuration() except: raise
def _check(self, doc): uri = doc.get_uri() #path = uri.replace('file://', '') try: import gnomevfs except: import matevfs as gnomevfs path = gnomevfs.get_local_path_from_uri(uri) res = [] res += self._check_pep8(path) res += self._check_pyflakes(path) for e in sorted(res, key=lambda x: x['line']): self._results[doc].add(e['line'], e['msg']) return
def __launch_vfsmimeapp(self, app, uri, cwd=None): if uri.startswith('file://'): uri = gnomevfs.get_local_path_from_uri(uri) if hasattr(gnomevfs, 'mime_application_launch'): gnomevfs.mime_application_launch(app, uri) else: exec_components = app[2].split(' ') replaced_f = False for i, component in enumerate(exec_components): if component == '%f': exec_components[i] = uri replaced_f = True if not replaced_f: exec_components.append(uri) subprocess.Popen(exec_components, stdout=sys.stdout, stderr=sys.stderr, cwd=cwd)
def __open_cb(self, handle, result): try: self.__handle = handle if self.__uri.startswith("file:///"): try: local_path = get_local_path_from_uri(self.__uri) size = os.path.getsize(local_path) if not (size): size = 4096 handle.read(size, self.__read_cb) except: raise ReadFileError else: try: handle.read(4096, self.__read_cb) except: raise ReadFileError except ReadFileError: self._error(i.exception_file_read) return
def view_other_file(self, button): dialog = gtk.FileChooserDialog("Open...", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) current_document = self.window.get_active_document() #current_path = urllib.unquote( current_document.get_uri().replace("file://", "") ) current_path = gnomevfs.get_local_path_from_uri( current_document.get_uri()) dialog.set_current_folder(os.path.dirname(current_path)) filter_list = [{ "label": "All Files", "patterns": ["*"], "mime-types": [] }, { "label": "Text Files", "patterns": [], "mime-types": ["text/html", "text/plain"] }] for dict in filter_list: filter = gtk.FileFilter() filter.set_name(dict["label"]) for each in dict["patterns"]: filter.add_pattern(each) for each in dict["mime-types"]: filter.add_mime_type(each) dialog.add_filter(filter) response = dialog.run() if (response == gtk.RESPONSE_OK): self.load_other_file(dialog.get_filename()) else: pass dialog.destroy()
def receive_dnd (self, widget, context, x, y, selection, targetType, time): """ TODO """ if targetType == self.TARGET_TYPE_TEXT: # the DND data are separated by the MS-DOS newline… files = selection.data.split('\r\n') for file in files: # and the split() gives an empty last argument, we must test «file»… if file: path = gnomevfs.get_local_path_from_uri(file) logging.progress("Received %s by DND." % styles.stylize(styles.ST_PATH, path)) if os.path.exists(path): if os.path.isdir(path) or os.path.isfile(path): if path not in [ p for (p, ) in self.liststore ]: self.liststore.append((path,)) else: StatusMessage('''Sorry, can't apply keywords on %s, refusing it.''' % path) self.update_keyword_usage() self.update_notebook()
def get_background_items_full(self, provider, window, item): """ Menu activated on entering a directory. Builds context menu for File menu and for window background. @type window: NautilusNavigationWindow @param window: @type item: NautilusVFSFile @param item: @rtype: list of MenuItems @return: The context menu entries to add to the menu. """ if not self.valid_uri(item.get_uri()): return path = six.text_type(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") self.nautilusVFSFile_table[path] = item # log.debug("get_background_items_full() called") conditions_dict = None if path in self.items_cache: conditions_dict = self.items_cache[path] if conditions_dict and conditions_dict != "in-progress": conditions = NautilusMenuConditions(conditions_dict) menu = NautilusMainContextMenu(self, path, [path], conditions).get_menu() return menu window.set_data("base_dir", path) if conditions_dict != "in-progress": self.status_checker.generate_menu_conditions_async( provider, path, [path], self.update_background_items) self.items_cache[path] = "in-progress" return ()
def get_property_pages(self, items): paths = [] for item in items: if self.valid_uri(item.get_uri()): path = unicode(gnomevfs.get_local_path_from_uri(item.get_uri()), "utf-8") if self.vcs_client.is_in_a_or_a_working_copy(path): paths.append(path) self.nautilusVFSFile_table[path] = item if len(paths) == 0: return [] label = rabbitvcs.ui.property_page.PropertyPageLabel(claim_domain=False).get_widget() page = rabbitvcs.ui.property_page.PropertyPage(paths, claim_domain=False).get_widget() ppage = nautilus.PropertyPage('RabbitVCS::PropertyPage', label, page) return [ppage]
def update_file_info(self, file): """ Callback from Nautilus to get the file status. """ if file.get_uri_scheme() != 'file': return path = gnomevfs.get_local_path_from_uri(file.get_uri()) c = pysvn.Client() try: entry = c.info(path) except: return if not entry: return # We'll scan the files during idle time, so add it to our stack self.scanStack.append(file) if len(self.scanStack) == 1: gobject.idle_add(self.OnIdle)
import cPickle except ImportError: #py3 import pickle as cPickle if __name__ == '__main__': import matplotlib matplotlib.use('Agg') # from pylab import * from matplotlib.pyplot import * from numpy import * dpi = 100. inputFile = gnomevfs.get_local_path_from_uri(sys.argv[1]) outputFile = sys.argv[2] thumbSize = int(sys.argv[3]) #logging.debug('Input File: %s\n' % inputFile) #logging.debug('Ouput File: %s\n' % outputFile) #logging.debug('Thumb Size: %s\n' % thumbSize) #def generateThumbnail(inputFile, thumbsize): fid = open(inputFile) spx, spy = cPickle.load(fid) fid.close() f = figure(figsize=(thumbSize / dpi, 0.5 * thumbSize / dpi)) axes([0, 0, 1, 1])
def load_tree(self, target): """ Loads the tree information from the target backup directory """ self.treestore.clear() # Checking if the target directory is local or remote local = True try: if gnomevfs.URI(target).is_local: target = gnomevfs.get_local_path_from_uri(target) else: local = False except: pass self.local = local self.target = target # Checking if it is a readable directory if local: if not (os.path.exists(target) and os.path.isdir(target) and os.access(target, os.R_OK | os.X_OK)): self.treestore.append( None, ["Error: backups directory does not exist!"]) self.target = False else: if not (gnomevfs.exists(target) and gnomevfs.get_file_info(target).type == 2): self.treestore.append( None, ["Error: backups directory does not exist!"]) self.target = False # Get list of backup directories r = re.compile( r"^(\d{4})-(\d{2})-(\d{2})_(\d{2})[\:\.](\d{2})[\:\.](\d{2})\.\d+\..*?\.(.+)$" ) listing = [] if local and self.target: listing = os.listdir(target) listing = filter(r.search, listing) elif self.target: try: d = gnomevfs.open_directory(target) listing = [] for f in d: if f.type == 2 and f.name != "." and f.name != ".." and r.search( f.name): listing.append(f.name) except: pass # Check if these directories are complete and remove from the list those that are not for adir in listing[:]: if not gnomevfs.exists(self.target + "/" + adir + "/ver"): listing.remove(adir) continue else: if str( gnomevfs.read_entire_file(self.target + "/" + adir + "/ver"))[:3] != "1.4": listing.remove(adir) continue listing.sort() listing.reverse() self.vtree = {} if listing == []: self.treestore.append( None, ["Error: no backups found in the target directory"]) self.target = False else: for base in listing: if str(gnomevfs.read_entire_file(target + "/" + base + "/ver"))[:3] == "1.4": self.vtree[base] = str( gnomevfs.read_entire_file(target + "/" + base + "/flist")).split("\000") else: self.vtree[base] = str( gnomevfs.read_entire_file(target + "/" + base + "/flist")).split("\n") self.blist.clear() for base in listing: self.blist.append([base]) self.good = False self.on_selection_change() if self.target: self.treestore.append(None, [ "Select any of the available backups to see list of files that can be restored." ])