Пример #1
0
 def show_urgent(self):
     self.set_urgency_hint(self.counter%2 == 0)
     self.counter = self.counter + 1
     if self.counter < 10:
         glib.timeout_add(1000 * (self.counter % 7), self.show_urgent)
     else:
         self.set_urgency_hint(1==1)
Пример #2
0
    def next_step(self):
        # We already sent the details, but may still be on the same step.
        if self.wizard.tef_request_done:
            return StoqAdminPasswordStep(self.wizard, self.previous)

        webapi = WebService()
        response = webapi.tef_request(self.model.name, self.model.email,
                                      self.model.phone)
        response.addCallback(self._on_response_done)
        response.addErrback(self._on_response_error)

        # FIXME: This is a hack, remove it when we can avoid
        #        calling dialog.run()
        if not reactor.running:
            reactor.run()

        self.send_progress.show()
        self.send_progress.set_text(_('Sending...'))
        self.send_progress.set_pulse_step(0.05)
        self.details_table.set_sensitive(False)
        self.wizard.next_button.set_sensitive(False)
        glib.timeout_add(50, self._pulse)

        # Cancel the request after 30 seconds without a reply
        glib.timeout_add(30000, self._cancel_request)

        # Stay on the same step while sending the details
        return self
Пример #3
0
    def run(self, uri):
        def bus_cb(bus, msg):
            if gst.MESSAGE_TAG == msg.type:
                print dict(msg.structure)

            return True

        def test_cb():
            if 'flat' == self.profile:
                self.profile = 'pop'
            else:
                self.profile = 'flat'

            return True

        glib.timeout_add(5000, test_cb)
        self.get_bus().add_watch(bus_cb)

        self.uri = uri
        self.volume = 0.5
        self.set_state(gst.STATE_PLAYING)

        try:
            glib.MainLoop().run()
        except KeyboardInterrupt:
            pass
Пример #4
0
    def convert(self,
                options,
                converted_file_extension,
                video_quality=None,
                audio_quality=None):

        self.converted_file_extension = converted_file_extension

        # Create our ffmpeg arguments list
        args_list = ["ffmpeg"]
        # Add the input file
        args_list += ["-i", self.tempfile]
        # Add any UploadSource specific options
        args_list += options

        # Configure the quality as selected by the user
        # If the quality slider circle is at the right-most position
        # use the same quality option
        if video_quality == 6001:
            args_list += ["-sameq"]
        elif video_quality:
            args_list += ["-b", "%sk" % video_quality]
        if audio_quality:
            args_list += ["-ab", "%sk" % audio_quality]
        # Finally add the desired output file
        args_list += ["%s%s" % (self.tempfile[:-4], converted_file_extension)]

        # Run the ffmpeg command and when it is done, set a variable to
        # show we have finished
        command = Popen(args_list)
        glib.timeout_add(100, self._poll, command)
Пример #5
0
def main():
    #example usage
    import random
    color_combos = (("red", "white"), ("white", "blue"), ("green", "black"))
    messages = (("Hello", "This is a popup"),
            ("Some Latin", "Quidquid latine dictum sit, altum sonatur."),
            ("A long message", "The quick brown fox jumped over the lazy dog. " * 6))
    images = ("logo1_64.png", None)
    def notify_factory():
        color = random.choice(color_combos)
        message = random.choice(messages)
        image = random.choice(images)
        notifier.bg_color = gtk.gdk.Color(color[0])
        notifier.fg_color = gtk.gdk.Color(color[1])
        notifier.show_timeout = random.choice((True, False))
        notifier.new_popup(title=message[0], message=message[1], image=image)
        return True
    def gtk_main_quit():
        print("quitting")
        gtk.main_quit()

    notifier = GTK2_Notifier(timeout=6)
    glib.timeout_add(4000, notify_factory)
    glib.timeout_add(20000, gtk_main_quit)
    gtk.main()
Пример #6
0
def main():
    #example usage
    import random
    color_combos = (("red", "white"), ("white", "blue"), ("green", "black"))
    messages = (("Hello", "This is a popup"),
            ("Some Latin", "Quidquid latine dictum sit, altum sonatur."),
            ("A long message", "The quick brown fox jumped over the lazy dog. " * 6))
    images = ("logo1_64.png", None)
    def notify_factory():
        color = random.choice(color_combos)
        message = random.choice(messages)
        image = random.choice(images)
        notifier.bg_color = gtk.gdk.Color(color[0])
        notifier.fg_color = gtk.gdk.Color(color[1])
        notifier.show_timeout = random.choice((True, False))
        notifier.new_popup(title=message[0], message=message[1], image=image)
        return True
    def gtk_main_quit():
        print("quitting")
        gtk.main_quit()

    notifier = GTK2_Notifier(timeout=6)
    glib.timeout_add(4000, notify_factory)
    glib.timeout_add(20000, gtk_main_quit)
    gtk.main()
Пример #7
0
 def start(self, message):
     '''Start.'''
     if self.ticker >= self.times:
         glib.timeout_add(self.interval, self.redraw)
         
     self.ticker = 0
     self.label.set_markup("<span foreground='#333333' size='%s'>%s</span>" % (LABEL_FONT_MEDIUM_SIZE, message))
Пример #8
0
  def Bind(self, widget, data=None):
    if self.socket_handler:
      print "Warning: Socket already bound to master"
      return
    try:
      self.socket_handler = SocketHandler('localhost', 1987) 
      self.socket_handler.Handshake(5) # 5=DAQ
      self.bind_button.set_sensitive(False)
      self.unbind_button.set_sensitive(True)
      self.start_button.set_sensitive(not self.acquisition_started)
      self.stop_button.set_sensitive(self.acquisition_started)
      self.client_id = int(self.socket_handler.GetClientId())

      self.socket_id.set_markup('Client id: <b>%d</b>' % self.client_id)
      self.socket_handler.Send('GET_RUN_NUMBER', self.client_id)
      res = self.socket_handler.Receive('RUN_NUMBER')
      if res:
        self.current_run_id = int(res[1])
        self.run_id.set_markup('Run id: <b>%d</b>' % self.current_run_id)

      glib.timeout_add(1000, self.Update)
      self.Log('Client connected with id: %d' % self.client_id)
      self.Update()
      if self.acquisition_started and not self.daq_loop_launched:
        #print "Launching the acquisition monitor loop."
        self.DAQLoop()
    except SocketHandler.SocketError:
      print "Failed to bind!"
      return
