Beispiel #1
0
    def testBackslash(self):
        self._setUp()
        for f in glob.glob(test_folder + "*"):
            if os.path.isdir(f):
                continue
            local = os.path.abspath(f)
            uri = gnomevfs.get_uri_from_local_path(local)
            self.p.add_file(uri)
        local = os.path.abspath("test/backslash.sfv")
        uri = gnomevfs.get_uri_from_local_path(local)
        self.p.save_hashfile(uri)
        self._tearDown()

        f = open(local, 'r')
        c = f.read().replace('/', '\\')
        f.close()
        f = open(local, 'w')
        f.write(c)
        f.close()

        self._setUp()
        self._load(uri)
        changed, missing, error = self.p.update_file_list()

        self.assert_(changed == 0 and missing == 0 and error == 0, "")
        self._tearDown()
	def testBackslash(self):
		self._setUp()
		for f in glob.glob( test_folder + "*"):
			if os.path.isdir(f):
				continue
			local = os.path.abspath(f)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.add_file(uri)
		local = os.path.abspath("test/backslash.sfv")
		uri = gnomevfs.get_uri_from_local_path(local)
		self.p.save_hashfile(uri)
		self._tearDown()
		
		f = open(local, 'r')
		c = f.read().replace('/','\\')
		f.close()
		f = open(local, 'w')
		f.write(c)
		f.close()
		
		self._setUp()
		self._load(uri)
		changed, missing, error = self.p.update_file_list()

		self.assert_( 
			changed == 0 and missing == 0 and error == 0
			, "")
		self._tearDown()
Beispiel #3
0
    def testMultiple(self):
        self._setUp()
        count = 0
        for f in glob.glob(test_folder + "*"):
            if os.path.isdir(f):
                continue
            local = os.path.abspath(f)
            uri = gnomevfs.get_uri_from_local_path(local)
            self.p.new_hashfile()
            self.p.add_file(uri)
            local = os.path.abspath("test/hash-%d.sfv" % count)
            uri = gnomevfs.get_uri_from_local_path(local)
            self.p.save_hashfile(uri)
            count += 1

        self.p.new_hashfile()
        for i in range(count):
            local = os.path.abspath("test/hash-%d.sfv" % i)
            uri = gnomevfs.get_uri_from_local_path(local)
            self.p.load_hashfile(uri)

        self.assert_(
            len(self.p.files) == count,
            "%d hashfiles loaded, expected %d" % (len(self.p.files), count))

        self._tearDown()
	def _save(self, format):
		for f in glob.glob( test_folder + "*"):
			if os.path.isdir(f):
				continue
			local = os.path.abspath(f)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.add_file(uri)
		local = os.path.abspath("test/test.%s" % format)
		uri = gnomevfs.get_uri_from_local_path(local)
		self.p.save_hashfile(uri)
		return uri
Beispiel #5
0
 def _save(self, format):
     for f in glob.glob(test_folder + "*"):
         if os.path.isdir(f):
             continue
         local = os.path.abspath(f)
         uri = gnomevfs.get_uri_from_local_path(local)
         self.p.add_file(uri)
     local = os.path.abspath("test/test.%s" % format)
     uri = gnomevfs.get_uri_from_local_path(local)
     self.p.save_hashfile(uri)
     return uri
	def testRelative(self):
		self._setUp()
		for f in glob.glob( test_folder + "*"):
			if os.path.isdir(f):
				continue
			local = os.path.abspath(f)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.add_file(uri)
		local = os.path.abspath("test/relative/test.sfv")
		uri = gnomevfs.get_uri_from_local_path(local)
		self.p.save_hashfile(uri)
		self._tearDown()
Beispiel #7
0
 def testRelative(self):
     self._setUp()
     for f in glob.glob(test_folder + "*"):
         if os.path.isdir(f):
             continue
         local = os.path.abspath(f)
         uri = gnomevfs.get_uri_from_local_path(local)
         self.p.add_file(uri)
     local = os.path.abspath("test/relative/test.sfv")
     uri = gnomevfs.get_uri_from_local_path(local)
     self.p.save_hashfile(uri)
     self._tearDown()
Beispiel #8
0
    def get_file_menuitems(self, file_obj, context=None):
        uri = gnomevfs.get_uri_from_local_path(file_obj.path)
        if file_obj.test_directory(follow_link=True):
            return []

        apps = gnomevfs.mime_get_all_applications(file_obj.mimetype)
        menuitems = []
        pbcache = PixbufCache.getInstance()

        def add_menuitem(app):
            _logger.debug("adding app %r", app)
            if have_gnomedesktop:
                desktop = gnomedesktop.item_new_from_basename(app[0], 0)
                iconpath = desktop.get_icon(self.__itheme)
            else:
                iconpath = None
            menuitem = gtk.ImageMenuItem(_('Open with %s') % (app[1], ))
            if iconpath:
                pbuf = pbcache.get(iconpath,
                                   trystock=True,
                                   stocksize=gtk.ICON_SIZE_MENU)
                img = gtk.image_new_from_pixbuf(pbuf)
                menuitem.set_property('image', img)
            menuitem.connect("activate", self.__on_appmenu_activated, app, uri,
                             context)
            menuitems.append(menuitem)

        for app in apps:
            add_menuitem(app)
        return menuitems
