Ejemplo n.º 1
0
    def __init__(self, halcomp, builder, useropts):
        '''
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        '''
        
        # TODO: add a signal to check if the relay for spindle-pump is ON
        halcomp.newpin("spindle.fwd", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.rev", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.jog-fwd", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.jog-rev", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.pump", hal.HAL_BIT, hal.HAL_OUT)

        self.halcomp = halcomp
        self.builder = builder
        self.nhits = 0
        
        self.ini_filename = __name__ + '.ini'
        self.defaults = {  IniFile.vars: dict(),
                           IniFile.widgets : widget_defaults(select_widgets(self.builder.get_objects(), hal_only=False,output_only = True))
                        }
        self.ini = IniFile(self.ini_filename,self.defaults,self.builder)
        self.ini.restore_state(self)

        self.e = EmcInterface()

        glib.timeout_add_seconds(1, self._query_emc_status)
Ejemplo n.º 2
0
def start(discoverer):
    pgnfile, gameno = queryGameno(sys.argv[1])
    analyzer = queryAnalyzer(list(discoverer.getAnalyzers()))
    secs = queryTime()
    name1, name2 = pgnfile.get_player_names(gameno)
    print "%s will now analyze the game between %s and %s with %d seconds per move." % \
            (discoverer.getName(analyzer), name1, name2, secs)
    print

    global game, values
    values = {}
    game = GameModel()
    game.setPlayers([DummyPlayer(), DummyPlayer()])
    analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant)
    analyzer.connect('analyze', onAnalyze)
    game.setSpectactors({0: analyzer})
    game.loadAndStart(sys.argv[1], pgn, gameno, -1)

    def cb():
        if game.ply == game.lowply:
            on_finish()
            return False
        check_blund()
        return True

    glib.timeout_add_seconds(secs, cb)
    def on_name_owner_changed(self, service, prev_owner, new_owner):
        # print("name_owner_changed: %s; %s; %s" % (service, prev_owner, new_owner))
        if (
                new_owner == '' and not service.startswith(':')
        ):  # a service has disappear from the bus, check if it was an item or a host.
            # search amongst the items.
            match = service + '/'
            # print("  search for ",match)
            to_be_removed = []
            for it in self.items_list:
                # print("  check for ",it)
                if (it.startswith(match)):  # it[0:len(match)] == match
                    # print("    match!")
                    to_be_removed.append(it)
            for it in to_be_removed:
                self.items_list.remove(it)
                self.StatusNotifierItemUnregistered(it)

            # search amongst the hosts.
            to_be_removed = []
            for it in self.hosts_list:
                if (it == service):
                    to_be_removed.append(it)
            for it in to_be_removed:
                self.hosts_list.remove(it)
                self.StatusNotifierHostUnregistered()
        elif (
                service == 'com.Skype.API'
        ):  # this stupid proprietary software only creates its item when the host appears !
            glib.timeout_add_seconds(2, self._emit_host_registered)
Ejemplo n.º 4
0
    def on_tick(self):
        """ Skip to another picture.

        If this picture is last, go to the first one. """

        # TODO: check did we manage to show the last image?
        if g_lastpainted == self.files[self.index]:
            print "happiness"
        else:
            print "much SADness, we should wait some more", g_lastpainted
            print "much SADness, we should wait some more", self.index
            print "much SADness, we should wait some more", self.files[self.index]

        global g_pause
        if not g_pause:
            self.index += 1
            if self.index >= len(self.files):
                if g_repeat:
                    print "wrap"
                    self.index = 0
                else:
                    # end of show
                    sys.exit(0)

        rv = self.display()

        if self.old_slide_time != self.SECONDS_BETWEEN_PICTURES:
            # change time and register new time
            glib.timeout_add_seconds(self.SECONDS_BETWEEN_PICTURES, self.on_tick)
            self.old_slide_time = self.SECONDS_BETWEEN_PICTURES
            rv = False

        # returning false destroys the old timer
        return rv
Ejemplo n.º 5
0
    def __init__(self, halcomp, builder, useropts):
        '''
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        '''
        
        # TODO: add a signal to check if the relay for spindle-pump is ON
        halcomp.newpin("spindle.fwd", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.rev", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.jog-fwd", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.jog-rev", hal.HAL_BIT, hal.HAL_IN)
        halcomp.newpin("spindle.pump", hal.HAL_BIT, hal.HAL_OUT)

        self.halcomp = halcomp
        self.builder = builder
        self.nhits = 0
        
        self.ini_filename = __name__ + '.ini'
        self.defaults = {  IniFile.vars: dict(),
                           IniFile.widgets : widget_defaults(select_widgets(self.builder.get_objects(), hal_only=False,output_only = True))
                        }
        self.ini = IniFile(self.ini_filename,self.defaults,self.builder)
        self.ini.restore_state(self)

        self.e = EmcInterface()

        glib.timeout_add_seconds(1, self._query_emc_status)
Ejemplo n.º 6
0
 def on_user_typing(self, account):
     """
     inform that the other user has started typing
     """
     if account in self.members:
         self.tab_label.set_image(gui.theme.image_theme.typing)
         glib.timeout_add_seconds(3, self.update_tab)
Ejemplo n.º 7
0
def start(discoverer):
    pgnfile, gameno = queryGameno(sys.argv[1])
    analyzer = queryAnalyzer(list(discoverer.getAnalyzers()))
    secs = queryTime()
    name1, name2 = pgnfile.get_player_names(gameno)
    print "%s will now analyze the game between %s and %s with %d seconds per move." % \
            (discoverer.getName(analyzer), name1, name2, secs)
    print
    
    global game, values
    values = {}
    game = GameModel()
    game.setPlayers([DummyPlayer(), DummyPlayer()])
    analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant)
    analyzer.connect('analyze', onAnalyze)
    game.setSpectactors({0: analyzer})
    game.loadAndStart(sys.argv[1], pgn, gameno, -1)
    
    def cb():
        if game.ply == game.lowply:
            on_finish()
            return False
        check_blund()
        return True
    glib.timeout_add_seconds(secs, cb)
