Exemplo n.º 1
0
 def start_fspot(button):
     #would be cleaner if we could autostart using dbus,
     #dbus.SessionBus().start_service_by_name(self.SERVICE_PATH)
     gobject.spawn_async(("f-spot", ),
                         flags=gobject.SPAWN_SEARCH_PATH
                         | gobject.SPAWN_STDOUT_TO_DEV_NULL
                         | gobject.SPAWN_STDERR_TO_DEV_NULL)
Exemplo n.º 2
0
 def _start_uinput_bridge(self):
     """
     Connect to a running uinput bridge. If none is running, we invoke one
     using dbus activation or (if activation is not present) we invoke
     uinputbridge our self.
     """
     dbus_db = dinterface(dbus.SessionBus(), 
                          "org.freedesktop.DBus", 
                          "/", 
                          "org.freedesktop.DBus")
     if not "org.uinputbridge" in dbus_db.ListNames() and \
        not "org.uinputbridge" in dbus_db.ListActivatableNames():
         gobject.spawn_async([self.path.get_binfile("uinputbridge")],
                             flags=gobject.SPAWN_STDOUT_TO_DEV_NULL | 
                                   gobject.SPAWN_STDERR_TO_DEV_NULL )
         count = 0
         while count < 10:
             count += 1
             if "org.uinputbridge" in dbus_db.ListNames():
                 count = 11
             time.sleep(1)
         if count == 10:
             raise UinputServiceStartException()
     self.uinputbridge = dinterface(dbus.SessionBus(), 
                                    "org.uinputbridge", 
                                    "/UInputBridge", 
                                    "org.uinputbridge")
Exemplo n.º 3
0
    def showManual(self, data=None):
        argv = []
        argv.append("/usr/bin/firefox")

        uri = "http://seedit.sourceforge.net/"

        argv.append(uri)

        prevusername = os.environ["USER"]
        prevlogname = os.environ["LOGNAME"]

        if os.environ.has_key("USERHELPER_UID"):
            uidstr = os.environ["USERHELPER_UID"]
            prevuid = os.getuid()
            uid = int(uidstr)
            username = pwd.getpwuid(uid)[0]
            os.environ["USER"] = username
            os.environ["LOGNAME"] = username
        try:
            gobject.spawn_async(argv)
        except:
            message = _("There was a problem launching the web browser")
            self.showMessageDialog(gtk.MESSAGE_ERROR, message)
        os.environ["USER"] = prevusername
        os.environ["LOGNAME"] = prevlogname
Exemplo n.º 4
0
 def start_fspot(button):
     #would be cleaner if we could autostart using dbus,
     #dbus.SessionBus().start_service_by_name(self.SERVICE_PATH)
     gobject.spawn_async(
             ("f-spot",), 
             flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_STDOUT_TO_DEV_NULL|gobject.SPAWN_STDERR_TO_DEV_NULL
     )
Exemplo n.º 5
0
 def activate_status_icon(self, status_icon):
         self.show_status_icon(False)
         gobject.spawn_async([GKSU_PATH, UPDATEMANAGER])
         if self.get_terminate_after_activate():
                 gtk.main_quit()
                 sys.exit(0)
         else:
                 self.schedule_next_check_for_checks()
Exemplo n.º 6
0
def _start_matchbox():
    cmd = ['matchbox-window-manager']

    cmd.extend(['-use_titlebar', 'no'])
    cmd.extend(['-theme', 'sugar'])
    cmd.extend(['-kbdconfig', os.path.join(config.data_path, 'kbdconfig')])

    gobject.spawn_async(cmd, flags=gobject.SPAWN_SEARCH_PATH)
	def __start_indexer_process(self):
		try:
			from gobject import spawn_async
			spawn_async([self.__python_executable, self.__executable,
			self.__editor.python_path], working_directory=self.__cwd)
		except:
			pass
		return False
Exemplo n.º 8
0
 def start_wine(self, *args):
     if self.wine_pid:
         logging.info("running command line: %s" % ' '.join(str(x) for x in args))
         gobject.spawn_async(
             ['wine', 'explorer', '/desktop=%s' % self.desktop_name] + [str(x) for x in args],
             flags=gobject.SPAWN_SEARCH_PATH)
     else:
         self.to_run.append(args)
Exemplo n.º 9
0
	def __start(self):
		from gobject import spawn_async
		from sys import executable
		from SCRIBES.Globals import python_path
		folder = self.__get_save_process_folder()
		module = self.__get_save_process_executable(folder)
		spawn_async([executable, module, python_path], working_directory=folder)
		return False
Exemplo n.º 10
0
	def __start_process(self):
		from gobject import spawn_async, GError
		try:
			args = [self.__python_executable, self.__executable, self.__editor.python_path]
			spawn_async(args, working_directory=self.__cwd)
		except GError:
			pass
		return False
Exemplo n.º 11
0
 def call(self):
     """
     Execute the supplied command by spawning a subprozess
     """
     self.logger.debug("Calling: " + str(self._to_array()))
     gobject.spawn_async( self._to_array(), 
                          flags= gobject.SPAWN_STDOUT_TO_DEV_NULL | 
                                 gobject.SPAWN_STDERR_TO_DEV_NULL )