Пример #9
0
    def __init__(self):
        gtk.Window.__init__(self)
        self.set_name('SplashWindow')
        self.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)
        self.resize(WIDTH, HEIGHT)
        # Ubuntu has backported the 3.0 has-resize-grip property,
        # disable it as it doesn't make sense for splash screens
        if hasattr(self.props, 'has_resize_grip'):
            self.props.has_resize_grip = False
        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.add(frame)

        darea = gtk.DrawingArea()
        try:
            darea.connect("expose-event", self.expose)
        except TypeError:
            darea.connect("draw", self.draw)
        frame.add(darea)

        self.show_all()
        pixbuf_data = environ.get_resource_string("stoq", "pixmaps",
                                                  "splash.png")
        self._pixbuf = pixbuf_from_string(pixbuf_data)

        glib.timeout_add(_WINDOW_TIMEOUT, self._hide_splash_timeout)
Пример #10
0
    def event1(self):
        self.emit('tag', {"tag": ""})
        self.clear_draw_que()
        self.continued = False

        movieobject = self.load_movie(
            os.path.join(self.imagedir, "Lucky_straw.avi"))

        print("event1")
        x = self.xaois1[self.round]
        y = self.yaois1[self.round]
        self.play_movie(movieobject, x, y, 0.2, 0.2)
        movieobject.draw()
        self.draw_queue.append(movieobject)

        self.stimulus_display_time = 2000

        self.next = self.event2

        active_aois = [0, 4, 0, 6]

        if self.continued:
            return
        else:
            glib.timeout_add(self.stimulus_display_time,
                             self.event2)  #defines onset asynchrony or delay
    def __init__(self, module_config_path, argv=""):
        '''
        init docs
        '''
        # Init.
        gtk.Plug.__init__(self, 0)
        self.module_config_path = module_config_path
        self.module_config = Config(self.module_config_path)
        self.module_config.load()
        self.module_id = self.module_config.get("main", "id")
        self.argv = argv
        
        # WARING: only use once in one process
        DBusGMainLoop(set_as_default=True) 
        
        # Init threads.
        if self.module_id != "bluetooth": # Added by hualet, wonder why? go ask him :)
            gtk.gdk.threads_init()

        # Init dbus.
        self.bus = dbus.SessionBus()
        self.module_dbus_name = "com.deepin.%s_settings" % (self.module_id)
        self.module_object_name = "/com/deepin/%s_settings" % (self.module_id)
        self.module_bus_name = dbus.service.BusName(self.module_dbus_name, bus=self.bus)
        
        # Handle signals.
        self.connect("realize", self.module_frame_realize)
        self.connect("destroy", self.module_frame_exit)

        glib.timeout_add(1000, self.is_exist)
Пример #12
0
def main():
    import sys
    def argint(n, d):
        try:
            return int(sys.argv[n])
        except:
            return d
    N = argint(1, 1)        #number of windows
    delay = argint(2, 20)
    ydelta = argint(3, 1)
    animate = argint(4, 1)
    client = FakeGTKClient()
    print("%i windows, delay=%ims, ydelta=%i" % (N, delay, ydelta))
    window_classes = []
    try:
        from xpra.client.gtk2.border_client_window import BorderClientWindow
        window_classes.append(BorderClientWindow)
    except:
        pass
    try:
        from xpra.client.gl.gtk2.gl_client_window import GLClientWindow
        window_classes.append(GLClientWindow)
    except:
        pass
    for wid in range(N):
        window_class = window_classes[wid % len(window_classes)]
        anim = WindowAnim(window_class, client, wid, animate=animate)
        glib.idle_add(anim.scrolluponce, ydelta)
        glib.timeout_add(delay, anim.scrollup, ydelta)
    try:
        gtk_main()
    except KeyboardInterrupt:
        pass