Beispiel #9
0
 def get_file_menuitems(self, file_obj, context=None):
     uri = gnomevfs.get_uri_from_local_path(file_obj.path)
     if file_obj.test_directory(follow_link=True):
         return []
     
     apps = gnomevfs.mime_get_all_applications(file_obj.mimetype)
     menuitems = []
     pbcache = PixbufCache.getInstance()
     def add_menuitem(app):
         _logger.debug("adding app %r", app)
         if have_gnomedesktop:
             desktop = gnomedesktop.item_new_from_basename(app[0], 0)
             iconpath = desktop.get_icon(self.__itheme)
         else:
             iconpath = None
         menuitem = gtk.ImageMenuItem(_('Open with %s') % (app[1],))
         if iconpath:
             pbuf = pbcache.get(iconpath, trystock=True, stocksize=gtk.ICON_SIZE_MENU)
             img = gtk.image_new_from_pixbuf(pbuf)
             menuitem.set_property('image', img)
         menuitem.connect("activate", self.__on_appmenu_activated, app, uri, context)
         menuitems.append(menuitem) 
     for app in apps:
         add_menuitem(app)
     return menuitems
Beispiel #10
0
    def load_other_file(self, source, raw_filename = True):
        current_tab = self.window.get_active_tab()

        self.same_document[current_tab] = False

        self.split_views[current_tab].remove(self.split_views[current_tab].get_children()[1])

        new_document = gedit.Document()#.gedit_document_new()

        if (raw_filename):
            #new_document.load("file://" + source.replace(" ", "%20"), self.encoding, 1, True)
            new_document.load(gnomevfs.get_uri_from_local_path(source), self.encoding, 1, True)

        else:
            new_document.load(source, self.encoding, 1, True)

        new_view = gedit.View(new_document)#.gedit_view_new(new_document)

        new_document.connect("mark-set", self.update_line_column_data)

        #new_document.save(0)

        self.alt_views[current_tab] = new_document

        sw = gtk.ScrolledWindow()
        sw.add(new_view)

        self.split_views[current_tab].add2(sw)

        self.label_other_document.set_label(os.path.basename(source).replace("%20", " "))

        self.window.get_active_tab().show_all()
Beispiel #11
0
    def _goto(self, item_no):
        self._l.debug("Entered: item[%d]" % item_no)

        where =  self._item_locations[item_no]
        if isinstance(where, gtk.TextMark):
            self._set_cursor_pos(where)
        else:
            (file_name, line_no, col_no) = where
            self._l.info("Document no currently loaded %s:%d:%d" % (file_name, line_no, col_no))
        
            #uri = "file://" + file_name
            uri = gnomevfs.get_uri_from_local_path(file_name)
            if gedit.utils.uri_exists(uri):
                # First check that we are not in the middle of opening this document
                if self._get_tab_for_uri(uri):
                    self._l.info("    but is loading...")
                    return
                
                tab = self._window.create_tab_from_uri(uri, None, 0, False, True)
                doc = tab.get_document()
                self._l.debug("Now opening [%s]" % doc.get_uri_for_display())
                doc.connect("loaded", self._doc_loaded_cb, item_no)
            else:
                md = gtk.MessageDialog(
                    self._window,
                    gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL,
                    gtk.MESSAGE_ERROR,
                    gtk.BUTTONS_CLOSE,
                    "Could not find '%s'" % file_name)
                md.run()
                md.destroy()
Beispiel #12
0
    def load_other_file(self, source, raw_filename=True):
        current_tab = self.window.get_active_tab()

        self.same_document[current_tab] = False

        self.split_views[current_tab].remove(
            self.split_views[current_tab].get_children()[1])

        new_document = gedit.Document()  #.gedit_document_new()

        if (raw_filename):
            #new_document.load("file://" + source.replace(" ", "%20"), self.encoding, 1, True)
            new_document.load(gnomevfs.get_uri_from_local_path(source),
                              self.encoding, 1, True)

        else:
            new_document.load(source, self.encoding, 1, True)

        new_view = gedit.View(new_document)  #.gedit_view_new(new_document)

        new_document.connect("mark-set", self.update_line_column_data)

        #new_document.save(0)

        self.alt_views[current_tab] = new_document

        sw = gtk.ScrolledWindow()
        sw.add(new_view)

        self.split_views[current_tab].add2(sw)

        self.label_other_document.set_label(
            os.path.basename(source).replace("%20", " "))

        self.window.get_active_tab().show_all()
Beispiel #13
0
    def _goto(self, item_no):
        self._l.debug("Entered: item[%d]" % item_no)

        where = self._item_locations[item_no]
        if isinstance(where, gtk.TextMark):
            self._set_cursor_pos(where)
        else:
            (file_name, line_no, col_no) = where
            self._l.info("Document no currently loaded %s:%d:%d" %
                         (file_name, line_no, col_no))

            #uri = "file://" + file_name
            uri = gnomevfs.get_uri_from_local_path(file_name)
            if gedit.utils.uri_exists(uri):
                # First check that we are not in the middle of opening this document
                if self._get_tab_for_uri(uri):
                    self._l.info("    but is loading...")
                    return

                tab = self._window.create_tab_from_uri(uri, None, 0, False,
                                                       True)
                doc = tab.get_document()
                self._l.debug("Now opening [%s]" % doc.get_uri_for_display())
                doc.connect("loaded", self._doc_loaded_cb, item_no)
            else:
                md = gtk.MessageDialog(
                    self._window,
                    gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL,
                    gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                    "Could not find '%s'" % file_name)
                md.run()
                md.destroy()
