Ejemplo n.º 1
0
    def __init__(self):
        Gtk.Window.__init__(self, title="Hinawa-1.0 gir sample")
        self.set_border_width(20)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        topbox = Gtk.Box(spacing=10)
        vbox.pack_start(topbox, True, True, 0)

        button = Gtk.Button("transact")
        button.connect("clicked", self.on_click_transact)
        topbox.pack_start(button, True, True, 0)

        button = Gtk.Button("_Close", use_underline=True)
        button.connect("clicked", self.on_click_close)
        topbox.pack_start(button, True, True, 0)

        bottombox = Gtk.Box(spacing=10)
        vbox.pack_start(bottombox, True, True, 0)

        self.entry = Gtk.Entry()
        self.entry.set_text("0xfffff0000980")
        bottombox.pack_start(self.entry, True, True, 0)

        self.label = Gtk.Label("result")
        self.label.set_text("0x00000000")
        bottombox.pack_start(self.label, True, True, 0)

        # handle unix signal
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, \
                             self.handle_unix_signal, None)
Ejemplo n.º 2
0
    def __init__(self):
        Gtk.Window.__init__(self, title="Hinawa-2.0 gir sample with Gtk+3")
        self.set_border_width(20)

        grid = Gtk.Grid(row_spacing=10, row_homogeneous=True,
                        column_spacing=10, column_homogeneous=True)
        self.add(grid)

        button = Gtk.Button(label="transact")
        button.connect("clicked", self.on_click_transact)
        grid.attach(button, 0, 0, 1, 1)

        button = Gtk.Button(label="_Close", use_underline=True)
        button.connect("clicked", self.on_click_close)
        grid.attach(button, 1, 0, 1, 1)

        self.entry = Gtk.Entry()
        self.entry.set_text("0xfffff0000980")
        grid.attach(self.entry, 0, 1, 1, 1)

        self.label = Gtk.Label(label="result")
        self.label.set_text("0x00000000")
        grid.attach(self.label, 1, 1, 1, 1)

        # handle unix signal
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, \
                             self.handle_unix_signal, None)
Ejemplo n.º 3
0
def run():
    utils.setproctitle('redshift-gtk')

    # Internationalisation
    gettext.bindtextdomain('redshift', defs.LOCALEDIR)
    gettext.textdomain('redshift')

    for help_arg in ('-h', '--help'):
        if help_arg in sys.argv:
            print(_('Please run `redshift -h` for help output.'))
            sys.exit(-1)

    # Create redshift child process controller
    c = RedshiftController(sys.argv[1:])

    def terminate_child(data=None):
        c.terminate_child()
        return False

    # Install signal handlers
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                         terminate_child, None)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                         terminate_child, None)

    try:
        # Create status icon
        RedshiftStatusIcon(c)

        # Run main loop
        Gtk.main()
    except:
        c.kill_child()
        raise
Ejemplo n.º 4
0
    def __init__(self, args):
        '''Initialize controller and start child process

        The parameter args is a list of command line arguments to pass on to
        the child process. The "-v" argument is automatically added.'''

        GObject.GObject.__init__(self)

        # Initialize state variables
        self._inhibited = False
        self._temperature = 0
        self._period = 'Unknown'
        self._location = (0.0, 0.0)

        # Start redshift with arguments
        args.insert(0, os.path.join(defs.BINDIR, 'redshift'))
        if '-v' not in args:
            args.insert(1, '-v')

        # Start child process with C locale so we can parse the output
        env = os.environ.copy()
        env['LANG'] = env['LANGUAGE'] = env['LC_ALL'] = env['LC_MESSAGES'] = 'C'
        self._process = GLib.spawn_async(args, envp=['{}={}'.format(k,v) for k, v in env.items()],
                                         flags=GLib.SPAWN_DO_NOT_REAP_CHILD,
                                         standard_output=True, standard_error=True)

        # Wrap remaining contructor in try..except to avoid that the child
        # process is not closed properly.
        try:
            # Handle child input
            # The buffer is encapsulated in a class so we
            # can pass an instance to the child callback.
            class InputBuffer(object):
                buf = ''

            self._input_buffer = InputBuffer()
            self._error_buffer = InputBuffer()
            self._errors = ''

            # Set non blocking
            fcntl.fcntl(self._process[2], fcntl.F_SETFL,
                        fcntl.fcntl(self._process[2], fcntl.F_GETFL) | os.O_NONBLOCK)

            # Add watch on child process
            GLib.child_watch_add(GLib.PRIORITY_DEFAULT, self._process[0], self._child_cb)
            GLib.io_add_watch(self._process[2], GLib.PRIORITY_DEFAULT, GLib.IO_IN,
                              self._child_data_cb, (True, self._input_buffer))
            GLib.io_add_watch(self._process[3], GLib.PRIORITY_DEFAULT, GLib.IO_IN,
                              self._child_data_cb, (False, self._error_buffer))

            # Signal handler to relay USR1 signal to redshift process
            def relay_signal_handler(signal):
                os.kill(self._process[0], signal)
                return True

            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1,
                                 relay_signal_handler, signal.SIGUSR1)
        except:
            self.termwait()
            raise
Ejemplo n.º 5
0
    def _convertSignals(self):
        # What tends to happen when we receive a signal is that the signal will
        # be received by the python interpreter's C handler, python will do
        # what it needs to do to set the python handler we registered to run,
        # the C handler returns, and then nothing happens because Gtk is
        # holding the global interpreter lock. The signal then gets delivered
        # to our python code when you move the mouse or something. We can get
        # around this by doing signals the GLib way. The conversion assumes
        # that none of our signal handlers care about the frame parameter,
        # which is generally true.
        #
        # After the unix_signal_add call, signal.getsignal will tell a half
        # truth: the method returned will still be called, by way of
        # _signal_converter, but GLib will have replaced the actual signal
        # handler for that signal.

        # Convert everything except SIGCHLD, because that's a different can of worms

        def _signal_converter(user_data):
            (handler, signum) = user_data
            handler(signum, None)

        for signum in (s for s in range(1, signal.NSIG) if s != signal.SIGCHLD):
            handler = signal.getsignal(signum)
            if handler and handler not in (signal.SIG_DFL, signal.SIG_IGN):
                # NB: if you are looking at the glib documentation you are in for
                # some surprises because gobject-introspection is a minefield.
                # g_unix_signal_add_full comes out as GLib.unix_signal_add, and
                # g_unix_signal_add doesn't come out at all.
                GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signum,
                        _signal_converter, (handler, signum))
Ejemplo n.º 6
0
    def __init__(self, run_as_service):
        Gio.Application.__init__(
            self,
            application_id='org.gnome.ChromeGnomeShell',
            flags=Gio.ApplicationFlags.IS_SERVICE if run_as_service
            else Gio.ApplicationFlags.IS_LAUNCHER | Gio.ApplicationFlags.HANDLES_OPEN
        )

        self.gio_settings = None
        self.shellAppearedId = None
        self.shellSignalId = None
        self.disableUserExtensionsSignalId = None
        self.disableVersionCheckSignalId = None

        # Set custom exception hook
        # noinspection SpellCheckingInspection
        sys.excepthook = self.default_exception_hook

        self.register()

        if not run_as_service:
            self.shell_proxy = Gio.DBusProxy.new_sync(self.get_dbus_connection(),
                                                      Gio.DBusProxyFlags.NONE,
                                                      None,
                                                      'org.gnome.Shell',
                                                      '/org/gnome/Shell',
                                                      'org.gnome.Shell.Extensions',
                                                      None)

            self.get_dbus_connection().signal_subscribe(
                self.get_application_id(),
                self.get_application_id(),
                None,
                "/org/gnome/ChromeGnomeShell",
                None,
                Gio.DBusSignalFlags.NONE,
                self.on_dbus_signal,
                None
            )

            stdin = GLib.IOChannel.unix_new(sys.stdin.fileno())
            stdin.set_encoding(None)
            stdin.set_buffered(False)

            GLib.io_add_watch(stdin, GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN, self.on_input, None)
            GLib.io_add_watch(stdin, GLib.PRIORITY_DEFAULT, GLib.IOCondition.HUP, self.on_hup, None)
            GLib.io_add_watch(stdin, GLib.PRIORITY_DEFAULT, GLib.IOCondition.ERR, self.on_hup, None)
        else:
            self.add_simple_action("create-notification", self.on_create_notification, 'a{sv}')
            self.add_simple_action("on-notification-clicked", self.on_notification_clicked, 's')
            self.add_simple_action("on-notification-action", self.on_notification_action, '(si)')

            GLib.timeout_add_seconds(5 * 60, self.on_service_timeout, None)

        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.on_sigint, None)

        if not run_as_service or not self.get_is_remote():
            self.hold()
Ejemplo n.º 7
0
    def main(self, args=None):
        # コマンドラインオプションをパース
        if args is None:
            args = sys.argv[1:]

        parser = optparse.OptionParser()
        parser.add_option("-r", "--reset", dest="reset", action="store_true")
        opt, args = parser.parse_args(args)

        if len(args) == 0:
            logger.critical("カウント対象機種を指定されていません。")
            return 1

        machine = args[0]

        # 設定ファイル保存ディレクトリとファイルのパスを生成
        makedir(self.resourcedir)
        datafilepath = os.path.join(self.resourcedir, machine)
        # ハードウエアレシーバオブジェクト作成
        try:
            hw = hwReceiverFactory("usbio")
        except HwReceiverError as e:
            logger.critical(e)
            return 1

        # 引数で指定され機種に対応したモジュールをインポートする
        loader = PluginLoader(self.basedir, "machines")
        plugin = loader.getInstance(machine)
        cd = plugin.createCountData()
        if not opt.reset:
            cd.load(datafilepath)

        # PCounterオブジェクト作成
        pc = PCounter(hw, plugin, cd)

        # メインループオブジェクト作成
        loop = GLib.MainLoop()

        # シグナルハンドラ設定
        if sys.platform != "win32":
            def signal_handler(user_data):
                loop.quit()
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT,
                                 signal.SIGTERM,
                                 signal_handler,
                                 None)

        GLib.timeout_add(self.pollingInterval, pc.loop)

        # メインループ
        try:
            loop.run()
        except KeyboardInterrupt:
            pass
        finally:
            cd.save(datafilepath)
            logger.info("Counter data is saved to {}".format(datafilepath))
        return 0
