コード例 #1
0
ファイル: ohmmeter.py プロジェクト: j2a/odesk-sprints
 def __init__(self, *args, **kwargs):
     gtk.StatusIcon.__init__(self, *args, **kwargs)
     self.set_from_stock(gtk.STOCK_FIND)
     self.set_tooltip('Fetching')
     self._init_menu()
     self.cb_refresh()
     gobject.timeout_add_seconds(10*60, self.cb_refresh)
コード例 #2
0
ファイル: gog_gui.py プロジェクト: Kaira-/gogonlinux
 def profile_update(self):
     try:
         self.user = data_handle.UserData(self.connection.get_user_data())
     except:
         self.show_error("There was a connection problem with the login page. Live profile update will be disabled.\n"
                         "Please relog/restart the client.")
         return False
     self.accountlabel.set_text(self.user.name)
     self.emaillabel.set_text(self.user.email)
     if self.user.forum != "0":
         self.forumnotelabel.set_text(self.user.forum)
     else:
         self.forumnotelabel.set_text("none")
     if self.user.messages != "0":
         self.privatenotelabel.set_text(self.user.messages)
     else:
         self.privatenotelabel.set_text("none")
     if self.user.games != "0":
         self.gamenotelabel.set_text(self.user.games)
     else:
         self.gamenotelabel.set_text("none")
     #Let's load the picture from the web
     response = urllib2.urlopen(self.user.imagesmall)
     loader = gtk.gdk.PixbufLoader()
     loader.write(response.read())
     loader.close()
     self.profilepic.set_from_pixbuf(loader.get_pixbuf().scale_simple(35,35,gtk.gdk.INTERP_BILINEAR))
     #refresh the update based on the settings, we do this because they may change dynamically
     #so we have to break the chain and re-create it every time
     gobject.timeout_add_seconds(int(self.settings["profile_update"]),self.profile_update)
     return False
コード例 #3
0
ファイル: messageboard.py プロジェクト: proximate/proximate
    def search(self, callback, ctx=None, criteria=None, keywords=None, replicated=False, fetch=True):
        """ The caller gets an indetermistic number of result callbacks.
            Empty keywords, or keywords == None, means get all messages. """

        if criteria == None:
            criteria = {}

        sctx = Search_Context(callback, ctx=ctx, criteria=criteria, keywords=keywords)

        if fetch:
            self.searchctxs.append(sctx)
            timeout_add_seconds(SEARCH_TIMEOUT, self.cancel_search, sctx)

            self.statusindicator.set_status("Searching messages", timeout=SEARCH_TIMEOUT)

            # Query others
            req = {"t": "msgquery"}
            if keywords != None:
                req["keywords"] = keywords
            req["criteria"] = criteria

            com = self.community.get_default_community()
            self.fetcher.fetch_community(com, self.name, req, self.got_query_results)

            self.query_cache(sctx)

        # Then query myself
        sctx.process(self.community.get_myself(), self.all_metas())
コード例 #4
0
ファイル: showvideo.py プロジェクト: burst/burst
    def _initGui(self):
        if self.WHICH_CAMERA == 1:
            print "using bottom camera"
            self._con.switchToBottomCamera()
        else:
            print "using top camera"
            self._con.switchToTopCamera()
        stage_color = clutter.Color(0x99, 0xCC, 0xFF, 0xFF)

        stage = clutter.Stage()
        # stage.connect('button-press-event', clutter.main_quit)
        stage.connect("destroy", clutter.main_quit)
        stage.set_color(stage_color)
        stage.set_user_resizable(True)
        stage.set_size(400, 300)

        self._texture = texture = clutter.Texture("top.jpg")
        texture.set_position(0, 0)
        stage.add(texture)

        # tick(texture)
        gobject.timeout_add_seconds(1, self.onUpdateImage)
        stage.show()
        stage.show_all()
        self.stage = stage
コード例 #5
0
ファイル: run.py プロジェクト: kyheo/multi-gmail-notifier
 def check(self):
     new = False
     for label in self.labels:
         new = label.check()
     if new:
         self.notify()
     gobject.timeout_add_seconds(self.timeout, self.check)
コード例 #6
0
ファイル: tray.py プロジェクト: abidinz/Stormee
    def __init__(self):
        self.caps = []
        self.rssfeeds = set()
        self.seen = set()
        self.windows = list()

#        self.rssfeeds.add('http://www.usgs.gov/hazard_alert/alerts/landslides.rss')

#        self.rssfeeds.add('http://alerts.weather.gov/cap/ca.php?x=0')
        self.rssfeeds.add('http://edis.oes.ca.gov/index.atom')
#        self.rssfeeds.add('http://earthquake.usgs.gov/eqcenter/recenteqsww/catalogs/caprss7days5.xml')
        self.mycoords = LATLONG_COORDS
        
        self.statusIcon = gtk.StatusIcon()
        self.statusIcon.set_from_stock(gtk.STOCK_DIALOG_WARNING)
        self.statusIcon.set_visible(True)
        self.statusIcon.set_tooltip("Common Alerting Protocol Viewer")
        
        self.menu = gtk.Menu()
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_EXECUTE)
        self.menuItem.connect('activate', self.execute_cb, self.statusIcon)
        self.menu.append(self.menuItem)
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menuItem.connect('activate', self.quit_cb, self.statusIcon)
        self.menu.append(self.menuItem)
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_CONNECT)
        self.menuItem.connect('activate', self.rssTimer_cb, self.statusIcon)
        
        self.statusIcon.connect('popup-menu', self.popup_menu_cb, self.menu)
        self.statusIcon.set_visible(1)

        gobject.timeout_add_seconds(60*10, self.rssTimer_cb)
        gobject.timeout_add(100, self.startup_cb)
    
	self.execute_cb(None, None, None)
コード例 #7
0
 def __init__(self, bus):
     self.path = "/org/freesmartphone/Time"
     super(Time, self).__init__(bus, self.path)
     self.interface = "org.freesmartphone.Time"
     self.last_emitted = None
     gobject.timeout_add_seconds(1, self.time_changed)
     self.bus = bus
コード例 #8
0
ファイル: pidgin_events.py プロジェクト: fordperfect/dot
 def __init__(self, timeout, function):
    self.last = d.datetime.now()
    self.last_active = False
    self.value = timeout
    self.function = function
    self.counter = self.value
    gobject.timeout_add_seconds(1, self.callback)
コード例 #9
0
ファイル: scheduler.py プロジェクト: proximate/proximate
    def __init__(self):
        self.register_plugin(PLUGIN_TYPE_SCHEDULER)
        self.community = None

        self.callbacks = []
        self.periodic = []
        timeout_add_seconds(SCHEDULE_PERIOD, self.schedule)
