Example #1
0
def open_file_directory(path):
    """
        Opens the parent directory of a file, selecting the file if possible.
    """
    import gio
    f = gio.File(path)
    platform = sys.platform
    if platform == 'win32':
        # Normally we can just run `explorer /select, filename`, but Python 2
        # always calls CreateProcessA, which doesn't support Unicode. We could
        # call CreateProcessW with ctypes, but the following is more robust.
        import ctypes
        ctypes.windll.ole32.CoInitialize(None)
        # Not sure why this is always UTF-8.
        upath = f.get_path().decode('utf-8')
        pidl = ctypes.windll.shell32.ILCreateFromPathW(upath)
        ctypes.windll.shell32.SHOpenFolderAndSelectItems(pidl, 0, None, 0)
        ctypes.windll.shell32.ILFree(pidl)
        ctypes.windll.ole32.CoUninitialize()
    elif platform == 'darwin':
        subprocess.Popen(["open", f.get_parent().get_parse_name()])
    else:
        subprocess.Popen(["xdg-open", f.get_parent().get_parse_name()])
Example #2
0
    def __init__(self, loop):
        """
        Delayed setup so we don't do everything at the same time
        """
        storage.Storage.__init__(self, loop)

        self.__con = None
        self.__cur = None
        self.__last_etag = None


        self.db_path = self.__init_db_file()

        # add file monitoring so the app does not have to be restarted
        # when db file is rewritten
        def on_db_file_change(monitor, gio_file, event_uri, event):
            if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
                if gio_file.query_info(gio.FILE_ATTRIBUTE_ETAG_VALUE).get_etag() == self.__last_etag:
                    # ours
                    return
            elif event == gio.FILE_MONITOR_EVENT_CREATED:
                # treat case when instead of a move, a remove and create has been performed
                self.con = None

            if event in (gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT, gio.FILE_MONITOR_EVENT_CREATED):
                print "DB file has been modified externally. Calling all stations"
                self.dispatch_overwrite()

                # plan "b" – synchronize the time tracker's database from external source while the tracker is running
                trophies.unlock("plan_b")


        self.__database_file = gio.File(self.db_path)
        self.__db_monitor = self.__database_file.monitor_file()
        self.__db_monitor.connect("changed", on_db_file_change)

        self.run_fixtures()
Example #3
0
def file_is_supported(filename, strict=False):
    ''' whther file is supported. '''

    try:
        if os.path.getsize(filename) < 10000:
            return False
    except:
        return False

    results = gio.File(filename).get_basename().split(".")
    if len(results) < 2:
        return False
    else:
        extension = results[-1].lower()
        if extension in TRUST_AUDIO_EXT:
            return True
        elif extension in UNTRUST_AUDIO_EXT:
            try:
                fileobj = file(filename, "rb")
            except:
                return False
            try:
                header = fileobj.read(128)
                results = [
                    Kind.score(filename, fileobj, header) for Kind in FORMATS
                ]
            except:
                return False
            finally:
                fileobj.close()
            results = zip(results, FORMATS)
            results.sort()
            score, Kind = results[-1]
            if score > 0: return True
            else: return False
        else:
            return False
    def apply_uri_snippet(self, snippet, mime, uri):
        # Remove file scheme
        gfile = gio.File(uri)
        pathname = ''
        dirname = ''
        ruri = ''

        if gedit.utils.uri_has_file_scheme(uri):
            pathname = gfile.get_path()
            dirname = gfile.get_parent().get_path()

        name = os.path.basename(uri)
        scheme = gfile.get_uri_scheme()

        os.environ['GEDIT_DROP_DOCUMENT_URI'] = uri
        os.environ['GEDIT_DROP_DOCUMENT_NAME'] = name
        os.environ['GEDIT_DROP_DOCUMENT_SCHEME'] = scheme
        os.environ['GEDIT_DROP_DOCUMENT_PATH'] = pathname
        os.environ['GEDIT_DROP_DOCUMENT_DIR'] = dirname
        os.environ['GEDIT_DROP_DOCUMENT_TYPE'] = mime

        buf = self.view.get_buffer()
        location = buf.get_location()
        if location:
            ruri = location.get_uri()

        relpath = self.relative_path(ruri, uri, mime)

        os.environ['GEDIT_DROP_DOCUMENT_RELATIVE_PATH'] = relpath

        mark = buf.get_mark('gtk_drag_target')

        if not mark:
            mark = buf.get_insert()

        piter = buf.get_iter_at_mark(mark)
        self.apply_snippet(snippet, piter, piter)