Ejemplo n.º 8
0
    def main(self, hook_func=None, skip_workdir_scan=False):
        """
        Where everything start.
        """
        parser = argparse.ArgumentParser(
            description='Manages scanned documents and PDFs'
        )
        parser.add_argument('--version', action='version',
                            version=str(__version__))
        parser.add_argument(
            "--debug", "-d", default=os.getenv("PAPERWORK_VERBOSE", "INFO"),
            choices=LogTracker.LOG_LEVELS.keys(),
            help="Set verbosity level. Can also be set via env"
            " PAPERWORK_VERBOSE (e.g. export PAPERWORK_VERBOSE=INFO)"
        )
        args, unknown_args = parser.parse_known_args(sys.argv[1:])

        LogTracker.init()
        logging.getLogger().setLevel(LogTracker.LOG_LEVELS.get(args.debug))

        set_locale()

        if hasattr(GLib, "unix_signal_add"):
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 self.quit_nicely, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                                 self.quit_nicely, None)

        backend_state = paperwork_backend.init()

        logger.info("Initializing pyinsane ...")
        pyinsane2.init()
        try:
            logger.info("Initializing libnotify ...")
            Notify.init("Paperwork")

            self.config = load_config()
            self.config.read()

            self.main_win = MainWindow(
                self.config, self.main_loop, not skip_workdir_scan,
                flatpak=backend_state['flatpak']
            )
            if hook_func:
                hook_func(self.config, self.main_win)

            self.main_loop.run()

            logger.info("Writing configuration ...")
            self.config.write()

            logger.info("Stopping libnotify ...")
            Notify.uninit()
        finally:
            logger.info("Stopping Pyinsane ...")
            pyinsane2.exit()
        logger.info("Good bye")
Ejemplo n.º 9
0
def main():
	mainloop = GLib.MainLoop()
	daemon = None
	
	set_procname(PROGNAME)
	GObject.threads_init()
	DBusGMainLoop(set_as_default = True)
	GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, 
		sigterm_handler, mainloop)
	
	# Get commandline arguments
	args = get_args()
	
	# Shut down an (possibly) already running Mailnag daemon
	# (must be called before instantiation of the DBUSService).
	shutdown_existing_instance()
	
	# Note: don't start logging before an existing Mailnag 
	# instance has been shut down completely (will corrupt logfile).
	init_logging(not args.quiet)
	
	try:
		if not cfg_exists():
			logging.critical(
				"Cannot find configuration file. " + \
				"Please run mailnag-config first.")
			exit(1)
		
		wait_for_inet_connection()
		
		def fatal_error_hdlr(ex):
			# Note: don't raise an exception 
			# (e.g InvalidOperationException) 
			# in the error handler.
			mainloop.quit()
			
		def shutdown_request_hdlr():
			if not mainloop.is_running():
				raise InvalidOperationException(
					"Mainloop is not running")
			mainloop.quit()
		
		daemon = MailnagDaemon(
			fatal_error_hdlr, 
			shutdown_request_hdlr)
		
		daemon.init()
				
		# start mainloop for DBus communication
		mainloop.run()
	
	except KeyboardInterrupt:
		pass # ctrl+c pressed
	finally:
		logging.info('Shutting down...')
		cleanup(daemon)
Ejemplo n.º 10
0
    def run(self):
        FwpUtil.mkDirAndClear(self.param.tmpDir)
        try:
            sys.stdout = StdoutRedirector(os.path.join(self.param.tmpDir, "fpemud-portal.out"))
            sys.stderr = sys.stdout

            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(logging.INFO)

            # create services
            self.servList.append(FwpServiceGitMirror(self.param))

            # start services
            for serv in self.servList:
                serv.start()

            # start apache
            os.mkdir(self.param.apacheDir)
            os.mkdir(self.param.apacheSubSiteCfgDir)
            for i in range(0, len(self.servList)):
                serv = self.servList[i]
                fn = os.path.join(self.param.apacheSubSiteCfgDir, "%02d-%s.conf" % (i + 1, serv.getName()))
                with open(fn, "w") as f:
                    f.write(serv.getApacheConfSnippet())
            self.apacheProc = self._runApache()
            logging.info("apache started.")

            # write pid file
            with open(os.path.join(self.param.tmpDir, "fpemud-portal.pid"), "w") as f:
                f.write(str(os.getpid()))

            # start main loop
            logging.info("Mainloop begins.")
            self.param.mainloop = GLib.MainLoop()
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None)
            self.param.mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            if self.apacheProc is not None:
                self.apacheProc.terminate()
                self.apacheProc.wait()

            i = len(self.servList) - 1
            while i >= 0:
                self.servList[i].stop()
                i = i - 1

            logging.shutdown()
            shutil.rmtree(self.param.tmpDir)
Ejemplo n.º 11
0
    def run(self):
        CgfwUtil.mkDirAndClear(self.param.tmpDir)
        try:
            sys.stdout = StdoutRedirector(os.path.join(self.param.tmpDir, "fpemud-cgfw.out"))
            sys.stderr = sys.stdout

            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(logging.INFO)

            # check configuration
            if len(CgfwCommon.getCgfwCfgList(self.param.etcDir)) == 0:
                raise Exception("no cgfw config file")

            # create main loop
            DBusGMainLoop(set_as_default=True)
            self.param.mainloop = GLib.MainLoop()
            self.param.dbusMainObject = DbusMainObject(self.param, self)

            # write pid file
            with open(os.path.join(self.param.tmpDir, "fpemud-cgfw.pid"), "w") as f:
                f.write(str(os.getpid()))

            # modify dns server configuration
            with open("/etc/resolv.conf", "r") as f:
                self.resloveFileContent = f.read()
            self.dnsmasqProc = self._runDnsmasq()
            with open("/etc/resolv.conf", "w") as f:
                f.write("# Generated by fpemud-cgfw\n")
                f.write("nameserver 127.0.0.1\n")
            logging.info("DNS resolution path modified.")

            # run vpn client
            GObject.timeout_add_seconds(0, self._timeoutCallback)

            # start main loop
            logging.info("Mainloop begins.")
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, self._sigHandlerHUP, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1, self._sigHandlerUSR1, None)
            self.param.mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            if self.vpnClientPidWatch is not None:
                GLib.source_remove(self.vpnClientPidWatch)
            if self.vpnClientProc is not None:
                self.vpnClientProc.terminate()
                self.vpnClientProc.wait()

            # revert dns resolution path
            if self.resloveFileContent is not None:
                with open("/etc/resolv.conf", "w") as f:
                    f.write(self.resloveFileContent)
            if self.dnsmasqProc is not None:
                self.dnsmasqProc.terminate()
                self.dnsmasqProc.wait()

            logging.shutdown()
            shutil.rmtree(self.param.tmpDir)
Ejemplo n.º 12
0
    def do_startup(self):
        Gtk.Application.do_startup(self)

        settings.load()

        for name in self._ACTIONS:
            action = Gio.SimpleAction.new(name, None)
            action.connect('activate', getattr(self, '_{}_cb'.format(name)))
            self.add_action(action)

        Gtk.Window.set_default_icon_name(app_info.ICON)
        self._window = window.MainWindow(self)
        self._window.load_state()

        self._tray = tray.Tray(self._window)

        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._on_quit)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._on_quit)
Ejemplo n.º 13
0
    def __init__(self):
        super().__init__()
        self.name = 'Worktime'
        self.update_func_list = []

        # create config dir
        config_dir = os.environ['HOME'] + '/.config/worktime'
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
        config_name = 'config.yaml'

        # View
        self.conf_win = ConfigWin(self, config_dir, config_name)
        self.main_win = MainWin(self)
        self.indicator = Indicator(self)

        # Event
        GLib.timeout_add(self.conf_win.duration, self.on_timeout)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH,
                             signal.SIGINT, self.on_quit, None)
Ejemplo n.º 14
0
 def setUpClass(cls) -> None:
     cls._flag = False
     IBus.init()
     cls._gsettings = Gio.Settings(
         schema='org.freedesktop.ibus.engine.typing-booster')
     cls._orig_dictionary = cls._gsettings.get_string('dictionary')
     cls._orig_tabenable = cls._gsettings.get_boolean('tabenable')
     cls._orig_inputmode = cls._gsettings.get_boolean('inputmode')
     cls._orig_inline_completion = cls._gsettings.get_int(
         'inlinecompletion')
     cls._orig_auto_select_candidate = cls._gsettings.get_boolean(
         'autoselectcandidate')
     signums: List[Optional[signal.Signals]] = [
         getattr(signal, s, None) for s in 'SIGINT SIGTERM SIGHUP'.split()
     ]
     for signum in filter(None, signums):
         original_handler = signal.getsignal(signum)
         GLib.unix_signal_add(GLib.PRIORITY_HIGH, signum,
                              cls.signal_handler,
                              (signum, original_handler))
Ejemplo n.º 15
0
    def __enter__(self):
        # Only use unix_signal_add if this is not win32 and there has
        # not already been one.
        if sys.platform != 'win32' and not InterruptibleLoopContext._loop_contexts:
            # Add a glib signal handler
            source_id = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT,
                                             signal.SIGINT,
                                             self._glib_sigint_handler, None)
            InterruptibleLoopContext._signal_source_id = source_id

        InterruptibleLoopContext._loop_contexts.append(self)
Ejemplo n.º 16
0
    def _watch_redshift(self):
        # Wrap remaining contructor in try..except to avoid that the child
        # process is not closed properly.
        try:
            # Handle child input
            # The buffer is encapsulated in a class so we
            # can pass an instance to the child callback.
            class InputBuffer(object):
                buf = ''

            self._input_buffer = InputBuffer()
            self._error_buffer = InputBuffer()
            self._errors = ''

            # Set non blocking
            fcntl.fcntl(
                self._process[2], fcntl.F_SETFL,
                fcntl.fcntl(self._process[2], fcntl.F_GETFL) | os.O_NONBLOCK)

            # Add watch on child process
            GLib.child_watch_add(
                GLib.PRIORITY_DEFAULT, self._process[0], self._child_cb)

            self._io_watch_input_id = GLib.io_add_watch(
                self._process[2], GLib.PRIORITY_DEFAULT, GLib.IO_IN,
                self._child_data_cb, (True, self._input_buffer))

            self._io_watch_error_id = GLib.io_add_watch(
                self._process[3], GLib.PRIORITY_DEFAULT, GLib.IO_IN,
                self._child_data_cb, (False, self._error_buffer))

            # Signal handler to relay USR1 signal to redshift process
            def relay_signal_handler(signal):
                os.kill(self._process[0], signal)
                return True

            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1,
                                 relay_signal_handler, signal.SIGUSR1)
        except:
            self.termwait()
            raise