Ejemplo n.º 8
0
def _find_printreader():
    global FingerDevice
    dialog = None
    while not FingerDevice:
        devs = pyfprint.discover_devices()
        if len(devs) == 0:
            if not dialog:
                msg = 'Fingerprint scanner not found'
                dialog = gtk.MessageDialog(type = gtk.MESSAGE_WARNING,
                                           message_format = msg)
                dialog.set_modal(True)
                dialog.show()
        else:
            FingerDevice = devs[0]
            break
        glib.timeout_add_seconds(1, done_waiting)
        gtk.main()

    FingerDevice.open()
    if not FingerDevice.supports_identification():
        raise "Device cannot do identification"
    #print "Found a " + FingerDevice.driver().full_name()
    if dialog:
        dialog.hide()
        dialog.destroy()
 def run(self):
     '''Run.'''
     # Run first time.
     self.update()
     
     # Update package list every 24 hours.
     glib.timeout_add_seconds(60 * 60 * 24, self.update)
    def __init__(self):
        home = os.curdir                       
        if 'HOME' in os.environ:
            home = os.environ['HOME']
        elif os.name == 'posix':
            home = os.path.expanduser("~/")
        elif os.name == 'nt':
            if 'HOMEPATH' in os.environ and 'HOMEDRIVE' in os.environ:
                home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
        else:
            home = os.environ['HOMEPATH']

        if os.path.isfile(home+"/.config/unread-mail-indicator/config.ini")==False:
            setup.main()
            
        self.Config = ConfigParser.ConfigParser()
        self.Config.read(home+"/.config/unread-mail-indicator/config.ini")
        print self.Config.sections()

        self.ind = appindicator.Indicator("Unread-Mail-Notify", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS)
        self.callback_minutes = int(self.Config.get('Basics', 'CheckIntervalMinutes'))
        self.strNoUnreadMails = self.Config.get('Strings', 'strNoUnreadMails')
        self.strUnreadMails = self.Config.get('Strings', 'strUnreadMails')
        self.notificationEnabled = self.Config.get('Basics', 'ShowNotifications')
        self.notificationTitle = self.Config.get('Strings', 'notificationTitle')
        self.notificationIcon = 'indicator-messages-new'
        self.actionOnClick = "thunderbird"
        self.set_menu()   
        glib.timeout_add_seconds(int(60)*self.callback_minutes, self.work)
Ejemplo n.º 11
0
    def __init__(self):
        self.io = telegraph.telegraph()
        self.io.set_pub_cb(self.msg_cb)
        self.started = False
        self.running = True
        self.rscount = 0
        self.fh = 0
        self.motd = ''
        self.failcount = 0
        self.failthresh = 45  # connect timeout ~45sec
        self.remoteuser = u''
        self.fullscreen = False  # maximise window?

        b = gtk.Builder()
        b.add_from_file(os.path.join(metarace.UI_PATH, 'announce.ui'))
        self.window = b.get_object('window')
        self.window.set_decorated(False)
        self.window.set_default_size(400, 300)
        self.buffer = b.get_object('buffer')
        self.view = b.get_object('view')
        #self.view.modify_base(gtk.STATE_NORMAL, gtk.gdk.Color('#001'))
        #self.view.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color('#001'))
        #self.view.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color('#001'))
        #self.view.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color('#eef'))
        self.clear()  # compulsory clear -> fills all lines
        self.intro()
        glib.timeout_add_seconds(5, self.delayed_cursor)
        b.connect_signals(self)
Ejemplo n.º 12
0
 def on_user_typing(self, account):
     """
     inform that the other user has started typing
     """
     if account in self.members:
         self.tab_label.set_image(gui.theme.image_theme.typing)
         glib.timeout_add_seconds(3, self.update_tab)
    def run(self):
        '''Run.'''
        # Run first time.
        self.update()

        # Update package list every 24 hours.
        glib.timeout_add_seconds(60 * 60 * 24, self.update)
Ejemplo n.º 14
0
 def starttrig(self, e):
     """React to start trigger."""
     if self.timerstat == 'armstart':
         self.start = e
         self.lstart = tod.tod('now')
         self.setrunning()
         glib.timeout_add_seconds(4, self.armfinish)
Ejemplo n.º 15
0
 def fireEvent(self):
     camera = Camera(self.config)
     camera.takePictures()
     camera = None
     self.processPictures()
     glib.timeout_add_seconds(10, self.resetDisplay)
     return False