Example #5
0
	def open_file(self, selection, application_info=None, exec_command=None):
		"""Open filename using config file or specified execute command"""
		if application_info is not None:
			# launch application using GIO API
			application = self.get_gio_application_by_id(application_info.id)

			if application is not None:
				if application.supports_uris():
					selection = map(lambda path: 'file://{0}'.format(path) if not path.startswith('file://') else path, selection)
					application.launch_uris(selection)
				else:
					application.launch([gio.File(path=path) for path in selection])

		elif exec_command is not None:
			# use specified command
			command = exec_command

			selection = map(lambda item: item.replace('"', '\\"'), selection)
			exec_string = self.__format_command_string(selection, command)

			# open selected file(s)
			split_command = shlex.split(exec_string, posix=False)
			test_command = split_command[0] if len(split_command) > 1 else exec_string

			if is_x_app(test_command):
				subprocess.Popen(split_command, cwd=os.path.dirname(selection[0]))

			else:
				active_object = self._application.get_active_object()

				options = Parameters()
				options.set('close_with_child', True)
				options.set('shell_command', split_command[0])
				options.set('arguments', split_command)
				options.set('path', os.path.dirname(selection[0]))

				self._application.create_terminal_tab(active_object._notebook, options)
    def _open_with_shortcut(self, shortcut, files):
        assert shortcut.type == shortcuts.SHORTCUT_TYPE_EXECUTABLE

        try:
            # Desktop and launch-panel shortcuts should have precedence over applications, so try to
            # get .desktop shortcut first...
            app = None
            if os.path.isfile(shortcut.target) and os.path.splitext(
                    shortcut.target)[1] == ".desktop":
                # with gtk_lock:
                app = gio.unix.desktop_app_info_new_from_filename(
                    shortcut.target)
            # ...and then stored application object if .desktop does not exists
            if not app:
                app = applications.applications_dict.get(shortcut.name, None)
            if app:
                # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy
                gfiles = [
                    gio.File(filepath) for filepath in files
                ]  # IGNORE:E1101 @UndefinedVariable Keep PyLint and PyDev happy
                launch_app_info(app, gfiles=gfiles)
                # app.launch([], gtk.gdk.AppLaunchContext())
        except Exception, e:
            logging.error(e)
Example #7
0
    def import_doc(self, file_uri, config, docsearch, current_doc=None):
        parent = gio.File(file_uri)
        doc = None

        idx = 0

        for child in self.__get_all_children(parent):
            if not child.get_basename().lower().endswith(".pdf"):
                continue
            try:
                # make sure we can import it
                poppler.document_new_from_file(child.get_uri(), password=None)
            except Exception:
                continue
            doc = PdfDoc(config.workdir)
            doc.path += ("_%02d" % idx)
            doc.docid += ("_%02d" % idx)
            doc.import_pdf(config, child.get_uri())
            for page in doc.pages:
                docsearch.index_page(page)
            idx += 1

        assert (doc != None)
        return (doc, doc.pages[0])
Example #8
0
    def testMountMountable(self):
        gfile = gio.File('localtest:')

        def unmount_done(mount, result):
            try:
                retval = mount.unmount_finish(result)
                self.failUnless(retval)
            finally:
                loop.quit()

        def mount_enclosing_volume_done(gfile, result):
            try:
                try:
                    retval = gfile.mount_enclosing_volume_finish(result)
                except gio.Error, e:
                    # If we run the tests too fast
                    if e.code == gio.ERROR_ALREADY_MOUNTED:
                        print('WARNING: testfile is already mounted, '
                              'skipping test')
                        loop.quit()
                        return
                    raise
                self.failUnless(retval)
            finally:
Example #9
0
def _run_command(entry, replace, background, argstr):
    tmpin = None

    cwd = None
    doc = entry.view().get_buffer()

    if not doc.is_untitled() and doc.is_local():
        gfile = gio.File(doc.get_uri())
        cwd = os.path.dirname(gfile.get_path())

    if '<!' in argstr:
        bounds = entry.view().get_buffer().get_selection_bounds()

        if not bounds:
            bounds = entry.view().get_buffer().get_bounds()

        inp = bounds[0].get_text(bounds[1])

        # Write to temporary file
        tmpin = tempfile.NamedTemporaryFile(delete=False)
        tmpin.write(inp)
        tmpin.flush()

        # Replace with temporary file
        argstr = argstr.replace('<!', '< "' + tmpin.name + '"')

    try:
        p = subprocess.Popen(argstr,
                             shell=True,
                             cwd=cwd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        stdout = p.stdout

    except Exception, e:
        raise commander.commands.exceptions.Execute('Failed to execute: ' + e)
Example #10
0
    def _get_items(cls, max_days, for_application_named=None):
        manager = recent_manager_get_default()
        items = manager.get_items()
        item_leaves = []
        for item in items:
            if for_application_named:
                low_apps = [A.lower() for A in item.get_applications()]
                if for_application_named.lower() not in low_apps:
                    continue
            day_age = item.get_age()
            if max_days >= 0 and day_age > max_days:
                continue
            if not item.exists():
                continue

            uri = item.get_uri()
            name = item.get_short_name()
            if item.is_local():
                leaf = FileLeaf(gio.File(uri).get_path())
            else:
                leaf = UrlLeaf(uri, name)
            item_leaves.append((leaf, item.get_modified()))
        for lf, date in sorted(item_leaves, key=lambda t: t[1], reverse=True):
            yield lf
Example #11
0
        def import_snippets(self, filenames):
                success = True
                
                for filename in filenames:
                        if not gedit.utils.uri_has_file_scheme(filename):
                                continue

                        # Remove file://
                        gfile = gio.File(filename)
                        filename = gfile.get_path()

                        importer = Importer(filename)
                        error = importer.run()
         
                        if error:
                                message = _('The following error occurred while importing: %s') % error
                                success = False
                                message_dialog(self.dlg, gtk.MESSAGE_ERROR, message)
                
                self.build_model(True)

                if success:
                        message = _('Import successfully completed')
                        message_dialog(self.dlg, gtk.MESSAGE_INFO, message)
Example #12
0
class CoherencePlugin(rb.Plugin, log.Loggable):

    logCategory = 'rb_coherence_plugin'

    def __init__(self):
        rb.Plugin.__init__(self)
        self.coherence = None
        self.config = gconf.client_get_default()

        if self.config.get(gconf_keys['dmc_active']) is None:
            # key not yet found represented by "None"
            self._set_defaults()

    def _set_defaults(self):
        for a in ('r', 's'):
            self.config.set_bool(gconf_keys['dm%s_active' % a], True)
            self.config.set_int(gconf_keys['dm%s_version' % a], 2)

        self.config.set_string(gconf_keys['dmr_name'],
                               "Rhythmbox UPnP MediaRenderer on {host}")
        self.config.set_string(gconf_keys['dms_name'],
                               "Rhythmbox UPnP MediaServer on {host}")

        self.config.set_bool(gconf_keys['dmc_active'], True)

    def activate(self, shell):
        from twisted.internet import gtk2reactor
        try:
            gtk2reactor.install()
        except AssertionError, e:
            # sometimes it's already installed
            self.warning("gtk2reactor already installed %r" % e)

        self.coherence = self.get_coherence()
        if self.coherence is None:
            self.warning("Coherence is not installed or too old, aborting")
            return

        self.warning("Coherence UPnP plugin activated")

        self.shell = shell
        self.sources = {}

        # Set up our icon
        the_icon = None
        face_path = os.path.join(os.path.expanduser('~'), ".face")
        if os.path.exists(face_path):
            file = gio.File(path=face_path)
            url = file.get_uri()
            info = file.query_info("standard::fast-content-type")
            mimetype = info.get_attribute_as_string(
                "standard::fast-content-type")
            pixbuf = gtk.gdk.pixbuf_new_from_file(face_path)
            width = "%s" % pixbuf.get_width()
            height = "%s" % pixbuf.get_height()
            depth = '24'
            the_icon = {
                'url': url,
                'mimetype': mimetype,
                'width': width,
                'height': height,
                'depth': depth
            }

        if self.config.get_bool(gconf_keys['dms_active']):
            # create our own media server
            from coherence.upnp.devices.media_server import MediaServer
            from MediaStore import MediaStore

            kwargs = {
                'version': self.config.get_int(gconf_keys['dms_version']),
                'no_thread_needed': True,
                'db': self.shell.props.db,
                'plugin': self
            }

            if the_icon:
                kwargs['icon'] = the_icon

            dms_uuid = self.config.get_string(gconf_keys['dms_uuid'])
            if dms_uuid:
                kwargs['uuid'] = dms_uuid

            name = self.config.get_string(gconf_keys['dms_name'])
            if name:
                name = name.replace('{host}', self.coherence.hostname)
                kwargs['name'] = name

            self.server = MediaServer(self.coherence, MediaStore, **kwargs)

            if dms_uuid is None:
                self.config.set_string(gconf_keys['dms_uuid'],
                                       str(self.server.uuid))

            self.warning("Media Store available with UUID %s" %
                         str(self.server.uuid))

        if self.config.get_bool(gconf_keys['dmr_active']):
            # create our own media renderer
            # but only if we have a matching Coherence package installed
            if self.coherence_version < (0, 5, 2):
                print "activation failed. Coherence is older than version 0.5.2"
            else:
                from coherence.upnp.devices.media_renderer import MediaRenderer
                from MediaPlayer import RhythmboxPlayer
                kwargs = {
                    "version": self.config.get_int(gconf_keys['dmr_version']),
                    "no_thread_needed": True,
                    "shell": self.shell,
                    'dmr_uuid': gconf_keys['dmr_uuid']
                }

                if the_icon:
                    kwargs['icon'] = the_icon

                dmr_uuid = self.config.get_string(gconf_keys['dmr_uuid'])
                if dmr_uuid:
                    kwargs['uuid'] = dmr_uuid

                name = self.config.get_string(gconf_keys['dmr_name'])
                if name:
                    name = name.replace('{host}', self.coherence.hostname)
                    kwargs['name'] = name

                self.renderer = MediaRenderer(self.coherence, RhythmboxPlayer,
                                              **kwargs)

                if dmr_uuid is None:
                    self.config.set_string(gconf_keys['dmr_uuid'],
                                           str(self.renderer.uuid))

                self.warning("Media Renderer available with UUID %s" %
                             str(self.renderer.uuid))

        if self.config.get_bool(gconf_keys['dmc_active']):
            self.warning("start looking for media servers")
            # watch for media servers
            louie.connect(self.detected_media_server,
                          'Coherence.UPnP.ControlPoint.MediaServer.detected',
                          louie.Any)
            louie.connect(self.removed_media_server,
                          'Coherence.UPnP.ControlPoint.MediaServer.removed',
                          louie.Any)
Example #13
0
 def file_new_cb(self, filename):
     self.stores['new'].add(gio.File(filename).get_uri())
     self.preview_window.set_status("%u new images scanned" %
                                    len(self.stores['new']))
Example #14
0
 def remove_file(self, path, relative_to=None):
     """Remove file"""
     real_path = self.real_path(path, relative_to)
     gio.File(real_path).delete()
Example #15
0
 def exists(self, path, relative_to=None):
     """Test if given path exists"""
     real_path = self.real_path(path, relative_to)
     return gio.File(real_path).query_exists()
Example #16
0
    def is_link(self, path, relative_to=None):
        """Test if given path is a link"""
        real_path = self.real_path(path, relative_to)
        info = gio.File(real_path).query_info('standard::type')

        return info.get_file_type() == gio.FILE_TYPE_SYMBOLIC_LINK
Example #17
0
 def remove_directory(self, path, relative_to=None):
     """Remove directory and optionally its contents"""
     real_path = self.real_path(path, relative_to)
     gio.File(real_path).delete()
Example #18
0
 def get_parent_path(self, path):
     """Get parent path for specified"""
     return unquote(gio.File(path).get_parent().get_uri())
Example #19
0
 def rename_path(self, source, destination, relative_to=None):
     """Rename file/directory within parents path"""
     real_source = self.real_path(source, relative_to)
     gio.File(real_source).set_display_name(destination)
Example #20
0
 def move_path(self, source, destination, relative_to=None):
     """Move path on same file system to a different parent node """
     real_source = self.real_path(source, relative_to)
     gio.File(real_source).move(gio.File(destination))
Example #21
0
 def set_mode(self, path, mode, relative_to=None):
     """Set access mode to specified path"""
     real_path = self.real_path(path, relative_to)
     gio.File(real_path).set_attribute(gio.FILE_ATTRIBUTE_UNIX_MODE,
                                       gio.FILE_ATTRIBUTE_TYPE_UINT32, mode)
Example #22
0
        menu.append(item)

        # Show the menu
        menu.show_all()

    # Open clicked bookmark
    def on_bookmark_click(self, widget, path):
        #       subprocess.Popen('/usr/bin/xdg-open %s' % path, shell = True)
        subprocess.Popen('/usr/bin/nautilus %s' % path, shell=True)

    def on_bookmarks_changed(self, filemonitor, file, other_file, event_type):
        if event_type == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
            print 'Bookmarks changed, updating menu...'
            self.update_menu()


if __name__ == "__main__":
    # Catch CTRL-C
    signal.signal(signal.SIGINT, lambda signal, frame: gtk.main_quit())

    # Run the indicator
    i = IndicatorPlaces()

    # Monitor bookmarks changes
    file = gio.File(i.BOOKMARKS_PATH)
    monitor = file.monitor_file()
    monitor.connect("changed", i.on_bookmarks_changed)

    # Main gtk loop
    gtk.main()
Example #23
0
 def binary_load_file(uri):
     if val._encoder is None:
         val.encoder = "base64"
     val.data = gio.File(uri).read().read()
    def _create_popup(self):
        paths = []

        # Open documents
        paths.append(CurrentDocumentsDirectory(self._window))

        doc = self._window.get_active_document()

        # Current document directory
        if doc and doc.is_local():
            gfile = doc.get_location()
            paths.append(gfile.get_parent())

        # File browser root directory
        if pluma.version[0] > 2 or (
                pluma.version[0] == 2 and
            (pluma.version[1] > 26 or
             (pluma.version[1] == 26 and pluma.version[2] >= 2))):
            bus = self._window.get_message_bus()

            try:
                msg = bus.send_sync('/plugins/filebrowser', 'get_root')

                if msg:
                    uri = msg.get_value('uri')

                    if uri:
                        gfile = gio.File(uri)

                        if gfile.is_native():
                            paths.append(gfile)

            except StandardError:
                pass

        # Recent documents
        paths.append(
            RecentDocumentsDirectory(screen=self._window.get_screen()))

        # Local bookmarks
        for path in self._local_bookmarks():
            paths.append(path)

        # Desktop directory
        desktopdir = self._desktop_dir()

        if desktopdir:
            paths.append(gio.File(desktopdir))

        # Home directory
        paths.append(gio.File(os.path.expanduser('~')))

        self._popup = Popup(self._window, paths, self.on_activated)

        self._popup.set_default_size(*self._plugin.get_popup_size())
        self._popup.set_transient_for(self._window)
        self._popup.set_position(gtk.WIN_POS_CENTER_ON_PARENT)

        self._window.get_group().add_window(self._popup)

        self._popup.connect('destroy', self.on_popup_destroy)
Example #25
0
    def parse_args(self, rawargs):
        usages = [("", _("Start with an empty window")),
                  ("<%s|%s>" % (_("file"), _("dir")),
                   _("Start a version control comparison")),
                  ("<%s> <%s> [<%s>]" % ((_("file"), ) * 3),
                   _("Start a 2- or 3-way file comparison")),
                  ("<%s> <%s> [<%s>]" % ((_("dir"), ) * 3),
                   _("Start a 2- or 3-way directory comparison")),
                  ("<%s> <%s>" % (_("file"), _("dir")),
                   _("Start a comparison between file and dir/file"))]
        pad_args_fmt = "%-" + str(max([len(s[0]) for s in usages])) + "s %s"
        usage_lines = ["  %prog " + pad_args_fmt % u for u in usages]
        usage = "\n" + "\n".join(usage_lines)

        parser = optparse.OptionParser(
            usage=usage,
            description=_("Meld is a file and directory comparison tool."),
            version="%prog " + version)
        parser.add_option("-L",
                          "--label",
                          action="append",
                          default=[],
                          help=_("Set label to use instead of file name"))
        parser.add_option(
            "-n",
            "--newtab",
            action="store_true",
            default=False,
            help=_("Open a new tab in an already running instance"))
        parser.add_option(
            "-a",
            "--auto-compare",
            action="store_true",
            default=False,
            help=_("Automatically compare all differing files on startup"))
        parser.add_option("-u",
                          "--unified",
                          action="store_true",
                          help=_("Ignored for compatibility"))
        parser.add_option(
            "-o",
            "--output",
            action="store",
            type="string",
            dest="outfile",
            default=None,
            help=_("Set the target file for saving a merge result"))
        parser.add_option("--auto-merge",
                          None,
                          action="store_true",
                          default=False,
                          help=_("Automatically merge files"))
        parser.add_option(
            "",
            "--comparison-file",
            action="store",
            type="string",
            dest="comparison_file",
            default=None,
            help=_("Load a saved comparison from a Meld comparison file"))
        parser.add_option(
            "",
            "--diff",
            action="callback",
            callback=self.diff_files_callback,
            dest="diff",
            default=[],
            help=_("Create a diff tab for the supplied files or folders"))
        options, args = parser.parse_args(rawargs)
        if len(args) > 3:
            parser.error(_("too many arguments (wanted 0-3, got %d)") % \
                         len(args))
        elif options.auto_merge and len(args) < 3:
            parser.error(_("can't auto-merge less than 3 files"))
        elif options.auto_merge and any([os.path.isdir(f) for f in args]):
            parser.error(_("can't auto-merge directories"))

        new_window = True
        open_paths = self.window.open_paths
        if options.newtab:
            if not dbus_app:
                print(_("D-Bus error; comparisons will open in a new window."))
            else:
                # Note that we deliberately discard auto-compare and -merge
                # options here; these are not supported via dbus yet.
                open_paths = lambda f, *x: dbus_app.OpenPaths(f, 0)
                new_window = False

        for files in options.diff:
            open_paths(files)

        if options.comparison_file or (len(args) == 1
                                       and args[0].endswith(".meldcmp")):
            path = options.comparison_file or args[0]
            comparison_file_path = os.path.expanduser(path)
            gio_file = gio.File(path=comparison_file_path)
            try:
                tab = self.window.append_recent(gio_file.get_uri())
            except (IOError, ValueError):
                parser.error(_("Error reading saved comparison file"))
        elif args:
            tab = open_paths(args, options.auto_compare, options.auto_merge)
        else:
            tab = None

        if options.label and tab:
            tab.set_labels(options.label)

        if not self.window.has_pages():
            self.window.append_new_comparison()

        if options.outfile and tab and isinstance(tab, filediff.FileDiff):
            tab.set_merge_output_file(options.outfile)

        return new_window
import os
import gobject, gio
import gtk
import gnome, gconf
import gnomekeyring as keyring
import xml
import urllib
import urlparse
import threading
import zipfile

magnatune_partner_id = "rhythmbox"

# URIs
magnatune_song_info_uri = gio.File(
    uri="http://magnatune.com/info/song_info_xml.zip")
magnatune_buy_album_uri = "https://magnatune.com/buy/choose?"
magnatune_api_download_uri = "http://%s:%[email protected]/buy/membership_free_dl_xml?"

magnatune_in_progress_dir = gio.File(
    path=rb.user_data_dir()).resolve_relative_path('magnatune')
magnatune_cache_dir = gio.File(
    path=rb.user_cache_dir()).resolve_relative_path('magnatune')

magnatune_song_info = os.path.join(magnatune_cache_dir.get_path(),
                                   'song_info.xml')
magnatune_song_info_temp = os.path.join(magnatune_cache_dir.get_path(),
                                        'song_info.zip.tmp')


class MagnatuneSource(rb.BrowserSource):
Example #27
0
 def binary_save_file(uri):
     fp = gio.File(uri).replace(etag='', make_backup=False)
     fp.write(val.data)
     fp.close()
Example #28
0
 def drag_got_data_cb(self, wid, context, x, y, selection, info, time):
     draglog("drag_got_data_cb%s", (wid, context, x, y, selection, info, time))
     #draglog("%s: %s", type(selection), dir(selection))
     #draglog("%s: %s", type(context), dir(context))
     targets = context.targets
     actions = context.actions
     def xid(w):
         if w:
             return w.xid
         return 0
     dest_window = xid(context.dest_window)
     source_window = xid(context.get_source_window())
     suggested_action = context.get_suggested_action()
     draglog("drag_got_data_cb context: source_window=%#x, dest_window=%#x, suggested_action=%s, actions=%s, targets=%s", source_window, dest_window, suggested_action, actions, targets)
     dtype = selection.get_data_type()
     fmt = selection.get_format()
     l = selection.get_length()
     target = selection.get_target()
     text = selection.get_text()
     uris = selection.get_uris()
     draglog("drag_got_data_cb selection: data type=%s, format=%s, length=%s, target=%s, text=%s, uris=%s", dtype, fmt, l, target, text, uris)
     if not uris:
         return
     filelist = []
     for uri in uris:
         if not uri:
             continue
         if not uri.startswith("file://"):
             draglog.warn("Warning: cannot handle drag-n-drop URI '%s'", uri)
             continue
         filename = strtobytes(uri[len("file://"):].rstrip("\n\r"))
         abspath = os.path.abspath(filename)
         if not os.path.isfile(abspath):
             draglog.warn("Warning: '%s' is not a file", abspath)
             continue
         filelist.append(abspath)
     draglog("drag_got_data_cb: will try to upload: %s", filelist)
     pending = set(filelist)
     #when all the files have been loaded / failed,
     #finish the drag and drop context so the source knows we're done with them:
     def file_done(filename):
         if not pending:
             return
         try:
             pending.remove(filename)
         except:
             pass
         if not pending:
             context.finish(True, False, time)
     for filename in filelist:
         def got_file_info(gfile, result):
             draglog("got_file_info(%s, %s)", gfile, result)
             file_info = gfile.query_info_finish(result)
             basename = gfile.get_basename()
             ctype = file_info.get_content_type()
             size = file_info.get_size()
             draglog("file_info(%s)=%s ctype=%s, size=%s", filename, file_info, ctype, size)
             def got_file_data(gfile, result, user_data=None):
                 data, filesize, entity = gfile.load_contents_finish(result)
                 draglog("got_file_data(%s, %s, %s) entity=%s", gfile, result, user_data, entity)
                 file_done(filename)
                 openit = self._client.remote_open_files
                 draglog.info("sending file %s (%i bytes)", basename, filesize)
                 self._client.send_file(filename, "", data, filesize=filesize, openit=openit)
             gfile.load_contents_async(got_file_data, user_data=(filename, True))
         try:
             import gio
             gfile = gio.File(filename)
             #basename = gf.get_basename()
             gfile.query_info_async("standard::*", got_file_info, flags=gio.FILE_QUERY_INFO_NONE)
         except Exception as e:
             log.error("Error: cannot upload '%s':", filename)
             log.error(" %s", e)
             file_done(filename)
Example #29
0
def run_external_tool(window, node):
    # Configure capture environment
    try:
        cwd = os.getcwd()
    except OSError:
        cwd = os.getenv('HOME')

    capture = Capture(node.command, cwd)
    capture.env = os.environ.copy()
    capture.set_env(PLUMA_CWD=cwd)

    view = window.get_active_view()
    if view is not None:
        # Environment vars relative to current document
        document = view.get_buffer()
        uri = document.get_uri()

        # Current line number
        piter = document.get_iter_at_mark(document.get_insert())
        capture.set_env(PLUMA_CURRENT_LINE_NUMBER=str(piter.get_line() + 1))

        # Current line text
        piter.set_line_offset(0)
        end = piter.copy()

        if not end.ends_line():
            end.forward_to_line_end()

        capture.set_env(PLUMA_CURRENT_LINE=piter.get_text(end))

        # Selected text (only if input is not selection)
        if node.input != 'selection' and node.input != 'selection-document':
            bounds = document.get_selection_bounds()

            if bounds:
                capture.set_env(
                    PLUMA_SELECTED_TEXT=bounds[0].get_text(bounds[1]))

        bounds = current_word(document)
        capture.set_env(PLUMA_CURRENT_WORD=bounds[0].get_text(bounds[1]))

        capture.set_env(PLUMA_CURRENT_DOCUMENT_TYPE=document.get_mime_type())

        if uri is not None:
            gfile = gio.File(uri)
            scheme = gfile.get_uri_scheme()
            name = os.path.basename(uri)
            capture.set_env(PLUMA_CURRENT_DOCUMENT_URI=uri,
                            PLUMA_CURRENT_DOCUMENT_NAME=name,
                            PLUMA_CURRENT_DOCUMENT_SCHEME=scheme)
            if pluma.utils.uri_has_file_scheme(uri):
                path = gfile.get_path()
                cwd = os.path.dirname(path)
                capture.set_cwd(cwd)
                capture.set_env(PLUMA_CURRENT_DOCUMENT_PATH=path,
                                PLUMA_CURRENT_DOCUMENT_DIR=cwd)

        documents_uri = [
            doc.get_uri() for doc in window.get_documents()
            if doc.get_uri() is not None
        ]
        documents_path = [
            gio.File(uri).get_path() for uri in documents_uri
            if pluma.utils.uri_has_file_scheme(uri)
        ]
        capture.set_env(PLUMA_DOCUMENTS_URI=' '.join(documents_uri),
                        PLUMA_DOCUMENTS_PATH=' '.join(documents_path))

    flags = capture.CAPTURE_BOTH

    if not node.has_hash_bang():
        flags |= capture.CAPTURE_NEEDS_SHELL

    capture.set_flags(flags)

    # Get input text
    input_type = node.input
    output_type = node.output

    # Get the panel
    panel = window.get_data("ExternalToolsPluginWindowData")._output_buffer
    panel.clear()

    if output_type == 'output-panel':
        panel.show()

    # Assign the error output to the output panel
    panel.set_process(capture)

    if input_type != 'nothing' and view is not None:
        if input_type == 'document':
            start, end = document.get_bounds()
        elif input_type == 'selection' or input_type == 'selection-document':
            try:
                start, end = document.get_selection_bounds()

                print start, end
            except ValueError:
                if input_type == 'selection-document':
                    start, end = document.get_bounds()

                    if output_type == 'replace-selection':
                        document.select_range(start, end)
                else:
                    start = document.get_iter_at_mark(document.get_insert())
                    end = start.copy()

        elif input_type == 'line':
            start = document.get_iter_at_mark(document.get_insert())
            end = start.copy()
            if not start.starts_line():
                start.set_line_offset(0)
            if not end.ends_line():
                end.forward_to_line_end()
        elif input_type == 'word':
            start = document.get_iter_at_mark(document.get_insert())
            end = start.copy()
            if not start.inside_word():
                panel.write(_('You must be inside a word to run this command'),
                            panel.command_tag)
                return
            if not start.starts_word():
                start.backward_word_start()
            if not end.ends_word():
                end.forward_word_end()

        input_text = document.get_text(start, end)
        capture.set_input(input_text)

    # Assign the standard output to the chosen "file"
    if output_type == 'new-document':
        tab = window.create_tab(True)
        view = tab.get_view()
        document = tab.get_document()
        pos = document.get_start_iter()
        capture.connect('stdout-line', capture_stdout_line_document, document,
                        pos)
        document.begin_user_action()
        view.set_editable(False)
        view.set_cursor_visible(False)
    elif output_type != 'output-panel' and output_type != 'nothing' and view is not None:
        document.begin_user_action()
        view.set_editable(False)
        view.set_cursor_visible(False)

        if output_type == 'insert':
            pos = document.get_iter_at_mark(document.get_mark('insert'))
        elif output_type == 'replace-selection':
            document.delete_selection(False, False)
            pos = document.get_iter_at_mark(document.get_mark('insert'))
        elif output_type == 'replace-document':
            document.set_text('')
            pos = document.get_end_iter()
        else:
            pos = document.get_end_iter()
        capture.connect('stdout-line', capture_stdout_line_document, document,
                        pos)
    elif output_type != 'nothing':
        capture.connect('stdout-line', capture_stdout_line_panel, panel)
        document.begin_user_action()

    capture.connect('stderr-line', capture_stderr_line_panel, panel)
    capture.connect('begin-execute', capture_begin_execute_panel, panel, view,
                    node.name)
    capture.connect('end-execute', capture_end_execute_panel, panel, view,
                    output_type)

    # Run the command
    capture.execute()

    if output_type != 'nothing':
        document.end_user_action()
Example #30
0
    def get_stat(self, path, relative_to=None, extended=False, follow=False):
        """Return file statistics"""
        real_path = self.real_path(path, relative_to)

        try:
            # try getting file stats
            flags = (gio.FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                     gio.FILE_QUERY_INFO_NONE)[follow]

            file_stat = gio.File(real_path).query_info(
                'standard::size,unix::mode,unix::uid,unix::gid'
                'time::access,time::modified,time::changed,'
                'standard::type,unix:device,unix::inode', flags)

        except:
            # handle invalid files/links
            if not extended:
                result = FileInfo(
                    size=0,
                    mode=0,
                    user_id=0,
                    group_id=0,
                    time_modify=0,
                    type=FileType.INVALID,
                )

            else:
                result = FileInfoExtended(size=0,
                                          mode=0,
                                          i_mode=0,
                                          user_id=0,
                                          group_id=0,
                                          time_access=0,
                                          time_modify=0,
                                          time_change=0,
                                          type=FileType.INVALID,
                                          device=0,
                                          inode=0)

            return result

        # get file type
        file_type = file_stat.get_file_type()

        if file_type == gio.FILE_TYPE_SYMBOLIC_LINK:
            item_type = FileType.LINK

        elif file_type == gio.FILE_TYPE_DIRECTORY:
            item_type = FileType.DIRECTORY

        elif file_type == gio.FILE_TYPE_SPECIAL:
            item_type = FileType.DEVICE_BLOCK

        else:
            item_type = FileType.REGULAR

        if not extended:
            # create normal file information
            result = FileInfo(
                size=file_stat.get_size(),
                mode=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_MODE),
                user_id=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_UID),
                group_id=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_GID),
                time_modify=file_stat.get_attribute_uint64(
                    gio.FILE_ATTRIBUTE_TIME_MODIFIED),
                type=item_type,
            )
        else:
            # create extended file information
            result = FileInfoExtended(
                size=file_stat.get_size(),
                mode=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_MODE),
                i_mode=0,
                user_id=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_UID),
                group_id=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_GID),
                time_access=file_stat.get_attribute_uint64(
                    gio.FILE_ATTRIBUTE_TIME_ACCESS),
                time_modify=file_stat.get_attribute_uint64(
                    gio.FILE_ATTRIBUTE_TIME_MODIFIED),
                time_change=file_stat.get_attribute_uint64(
                    gio.FILE_ATTRIBUTE_TIME_CHANGED),
                type=item_type,
                device=file_stat.get_attribute_uint32(
                    gio.FILE_ATTRIBUTE_UNIX_DEVICE),
                inode=file_stat.get_attribute_uint64(
                    gio.FILE_ATTRIBUTE_UNIX_INODE))

        return result