Ejemplo n.º 17
0
    def __init__(self):
        setproctitle('GWinWrap')
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             gtk.main_quit)
        faulthandler.enable()  # For better debug info

        settings = Settings()
        builder = settings.returnBuilder()

        # Gets the methods from the classes and sets to handler.
        # Then, builder connects to any signals it needs.
        classes = [CrossClassSignals(settings)]

        handlers = {}
        for c in classes:
            methods = inspect.getmembers(c, predicate=inspect.ismethod)
            handlers.update(methods)

        builder.connect_signals(handlers)
        window = settings.createWindow()
        window.show()
Ejemplo n.º 18
0
    def __enter__(self):
        # Only use unix_signal_add if this is not win32 and there has
        # not already been one.
        if sys.platform != 'win32' and not InterruptibleLoopContext._loop_contexts:
            # Add a glib signal handler
            source_id = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT,
                                             signal.SIGINT,
                                             self._glib_sigint_handler,
                                             None)
            InterruptibleLoopContext._signal_source_id = source_id

        InterruptibleLoopContext._loop_contexts.append(self)
Ejemplo n.º 19
0
    def __init__(self, parent=None):
        super(Sample, self).__init__(parent)

        self.setWindowTitle("Hinawa-2.0 gir sample with PyQt4")

        layout = QVBoxLayout()
        self.setLayout(layout)

        top_grp = QGroupBox(self)
        top_layout = QHBoxLayout()
        top_grp.setLayout(top_layout)
        layout.addWidget(top_grp)

        buttom_grp = QGroupBox(self)
        buttom_layout = QHBoxLayout()
        buttom_grp.setLayout(buttom_layout)
        layout.addWidget(buttom_grp)

        button = QToolButton(top_grp)
        button.setText('transact')
        top_layout.addWidget(button)
        button.clicked.connect(self.transact)

        close = QToolButton(top_grp)
        close.setText('close')
        top_layout.addWidget(close)
        close.clicked.connect(app.quit)

        self.addr = QLineEdit(buttom_grp)
        self.addr.setText('0xfffff0000980')
        buttom_layout.addWidget(self.addr)

        self.value = QLabel(buttom_grp)
        self.value.setText('00000000')
        buttom_layout.addWidget(self.value)

        # handle unix signal
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, \
                             self.handle_unix_signal, None)
Ejemplo n.º 20
0
def main(hook_func=None):
    """
    Where everything start.
    """
    LogTracker.init()

    set_locale()

    GLib.threads_init()
    GObject.threads_init()

    if hasattr(GLib, "unix_signal_add"):
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             Gtk.main_quit, None)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                             Gtk.main_quit, None)

    try:
        pyinsane2.init()

        config = load_config()
        config.read()

        main_win = MainWindow(config)
        ActionRefreshIndex(main_win, config).do()

        if hook_func:
            thread = threading.Thread(target=hook_func,
                                      args=(config, main_win))
            thread.start()

        Gtk.main()

        for scheduler in main_win.schedulers.values():
            scheduler.stop()

        config.write()
    finally:
        logger.info("Good bye")
Ejemplo n.º 21
0
    def __init__(self, parent=None):
        super(Sample, self).__init__(parent)

        self.setWindowTitle("Hinawa-1.0 gir sample with PyQt5")

        layout = QVBoxLayout()
        self.setLayout(layout)

        top_grp = QGroupBox(self)
        top_layout = QHBoxLayout()
        top_grp.setLayout(top_layout)
        layout.addWidget(top_grp)

        buttom_grp = QGroupBox(self)
        buttom_layout = QHBoxLayout()
        buttom_grp.setLayout(buttom_layout)
        layout.addWidget(buttom_grp)

        button = QToolButton(top_grp)
        button.setText('transact')
        top_layout.addWidget(button)
        button.clicked.connect(self.transact)

        close = QToolButton(top_grp)
        close.setText('close')
        top_layout.addWidget(close)
        close.clicked.connect(app.quit)

        self.addr = QLineEdit(buttom_grp)
        self.addr.setText('0xfffff0000980')
        buttom_layout.addWidget(self.addr)

        self.value = QLabel(buttom_grp)
        self.value.setText('00000000')
        buttom_layout.addWidget(self.value)

        # handle unix signal
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, \
                             self.handle_unix_signal, None)
Ejemplo n.º 22
0
    def __init__(self):
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain('cinnamon')

        self.builder.add_from_file(
            "/usr/share/cinnamon/cinnamon-settings/bin/scrollbar-test-widget.glade"
        )
        self.content_box = self.builder.get_object("content_box")

        # In hidpi, the size request seems to be doubled, resulting in too high a test window.
        # Check and adjust here at runtime.
        if self.content_box.get_scale_factor() == 2:
            self.content_box.set_size_request(-1, 50)

        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM,
                             self.on_terminate)

        plug = Gtk.Plug.new(int(sys.argv[1]))
        plug.add(self.content_box)

        plug.connect("destroy", Gtk.main_quit)
        plug.show_all()
Ejemplo n.º 23
0
def main(hook_func=None, skip_workdir_scan=False):
    """
    Where everything start.
    """
    LogTracker.init()

    set_locale()

    if hasattr(GLib, 'set_application_name'):
        GLib.set_application_name("Paperwork")
    if hasattr(GLib, "unix_signal_add"):
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                             Gtk.main_quit, None)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                             Gtk.main_quit, None)

    try:
        pyinsane2.init()

        config = load_config()
        config.read()

        main_win = MainWindow(config)
        ActionRefreshIndex(main_win,
                           config,
                           skip_examination=skip_workdir_scan).do()

        if hook_func:
            hook_func(config, main_win)

        Gtk.main()

        for scheduler in main_win.schedulers.values():
            scheduler.stop()

        config.write()
    finally:
        logger.info("Good bye")
Ejemplo n.º 24
0
    def run(self):
        try:
            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(
                CgfwUtil.getLoggingLevel(self.param.logLevel))
            logging.info("Program begins.")

            # read configuration
            for section, data in CgfwCommon.getCgfwCfg().items():
                tmpDir2 = os.path.join(self.param.tmpDir, section)
                if self.varDir is None:
                    varDir2 = None
                else:
                    varDir2 = os.path.join(self.param.varDir, section)
                self.curProviderList.append(
                    CgfwCommon.getProvider(section, data, tmpDir2, varDir2))

            # create main loop
            mainloop = GLib.MainLoop()

            # start business
            if not os.path.exists(self.param.tmpDir):
                os.makedirs(self.param.tmpDir)
            self.vpnRestartTimer = GObject.timeout_add_seconds(
                0, self._vpnRestartTimerCallback)

            # start main loop
            logging.info("Mainloop begins.")
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, on_sig_int,
                                 None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM,
                                 on_sig_term, None)
            mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            logging.shutdown()
Ejemplo n.º 25
0
def run():
    utils.setproctitle('redshift-gtk')

    # Install TERM signal handler
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                         sigterm_handler, None)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, sigterm_handler,
                         None)

    # Internationalisation
    gettext.bindtextdomain('redshift', defs.LOCALEDIR)
    gettext.textdomain('redshift')

    # Create redshift child process controller
    c = RedshiftController(sys.argv[1:])
    try:
        # Create status icon
        s = RedshiftStatusIcon(c)

        # Run main loop
        Gtk.main()
    finally:
        # Always make sure that the child process is closed
        c.termwait()
Ejemplo n.º 26
0
def run():
    utils.setproctitle('redshift-gtk')

    # Install TERM signal handler
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM,
                         sigterm_handler, None)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                         sigterm_handler, None)

    # Internationalisation
    gettext.bindtextdomain('redshift', defs.LOCALEDIR)
    gettext.textdomain('redshift')

    # Create redshift child process controller
    c = RedshiftController(sys.argv[1:])
    try:
        # Create status icon
        s = RedshiftStatusIcon(c)

        # Run main loop
        Gtk.main()
    finally:
        # Always make sure that the child process is closed
        c.termwait()
Ejemplo n.º 27
0
    def add_signal_handler(self, signum, callback, *args):
        def doit(_1, _2):  # not sure what the args are
            callback(*args)
            return \
                True # keep triggering

        #end doit

    #begin add_signal_handler
        self._add_source \
          (
            attr = "_signal_sources",
            key = signum,
            source_nr = GLib.unix_signal_add(0, signum, doit, None, None)
          )
        self = None  # avoid circular references
Ejemplo n.º 28
0
 def test_no_replace_if_set_by_glib(self):
     id_ = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                lambda *args: None)
     try:
         # signal.getsignal() doesn't pick up that unix_signal_add()
         # has changed the handler, but we should anyway.
         self.assertEqual(signal.getsignal(signal.SIGINT),
                          signal.default_int_handler)
         with register_sigint_fallback(lambda: None):
             self.assertEqual(signal.getsignal(signal.SIGINT),
                              signal.default_int_handler)
         self.assertEqual(signal.getsignal(signal.SIGINT),
                          signal.default_int_handler)
     finally:
         GLib.source_remove(id_)
         signal.signal(signal.SIGINT, signal.SIG_DFL)
         signal.signal(signal.SIGINT, signal.default_int_handler)
Ejemplo n.º 29
0
 def test_no_replace_if_set_by_glib(self):
     id_ = GLib.unix_signal_add(
         GLib.PRIORITY_DEFAULT, signal.SIGINT, lambda *args: None)
     try:
         # signal.getsignal() doesn't pick up that unix_signal_add()
         # has changed the handler, but we should anyway.
         self.assertEqual(
             signal.getsignal(signal.SIGINT), signal.default_int_handler)
         with register_sigint_fallback(lambda: None):
             self.assertEqual(
                 signal.getsignal(signal.SIGINT),
                 signal.default_int_handler)
         self.assertEqual(
             signal.getsignal(signal.SIGINT), signal.default_int_handler)
     finally:
         GLib.source_remove(id_)
         signal.signal(signal.SIGINT, signal.SIG_DFL)
         signal.signal(signal.SIGINT, signal.default_int_handler)