Ejemplo n.º 16
0
    def __init__(self, halcomp, builder, useropts):
        """
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        """
        self.halcomp = halcomp
        self.builder = builder

        (directory, filename) = os.path.split(__file__)
        (basename, extension) = os.path.splitext(filename)
        self.ini_filename = os.path.join(directory, basename + ".ini")

        # the dict driving the ini file persistence feature
        # a signature checks variable names,types,sections
        #
        # to see the mechanism at work, do this:
        # - run the application, change some values, and exit
        # - edit the complex.ini file and change a variable name in the widgets or vars section
        #   for example, rename 'a' to 'z'
        #   and remove one of the widgets in the widgets section
        # - then re-run the application
        # during startup, you get a message saying
        # "key 'a' in section 'vars' : missing"
        # "key 'hal_radiobutton1' in section 'widgets' : missing"
        #
        # to see how the protection of ini file versus a changed program works,
        # change the defaults dict below, for instance remove the 'c' : "a string variable
        # then re-run - the signature check at startup should fail, you should get:
        # "signature mismatch in ./complex.ini -  resetting to default"
        # and a default ini file is generated

        self.defaults = {  # these will be saved/restored as method attributes
            IniFile.vars: {"nhits": 0, "lifetime_ticks": 0, "a": 1.67, "d": True, "c": "a string"},
            # we're interested restoring state to output HAL widgets only
            # NB: this does NOT restore state pf plain gtk objects - set hal_only to False to do this
            IniFile.widgets: widget_defaults(
                select_widgets(self.builder.get_objects(), hal_only=True, output_only=True)
            ),
        }

        self.ini = IniFile(self.ini_filename, self.defaults, self.builder)
        self.ini.restore_state(self)

        # at this point it is ok to refer to restored attributes like self.nhits and self.lifetime_ticks:
        self.builder.get_object("hal_button1").set_label("past hits: %d" % self.nhits)
        self.builder.get_object("message").hal_pin.set(self.lifetime_ticks)

        self._hal_setup(halcomp, builder)

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
                def expires_normal(color):
                    self.modify_bg(gtk.STATE_NORMAL, color)
                    self.child.modify_fg(gtk.STATE_NORMAL,
                                         gtk.gdk.Color(0, 0, 0))

                    glib.timeout_add_seconds(1, expires_inverted, color)
                    return False
Ejemplo n.º 18
0
    def __init__(self, halcomp, builder, useropts, compname):
        '''
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        '''

        self.halcomp = halcomp
        self.builder = builder

        self.halcomp.newpin("value", hal.HAL_FLOAT, hal.HAL_OUT)
        self.start = time.time()
        self.nhits = 0
        self.ticks = 0

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
Ejemplo n.º 19
0
	def _linger (self):
		"""
		Display for a short while
		"""
		self.show_all ()
		glib.timeout_add_seconds (self.linger_time, self.hide)
			
 def main(self):
     '''Main.'''
     # Send statistics information.
     AnonymityThread(sendStatistics).start()
     
     # Just show tray icon when have updatable packages.
     self.updateNum = self.calculateUpdateNumber()
     if self.updateNum > 0:
         print "Show tray icon."
         
         gtk.gdk.threads_init()        
         
         self.trayIcon = gtk.StatusIcon()
         self.trayIcon.set_from_file("../icon/icon.png")
         self.trayIcon.set_has_tooltip(True)
         self.trayIcon.set_visible(True)
         self.trayIcon.connect("activate", lambda w: self.showSoftwareCenter())
         self.trayIcon.connect("query-tooltip", self.hoverIcon)
         self.trayIcon.connect("popup-menu", self.handleRightClick)
         
         # Show tooltips.
         # Add timeout to make tooltip display at correct coordinate.
         glib.timeout_add_seconds(1, self.hoverIcon)
         
         gtk.main()
     else:
         print "No updatable packages, exit."
Ejemplo n.º 21
0
    def __init__(self, halcomp, builder, useropts, compname):
        '''
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        '''
        self.halcomp = halcomp
        self.builder = builder

        (directory, filename) = os.path.split(__file__)
        (basename, extension) = os.path.splitext(filename)
        self.ini_filename = os.path.join(directory, basename + '.save')

        # the dict driving the ini file persistence feature
        # a signature checks variable names,types,sections
        #
        # to see the mechanism at work, do this:
        # - run the application, change some values, and exit
        # - edit the complex.save file and change a variable name in the widgets or vars section
        #   for example, rename 'a' to 'z'
        #   and remove one of the widgets in the widgets section
        # - then re-run the application
        # during startup, you get a message saying
        # "key 'a' in section 'vars' : missing"
        # "key 'hal_radiobutton1' in section 'widgets' : missing"
        #
        # to see how the protection of ini file versus a changed program works,
        # change the defaults dict below, for instance remove the 'c' : "a string variable
        # then re-run - the signature check at startup should fail, you should get:
        # "signature mismatch in ./complex.save -  resetting to default"
        # and a default ini file is generated

        self.defaults = {  # these will be saved/restored as method attributes
                            IniFile.vars: { 'nhits' : 0, 'lifetime_ticks': 0, 'a': 1.67, 'd': True, 'c' :  "a string"},

                            # we're interested restoring state to output HAL widgets only
                            # NB: this does NOT restore state pf plain gtk objects - set hal_only to False to do this
                            IniFile.widgets: widget_defaults(select_widgets(self.builder.get_objects(), hal_only=True,output_only = True)),
                       }

        self.ini = IniFile(self.ini_filename, self.defaults, self.builder)
        self.ini.restore_state(self)

        # at this point it is ok to refer to restored attributes like self.nhits and self.lifetime_ticks:
        self.builder.get_object('hal_button1').set_label("past hits: %d" %
                                                         self.nhits)
        self.builder.get_object('message').hal_pin.set(self.lifetime_ticks)

        self._hal_setup(halcomp, builder)

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
Ejemplo n.º 22
0
    def __init__(self):
        # logger and handler
        self.log = logging.getLogger()
        self.log.setLevel(logging.DEBUG)
        self.loghandler = logging.FileHandler(LOGFILE)
        self.loghandler.setLevel(logging.DEBUG)
        self.loghandler.setFormatter(logging.Formatter(
                       '%(asctime)s %(levelname)s:%(name)s: %(message)s'))
        self.log.addHandler(self.loghandler)
        self.log.info(u'IRTT Starter - Init.')

        # require one timy and one uscbsrv
        self.timer = timy.timy()
        self.scb = telegraph.telegraph()

        self.started = False
        self.running = True

        # Audio output
        self.player = gst.element_factory_make("playbin2", "player")
        self.player.set_property("audio-sink",
                         gst.element_factory_make("alsasink", "sink"))
        self.player.set_property("video-sink",
                         gst.element_factory_make("fakesink", "fakesink"))
        bus = self.player.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.gst_message)
        self.player.set_property('uri', u'file://'
                             + os.path.join(metarace.DB_PATH, u'start.wav'))

        # variables
        self.armed = False
        self.width = 0
        self.height = 0
        self.backlight = 0.0
        self.backlightmax = 20
        self.backlightdev = None
        self.backlightlow = 0.25
        self.backlighthigh = 1.0
        self.syncthresh = 100000000
        self.tod = tod.tod(u'now').truncate(0)
        self.nc = self.tod + tod.tod(u'1.22') # set interval a little off mark
        self.countdown = None
        self.riderstr = None
        self.bulb = None
        self.currider = None
        self.ridermap = {}
        self.window = gtk.Window()
        self.window.set_title(u'Start Clock')
        self.window.connect('destroy', self.window_destroy_cb)
        self.area_src = None
        self.area = gtk.DrawingArea()
        self.area.connect('configure_event', self.area_configure_event_cb)
        self.area.connect('expose_event', self.area_expose_event_cb)
        self.area.set_size_request(400,220)
        self.area.show()
        self.window.add(self.area)
        self.log.info(u'Starting clock intervals at: ' + self.nc.rawtime(3))
        glib.timeout_add(2000, self.timeout)
        glib.timeout_add_seconds(5, self.delayed_cursor)