コード例 #10
0
ファイル: Tracktree.py プロジェクト: csryan/pogo
    def onAppStarted(self):
        """ This is the real initialization function, called when the module has been loaded """
        wTree                  = tools.prefs.getWidgetsTree()
        self.playtime          = 0
        self.bufferedTrack     = None
        # Retrieve widgets
        self.window     = wTree.get_object('win-main')

        columns = (('',   [(gtk.CellRendererPixbuf(), gtk.gdk.Pixbuf), (gtk.CellRendererText(), TYPE_STRING)], True),
                   (None, [(None, TYPE_PYOBJECT)], False),
                  )

        self.tree = TrackTreeView(columns, use_markup=True)
        self.tree.enableDNDReordering()
        self.tree.setDNDSources([DND_INTERNAL_TARGET])

        wTree.get_object('scrolled-tracklist').add(self.tree)

        # GTK handlers
        self.tree.connect('exttreeview-button-pressed', self.onMouseButton)
        self.tree.connect('tracktreeview-dnd', self.onDND)
        self.tree.connect('key-press-event', self.onKeyboard)
        self.tree.get_model().connect('row-deleted', self.onRowDeleted)

        (options, args) = prefs.getCmdLine()

        self.savedPlaylist = os.path.join(consts.dirCfg, 'saved-playlist')
        self.paused = False


        # Populate the playlist with the saved playlist
        dump = None
        if os.path.exists(self.savedPlaylist):
            try:
                dump = pickleLoad(self.savedPlaylist)
            except:
                msg = '[%s] Unable to restore playlist from %s\n\n%s'
                log.logger.error(msg % (MOD_INFO[modules.MODINFO_NAME],
                                self.savedPlaylist, traceback.format_exc()))

        if dump:
            self.restoreTreeDump(dump)
            log.logger.info('[%s] Restored playlist' % MOD_INFO[modules.MODINFO_NAME])
            self.tree.collapse_all()
            self.select_last_played_track()
            self.onListModified()

        commands, args = tools.separate_commands_and_tracks(args)

        # Add commandline tracks to the playlist
        if args:
            log.logger.info('[%s] Filling playlist with files given on command line' % MOD_INFO[modules.MODINFO_NAME])
            tracks  = media.getTracks([os.path.abspath(arg) for arg in args])
            playNow = not 'stop' in commands and not 'pause' in commands
            modules.postMsg(consts.MSG_CMD_TRACKLIST_ADD, {'tracks': tracks, 'playNow': playNow})
        elif 'play' in commands:
            modules.postMsg(consts.MSG_CMD_TOGGLE_PAUSE)

        # Automatically save the content at regular intervals
        gobject.timeout_add_seconds(SAVE_INTERVAL, self.save_track_tree)
コード例 #11
0
ファイル: main.py プロジェクト: gfunkmonk2/mate-games
    def __init__ (self, run_selector = True):
        """run_selector means that we start our regular game.

        For testing purposes, it will be convenient to hand a
        run_selector=False to this method to avoid running the dialog
        and allow a tester to set up a game programmatically.
        """
        mateconf_wrapper.MateConfWrapper.__init__(self,
                                            mateconf_wrapper.MateConf('mate-sudoku')
                                            )
        self.setup_gui()
        self.timer = timer.ActiveTimer(self.w)
        self.won = False
        # add the accelerator group to our toplevel window
        self.worker_connections = []
        self.is_fullscreen = False

        # setup sudoku maker...
        self.sudoku_maker = sudoku_maker.SudokuMaker()
        self.sudoku_tracker = saver.SudokuTracker()
        # generate puzzles while our use is working...
        self.show()
        if run_selector:
            self.do_stop()
            if self.select_game():
                # If this return True, the user closed...
                self.quit = True
            else:
                self.quit = False
                # Generate puzzles in background...
                if self.mateconf['generate_puzzles_in_background']:
                    gobject.timeout_add_seconds(1, lambda *args: self.start_worker_thread() and True)
コード例 #12
0
ファイル: asyncipp.py プロジェクト: Alberto-Beralix/Beralix
    def destroy (self):
        debugprint ("DESTROY: %s" % self)
        for binding in self.bindings:
            delattr (self, binding)

        if self.thread.isAlive ():
            gobject.timeout_add_seconds (1, self._reap_thread)
コード例 #13
0
ファイル: gpsWindow.py プロジェクト: 119-org/gmapcatcher
 def __init__(self, mapsObj):
     gtk.Window.__init__(self)
     self.mapsObj = mapsObj
     self.gps_values = []
     self.__stop = False
     vbox = gtk.VBox(False)
     vbox.pack_start(self._createLabels(FontDescription("16")))
     self.add(vbox)
     self.set_title("GPS")
     self.set_border_width(10)
     self.update_widgets()
     self.set_position(gtk.WIN_POS_CENTER)
     self.set_gravity(gtk.gdk.GRAVITY_STATIC)
     self.placement = self.get_position()
     self.set_size_request(250, 300)
     self.connect('key-press-event', self.key_press)
     self.connect('delete-event', self.on_delete)
     self.connect('hide', self.on_hide)
     self.add_events(gtk.gdk.BUTTON_PRESS_MASK)
     menu = self.rclick_menu()
     self.connect('button_press_event', self.window_event, menu)
     self.show_all()
     self.set_transient_for(mapsObj)
     self.connect('show', self.on_show)
     timeout_add_seconds(1, self.update_widgets)
コード例 #14
0
ファイル: aerobat.py プロジェクト: zommerfelds/aerobat
    def __init__(self):
        
        self.statusicon = gtk.StatusIcon()

        while not self.statusicon.is_embedded():
            gtk.main_iteration()

        self.bkgr_pixbuf = gen_pixbuf(border_color, width, height)
        tmp_pixbuf = gen_pixbuf(background_color, width-2*border, height-2*border)
        tmp_pixbuf.copy_area(src_x=0, src_y=0, width=width-2*border, height=height-2*border,
                               dest_pixbuf=self.bkgr_pixbuf, dest_x=border, dest_y=border)
                               
        self.normal_pixbuf   = gen_pixbuf(normal_color, width-2*border, height-2*border)
        self.low_pixbuf      = gen_pixbuf(low_color, width-2*border, height-2*border)
        self.critical_pixbuf = gen_pixbuf(critical_color, width-2*border, height-2*border)
        
        self.disabled_pixbuf = gen_pixbuf(border_color, width, height)
        tmp_pixbuf = gen_pixbuf(disabled_color, width-2*border, height-2*border)
        tmp_pixbuf.copy_area(src_x=0, src_y=0, width=width-2*border, height=height-2*border,
                               dest_pixbuf=self.disabled_pixbuf, dest_x=border, dest_y=border)
        
        self.update()

        gobject.timeout_add_seconds(sleep, self.update)

        self.statusicon.connect("popup-menu", self.right_click_event)
コード例 #15
0
ファイル: ParallelProcessing.py プロジェクト: I--Fox--I/pycam
 def toggle_process_pool_window(self, widget=None, value=None, action=None):
     toggle_process_pool_checkbox = self.gui.get_object("ToggleProcessPoolWindow")
     checkbox_state = toggle_process_pool_checkbox.get_active()
     if value is None:
         new_state = checkbox_state
     else:
         if action is None:
             new_state = value
         else:
             new_state = action
     if new_state:
         is_available = pycam.Utils.threading.is_pool_available()
         disabled_box = self.gui.get_object("ProcessPoolDisabledBox")
         statistics_box = self.gui.get_object("ProcessPoolStatisticsBox")
         if is_available:
             disabled_box.hide()
             statistics_box.show()
             # start the refresh function
             interval = int(max(1, self.gui.get_object(
                     "ProcessPoolRefreshInterval").get_value()))
             gobject.timeout_add_seconds(interval,
                     self.update_process_pool_statistics, interval)
         else:
             disabled_box.show()
             statistics_box.hide()
         self.process_pool_window.show()
     else:
         self.process_pool_window.hide()
     toggle_process_pool_checkbox.set_active(new_state)
     # don't destroy the window with a "destroy" event
     return True