Ejemplo n.º 30
0
def register_os_signal(callback, commandtype="", signum=signal.SIGINT):
    from gi.repository import GLib  #pylint: disable=import-outside-toplevel
    signame = SIGNAMES.get(signum, str(signum))

    def write_signal():
        if commandtype is None:
            return
        try:
            sys.stderr.write("\n")
            sys.stderr.flush()
            cstr = ""
            if commandtype:
                cstr = commandtype + " "
            get_util_logger().info("%sgot signal %s", cstr, signame)
        except OSError:
            pass

    def do_handle_signal():
        callback(signum)

    if POSIX:
        #replace the previous definition if we had one:
        global _glib_unix_signals
        current = _glib_unix_signals.get(signum, None)
        if current:
            GLib.source_remove(current)

        def handle_signal(_signum):
            write_signal()
            do_handle_signal()
            return True

        source_id = GLib.unix_signal_add(GLib.PRIORITY_HIGH, signum,
                                         handle_signal, signum)
        _glib_unix_signals[signum] = source_id
    else:

        def os_signal(_signum, _frame):
            write_signal()
            GLib.idle_add(do_handle_signal)

        signal.signal(signum, os_signal)
Ejemplo n.º 31
0
def register_os_signals(callback,
                        commandtype="",
                        signals=(signal.SIGINT, signal.SIGTERM)):
    from gi.repository import GLib

    def handle_signal(signum):
        if commandtype is not None:
            try:
                sys.stderr.write("\n")
                sys.stderr.flush()
                cstr = ""
                if commandtype:
                    cstr = commandtype + " "
                get_util_logger().info("%sgot signal %s", cstr,
                                       SIGNAMES.get(signum, signum))
            except OSError:
                pass
        callback(signum)
        return True

    def os_signal(signum, _frame):
        GLib.idle_add(handle_signal, signum)
        return True

    for signum in signals:
        if POSIX:
            #replace the previous definition if we had one:
            global _glib_unix_signals
            current = _glib_unix_signals.get(signum, None)
            if current:
                GLib.source_remove(current)
            source_id = GLib.unix_signal_add(GLib.PRIORITY_HIGH, signum,
                                             handle_signal, signum)
            _glib_unix_signals[signum] = source_id
        else:
            signal.signal(signum, os_signal)
Ejemplo n.º 32
0
    def run(self):
        GbsUtil.mkDirAndClear(self.param.tmpDir)
        GbsUtil.mkDirAndClear(self.param.runDir)
        try:
            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(GbsUtil.getLoggingLevel(self.param.logLevel))
            logging.info("Program begins.")

            # create main loop
            self.mainloop = GLib.MainLoop()

            # write pid file
            with open(self.param.pidFile, "w") as f:
                f.write(str(os.getpid()))

            # check certificate and private key
            if not os.path.exists(self.param.certFile) or not os.path.exists(self.param.privkeyFile):
                raise GbsDaemonException("Certificate and private key not found")

            # start control server
            self.ctrlServer = GbsCtrlServer(self.param)
            self.ctrlServer.start()
            logging.info('Control server started.')

            # start main loop
            logging.info("Mainloop begins.")
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGUSR2, self._sigHandlerUSR2, None)    # let the process ignore SIGUSR2, we
            signal.siginterrupt(signal.SIGUSR2, True)                                               # use it to interrupt blocking system calls
            self.mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            if self.ctrlServer is not None:
                self.ctrlServer.stop()
            logging.shutdown()
            shutil.rmtree(self.param.runDir)
            shutil.rmtree(self.param.tmpDir)
            logging.info("Program exits.")
Ejemplo n.º 33
0
Archivo: CBM.py Proyecto: Pacsiy/CBM
    def run(self):
        self.window = Gtk.Window(type=Gtk.WindowType.POPUP)
        self.c_id = self.clipboard.connect('owner-change',
                                           self.owner_change)

        with suppress_if_errno(FileNotFoundError, errno.ENOENT):
            os.unlink(self.sock_file)

        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.bind(self.sock_file)
        os.chmod(self.sock_file, stat.S_IRUSR | stat.S_IWUSR)
        self.sock.listen(5)

        #keyboard.add_hotkey('ctrl+c', self.on_copy)
        #keyboard.add_hotkey('ctrl+x', self.on_copy)

        # Handle socket connections
        GObject.io_add_watch(self.sock, GObject.IO_IN,
                             self.socket_accept)
        # Handle unix signals
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self.exit)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self.exit)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGHUP, self.exit)
        Gtk.main()
Ejemplo n.º 34
0
def run_pipeline(pipeline,
                 layout,
                 loop,
                 display,
                 handle_sigint=True,
                 signals=None):

    # Create pipeline
    pipeline = describe(pipeline)
    print(pipeline)
    pipeline = Gst.parse_launch(pipeline)

    if display is not Display.NONE:
        # Workaround for https://gitlab.gnome.org/GNOME/gtk/issues/844 in gtk3 < 3.24.
        widget_draws = 123

        def on_widget_draw(widget, cairo):
            nonlocal widget_draws
            if widget_draws:
                widget.queue_draw()
                widget_draws -= 1
            return False

        # Needed to account for window chrome etc.
        def on_widget_configure(widget, event, glsink):
            allocation = widget.get_allocation()
            glsink.set_render_rectangle(allocation.x, allocation.y,
                                        allocation.width, allocation.height)
            return False

        window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        window.set_title(WINDOW_TITLE)
        window.set_default_size(layout.render_size.width,
                                layout.render_size.height)
        if display is Display.FULLSCREEN:
            window.fullscreen()

        drawing_area = Gtk.DrawingArea()
        window.add(drawing_area)
        drawing_area.realize()

        glsink = pipeline.get_by_name('glsink')
        set_display_contexts(glsink, drawing_area)
        drawing_area.connect('draw', on_widget_draw)
        drawing_area.connect('configure-event', on_widget_configure, glsink)
        window.connect('delete-event', Gtk.main_quit)
        window.show_all()

    with Worker(save_frame) as images, Commands() as get_command:
        signals = {
            'appsink': {
                'new-sample':
                functools.partial(on_new_sample,
                                  layout=layout,
                                  images=images,
                                  get_command=get_command)
            },
            **(signals or {})
        }

        for name, signals in signals.items():
            component = pipeline.get_by_name(name)
            if component:
                for signal_name, signal_handler in signals.items():
                    component.connect(signal_name, signal_handler, pipeline)

        # Set up a pipeline bus watch to catch errors.
        bus = pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect('message', on_bus_message, pipeline, loop)

        # Handle signals.
        if handle_sigint:
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 Gtk.main_quit)

        # Run pipeline.
        pipeline.set_state(Gst.State.PLAYING)
        try:
            Gtk.main()
        except KeyboardInterrupt:
            pass
        finally:
            pipeline.set_state(Gst.State.NULL)

        # Process all pending MainContext operations.
        while GLib.MainContext.default().iteration(False):
            pass
Ejemplo n.º 35
0
client.connect('event', handle_event)

print('  Changed parameters:')
params = client.get_property('params')
print('   params:       {0}'.format(params))
print('   ticks:        {0}'.format(client.get_property('ticks')))
print('   queue-size:   {0}'.format(client.get_property('queue-size')))
print('   filter:       {0}'.format(client.get_property('filter')))

try:
    client.start()
except Exception as e:
    print(e)
    sys.exit()
print('  started')

# Handle unix signal
def handle_unix_signal(self):
    loop.quit()
GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, \
                     handle_unix_signal, None)

# Event loop
loop = GLib.MainLoop()
loop.run()

client.stop()
print('  stopped')

sys.exit()
Ejemplo n.º 36
0
from setproctitle import setproctitle

# Lib imports
import gi, faulthandler, signal
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib

# Application imports
from main import Main



if __name__ == "__main__":
    try:
        # pdb.set_trace()
        setproctitle('Pytop')
        faulthandler.enable()  # For better debug info
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, Gtk.main_quit)

        parser = argparse.ArgumentParser()
        # Add long and short arguments
        parser.add_argument("--file", "-f", default="default", help="JUST SOME FILE ARG.")
        # Read arguments (If any...)
        args, unknownargs = parser.parse_known_args()

        main = Main(args, unknownargs)
        Gtk.main()
    except Exception as e:
        traceback.print_exc()