Пример #13
0
 def increment_level(self):
     """Increment level by 1, and change the label. Also call make_timer
     and hook up the resulting function with glib.timeout_add, to be
     called  every 2.0/(level+3) seconds."""
     self.level += 1
     styled_set_label_text(self.level_display, "Level:  "+str(self.level))
     glib.timeout_add(2000//(self.level+3), self.make_timer(self.level))
Пример #14
0
    def handleHardware(self, actionString):
        hwSelected = False
        selHw = []
        selHwString = ''
        chkList = functions.getColumnValues(self.tvHardware, 0)
        statList = functions.getColumnValues(self.tvHardware, 5)
        hwList = functions.getColumnValues(self.tvHardware, 4)
        for i in range(len(chkList)):
            if chkList[i]:
                self.log.write(actionString + ' hardware code: ' + hwList[i],
                               'ddm.handleHardware', 'info')
                selHw.append([hwList[i], statList[i]])
                hwSelected = True

        if hwSelected:
            # Install selected drivers
            self.toggleGuiElements(True)
            # Start saving in a separate thread
            self.log.write('Start driver ' + actionString + ' thread',
                           'ddm.handleHardware', 'info')
            if actionString == 'install':
                t = DriverInstall(selHw, self.log)
            else:
                t = DriverRemove(selHw, self.log)
            t.start()
            # Run spinner as long as the thread is alive
            self.log.write('Check every 5 seconds if thread is still active',
                           'ddm.installHardware', 'debug')
            glib.timeout_add(5, self.checkThread, actionString)
        else:
            msg = 'Select a driver to install.'
            MessageDialog('Driver install', msg, gtk.MESSAGE_INFO,
                          self.window.get_icon()).show()
    def hoverIcon(self, *args):
        '''Hover icon.'''
        self.ticker = self.times
        if self.tooltipWindow == None:
            self.tooltipWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.tooltipWindow.set_decorated(False)
            self.tooltipWindow.set_default_size(self.TOOLTIP_WIDTH, self.TOOLTIP_HEIGHT)
            self.tooltipWindow.connect("size-allocate", lambda w, a: updateShape(w, a, 4))
            
            self.tooltipEventBox = gtk.EventBox()
            self.tooltipEventBox.connect("button-press-event", lambda w, e: self.showSoftwareCenter())
            self.tooltipWindow.add(self.tooltipEventBox)
            
            glib.timeout_add(self.interval, self.redraw)

        (iconScreen, iconRect, orientation) = self.trayIcon.get_geometry()
        (screenWidth, screenHeight) = getScreenSize(self.trayIcon)
        tooltipX = iconRect.x - iconRect.width
        if iconRect.y + iconRect.height > screenHeight:
            tooltipY = iconRect.y - self.TOOLTIP_HEIGHT - self.TOOLTIP_OFFSET_Y 
        else:
            tooltipY = iconRect.y + iconRect.height + self.TOOLTIP_OFFSET_Y
        self.tooltipWindow.set_opacity(0.9)
        self.tooltipWindow.move(tooltipX, tooltipY)
        self.tooltipWindow.queue_draw()
        self.tooltipWindow.show_all()
Пример #16
0
def run_later_in_gui_thread(delay, func, *a, **kw):
    """Run the function in the GUI thread, after a delay"""
    def timer():
        func(*a, **kw)
        return False
    glib.timeout_add(delay, timer)
    return None
Пример #17
0
    def __init__(self, trace, timeout):
        super(OutbreakGUI, self).__init__()

        # Read the file to know the number of players or the size of the window
        self.trace = open(trace, 'r')
        self.read_initial_data()

        self.set_title('Outbreak')
        # self.set_size_request(self.width, self.height)
        self.set_resizable(False)
        self.set_position(gtk.WIN_POS_CENTER)

        # Main box ((Arena + players) + status bar)
        self.main_box = gtk.VBox(False, 0)
        self.central_box = gtk.HBox(False, 5)

        self.player_box = self.build_player_box()
        self.arena = Arena(self.rows, self.cols)
        self.statusbar = gtk.Statusbar()
        self.statusbar.set_has_resize_grip(False)

        self.central_box.pack_start(self.arena, False, False, 0)
        self.central_box.pack_start(self.player_box, False, False, 0)

        self.main_box.pack_start(self.central_box, False, False, 0)
        self.main_box.pack_start(self.statusbar, False, False, 0)

        self.add(self.main_box)

        self.connect("destroy", gtk.main_quit)
        self.show_all()

        self.update_gui()

        glib.timeout_add(timeout, self.update_gui)
Пример #18
0
    def loop_iteration(self, timeout=1):
        self._stack.append(None)
        try:
            if self.check_events():
                return
            self._prepare_pending()

            def dummy_cb():
                "Dummy callback function to force event if none are pending."
                self._anything_done = True
                logger.debug("Dummy timeout func called")
                return False

            if not glib.main_context_default().pending():
                glib.timeout_add(int(timeout * 1000), dummy_cb)
            self._anything_done = False
            logger.debug("Calling main_context_default().iteration()")
            while not self._anything_done:
                glib.main_context_default().iteration(True)
            logger.debug("..main_context_default().iteration() exited")
        finally:
            self._stack.pop()
        if self.exc_info:
            (exc_type, exc_value, ext_stack), self.exc_info = (self.exc_info,
                                                               None)
            raise exc_type(exc_value).with_traceback(ext_stack)
Пример #19
0
 def no_connection(self):
     if self.reconnect is None:
         print 'Auto reconnect disabled, quitting...'
         self.main_loop.quit()
     else:
         print 'Will retry every %d seconds' % self.reconnect
         glib.timeout_add(self.reconnect * 1000, self._connect)
Пример #20
0
    def on_prefs_ex_activate(self, expander):
        def resize():
            self.window.resize(self.window.get_size()[0],
                               self.window.size_request()[1])
            return False

        glib.timeout_add(200, resize)
Пример #21
0
 def __init__(self):
     try:
         self.icon = gtk.StatusIcon()
         self.update_icon()
         glib.timeout_add(1100, self.update_icon)
     except:
         glib.timeout_add(1100, self.update_icon)
 def __init__(self, gtkbuilder):
   self.builder = gtkbuilder
   self.liststore = gtkbuilder.get_object("liststore_comports")
   self.combobox = gtkbuilder.get_object("combobox1")
   self.__updateComPorts()
   glib.timeout_add(500, self.__updateComPorts)
   self.ctx = barobo.BaroboCtx()
Пример #23
0
    def next_step(self):
        # We already sent the details, but may still be on the same step.
        if self.wizard.tef_request_done:
            return StoqAdminPasswordStep(self.wizard, self.previous)

        webapi = WebService()
        response = webapi.tef_request(self.model.name, self.model.email,
                                      self.model.phone)
        response.addCallback(self._on_response_done)
        response.addErrback(self._on_response_error)

        # FIXME: This is a hack, remove it when we can avoid
        #        calling dialog.run()
        if not reactor.running:
            reactor.run()

        self.send_progress.show()
        self.send_progress.set_text(_('Sending...'))
        self.send_progress.set_pulse_step(0.05)
        self.details_table.set_sensitive(False)
        self.wizard.next_button.set_sensitive(False)
        glib.timeout_add(50, self._pulse)

        # Cancel the request after 30 seconds without a reply
        glib.timeout_add(30000, self._cancel_request)

        # Stay on the same step while sending the details
        return self
Пример #24
0
    def test_signal_do_not_notify_then_new_versions_do_not_change_tags(self):
        request = { 'all_count': 1,
                    'out': [ { 'uid': 1, 'activity_id': 1, 'timestamp': 1, '_tags_': '[[["A"], "__tag_A__"]]' } ] }

        errors = []

        def tags_cb(s, type):
            errors.append(type)

        semaphore = [1]

        def signal_cb(s):
            if len(semaphore):
                semaphore.pop()
                ds.call('Created', { 'uid': 2, 'activity_id': 1, 'timestamp': 2, '_tags_': '[[["A"], "__tag_A__"]]' })
                ds.call('Updated', { 'uid': 3, 'activity_id': 1, 'timestamp': 3, '_tags_': '[[["A"], "__tag_A__"]]' })

        def timeout_cb():
            gtk.main_quit()

        s = DatastoreRichSource()
        s.connect('tags-updated', tags_cb)
        s.connect('objects-updated', signal_cb)
        s.on_query(request)
        glib.timeout_add(500, timeout_cb)
        gtk.main()

        self.assertEqual(3, len(errors))

        self.assertEqual({ 'buddies_count': 0, 'uid': 3, 'activity_id': 1, 'timestamp': 3, '_tags_': [(['A',], ['tag_A'])] }, s.get_row(0))
        self.assertEqual(1, s.get_count())
Пример #25
0
    def test_browse_async(self):
        caps = self.plugin.get_caps(Grl.SupportedOps.SEARCH)
        options = Grl.OperationOptions.new(caps)
        l = []
        results = []
        def callback(source, operation_id, media, remaining, user_data, error):
            if media:
                l.append(media)
            if remaining == 0:
                # todo: recurse
                dirs = []
                for m in l:
                    if isinstance(m, Grl.MediaBox):
                        dirs.append(m)
                    else:
                        results.append(m)
                l[:] = []
                for m in dirs:
                    self.plugin.browse(m, [Grl.METADATA_KEY_ID], options, callback, None)


        def check_result():
            loop.quit()
            path_list = sorted(m.get_id() for m in results)
            expected_result = sorted(os.path.join(_tempdir, d) for d in self.file_tree)
            self.assertEqual(path_list, expected_result)

            return False

        self.plugin.browse(None, [Grl.METADATA_KEY_ID], options, callback, None)

        loop = glib.MainLoop()
        glib.timeout_add(1000, check_result)
        loop.run()
    def __init__(self, datadir, db, icons):
        gtk.TreeStore.__init__(self, AnimatedImage, str, int, gobject.TYPE_PYOBJECT)
        self.icons = icons
        self.datadir = datadir
        self.backend = get_install_backend()
        self.backend.connect("transactions-changed", self.on_transactions_changed)
        self.backend.connect("channels-changed", self.on_channels_changed)
        self.db = db
        self.distro = get_distro()
        # pending transactions
        self._pending = 0
        # setup the normal stuff
        available_icon = self._get_icon("softwarecenter")
        self.available_iter = self.append(None, [available_icon, _("Get Software"), self.ACTION_ITEM_AVAILABLE, None])

        # do initial channel list update
        self._update_channel_list()
        
        icon = AnimatedImage(self.icons.load_icon("computer", self.ICON_SIZE, 0))
        installed_iter = self.append(None, [icon, _("Installed Software"), self.ACTION_ITEM_INSTALLED, None])
        icon = AnimatedImage(None)
        self.append(None, [icon, "<span size='1'> </span>", self.ACTION_ITEM_SEPARATOR_1, None])
        
        # kick off a background check for changes that may have been made
        # in the channels list
        glib.timeout_add(300, lambda: self._check_for_channel_updates(self.channels))
Пример #27
0
    def __init__(self):
        global args

        super(PyApp, self).__init__()

        self.set_title("Lasersaur")
        self.resize(1220, 610)
        self.set_position(gtk.WIN_POS_CENTER)

        self.connect("destroy", gtk.main_quit)
        # exit with ctr-q
        accel_group = gtk.AccelGroup()
        accel_group.connect_group(ord('q'), gtk.gdk.CONTROL_MASK,
        gtk.ACCEL_LOCKED, gtk.main_quit)
        self.add_accel_group(accel_group)

        self.darea = gtk.DrawingArea()
        self.darea.connect("expose-event", self.expose)
        self.add(self.darea)

        if args.animate:
            self.timer = True
            if args.fast:
                glib.timeout_add(10, self.on_timer)  #100fps
                self.inc = 8
            else:
                glib.timeout_add(40, self.on_timer)  #25fps
                self.inc = 4
            self.todraw = self.inc

        self.show_all()
Пример #28
0
 def __init__(self, width, hight, data_path, module_path):
     self.gda = gltools.create_drawning_area(width, hight)
     self.scene = list()
     self.data_path = data_path
     self.draw_callbacks = list()
     self.textures = dict()
     self.fonts = dict()
     self.mouse_pos = [0, 0]
     self.events = dict()  # Свои события
     self.time_now = datetime.now()
     user_module = tools.load_module(module_path)
     self.gda.connect_after('realize', callbacks.on_realize, self, user_module)
     self.gda.connect('expose-event', callbacks.on_expose_event, self, user_module)
     self.main_window = gtk.Window()
     self.main_window.set_reallocate_redraws(True)
     self.main_window.connect('delete-event', gtk.main_quit)
     self.main_window.set_title('GTKGLUI - Example')
     self.main_window.connect('key-press-event', glwidgets.key_dispatcher)
     self.main_window.connect('key-press-event',  callbacks.on_key_callback, self, user_module)
     glib.timeout_add(25, callbacks.on_timer_tick, self, user_module)
     vbox = gtk.VBox()
     self.main_window.add(vbox)
     vbox.pack_start(self.gda)
     self.main_window.show_all()
     self.main = gtk.main
	def __init__(self):
		self._commands = cmds = []
		self.win = gtk.Window()
		self.win.connect('destroy', lambda w: gtk.main_quit())
		self.root = gtk.VBox(False,10); self.win.add( self.root )
		self.root.set_border_width(20)
		self.header = header = gtk.HBox()
		self.root.pack_start( header, expand=False )
		b = gtk.Button('spike all neurons')
		b.connect('clicked', lambda b,s: s._commands.append('spike-all'), self )
		self.header.pack_start( b, expand=False )

		b = gtk.Button('spike one neuron')
		b.connect('clicked', lambda b,s: s._commands.append('spike-one'), self )
		self.header.pack_start( b, expand=False )

		b = gtk.Button('spike column 1')
		b.connect('clicked', lambda b,s: s._commands.append('spike-column'), self )
		self.header.pack_start( b, expand=False )

		self.header.pack_start( gtk.SeparatorMenuItem() )

		b = gtk.Button('debug')
		b.connect('clicked', lambda b,s: s._commands.append('info'), self )
		self.header.pack_start( b, expand=False )

		da = gtk.DrawingArea()
		da.set_size_request( 640,480 )
		da.connect('realize', self.realize)
		self.root.pack_start( da )

		self._read = None
		glib.timeout_add( 33, self.loop )
		self.win.show_all()
Пример #30
0
	def __init__(self, thread):
		gtk.Window.__init__(self, gtk.WINDOW_POPUP)
		self.set_border_width(12)
		self.set_decorated(False)
		self.set_position(gtk.WIN_POS_CENTER_ALWAYS)

		self.alarmThread = thread

		self.alarmThread.config.screen.disable()
		
		# VBox setup
		layout = gtk.VBox()
		layout.set_spacing(12)
		self.add(layout)

		self.time = gtk.Label()
		self.time.set_use_markup(True)
		layout.pack_start(self.time)
		self.updateClock()

		snooze = gtk.Button('Snooze')
		snooze.connect('clicked', self.onSnooze)
		snooze.set_size_request(-1, 75)
		layout.pack_start(snooze)

		off = gtk.Button('Off')
		off.connect('clicked', self.close)
		off.set_size_request(-1, 75)
		layout.pack_start(off)

		glib.timeout_add(2000, self.updateClock)
Пример #31
0
    def __init__(self, module_config_path, argv=""):
        '''
        init docs
        '''
        # Init.
        gtk.Plug.__init__(self, 0)
        self.module_config_path = module_config_path
        self.module_config = Config(self.module_config_path)
        self.module_config.load()
        self.module_id = self.module_config.get("main", "id")
        self.argv = argv

        # WARING: only use once in one process
        DBusGMainLoop(set_as_default=True)

        # Init threads.
        if self.module_id != "bluetooth":  # Added by hualet, wonder why? go ask him :)
            gtk.gdk.threads_init()

        # Init dbus.
        self.bus = dbus.SessionBus()
        self.module_dbus_name = "com.deepin.%s_settings" % (self.module_id)
        self.module_object_name = "/com/deepin/%s_settings" % (self.module_id)
        self.module_bus_name = dbus.service.BusName(self.module_dbus_name,
                                                    bus=self.bus)

        # Handle signals.
        self.connect("realize", self.module_frame_realize)
        self.connect("destroy", self.module_frame_exit)

        glib.timeout_add(1000, self.is_exist)
Пример #32
0
 def startPolling(self, widget):
     if self.allow_polling == False:
         self.allow_polling = True
         glib.timeout_add(2000, self.ticktock)
         z = widget.get_name()
         print 'widgetname=',z
     return
Пример #33
0
    def Bind(self, widget, data=None):
        if self.socket_handler:
            print "Warning: Socket already bound to master"
            return
        try:
            self.socket_handler = SocketHandler('localhost', 1987)
            self.socket_handler.Handshake(5)  # 5=DAQ
            self.bind_button.set_sensitive(False)
            self.unbind_button.set_sensitive(True)
            self.start_button.set_sensitive(not self.acquisition_started)
            self.stop_button.set_sensitive(self.acquisition_started)
            self.client_id = int(self.socket_handler.GetClientId())

            self.socket_id.set_markup('Client id: <b>%d</b>' % self.client_id)
            self.socket_handler.Send('GET_RUN_NUMBER', self.client_id)
            res = self.socket_handler.Receive('RUN_NUMBER')
            if res:
                self.current_run_id = int(res[1])
                self.run_id.set_markup('Run id: <b>%d</b>' %
                                       self.current_run_id)

            glib.timeout_add(1000, self.Update)
            self.Log('Client connected with id: %d' % self.client_id)
            self.Update()
            if self.acquisition_started and not self.daq_loop_launched:
                #print "Launching the acquisition monitor loop."
                self.DAQLoop()
        except SocketHandler.SocketError:
            print "Failed to bind!"
            return
Пример #34
0
    def next_step(self):
        # We already sent the details, but may still be on the same step.
        # Also, if the user didn't choose to "register now", respect his
        # decision
        if not self.model.register_now or self.wizard.link_request_done:
            return FinishInstallationStep(self.wizard)

        webapi = WebService()
        webapi.link_registration(self.model.name,
                                 self.model.email,
                                 self.model.phone,
                                 callback=lambda r: schedule_in_main_thread(
                                     self._on_response_done, r),
                                 errback=lambda e: schedule_in_main_thread(
                                     self._on_response_error, e))

        self.send_progress.show()
        self.send_progress.set_text(_('Sending...'))
        self.send_progress.set_pulse_step(0.05)
        self.wizard.next_button.set_sensitive(False)
        glib.timeout_add(50, self._pulse)

        # Cancel the request after 30 seconds without a reply
        glib.timeout_add(30000, self._cancel_request)

        # Stay on the same step while sending the details
        return self
Пример #35
0
    def start(self, index):
        '''Start show slide.'''
        # Stop if index same as current one.
        if self.index == index:
            return False
        # Just start slide when stop.
        elif self.stop:
            # Get path.
            self.sourceIndex = self.index
            self.targetIndex = index

            # Get new image.
            self.sourceImage = self.createSlideImage(self.sourceIndex)
            self.targetImage = self.createSlideImage(self.targetIndex)

            # Reset.
            self.stop = False
            self.index = index
            self.ticker = 0
            self.alphaInterval = 1.0 / self.times

            # Change slide item.
            self.updateSlideItem()

            # Start slide.
            glib.timeout_add(self.interval, self.slide)

            return False
Пример #36
0
 def __init__(self, count):
     '''
     Init Count TipWindow
     @param count: the count num, an int num
     '''
     self.count = count
     self.paddingX = 10
     
     self.tipWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
     self.tipWindow.set_skip_taskbar_hint(True)
     self.tipWindow.set_skip_pager_hint(True)
     self.tipWindow.set_keep_above(True)
     self.tipWindow.set_size_request(100, 100)
     self.tipWindow.set_decorated(False)
     self.tipWindow.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse("black"))
     self.tipWindow.set_accept_focus(False)
     #self.tipWindow.set_icon_from_file("../theme/logo/deepin-screenshot.ico")
     self.tipWindow.set_opacity(0.8)
     self.tipWindow.move(SCREEN_X + SCREEN_WIDTH - 200, 34)
     self.tipWindow.connect('expose-event', self.tip_expose)
     self.tipWindow.connect("size-allocate", lambda w, a: updateShape(w, a, 4))
     
     # Create tooltips label.
     self.label = gtk.Label()
     self.label.set_markup("<span foreground='#00AEFF' size='36000'>%d</span>" % (self.count))
     self.label.set_single_line_mode(True) # just one line
     self.align = gtk.Alignment()
     self.align.set(0.5, 0.5, 1.0, 1.0)
     self.align.set_padding(0, 28, self.paddingX, self.paddingX)
     self.align.add(self.label)
     self.tipWindow.add(self.align)
     glib.timeout_add(1000, lambda: self.timeout_handler(self.tipWindow))
     self.tipWindow.show_all()
     
     gtk.main()
 def start(self, index):
     '''Start show slide.'''
     # Stop if index same as current one.
     if self.index == index:
         return False
     # Just start slide when stop.
     elif self.stop:
         # Get path.
         self.sourceIndex = self.index
         self.targetIndex = index
         
         # Get new image.
         self.sourceImage = self.createSlideImage(self.sourceIndex)
         self.targetImage = self.createSlideImage(self.targetIndex)
         
         # Reset.
         self.stop = False
         self.index = index
         self.ticker = 0
         self.alphaInterval = 1.0 / self.times
         
         # Change slide item.
         self.updateSlideItem()
                     
         # Start slide.
         glib.timeout_add(self.interval, self.slide)
         
         return False