Ejemplo n.º 23
0
	def __init__(self, argv, finish_callback, timeout_s, stdin=None):
		self.stdout = []
		self.stderr = []
		self.stdin = []
		self.timeout = False
		self.killed = False
		self.finished = False
		self.finish_callback = finish_callback

		argv = _argv_to_locale(argv)
		pretty.print_debug(__name__, "AsyncCommand:", argv)

		flags = (glib.SPAWN_SEARCH_PATH | glib.SPAWN_DO_NOT_REAP_CHILD)
		pid, stdin_fd, stdout_fd, stderr_fd = \
		     glib.spawn_async(argv, standard_output=True, standard_input=True,
		                      standard_error=True, flags=flags)

		if stdin:
			self.stdin[:] = self._split_string(stdin, self.max_input_buf)
			in_io_flags = glib.IO_OUT | glib.IO_ERR | glib.IO_HUP | glib.IO_NVAL
			glib.io_add_watch(stdin_fd, in_io_flags, self._in_io_callback,
			                  self.stdin)
		else:
			os.close(stdin_fd)

		io_flags = glib.IO_IN | glib.IO_ERR | glib.IO_HUP | glib.IO_NVAL
		glib.io_add_watch(stdout_fd, io_flags, self._io_callback, self.stdout)
		glib.io_add_watch(stderr_fd, io_flags, self._io_callback, self.stderr)
		self.pid = pid
		glib.child_watch_add(pid, self._child_callback)
		if timeout_s is not None:
			glib.timeout_add_seconds(timeout_s, self._timeout_callback)
Ejemplo n.º 24
0
    def __init__(self, halcomp,builder,useropts):
        '''
        Handler classes are instantiated in the following state:
        - the widget tree is created, but not yet realized (no toplevel window.show() executed yet)
        - the halcomp HAL component is set up and the widhget tree's HAL pins have already been added to it
        - it is safe to add more hal pins because halcomp.ready() has not yet been called at this point.

        after all handlers are instantiated in command line and get_handlers() order, callbacks will be
        connected with connect_signals()/signal_autoconnect()

        The builder may be either of libglade or GtkBuilder type depending on the glade file format.
        '''

        self.halcomp = halcomp
        self.builder = builder

        self.halcomp.newpin("value", hal.HAL_FLOAT, hal.HAL_OUT)
        self.start = time.time()
        self.nhits = 0
        self.ticks = 0

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
	def on_name_owner_changed(self, service, prev_owner, new_owner):
		# print("name_owner_changed: %s; %s; %s" % (service, prev_owner, new_owner))
		if (new_owner == '' and not service.startswith(':')):  # a service has disappear from the bus, check if it was an item or a host.
			# search amongst the items.
			match = service+'/'
			# print("  search for ",match)
			to_be_removed=[]
			for it in self.items_list:
				# print("  check for ",it)
				if (it.startswith(match)):  # it[0:len(match)] == match
					# print("    match!")
					to_be_removed.append(it)
			for it in to_be_removed:
				self.items_list.remove (it)
				self.StatusNotifierItemUnregistered(it)

			# search amongst the hosts.
			to_be_removed=[]
			for it in self.hosts_list:
				if (it == service):
					to_be_removed.append(it)
			for it in to_be_removed:
				self.hosts_list.remove (it)
				self.StatusNotifierHostUnregistered()
		elif (service == 'com.Skype.API'):  # this stupid proprietary software only creates its item when the host appears !
			glib.timeout_add_seconds(2, self._emit_host_registered)