Ejemplo n.º 37
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close)
        Gst.init(None)

        self._what_list = []

        self.play_recording_thread = None

        self.playing_recording = False
        self.firstTime = False
        self.playing = False
        self.regularity = 0.7
        self._drums_store = []
        self.recording = False
        self.recorded_keys = []
        self.is_valid_recording = False

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1
        self.csnd = new_csound_client()
        self.rythmInstrument = 'drum1kick'
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        self.play_index = 0

        self.play_recording_button = ToolButton(
            icon_name='media-playback-start')
        self.play_recording_button.set_property('can-default', True)
        self.play_recording_button.show()
        self.record_button = ToggleToolButton(icon_name='media-record')
        self.record_button.set_property('can-default', True)
        self.record_button.show()
        self.play_recording_button.set_sensitive(False)

        self.record_button.connect('clicked', self.__record_button_click_cb)

        self.play_recording_button.connect('clicked',
                                           self.handlePlayRecordingButton)

        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        # TODO: disabe until is implemented with csnd6
        # self.createPercussionToolbar(toolbar_box)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        ti_notes_labels = RadioToolButton()
        ti_notes_labels.props.icon_name = 'ti_key'
        ti_notes_labels.props.group = keybord_labels
        ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb)
        toolbar_box.toolbar.insert(ti_notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        no_labels = RadioToolButton()
        no_labels.props.icon_name = 'edit-clear'
        no_labels.props.group = keybord_labels
        no_labels.connect('clicked', self.set_keyboard_no_labels_cb)
        toolbar_box.toolbar.insert(no_labels, -1)
        self._what_widget = Gtk.ToolItem()
        self._what_search_button = FilterToolItem(_('Select Instrument'),
                                                  'view-type', _('Piano'),
                                                  self._what_widget)
        self._what_widget.show()
        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(self._what_search_button, -1)
        self._what_search_button.show()
        self._what_search_button.set_is_important(True)
        self._what_widget_contents = None
        self._what_drum_widget_contents = None

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(self.record_button, -1)
        toolbar_box.toolbar.insert(self.play_recording_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._save_as_audio_bt = ToolButton(icon_name='save-as-audio')
        self._save_as_audio_bt.props.tooltip = _('Save as audio')
        self._save_as_audio_bt.connect('clicked', self._save_ogg_cb)
        self._save_as_audio_bt.show()
        self._save_as_audio_bt.set_sensitive(False)
        activity_button.page.insert(self._save_as_audio_bt, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI'
        ]
        self.notes_labels = [notes, notes, ['DO']]

        # some countries use TI instead of SI
        ti_notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI'
        ]
        self.ti_notes_labels = [ti_notes, ti_notes, ['DO']]

        german_notes = [
            'C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G',
            ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B'
        ]

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2,
                                   add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.beat = 4
        self.reverb = 0.1
        self.tempo = PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0

        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.drumFillin = Fillin(self.beat, self.tempo, self.rythmInstrument,
                                 self.reverb, self.drumVolume)

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        # TODO commented because apparently are not used in the activity
        # for i in range(10):
        #     self.csnd.load_instrument('guidice' + str(i + 1))

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        self._event_box = Gtk.EventBox()
        self._event_box.modify_bg(Gtk.StateType.NORMAL,
                                  style.COLOR_WHITE.get_gdk_color())
        vbox.pack_start(self._event_box, False, False, 0)
        vbox.pack_end(self.piano, True, True, 0)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self._event_box.set_size_request(
            -1,
            Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
Ejemplo n.º 38
0
def set_sigint_handler(sigint_callback):
    logging.debug('setting SIGINT handler')
    from gi.repository import GLib
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, sigint_callback)
def main(argv):
	parser = optparse.OptionParser(description="faux-gnome-screensaver - a GNOME compatibility layer for XScreenSaver")
	parser.add_option('--no-daemon', action='store_true', dest='no_daemon', default=False, help="Don't become a daemon (not implemented)")
	parser.add_option('--debug', action='store_true', dest='debug', default=False, help="Enable debugging code")
	parser.add_option('--no-dpms', action='store_true', dest='no_dpms', default=False, help="Don't manage DPMS (Energy Star) features")

	options, args = parser.parse_args()

	logging_level = logging.DEBUG if options.debug else logging.INFO
	logging.basicConfig(format=LOG_FORMAT, level=logging_level)

	DBusGMainLoop(set_as_default=True)
	mainloop = GLib.MainLoop()

	def quit(signum=None):
		if signum is not None:
			LOG.debug("Received signal %d, leaving main loop", signum)
		else:
			LOG.debug("Leaving main loop")
		mainloop.quit()

	sighup_id = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, quit, signal.SIGHUP)
	sigterm_id = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, quit, signal.SIGTERM)

	objs = {
		'gset_manager': {
			'obj': GSettingsManager(),
			'signals': []
		},
		'xss_manager': {
			'obj': XScreenSaverManager(options.no_dpms),
			'signals': [
				('active-changed', lambda _, a: getobj('gs_service').active_changed(a))
			]
		},
		'gs_service': {
			'obj': FauxGnomeScreensaverService(),
			'signals': [
				('quit', lambda _: quit()),
				('lock', lambda _: getobj('xss_manager').lock()),
				('simulate-user-activity', lambda _: getobj('xss_manager').simulate_user_activity()),
				('set-active', lambda _, v: setattr(getobj('xss_manager'), 'active', v)),
				('get-active', lambda _: getobj('xss_manager').active),
				('get-active-time', lambda _: getobj('xss_manager').active_time)
			]
		},
		'gsm_listener': {
			'obj': GnomeSessionManagerListener(),
			'signals': [
				('inhibited-changed', lambda _, i: getobj('xss_manager').inhibit() if i else getobj('xss_manager').uninhibit())
			]
		},
		'ck_listener': {
			'obj': ConsoleKitListener(),
			'signals': [
				('lock', lambda _: getobj('xss_manager').lock()),
				('unlock', lambda _: setattr(getobj('xss_manager'), 'active', False)),
				('is-active', lambda _: getobj('xss_manager').simulate_user_activity())
			]
		},
		'sl_listener': {
			'obj': SystemdLogindListener(),
			'signals': [
				('lock', lambda _: getobj('xss_manager').lock()),
				('unlock', lambda _: setattr(getobj('xss_manager'), 'active', False)),
				('is-active', lambda _: getobj('xss_manager').simulate_user_activity())
			]
		}
	}

	order = ['gset_manager', 'xss_manager', 'gs_service', 'gsm_listener', 'ck_listener', 'sl_listener']

	def getobj(k):
		return objs[k]['obj']

	for k in order:
		o = objs[k]
		obj = o['obj']
		ids = []
		for s, h in o['signals']:
			ids.append(obj.connect(s, h))
		o['ids'] = ids

	for k in order:
		getobj(k).activate()

	LOG.debug("Entering main loop")
	try:
		mainloop.run()
	except KeyboardInterrupt:
		LOG.debug("Received signal %d, leaving main loop", signal.SIGINT)

	GLib.source_remove(sighup_id)
	GLib.source_remove(sigterm_id)

	for k in reversed(order):
		getobj(k).deactivate()

	for k in reversed(order):
		o = objs[k]
		obj = o['obj']
		for h in o['ids']:
			obj.disconnect(h)
Ejemplo n.º 40
0
                if options.label:
                    tab.set_labels(options.label)

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

        if error:
            if not tab:
                parser.local_error(error)
            else:
                print(error)
            # Delete the error here; otherwise we keep the local app
            # alive in a reference cycle, and the command line hangs.
            del error

        if parser.should_exit:
            cleanup()
            return parser.exit_status

        parser.command_line = None
        return tab if len(comparisons) == 1 else None


app = MeldApp()

# On Mac OSX, this allows the GTK app to exit cleanly and
# preserve SavedWindowState for the
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, app.quit)
Ejemplo n.º 41
0
def start():
    win = PseudoSink(sys.argv)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, win.onDestroy)
    Gtk.main()
Ejemplo n.º 42
0
def main():
    """
    Main function that starts everything
    """
    options = get_options()

    # Set up global logging for stdout and file
    file_handler = logging.FileHandler(f"{STATE_DIR}/last.log", mode='w+')
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(
        logging.DEBUG if options.verbose else logging.WARNING)
    stream_handler.setFormatter(ColoredFormatter())

    logging.root.handlers = []
    logging.basicConfig(
        level=logging.DEBUG,
        format=
        "%(asctime)s | %(levelname)s | %(message)s | %(module)s.%(funcName)s():%(lineno)s",
        handlers=[file_handler, stream_handler])

    # Logger for actual use in this file
    logger = logging.getLogger()

    logger.info('Ulauncher version %s', VERSION)
    logger.info('Extension API version %s', API_VERSION)
    logger.info("GTK+ %s.%s.%s", Gtk.get_major_version(),
                Gtk.get_minor_version(), Gtk.get_micro_version())
    logger.info("PyGobject+ %i.%i.%i", *gi.version_info)

    logger.info("Desktop: %s (%s) on %s", DESKTOP_NAME, XDG_SESSION_TYPE,
                DISTRO)

    if XDG_SESSION_TYPE != "X11":
        logger.info("X11 backend: %s", ('Yes' if IS_X11_COMPATIBLE else 'No'))
    if (Gtk.get_major_version(), Gtk.get_minor_version()) < (3, 22):
        logger.critical(
            "Ulauncher requires GTK+ version 3.22 or newer. Please upgrade your GTK version."
        )
        sys.exit()
    if gi.version_info < (3, 30, 0):
        logger.critical(
            "Ulauncher requires PyGobject version 3.30 or newer. "
            "See https://github.com/Ulauncher/Ulauncher/issues/1051 for PyGobject upgrade instructions."
        )
        sys.exit()
    if options.no_window_shadow:
        logger.warning(
            "The --no-window-shadow argument has been moved to a user setting")
    if options.hide_window:
        # Ulauncher's "Launch at Login" is now implemented with systemd, but originally
        # it was implemented using XDG autostart. To prevent files created the old way
        # from starting a second Ulauncher background process we have to make sure the
        # --no-window flag prevents the app from starting.
        logger.critical(
            "The --hide-window argument has been renamed to --no-window")
        sys.exit()

    # log uncaught exceptions
    def except_hook(exctype, value, tb):
        logger.error("Uncaught exception", exc_info=(exctype, value, tb))

    sys.excepthook = except_hook

    app = UlauncherApp()

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP,
                         partial(reload_config, app, logger), None)
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, app.quit)

    try:
        app.run(sys.argv)
    except KeyboardInterrupt:
        logger.warning('On KeyboardInterrupt')
def run_pipeline(pipeline,
                 layout,
                 loop,
                 render_overlay,
                 stupid_overlay,
                 display,
                 handle_sigint=True,
                 signals=None):
    # Create pipeline
    pipeline = describe(pipeline)

    pipeline = Gst.parse_launch(pipeline)

    # Set up a pipeline bus watch to catch errors.
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect('message', on_bus_message, pipeline, loop)

    if display is not Display.NONE:
        # Needed to commit the wayland sub-surface.
        def on_gl_draw(sink, widget):
            widget.queue_draw()

        # Needed to account for window chrome etc.
        def on_widget_configure(widget, event, glsink):
            allocation = widget.get_allocation()
            glsink.set_render_rectangle(allocation.x, allocation.y,
                                        allocation.width, allocation.height)
            return False

        window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        window.set_title(WINDOW_TITLE)
        window.set_default_size(layout.render_size.width,
                                layout.render_size.height)
        if display is Display.FULLSCREEN:
            window.fullscreen()

        drawing_area = Gtk.DrawingArea()
        window.add(drawing_area)
        drawing_area.realize()

        glsink = pipeline.get_by_name('glsink')
        glsink.connect('drawn', on_gl_draw, drawing_area)

        # Wayland window handle.
        wl_handle = glsink.get_wayland_window_handle(drawing_area)
        glsink.set_window_handle(wl_handle)

        # Wayland display context wrapped as a GStreamer context.
        wl_display = glsink.get_default_wayland_display_context()
        glsink.set_context(wl_display)

        drawing_area.connect('configure-event', on_widget_configure, glsink)
        window.connect('delete-event', Gtk.main_quit)
        window.show_all()

        # The appsink pipeline branch must use the same GL display as the screen
        # rendering so they get the same GL context. This isn't automatically handled
        # by GStreamer as we're the ones setting an external display handle.
        def on_bus_message_sync(bus, message, glsink):
            if message.type == Gst.MessageType.NEED_CONTEXT:
                _, context_type = message.parse_context_type()
                if context_type == GstGL.GL_DISPLAY_CONTEXT_TYPE:
                    sinkelement = glsink.get_by_interface(
                        GstVideo.VideoOverlay)
                    gl_context = sinkelement.get_property('context')
                    if gl_context:
                        display_context = Gst.Context.new(
                            GstGL.GL_DISPLAY_CONTEXT_TYPE, True)
                        GstGL.context_set_gl_display(display_context,
                                                     gl_context.get_display())
                        message.src.set_context(display_context)
            return Gst.BusSyncReply.PASS

        bus.set_sync_handler(on_bus_message_sync, glsink)

    with Worker(save_frame) as images, Commands() as get_command:
        signals = {
            'appsink': {
                'new-sample':
                functools.partial(on_new_sample,
                                  render_overlay=functools.partial(
                                      render_overlay, layout=layout),
                                  layout=layout,
                                  images=images,
                                  get_command=get_command),
                'eos':
                on_sink_eos
            },
            'stupidsink': {
                'new-sample':
                functools.partial(on_new_sample,
                                  render_overlay=functools.partial(
                                      stupid_overlay, layout=layout),
                                  layout=layout,
                                  images=images,
                                  get_command=get_command),
                'eos':
                on_sink_eos
            },
            **(signals or {})
        }

        for name, signals in signals.items():
            component = pipeline.get_by_name(name)
            if component:
                for signal_name, signal_handler in signals.items():
                    component.connect(signal_name, signal_handler, pipeline)

        # Handle signals.
        if handle_sigint:
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 Gtk.main_quit)

        # Run pipeline.
        pipeline.set_state(Gst.State.PLAYING)
        try:
            Gtk.main()
        except KeyboardInterrupt:
            pass
        finally:
            pipeline.set_state(Gst.State.NULL)

        # Process all pending MainContext operations.
        while GLib.MainContext.default().iteration(False):
            pass