コード例 #16
0
ファイル: meg.py プロジェクト: ming13/meg
    def update(self):
        """ Circle of updating, meanwhile controls rest window
            and timer update """

        if self.gui.state == "working":
            # Update tooltip anyway
            self.update_tray_icon_tooltip()

            # Handle long rest first
            if time() > self.timer.long_rest_time:
                self.gui.call_rest_window()

                self.timer.rest_time_ending = time() + self.timer.long_rest_length

                self.update_rest_window()

                self.timer.update_long_rest_time()

            elif time() > self.timer.short_rest_time:
                self.gui.call_rest_window()

                self.timer.rest_time_ending = time() + self.timer.short_rest_length

                self.update_rest_window()

                self.timer.update_short_rest_time()
        else:
            # Reinit timer data for currect timing after idle state
            self.timer.reinit_timer()

        # Check in circle
        gobject.timeout_add_seconds(5, self.update)
	def testMonitorDeleteNonExistingEvent(self):
		result = []
		mainloop = self.create_mainloop(None)
		events = parse_events("test/data/five_events.js")
		
		@asyncTestMethod(mainloop)
		def timeout():
			# We want this timeout - we should not get informed
			# about deletions of non-existing events
			mainloop.quit()
			return False

		@asyncTestMethod(mainloop)
		def notify_insert_handler(time_range, events):
			event_ids = map(lambda ev : ev.id, events)
			self.client.delete_events([9999999])
		
		@asyncTestMethod(mainloop)
		def notify_delete_handler(time_range, event_ids):
			mainloop.quit()
			self.fail("Notified about deletion of non-existing events %s", events)
			
		self.client.install_monitor(TimeRange(125, 145), [],
			notify_insert_handler, notify_delete_handler)
		
		gobject.timeout_add_seconds(5, timeout)
		self.client.insert_events(events)
		mainloop.run()
コード例 #18
0
  def show_indicator(self, conversation):
    print "adding " + conversation.display_name

    try:
      # Ubuntu 9.10 and above
      indicator = indicate.Indicator()
    except:
      # Ubuntu 9.04
      indicator = indicate.IndicatorMessage()

    indicator.set_property("name", conversation.display_name)
    indicator.set_property("subtype", "instant")
    indicator.set_property('draw-attention', 'true');

    # we can only display timestamp OR count
    if conversation.count == 1:
      indicator.set_property_time('time', conversation.timestamp)
    else:
      indicator.set_property('count', str(conversation.count));

    indicator.connect("user-display", self.show_conversation)
    indicator.show()

    # TODO: why?
    gobject.timeout_add_seconds(5, do_nothing, indicator)
コード例 #19
0
ファイル: launch.py プロジェクト: pbx/kupfer
 def launched_application(self, app_id, pid):
     if self._has_match(app_id):
         return
     timeout = time() + 15
     gobject.timeout_add_seconds(2, self._find_application, app_id, pid, timeout)
     # and once later
     gobject.timeout_add_seconds(30, self._find_application, app_id, pid, timeout)
コード例 #20
0
ファイル: Conversation.py プロジェクト: SWOriginal/emesene
    def update_group_information(self):
        """
        update the information for a conversation with multiple users
        """
        if not self.rotate_started:
            self.rotate_started = True
            gobject.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()
コード例 #21
0
ファイル: ocad_gui.py プロジェクト: IMI-KIT/ontocad
	def __init__( self, data ):
		self.data = data
		self.data.gtk = gtk
		self.data.builder = gtk.Builder()

		factory = gtk.IconFactory()
		factory.add_default()

		builder = self.data.builder
		builder.add_from_file("../res/gui.glade")
		self.window = builder.get_object("window1")
		self.window.connect("delete_event", self.delete_event)
		self.setCellRenderers()

		#self.pb_blue = gtk.gdk.pixbuf_new_from_file("../pixbuf1.png")
		#self.pb_green = gtk.gdk.pixbuf_new_from_file("../pixbuf2.png")
		#self.pb_red = gtk.gdk.pixbuf_new_from_file("../pixbuf3.png")

		self.data.status = builder.get_object("gui_status")

		self.viewer = ocad_viewer.ocad_viewer(self.data, gtk, self.window)
		self.viewer.isLayerVisible = self.isLayerVisible

		self.initImageViewer()
		self.viewer.viewer = self.view

		#every second check if status is empty
		gobject.timeout_add_seconds(1, self.check_status, False)
		self.clean_status = True
コード例 #22
0
ファイル: flukso_gui.py プロジェクト: 0110/pythonflukso
	def __init__(self, timeout_power, timeout_weather):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_size_request(800,600);
		self.window.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
#		self.window.fullscreen()
		
		self.label = gtk.Label('time label')
		self.label.set_use_markup(True)
		self.label.modify_font(pango.FontDescription("sans 20"))
		self.label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,65535,65535))

		self.weather = gtk.Label('Weather')
		self.weather.set_use_markup(True)
		self.weather.modify_font(pango.FontDescription("sans 20"))
		self.weather.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(0,65535,0))

		self.power = gtk.Label('Power')
		self.power.set_use_markup(True)
		self.power.modify_font(pango.FontDescription("sans 50"))
		self.power.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(65535,65535,65535))

		vbox = gtk.VBox()
	
		vbox.pack_start(self.label)
		vbox.pack_start(self.weather)
		vbox.pack_start(self.power)		

		self.window.add(vbox)
		self.window.show_all()
		gobject.timeout_add_seconds(timeout_power, self.update_power)
		gobject.timeout_add_seconds(timeout_weather, self.update_weather)
コード例 #23
0
	def show_xep0184_warning(self, id_):
		if id_ in self.xep0184_marks:
			return

		buffer = self.tv.get_buffer()
		buffer.begin_user_action()

		self.xep0184_marks[id_] = buffer.create_mark(None,
			buffer.get_end_iter(), left_gravity=True)
		self.xep0184_shown[id_] = NOT_SHOWN

		def show_it():
			if (not id_ in self.xep0184_shown) or \
			self.xep0184_shown[id_] == ALREADY_RECEIVED:
				return False

			end_iter = buffer.get_iter_at_mark(
				self.xep0184_marks[id_])
			buffer.insert(end_iter, ' ')
			buffer.insert_pixbuf(end_iter,
				ConversationTextview.XEP0184_WARNING_PIXBUF)
			before_img_iter = buffer.get_iter_at_mark(
				self.xep0184_marks[id_])
			before_img_iter.forward_char()
			post_img_iter = before_img_iter.copy()
			post_img_iter.forward_char()
			buffer.apply_tag_by_name('xep0184-warning', before_img_iter,
				post_img_iter)

			self.xep0184_shown[id_] = SHOWN
			return False
		gobject.timeout_add_seconds(2, show_it)

		buffer.end_user_action()
コード例 #24
0
    def __toggled(self, widget, argv):
        if argv == "auto_time_toggle":
            is_auto_set_time = widget.get_active()
            self.datetime_settings.set_boolean("is-auto-set", is_auto_set_time)
            if is_auto_set_time:
                self.__send_message("status", ("date_time", _("Time will be synchronized with an Internet time server")))
                self.set_time_spin_align.set_child_visible(False)
                gobject.timeout_add_seconds(3, self.__set_using_ntp, True)
            else:
                self.__send_message("status", ("date_time", _("Time will not be synchronized with an Internet time server")))
                self.set_time_spin_align.set_child_visible(True)
                if self.__toggle_id:
                    gobject.source_remove(self.__toggle_id)
                self.__toggle_id = gobject.timeout_add_seconds(3, self.__set_using_ntp, False)
            return

        if argv == "time_display_toggle":
            self.is_24hour = widget.get_active()
            if self.is_24hour:
                self.__send_message("status", ("date_time", _("Time will be shown in 24 hour format")))
            else:
                self.__send_message("status", ("date_time", _("Time will be shown in 12 hour format")))
            self.datetime_settings.set_boolean("is-24hour", self.is_24hour)
            self.datetime_widget.set_is_24hour(self.is_24hour)
            self.set_time_spin.set_24hour(self.is_24hour)
コード例 #25
0
ファイル: dispatcher.py プロジェクト: Alberto-Beralix/Beralix
  def refresh(self, *args):
    if self.refresh_timer_id:
      gobject.source_remove(self.refresh_timer_id)

    refresh_interval = gsettings.get_int("interval")

    if not self.maintRunning and not self.refreshRunning:
      log.logger.debug("Refresh interval is set to %s", refresh_interval)
      operations = []
    
      for o in self.collector.get_operations():
        interval = FEATURES[o[1]].get("interval", 1)
        if self.refresh_count % interval == 0:
          operations.append(o)
    
      if operations:
        log.logger.debug("** Starting Refresh - %s **", mx.DateTime.now())
        self.LoadingStarted()
        self.perform_async_operation(operations)


      self.refresh_timer_id = gobject.timeout_add_seconds(int(60 * refresh_interval), self.refresh)
    else:
      self.refresh_timer_id = gobject.timeout_add_seconds(int(30), self.refresh)

    if not self.maintDone:
      self.maint_timer_id = gobject.timeout_add_seconds(60, self.do_maintenance)

    return False