Ejemplo n.º 26
0
Archivo: omotgtk.py Proyecto: vrza/omot
    def on_tick(self):
        # returning False from on_tick will destroy the timeout
        # and stop calling on_tick
        logger.debug("entering on_tick callback.")
        again = True

        if self.paused:
            logger.debug("Slide show is paused, exiting callback")
            return again

        if self.keypress_lock.is_set():
            logger.debug("Keypress handler is running, exiting callback!")
            return again

        logger.debug("acquring mutex lock...")
        self.mutex.acquire()

        if self.update_file_list():
            # skip to the next picture in list an display it if possible
            self.change_image()
        else:
            logger.debug("Could not get new file list from mpd, exiting callback")

        if self.respawn_on_tick.is_set():
             logger.debug("Spawning new on_tick callback [%ds]" % self.cfg['seconds_between_pictures'])
             glib.timeout_add_seconds(self.cfg['seconds_between_pictures'], self.on_tick)
             again = False
             logger.debug("Callback will be destroyed on exit.")
             self.respawn_on_tick.clear()

        self.update_window_title()
        logger.debug("exiting on_tick callback. releasing mutex lock...")
        self.mutex.release()
        return again
 def main(self):
     '''Main.'''
     # Get input.
     ignoreInterval = len(sys.argv) == 2 and sys.argv[1] == "--now"
     
     # Just update one day after.
     if ignoreInterval:
         # Send statistics information.
         AnonymityThread(sendStatistics).start()
         
         # Just show tray icon when have updatable packages.
         self.updateNum = self.calculateUpdateNumber()
         if self.updateNum > 0:
             print "Show tray icon."
             
             gtk.gdk.threads_init()        
             
             self.trayIcon = gtk.StatusIcon()
             self.trayIcon.set_from_file("../icon/icon.png")
             self.trayIcon.set_has_tooltip(True)
             self.trayIcon.set_visible(True)
             self.trayIcon.connect("activate", lambda w: self.showSoftwareCenter())
             self.trayIcon.connect("query-tooltip", self.hoverIcon)
             self.trayIcon.connect("popup-menu", self.handleRightClick)
             
             # Show tooltips.
             # Add timeout to make tooltip display at correct coordinate.
             glib.timeout_add_seconds(1, self.hoverIcon)
             
             gtk.main()
         else:
             print "No updatable packages, exit."
Ejemplo n.º 28
0
Archivo: omotgtk.py Proyecto: vrza/omot
    def __init__(self):
        config.parse(self.cfg, config.file_parser, 'Display')
        
        self.window = gtk.Window()
        if not self.window.get_screen():
            sys.exit("No screen to display window on (check if DISPLAY has been set)!")
        
        self.window.connect('destroy', gtk.main_quit)
        self.window.set_default_size(self.cfg['default_width'], self.cfg['default_height'])
        
        self.icon = gtk.gdk.pixbuf_new_from_file(find_path('blade-runner-331x331.png')) #.scale_simple(256, 256, gtk.gdk.INTERP_HYPER)
        self.window.set_icon(self.icon) #sonatacd.png
        
        self.image = resizeable_image.ResizableImage(True, True, gtk.gdk.INTERP_HYPER)
        self.image.set_from_pixbuf(images.getdefault())
        self.image.show()
        self.window.add(self.image)

        mpdstatus.connect()
        
        self.update_file_list()
        
        self.update_window_title()
        
        self.window.show_all()
        
        if self.cfg['fullscreen']:
            self.fullscreen_toggle()
        
        # connect callbacks
        glib.timeout_add_seconds(self.cfg['seconds_between_pictures'], self.on_tick)
        self.window.connect('key_press_event', self.on_key_press_event)

        self.reload_current_image()
Ejemplo n.º 29
0
def _find_printreader():
    global FingerDevice
    dialog = None
    while not FingerDevice:
        devs = pyfprint.discover_devices()
        if len(devs) == 0:
            if not dialog:
                msg = 'Fingerprint scanner not found'
                dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
                                           message_format=msg)
                dialog.set_modal(True)
                dialog.show()
        else:
            FingerDevice = devs[0]
            break
        glib.timeout_add_seconds(1, done_waiting)
        gtk.main()

    FingerDevice.open()
    if not FingerDevice.supports_identification():
        raise "Device cannot do identification"
    #print "Found a " + FingerDevice.driver().full_name()
    if dialog:
        dialog.hide()
        dialog.destroy()
Ejemplo n.º 30
0
Archivo: status.py Proyecto: stoq/stoq
    def __init__(self):
        super(ResourceStatusManager, self).__init__()

        self._lock = threading.Lock()
        self.running_action = None
        self.resources = {}
        glib.timeout_add_seconds(self.REFRESH_TIMEOUT, self.refresh_and_notify)
Ejemplo n.º 31
0
def show_message(brief, body=None, icon=None):
    try:
        notification = pynotify.Notification(brief, body, icon)
        notification.show()
    except glib.GError:
        print_warning()
        glib.timeout_add_seconds(RETRY_INTERVAL, lambda: retry(brief, body, icon))
Ejemplo n.º 32
0
    def on_contact_list_ready(self):
        """callback called when the contact list is ready to be used"""
        self.window.content.contact_list.fill()

        def on_contact_added_you(responses):
            """
            callback called when the dialog is closed
            """
            for account in responses["accepted"]:
                self.session.add_contact(account)

            for account in responses["rejected"]:
                self.session.reject_contact(account)

        if self.session.contacts.pending:
            accounts = []
            for contact in self.session.contacts.pending.values():
                accounts.append((contact.account, contact.display_name))

            dialog = extension.get_default("dialog")
            dialog.contact_added_you(accounts, on_contact_added_you)

        glib.timeout_add(500, self.session.logger.check)

        # we instantiate this here to prevent the whole contact list
        # online notification
        def instantiate_notification():
            notificationcls = extension.get_default("notification")
            self.notification = notificationcls(self.session)

        glib.timeout_add_seconds(10, instantiate_notification)
Ejemplo n.º 33
0
    def update_group_information(self):
        """
        update the information for a conversation with multiple users
        """
        if not self.rotate_started:
            self.rotate_started = True
            glib.timeout_add_seconds(5, self.rotate_picture)

        #TODO add plus support for nick to the tab label!
        members_nick = []
        i = 0
        for account in self.members:
            i += 1
            contact = self.session.contacts.get(account)

            if contact is None or contact.nick is None:
                nick = account
            elif len(contact.nick) > 20 and i != len(self.members):
                nick = contact.nick[:20] + '...'
            else:
                nick = contact.nick

            members_nick.append(nick)

        self.header.information = \
            ('%d members' % (len(self.members) + 1, ),
                    ", ".join(members_nick))
        self.update_tab()
    def finishCallback(self):
        '''Finish callback for progress.'''
        # Update status.
        self.statusbar.setStatus(__("Update sources list completed."))

        # Reset statusbar after 2 seconds.
        glib.timeout_add_seconds(5, self.resetStatus)