Ejemplo n.º 44
0
def main():
    (options, leftovers) = parse_commandline()

    cli.setupLogging("virt-manager", options.debug, False, False)

    log.debug("virt-manager version: %s", BuildConfig.version)
    log.debug("virtManager import: %s", os.path.dirname(__file__))

    if BuildConfig.running_from_srcdir:
        _setup_gsettings_path(BuildConfig.gsettings_dir)

    if options.trace_libvirt:
        log.debug("Libvirt tracing requested")
        from .lib import module_trace
        import libvirt
        module_trace.wrap_module(
            libvirt,
            mainloop=(options.trace_libvirt == "mainloop"),
            regex=None)

    CLITestOptions = CLITestOptionsClass(options.test_options)

    # With F27 gnome+wayland we need to set these before GTK import
    os.environ["GSETTINGS_SCHEMA_DIR"] = BuildConfig.gsettings_dir

    # Now we've got basic environment up & running we can fork
    do_drop_stdio = False
    if not options.no_fork and not options.debug:
        drop_tty()
        do_drop_stdio = True

        # Ignore SIGHUP, otherwise a serial console closing drops the whole app
        signal.signal(signal.SIGHUP, signal.SIG_IGN)

    leftovers = _import_gtk(leftovers)
    Gtk = globals()["Gtk"]

    # Do this after the Gtk import so the user has a chance of seeing any error
    if do_drop_stdio:
        drop_stdio()

    if leftovers:
        raise RuntimeError("Unhandled command line options '%s'" % leftovers)

    log.debug("PyGObject version: %d.%d.%d", gi.version_info[0],
              gi.version_info[1], gi.version_info[2])
    log.debug("GTK version: %d.%d.%d", Gtk.get_major_version(),
              Gtk.get_minor_version(), Gtk.get_micro_version())

    # Prime the vmmConfig cache
    from . import config
    config.vmmConfig.get_instance(BuildConfig, CLITestOptions)

    # Add our icon dir to icon theme
    icon_theme = Gtk.IconTheme.get_default()
    icon_theme.prepend_search_path(BuildConfig.icon_dir)

    from .engine import vmmEngine
    Gtk.Window.set_default_icon_name("virt-manager")

    show_window = None
    domain = None
    if options.show_domain_creator:
        show_window = vmmEngine.CLI_SHOW_DOMAIN_CREATOR
    elif options.show_host_summary:
        show_window = vmmEngine.CLI_SHOW_HOST_SUMMARY
    elif options.show_domain_editor:
        show_window = vmmEngine.CLI_SHOW_DOMAIN_EDITOR
        domain = options.show_domain_editor
    elif options.show_domain_performance:
        show_window = vmmEngine.CLI_SHOW_DOMAIN_PERFORMANCE
        domain = options.show_domain_performance
    elif options.show_domain_console:
        show_window = vmmEngine.CLI_SHOW_DOMAIN_CONSOLE
        domain = options.show_domain_console
    elif options.show_domain_delete:
        show_window = vmmEngine.CLI_SHOW_DOMAIN_DELETE
        domain = options.show_domain_delete

    if show_window and options.uri is None:  # pragma: no cover
        raise RuntimeError("can't use --show-* options without --connect")

    skip_autostart = False
    if show_window:
        skip_autostart = True

    # Hook libvirt events into glib main loop
    LibvirtGLib.init(None)
    LibvirtGLib.event_register()

    engine = vmmEngine.get_instance()

    # Actually exit when we receive ctrl-c
    from gi.repository import GLib

    def _sigint_handler(user_data):
        ignore = user_data
        log.debug("Received KeyboardInterrupt. Exiting application.")
        engine.exit_app()

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, _sigint_handler,
                         None)

    engine.start(options.uri, show_window, domain, skip_autostart)
Ejemplo n.º 45
0
 def install_glib_handler(sig): # add a unix signal handler
     GLib.unix_signal_add( GLib.PRIORITY_HIGH, 
         sig, # for the given signal
         handler, # on this signal, run this function
         sig # with this argument
         )