Пример #38
0
	def previous_press(self, widget,event, applet):
		if event.button == 1 and self.loadlist_flag == "play":
			glib.timeout_add(1*1000, self.seek, '-4')
			self.ts = True
		elif event.button == 3 :
			applet.emit("button-press-event",event)
			return True
Пример #39
0
    def scanTouchEvents(self):
        for event in pygame.event.get():

            if (event.type is MOUSEBUTTONDOWN):
                pos = pygame.mouse.get_pos()
                # if self.highlighted is not True:
                #     self.highlightButton(pos)
                #print pos
            elif (event.type is MOUSEBUTTONUP):
                pos = pygame.mouse.get_pos()
                #print pos
                #Find which quarter of the screen we're in
                x, y = pos
                if y < 120:
                    if x < 160:
                        self.handlePrevious()
                    else:
                        self.handleNext()
                else:
                    if x < 160:
                        self.handlePlayPause()
                    else:
                        self.handleQuit()

        # re-schedule scan of touch events.
        glib.timeout_add(20, self.scanTouchEvents)
Пример #40
0
    def handleHardware(self, actionString):
        hwSelected = False
        selHw = []
        chkList = functions.getColumnValues(self.tvHardware, 0)
        hwList = functions.getColumnValues(self.tvHardware, 4)
        statList = functions.getColumnValues(self.tvHardware, 5)
        for i in range(len(chkList)):
            if chkList[i]:
                self.log.write(actionString + ' hardware code: ' + hwList[i], 'ddm.handleHardware', 'info')
                selHw.append([hwList[i], statList[i]])
                hwSelected = True

        if hwSelected:
            # Install selected drivers
            self.toggleGuiElements(True)
            # Start saving in a separate thread
            self.log.write('Start driver ' + actionString + ' thread', 'ddm.handleHardware', 'info')
            if actionString == 'install':
                t = DriverInstall(selHw, self.log)
            else:
                t = DriverRemove(selHw, self.log)
            t.start()
            # Run spinner as long as the thread is alive
            self.log.write('Check every 5 seconds if thread is still active', 'ddm.installHardware', 'debug')
            glib.timeout_add(5, self.checkThread, actionString)
        else:
            msg = 'Select a driver to install.'
            MessageDialog('Driver install', msg, gtk.MESSAGE_INFO, self.window).show()