Beispiel #14
0
	def get_uri(self):
		"""
		Returns the uri of the dragitem
		Throws if not FILE_TYPE
		"""
		from gnomevfs import get_uri_from_local_path
		uri = get_uri_from_local_path(self.object)
		return uri
Beispiel #15
0
 def __init__(self, path):
     '''
     Initialises the UI.
     '''
     InterfaceView.__init__(self, "property_editor", "PropertyEditor")
     
     note = rabbitvcs.ui.wraplabel.WrapLabel(PROP_EDITOR_NOTE)
     note.set_use_markup(True)
     
     self.get_widget("note_box").pack_start(note)        
     self.get_widget("note_box").show_all()
             
     self.path = path
     
     self.get_widget("wc_text").set_text(gnomevfs.get_uri_from_local_path(os.path.realpath(path)))
             
     self.vcs = rabbitvcs.vcs.VCS()
     self.svn = self.vcs.svn()
             
     if not self.svn.is_versioned(self.path):
         rabbitvcs.ui.dialog.MessageBox(_("File is not under version control."))
         self.close()
         return
     
     self.get_widget("remote_uri_text").set_text(self.svn.get_repo_url(path))
            
     self.table = rabbitvcs.ui.widget.Table(
         self.get_widget("table"),
         [gobject.TYPE_STRING, rabbitvcs.ui.widget.TYPE_ELLIPSIZED,
          gobject.TYPE_STRING, rabbitvcs.ui.widget.TYPE_STATUS], 
         [_("Name"), _("Value"), _("Reserved"), _("Status")],
         
         filters=[
             {
                 "callback": rabbitvcs.ui.widget.long_text_filter,
                 "user_data": {
                     "cols": 0,
                     "column": 1
                 }
             },
             
             {
                 "callback": rabbitvcs.ui.widget.translate_filter,
                 "user_data": {
                     "column": 3
                 }
             }],
             
         callbacks={
             "row-activated":  self.on_table_row_activated,
             "mouse-event":   self.on_table_mouse_event,
             "key-event":     self.on_table_key_event
         }
     )
     self.table.allow_multiple()
     
     self.refresh()
Beispiel #16
0
def get_thumbnail_path(file):
    uri = gnomevfs.get_uri_from_local_path(file.path)
    factory = gnome.ui.ThumbnailFactory(gnome.ui.THUMBNAIL_SIZE_NORMAL)

    lookup = factory.lookup(uri, 0)

    if lookup != None:
        return lookup
    else:
        return generate_thumbnail(factory, uri)
Beispiel #17
0
 def _on_open_config(self, action):
     print(_("reloading shortcuts from config file: %s") % accel_map_file)
     uri = "file://" + accel_map_file
     try:
         import gedit
         import gnomevfs
         uri = gnomevfs.get_uri_from_local_path(accel_map_file)
     except:
         import matevfs
         uri = matevfs.get_uri_from_local_path(accel_map_file)
     self._window.create_tab_from_uri(uri, None, 0, True, True)
Beispiel #18
0
def vfs_clean_uri(uri):
	"""return an uri from an uri or a local path"""
	try:
		gnomevfs.URI(uri)
		gnomevfs.Handle(uri)
	except : #gnomevfs.InvalidURIError:
		# maybe a local path ?
		local = os.path.abspath(uri)
		if os.path.exists(local):
			uri = gnomevfs.get_uri_from_local_path(local)
		uri = gnomevfs.escape_host_and_path_string(uri)
	return uri
Beispiel #19
0
def vfs_clean_uri(uri):
    """return an uri from an uri or a local path"""
    try:
        gnomevfs.URI(uri)
        gnomevfs.Handle(uri)
    except:  #gnomevfs.InvalidURIError:
        # maybe a local path ?
        local = os.path.abspath(uri)
        if os.path.exists(local):
            uri = gnomevfs.get_uri_from_local_path(local)
        uri = gnomevfs.escape_host_and_path_string(uri)
    return uri
Beispiel #20
0
 def __init__( self, plugin, window ):
   self._window = window
   self._plugin = plugin
   self._encoding = gedit.encoding_get_current()
   self._rootpath = os.getcwd()
   self._rootdir = gnomevfs.get_uri_from_local_path(self._rootpath)
   self._show_hidden = False
   self._suggestion = None
   self._git = False
   self._liststore = None
   self._last_pattern = ""
   self._init_glade()
   self._insert_menu()
Beispiel #21
0
    def getFreeDesktopThumbnail(filename):
        "if we have gnome libs available, try to find a system-generated thumbnail"
        try:
            import gnome.ui
            import gnomevfs
        except:
            return None

        path = os.path.abspath(filename)
        uri = gnomevfs.get_uri_from_local_path(path)
        thumb = gnome.ui.thumbnail_path_for_uri(uri, "normal")
        if os.path.exists(thumb):
            return thumb
        return None
Beispiel #22
0
    def _download(self, row):
        self.active_downloads += 1
        track = self._get_track(row)

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

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

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

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

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

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

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

        scheme, host, path, _, _, _ = urlparse(url)
        factory = ProgressDownloader(url, openfile, started, progress)
        reactor.connectTCP(host, 80, factory)
        factory.deferred.addCallback(complete).addErrback(error)
        track.start(factory)