コード例 #26
0
ファイル: background.py プロジェクト: wpjunior/telecentros
    def grab(self, window, att=0):

        window.show()
        self.grabed_window = window
        self.set_left_cursor(window)
        window.set_keep_above(True)
        pstatus = self.lock_pointer(window)
        kstatus = self.lock_keyboard(window)
        window.set_keep_above(True)

        if self.grab_connect_id > 0:
            gobject.source_remove(self.grab_connect_id)
            self.grab_connect_id = 0

        self.grab_connect_id = window.connect("event", 
                                              self.grabed_window_event)
        
        # stop after 4 attempts
        if att >= 4:
            return

        if pstatus != gtk.gdk.GRAB_SUCCESS or kstatus != gtk.gdk.GRAB_SUCCESS:
            gobject.timeout_add_seconds(1, self.grab,
                                        window,
                                        att+1)
コード例 #27
0
ファイル: posix_dbus.py プロジェクト: MarSoft/skype4py
 def send_command(self, command):
     if not self.skype_out:
         self.attach(command.Timeout)
     self.push_command(command)
     self.notifier.sending_command(command)
     cmd = '#%d %s' % (command.Id, command.Command)
     self.logger.debug('sending %s', repr(cmd))
     if command.Blocking:
         if self.run_main_loop:
             command._event = event = threading.Event()
         else:
             command._loop = loop = gobject.MainLoop()
             command._set = False
     else:
         command._timer = timer = threading.Timer(command.timeout2float(), self.pop_command, (command.Id,))
     try:
         result = self.skype_out.Invoke(cmd)
     except dbus.DBusException as err:
         raise SkypeAPIError(str(err))
     if result.startswith('#%d ' % command.Id):
         self.notify(result)
     if command.Blocking:
         if self.run_main_loop:
             event.wait(command.timeout2float())
             if not event.isSet():
                 raise SkypeAPIError('Skype command timeout')
         elif not command._set:
             gobject.timeout_add_seconds(int(command.timeout2float()), loop.quit)
             loop.run()
             if not command._set:
                 raise SkypeAPIError('Skype command timeout')
     else:
         timer.start()
コード例 #28
0
ファイル: pygnad.py プロジェクト: mutax/PyGNAD
	def __init__(self,nic,fg,bg,ival):

		gtk.gdk.threads_init()

		self.myqueue=deque()
		self.lastvalue=None
		self.fgcolor=fg
		self.bgcolor=bg
		self.nic=nic

		for i in range(self.w):
			self.myqueue.append(20)

		sys.stderr.write("icon init started\n")
		# create a new Status Icon
		self.staticon = gtk.StatusIcon()

		#self.draw_graph()

		gobject.timeout_add_seconds(ival, self.timer_update)

		self.staticon.connect("activate", self.activate)
		self.staticon.connect("popup_menu", self.popup)
		self.staticon.set_visible(True)
		sys.stderr.write("icon init finished\n")
コード例 #29
0
ファイル: Search.py プロジェクト: csryan/pogo
 def cache_dirs(self, keep_caching):
     for index, path in enumerate(self.paths):
         # Cache dirs one by one after a small timeout
         gobject.timeout_add_seconds(3 * index, self.search_dir, path,
                                     CACHE_QUERY)
     # Keep caching in regular intervals
     return keep_caching
コード例 #30
0
    def test_queries_while_batch_insert (self):
        self.assertTrue (os.path.exists ('ttl'))
        
        for root, dirs, files in os.walk('ttl'):
            for ttl_file in filter (lambda f: f.endswith (".ttl"), files):
                full_path = os.path.abspath(os.path.join (root, ttl_file))
                print full_path

                counter = 0
                current_batch = ""
                for line in open(full_path):
                    if (line.startswith ("@prefix")):
                        continue
                    current_batch += line
                    if len(line) > 1 and line[:-1].endswith ('.'):
                        counter += 1
                
                    if counter == BATCH_SIZE:
                        query = "INSERT {" + current_batch + "}"
                        self.tracker.get_tracker_iface ().BatchSparqlUpdate (query,
                                                          timeout=20000,
                                                          reply_handler=self.batch_success_cb,
                                                          error_handler=self.batch_failed_cb)
                        self.run_a_query ()
                        counter = 0
                        current_batch = ""
                        self.batch_counter += 1
                        
        
        gobject.timeout_add_seconds (2, self.run_a_query)
        # Safeguard of 60 seconds. The last reply should quit the loop
        gobject.timeout_add_seconds (60, self.timeout_cb)
        self.main_loop.run ()
コード例 #31
0
 def _init_dbus_reconnect_timer(self):
     gobject.timeout_add_seconds(constants.DBUS_RECONNECT_INTERVAL_SECONDS,
                                 self._dbus_reconnect)
コード例 #32
0
 def _init_dbus_check_timer(self):
     gobject.timeout_add_seconds(constants.DBUS_CHECK_INTERVAL_SECONDS,
                                 self._dbus_check)
コード例 #33
0
 def _init_autoexit_timer(self):
     gobject.timeout_add_seconds(constants.AUTOEXIT_TIMEOUT_SECONDS,
                                 self._autoexit)
コード例 #34
0
 def _init_autoexitcheck_timer(self):
     if self._indicator_hdl.get_keep_alive() is False:
         gobject.timeout_add_seconds(
             constants.AUTOEXIT_CHECK_INTERVAL_SECONDS, self._autoexitcheck)
コード例 #35
0
bus = pipeline.get_bus()

#Set the download flag
flags = pipeline.get_property("flags")
flags |= GstPlayFlags.GST_PLAY_FLAG_DOWNLOAD
pipeline.set_property("flags", flags)

#Start playing
ret = pipeline.set_state(gst.STATE_PLAYING)
if (ret == gst.STATE_CHANGE_FAILURE):
    print >> sys.stderr, "Unable to set pipeline to playing state"
    exit(-1)
elif (ret == gst.STATE_CHANGE_NO_PREROLL):
    data.is_live = True

main_loop = gobject.MainLoop(None, False)
data.loop = main_loop
data.pipeline = pipeline

bus.add_signal_watch()
bus.connect("message", cb_message, data)
pipeline.connect("deep-notify::temp-location", got_location)

#Register a function that GLib will call every second
gobject.timeout_add_seconds(1, refresh_ui, data)
main_loop.run()

#Free resources
pipeline.set_state(gst.STATE_NULL)
print ""
コード例 #36
0
 def idle( self ):
     logger.info( "================== mainloop   entered ===================" )
     logger.info( "startup time was %.2f seconds" % ( time.time() - self.launchTime ) )
     gobject.timeout_add_seconds( 1*60, self.timeout )
     return False # mainloop: don't call me again