Ejemplo n.º 46
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.close)
        Gst.init(None)

        self._what_list = []

        self.play_recording_thread = None

        self.playing_recording = False
        self.firstTime = False
        self.playing = False
        self.regularity = 0.7
        self._drums_store = []
        self.recording = False
        self.recorded_keys = []
        self.is_valid_recording = False

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1
        self.csnd = new_csound_client()
        self.rythmInstrument = 'drum1kick'
        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)
        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        self.play_index = 0

        self.play_recording_button = ToolButton(
            icon_name='media-playback-start')
        self.play_recording_button.set_property('can-default', True)
        self.play_recording_button.show()
        self.record_button = ToggleToolButton(icon_name='media-record')
        self.record_button.set_property('can-default', True)
        self.record_button.show()
        self.play_recording_button.set_sensitive(False)

        self.record_button.connect('clicked', self.__record_button_click_cb)

        self.play_recording_button.connect('clicked',
                                           self.handlePlayRecordingButton)

        toolbar_box.toolbar.set_style(Gtk.ToolbarStyle.BOTH_HORIZ)

        # TODO: disabe until is implemented with csnd6
        # self.createPercussionToolbar(toolbar_box)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        ti_notes_labels = RadioToolButton()
        ti_notes_labels.props.icon_name = 'ti_key'
        ti_notes_labels.props.group = keybord_labels
        ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb)
        toolbar_box.toolbar.insert(ti_notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        no_labels = RadioToolButton()
        no_labels.props.icon_name = 'edit-clear'
        no_labels.props.group = keybord_labels
        no_labels.connect('clicked', self.set_keyboard_no_labels_cb)
        toolbar_box.toolbar.insert(no_labels, -1)
        self._what_widget = Gtk.ToolItem()
        self._what_search_button = FilterToolItem(_('Select Instrument'),
                                                  'view-type',
                                                  _('Piano'),
                                                  self._what_widget)
        self._what_widget.show()
        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)
        toolbar_box.toolbar.insert(self._what_search_button, -1)
        self._what_search_button.show()
        self._what_search_button.set_is_important(True)
        self._what_widget_contents = None
        self._what_drum_widget_contents = None

        separator = Gtk.SeparatorToolItem()
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(self.record_button, -1)
        toolbar_box.toolbar.insert(self.play_recording_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self._save_as_audio_bt = ToolButton(icon_name='save-as-audio')
        self._save_as_audio_bt.props.tooltip = _('Save as audio')
        self._save_as_audio_bt.connect('clicked', self._save_ogg_cb)
        self._save_as_audio_bt.show()
        self._save_as_audio_bt.set_sensitive(False)
        activity_button.page.insert(self._save_as_audio_bt, -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
                 ['FA#', 'SOLb'], 'SOL',
                 ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI']
        self.notes_labels = [notes, notes, ['DO']]

        # some countries use TI instead of SI
        ti_notes = ['DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
                    ['FA#', 'SOLb'], 'SOL',
                    ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI']
        self.ti_notes_labels = [ti_notes, ti_notes, ['DO']]

        german_notes = ['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F',
                        ['F#', 'Gb'], 'G',
                        ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B']

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2, add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.beat = 4
        self.reverb = 0.1
        self.tempo = PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0

        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.drumFillin = Fillin(self.beat,
                                 self.tempo,
                                 self.rythmInstrument,
                                 self.reverb,
                                 self.drumVolume)

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        # TODO commented because apparently are not used in the activity
        # for i in range(10):
        #     self.csnd.load_instrument('guidice' + str(i + 1))

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        self._event_box = Gtk.EventBox()
        self._event_box.modify_bg(
            Gtk.StateType.NORMAL, style.COLOR_WHITE.get_gdk_color())
        vbox.pack_start(self._event_box, False, False, 0)
        vbox.pack_end(self.piano, True, True, 0)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self._event_box.set_size_request(
            -1, Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
Ejemplo n.º 47
0
    def __init__(self):
        # Create the temporary directory
        self.tmp_dir = tempfile.mkdtemp('pdfshuffler')
        os.chmod(self.tmp_dir, 0o700)

        iconsdir = os.path.join(sharedir, 'pdfshuffler', 'icons')
        if not os.path.exists(iconsdir):
            iconsdir = os.path.join(sharedir, 'data')
        Gtk.IconTheme.get_default().append_search_path(iconsdir)
        Gtk.Window.set_default_icon_name('pdfshuffler')

        # Import the user interface file, trying different possible locations
        ui_path = os.path.join(basedir, 'share', 'pdfshuffler',
                               'pdfshuffler.ui')
        if not os.path.exists(ui_path):
            ui_path = os.path.join(basedir, 'data', 'pdfshuffler.ui')
        if not os.path.exists(ui_path):
            ui_path = '/usr/share/pdfshuffler/pdfshuffler.ui'
        if not os.path.exists(ui_path):
            ui_path = '/usr/local/share/pdfshuffler/pdfshuffler.ui'

        self.uiXML = Gtk.Builder()
        self.uiXML.set_translation_domain('pdfshuffler')
        self.uiXML.add_from_file(ui_path)
        self.uiXML.connect_signals(self)

        # Create the main window, and attach delete_event signal to terminating
        # the application
        self.window = self.uiXML.get_object('main_window')
        self.window.set_title(APPNAME)
        self.window.set_border_width(0)
        self.window.set_default_size(self.prefs['window width'],
                                     self.prefs['window height'])
        self.window.connect('delete_event', self.close_application)

        if hasattr(GLib, "unix_signal_add"):
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
                                 self.close_application)

        # Create a scrolled window to hold the thumbnails-container
        self.sw = self.uiXML.get_object('scrolledwindow')
        self.sw.drag_dest_set(
            Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT
            | Gtk.DestDefaults.DROP | Gtk.DestDefaults.MOTION, self.TARGETS_SW,
            Gdk.DragAction.COPY | Gdk.DragAction.MOVE)
        self.sw.connect('drag_data_received', self.sw_dnd_data_received)
        self.sw.connect('button_press_event', self.sw_button_press_event)
        self.sw.connect('scroll_event', self.sw_scroll_event)

        # Create an alignment to keep the thumbnails center-aligned
        align = Gtk.Alignment.new(0.5, 0.5, 0, 0)
        self.sw.add_with_viewport(align)

        # Create ListStore model and IconView
        self.model = Gtk.ListStore(
            str,  # 0.Text descriptor
            GObject.TYPE_PYOBJECT,
            # 1.Cached page image
            int,  # 2.Document number
            int,  # 3.Page number
            float,  # 4.Scale
            str,  # 5.Document filename
            int,  # 6.Rotation angle
            float,  # 7.Crop left
            float,  # 8.Crop right
            float,  # 9.Crop top
            float,  # 10.Crop bottom
            float,  # 11.Page width
            float,  # 12.Page height
            float)  # 13.Resampling factor

        self.zoom_set(self.prefs['initial zoom level'])
        self.iv_col_width = self.prefs['initial thumbnail size']

        self.iconview = Gtk.IconView(self.model)
        self.iconview.clear()
        self.iconview.set_item_width(-1)  #self.iv_col_width + 12)

        self.cellthmb = CellRendererImage()
        self.iconview.pack_start(self.cellthmb, False)
        self.iconview.set_cell_data_func(self.cellthmb,
                                         self.set_cellrenderer_data, None)
        #        self.iconview.add_attribute(self.cellthmb, 'image', 1)
        #        self.iconview.add_attribute(self.cellthmb, 'scale', 4)
        #        self.iconview.add_attribute(self.cellthmb, 'rotation', 6)
        #        self.iconview.add_attribute(self.cellthmb, 'cropL', 7)
        #        self.iconview.add_attribute(self.cellthmb, 'cropR', 8)
        #        self.iconview.add_attribute(self.cellthmb, 'cropT', 9)
        #        self.iconview.add_attribute(self.cellthmb, 'cropB', 10)
        #        self.iconview.add_attribute(self.cellthmb, 'width', 11)
        #        self.iconview.add_attribute(self.cellthmb, 'height', 12)
        #        self.iconview.add_attribute(self.cellthmb, 'resample', 13)

        #        self.celltxt = Gtk.CellRendererText()
        #        self.celltxt.set_property('width', self.iv_col_width)
        #        self.celltxt.set_property('wrap-width', self.iv_col_width)
        #        self.celltxt.set_property('alignment', Pango.Alignment.CENTER)
        #        self.iconview.pack_start(self.celltxt, False)
        #        self.iconview.add_attribute(self.celltxt, 'text', 0)
        self.iconview.set_text_column(0)

        self.iconview.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
        self.iconview.enable_model_drag_source(
            Gdk.ModifierType.BUTTON1_MASK, self.TARGETS_IV,
            Gdk.DragAction.COPY | Gdk.DragAction.MOVE)
        self.iconview.enable_model_drag_dest(self.TARGETS_IV,
                                             Gdk.DragAction.DEFAULT)
        self.iconview.connect('drag_begin', self.iv_drag_begin)
        self.iconview.connect('drag_data_get', self.iv_dnd_data_get)
        self.iconview.connect('drag_data_received', self.iv_dnd_data_received)
        self.iconview.connect('drag_data_delete', self.iv_dnd_data_delete)
        self.iconview.connect('drag_motion', self.iv_dnd_motion)
        self.iconview.connect('drag_leave', self.iv_dnd_leave)
        self.iconview.connect('drag_end', self.iv_dnd_leave)
        self.iconview.connect('button_press_event', self.iv_button_press_event)
        self.iconview.connect('motion_notify_event', self.iv_motion)
        self.iconview.connect('button_release_event',
                              self.iv_button_release_event)

        align.add(self.iconview)

        # Progress bar
        self.progress_bar = self.uiXML.get_object('progressbar')
        self.progress_bar_timeout_id = 0

        # Define window callback function and show window
        self.window.connect('size_allocate',
                            self.on_window_size_request)  # resize
        self.window.connect('key_press_event',
                            self.on_keypress_event)  # keypress
        self.window.show_all()
        self.progress_bar.hide()

        # Change iconview color background
        style_context_sw = self.sw.get_style_context()
        color_selected = self.iconview.get_style_context()\
                             .get_background_color(Gtk.StateFlags.SELECTED)
        color_prelight = color_selected.copy()
        color_prelight.alpha = 0.3
        for state in (Gtk.StateFlags.NORMAL, Gtk.StateFlags.ACTIVE):
            self.iconview.override_background_color \
               (state, style_context_sw.get_background_color(state))
        self.iconview.override_background_color(Gtk.StateFlags.SELECTED,
                                                color_selected)
        self.iconview.override_background_color(Gtk.StateFlags.PRELIGHT,
                                                color_prelight)

        # Creating the popup menu
        self.popup = Gtk.Menu()
        labels = (_('_Rotate Right'), _('Rotate _Left'), _('C_rop...'),
                  _('_Delete'), _('_Export selection...'))
        cbs = (self.rotate_page_right, self.rotate_page_left,
               self.crop_page_dialog, self.clear_selected,
               self.choose_export_selection_pdf_name)
        for label, cb in zip(labels, cbs):
            popup_item = Gtk.MenuItem.new_with_mnemonic(label)
            popup_item.connect('activate', cb)
            popup_item.show()
            self.popup.append(popup_item)

        # Initializing variables
        self.export_directory = os.path.expanduser('~')
        self.import_directory = self.export_directory
        self.nfile = 0
        self.iv_auto_scroll_direction = 0
        self.iv_auto_scroll_timer = None
        self.pdfqueue = []
        self.pressed_button = None

        GObject.type_register(PDFRenderer)
        GObject.signal_new(
            'update_thumbnail', PDFRenderer, GObject.SignalFlags.RUN_FIRST,
            None,
            [GObject.TYPE_INT, GObject.TYPE_PYOBJECT, GObject.TYPE_FLOAT])
        self.rendering_thread = None

        self.set_unsaved(False)

        # Importing documents passed as command line arguments
        for filename in sys.argv[1:]:
            self.add_pdf_pages(filename)
Ejemplo n.º 48
0
   def __init__(self, app, log, config, settings, playlist, stationlist):

      app.connect('window_removed', self.on_destroy)

      self.win = Gtk.ApplicationWindow(application=app)
      self.win.set_title(config['name'].capitalize())
      self.win.set_default_size(width=int(settings['size_x']), height=int(settings['size_y']))
      #self.win.set_size_request(width=int(settings['size_x']), height=int(settings['size_y']))
      self.win.set_resizable(True)

      self.win.get_root().connect_after('notify', self.on_notify)

      self.log = log
      self.config = config
      self.settings = settings
      self.playlist = playlist
      self.stationlist = stationlist

      gtk_settings = Gtk.Settings.get_default()
      gtk_theme_name = gtk_settings.get_property('gtk-theme-name')
      self.log.debug('gtk_theme_name: %s' % gtk_theme_name)
      #gtk_settings.set_property('gtk-theme-name', 'Adwaita-dark')
      #gtk_settings.set_property('gtk-theme-name', 'Adwaita')



      self.pnum = 0

      # self.process_database[item]['status'] -> active, inactive, killed
      # self.process_database[item]['todo']   -> show, nooutput, result
      # self.process_database[item]['result'] -> True, False
      self.process_database = {}


      self.notebook = Gtk.Notebook()
      self.win.set_child(self.notebook)

      self.notebook_tab_musicplayer = tab_musicplayer.TabMusicPlayer(self, log, config, settings, playlist)
      self.notebook_tab_converter = tab_coverter.TabConverter(self, log, config, settings)
      self.notebook_tab_streamripper = tab_streamripper.TabStreamRipper(self, log, config, settings, stationlist)
      self.notebook_tab_settings = tab_settings.TabSettings(self, log, config, settings)
      self.notebook_tab_about = tab_about.TabAbout(self, log, config, settings)



      # size 994 (hbox1)
      self.notebook.append_page(self.notebook_tab_musicplayer.box, Gtk.Label(label='Music Player'))
      # size 594
      self.notebook.append_page(self.notebook_tab_converter.vbox, Gtk.Label(label='Converter'))
      # size 901
      self.notebook.append_page(self.notebook_tab_streamripper.hbox, Gtk.Label(label='Streamripper'))
      # size 996
      self.notebook.append_page(self.notebook_tab_settings.vbox, Gtk.Label(label='Settings'))
      # size 743
      self.notebook.append_page(self.notebook_tab_about.box, Gtk.Image.new_from_icon_name('help-about'))



      try:
         thread = Thread(target=self.ipc_server)
         thread.setDaemon(True)
         thread.start()
      except Exception as e:
         self.log.debug('ipc_server error: %s' % str(e))


      GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.signal_handler_sigint)

      self.win.present()
Ejemplo n.º 49
0
  def build_gui(self):
    self.win = win = Gtk.Window(title='Gnomecast v%s' % __version__)
    win.set_border_width(0)
    win.set_icon(self.get_logo_pixbuf(color='#000000'))
    self.cast_store = cast_store = Gtk.ListStore(object, str)

    vbox_outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=16)
    
    self.thumbnail_image = Gtk.Image()
    self.thumbnail_image.set_from_pixbuf(self.get_logo_pixbuf())
    vbox_outer.pack_start(self.thumbnail_image, True, False, 0)
    alignment = Gtk.Alignment(xscale=1, yscale=1)
    alignment.add(vbox)
    alignment.set_padding(16, 20, 16, 16)
    vbox_outer.pack_start(alignment, False, False, 0)

    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
    vbox.pack_start(hbox, False, False, 0)
    self.cast_combo = cast_combo = Gtk.ComboBox.new_with_model(cast_store)
    cast_combo.set_entry_text_column(1)
    renderer_text = Gtk.CellRendererText()
    cast_combo.pack_start(renderer_text, True)
    cast_combo.add_attribute(renderer_text, "text", 1)
    hbox.pack_start(cast_combo, True, True, 0)
    refresh_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_REFRESH))
    refresh_button.connect("clicked", self.init_casts)
    hbox.pack_start(refresh_button, False, False, 0)

    win.add(vbox_outer)

    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
    vbox.pack_start(hbox, False, False, 0)
    self.file_button = button1 = Gtk.Button("Choose an audio or video file...")
    button1.connect("clicked", self.on_file_clicked)
    hbox.pack_start(button1, True, True, 0)
    self.save_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_SAVE))
    self.save_button.set_tooltip_text('Overwrite original file with transcoded version.')
    self.save_button.connect("clicked", self.save_transcoded_file)
    hbox.pack_start(self.save_button, False, False, 0)

    self.subtitle_store = subtitle_store = Gtk.ListStore(str, int, str)
    subtitle_store.append(["No subtitles.", -1, None])
    subtitle_store.append(["Add subtitle file...", -2, None])
    self.subtitle_combo = Gtk.ComboBox.new_with_model(subtitle_store)
    self.subtitle_combo.connect("changed", self.on_subtitle_combo_changed)
    self.subtitle_combo.set_entry_text_column(0)
    renderer_text = Gtk.CellRendererText()
    self.subtitle_combo.pack_start(renderer_text, True)
    self.subtitle_combo.add_attribute(renderer_text, "text", 0)
    self.subtitle_combo.set_active(0)
    vbox.pack_start(self.subtitle_combo, False, False, 0)
    
    self.scrubber_adj = Gtk.Adjustment(0, 0, 100, 15, 60, 0)
    self.scrubber = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=self.scrubber_adj)
    self.scrubber.set_digits(0)
    def f(scale, s):
      notes = [self.humanize_seconds(s)]
      return ''.join(notes)
    self.scrubber.connect("format-value", f)
    self.scrubber.connect("change-value", self.scrubber_move_started)
    self.scrubber.connect("change-value", self.scrubber_moved)
    self.scrubber.set_sensitive(False)
    vbox.pack_start(self.scrubber, False, False, 0)

    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
    self.rewind_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_MEDIA_REWIND))
    self.rewind_button.connect("clicked", self.rewind_clicked)
    self.rewind_button.set_sensitive(False)
    self.rewind_button.set_relief(Gtk.ReliefStyle.NONE)
    hbox.pack_start(self.rewind_button, True, False, 0)
    self.play_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_MEDIA_PLAY))
    self.play_button.connect("clicked", self.play_clicked)
    self.play_button.set_sensitive(False)
    self.play_button.set_relief(Gtk.ReliefStyle.NONE)
    hbox.pack_start(self.play_button, True, False, 0)
    self.forward_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_MEDIA_FORWARD))
    self.forward_button.connect("clicked", self.forward_clicked)
    self.forward_button.set_sensitive(False)
    self.forward_button.set_relief(Gtk.ReliefStyle.NONE)
    hbox.pack_start(self.forward_button, True, False, 0)
    self.stop_button = Gtk.Button(None, image=Gtk.Image(stock=Gtk.STOCK_MEDIA_STOP))
    self.stop_button.connect("clicked", self.stop_clicked)
    self.stop_button.set_sensitive(False)
    self.stop_button.set_relief(Gtk.ReliefStyle.NONE)
    hbox.pack_start(self.stop_button, True, False, 0)
    self.volume_button = Gtk.VolumeButton()
    self.volume_button.set_value(1)
    self.volume_button.connect("value-changed", self.volume_moved)
    self.volume_button.set_sensitive(False)
    hbox.pack_start(self.volume_button, True, False, 0)
    vbox.pack_start(hbox, False, False, 0)
    
    cast_combo.connect("changed", self.on_cast_combo_changed)

    win.connect("delete-event", self.quit)
    win.connect("key_press_event", self.on_key_press)
    win.show_all()

    self.save_button.set_visible(False)

    win.resize(1,1)

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, self.quit)
Ejemplo n.º 50
0
    def run(self):
        WrtUtil.ensureDir(self.param.varDir)
        WrtUtil.mkDirAndClear(self.param.tmpDir)
        WrtUtil.mkDirAndClear(self.param.runDir)
        try:
            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(WrtUtil.getLoggingLevel(self.param.logLevel))
            logging.info("Program begins.")

            # manipulate iptables
            if not self.param.abortOnError:
                WrtUtil.iptablesSetEmpty()
            else:
                if not WrtUtil.iptablesIsEmpty():
                    raise Exception("iptables is not empty, wrtd use iptables exclusively")

            # load configuration
            self._loadCfg()

            # load UUID
            if WrtCommon.loadUuid(self.param):
                logging.info("UUID generated: \"%s\"." % (self.param.uuid))
            else:
                logging.info("UUID loaded: \"%s\"." % (self.param.uuid))

            # write pid file
            with open(self.param.pidFile, "w") as f:
                f.write(str(os.getpid()))

            # load plugin hub
            self.param.pluginHub = PluginHub(self.param)
            logging.info("Plugin HUB loaded.")

            # load prefix pool
            self.param.prefixPool = PrefixPool(os.path.join(self.param.varDir, "prefix-pool.json"))
            logging.info("Prefix pool loaded.")

            # create our own resolv.conf
            with open(self.param.ownResolvConf, "w") as f:
                f.write("")

            # load manager caller
            self.param.managerCaller = ManagerCaller(self.param)
            logging.info("Manager caller initialized.")

            # create main loop
            DBusGMainLoop(set_as_default=True)
            self.param.mainloop = GLib.MainLoop()

            # business initialize
            self.param.trafficManager = WrtTrafficManager(self.param)
            self.param.wanManager = WrtWanManager(self.param)
            self.param.lanManager = WrtLanManager(self.param)
            self._loadManagerPlugins()
            self.interfaceTimer = GObject.timeout_add_seconds(0, self._interfaceTimerCallback)

            # enable ip forward
            if WrtUtil.readFile(self.param.procIpForwareFile) == "0":
                with open(self.param.procIpForwareFile, "w") as f:
                    f.write("1")
                logging.info("IP forwarding enabled.")
            else:
                logging.warn("IP forwarding already enabled.")

            # start DBUS API server
            self.param.dbusMainObject = DbusMainObject(self.param)
            self.param.dbusIpForwardObject = DbusIpForwardObject(self.param)
            logging.info("DBUS-API server started.")

            # start main loop
            logging.info("Mainloop begins.")
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None)
            GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, self._sigHandlerHUP, None)
            self.param.mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            if self.interfaceTimer is not None:
                GLib.source_remove(self.interfaceTimer)
                self.interfaceTimer = None
            if True:
                for p in self.managerPluginDict.values():
                    p.dispose()
                    logging.info("Manager plugin \"%s\" deactivated." % (p.full_name))
                self.managerPluginDict = dict()
            if self.param.lanManager is not None:
                self.param.lanManager.dispose()
                self.param.lanManager = None
            if self.param.wanManager is not None:
                self.param.wanManager.dispose()
                self.param.wanManager = None
            if self.param.trafficManager is not None:
                self.param.trafficManager.dispose()
                self.param.trafficManager = None
            logging.shutdown()
            shutil.rmtree(self.param.tmpDir)
            if self.bRestart:
                WrtUtil.restartProgram()