Пример #41
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)

        notificationcls = extension.get_default('notification')
        self.notification = notificationcls(self.session)
Пример #42
0
    def __init__(self):

        super(GandRing, self).__init__()

        self.cap = cv2.VideoCapture(0)
        self.face_cascade = cv2.CascadeClassifier(FACECASCADE)

        self.set_title("G And Ring")
        self.connect("destroy", self.on_destroy)
        self.set_position(gtk.WIN_POS_CENTER)
        self.maximize()
                
        self.darea = gtk.DrawingArea()
        self.darea.connect("expose-event", self.expose)
                
        self.add(self.darea)
        self.show_all()

        self.timer = True
        self.interval = 50
        glib.timeout_add(self.interval, self.on_timer)
     
        self.prevframe = None

        self.egmin, self.esmin = 0,0
        self.egmax, self.esmax = numpy.iinfo(numpy.int16).min, numpy.iinfo(numpy.int16).min
Пример #43
0
	def _on_adjustment_changed(self, adjustment, progress_bar):
		"""
		Callback when an adjustment is changed.
		"""
		upper = adjustment.get_upper()
		lower = adjustment.get_lower()
		value = adjustment.get_value()
		
		if upper - lower != 0:
			# Display the progress bar
			fraction = float(value - lower) / float(upper-lower)
			progress_bar.set_fraction(fraction)
			
			# Alert/show if just started
			if progress_bar not in self.active_bars:
				if self.auto_hide:
					progress_bar.show()
				self.emit("started", progress_bar.get_text())
				self.active_bars.add(progress_bar)
		else:
			# The progress bar has finished, show it as 100% then hide it.
			
			# Set it to 100% if auto-hiding, otherwise just set it to 0 now as
			# otherwise it looks as if the process is still finishing off.
			if self.auto_hide:
				progress_bar.set_fraction(1)
			else:
				progress_bar.set_fraction(0)
			
			# Hide it later
			glib.timeout_add(int(self.loiter*1000),
			                 self._delayed_remove, adjustment, progress_bar)