コード例 #37
0
ファイル: journal.py プロジェクト: abhinav3295/RedNotebook
    def __init__(self):
        self.dirs = dirs

        user_config = configuration.Config(self.dirs.config_file)
        # Apply defaults where no custom values have been set
        for key, value in default_config.items():
            if key not in user_config:
                user_config[key] = value
        self.config = user_config
        self.config.save_state()

        logging.info('Running in portable mode: %s' % self.dirs.portable)

        # Allow starting minimized to tray
        # When we start minimized we have to set the tray icon visible
        self.start_minimized = filesystem.HAS_TRAY and args.minimized
        if not filesystem.HAS_TRAY:
            self.config['closeToTray'] = 0
        elif self.start_minimized:
            self.config['closeToTray'] = 1

        self.month = None
        self.date = None
        self.months = {}

        # The dir name is the title
        self.title = ''

        # show instructions at first start
        self.is_first_start = self.config.read('firstStart', 1)
        self.config['firstStart'] = 0
        logging.info('First Start: %s' % bool(self.is_first_start))

        logging.info('RedNotebook version: %s' % info.version)
        logging.info(filesystem.get_platform_info())

        utils.set_environment_variables(self.config)

        self.actual_date = self.get_start_date()

        # Let components check if the MainWindow has been created
        self.frame = None
        self.frame = MainWindow(self)

        journal_path = self.get_journal_path()
        if not self.dirs.is_valid_journal_path(journal_path):
            logging.error('Invalid directory: %s. Using default journal.' %
                          journal_path)
            self.show_message(
                _('You cannot use this directory for your journal:') +
                ' %s' % journal_path + '. ' + _('Opening default journal.'),
                error=True)
            journal_path = self.dirs.default_data_dir
        self.open_journal(journal_path)

        self.archiver = backup.Archiver(self)
        #self.archiver.check_last_backup_date()

        # Check for a new version
        if self.config.read('checkForNewVersion', 0) == 1:
            utils.check_new_version(self, info.version, startup=True)

        # Automatically save the content after a period of time
        gobject.timeout_add_seconds(600, self.save_to_disk)
コード例 #38
0
        self.topwindow.show_all()

        ## offset the window if required
        self.topwindow.move(int(xoffset), int(yoffset))

        self.running = True

        if self.last_file is not None:
            self.topwindow.set_title(g_progname + ': ' +
                                     os.path.basename(self.last_file))
            self.last_file_mtime = datetime.datetime.fromtimestamp(
                os.path.getmtime(self.last_file))

        self.ct = 0
        self._periodic('BEGIN')
        gobject.timeout_add_seconds(g_periodic_secs, self._periodic,
                                    'Continue')
        # or use gobject.timeout_add() interval units in mS

    def _periodic(self, arg):
        # print "_periodic:",self.ct,arg
        self.ct += 1
        self.halg.poll()

        # prevent it forcing to the top when embedded into another window
        # that gremlin_view knows nothing about
        if g_childwindow == False:
            if self.parent is None:
                self.topwindow.deiconify()

        if (self.parent is not None) and (self.ct) == 2:
            # not sure why delay is needed for reparenting
コード例 #39
0
 def on_leave_notify_event(self, *args):
     """
     callback called when the mouse leaves this window
     """
     if self.tag is None:
         self.tag = gobject.timeout_add_seconds(1, self.windows_workaround)
コード例 #40
0
	def bind_timer(self, ev, interval, handler, *args, **kwargs):
		self.unbind_ev(ev)
		self.events[ev] = gobject.timeout_add_seconds(interval, handler, *args, **kwargs)
コード例 #41
0
 def rescan():
     mpris2sources.rescan()
     gobject.timeout_add_seconds(30, rescan)
コード例 #42
0
ファイル: phony_service.py プロジェクト: tonwu123/phony
    def run(self):
        """
    Starts phony service which manages device pairing and setting
    up of hands-free profile services.  This function never returns.
    """
        stdin_fd = sys.stdin.fileno()
        pid = os.fork()
        if not pid:
            #child
            os.setsid()
            bus = phony.base.ipc.BusProvider()
            # Find the first audio card that provides audio input and output mixers.
            audio_card_index = -1
            with phony.bluetooth.adapters.Bluez5(bus) as adapter, \
                 phony.bluetooth.profiles.handsfree.Ofono(bus) as hfp, \
                 phony.audio.alsa.Alsa(card_index=audio_card_index) as audio, \
                 phony.headset.HandsFreeHeadset(bus, adapter, hfp, audio) as hs:
                # Register to receive some bluetooth events
                hs.on_device_connected(self.device_connected)
                hs.on_incoming_call(self.incoming_call)
                hs.on_call_began(self.call_began)
                hs.on_call_ended(self.call_ended)
                hs.start('MyBluetoothHeadset', pincode='1234')
                hs.enable_pairability(timeout=30)
                self._hs = hs

                signal.signal(signal.SIGTERM, process_end)
                signal.signal(signal.SIGINT, process_end)
                signal.signal(signal.SIGUSR1, process_answer_call)
                signal.signal(signal.SIGUSR2, process_dial_number)
                gobject.timeout_add_seconds(1, tick)
                loop = gobject.MainLoop()
                try:
                    loop.run()
                except KeyboardInterrupt:
                    print("Child caught keyborad interrupt")
                return 0
                # Wait forever> gobject.MainLoop().run()
        #parent
        def on_sigchld(signum, frame):
            assert signum == signal.SIGCHLD
            print("Child terminated - terminating parent")
            sys.exit(0)

        signal.signal(signal.SIGCHLD, on_sigchld)
        stdin_attrs = termios.tcgetattr(stdin_fd)
        tty.setcbreak(stdin_fd)
        while True:
            try:
                char = os.read(stdin_fd, 1)
                if char.lower() == "a":
                    os.kill(pid, signal.SIGUSR1)
                if char.lower() == "d":
                    os.kill(pid, signal.SIGUSR2)
            except KeyboardInterrupt:
                print("Forwarding SIGINT to child process")
                os.kill(pid, signal.SIGINT)
            except SystemExit:
                print("Caught SystemExit: cleaning up")
                termios.tcsetattr(stdin_fd, termios.TCSADRAIN, stdin_attrs)
                print("Parent terminated normally")
                return 0
コード例 #43
0
# use work stealing
sched = WSScheduler()

# our application state
state = {}

# our exclusive port, only one of these will be processed
# at a time and no teardown or concurrent will be processed
# concurrently
port_e = Port()

# our concurrent port, as many of these will be processed as
# allowed concurrently
port_c = Port()

# our teardown port, after a message is received from this port,
# no more messages will be received, ever.
port_t = Port()

# setup our coordinator to manage the receivers
recv_e = Arbiter.receive(port_e, onExclusiveMsg, state, scheduler=None)
recv_c = Arbiter.receive(port_c, onConcurrentMsg, state, scheduler=None)
recv_t = Arbiter.receive(port_t, onTeardownMsg, state, scheduler=None)
a = Arbiter.coordinate(recv_e, recv_c, recv_t)

gobject.timeout_add(0, queueMsgs, (port_e, port_c, port_t))
gobject.timeout_add_seconds(
    2, printStat, (port_e, port_c, port_t, recv_e, recv_c, recv_t, a))
gtk.main()
コード例 #44
0
 def on_show(self, widget=None, event=None):
     self.move(self.placement[0], self.placement[1])
     if self.__stop:
         self.__stop = False
         timeout_add_seconds(1, self.update_widgets)