Ejemplo n.º 51
0
    def run(self):
        if not os.path.exists(CConst.varDir):
            os.makedirs(CConst.varDir)
        CUtil.mkDirAndClear(self.param.tmpDir)
        CUtil.mkDirAndClear(CConst.runDir)

        try:
            logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
            logging.getLogger().setLevel(
                CUtil.getLoggingLevel(self.param.logLevel))
            logging.info("Program begins.")

            # create main loop
            self.mainloop = GLib.MainLoop()

            # write pid file
            with open(self.param.pidFile, "w") as f:
                f.write(str(os.getpid()))

            # check certificate and private key, generate if neccessary
            if not os.path.exists(self.param.certFile) or not os.path.exists(
                    self.param.privkeyFile):
                cert, key = CUtil.genSelfSignedCertAndKey(
                    "conduit", CConst.keySize)
                CUtil.dumpCertAndKey(cert, key, self.param.certFile,
                                     self.param.privkeyFile)
                logging.info('Certificate and private key generated.')

            # load built-in data-types
            self.param.dataTypeDict.update(BuiltInDataTypes.getDataTypeDict())

            # load built-in protocols
            self.param.protocolDict.update(BuiltInProtocols.getProtocolDict())

            # load plugins
            CPluginManager(self.param).loadPlugins()

            # start control server
            self.ctrlServer = CCtrlServer(self.param)
            self.ctrlServer.start()
            logging.info('Control server started.')

            # register serivce
            if CConst.avahiSupport:
                self.avahiObj = AvahiServiceRegister()
                self.avahiObj.add_service(socket.gethostname(),
                                          "_conduit._tcp",
                                          self.ctrlServer.getPort())
                self.avahiObj.start()

            # start main loop
            logging.info("Mainloop begins.")
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT,
                                 self._sigHandlerINT, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM,
                                 self._sigHandlerTERM, None)
            GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGUSR2,
                                 self._sigHandlerUSR2,
                                 None)  # let the process ignore SIGUSR2, we
            signal.siginterrupt(
                signal.SIGUSR2,
                True)  # use it to interrupt blocking system calls
            self.mainloop.run()
            logging.info("Mainloop exits.")
        finally:
            if self.avahiObj is not None:
                self.avahiObj.stop()
            if self.ctrlServer is not None:
                self.ctrlServer.stop()
            logging.shutdown()
            shutil.rmtree(CConst.runDir)
            shutil.rmtree(self.param.tmpDir)
            logging.info("Program exits.")
Ejemplo n.º 52
0
 def install_handler(self, sig):
     GLib.unix_signal_add(GLib.PRIORITY_HIGH, sig,
                          self.sig_refresh_grid_tasks, None)