Ejemplo n.º 35
0
    def __init__(self):
        home = os.curdir
        if 'HOME' in os.environ:
            home = os.environ['HOME']
        elif os.name == 'posix':
            home = os.path.expanduser("~/")
        elif os.name == 'nt':
            if 'HOMEPATH' in os.environ and 'HOMEDRIVE' in os.environ:
                home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
        else:
            home = os.environ['HOMEPATH']

        if os.path.isfile(
                home + "/.config/unread-mail-indicator/config.ini") == False:
            setup.main()

        self.Config = ConfigParser.ConfigParser()
        self.Config.read(home + "/.config/unread-mail-indicator/config.ini")
        print self.Config.sections()

        self.ind = appindicator.Indicator(
            "Unread-Mail-Notify", "indicator-messages",
            appindicator.CATEGORY_APPLICATION_STATUS)
        self.callback_minutes = int(
            self.Config.get('Basics', 'CheckIntervalMinutes'))
        self.strNoUnreadMails = self.Config.get('Strings', 'strNoUnreadMails')
        self.strUnreadMails = self.Config.get('Strings', 'strUnreadMails')
        self.notificationEnabled = self.Config.get('Basics',
                                                   'ShowNotifications')
        self.notificationTitle = self.Config.get('Strings',
                                                 'notificationTitle')
        self.notificationIcon = 'indicator-messages-new'
        self.actionOnClick = "thunderbird"
        self.set_menu()
        glib.timeout_add_seconds(int(60) * self.callback_minutes, self.work)
Ejemplo n.º 36
0
    def __init__(self, argv, finish_callback, timeout_s, stdin=None, env=""):
        self.stdout = []
        self.stderr = []
        self.stdin = []
        self.timeout = False
        self.killed = False
        self.finished = False
        self.finish_callback = finish_callback

        argv = _argv_to_locale(argv)
        pretty.print_debug(__name__, "AsyncCommand:", argv)

        # get default environment var if not given
        env = env or ['='.join(kv) for kv in os.environ.iteritems()]

        flags = (glib.SPAWN_SEARCH_PATH | glib.SPAWN_DO_NOT_REAP_CHILD)
        pid, stdin_fd, stdout_fd, stderr_fd = \
             glib.spawn_async(argv, standard_output=True, standard_input=True,
                              standard_error=True, flags=flags, envp=env)

        if stdin:
            self.stdin[:] = self._split_string(stdin, self.max_input_buf)
            in_io_flags = glib.IO_OUT | glib.IO_ERR | glib.IO_HUP | glib.IO_NVAL
            glib.io_add_watch(stdin_fd, in_io_flags, self._in_io_callback,
                              self.stdin)
        else:
            os.close(stdin_fd)

        io_flags = glib.IO_IN | glib.IO_ERR | glib.IO_HUP | glib.IO_NVAL
        glib.io_add_watch(stdout_fd, io_flags, self._io_callback, self.stdout)
        glib.io_add_watch(stderr_fd, io_flags, self._io_callback, self.stderr)
        self.pid = pid
        glib.child_watch_add(pid, self._child_callback)
        if timeout_s is not None:
            glib.timeout_add_seconds(timeout_s, self._timeout_callback)
Ejemplo n.º 37
0
    def __init__(self, path=None):
        RawConfigParser.__init__(self)

        if path:
            self.location = path
        else:
            config_home = glib.get_user_config_dir()
            config_home = os.path.join(config_home, 'feattool')
            if not os.path.exists(config_home):
                os.makedirs(config_home)
            self.location = os.path.join(config_home, 'settings.ini')

        if not os.path.exists(self.location):
            open(self.location, "w").close()

        self._dirty = False
        self._saving = False

        try:
            self.read(self.location)
        except:
            pass

       #Save settings every 30 secs
        glib.timeout_add_seconds(30, self._timeout_save)
 def finishCallback(self):
     '''Finish callback for progress.'''
     # Update status.
     self.statusbar.setStatus(__("Update sources list completed."))
     
     # Reset statusbar after 2 seconds.
     glib.timeout_add_seconds(5, self.resetStatus)