コード例 #45
0
def main():

	#
	# Check if Source Controller started and available
	#
	printer('Checking if Source Controller is online...')	
	messaging.publish_command('/source/next', 'SET')
	
	# !! !! TODO IMPORTANT !! !!


	#
	# QuickPlay
	#
	print "XX DEBUG XX"
	print SOURCE
	print SOURCE_SUB

	print "XX DEBUG XX"
	SOURCE = None

		
	# BOOT is true for 'early boot'
	#if BOOT and not prevSource = "" and not prevSource == SOURCE:

	#if not prevSource == SOURCE and not prevSource:
	#	print('Quickplay failed due mismatching source')
	#	exit()

	if not SOURCE:
		printer ('No previous source; starting first available source', tag='QPLAY')	
		messaging.send_command('/source/next', 'SET')
		messaging.send_command('/player/state', 'SET:play')
		
	else:
		ret = QuickPlay( prevSource,
						 prevSourceSub )
						 
		if ret:
			printer ('Checking other sources...', tag='QPLAY')
			# TODO: the prev. source is now checked again.. this is not efficient..
			Sources.sourceCheckAll()
			printSummary(Sources)
			
		else:
			printer ('Continuing playback not available, checking all sources...', tag='QPLAY')
			Sources.sourceCheckAll()
			printSummary(Sources)
			printer ('Starting first available source', tag='QPLAY')
			Sources.next()
			hu_play(resume=False)

	print "XX DEBUG XX"


	
	"""
	# Save Settings
	currSrc = Sources.getComposite()
	cSettings.set('source',currSrc['name'])

	# update sub-source key (in case of sub-source)
	if 'subsource' in currSrc:
		subsource_key = {}
		for key in currSrc['subsource_key']:
			subsource_key[key] = currSrc['subsource'][key]
		cSettings.set('subsourcekey', subsource_key)

	cSettings.save()

	"""
			

			
	"""
	else:
		for source in Sources.getAll():
			if source['name'] == prevSource:
				print("!! PREVIOUS SOURCE: {0}".format(source['name']))
				#if 'label' in source:
				index = Sources.getIndex
				print("!! CHECKING IF IT IS AVAILABLE...")
				
				Sources.sourceCheck(
	"""
	# First, try previously active source


	# on demand...
	#plugin_sources.media.media_add('/media/USBDRIVE', Sources)


	#myprint('A WARNING', level=logging.WARNING, tag="test")
	#logger.warning('Another WARNING', extra={'tag':'test'})

	# Save operational settings
	#dSettings1 = {"source": -1, 'volume': 99, 'mediasource': -1, 'medialabel': ''}	 # No need to save random, we don't want to save that (?)
	#settings_save( sFileSettings, dSettings1 )

	#
	# Setting up worker threads
	#

	"""
	printer('Setting up queues and worker threads')

	qPrio = Queue(maxsize=4)	# Short stuff that can run anytime:
	qBlock = Queue(maxsize=4)	# Blocking stuff that needs to run in sequence
	qAsync = Queue(maxsize=4)	# Long stuff that can run anytime (but may occasionally do a reality check):

	t = threading.Thread(target=worker_queue_prio)
	#p = Process(target=worker_queue_prio)
	t.setDaemon(True)
	#p.daemon = True
	t.start()
	#p.join()

	# disabled: see idle_add Queue Handler below
	# t = threading.Thread(target=worker_queue_blocking)
	# p = Process(target=worker_queue_blocking)
	# t.setDaemon(True)
	# p.daemon = True
	# t.start()

	t = threading.Thread(target=worker_queue_async)
	#p = Process(target=worker_queue_async)
	t.setDaemon(True)
	#p.daemon = True

	# DISABLED FOR ZMQ:
	#t.start()
	"""


	"""
	qBlock.put("SOURCE")
	qPrio.put("VOL_UP")
	qBlock.put("NEXT")
	qPrio.put("VOL_UP")
	qPrio.put("VOL_ATT")
	qBlock.put("SHUFFLE")
	qPrio.put("SHUTDOWN")

	exit()
	"""

	#********************************************************************************
	#
	# Main loop
	#

		
	#
	# Initialize the mainloop
	#
	DBusGMainLoop(set_as_default=True)


	#
	# main loop
	#
	mainloop = gobject.MainLoop()


	#
	# 30 second timer
	#
	# timer1:
	# - Save settings
	# - check if dbus services still online? (or make this a separate service?)
	gobject.timeout_add_seconds(30,cb_timer1)

	#
	# Queue handler
	# NOTE: Remember, everything executed through the qBlock queue blocks, including qPrio!
	# IDEALLY, WE'D PUT THIS BACK IN A THREAD, IF THAT WOULD PERFORM... (which for some reason it doesn't!)
	gobject.idle_add(idle_msg_receiver)
	queue_actions = Queue(maxsize=40)		# Blocking stuff that needs to run in sequence
	#gobject.idle_add(process_queue)

	#
	# Start the blocking main loop...
	#
	#with PidFile(PID_FILE) as p:
	try:
		mainloop.run()
	finally:
		mainloop.quit()
コード例 #46
0
ファイル: dispatcher.py プロジェクト: SMIDEC/gwibber-lc
    def __init__(self, loop, autorefresh=True):
        self.bus = dbus.SessionBus()
        bus_name = dbus.service.BusName("com.Gwibber.Service", bus=self.bus)
        dbus.service.Object.__init__(self, bus_name, self.__dbus_object_path__)

        self.db = sqlite3.connect(SQLITE_DB_FILENAME)

        self.accounts = storage.AccountManager(self.db)
        self.searches = storage.SearchManager(self.db)
        self.streams = storage.StreamManager(self.db)
        self.messages = storage.MessageManager(self.db)
        self.collector = OperationCollector(self)

        # Monitor the connection
        self.connection_monitor = util.getbus("Connection")
        self.connection_monitor.connect_to_signal("ConnectionOnline",
                                                  self.on_connection_online)
        self.connection_monitor.connect_to_signal("ConnectionOffline",
                                                  self.on_connection_offline)

        self.indicate = None

        if indicate and util.resources.get_desktop_file():
            self.indicate = indicate.indicate_server_ref_default()
            self.indicate.set_type("message.gwibber")
            self.indicate.set_desktop_file(util.resources.get_desktop_file())
            self.indicate.connect("server-display",
                                  self.on_indicator_server_activate)
            self.indicate.connect("interest-added",
                                  self.on_indicator_interest_added)
            self.indicate.connect("interest-removed",
                                  self.on_indicator_interest_removed)
            self.indicate.show()
        self.indicator_items = {}
        self.notified_items = []
        self.notified_errors = {}
        self.messages_indicator = None
        self.replies_indicator = None
        self.private_indicator = None
        self.unseen_counts = {}
        for s in "messages", "replies", "private":
            self.unseen_counts[s] = 0

        if Unity and Dbusmenu:
            launcher = Unity.LauncherEntry.get_for_desktop_id(
                "gwibber.desktop")
            ql = Dbusmenu.Menuitem.new()
            refresh_menu = Dbusmenu.Menuitem.new()
            refresh_menu.property_set(Dbusmenu.MENUITEM_PROP_LABEL,
                                      _("Refresh"))
            refresh_menu.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE,
                                           True)
            refresh_menu.connect("item-activated", self.refresh)
            ql.child_append(refresh_menu)
            accounts_menu = Dbusmenu.Menuitem.new()
            accounts_menu.property_set(Dbusmenu.MENUITEM_PROP_LABEL,
                                       _("Accounts"))
            accounts_menu.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE,
                                            True)
            accounts_menu.connect("item-activated", self.show_accounts)
            ql.child_append(accounts_menu)
            preferences_menu = Dbusmenu.Menuitem.new()
            preferences_menu.property_set(Dbusmenu.MENUITEM_PROP_LABEL,
                                          _("Preferences"))
            preferences_menu.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE,
                                               True)
            preferences_menu.connect("item-activated", self.show_preferences)
            ql.child_append(preferences_menu)
            quit_menu = Dbusmenu.Menuitem.new()
            quit_menu.property_set(Dbusmenu.MENUITEM_PROP_LABEL, _("Quit"))
            quit_menu.property_set_bool(Dbusmenu.MENUITEM_PROP_VISIBLE, True)
            quit_menu.connect("item-activated", self.shutdown)
            ql.child_append(quit_menu)
            launcher.set_property("quicklist", ql)

        self.refresh_count = 0
        self.mainloop = loop
        self.workerpool = multiprocessing.Pool()

        self.refresh_timer_id = None

        self.maintDone = False
        self.maintRunning = False
        self.refreshRunning = False

        if autorefresh:
            if self.refresh_timer_id:
                gobject.source_remove(self.refresh_timer_id)
            # wait a few seconds before alerting the world we are online
            self.refresh_timer_id = gobject.timeout_add_seconds(
                int(10), self.refresh)

        self.accounts_service = util.getbus("Accounts")
        self.accounts_service.connect_to_signal("Updated",
                                                self.on_account_updated)
        self.accounts_service.connect_to_signal("Deleted",
                                                self.on_account_deleted)
        self.accounts_service.connect_to_signal("Created",
                                                self.on_account_created)