Beispiel #23
0
 def create_tab(self, uri):
     try:
         win = gedit.app_get_default().get_active_window()
         try:
             import gnomevfs
         except:
             import matevfs as gnomevfs
         uri = gnomevfs.get_uri_from_local_path(uri)
         win.create_tab_from_uri(uri, None, 1, False, False)
     except:
         try:
             import gedit
             os.system('gedit %s' % uri)
         except:
             os.system('pluma "%s"' % uri)
	def testMultiple(self):
		self._setUp()
		count=0
		for f in glob.glob( test_folder + "*"):
			if os.path.isdir(f):
				continue
			local = os.path.abspath(f)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.new_hashfile()
			self.p.add_file(uri)
			local = os.path.abspath("test/hash-%d.sfv" % count)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.save_hashfile(uri)
			count += 1

		self.p.new_hashfile()
		for i in range(count):
			local = os.path.abspath("test/hash-%d.sfv" % i)
			uri = gnomevfs.get_uri_from_local_path(local)
			self.p.load_hashfile(uri)

		self.assert_(len(self.p.files) == count, "%d hashfiles loaded, expected %d" % (len(self.p.files), count))

		self._tearDown()
Beispiel #25
0
def on_file_lines_row_activated(treeview, path, view_column, plugin):
    """Open the file and jump to the line."""
    treestore = treeview.get_model()
    piter = treestore.get_iter(path)
    base_dir = treestore.get_value(piter, 4)
    path = treestore.get_value(piter, 0)
    if base_dir is None or path is None:
        # There is not enough information to open a document.
        return
    #uri = 'file://%s' % os.path.abspath(os.path.join(base_dir, path))
    uri = gnomevfs.get_uri_from_local_path(
        os.path.abspath(os.path.join(base_dir, path)))
    line_no = treestore.get_value(piter, 2) - 1
    if line_no < 0:
        line_no = 0
    plugin.activate_open_doc(uri, jump_to=line_no)
Beispiel #26
0
    def _download(self, row):
        self.active_downloads += 1
        track = self._get_track(row)

        def started():
            self.model.set_value(row, ICON_COLUMN, icons['started'])
        def progress(rate_estimator):
            self.model.set_value(row, PROGRESS_COLUMN,
                                 100*rate_estimator.fraction_read())
            self.model.set_value(row, PROGRESS_TIME_COLUMN,
                                 format_time(rate_estimator.remaining_time()))
        def complete(result):
            if track.status != 'aborted':
                self.model.set_value(row, PROGRESS_COLUMN, 100)
                self.model.set_value(row, ICON_COLUMN, icons['completed'])
                track.completed()
            self._download_done()
        def error(failure):
            print failure.getErrorMessage()
            self.model.set_value(row, ICON_COLUMN, icons['error'])
            track.error(failure)
            self._download_done()

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

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

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

        scheme,host,path,_,_,_ = urlparse(url)
        factory = ProgressDownloader(url, openfile, started, progress)
        reactor.connectTCP(host, 80, factory)
        factory.deferred.addCallback(complete).addErrback(error)
        track.start(factory)
Beispiel #27
0
 def getFreeDesktopThumbnail(filename):
     "if we have gnome libs available, try to find a system-generated thumbnail"
     path = os.path.abspath(filename)
     thumb = None
     try:
         import gnome.ui
         import gnomevfs
     except:
         # alternative method
         import hashlib
         fhash = hashlib.md5(("file://"+path).encode("utf8")).hexdigest()
         thumb = os.path.join(os.path.expanduser("~"),".thumbnails","normal",fhash+".png")
     else:
         uri = gnomevfs.get_uri_from_local_path(path)
         thumb = gnome.ui.thumbnail_path_for_uri(uri, "normal")
     if thumb and os.path.exists(thumb):
         return thumb
     return None
Beispiel #28
0
    def __init__(self):
        self.scanStack = []
        self.allvfs = {}
        self.inv_dirs = set()

        from tortoisehg.util import menuthg
        self.hgtk = paths.find_in_path(thg_main)
        self.menu = menuthg.menuThg()
        self.notify = os.path.expanduser('~/.tortoisehg/notify')
        try:
            f = open(self.notify, 'w')
            f.close()
            ds_uri = gnomevfs.get_uri_from_local_path(self.notify)
            self.gmon = gnomevfs.monitor_add(ds_uri,
                      gnomevfs.MONITOR_FILE, self.notified)
        except (gnomevfs.NotSupportedError, IOError), e:
            debugf('no notification because of %s', e)
            self.notify = ''
Beispiel #29
0
def vfs_clean_uri(uri):
	"""return an uri from an uri or a local path"""
	try:
		gnomevfs.URI(uri)
		gnomevfs.Handle(uri)
	except : #gnomevfs.InvalidURIError:
		try:
			uri_ = uri.replace('%5C', '/') # convert backslashes
			gnomevfs.URI(uri_)
			gnomevfs.Handle(uri_)
			uri = uri_
		except : #gnomevfs.InvalidURIError:
			# maybe a local path ?
			local = os.path.abspath(uri)
			if os.path.exists(local):
				uri = gnomevfs.get_uri_from_local_path(local)
			uri = gnomevfs.escape_host_and_path_string(uri)
	return uri