Пример #44
0
    def timeout(self, data=None):
        """Handle timeout."""

        # 1: Terminate?
        if not self.running:
            return False

        # 2: Process?
        try:
            ntime = tod.tod(u'now')
            ntod = ntime.truncate(0)
            if ntime >= self.nc.truncate(1):
                self.tod = ntod
                self.nc += tod.ONE
                self.process_timeout()
            else:
                self.log.debug(u'Timeout called early: ' + ntime.rawtime())
                # no need to advance, desired timeout not yet reached
        except Exception as e:
            self.log.error(u'Timeout: ' + unicode(e))

        # 3: Re-Schedule
        tt = tod.tod(u'now')+tod.tod(u'0.01')
        while self.nc < tt:	# ensure interval is positive
            if tod.MAX - tt < tod.ONE:
                self.log.debug(u'Midnight rollover.')
                break
            self.log.debug(u'May have missed an interval, catching up.')
            self.nc += tod.ONE	# 0.01 allows for processing delay
        ival = int(1000.0 * float((self.nc - tod.tod(u'now')).timeval))
        glib.timeout_add(ival, self.timeout)

        # 4: Return False
        return False	# must return False
Пример #45
0
    def __init__(self, motors, video):
        self.motors = motors
        self.video = video
        self.ip_box = None
        self.keystate = {k: False for k in ["w", "s", "a", "d"]}

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("WiFi Tank Remote")
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)

        layout = gtk.VBox(False, 5)

        self.connect_box = self.setup_connection_box()
        layout.add(self.connect_box)

        self.direction_pad = self.setup_direction_pad()
        layout.add(self.direction_pad)

        self.vid_img = self.setup_video_image()
        layout.add(self.vid_img)

        layout.show()
        self.window.add(layout)

        self.motors.connect("connected", self.on_connection_state_change)

        self.window.connect("key-press-event", self.on_key_down)
        self.window.connect("key-release-event", self.on_key_up)
        self.window.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK)

        self.window.show()

        glib.timeout_add(100, self.tick)