コード例 #47
0
 def rescan():
     mpris2sources.rescan()
     gobject.timeout_add_seconds(TIME_FOR_RESCAN, rescan)
コード例 #48
0
 def run(self):
     gobject.timeout_add_seconds(60, self._refresh)
     self._refresh()
     loop = gobject.MainLoop()
     loop.run()
コード例 #49
0
 def __init__(self, ThisPtr, timeout):
     # register a periodic timer
     self.ThisPtr = ThisPtr
     self.tick = 120
     self.tag = gobject.timeout_add_seconds(timeout, self.callback)
コード例 #50
0
 def __init__(self, path):
     self.vfile = vfs.File.for_path(path)
     self.monitor = self.vfile.monitor()
     self.monitor.connect('changed', self.on_change)
     if self.vfile.props.file_type == vfs.FILE_TYPE_DIRECTORY:
         gobject.timeout_add_seconds(2, self.do_emit)
コード例 #51
0
 def state_checker(self):
   if os.path.exists(self.lock_file):
     self.ind.set_from_file(gtk.icon_theme_get_default().lookup_icon("bumblebee-indicator-active", 48, 0).get_filename())
   else:
     self.ind.set_from_file(gtk.icon_theme_get_default().lookup_icon("bumblebee-indicator", 48, 0).get_filename())
   gobject.timeout_add_seconds(5, self.state_checker)
コード例 #52
0
ファイル: today.py プロジェクト: goozbach/hamster
class DailyView(object):
    def __init__(self):
        # initialize the window.  explicitly set it to None first, so that the
        # creator knows it doesn't yet exist.
        self.window = None
        self.create_hamster_window()

        self.new_name.grab_focus()

        # DBus Setup
        try:
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
            # Set up connection to the screensaver
            self.dbusIdleListener = idle.DbusIdleListener()
            self.dbusIdleListener.connect('idle-changed', self.on_idle_changed)

        except dbus.DBusException, e:
            logging.error("Can't init dbus: %s" % e)

        # configuration
        self.timeout_enabled = conf.get("enable_timeout")
        self.notify_on_idle = conf.get("notify_on_idle")
        self.notify_interval = conf.get("notify_interval")
        self.workspace_tracking = conf.get("workspace_tracking")

        conf.connect('conf-changed', self.on_conf_changed)

        # Load today's data, activities and set label
        self.last_activity = None
        self.todays_facts = None

        runtime.storage.connect('activities-changed',self.after_activity_update)
        runtime.storage.connect('facts-changed',self.after_fact_update)
        runtime.storage.connect('toggle-called', self.on_toggle_called)

        self.screen = None
        if self.workspace_tracking:
            self.init_workspace_tracking()

        self.notification = None
        if pynotify:
            self.notification = pynotify.Notification("Oh hi",
                                                      "Greetings from hamster!")
            self.notification.set_urgency(pynotify.URGENCY_LOW) # lower than grass

        # refresh hamster every 60 seconds
        gobject.timeout_add_seconds(60, self.refresh_hamster)

        self.prev_size = None

        # bindings
        self.accel_group = self.get_widget("accelgroup")
        self.window.add_accel_group(self.accel_group)

        gtk.accel_map_add_entry("<hamster-applet>/tracking/add", gtk.keysyms.n, gtk.gdk.CONTROL_MASK)
        gtk.accel_map_add_entry("<hamster-applet>/tracking/overview", gtk.keysyms.o, gtk.gdk.CONTROL_MASK)
        gtk.accel_map_add_entry("<hamster-applet>/tracking/stats", gtk.keysyms.i, gtk.gdk.CONTROL_MASK)
        gtk.accel_map_add_entry("<hamster-applet>/tracking/close", gtk.keysyms.Escape, 0)
        gtk.accel_map_add_entry("<hamster-applet>/tracking/quit", gtk.keysyms.q, gtk.gdk.CONTROL_MASK)
        gtk.accel_map_add_entry("<hamster-applet>/edit/prefs", gtk.keysyms.p, gtk.gdk.CONTROL_MASK)
        gtk.accel_map_add_entry("<hamster-applet>/help/contents", gtk.keysyms.F1, 0)



        # create the status icon
        self.statusicon = ProjectHamsterStatusIcon(self)


        self.reposition_hamster_window()
        self.show_hamster_window()
        self.show_in_tray()
コード例 #53
0
    def __init__(self,
                 dirs,
                 args,
                 update_period=300,
                 update_period_remote=3600):

        self.args = args
        self.dirs = dirs
        self.update_period = update_period
        self.update_period_remote = update_period_remote
        self.remote = False  # Flag to update the remote
        self.ind = appindicator.Indicator(
            "checkgit", "", appindicator.CATEGORY_APPLICATION_STATUS)

        self.ind.set_status(appindicator.STATUS_ACTIVE)
        self.ind.set_attention_icon("indicator-messages-new")

        self.IconMenuDictionary = {
            'ahead': gtk.STOCK_GO_UP,
            'diverged': gtk.STOCK_REFRESH,
            'behind': gtk.STOCK_GO_DOWN,
            'up-to-date': gtk.STOCK_YES,
            'no-state': gtk.STOCK_HELP
        }
        # create a menu
        menu = gtk.Menu()

        ManualCheck = gtk.ImageMenuItem(gtk.STOCK_REFRESH)
        ManualCheck.set_always_show_image(True)
        ManualCheck.show()
        ManualCheck.connect("activate", self.SetIconAndMenuRemote2)
        menu.append(ManualCheck)

        ManualUpdate = gtk.ImageMenuItem(gtk.STOCK_HOME)
        ManualUpdate.set_always_show_image(True)
        ManualUpdate.show()
        ManualUpdate.connect("activate", self.PullPushAll)
        ManualUpdate.connect("activate", self.SetIconAndMenuRemote2)
        menu.append(ManualUpdate)

        dirs_items = []
        for dir in self.dirs:
            label_name = self.ClearDirName(dir)
            item = gtk.ImageMenuItem(gtk.STOCK_YES, label_name)
            item.show()
            item.set_always_show_image(True)
            menu.append(item)
            dirs_items.append(item)

        self.dirs_items = dirs_items

        quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quit.connect("activate", self.quit)
        quit.set_always_show_image(True)
        quit.show()
        menu.append(quit)

        self.ind.set_menu(menu)

        # Update the custom labels: must be done after `set_menu`.
        ManualCheck.set_label("Check status")
        ManualUpdate.set_label("Pull/Push")

        self.SetIconAndMenu(remote=True)  # Initialise the icon

        gobject.timeout_add_seconds(int(self.update_period),
                                    self.SetIconAndMenu)
        gobject.timeout_add_seconds(int(self.update_period_remote),
                                    self.SetIconAndMenuRemote)
        gtk.threads_init()