Ejemplo n.º 39
0
    def __start_traffic_history(self):
        '''
        This method creates the necessary data structures to manage the expenses
        of current connection
        '''
        # Get some IMSI dependent data, like monthly limits, billing_period, etc.
        imsi = self.conf.get_last_imsi_seen()
        if not self.conf.is_last_imsi_seen_valid():
            self._cached_billing_period = self.conf.get_default_billing_period()
            for is_roaming in (True, False):
                monthly_limit = self.conf.get_default_selected_monthly_limit(is_roaming)
                self._cached_monthly_limit[is_roaming] = monthly_limit * 1024 * 1024    # calculate it in bytes
        else:
            self._cached_billing_period = self.conf.get_imsi_based_billing_period(imsi)
            for is_roaming in (True, False):
                monthly_limit = self.conf.get_imsi_based_selected_monthly_limit(imsi, is_roaming)
                if monthly_limit == -1:     # Is it a custom monthly limit?
                    monthly_limit = self.conf.get_imsi_based_other_monthly_limit(imsi, is_roaming)
                self._cached_monthly_limit[is_roaming] = monthly_limit * 1024 * 1024    # calculate it in bytes

        # Calculate the expenses for current billing period
        first_day = self._cached_billing_period[0]
        last_day = self._cached_billing_period[1]
        for is_roaming in (True, False):
            self._cached_expenses[is_roaming] = self._storage.get_accumulated(imsi, \
                    first_day, last_day, is_roaming)

        # Throw a signal 'traffic-data-changed'. That is a high-level signal used by some components
        # like the Traffic window and TrafficZone in the dock
        self.emit('traffic-data-changed',
                self._cached_expenses[False]['total'],  # data_used, NOT roaming
                self._cached_expenses[True]['total'],   # data_used_roaming
                self._cached_monthly_limit[False],      # limit_data NOT roaming
                self._cached_billing_period             # billing_period
        )

        # Throw an 'update-expenses-info' signal for both roaming and not roaming. That is a lower
        # level signal which talks about absolute expenses
        for is_roaming in (True, False):
            signal_id = 'update-expenses-info' if not is_roaming else 'update-roaming-expenses-info'
            expenses = self._cached_expenses[is_roaming]
            self.emit(signal_id, expenses['total'], expenses['received'], expenses['sent'])

        ## Live billing period change management

        # It is pretty unlikely, but it could be possible that TGCM is being executed during a
        # billing period change. To handle this situation, we will create a scheduled event to
        # recreate the traffic history

        # Cancel any existing scheduled event
        if self.__billing_period_change_event is not None:
            self.__billing_period_change_event.cancel()

        # Calculate the delta difference between now and the next billing period change, and
        # configure consequently the scheduled event
        delta_next_day = datetime.timedelta(days = 1)
        period_end = last_day + delta_next_day
        interval = int(time.mktime(period_end.timetuple()) - time.time())
        glib.timeout_add_seconds(interval, self.__on_billing_period_change)
	def begin_watch(self):
		if not self.watching:
			self.wdd = self.wm.add_watch(self.directory, pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO)
			if self.debug:
				print "Added watch to %s" % (self.directory,)
			
			glib.timeout_add_seconds(1, self.quick_check)
			self.watching = True
Ejemplo n.º 41
0
 def _maybe_schedule_idle_logout(self):
     # Verify if the user will use automatic logout.
     from stoqlib.lib.parameters import sysparam
     minutes = sysparam.get_int('AUTOMATIC_LOGOUT')
     # If user defined 0 minutes, ignore automatic logout.
     if minutes != 0:
         seconds = minutes * 60
         glib.timeout_add_seconds(5, self._verify_idle_logout, seconds)
Ejemplo n.º 42
0
    def set_status(self, status, timeout=0):
        """
            Sets the status message
        """
        self.message_ids += [self.status_bar.push(self.context_id, status)]

        if timeout > 0:
            glib.timeout_add_seconds(timeout, self.clear_status)
Ejemplo n.º 43
0
	def __init__(self):
		icon = gtk.status_icon_new_from_file("icon.png")
		icon.connect('popup-menu', self.rightClick)
		icon.connect('activate', self.leftClick)
		self.window = NistWindow()
		self.checkfornew()
		#start timer to check the database again for new vulns every 10 min
		glib.timeout_add_seconds(600, self.checkfornew)
Ejemplo n.º 44
0
 def push_status(self, msg, level):
     """Push the given msg onto the status stack, and defer removal."""
     delay = 3
     if level > 25:
         delay = 8
     msgid = self.status.push(self.context, msg)
     glib.timeout_add_seconds(delay, self.pull_status, msgid)
     return False
Ejemplo n.º 45
0
 def _maybe_schedule_idle_logout(self):
     # Verify if the user will use automatic logout.
     from stoqlib.lib.parameters import sysparam
     minutes = sysparam.get_int('AUTOMATIC_LOGOUT')
     # If user defined 0 minutes, ignore automatic logout.
     if minutes != 0:
         seconds = minutes * 60
         glib.timeout_add_seconds(5, self._verify_idle_logout, seconds)
Ejemplo n.º 46
0
    def __init__(self):
        super(ResourceStatusManager, self).__init__()

        self._lock = threading.Lock()
        self.running_action = None
        self.resources = {}
        glib.timeout_add_seconds(self.REFRESH_TIMEOUT,
                                 self.refresh_and_notify)
Ejemplo n.º 47
0
 def __init__(self):
     self.icon = gtk.StatusIcon()
     self.set_icon_off()
     self.icon.connect('popup-menu', self.on_right_click)
     self.icon.connect('activate', self.on_left_click)
     self.check_blog_for_newrss()
     #6 hour timer
     glib.timeout_add_seconds(21600, self.check_blog_for_newrss)
Ejemplo n.º 48
0
    def set_status(self, status, timeout=0):
        """
            Sets the status message
        """
        self.message_ids += [self.status_bar.push(self.context_id, status)]

        if timeout > 0:
            glib.timeout_add_seconds(timeout, self.clear_status)
Ejemplo n.º 49
0
 def push_status(self, msg, level):
     """Push the given msg onto the status stack, and defer removal."""
     delay = 3
     if level > 25:
         delay = 8
     msgid = self.status.push(self.context, msg)
     glib.timeout_add_seconds(delay, self.pull_status, msgid)
     return False
Ejemplo n.º 50
0
 def start_timer_cb(self, *a):
   if self.first_update:
     self.TIMER_ID = glib.timeout_add_seconds(5, self.timer_cb)
     return True
   if self.TIMER_ID:
     glib.source_remove(self.TIMER_ID)
     self.TIMER_ID=None
   SEC = int(self.conf['Utime'])*60
   self.TIMER_ID = glib.timeout_add_seconds(SEC, self.timer_cb)