Пример #46
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)
Пример #47
0
 def increment_level(self):
     """Increment level by 1, and change the label. Also call make_timer
     and hook up the resulting function with glib.timeout_add, to be
     called  every 2.0/(level+3) seconds."""
     self.level += 1
     styled_set_label_text(self.level_display, "Level:  " + str(self.level))
     glib.timeout_add(2000 // (self.level + 3), self.make_timer(self.level))
    def hoverIcon(self, *args):
        '''Hover icon.'''
        self.ticker = self.times
        if self.tooltipWindow == None:
            self.tooltipWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.tooltipWindow.set_decorated(False)
            self.tooltipWindow.set_default_size(self.TOOLTIP_WIDTH, self.TOOLTIP_HEIGHT)
            self.tooltipWindow.connect("size-allocate", lambda w, a: updateShape(w, a, 4))
            
            self.tooltipEventBox = gtk.EventBox()
            self.tooltipEventBox.connect("button-press-event", lambda w, e: self.showSoftwareCenter())
            self.tooltipWindow.add(self.tooltipEventBox)
            
            glib.timeout_add(self.interval, self.redraw)

        (iconScreen, iconRect, orientation) = self.trayIcon.get_geometry()
        (screenWidth, screenHeight) = getScreenSize(self.trayIcon)
        tooltipX = iconRect.x - iconRect.width
        if iconRect.y + iconRect.height > screenHeight:
            tooltipY = iconRect.y - self.TOOLTIP_HEIGHT - self.TOOLTIP_OFFSET_Y 
        else:
            tooltipY = iconRect.y + iconRect.height + self.TOOLTIP_OFFSET_Y
        self.tooltipWindow.set_opacity(0.9)
        self.tooltipWindow.move(tooltipX, tooltipY)
        self.tooltipWindow.queue_draw()
        self.tooltipWindow.show_all()
 def __init__(self, gtkbuilder):
     self.builder = gtkbuilder
     self.liststore = gtkbuilder.get_object("liststore_comports")
     self.combobox = gtkbuilder.get_object("combobox1")
     self.__updateComPorts()
     glib.timeout_add(500, self.__updateComPorts)
     self.ctx = barobo.BaroboCtx()
Пример #50
0
    def __init__(self):
        gtk.Window.__init__(self)
        self.set_name('SplashWindow')
        self.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)
        self.resize(WIDTH, HEIGHT)
        # Ubuntu has backported the 3.0 has-resize-grip property,
        # disable it as it doesn't make sense for splash screens
        if hasattr(self.props, 'has_resize_grip'):
            self.props.has_resize_grip = False
        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.add(frame)

        darea = gtk.DrawingArea()
        try:
            darea.connect("expose-event", self.expose)
        except TypeError:
            darea.connect("draw", self.draw)
        frame.add(darea)

        self.show_all()
        pixbuf_data = environ.get_resource_string("stoq", "pixmaps", "splash.png")
        self._pixbuf = pixbuf_from_string(pixbuf_data)

        glib.timeout_add(_WINDOW_TIMEOUT, self._hide_splash_timeout)