Beispiel #30
0
def vfs_clean_uri(uri):
    """return an uri from an uri or a local path"""
    try:
        gnomevfs.URI(uri)
        gnomevfs.Handle(uri)
    except:  #gnomevfs.InvalidURIError:
        try:
            uri_ = uri.replace('%5C', '/')  # convert backslashes
            gnomevfs.URI(uri_)
            gnomevfs.Handle(uri_)
            uri = uri_
        except:  #gnomevfs.InvalidURIError:
            # maybe a local path ?
            local = os.path.abspath(uri)
            if os.path.exists(local):
                uri = gnomevfs.get_uri_from_local_path(local)
            uri = gnomevfs.escape_host_and_path_string(uri)
    return uri
Beispiel #31
0
def import_thumbnail(filepath):
    uriUTF = "file://" + quote(filepath).encode('utf-8')#quote(path).encode('utf-8')              #change path to utf-8 path
    uri = "file://" + filepath
    import hashlib
    hash = hashlib.md5(uriUTF).hexdigest()
    thumbFactory = ui.ThumbnailFactory(ui.THUMBNAIL_SIZE_NORMAL)
    path = os.path.expanduser('~') + "/.thumbnails/normal/"+hash+".png"
    if path is None or not os.path.exists(path):
        path = ui.thumbnail_path_for_uri(gnomevfs.get_uri_from_local_path(os.path.abspath(uri)), 'normal')
    if path is None or not os.path.exists(path):
        path = thumbFactory.lookup(uri,0)
    if path is None or not os.path.exists(path):
        #create thumbnail
        mimetype, _ = mimetypes.guess_type(uri, strict=False)
        result = create_thumbnail_via_gnome(mimetype, uri)
        if result == False:
            return create_thumbnail(uri, hash, mimetype)
        #TODO prepare for not exist file after create thumbnail
    new_path = copy_file_and_change_path(path, os.path.basename(path))
    return new_path
Beispiel #32
0
	def __init__( self, plugin, window ):
		self._window = window
		self._plugin = plugin
		self._encoding = gedit.encoding_get_current()
		#self._rootdir = "file://" + os.getcwd()
		self._rootdir = gnomevfs.get_uri_from_local_path(os.getcwd())
		
		#self._tmpfile = os.path.join(tempfile.gettempdir(), 'snapopen.%s.%s' % (os.getuid(),os.getpid()))
		user = ""
		try:
			import getpass
			user = getpass.getuser()
		except:
			pass
		self._tmpfile = os.path.join(tempfile.gettempdir(), 'snapopen.%s.%s' % (user,os.getpid()))
		
		self._show_hidden = False
		self._liststore = None;
		self._init_glade()
		self._insert_menu()
Beispiel #33
0
 def choose_patch_path(self):
     path = ""
     
     dialog = gtk.FileChooserDialog(
         _("Create Patch"),
         None,
         gtk.FILE_CHOOSER_ACTION_SAVE,(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                       gtk.STOCK_SAVE, gtk.RESPONSE_OK))
     dialog.set_do_overwrite_confirmation(True)
     dialog.set_default_response(gtk.RESPONSE_OK)
     dialog.set_current_folder_uri(
         gnomevfs.get_uri_from_local_path(get_common_directory(self.paths))
     )
     response = dialog.run()
     
     if response == gtk.RESPONSE_OK:
         path = dialog.get_filename()
         
     dialog.destroy()
     
     return path
Beispiel #34
0
    def _parse_doc_to_model(self):
        """ Parse the given document and write the tags to a gtk.TreeModel.
        
        The parser uses the ctags command from the shell to create a ctags file,
        then parses the file, and finally populates a treemodel. """
        # refactoring noise    
        doc = self.document
        ls = self.model        
        ls.clear()
        tmpfile = self._generate_tagfile_from_document(doc)
        if tmpfile is None: return ls
        
        # A list of lists. Matches the order found in tag files.
        # identifier, path to file, line number, type, and then more magical things
        tokenlist = [] 
        h = open(tmpfile)
        for r in h.readlines():
            tokens = r.strip().split("\t")
            if tokens[0][:2] == "!_": continue

            # convert line numbers to an int
            tokens[2] =  int(filter( lambda x: x in '1234567890', tokens[2] ))
            
            # prepend container elements, append member elements. Do this to
            # make sure that container elements are created first.
            if self._is_container(tokens): tokenlist = [tokens] + tokenlist
            else: tokenlist.append(tokens)
        h.close()

        # add tokens to the treestore---------------------------------------
        containers = { None: None } # keep dict: token's name -> treeiter
        
        # iterate through the list of tags, 
        # Note: Originally sorted by line number, bit it did break some
        # formatting in c
        for tokens in tokenlist:
        
            # skip enums
            #if self.__get_type(tokens) in 'de': continue
        
            # append current token to parent iter, or to trunk when there is none
            parent = self._get_parent(tokens)
            
            if parent in containers: node = containers[parent]
            else:
                # create a dummy element in case the parent doesn't exist
                node = ls.append( None, [parent,"",0,""] )
                containers[parent] = node
            
            # escape blanks in file path
            tokens[1] = str( gnomevfs.get_uri_from_local_path(tokens[1]) )
            
            # make sure tokens[4] contains type code
            if len(tokens) == 3: tokens.append("")
            else: tokens[3] = self.__get_type(tokens)
            
            # append to treestore
            it = ls.append( node, tokens[:4] )
            
            # if this element was a container, remember its treeiter
            if self._is_container(tokens):
                containername = self._get_container_name(tokens)
                containers[ containername ] = it
            
        # remove temp file
        os.remove(tmpfile)