Ejemplo n.º 51
0
    def __init__(self, halcomp,builder,useropts,compname):
        self.halcomp = halcomp
        self.builder = builder
        self.useropts = useropts

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
Ejemplo n.º 52
0
    def __init__(self, halcomp, builder, useropts):
        self.halcomp = halcomp
        self.builder = builder
        self.useropts = useropts

        # demonstrate a slow background timer - granularity is one second
        # for a faster timer, use this:
        # glib.timeout_add(5000,  self._on_timer_tick)
        glib.timeout_add_seconds(1, self._on_timer_tick)
Ejemplo n.º 53
0
def _on_child_exit(pid, condition, user_data):
	# @condition is the &status field of waitpid(2) (C library)
	argv, respawn = user_data
	if respawn:
		is_signal = os.WIFSIGNALED(condition)
		if is_signal and respawn:
			def callback(*args):
				spawn_child(*args)
				return False
			glib.timeout_add_seconds(10, callback, argv, respawn)
Ejemplo n.º 54
0
Archivo: utils.py Proyecto: pbx/kupfer
def _on_child_exit(pid, condition, user_data):
    # @condition is the &status field of waitpid(2) (C library)
    argv, respawn = user_data
    if respawn:
        is_signal = os.WIFSIGNALED(condition)
        if is_signal and respawn:
            def callback(*args):
                spawn_child(*args)
                return False
            glib.timeout_add_seconds(10, callback, argv, respawn)
Ejemplo n.º 55
0
 def __init__(self, halcomp,builder,useropts):
     self.inifile = linuxcnc.ini(os.environ["INI_FILE_NAME"])
     self.configpath = os.environ['CONFIG_DIR']
     self.toolfile = os.path.join( self.configpath, self.inifile.find("EMCIO", "TOOL_TABLE") )
     self.builder = builder
     self.halcomp = halcomp
     self.change_text = builder.get_object("lbl_tool_change_info")
     self.ref_tool = builder.get_object("reftool")
     
     self.command_value_to_name = {}
     value = 1
     for command in self.commands:
         self.halcomp.newpin(command, hal.HAL_FLOAT, hal.HAL_IN)
         hal.set_p(halcomp.getprefix() + "." + command, str(value))
         self.command_value_to_name[value] = command
         value = value + 1
     
     self.gcode_command = hal_glib.GPin(halcomp.newpin("gcode-command", hal.HAL_FLOAT, hal.HAL_IN))
     self.gcode_param = hal_glib.GPin(halcomp.newpin("gcode-parameter", hal.HAL_FLOAT, hal.HAL_IN))
     self.num_of_tools = hal_glib.GPin(halcomp.newpin("num_of_tools", hal.HAL_FLOAT, hal.HAL_IN))
     
     self.gcode_command.connect("value-changed", self.command_from_gcode)
     self.gcode_param.connect("value-changed", self.parameter_from_gcode)
     
     self.parameter = None
     self.tools_in_file = []
     
     self.tooledit1 = self.builder.get_object("tooledit1")
     self.tooledit1.set_filename(self.toolfile)
     
     self.liststore1 = self.builder.get_object("liststore1")
     self.treeview1 = self.builder.get_object("treeview1")
     
     # Set tool table columns
     tool_table_width = self.treeview1.get_property("width_request")
     self.cell_desc = self.builder.get_object("cell_desc")
     self.cell_desc.props.wrap_mode = pango.WRAP_WORD
     self.cell_desc.props.wrap_width = int(self.COL_TOOL_NAME_WIDTH * tool_table_width)
     self.cell_operation = self.builder.get_object("cell_operation")
     self.cell_operation.props.wrap_mode = pango.WRAP_WORD
     self.cell_operation.props.wrap_width = int(self.COL_TOOL_OPERATION_WIDTH * tool_table_width)
     
     self.current_tool_index = -1
     self.spindle_rpm_bar = self.builder.get_object("spindle_speed")
     
     self.gcode_command = hal_glib.GPin(halcomp.newpin("spindle-target-speed", hal.HAL_FLOAT, hal.HAL_IN))
     self.gcode_command.connect("value-changed", self.spindle_target_changed)
     
     self.file_progress_bar = self.builder.get_object("file_progress")
     self.rows_in_file = 200
     self.current_row = 0
     self.spindle_on_timer = 0
     glib.timeout_add_seconds(1, self._on_timer_tick)
     
     self.runtime = self.builder.get_object("runtime")
 def on_user_typing(self, cid, account, *args):
     """
     inform that the other user has started typing
     """
     if account in self.conversation.members:
         contact = self.session.contacts.get(account)
         if contact and not self.active:
             self.active = True  #avoid many timeout
             display_name = Plus.msnplus_strip(contact.display_name)
             self.set_markup(_("%s is typing") % display_name)
             glib.timeout_add_seconds(3, self.update_label)
Ejemplo n.º 57
0
    def __init__(self):
        Lanshare.__init__(self)

        self.create_gui()
        self.create_peer_socket()

        from glib import idle_add, timeout_add_seconds
        idle_add(self.gui_idle)
        timeout_add_seconds(self.peer_announce_interval, self.peer_tick)

        self.populate_shares()
Ejemplo n.º 58
0
    def test_remove(self):
        timeout_id = 1
        self.mox.StubOutWithMock(glib, 'timeout_add_seconds')
        glib.timeout_add_seconds(self.TIMEOUT, mox.IsA(
            types.MethodType)).AndReturn(timeout_id)

        self.mox.ReplayAll()
        self.mc.add('foo', 'bar')
        self.mc.remove('foo')
        self.assertEqual(self.mc.get('foo'), None)
        self.mox.VerifyAll()
Ejemplo n.º 59
0
    def initDB(self):
        '''Init DB.'''
        self.database = DB()
        self.statusbar.setStatus(
            (__("Build the search index file is completed.")))

        # Touch lock file.
        if not os.path.exists(self.lockFile):
            touchFile(self.lockFile)

        glib.timeout_add_seconds(2, self.resetStatus)