Пример #51
0
    def on_quit(self, *args):
        if self._model.get_clear_entry():
            self._view.clear_all()
        window = self._view.get_toplevel()

        if self._model.get_ui_name() == deskbar.WINDOW_UI_NAME:
            x, y = window.get_position()
            self._model.set_window_x(x)
            self._model.set_window_y(y)

        if len(args) == 2:
            event = args[1]
            if hasattr(event, 'type'):
                if event.type == gtk.gdk.FOCUS_CHANGE:
                    # If the keybinding is pressed to close the window
                    # we receive a focus-out-event first. Now we close
                    # the window and the keybinding handler thinks it
                    # should show the window.
                    # Settings this flag will tell us
                    # that we saw a focus-out-event recently
                    self._focus_out = True
                    glib.timeout_add(250, self._reset_focus_out)

        window.hide()

        return True
Пример #52
0
def doFilterProcess(item):
    _isEventQueueRecursing = isEventQueueRecursing()
    """
  Perform the actual filtering of the
  [old] clipboard text contents (`item`)
  into [new] filtered text (`filtStr`)
  """
    filtStr = filterWithRegex(item)
    """
  Save the filtered result as the
  latest item in glipper history
  note: if it so happens that filtStr == get_history_item(0)
  then one item (extra) is deleted from history list!
  do a check first
  """
    gho = get_glipper_history()
    #~ print "doFilterProcess:",len(gho.history)
    #~ print get_history_item(0)
    #~ print filtStr
    if not (filtStr == get_history_item(0)):
        set_history_item(0, filtStr)
        """
    must emit `changed`, so the displayed
    `glipper` menu reflects the state of
    history after change
    """
        try:
            gho.emit('changed', gho.history)
        except:
            pass
        """
    up to this point, the history item in Glipper's menu is changed;
    but the clipboard still has original contents, which will be
    pasted on Ctrl-V. Then you must open Glipper menu again, and
    click on the (now modified) history item, to replace the clipboard
    contents with the filtered string, so it can be pasted!
    get_glipper_clipboards() should be used:
    API: /usr/lib/pymodules/python2.7/glipper/Clipboards.py
     can see it in action in on_menu_item_activate from:
     /usr/lib/pymodules/python2.7/glipper/AppIndicator.py
    so re-set the filtered string, to be the content of clipboard(s)?
    but this sets recursion going (print "AAAAA" here would be
    continously output to terminal, as a sign of endless loop)!
    with proper event queue checking - no more need for
    "emit_stop_by_name" (which doesn't work here) ...

    See first whether the Preferences are set to "Immediately
    update clipboard with filtered contents"
    """
        if should_update_immediately:
            """
      so check first if events in queue indicate a recursion loop;
      and if a loop is not yet started - only then set the clipboard
      itself with the filtered text.
      Since this check is now already performed above, we can only
      come to this part when not(_isEventQueueRecursing) is True;
      so it is unnecessarry - but keeping it for development history
      """
            if not (_isEventQueueRecursing):
                glib.timeout_add(250, timer_settext_cb, filtStr)
Пример #53
0
 def no_connection(self):
   if self.reconnect is None:
     print 'Auto reconnect disabled, quitting...'
     self.main_loop.quit()
   else:
     print 'Will retry every %d seconds' % self.reconnect
     glib.timeout_add(self.reconnect * 1000, self._connect)
Пример #54
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)
Пример #55
0
    def next_step(self):
        # We already sent the details, but may still be on the same step.
        # Also, if the user didn't choose to "register now", respect his
        # decision
        if not self.model.register_now or self.wizard.link_request_done:
            return FinishInstallationStep(self.wizard)

        webapi = WebService()
        response = webapi.link_registration(
            self.model.name, self.model.email, self.model.phone)
        response.addCallback(self._on_response_done)
        response.addErrback(self._on_response_error)

        # FIXME: This is a hack, remove it when we can avoid
        #        calling dialog.run()
        if not reactor.running:
            reactor.run()

        self.send_progress.show()
        self.send_progress.set_text(_('Sending...'))
        self.send_progress.set_pulse_step(0.05)
        self.wizard.next_button.set_sensitive(False)
        glib.timeout_add(50, self._pulse)

        # Cancel the request after 30 seconds without a reply
        glib.timeout_add(30000, self._cancel_request)

        # Stay on the same step while sending the details
        return self
Пример #56
0
    def on_location_changed(self, monitor, gfile, other_gfile, event):
        """
            Updates the library on changes of the location
        """
        
        if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
            self.__process_change_queue(gfile)
        elif event == gio.FILE_MONITOR_EVENT_CREATED or \
             event == gio.FILE_MONITOR_EVENT_CHANGED:
            
            # Enqueue tracks retrieval
            if gfile not in self.__queue:
                self.__queue[gfile] = True
            
                # File monitor only emits the DONE_HINT when using inotify,
                # and only on single files. Give it some time, but don't 
                # lose the change notification
                glib.timeout_add(500, self.__process_change_queue, gfile)
            
            # Set up new monitor if directory
            fileinfo = gfile.query_info('standard::type')

            if fileinfo.get_file_type() == gio.FILE_TYPE_DIRECTORY and \
               gfile not in self.__monitors:
                
                for directory in common.walk_directories(gfile):
                    monitor = directory.monitor_directory()
                    monitor.connect('changed', self.on_location_changed)
                    self.__monitors[directory] = monitor

                    self.emit('location-added', directory)

        elif event == gio.FILE_MONITOR_EVENT_DELETED:
            removed_tracks = []

            track = trax.Track(gfile.get_uri())

            if track in self.__library.collection:
                # Deleted file was a regular track
                removed_tracks += [track]
            else:
                # Deleted file was most likely a directory
                for track in self.__library.collection:
                    track_gfile = gio.File(track.get_loc_for_io())

                    if track_gfile.has_prefix(gfile):
                        removed_tracks += [track]

            self.__library.collection.remove_tracks(removed_tracks)

            # Remove obsolete monitors
            removed_directories = [d for d in self.__monitors \
                if d == gfile or d.has_prefix(gfile)]

            for directory in removed_directories:
                self.__monitors[directory].cancel()
                del self.__monitors[directory]
                
                self.emit('location-removed', directory)