Beispiel #35
0
    def __put_files(self, tree_iter=None, show_hidden=False):
        """
        Put files of the current directory starting in tree_iter.
        
        @param tree_iter: The tree iter where the files will be put.
        @type tree_iter: A TreeIter object.
        
        @param show_hidden: True if this function put hidden files too.
        @type show_hidden: A boolean.
        
        @return: True if the current directory has some files,
        False if the current directory is empty.
        @rtype: A boolean.
        """

        filter = self.filter_text
        
        directory = self.flist.get_current_dir()
        theme = gtk.icon_theme_get_default()
        #self.treeview.set_model(self.treestore)
        
        if tree_iter == None:
            icon = \
            self.treeview.render_icon(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_MENU)
            
            # Setting combobox elements
            self.liststore_dir.clear()
            
            dir_list = self.__get_dir_list()
            
            for i in dir_list:
                self.liststore_dir.append(None, [icon, i])
                
            self.combobox_dir.handler_block(self.combobox_dir_signal)
            self.combobox_dir.set_active(len(self.liststore_dir) - 1)
            self.combobox_dir.handler_unblock(self.combobox_dir_signal)
            
        dir_info = gnomevfs.get_file_info(directory)
        
        if not (dir_info.permissions & gnomevfs.PERM_USER_EXEC):
            return False
                
        files = self.flist.get_files(show_hidden)        
        
        if len(files) == 0:
            if tree_iter == None:
                self.treestore.append(None, [None, _('(Empty)')])
            return False
        else:
            info = theme.lookup_icon("text-x-generic", gtk.ICON_SIZE_MENU, 0)
            
            if info == None:
                # text-x-generic icon doesn't exist
                icon_f = self.treeview.render_icon(gtk.STOCK_FILE,
                                         gtk.ICON_SIZE_MENU)
            else:
                icon_f = info.load_icon()
            
            for i in files:
                if i.type == gnomevfs.FILE_TYPE_DIRECTORY:
                    icon = self.treeview.render_icon(gtk.STOCK_DIRECTORY,
                                                     gtk.ICON_SIZE_MENU)
                    #direc = self.__get_current_directory(directory)
                    i_iter = self.treestore.append(tree_iter, [icon, i.name])
                    self.treestore.append(i_iter, [None, _('(Empty)')])
                elif i.type == gnomevfs.FILE_TYPE_REGULAR:
                    file_dir = os.path.join(directory, i.name)
                    uri = gnomevfs.get_uri_from_local_path(file_dir)
                    mime = gnomevfs.get_mime_type(uri)
                    t = mime.split("/")
                    
                    #if mime in self.except_mimes or t[0] == "text":
                    if Files.get_language_from_mime(mime) != None \
                    or mime == "" or t[0] == "text":
                        if filter == "":
                            i_iter = self.treestore.append(tree_iter, [icon_f, i.name])
                        else:
                            if self.__parse_filter(i.name, filter) != None:
                                i_iter = self.treestore.append(tree_iter, [icon_f, i.name])
                            
            self.treeview.columns_autosize()

            return True
Beispiel #36
0
 def launch_edit_file(self, path):
     uri = gnomevfs.get_uri_from_local_path(path) 
     app = gnomevfs.mime_get_default_application("text/plain")
     self.__launch_vfsmimeapp(app, uri)
 def get_uri(self, path):
     return gnomevfs.get_uri_from_local_path(path)
Beispiel #38
0
    def find_all_in_dir(self,
                        parent_it,
                        dir_path,
                        file_pattern,
                        search_pattern,
                        find_options,
                        replace_flg=False):
        #start_time = time.time()
        if search_pattern == "":
            return

        #d_list = []
        file_list = []

        if find_options['INCLUDE_SUBFOLDER'] == True:
            grep_cmd = ['grep', '-E', '-l', '-R', search_pattern, dir_path]
        else:
            grep_cmd = ['grep', '-E', '-l', search_pattern, dir_path]
        p = subprocess.Popen(grep_cmd, stdout=subprocess.PIPE)
        for f in p.stdout:
            if self.check_file_pattern(f, unicode(file_pattern, 'utf-8')):
                file_list.append(f[:-1])
        '''
		for root, dirs, files in os.walk(unicode(dir_path, 'utf-8')):
			for d in dirs:
				d_list.append(os.path.join(root, d))
			for f in files:
				if self.check_file_pattern(f, unicode(file_pattern, 'utf-8')):
					if find_options['INCLUDE_SUBFOLDER'] == True:
						file_list.append(os.path.join(root, f))
					else:
						if os.path.dirname(f) not in d_list:
							file_list.append(os.path.join(root, f))
				self.find_ui.do_events()
		#'''

        #mid_time = time.time()
        #print 'Use ' + str(mid_time-start_time) + ' seconds to find files.'

        for file_path in file_list:
            if os.path.isfile(file_path):
                temp_doc = gedit.Document()
                #file_uri = "file://" + urllib.pathname2url(file_path.encode('utf-8'))
                #file_uri = ('file://' + file_path).encode('utf-8')
                file_uri = gnomevfs.get_uri_from_local_path(file_path)
                try:
                    temp_doc.load(file_uri,
                                  gedit.encoding_get_from_charset('utf-8'), 0,
                                  False)
                except:
                    print 'Can not open ' + file_uri + '.'
                    continue
                f_temp = open(file_path, 'r')
                try:
                    text = unicode(f_temp.read(), 'utf-8')
                except:
                    text = f_temp.read()
                f_temp.close()
                temp_doc.set_text(text)

                self.advanced_find_all_in_doc(parent_it, temp_doc,
                                              search_pattern, find_options,
                                              replace_flg)
                self.find_ui.do_events()