コード例 #54
0
ファイル: tray.py プロジェクト: luilver/hamster
    def __init__(self, project):
        self.project = project

        # Gconf settings
        #        self._settings = gconf.client_get_default()
        #        self._settings.add_dir(self.BASE_KEY, gconf.CLIENT_PRELOAD_NONE)
        # Key to enable/disable icon glow
        self._use_icon_glow = conf.get("icon_glow")
        self._show_label = conf.get("show_label")
        self._label_length = conf.get("label_length")
        self._last_activities_days = conf.get("last_activities_days")
        conf.connect('conf-changed', self.on_conf_changed)

        self._activity_as_attribute = None
        # Create a fake applet since HamsterApplet requires one
        #        applet = FakeApplet()

        self.indicator = appindicator.Indicator(
            "hamster-applet", "hamster-applet-inactive",
            appindicator.CATEGORY_SYSTEM_SERVICES)

        self.indicator.set_status(appindicator.STATUS_ACTIVE)
        # Set the attention icon as per the icon_glow gconf key
        self._set_attention_icon()

        # Initialise the activity label with "No Activity"
        self.indicator.set_label(self._get_no_activity_label())

        self.activity, self.duration = None, None

        self.menu = gtk.Menu()
        self.activity_item = gtk.MenuItem("")
        self.menu.append(self.activity_item)
        # this is where you would connect your menu item up with a function:
        self.activity_item.connect("activate", self.on_activate)
        self.activity_label = self.activity_item.get_child()
        self.activity_label.connect('style-set', self.on_label_style_set)

        # show the items
        self.activity_item.show()

        self.stop_activity_item = gtk.MenuItem(_(u"Sto_p tracking"))
        self.menu.append(self.stop_activity_item)
        # this is where you would connect your menu item up with a function:
        self.stop_activity_item.connect("activate",
                                        self.on_stop_activity_activated, None)
        # show the items
        self.stop_activity_item.show()

        self.last_activities_item = gtk.MenuItem(_(u"_Last activities"))
        self.menu.append(self.last_activities_item)
        # show the items
        self.last_activities_item.show()

        self.append_separator(self.menu)

        self.earlier_activity_item = gtk.MenuItem(_(u"Add earlier activity"))
        self.menu.append(self.earlier_activity_item)
        # this is where you would connect your menu item up with a function:
        self.earlier_activity_item.connect("activate",
                                           self.on_earlier_activity_activated,
                                           None)
        # show the items
        self.earlier_activity_item.show()

        self.overview_show_item = gtk.MenuItem(_(u"Show Overview"))
        self.menu.append(self.overview_show_item)
        # this is where you would connect your menu item up with a function:
        self.overview_show_item.connect("activate",
                                        self.on_overview_show_activated, None)
        # show the items
        self.overview_show_item.show()

        self.append_separator(self.menu)

        self.preferences_show_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)

        self.menu.append(self.preferences_show_item)
        # this is where you would connect your menu item up with a function:
        self.preferences_show_item.connect("activate",
                                           self.on_show_preferences_activated,
                                           None)
        # show the items
        self.preferences_show_item.show()

        self.append_separator(self.menu)

        self.quit_item = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menu.append(self.quit_item)
        # this is where you would connect your menu item up with a function:
        self.quit_item.connect("activate", gtk.main_quit, None)
        # show the items
        self.quit_item.show()

        self.project.last_activity = None
        runtime.storage.connect('activities-changed',
                                self.after_activity_update)
        runtime.storage.connect('facts-changed', self.after_fact_update)
        runtime.storage.connect('toggle-called', self.on_toggle_called)

        gobject.timeout_add_seconds(
            20, self.refresh_tray
        )  # refresh hamster every 20 seconds to update duration
コード例 #55
0
ファイル: channel.py プロジェクト: freesmartphone/framework
 def modemStateSimReady( self ):
     """
     Called, when the modem signalizes the SIM data can be read.
     """
     gobject.timeout_add_seconds( 1, self._sendCommands, "sim" )
コード例 #56
0
ファイル: plugin.py プロジェクト: lheckemann/gajim-plugins
 def activate(self):
     #self.check_birthdays()
     self.timeout_id = gobject.timeout_add_seconds(24*3600,
         self.check_birthdays)
コード例 #57
0
ファイル: scan.py プロジェクト: xxv/bcb_photobooth
 def clear(self):
     print "\n" * 60
     self.player.set_state(gst.STATE_NULL)
     gobject.timeout_add_seconds(5, self.resume_view)
コード例 #58
0
install_progressbar = gtk.ProgressBar()
install_progressbar.set_size_request(-1,30)
install_progressbar.set_text("Pretending to install. Please wait...")
install_progressbar.set_fraction(0)


slideshow_container.add(install_progressbar)
slideshow_container.add(slideshow_webview)


slideshow_window.show_all()


def progress_increment(progressbar, fraction):
	new_fraction = progressbar.get_fraction() + fraction
	if new_fraction > 1:
		progressbar.set_fraction(1.0)
		install_progressbar.set_text("Finished pretending to install.")
		return False
	
	progressbar.set_fraction(new_fraction)
	install_progressbar.set_text("Pretending to install... %d%%" % (new_fraction * 100))
	return True

install_timer = gobject.timeout_add_seconds(2, progress_increment, install_progressbar, 0.01)

gtk.main()

#gtk.widget_pop_colormap()
#print('Cleaned up GTK colormap stuff')
コード例 #59
0
class IdleNotifier(dbus.service.Object):
    #=========================================================================#
    """A Dbus Object implementing org.freesmartphone.Device.IdleNotifier"""
    DBUS_INTERFACE = DBUS_INTERFACE_PREFIX + ".IdleNotifier"

    _instance = None

    @classmethod
    def instance(klass):
        return klass._instance

    def __init__(self, bus, index, extranodes):
        self.__class__._instance = self
        self.interface = self.DBUS_INTERFACE
        self.path = DBUS_PATH_PREFIX + "/IdleNotifier/%s" % index
        dbus.service.Object.__init__(self, bus, self.path)
        logger.info("%s %s initialized. Serving %s at %s",
                    self.__class__.__name__, __version__, self.interface,
                    self.path)

        self.defaultTimeouts = dict(awake=-1,
                                    busy=-1,
                                    idle=10,
                                    idle_dim=20,
                                    idle_prelock=12,
                                    lock=2,
                                    suspend=20)
        self.timeouts = self.defaultTimeouts.copy()
        self.states = "awake busy idle idle_dim idle_prelock lock suspend".split(
        )
        self.validStates = set(self.states)
        self.allowedStates = set(self.states)
        self.state = self.states[0]

        configvalue = config.getValue(MODULE_NAME, "ignoreinput", "")
        ignoreinput = [
            int(value) for value in configvalue.split(',') if value != ""
        ]

        self.input = {}
        for i in itertools.count():
            if i in ignoreinput:
                logger.info("skipping input node %d due to configuration" % i)
                continue
            try:
                f = os.open("/dev/input/event%d" % i, os.O_NONBLOCK)
            except OSError, e:
                logger.debug(
                    "can't open /dev/input/event%d: %s. Assuming it doesn't exist."
                    % (i, e))
                break
            else:
                self.input[f] = "event%d" % i

        logger.info("opened %d input file descriptors" % len(self.input))

        # override default timeouts with configuration (if set)
        for key in self.timeouts:
            timeout = config.getInt(MODULE_NAME, key,
                                    self.defaultTimeouts[key])
            self.timeouts[key] = timeout
            if timeout == 0:
                self.allowedStates.remove(key)
            logger.debug("(re)setting %s timeout to %d" %
                         (key, self.timeouts[key]))

        self.next = None
        self.timeout = 0

        self.setState("busy")

        if len(self.input):
            self.timer = gobject.timeout_add_seconds(1, self.onTimer)
コード例 #60
0
ファイル: splash.py プロジェクト: napcok/MGAextra
# Set window centered
splash.set_position (gtk.WIN_POS_CENTER)
# Set window above the others
splash.set_keep_above (True)
# _I_ draw the window
splash.set_app_paintable(True)
# Draw window
splash.realize()
# Set null background
splash.window.set_back_pixmap(None, False)

# Signals
splash.connect("delete-event", gtk.main_quit, None)
splash.connect_after("expose-event", window_draw, None)

splash.show()

# Fade in splash screen
fade_window(splash)

# read delay time from command line
if len(sys.argv) < 2:
    delay = 3
else:
    delay = int(sys.argv[1])

# Close splash screen after X seconds
gobject.timeout_add_seconds(delay, gtk.main_quit, None);

gtk.main()