Exemplo n.º 12
0
 def activate_status_icon(self, status_icon):
         self.show_status_icon(False)
         gobject.spawn_async([GKSU_PATH, UPDATEMANAGER])
         if self.get_terminate_after_activate():
                 gtk.main_quit()
                 sys.exit(0)
         else:
                 self.schedule_next_check_for_checks()
Exemplo n.º 13
0
    def cmd_spawn(self, cmd):
        """
            Run cmd in a shell.

            Example:

                spawn("firefox")
        """
        gobject.spawn_async([os.environ['SHELL'], '-c', cmd])
Exemplo n.º 14
0
    def cmd_spawn(self, cmd):
        """
            Run cmd in a shell.

            Example:

                spawn("firefox")
        """
        gobject.spawn_async([os.environ['SHELL'], '-c', cmd])
Exemplo n.º 15
0
 def __start(self):
     from gobject import spawn_async
     from sys import executable
     from SCRIBES.Globals import python_path
     folder = self.__get_save_process_folder()
     module = self.__get_save_process_executable(folder)
     spawn_async([executable, module, python_path],
                 working_directory=folder)
     return False
Exemplo n.º 16
0
 def __open_to_line(self, view, path, column):
     code = view.get_model()[path][0]
     try:
         lineno = "+%d" % code.co_firstlineno
         filename = code.co_filename
     except AttributeError: pass
     else:
         args = ['sensible-editor', lineno, filename]
         gobject.spawn_async(args, flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 17
0
 def start_wine(self, *args):
     if self.wine_pid:
         logging.info("running command line: %s" %
                      ' '.join(str(x) for x in args))
         gobject.spawn_async(
             ['wine', 'explorer',
              '/desktop=%s' % self.desktop_name] + [str(x) for x in args],
             flags=gobject.SPAWN_SEARCH_PATH)
     else:
         self.to_run.append(args)
Exemplo n.º 18
0
 def __start_process(self):
     from gobject import spawn_async, GError
     try:
         args = [
             self.__python_executable, self.__executable,
             self.__editor.python_path
         ]
         spawn_async(args, working_directory=self.__cwd)
     except GError:
         pass
     return False
Exemplo n.º 19
0
    def ui_help(self, ui):
        '''The UI's help button was clicked.

        This should open a help HTML page or website, call yelp with an
        appropriate topic, etc. This gets the current UI object passed, which
        can be used to determine whether GTK/KDE is used, etc.
        '''
        if 'gtk' in str(ui.__class__).lower():
            import gobject
            gobject.spawn_async(['yelp', 'help:ubuntu-help/hardware-driver-proprietary'],
                flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 20
0
    def upload_files(self, menu, files):
        # This is the method invoked when our extension is activated
        # Do whatever you want to do with the files selected
        if len(files) == 0:
            return

        names = [ unquote(file.get_uri()[7:]) for file in files ]

        argv = [ PROGRAM_NAME ] + names

        # TODO: use startup notification
        gobject.spawn_async(argv, flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 21
0
 def __exit_app(self, restart=False):
     gui_misc.shutdown_logging()
     if restart:
         try:
             if self.image_dir_arg:
                 gobject.spawn_async([self.application_path, "--image-dir", self.image_dir_arg])
             else:
                 gobject.spawn_async([self.application_path])
         except gobject.GError, ex:
             if debug:
                 print >>sys.stderr, "Exception occurred: %s" % ex
             logger.error(ex)
Exemplo n.º 22
0
    def ui_help(self, ui):
        '''The UI's help button was clicked.

        This should open a help HTML page or website, call yelp with an
        appropriate topic, etc. This gets the current UI object passed, which
        can be used to determine whether GTK/KDE is used, etc.
        '''
        if 'gtk' in str(ui.__class__).lower():
            import gobject
            gobject.spawn_async(
                ['yelp', 'help:ubuntu-help/hardware-driver-proprietary'],
                flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 23
0
    def upload_files(self, menu, files):
        # This is the method invoked when our extension is activated
        # Do whatever you want to do with the files selected
        if len(files) == 0:
            return

        names = [unquote(file.get_uri()[7:]) for file in files]

        argv = [PROGRAM_NAME] + names

        # TODO: use startup notification
        gobject.spawn_async(argv, flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 24
0
 def __exit_app(self, restart = False):
         gui_misc.shutdown_logging()
         if restart:
                 try:
                         if self.image_dir_arg:
                                 gobject.spawn_async([self.application_path,
                                     "--image-dir", self.image_dir_arg])
                         else:
                                 gobject.spawn_async([self.application_path])
                 except gobject.GError, ex:
                         if debug:
                                 print >> sys.stderr, "Exception occurred: %s" % ex
                         logger.error(ex)
    def _create_activity(self):
        if self._handle.activity_id is None:
            self._handle.activity_id = create_activity_id()

        self._shell.NotifyLaunch(
                    self._service_name, self._handle.activity_id,
                    reply_handler=self._no_reply_handler,
                    error_handler=self._notify_launch_error_handler)

        environ = get_environment(self._bundle)
        (log_path, log_file) = open_log_file(self._bundle)
        command = get_command(self._bundle, self._handle.activity_id,
                              self._handle.object_id,
                              self._handle.uri)

        if not self._use_rainbow:
            # use gobject spawn functionality, so that zombies are
            # automatically reaped by the gobject event loop.
            def child_setup():
                # clone logfile.fileno() onto stdout/stderr
                os.dup2(log_file.fileno(), 1)
                os.dup2(log_file.fileno(), 2)
                # close all other fds
                _close_fds()
            # we need to sanitize and str-ize the various bits which
            # dbus gives us.
            gobject.spawn_async([str(s) for s in command],
                                envp=['%s=%s' % (k, str(v))
                                        for k, v in environ.items()],
                                working_directory=str(self._bundle.get_path()),
                                child_setup=child_setup,
                                flags=(gobject.SPAWN_SEARCH_PATH |
                                        gobject.SPAWN_LEAVE_DESCRIPTORS_OPEN))
            log_file.close()
        else:
            log_file.close()
            system_bus = dbus.SystemBus()
            factory = system_bus.get_object(_RAINBOW_SERVICE_NAME,
                                            _RAINBOW_ACTIVITY_FACTORY_PATH)
            factory.CreateActivity(
                    log_path,
                    environ,
                    command,
                    environ['SUGAR_BUNDLE_PATH'],
                    environ['SUGAR_BUNDLE_ID'],
                    timeout=30,
                    reply_handler=self._create_reply_handler,
                    error_handler=self._create_error_handler,
                    dbus_interface=_RAINBOW_ACTIVITY_FACTORY_INTERFACE)
Exemplo n.º 26
0
    def on_parent_map(self, widget):
        os.environ['WINE_DESKTOP_PARENT'] = str(self.desktop_parent.window.xid)
        os.environ['SUGARED_WINE_TOPLEVEL'] = str(self.window.xid)

        gtk.gdk.flush()

        os.chdir(self.get_unix_path('c:\\'))

        width = gtk.gdk.screen_width()
        height = gtk.gdk.screen_height()

        cmdline = ('wine', 'explorer', '/desktop=%s,%sx%s' % (self.desktop_name, width, height))
        try:
            args = self.settings['exec'].split(' ')
        except KeyError:
            pass
        else:
            cmdline += ('start', '/unix')
            cmdline += (os.path.join(self.bundle_path, args[0]),)
            cmdline += tuple(args[1:])

        self.wine_pid, stdin, stdout, stderr = gobject.spawn_async(cmdline,
            flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_DO_NOT_REAP_CHILD)
        gobject.child_watch_add(self.wine_pid, self.on_wine_quit, None)

        for cmdline in self.to_run:
            self.start_wine(*cmdline)
Exemplo n.º 27
0
 def launch(self):
     '''
     Launch the service
     '''
     self.dead = False
     runner = os.path.join(self.path, 'run')
     if not os.path.exists(runner):
         self.lastDied = time()
         self.dead = True
         self.parent.log(
             'unable to start %s: run does not exist' % self.path)
         return
     if not os.access(runner, os.X_OK):
         self.lastDied = time()
         self.dead = True
         self.parent.log(
             'unable to start %s: run is not executable' % self.path)
         return
     self.parent.log('starting service: %s' % self.path)
     (self.pid, stdin, stdout, stderr) = gobject.spawn_async(
         [runner], working_directory=self.path, flags=gobject.SPAWN_DO_NOT_REAP_CHILD)
     if self.pid <= 0:
         self.lastDied = time()
         self.dead = True
         self.parent.log('failed to start process: %s', self.path)
     else:
         gobject.child_watch_add(self.pid, self.died)
         self.changed('up')
Exemplo n.º 28
0
def spawn_async(argv, in_dir="."):
	pretty.print_debug(__name__, "Spawn commandline", argv, in_dir)
	try:
		return gobject.spawn_async (argv, working_directory=in_dir,
				flags=gobject.SPAWN_SEARCH_PATH)
	except gobject.GError, exc:
		pretty.print_debug(__name__, "spawn_async", argv, exc)
Exemplo n.º 29
0
 def _start_uinput_bridge(self):
     db = dinterface(dbus.SessionBus(), "org.freedesktop.DBus", "/", "org.freedesktop.DBus")
     if not "org.uinputbridge" in db.ListNames() and \
        not "org.uinputbridge" in db.ListActivatableNames():
         gobject.spawn_async([self.path.get_binfile("uinputbridge")],
                             flags=gobject.SPAWN_STDOUT_TO_DEV_NULL | 
                                   gobject.SPAWN_STDERR_TO_DEV_NULL )
         count = 0
         while count < 10:
             count += 1
             if "org.uinputbridge" in db.ListNames():
                 count = 11
             time.sleep(1)
         if count == 10:
             raise UinputServiceStartException()
     self.uinputbridge = dinterface(dbus.SessionBus(), "org.uinputbridge", "/UInputBridge", "org.uinputbridge")
Exemplo n.º 30
0
    def run_cmd(self):
        def child_setup():
            os.setsid()
            tty_slave_fd = os.open(self.tty_slave_name, os.O_RDWR)
            os.close(tty_slave_fd)
            os.close(self.tty_master_fd)


	self.set_state(STATE_RUNNING)
        self.cmd = self.cmd_widget.get_text()

        self.tty_master_fd, self.tty_slave_fd = os.openpty()
        self.tty_slave_name = os.ttyname(self.tty_slave_fd)

	self.tty_view.set_fd(self.tty_master_fd)
        set_raw_input(self.tty_master_fd)

	try:
            import shlex
	    self.pid, self.stdin_fd, self.stdout_fd, self.stderr_fd = \
		      gobject.spawn_async(shlex.split(self.cmd),
					  standard_output=True, standard_error=True,
					  flags=gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH,
                                          child_setup=child_setup)
	except Exception, e:
	    self.insert_text('stderr', str(e))
	    self.exit_status = -1
	    self.set_state(STATE_DONE)
	    return
Exemplo n.º 31
0
 def convert(self):
     src = self.target
     target = src.replace(self.codec, ".mp3")
     if os.path.exists(target):
         os.remove(target)
     if sys.platform != "linux2":
         ffmpeg_path = os.path.join(
             os.path.dirname(os.path.dirname(config.exec_path)), "ffmpeg\\ffmpeg.exe"
         ).replace("\\", "\\\\")
         target = target.replace("\\", "\\\\")
         src = src.replace("\\", "\\\\")
     else:
         ffmpeg_path = "/usr/bin/ffmpeg"
     self.print_info(_("Extracting audio..."))
     try:
         self.gui.throbber.show()
         (pid, t, r, s) = gobject.spawn_async(
             [str(ffmpeg_path), "-i", str(src), "-f", "mp3", "-ab", "192k", str(target)],
             flags=gobject.SPAWN_DO_NOT_REAP_CHILD,
             standard_output=True,
             standard_error=True,
         )
         gobject.child_watch_add(pid, self.task_done)
     except:
         self.print_info(_("Extraction failed..."))
         sleep(4)
         self.print_info("")
         self.gui.throbber.hide()
Exemplo n.º 32
0
    def _execute(self, options):
        """
        Launch the monitored process
        """
        if options is None:
            cmdline = self._cmdline
        else:
            cmdline = [self._cmdline[0]] + options.split()

        result = gobject.spawn_async(
            cmdline,
            envp="",
            working_directory=os.environ.get("PWD", "/"),
            flags=gobject.SPAWN_DO_NOT_REAP_CHILD,  # needed for child watch
            user_data=None,
            standard_input=False,
            standard_output=True,
            standard_error=True)
        if result[0] < 0:
            raise OSError("foo")

        self.pid, self.stdin, self.stdout, self.stderr = result

        self._childwatch = gobject.child_watch_add(self.pid,
                                                   self._exitFromChild,
                                                   priority=100)
        self._stdoutwatch = gobject.io_add_watch(self.stdout, gobject.IO_IN,
                                                 self._outputFromChild)
        self._stderrwatch = gobject.io_add_watch(self.stderr, gobject.IO_IN,
                                                 self._errorFromChild)
Exemplo n.º 33
0
    def on_parent_map(self, widget):
        os.environ['WINE_DESKTOP_PARENT'] = str(self.desktop_parent.window.xid)
        os.environ['SUGARED_WINE_TOPLEVEL'] = str(self.window.xid)

        gtk.gdk.flush()

        os.chdir(self.get_unix_path('c:\\'))

        width = gtk.gdk.screen_width()
        height = gtk.gdk.screen_height()

        cmdline = ('wine', 'explorer',
                   '/desktop=%s,%sx%s' % (self.desktop_name, width, height))
        try:
            args = self.settings['exec'].split(' ')
        except KeyError:
            pass
        else:
            cmdline += ('start', '/unix')
            cmdline += (os.path.join(self.bundle_path, args[0]), )
            cmdline += tuple(args[1:])

        self.wine_pid, stdin, stdout, stderr = gobject.spawn_async(
            cmdline,
            flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD)
        gobject.child_watch_add(self.wine_pid, self.on_wine_quit, None)

        for cmdline in self.to_run:
            self.start_wine(*cmdline)
Exemplo n.º 34
0
	def action(self, text=None):
		if TYPES[self.result["type"]].has_key("action"):
			cmd = TYPES[self.result["type"]]["action"]
			cmd = map(lambda arg : arg % self.result, cmd.split()) # we need this to handle spaces correctly
			print "Opening Tracker hit with command:", cmd
			try:
				# deskbar >= 2.17
				deskbar.Utils.spawn_async(cmd)
			except AttributeError:
				# deskbar <= 2.16
				gobject.spawn_async(args, flags=gobject.SPAWN_SEARCH_PATH)
		else:
			try:
				# deskbar >= 2.17
				deskbar.Utils.url_show ("file://"+cgi.escape(self.result['uri']))
			except AttributeError:
				gnome.url_show("file://"+cgi.escape(self.result['uri']))
			print "Opening Tracker hit:", self.result['uri']
Exemplo n.º 35
0
 def Run(self):
     self.pid, stdin, self.stdout, self.stderr = gobject.spawn_async(
         self.argv,
         flags=gobject.SPAWN_DO_NOT_REAP_CHILD,
         # make sure we can handle it's exit
         standard_input=False,
         standard_output=True,
         standard_error=True)
     gobject.child_watch_add(self.pid, self.__HandleExit)
Exemplo n.º 36
0
 def _check_agent_is_loaded(self):
     self.label.set_text("checking agent")
     pid, stdin, stdout, stderr = gobject.spawn_async(
             ["ssh-add", "-L"],
             flags=gobject.SPAWN_DO_NOT_REAP_CHILD|
                   gobject.SPAWN_STDOUT_TO_DEV_NULL|
                   gobject.SPAWN_SEARCH_PATH)
     pid.close()
     gobject.child_watch_add(pid, self._check_agent_is_loaded_cb)
Exemplo n.º 37
0
def main(argv):
    """ The main daemon program.

    Keyword arguments:
    argv -- The arguments passed to the script.

    """
    global child_pid
    do_daemonize = True
    redirect_stderr = True
    redirect_stdout = True
    auto_connect = True

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'fenoah',
                                   ['help', 'no-daemon', 'no-poll', 'no-stderr', 'no-stdout',
                                    'no-autoconnect'])
    except getopt.GetoptError:
        # Print help information and exit
        usage()
        sys.exit(2)

    no_poll = False
    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit()
        if o in ('-e', '--no-stderr'):
            redirect_stderr = False
        if o in ('-o', '--no-stdout'):
            redirect_stdout = False
        if o in ('-f', '--no-daemon'):
            do_daemonize = False
        if o in ('-a', '--no-autoconnect'):
            auto_connect = False
        if o in ('-n', '--no-poll'):
            no_poll = True

    #This is commented only for testing purposes
    #daemonize()

    # Open the DBUS session
    # TODO: Decide if I should use a SessionBus(SessionWide) or a SystemBus(SystemWide)
    d_bus_name = dbus.service.BusName('org.filezaar.daemon', bus=dbus.SessionBus())
    obj = FileZaarDBUS(d_bus_name, auto_connect=auto_connect)

    gobject.threads_init()

    (child_pid, aa, bb, cc) = gobject.spawn_async(["controller.py"],
                                               flags=gobject.SPAWN_CHILD_INHERITS_STDIN)


    signal.signal(signal.SIGINT, sigterm_caught)
    signal.signal(signal.SIGTERM, sigterm_caught)
    # Enter the main loop
    mainloop = gobject.MainLoop()
    mainloop.run()
Exemplo n.º 38
0
def spawn_async(argv, in_dir="."):
	"Silently spawn @argv in the background"
	pretty.print_debug(__name__, "Spawn commandline", argv, in_dir)
	argv = _argv_to_locale(argv)
	try:
		return gobject.spawn_async (argv, working_directory=in_dir,
				flags=gobject.SPAWN_SEARCH_PATH)
	except gobject.GError, exc:
		pretty.print_debug(__name__, "spawn_async", argv, exc)
Exemplo n.º 39
0
 def _start_forwarding(self):
     args = ['ssh', self.target, '-o', 'PasswordAuthentication no',
             '-N', '-R', '21693:localhost:21693']
     if self.keyfile:
         args[2:2] = ['-i', self.keyfile]
     flags = gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD
     self.ssh_pid, stdin_fd, stdout_fd, stderr_fd = \
         gobject.spawn_async(args, flags=flags)
     gobject.child_watch_add(self.ssh_pid, self._restart_forwarding)
Exemplo n.º 40
0
 def init_xkb(self):
     self.lang_line = ""
     cpid, cstdin, cstdout, cstderr = gobject.spawn_async(
         ['xkb-switch', '-W'],
         flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD,
         standard_output=True,
     )
     gobject.io_add_watch(cstdout, gobject.IO_IN, self.xkb_listener)
     self.channel = os.fdopen(cstdout)
Exemplo n.º 41
0
Arquivo: UI.py Projeto: ballju/conduit
    def on_help(self, widget):
        """
        Display help
        """
        if conduit.IS_INSTALLED:
            uri = "ghelp:conduit"
        else:
            # if we are not installed then launch the ghelp uri with a full path
            uri = "ghelp:%s" % os.path.join(conduit.DIRECTORY, "help", "C", "conduit.xml")

        log.debug("Launching help: %s" % uri)

        if gtk.gtk_version >= (2, 14, 0):
            gtk.show_uri(self.mainWindow.get_screen(), uri, gtk.get_current_event_time())
        else:
            gobject.spawn_async(
                argv=("xdg-open", uri),
                flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_STDOUT_TO_DEV_NULL | gobject.SPAWN_STDERR_TO_DEV_NULL,
            )
Exemplo n.º 42
0
 def Run(self):
     self.pid, stdin, self.stdout, self.stderr = gobject.spawn_async(
         self.argv,
         flags = gobject.SPAWN_DO_NOT_REAP_CHILD, 
         # make sure we can handle it's exit
         standard_input=False,
         standard_output=True,
         standard_error=True
         )   
     gobject.child_watch_add(self.pid, self.__HandleExit)
Exemplo n.º 43
0
 def init_xkb(self):
     self.lang_line = ""
     cpid, cstdin, cstdout, cstderr = gobject.spawn_async(
         ['xkb-switch','-W'],
         flags=gobject.SPAWN_SEARCH_PATH|gobject.SPAWN_DO_NOT_REAP_CHILD,
         standard_output=True,
     )
     gobject.io_add_watch(cstdout,
                          gobject.IO_IN,
                          self.xkb_listener)
     self.channel = os.fdopen(cstdout)
 def install_pkgs(self):
     try:
         (pid, sin, sout, serr) = gobject.spawn_async(
                                      ["install-langs", tmpdir],
                                      flags=gobject.SPAWN_SEARCH_PATH |
                                            gobject.SPAWN_DO_NOT_REAP_CHILD)
         gobject.child_watch_add(pid, self.install_pkgs_done)
         if self.window.window:
             self.window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
     except gobject.GError:
         self.install = False
         install_pkgs_done(self, None, None)
Exemplo n.º 45
0
    def run_cmd(self, *args):
        pid, stdin, stdout, stderr = gobject.spawn_async(
            args, flags=gobject.SPAWN_SEARCH_PATH, standard_output=True)

        result = []
        s = os.read(stdout, 4096)
        while s:
            result.append(s)
            s = os.read(stdout, 4096)

        result = ''.join(result)

        return result
Exemplo n.º 46
0
def spawn_async_raise(argv, workdir="."):
	"""
	A version of spawn_async that raises on error.

	raises SpawnError
	"""
	argv = _argv_to_locale(argv)
	pretty.print_debug(__name__, "spawn_async", argv, workdir)
	try:
		return gobject.spawn_async (argv, working_directory=workdir,
				flags=gobject.SPAWN_SEARCH_PATH)
	except gobject.GError as exc:
		raise SpawnError(exc)
Exemplo n.º 47
0
    def spawn(self, args=None, callback=None, data=None, cwd=None):
        '''Start the application in the background and return immediately.
		This is used to start an external in parallel with zim that is
		not expected to exit immediatly, so we do not want to wait for
		it - e.g. a webbrowser to show an URL that was clicked.

		@param args: additional arguments to give to the command as tuple or list
		@param callback: optional callback can be used to trigger when
		the application exits. The signature is::

			callback(status, data)

		where 'C{status}' is the exit status of the process. The
		application object provides a constant 'C{STATUS_OK}' which can
		be used to test if the application was successful or not.
		@param data: additional data for the callback
		@param cwd: the folder to set as working directory for the command
		@returns: the PID for the new process
		'''
        cwd, argv = self._checkargs(cwd, args)
        opts = {}

        flags = gobject.SPAWN_SEARCH_PATH
        if callback:
            flags |= gobject.SPAWN_DO_NOT_REAP_CHILD
            # without this flag child is reaped automatically -> no zombies

        logger.info('Spawning: %s (cwd: %s)', argv, cwd)
        try:
            pid, stdin, stdout, stderr = \
             gobject.spawn_async(argv, flags=flags, **opts)
        except gobject.GError:
            from zim.gui.widgets import ErrorDialog
            ErrorDialog(None, _('Failed running: %s') % argv[0]).run()
            #~ # T: error when application failed to start
            return None
        else:
            logger.debug('Process started with PID: %i', pid)
            if callback:
                # child watch does implicit reaping -> no zombies
                if data is None:
                    gobject.child_watch_add(
                        pid, lambda pid, status: callback(status))
                else:
                    gobject.child_watch_add(
                        pid, lambda pid, status, data: callback(status, data),
                        data)
            return pid
Exemplo n.º 48
0
    def __init__(self, path, args=[], warnwords=[], env=None):
        gobject.GObject.__init__(self)

        self.path = path
        self.args = args
        self.warnwords = warnwords
        self.env = env or os.environ
        self.buffer = ""

        self.linePublisher = EmitPublisher(self, "line",
                                           EmitPublisher.SEND_LIST)
        self.linePublisher.start()

        self.defname = os.path.split(path)[1]
        self.defname = self.defname[:1].upper() + self.defname[1:].lower()
        t = time.time()
        self.defname = (self.defname,
                        time.strftime("%H:%m:%%.3f", time.localtime(t)) %
                        (t % 60))
        log.debug(path + "\n", self.defname)

        argv = [str(u) for u in [self.path] + self.args]
        self.pid, stdin, stdout, stderr = gobject.spawn_async(
            argv,
            child_setup=self.__setup,
            standard_input=True,
            standard_output=True,
            standard_error=True,
            flags=gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH)

        self.__channelTags = []
        self.inChannel = self._initChannel(stdin, None, None, False)
        readFlags = gobject.IO_IN | gobject.IO_HUP  #|gobject.IO_ERR
        self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb,
                                            False)
        self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb,
                                            True)

        self.channelsClosed = False
        self.channelsClosedLock = threading.Lock()
        gobject.child_watch_add(self.pid, self.__child_watch_callback)

        self.subprocExitCode = (None, None)
        self.subprocFinishedEvent = threading.Event()
        self.subprocFinishedEvent.clear()
        subprocesses.append(self)
        pool.start(self._wait4exit)
Exemplo n.º 49
0
    def Start(self):
        """Start program.

    """
        logging.info("Starting program, executable=%r, args=%r",
                     self.__executable, self.__args)

        # TODO: Make gobject.SPAWN_SEARCH_PATH controllable by caller?
        flags = gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH

        if self.__executable:
            args = self.__FormatArgs([self.__executable] + self.__args)
            flags |= gobject.SPAWN_FILE_AND_ARGV_ZERO
        else:
            args = self.__FormatArgs(self.__args)

        # gobject.spawn_async doesn't take None for default values, hence we can
        # only fill these parameters if they need to be set.
        kwargs = {}

        if self.__env is not None:
            kwargs["envp"] = self.__FormatEnvironment(self.__env)

        if self.__cwd is not None:
            kwargs["working_directory"] = self.__cwd

        (pid, stdin_fd, stdout_fd, stderr_fd) = \
          gobject.spawn_async(args, flags=flags, child_setup=self.__ChildSetup,
                              standard_input=True,
                              standard_output=True,
                              standard_error=True,
                              **kwargs)

        logging.info("Child %s[%d] started", self.__progname, pid)
        self.__pid = pid

        self.stdin.Attach(stdin_fd)
        self.stdout.Attach(stdout_fd)
        self.stderr.Attach(stderr_fd)

        self.__child_watch_handle = \
          gobject.child_watch_add(self.__pid, self.__HandleExit)

        return self.pid
Exemplo n.º 50
0
def spawn_exchangerates_updater():
    if not is_update_check_due():
        print "Time is low, skipping"
        return 0

    try:
        try:
            if CURRENT_PLATFORM in (PLATFORM_NAME_LINUX, PLATFORM_NAME_OSX):
                import gobject  # @UnresolvedImport
                cmdline = [
                    "python",
                    os.path.join(_get_enso_directory(), "enso", "contrib",
                                 "calc", "exchangerates", "updater.py")
                ]
                argv = argv_to_locale(cmdline)
                pid = gobject.spawn_async(
                    argv,  #working_directory=workdir,
                    flags=gobject.SPAWN_SEARCH_PATH
                    | gobject.SPAWN_STDOUT_TO_DEV_NULL)
                return pid
            else:
                cmdline = [
                    "python.exe",
                    os.path.join(_get_enso_directory(), "enso", "contrib",
                                 "calc", "exchangerates", "updater.py")
                ]
                pid = subprocess.Popen(
                    cmdline, shell=False, stdout=None
                ).pid  # Only on windows: , creationflags=os.P_NOWAIT
                return pid
        except Exception as e:
            logging.error(e)
    except Exception as e:
        logging.error("Error spawning exchangerates_updater process: %s", e)
        return 0
    finally:
        reset_update_check_time()
Exemplo n.º 51
0
def _start_window_manager():
    cmd = ['metacity']

    cmd.extend(['--no-force-fullscreen'])

    gobject.spawn_async(cmd, flags=gobject.SPAWN_SEARCH_PATH)
Exemplo n.º 52
0
 def activate_mixer(self, widget):
     gobject.spawn_async(
         [MIXER_CMD],
         flags=gobject.SPAWN_SEARCH_PATH
     )
Exemplo n.º 53
0
    def perform_action(self):
        cmd = ''
        if self.action == ACTION_RECV:
            self.wiz.set_page_title(self.progress_page, _('Receiving...'))
            port = self.xml.get_widget('listen_port').get_text()
            dest_dir = self.xml.get_widget('recv_dir').get_filename()

            self.config.set('history', 'listen_port', port)
            self.config.set('history', 'recv_dir', dest_dir)

            cmd = "nc -l -v --close -p %s | tar -xvz -C '%s'" % (port,
                                                                 dest_dir)
        else:  # ACTION_SEND
            self.wiz.set_page_title(self.progress_page, _('Sending...'))
            host = self.xml.get_widget('dest_host').get_text()
            port = self.xml.get_widget('dest_port').get_text()

            self.config.set('history', 'dest_host', host)
            self.config.set('history', 'dest_port', port)

            files = ' '
            dirs = []
            for it in self.send_list:
                # special char like single quote should be escaped
                files += ("'%s' " % it[1].replace("'", "'\\''"))
                # FIXME: how to escape dir names correctly for transformation pattern?
                dir = os.path.dirname(it[1])
                if not dir in dirs:
                    dirs.append(dir)

            transform = '--show-transformed-names '
            # sort the dirs to put the longer ones before shorter ones
            dirs.sort(lambda a, b: len(b) - len(a))
            # use --transform to strip all prefix of the added files
            for dir in dirs:
                transform += ("--transform='s,^%s/,,' " % dir)

            # striping dir paths of those files with --transform
            cmd = "tar %s -cvzP %s| nc -w30 -v --close '%s' %s" % (
                transform, files, host, port)

        self.progress.insert(
            self.progress.get_end_iter(), '%s %s\n\n%s\n\n' %
            (_('Execute command:'), _('Processing...'), cmd))
        # print cmd
        (self.pid, self.stdi, self.stdo, self.stde) = gobject.spawn_async(
            ['sh', '-c', ('exec %s' % cmd)],
            flags=gobject.SPAWN_SEARCH_PATH | gobject.SPAWN_DO_NOT_REAP_CHILD,
            standard_input=True,
            standard_output=True,
            standard_error=True)
        gobject.child_watch_add(self.pid, self.on_process_exit)
        gobject.io_add_watch(self.stdo,
                             gobject.IO_IN | gobject.IO_HUP | gobject.IO_ERR,
                             self.on_stdout)
        gobject.io_add_watch(self.stde,
                             gobject.IO_IN | gobject.IO_HUP | gobject.IO_ERR,
                             self.on_stderr)

        # enable the Cancel button with very dirty hacks
        def find_cancel_btn(btn, _self):
            if btn and gobject.type_is_a(
                    btn, gtk.Button) and btn.get_label() == gtk.STOCK_CANCEL:
                _self.cancel_btn = btn

        def find_hbox(w, _self):
            if w and gobject.type_is_a(w, gtk.HBox):
                w.forall(find_cancel_btn, _self)

        self.wiz.forall(find_hbox, self)
        if self.cancel_btn:
            self.cancel_btn.set_sensitive(True)
Exemplo n.º 54
0
  def start(self):
    progname='tuxpaint'
    tuxpaint_dir = None
    flags = gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH

    print platform.platform(), platform.platform().split('-')[0]
    if (platform.platform().split('-')[0] == 'Windows'):
      progname = 'tuxpaint.exe'

      try:
         import _winreg

         tuxpaint_key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE,
                                         "Software\\TuxPaint" )
         tuxpaint_dir, type = _winreg.QueryValueEx(tuxpaint_key, "Install_Dir")
         flags = gobject.SPAWN_DO_NOT_REAP_CHILD
         # escape mandatory in Win pygtk2.6
         tuxpaint_dir = '"' + tuxpaint_dir + '"'

      except:
	   pass

    self.window = self.gcomprisBoard.canvas.get_toplevel()

    Prop = gcompris.get_properties()

    #get default values
    self.config_dict = self.init_config()

    #replace configured values
    self.config_dict.update(gcompris.get_board_conf())

    self.rootitem = goocanvas.Group(parent = self.gcomprisBoard.canvas.get_root_item())

    options = [progname]

    if (Prop.fullscreen and eval(self.config_dict['fullscreen'])):
      options.append('--fullscreen')

    if eval(self.config_dict['disable_shape_rotation']):
      options.append('--simpleshapes')

    if eval(self.config_dict['uppercase_text']):
      options.append('--uppercase')

    if eval(self.config_dict['disable_stamps']):
      options.append('--nostamps')

    if eval(self.config_dict['disable_stamps_control']):
      options.append('--nostampcontrols')

    gcompris.sound.close()

    global pid
    try:
       # bug in working_directory=None ?
       if (tuxpaint_dir):
          pid, stdin, stdout, stderr = gobject.spawn_async(
            argv=options,
            flags=flags,
            working_directory=tuxpaint_dir)

       else:
          pid, stdin, stdout, stderr = gobject.spawn_async(
            argv=options,
            flags=flags)

    except:
       gcompris.utils.dialog(_("Cannot find Tuxpaint.\nInstall it to use this activity !"),stop_board)
       return

    gobject.child_watch_add(pid, child_callback, data=self, priority=gobject.PRIORITY_HIGH)

    gcompris.bar_set(gcompris.BAR_CONFIG)
    gcompris.bar_hide(1)

    gcompris.set_default_background(self.gcomprisBoard.canvas.get_root_item())

    textItem = goocanvas.Text(
      parent = self.rootitem,
      text = _("Waiting for Tuxpaint to finish"),
      x = gcompris.BOARD_WIDTH/2,
      y = 185,
      fill_color_rgba = 0x000000ffL,
      anchor = gtk.ANCHOR_CENTER,
      font = gcompris.skin.get_font("gcompris/board/title bold"),
      )
Exemplo n.º 55
0
 def launch (self):
     full_key = self._conf.resolve_plugin_key (self, "command")
     command = self._conf.client.get_string (full_key)
     flags = gobject.SPAWN_STDOUT_TO_DEV_NULL | gobject.SPAWN_STDERR_TO_DEV_NULL
     gobject.spawn_async (["/bin/sh", "-c", command], flags=flags)
Exemplo n.º 56
0
 def _new_window_requested_cb (self, tab_content, view):
     program = '/usr/bin/roaster'
     launcher = '/usr/bin/python'
     url = tab_content._hovered_uri
     command = [launcher, program, url]
     (cpid, cstdin, cstdout, cstderr)=gobject.spawn_async(command)