Beispiel #39
0
    def _parse_doc_to_model(self):
        """ Parse the given document and write the tags to a gtk.TreeModel.
        
        The parser uses the ctags command from the shell to create a ctags file,
        then parses the file, and finally populates a treemodel. """
        # refactoring noise
        doc = self.document
        ls = self.model
        ls.clear()
        tmpfile = self._generate_tagfile_from_document(doc)
        if tmpfile is None: return ls

        # A list of lists. Matches the order found in tag files.
        # identifier, path to file, line number, type, and then more magical things
        tokenlist = []
        h = open(tmpfile)
        for r in h.readlines():
            tokens = r.strip().split("\t")
            if tokens[0][:2] == "!_": continue

            # convert line numbers to an int
            tokens[2] = int(filter(lambda x: x in '1234567890', tokens[2]))

            # prepend container elements, append member elements. Do this to
            # make sure that container elements are created first.
            if self._is_container(tokens): tokenlist = [tokens] + tokenlist
            else: tokenlist.append(tokens)
        h.close()

        # add tokens to the treestore---------------------------------------
        containers = {None: None}  # keep dict: token's name -> treeiter

        # iterate through the list of tags,
        # Note: Originally sorted by line number, bit it did break some
        # formatting in c
        for tokens in tokenlist:

            # skip enums
            #if self.__get_type(tokens) in 'de': continue

            # append current token to parent iter, or to trunk when there is none
            parent = self._get_parent(tokens)

            if parent in containers: node = containers[parent]
            else:
                # create a dummy element in case the parent doesn't exist
                node = ls.append(None, [parent, "", 0, ""])
                containers[parent] = node

            # escape blanks in file path
            tokens[1] = str(gnomevfs.get_uri_from_local_path(tokens[1]))

            # make sure tokens[4] contains type code
            if len(tokens) == 3: tokens.append("")
            else: tokens[3] = self.__get_type(tokens)

            # append to treestore
            it = ls.append(node, tokens[:4])

            # if this element was a container, remember its treeiter
            if self._is_container(tokens):
                containername = self._get_container_name(tokens)
                containers[containername] = it

        # remove temp file
        os.remove(tmpfile)
Beispiel #40
0
 def get_mime_type(path):
     return gnomevfs.get_mime_type(gnomevfs.get_uri_from_local_path(path))
Beispiel #41
0
    def __parse_doc_to_model(self):
        """ Parse the given document and write the tags to a gtk.TreeModel.

        The parser uses the ctags command from the shell to create a ctags file,
        then parses the file, and finally populates a treemodel.
        """

        # refactoring noise
        doc = self.document
        ls = self.model
        ls.clear()

        # make sure this is a local file (ie. not via ftp or something)
        try:
            if doc.get_uri()[:4] != "file": return ls
        except:
            return

        docpath = doc.get_uri_for_display()
        path, filename = os.path.split(docpath)
        if filename.find(".") != -1:
            arg = path + os.sep + filename[:filename.rfind(".")] + ".*"
        else:
            arg = docpath

        # simply replacing blanks is the best variant because both gnomevfs
        # and the fs understand it.
        arg = arg.replace(" ","\ ")

        # create tempfile
        h, tmpfile = tempfile.mkstemp()

        # launch ctags
        command = "ctags -n -f %s %s"%(tmpfile,arg)
        os.system(command)

        # print "command:",command

        # create list of tokens from the ctags file-------------------------

        # A list of lists. Matches the order found in tag files.
        # identifier, path to file, line number, type, and then more magical things
        tokenlist = []

        h = open(tmpfile)
        enumcounter = 0
        for r in h.readlines():
            tokens = r.strip().split("\t")
            if tokens[0][:2] == "!_": continue

            # convert line numbers to an int
            tokens[2] =  int(filter( lambda x: x in '1234567890', tokens[2] ))

            # prepend container elements, append member elements. Do this to
            # make sure that container elements are created first.
            if self.__is_container(tokens): tokenlist = [tokens] + tokenlist
            else: tokenlist.append(tokens)

            # hack: remember the number of enums without parents for later grouping
            if self.__get_type(tokens) == 'e' and self.__get_parent(tokens) is None:
                enumcounter += 1

        # add tokens to the treestore---------------------------------------
        containers = { None: None } # keep dict: token's name -> treeiter

        #if enumcounter > 0:
        #    node = ls.append( None, ["Enumerators","",0,""] )
        #    containers["Enumerators"] = node

        # used to sort the list of tokens by file, then by line number
        def cmpfunc(a,b):
            # by filename
            #if a[1] < b[1]: return -1
            #if a[1] > a[1]: return 1

            # by line number
            if a[2] < b[2]: return -1
            if a[2] > b[2]: return 1
            return 0


        # iterate through the list of tags, sorted by their line number
        # a token is a list. Order matches tag file order (name,path,line,type,...)
        for tokens in sorted(tokenlist,cmpfunc):

            # skip enums
            if self.__get_type(tokens) in 'de': continue

            #print self.__get_type(tokens),tokens[0],self.__get_parent(tokens)

            # append current token to parent iter, or to trunk when there is none
            parent = self.__get_parent(tokens)

            # hack: group enums without parents:
            if parent is None and self.__get_type(tokens) == 'e': parent = "Enumerators"

            if parent in containers: node = containers[parent]
            else:
                # create a dummy element in case the parent doesn't exist
                node = ls.append( None, [parent,"",0,""] )
                containers[parent] = node

            # escape blanks in file path
            tokens[1] = str( gnomevfs.get_uri_from_local_path(tokens[1]) )


            # make sure tokens[4] contains type code
            if len(tokens) == 3: tokens.append("")
            else: tokens[3] = self.__get_type(tokens)

            # append to treestore
            it = ls.append( node, tokens[:4] )

            # if this element was a container, remember it's treeiter
            if self.__is_container(tokens): containers[tokens[0]] = it

        # remove temp file
        os.remove(tmpfile)
Beispiel #42
0
 def get_uri(path):
     return gnomevfs.get_uri_from_local_path(path)
Beispiel #43
0
 def launch_edit_file(self, path):
     uri = gnomevfs.get_uri_from_local_path(path)
     app = gnomevfs.mime_get_default_application("text/plain")
     self.__launch_vfsmimeapp(app, uri)
Beispiel #44
0
 def get_mime_type(path):
     return gnomevfs.get_mime_type(gnomevfs.get_uri_from_local_path(path))
Beispiel #45
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
Beispiel #46
0
    def __parse_doc_to_model(self):
        """ Parse the given document and write the tags to a gtk.TreeModel.
        
        The parser uses the ctags command from the shell to create a ctags file,
        then parses the file, and finally populates a treemodel.        
        """

        # refactoring noise
        doc = self.document
        ls = self.model
        ls.clear()

        # make sure this is a local file (ie. not via ftp or something)
        try:
            if doc.get_uri()[:4] != "file": return ls
        except:
            return

        docpath = doc.get_uri_for_display()
        path, filename = os.path.split(docpath)
        if filename.find(".") != -1:
            arg = path + os.sep + filename[:filename.rfind(".")] + ".*"
        else:
            arg = docpath

        # simply replacing blanks is the best variant because both gnomevfs
        # and the fs understand it.
        arg = arg.replace(" ", "\ ")

        # create tempfile
        h, tmpfile = tempfile.mkstemp()

        # launch ctags
        command = "ctags -n -f %s %s" % (tmpfile, arg)
        os.system(command)

        print "command:", command

        # create list of tokens from the ctags file-------------------------

        # A list of lists. Matches the order found in tag files.
        # identifier, path to file, line number, type, and then more magical things
        tokenlist = []

        h = open(tmpfile)
        enumcounter = 0
        for r in h.readlines():
            tokens = r.strip().split("\t")
            if tokens[0][:2] == "!_": continue

            # convert line numbers to an int
            tokens[2] = int(filter(lambda x: x in '1234567890', tokens[2]))

            # prepend container elements, append member elements. Do this to
            # make sure that container elements are created first.
            if self.__is_container(tokens): tokenlist = [tokens] + tokenlist
            else: tokenlist.append(tokens)

            # hack: remember the number of enums without parents for later grouping
            if self.__get_type(tokens) == 'e' and self.__get_parent(
                    tokens) == None:
                enumcounter += 1

        # add tokens to the treestore---------------------------------------
        containers = {None: None}  # keep dict: token's name -> treeiter

        #if enumcounter > 0:
        #    node = ls.append( None, ["Enumerators","",0,""] )
        #    containers["Enumerators"] = node

        # used to sort the list of tokens by file, then by line number
        def cmpfunc(a, b):
            # by filename
            #if a[1] < b[1]: return -1
            #if a[1] > a[1]: return 1

            # by line number
            if a[2] < b[2]: return -1
            if a[2] > b[2]: return 1
            return 0

        # iterate through the list of tags, sorted by their line number
        # a token is a list. Order matches tag file order (name,path,line,type,...)
        for tokens in sorted(tokenlist, cmpfunc):

            # skip enums
            if self.__get_type(tokens) in 'de': continue

            #print self.__get_type(tokens),tokens[0],self.__get_parent(tokens)

            # append current token to parent iter, or to trunk when there is none
            parent = self.__get_parent(tokens)

            # hack: group enums without parents:
            if parent is None and self.__get_type(tokens) == 'e':
                parent = "Enumerators"

            if parent in containers: node = containers[parent]
            else:
                # create a dummy element in case the parent doesn't exist
                node = ls.append(None, [parent, "", 0, ""])
                containers[parent] = node

            # escape blanks in file path
            tokens[1] = str(gnomevfs.get_uri_from_local_path(tokens[1]))

            # make sure tokens[4] contains type code
            if len(tokens) == 3: tokens.append("")
            else: tokens[3] = self.__get_type(tokens)

            # append to treestore
            it = ls.append(node, tokens[:4])

            # if this element was a container, remember it's treeiter
            if self.__is_container(tokens): containers[tokens[0]] = it

        # remove temp file
        os.remove(tmpfile)
Beispiel #47
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