Example #1
0
def fetch_opml(url):
    try:
        outline = opml.parse(url)
    except IOError:
        print_d("Failed opening OPML %s" % url)
        return []
    GObject.idle_add(lambda: update_feeds([x.xmlUrl for x in outline]))
    def set_blinking(self, blinking):
        self.blinking = blinking

        if blinking and self.tick_id == 0:
            GObject.idle_add(self._blink_idle)
        elif self.tick_id > 0:
            self.stop_blinking = True
 def find_books(self, search_text):
     if _NEW_TOOLBAR_SUPPORT:
         self.enable_button(False)
     else:
         self._books_toolbar.enable_button(False)
     self.clear_downloaded_bytes()
     textbuffer = self.textview.get_buffer()
     textbuffer.set_text(_('Performing lookup, please wait') + '...')
     self.book_selected = False
     self.ls.clear()
     search_tuple = search_text.lower().split()
     if len(search_tuple) == 0:
         self._alert(_('Error'), _('You must enter at least one search word.'))
         if _NEW_TOOLBAR_SUPPORT:
             self.search_entry.grab_focus()
         else:
             self._books_toolbar.search_entry.grab_focus()
         return
     FL = urllib.quote('fl[]')
     SORT = urllib.quote('sort[]')
     self.search_url = 'http://www.archive.org/advancedsearch.php?q=' +  \
         urllib.quote('(title:(' + search_text.lower() + ') OR creator:(' + search_text.lower() +')) AND format:(DJVU)')
     self.search_url += '&' + FL + '=creator&' + FL + '=description&' + FL + '=format&' + FL + '=identifier&'  \
         + FL + '=language'
     self.search_url += '&' + FL +  '=publisher&' + FL + '=subject&' + FL + '=title&' + FL + '=volume'
     self.search_url += '&' + SORT + '=title&' + SORT + '&' + SORT + '=&rows=500&save=yes&fmt=csv&xmlsearch=Search'
     GObject.idle_add(self.download_csv,  self.search_url)
Example #4
0
    def buffer_icons(self):

        def buffer_icons():
            #~ print "Buffering icons ..."
            #t0 = GObject.get_current_time()
            if self.current_matches is None:
                return False
            db = self.db.xapiandb
            for m in self.current_matches:
                doc = db.get_document(m.docid)

                # calling get_icon is enough to cache the icon
                self.get_icon(doc)

                while Gtk.events_pending():
                    Gtk.main_iteration()

            #~ import sys
            #~ t_lapsed = round(GObject.get_current_time() - t0, 3)
            #~ print "Appstore buffered icons in %s seconds" % t_lapsed
            #from softwarecenter.utils import get_nice_size
            #~ cache_size = get_nice_size(sys.getsizeof(_app_icon_cache))
            #~ print "Number of icons in cache: %s consuming: %sb" % (
                #~ len(_app_icon_cache), cache_size)
            return False    # remove from sources on completion

        if self.current_matches is not None:
            GObject.idle_add(buffer_icons)
    def on_realized(self, widget, data=None):
        if self.blinking and self.tick_id == 0:
            GObject.idle_add(self._blink_idle)

        trackers.con_tracker_get().disconnect(self,
                                              "realize",
                                              self.on_realized)
Example #6
0
    def __init__(self, window):
        Gtk.Dialog.__init__(self, _('Edit archive'), window, Gtk.DialogFlags.MODAL,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
        self.kill = False # Dialog is killed.
        self.file_handler = window.file_handler
        self._window = window
        self._save_button = self.add_button(Gtk.STOCK_SAVE_AS, Gtk.ResponseType.OK)
        # There is no stock response for "import", but by using
        # RESPONSE_HELP we automatically get the button placed at the left.
        self._import_button = self.add_button(_('Import'), Gtk.ResponseType.HELP)
        self._import_button.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_ADD,
            Gtk.IconSize.BUTTON))
        self.set_border_width(4)
        self.resize(min(Gdk.Screen.get_default().get_width() - 50, 750),
            min(Gdk.Screen.get_default().get_height() - 50, 600))
        self.connect('response', self._response)
        
        self._image_area = _ImageArea(self)
        self._other_area = _OtherArea(self)

        notebook = Gtk.Notebook()
        notebook.set_border_width(6)
        notebook.append_page(self._image_area, Gtk.Label(label=_('Images')))
        notebook.append_page(self._other_area, Gtk.Label(label=_('Other files')))
        self.vbox.pack_start(notebook, True, True, 0)
        self.show_all()
        GObject.idle_add(self._load_original_files)
Example #7
0
 def checkFiles( self ):
     for monitored in self.monitoredFiles:
         if monitored.hasChanged():
             if monitored.args:
                 GObject.idle_add( monitored.callback, monitored.args )
             else:
                 GObject.idle_add( monitored.callback )
Example #8
0
	def __init__(self):
		#self.radio = tea5767()
		self.player = player()
		self.load = False
		self.defaullt = "/data/media/Music"
		self.config = configparser.ConfigParser()
		self.config.read('config.ini')
		interface = gtk.Builder()
		interface.add_from_file('./interface/interface.glade')
		self.volume = interface.get_object("volume")
		self.progression = interface.get_object("progression")
		self.music = interface.get_object("music")
		self.artiste = interface.get_object("artiste")
		self.cover = interface.get_object("pochette")
		self.mode = interface.get_object("mode")
		self.freq = interface.get_object("scale1")
		self.deroul = interface.get_object("liststore1") 
		self.folder = interface.get_object("filechooserbutton1")
		self.tab = interface.get_object('notebook1')
		self.on_notebook1_switch_page(self.tab, None,self.tab.get_current_page())
		self.fullScreen = interface.get_object("main")
		interface.connect_signals(self)
		gobject.idle_add(self.test)
		if True:#(self.config["player"]["last"] != self.defaullt)
			time.sleep(2)
			self.player.new_folder(self.defaullt)
			self.config["player"]["last"] = self.defaullt
			with open("./config.ini", 'w') as configfile:    # save
				self.config.write(configfile)
Example #9
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.connected = False
        
        
        # check is ONECONF_NET_CONNECTED is in the environment variables
        # if so force the network status to be connected or disconnected
        if "ONECONF_NET_CONNECTED" in os.environ:
            if os.environ["ONECONF_NET_CONNECTED"].lower() == 'true':
                GObject.idle_add(self._on_connection_state_changed, self.NM_STATE_CONNECTED_LOCAL)
                LOG.warn('forced netstate into connected mode...')
            else:
                GObject.idle_add(self._on_connection_state_changed, self.NM_STATE_DISCONNECTED)
                LOG.warn('forced netstate into disconnected mode...')
            return
        try:
            bus = dbus.SystemBus()
            nm = bus.get_object('org.freedesktop.NetworkManager',
                                '/org/freedesktop/NetworkManager')
            nm.connect_to_signal("StateChanged", self._on_connection_state_changed)
            network_state = nm.state(dbus_interface='org.freedesktop.NetworkManager')
            self._on_connection_state_changed(network_state)

        except Exception as e:
            LOG.warn("failed to init network state watcher '%s'" % e)
            self._on_connection_state_changed(self.NM_STATE_UNKNOWN)
Example #10
0
	def fullscreen(self):
		""" Makes the window fullscreen. """
		
		if not self.is_fullscreen:
			GObject.idle_add(self.main.set_resizable, True)
			GObject.idle_add(self.main.fullscreen)
			self.is_fullscreen = True
Example #11
0
	def unfullscreen(self):
		""" Unfullscreens the window """
		
		if self.is_fullscreen:
			GObject.idle_add(self.main.set_resizable, False)
			GObject.idle_add(self.main.unfullscreen)
			self.is_fullscreen = False
Example #12
0
	def on_changed(self, *args):
		text = self.get_text().strip()[:self.get_max_length()]
		new_pos = 0
		new_text = ''
		for c in text:
			if c in '0123456789-+':
				print('C:',c,new_text)
				if new_pos != 0 and c in ('-','+'):
					continue
				
				new_text += c
				new_pos += 1

		if new_text:
			cur_pos = self.get_position()
			if new_pos - cur_pos > 2:
				new_pos = cur_pos 
			self.handler_block_by_func(self.on_changed)
			print('new-text:',new_text)
			if len(new_text) > 1 or not new_text[0] in ('-','+'):
				if int(new_text) > self._max:
					new_text = str(self._max)

			if len(new_text) > 1 or not new_text[0] in ('-','+'):
				if int(new_text) < self._min:
					new_text = str(self._min)
			
			self.set_text(new_text)
			self.handler_unblock_by_func(self.on_changed)
			GObject.idle_add(self.set_position, new_pos)
		else:
			self.set_text(new_text)
		
		self.stop_emission("changed")
Example #13
0
	def on_changed(self, *args):
		text = self.get_text().strip()[:self.get_max_length()]
		new_pos = 0
		new_text = ''
		for c in text:
			if c in '0123456789:+-':
				if new_pos in (2,5):
					if c != ':':
						new_text += ':' + c
						new_pos += 1
					else:
							new_text += c
				else:
					if new_pos == 8:
						if c in ('-','+'):
							new_text += c
					else:
						if c != ':':
							new_text += c
					
				new_pos += 1
		if new_text:
			cur_pos = self.get_position()
			if new_pos - cur_pos > 2:
				new_pos = cur_pos 
			self.handler_block_by_func(self.on_changed)
			self.set_text(new_text)
			self.handler_unblock_by_func(self.on_changed)
			GObject.idle_add(self.set_position, new_pos)
		else:
			self.set_text(new_text)
		
		self.stop_emission("changed")
Example #14
0
    def __init__(self, handle):
        super(PhysicsActivity, self).__init__(handle)
        self.metadata['mime_type'] = 'application/x-physics-activity'
        self.add_events(Gdk.EventMask.ALL_EVENTS_MASK |
                        Gdk.EventMask.VISIBILITY_NOTIFY_MASK)

        self.connect('visibility-notify-event', self._focus_event)
        self.connect('window-state-event', self._window_event)

        self.game_canvas = sugargame.canvas.PygameCanvas(self)
        self.game = physics.main(self)

        self.preview = None
        self._sample_window = None

        self._fixed = Gtk.Fixed()
        self._fixed.put(self.game_canvas, 0, 0)

        w = Gdk.Screen.width()
        h = Gdk.Screen.height() - 2 * GRID_CELL_SIZE

        self.game_canvas.set_size_request(w, h)

        self._constructors = {}
        self.build_toolbar()

        self.set_canvas(self._fixed)
        Gdk.Screen.get_default().connect('size-changed',
                                         self.__configure_cb)

        logging.debug(os.path.join(
                      activity.get_activity_root(), 'data', 'data'))
        self.game_canvas.run_pygame(self.game.run)
        GObject.idle_add(self._setup_sharing)
        self.show_all()
Example #15
0
 def update_progress(self, fail=False, done=False, pulse=False, total=0,current=0,message=""):
     if(pulse):
         Gdk.threads_enter()
         self.label.set_label(message)
         Gdk.threads_leave()
         self.do_progress_pulse(message)
         return
     if(done):
         # cool, finished :D
         self.should_pulse = False
         self.done = done
         Gdk.threads_enter()
         self.progress.set_fraction(1)
         self.label.set_label(message)
         GObject.idle_add(self.go_quit)
         Gdk.threads_leave()
         return
     self.should_pulse = False
     _total = float(total)
     _current = float(current)
     pct = float(_current/_total)
     szPct = int(pct)
     # thread block
     Gdk.threads_enter()
     self.progress.set_fraction(pct)
     self.label.set_label(message)
     Gdk.threads_leave()
Example #16
0
File: usi.py Project: gbtami/gshogi
    def start_ponder(self, pondermove, movelist, cmove):

        startpos = gv.gshogi.get_startpos()

        # if not startpos must be sfen
        if startpos != "startpos":
            startpos = "sfen " + startpos

        ml = ""
        for move in movelist:
            ml = ml + move + " "
        # if ml == "":
        #    print "error empty movelist in ponder in usi.py"
        #    return

        ml = ml.strip()
        ml = ml + " " + cmove + " " + pondermove
        ml = ml.strip()

        # create the position string with the ponder move added
        b = "position " + startpos + " moves " + ml + "\n"

        # Send the board position to the engine
        self.command(b)

        pondercmd = "go ponder" + self.gocmnd[2:]
        self.command(pondercmd + "\n")

        # clear the engine output window ready for next move
        GObject.idle_add(
            self.engine_output.clear, self.side,
            self.get_running_engine().strip())

        return
    def _save_selected_subtitle (self):
        cursor = Gdk.Cursor.new (Gdk.CursorType.WATCH)
        self._dialog.get_window ().set_cursor (cursor)

        model, rows = self._tree_view.get_selection ().get_selected_rows ()
        if rows:
            subtitle_iter = model.get_iter (rows[0])
            subtitle_id = model.get_value (subtitle_iter, 3)
            subtitle_format = model.get_value (subtitle_iter, 1)

            bpath = self._cache_subtitles_dir()

            directory = Gio.file_new_for_path (bpath)
            try:
                directory.make_directory_with_parents (None);
            except:
                pass

            thread = DownloadThread (self._model, subtitle_id)
            thread.start ()
            GObject.idle_add (self._save_subtitles, thread, subtitle_format)

            self._progress.set_text (_(u'Downloading the subtitles…'))
            GObject.timeout_add (350, self._progress_bar_increment, thread)
        else:
            #warn user!
            pass
Example #18
0
 def on_tab_switch(self, notebook, page,  page_num,  data=None):
     """Do the real work for a tab switch"""
     tabs_last_active_term = data['tabs_last_active_term']
     if tabs_last_active_term:
         term = self.terminator.find_terminal_by_uuid(tabs_last_active_term.urn)
         GObject.idle_add(term.ensure_visible_and_focussed)
     return True
Example #19
0
File: usi.py Project: gbtami/gshogi
 def read_stdout(self):
     while True:
         try:
             e = ("<-" + self.side + "(" +
                  self.get_running_engine().strip() + "):")
             self.p.stdout.flush()
             line = self.p.stdout.readline()
             if line == "":
                 if gv.verbose:
                     print e + "eof reached"
                 if gv.verbose:
                     print e + "stderr:", self.p.stderr.read()
                 break
             line = line.strip()
             if gv.verbose or gv.verbose_usi:
                 print e + line
             GObject.idle_add(self.engine_debug.add_to_log, e+line)
             if line.startswith("info"):
                 GObject.idle_add(
                     self.engine_output.add_to_log, self.side,
                     self.get_running_engine().strip(), line)
             self.op.append(line)
         except Exception, e:
             # line = e + "error"
             print "subprocess error in usi.py read_stdout:", e
Example #20
0
 def wait_idle(self):
     with self.condition:
         def notify():
             with self.condition:
                 self.condition.notify()
         GObject.idle_add(notify)
         self.condition.wait()
 def isRedundant(self, path):
     if not self.symlinks.get_active() or not os.path.islink(path) or not os.path.isdir(path):
         return False
     else:
         if os.path.realpath(path) in self.dirs:
             GObject.idle_add(self.setStatusText, "Skipping " + path + " - direcotry already searched")
             return True
Example #22
0
	def updateText(self, selection, filesize):
		if selection:
			self.window.set_icon(selection[0])
			self.text = htmlentitydecode(selection[1]) + "\n" + selection[2] + "\n"
			if selection[3]:
				self.text += "Length: " + selection[3] + "\n"
			if selection[4]:
				self.text += "This is a " + selection[4] + " file.\n"
			if filesize:
				self.text += "File size: " + filesize + "\n"
			if selection[5]:
				self.text += "Comment:\n" + selection[5] + "\n"
			if selection[6]:
				self.text += "Released:\n" + selection[6] + "\n"
			if selection[7]:
				self.text += "Modified:\n" + selection[7] + "\n"
			if selection[8]:
				self.text += "This links to:\n" + selection[8] + "\n\n"
			if selection[9]:
				self.text += "This file is at:\n" +selection[9] + "\n\n"
			if selection[10]:
				self.text += "Price:\n" + selection[10] + "\n\n"
			if selection[11]:
				self.text += "id:" + selection[11]
			GObject.idle_add(self.settext, self.text);
Example #23
0
    def update(self):

        # update liststore
        self.liststore.clear()
        self.liststore.append(("0.", _("Start Pos"), " "))
        mvstr = engine.getmovelist()

        if mvstr != "":
            mlst = mvstr.split(",")
            moveno = 1
            for m in mlst:

                (capture, ispromoted, move) = m.split(";")

                if move.find("*") == -1:
                    m1 = move[0:3]
                    m2 = move[3:]
                    move = m1 + capture + m2
                    if ispromoted == "+":
                        move = "+" + move
                comment = self.comments.get_comment(moveno)
                if comment != "":
                    cind = "..."
                else:
                    cind = " "
                e = str(moveno) + ".", move, cind
                self.liststore.append(e)
                moveno += 1

        GObject.idle_add(self.scroll_to_end)
Example #24
0
 def clicked(self, key):
     '''
         This function is called in response to a menu_item click.
     Fire away.
     '''
     x = self.services[key]
     GObject.idle_add(self.emit, "connect", (x.name, x.address, x.port, x))
Example #25
0
 def start(self):
     """Starts the Clutter main event loop and sets our kernel startup routine.
     """
     # Register our function to initiate the kernel and start Clutter
     GObject.idle_add(self._wire_kernel)
     Clutter.init([])
     Clutter.main()
Example #26
0
 def __key_press_event(self, widget, event):
     """
     Tabulador Inteligente.
     """
     
     if event.keyval == 65421:
         buffer = self.get_buffer()
         
         textmark = buffer.get_insert()
         textiter = buffer.get_iter_at_mark(textmark)
         
         id = textiter.get_line()
         
         line_iter = buffer.get_iter_at_line(id)
         chars = line_iter.get_chars_in_line()
         
         if chars > 3:
             ### Ultimo caracter.
             start_iter = buffer.get_iter_at_line_offset(id, chars-2)
             end_iter = buffer.get_iter_at_line_offset(id, chars-1)
             
             texto = buffer.get_text(start_iter, end_iter, True)
             
             if texto == ":":
                 ### Tola la linea.
                 line_end_iter = buffer.get_iter_at_line_offset(id, chars-1)
                 texto = buffer.get_text(line_iter, line_end_iter, True)
                 
                 tabs = 0
                 if texto.startswith(self.tab):
                     tabs = len(texto.split(self.tab))-1
                 
                 GObject.idle_add(self.__forzar_identacion, tabs+1)
Example #27
0
 def list_periodic_refresher():
     while True:
         # Trying to update the GTK GUI from a thread causes
         # a segmentation fault - this is the proper way to do it
         if self.in_list_mode:
             GObject.idle_add(self.refresh_list)
         sleep(15)
Example #28
0
def _button_release_cb(win, event, sw):
    if sw.press == None:
        return True
    for i in range (0,4):
        if sw.press == sw.buttons_off[i].spr:
            sw.buttons_on[i].draw_sprite(1500)
            GObject.idle_add(__play_sound_cb, sw.sound_files[i], sw.sound)
            GObject.timeout_add(500,sw.buttons_on[i].spr.hide)
            if sw.playpushed is False:
                sw.press = None
                return
            if sw.seq[sw.counter] == i: # correct reponse
                sw.counter += 1
                if sw.counter == sw.level*2:
                    GObject.timeout_add(1000, _dance, sw, [i], 10, 0)
                    sw.counter = 0
                    sw.level += 1
                    sw.activity.level_label.set_text(
                        "%s %d" % (_("Level"),sw.level))
                    if sw.level*2 < len(sw.seq):
                        GObject.timeout_add(3000, play_the_game, sw)
                    else: # game over
                        GObject.timeout_add(2000, _flash, sw, 7, True)
                        sw.playpushed = False
                        sw.level = 1
                        sw.seq = gen_seq(30)
                        sw.activity.level_label.set_text(
                            "%s %d" % (_("Level"),sw.level))
            else: # incorrect response
                _all_gone(sw)
                GObject.timeout_add(1000, _all_off, sw)
                sw.counter = 0
    sw.press = None
Example #29
0
    def start_profiling_cb(self, action):
        if getattr(self, 'profiler_active', False):
            self.profiler_active = False
            return

        def doit():
            import cProfile
            profile = cProfile.Profile()

            self.profiler_active = True
            logger.info('--- GUI Profiling starts ---')
            while self.profiler_active:
                profile.runcall(Gtk.main_iteration_do, False)
                if not Gtk.events_pending():
                    time.sleep(0.050) # ugly trick to remove "user does nothing" from profile
            logger.info('--- GUI Profiling ends ---')

            profile.dump_stats('profile_fromgui.pstats')
            logger.debug('profile written to mypaint_profile.pstats')
            if os.path.exists("profile_fromgui.png"):
                os.unlink("profile_fromgui.png")
            os.system('gprof2dot.py -f pstats profile_fromgui.pstats | dot -Tpng -o profile_fromgui.png')
            if os.path.exists("profile_fromgui.png"):
                os.system('xdg-open profile_fromgui.png &')

        GObject.idle_add(doit)
Example #30
0
 def deferred_set_rough_geometry_hints(self):
     # no parameters are used in set_rough_geometry_hints, so we can
     # use the set_rough_geometry_hints
     if self.pending_set_rough_geometry_hint == True:
         return
     self.pending_set_rough_geometry_hint = True
     GObject.idle_add(self.do_deferred_set_rough_geometry_hints)
Example #31
0
 def update_object():
     if event.obj:
         GObject.idle_add(self.hosts_sidebar.update_object, event.obj)
         host_count, service_count, vuln_count = self.update_counts()
         GObject.idle_add(self.statusbar.update_ws_info, host_count,
                          service_count, vuln_count)
Example #32
0
    def _merge_cache_info(self, cache_installed, collect_type):
        self._resolve_id_for_collection(collect_type)
        collect_install = cache_installed[collect_type]
        collect_online = self.cache_object[collect_type]
        cache_folder = self.get_cache_folder(collect_type)
        used_thumbs = []
        for pkg_id in collect_install:
            if not pkg_id in collect_online:
                collect_online[pkg_id] = collect_install[pkg_id]
            else:
                data_install = collect_install[pkg_id]
                data_online = collect_online[pkg_id]
                for key in data_install:
                    if not key in data_online:
                        data_online[key] = data_install[key]
                data_online["hide-configuration"] = data_install[
                    "hide-configuration"]
                data_online["settings-type"] = data_install["settings-type"]
                data_online["ext-setting-app"] = data_install[
                    "ext-setting-app"]
                data_online["schema-file"] = data_install["schema-file"]
                data_online["installed-folder"] = data_install[
                    "installed-folder"]
                data_online["install-edited"] = data_install["install-edited"]
                data_online["max-instances"] = data_install["max-instances"]
                if data_install["icon"]:
                    data_online["icon"] = data_install["icon"]
        for pkg_id in collect_online:
            data_online = collect_online[pkg_id]
            try:
                data_online["score"] = int(data_online["score"])
            except Exception:
                data_online["score"] = 0
            try:
                data_online["max-instances"] = int(
                    data_online["max-instances"])
            except Exception:
                data_online["max-instances"] = 1
            try:
                data_online["spices-show"] = "'%s/%ss/view/%s'" % (
                    URL_SPICES_HOME, collect_type, data_online["spices-id"])
            except KeyError:
                data_online["spices-show"] = ""
            except ValueError:
                data_online["spices-show"] = ""
            self._fix_last_edited(data_online)
            data_online["uuid"] = str(pkg_id)
            icon_path = ""
            if data_online["icon-filename"]:
                icon_basename = data_online["icon-filename"]
                used_thumbs.append(icon_basename)
                icon_path = os.path.join(cache_folder, icon_basename)
            if not pkg_id in collect_install:
                if icon_path:
                    data_online["icon"] = icon_path
                data_online["settings-type"] = SETTING_TYPE_NONE
                data_online["ext-setting-app"] = ""
                data_online["schema-file"] = ""
                data_online["installed-folder"] = ""
                data_online["collection"] = collect_type
                data_online["install-edited"] = -1
                data_online["max-instances"] = 1
                data_online["installed-type"] = 0
            else:
                can_update = data_online[
                    "install-edited"] != -1 and data_online[
                        "install-edited"] < data_online["last-edited"]
                if can_update:
                    data_online["installed-type"] = 2
                else:
                    data_online["installed-type"] = 1
            if not data_online["icon"]:
                data_online["icon"] = "cs-%ss" % (collect_type)

            if data_online["install-edited"] > 0:
                data_online["install-ver"] = datetime.datetime.fromtimestamp(
                    data_online["install-edited"]).strftime(
                        "%Y-%m-%d\n%H:%M:%S")
            else:
                data_online["install-ver"] = ""
            if data_online["last-edited"] > 0:
                data_online["last-ver"] = datetime.datetime.fromtimestamp(
                    data_online["last-edited"]).strftime("%Y-%m-%d\n%H:%M:%S")
            else:
                data_online["last-ver"] = ""

        GObject.idle_add(self._cleanup_obsolete_thumbs, used_thumbs,
                         cache_folder)
Example #33
0
def get_regcode_thread(window):
    safe_id = get_safe_id()
    if get_regcode(safe_id):
        GObject.idle_add(update_window, window)
Example #34
0
def _calculate_apt_changes(task):
    global _apt_cache_lock
    apt_cache = get_apt_cache()

    with _apt_cache_lock:
        apt_cache.clear()

        print("MintInstall: Calculating changes required for APT package: %s" %
              task.pkginfo.name)

        pkginfo = task.pkginfo

        aptpkg = apt_cache[pkginfo.name]

        try:
            if aptpkg.is_installed:
                aptpkg.mark_delete(True, True)
            else:
                aptpkg.mark_install()
        except:
            if aptpkg.name not in BROKEN_PACKAGES:
                BROKEN_PACKAGES.append(aptpkg.name)

        changes = apt_cache.get_changes()

        for pkg in changes:
            if pkg.marked_install:
                task.to_install.append(pkg.name)
            elif pkg.marked_upgrade:
                task.to_update.append(pkg.name)
            elif pkg.marked_delete:
                task.to_remove.append(pkg.name)

        task.download_size = apt_cache.required_download

        space = apt_cache.required_space

        if space < 0:
            task.freed_size = space * -1
            task.install_size = 0
        else:
            task.freed_size = 0
            task.install_size = space

        for pkg_name in task.to_remove:
            if _is_critical_package(apt_cache[pkg_name]):
                print("MintInstall: apt - cannot remove critical package: %s" %
                      pkg_name)
                task.info_ready_status = task.STATUS_FORBIDDEN

        if aptpkg.name in BROKEN_PACKAGES:
            print(
                "MintInstall: apt- cannot execute task, package is broken: %s"
                % aptpkg.name)
            task.info_ready_status = task.STATUS_BROKEN

        print("For install:", task.to_install)
        print("For removal:", task.to_remove)
        print("For upgrade:", task.to_update)

        if task.info_ready_status not in (task.STATUS_FORBIDDEN,
                                          task.STATUS_BROKEN):
            task.info_ready_status = task.STATUS_OK
            task.execute = execute_transaction

    GObject.idle_add(task.info_ready_callback, task)
Example #35
0
 def runthread():
     # Called in other thread
     returned = getimage.savefromPIL(
         getimage.getimage_2(self.listbundle), "bundle-mosaic.png")
     # Add
     GObject.idle_add(finished, returned)
 def emit(self, *args):
     GObject.idle_add(GObject.GObject.emit, self, *args)
Example #37
0
 def halt(self):
     if getattr(self, 'pipeline', False):
         self.pipeline.set_state(Gst.State.NULL)
         del self.pipeline
     _log.info('Quitting MainLoop gracefully...')
     GObject.idle_add(self._loop.quit)
Example #38
0
 def lost_connection_to_server_event():
     GObject.idle_add(self.lost_db_connection, event.problem,
                      self.handle_connection_lost,
                      self.force_change_couch_url)
     GObject.idle_add(self.reload_workspaces_no_connection)
Example #39
0
 def normal_error_event():
     GObject.idle_add(self.show_normal_error, event.text)
Example #40
0
 def workspace_not_accessible_event():
     GObject.idle_add(self.handle_no_active_workspace)
Example #41
0
 def new_notification_event():
     self.notificationsModel.prepend([str(event)])
     GObject.idle_add(self.statusbar.inc_notif_button_label)
     host_count, service_count, vuln_count = self.update_counts()
     GObject.idle_add(self.statusbar.update_ws_info, host_count,
                      service_count, vuln_count)
Example #42
0
 def important_error_event():
     GObject.idle_add(self.show_important_error, event)
Example #43
0
 def new_log_event():
     GObject.idle_add(self.console_log.customEvent, event.text)
Example #44
0
        def workspace_changed_event():
            self.serverIO.active_workspace = event.workspace.name
            host_count, service_count, vuln_count = self.update_counts()
            total_host_amount = self.serverIO.get_hosts_number()
            first_host_page = self.serverIO.get_hosts(page='1',
                                                      page_size='20',
                                                      sort='vulns',
                                                      sort_dir='desc')

            total_host_amount = self.serverIO.get_workspace_numbers()[0]
            GObject.idle_add(self.statusbar.set_workspace_label,
                             event.workspace.name)
            GObject.idle_add(
                self.hosts_sidebar.reset_model_after_workspace_changed,
                first_host_page, total_host_amount)
            GObject.idle_add(self.statusbar.update_ws_info, host_count,
                             service_count, vuln_count)
            GObject.idle_add(self.statusbar.set_default_conflict_label)
            GObject.idle_add(self.statusbar.set_default_conflict_label)
            GObject.idle_add(self.select_active_workspace)
Example #45
0
 def exit_faraday(self, button=None, parent=None):
     """A simple exit which will ask for confirmation."""
     if not self.window.do_delete_event(parent):
         if parent is not None:
             GObject.idle_add(parent.destroy)
         GObject.idle_add(self.window.destroy)
Example #46
0
 def new_conflict_event():
     GObject.idle_add(self.statusbar.update_conflict_button_label,
                      event.nconflicts)
Example #47
0
    def lost_db_connection(self,
                           explanatory_message=None,
                           handle_connection_lost=None,
                           connect_to_a_different_couch=None):
        """Creates a simple dialog with an error message to inform the user
        some kind of problem has happened and the connection was lost.

        Returns whether the login dialog should be shown or not
        """

        # NOTE: if we start faraday without CouchDB, both the signal coming
        # from CouchDB manager AND our test in do_activate will try
        # to raise the dialog. This avoids more than one dialog to be raised.
        if self.lost_connection_dialog_raised:
            return False

        def do_nothing_on_key_stroke(event, key):
            """Do nothing except return True"""
            return True

        self.lost_connection_dialog_raised = True

        if explanatory_message and isinstance(explanatory_message, basestring):
            explanation = "\n The specific error was: " + explanatory_message
        else:
            explanation = ""

        dialog = Gtk.MessageDialog(
            self.window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.NONE,
            "The client can't connect to Faraday Server. "
            "You can try to reconnect to the last URL "
            "you set up, change it or exit Faraday "
            "until you fix the problem. \n"
            "For more information about Faraday Server "
            "please refer to the Faraday Github Wiki. \n " + explanation)

        dialog.set_deletable(False)

        dialog.set_modal(True)
        dialog.connect("key_press_event", do_nothing_on_key_stroke)

        retry_button = dialog.add_button("Retry connection?", 42)
        retry_button.connect("clicked", handle_connection_lost, dialog)

        change_couch_url = dialog.add_button("Change server IP?", 43)
        change_couch_url.connect("clicked", connect_to_a_different_couch,
                                 dialog)

        cancel_button = dialog.add_button("Exit Faraday", 0)
        cancel_button.connect("clicked", self.on_quit)

        if hasattr(self, 'force_new_workspace_dialog'):
            # The dialog to create a new workspace is open. Lets close it
            new_workspace_dialog = getattr(self, 'force_new_workspace_dialog')

            new_workspace_dialog.destroy()
            setattr(self, 'force_new_workspace_dialog', None)

        response = dialog.run()
        if response == Gtk.ResponseType.DELETE_EVENT:
            GObject.idle_add(self.exit_faraday_without_confirm)
        elif response in [0, 42, 43]:
            return False

        return True
Example #48
0
 def delete_notifications(self):
     """Clear the notifications model of all info, also send a signal
     to get the notification label to 0 on the main window's button
     """
     self.notificationsModel.clear()
     GObject.idle_add(self.statusbar.set_default_notif_label)
Example #49
0
    def _keypress_cb(self, area, event):
        ''' Keypress '''
        # Games 4, 5, and 6 use the keyboard
        print 'keypress event'
        if self.level not in [4, 5, 6]:
            return True
        k = Gdk.keyval_name(event.keyval)
        u = Gdk.keyval_to_unicode(event.keyval)

        if self._waiting_for_enter:
            if k == 'Return':
                self._waiting_for_enter = False
                self._panel.hide()
                self._counter += 1
                self._correct = 0
                GObject.timeout_add(1000, self.new_game, False)
            return

        if k in NOISE_KEYS or k in WHITE_SPACE:
            return True

        if self.level == 6 and self._waiting_for_delete:
            if k in ['BackSpace', 'Delete']:
                self._waiting_for_delete = False
                self._sticky_cards[self._correct].set_label_color('white')
                self._sticky_cards[self._correct].set_label(MSGS[
                    self._counter][self._sticky_cards[self._correct].type])
                self._panel.hide()
                self._panel.set_label_color('black')
            return

        if k[0:5] == 'dead_':
            self._dead_key = k[5:]
            return

        if self.level == 6:
            n = len(MSGS[self._counter])
        else:
            n = self._counter + 1

        if self.level == 6:
            i = self._correct
            if self._dead_key is not None:
                k = DEAD_DICTS[DEAD_KEYS.index(self._dead_key)][k]
                self._dead_key = None
            elif k in PUNCTUATION:
                k = PUNCTUATION[k]
            elif k in SPECIAL:
                k = SPECIAL[k]
            elif len(k) > 1:
                return True
            if self._sticky_cards[i].labels[0] == k:
                self._sticky_cards[i].set_label_color('blue')
                self._sticky_cards[i].set_label(k)
                self._correct += 1
            else:
                self._sticky_cards[i].set_label_color('red')
                self._sticky_cards[i].set_label(k)
                self._panel.set_label_color('red')
                self._panel.set_label(ALERTS[1])
                self._panel.set_layer(PANEL_LAYER)
                self._waiting_for_delete = True
                play_audio_from_file(
                    self, os.path.join(self._path, 'sounds', 'glass.ogg'))
        else:
            for i in range(n):
                if self._sticky_cards[i].labels[0] == k:
                    self._sticky_cards[i].set_label('')
                    self._sticky_cards[i].hide()
                    break

        # Test for end condition
        if self.level == 6 and \
           self._correct == len(MSGS[self._counter]) - \
                            MSGS[self._counter].count(' '):
            c = 0
            for i in range(len(MSGS[self._counter])):
                if MSGS[self._counter][i] == ' ':
                    continue
                elif MSGS[self._counter][i] != self._sticky_cards[c].labels[0]:
                    return True
                c += 1
            self._panel.set_label(ALERTS[0])
            self._panel.set_layer(PANEL_LAYER)
            self._waiting_for_enter = True
            GObject.idle_add(play_audio_from_file, self,
                             os.path.join(self._path, 'sounds', 'drip.ogg'))
            return
        else:
            for i in range(n):
                if len(self._sticky_cards[i].labels[0]) > 0:
                    return True
        self._counter += 1
        self._correct = 0
        GObject.timeout_add(1000, self.new_game, False)
Example #50
0
 def exit(*args, **kwargs):
     logger.info(
         "Exit because there are no workspaces found, and user is not admin"
     )
     GObject.idle_add(self.window.destroy)
     GObject.idle_add(self.on_quit)
Example #51
0
    def _do_start_service(self):

        # Network manager
        self.network_manager = g15network.NetworkManager(self)

        # Global plugins        
        self.session_active = True
        self.global_plugins = g15pluginmanager.G15Plugins(None, self, network_manager=self.network_manager)
        self.global_plugins.start()

        for listener in self.service_listeners:
            listener.service_starting_up()

        # UINPUT
        try:
            g15uinput.open_devices()
        except OSError as e:
            logger.debug("Error opening uinput devices", exc_info=e)
            if e.errno == 13 or e.errno == 2:
                raise Exception(
                    "Failed to open uinput devices. Do you have the uinput module loaded (try modprobe uinput), "
                    "and are the permissions of /dev/uinput correct? "
                    "If you have just installed Gnome15 for the first time, you may need to simply reboot.")
            else:
                raise

        self.session_bus = dbus.SessionBus()
        self.system_bus = dbus.SystemBus()

        # Create a screen for each device        
        self.conf_client.add_dir("/apps/gnome15", gconf.ClientPreloadType.PRELOAD_NONE)
        logger.info("Looking for devices")
        if len(self.devices) == 0:
            if g15devices.have_udev and not self.exit_on_no_devices:
                logger.error("No devices found yet, waiting for some to appear")
            else:
                logger.error("No devices found. Gnome15 will now exit")
                self.shutdown()
                return
        else:
            # Create the default profile for all devices
            for device in self.devices:
                g15profile.create_default(device)

            # If there is a single device, it is enabled by default
            if len(self.devices) == 1:
                self.conf_client.set_bool("/apps/gnome15/%s/enabled" % self.devices[0].uid, True)

            errors = 0
            for device in self.devices:
                val = self.conf_client.get("/apps/gnome15/%s/enabled" % device.uid)
                h = self.conf_client.notify_add("/apps/gnome15/%s/enabled" % device.uid,
                                                self._device_enabled_configuration_changed, device)
                self.device_notify_handles[device.uid] = h
                if (val is None and device.model_id != "virtual") or (val is not None and val.get_bool()):
                    screen = self._add_screen(device)
                    if not screen:
                        errors += 1

            if len(self.devices) == errors:
                logger.error("All screens failed to load. Shutting down")
                self.shutdown()
                return

            if len(self.screens) == 0:
                logger.warning("No screens found yet. Will stay running waiting for one to be enabled.")

        # Load hidden configuration and monitor for changes
        self._load_hidden_configuration()
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/scroll_delay", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/scroll_amount", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/animated_menus", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/animation_delay", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/key_hold_duration", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/use_x_test", self._hidden_configuration_changed))
        self.notify_handles.append(
            self.conf_client.notify_add("/apps/gnome15/disable_svg_glow", self._hidden_configuration_changed))

        # Monitor active application    
        gobject.idle_add(self._configure_window_monitoring)

        # Activate global plugins
        self.global_plugins.activate()

        # Start each screen's plugin manager
        th = []
        for screen in self.screens:
            t = StartThread(screen)
            if self.start_in_threads:
                t.start()
            else:
                t.run()
            th.append(t)
        if len(self.screens) == 1:
            if th[0].error is not None:
                raise th[0].error

        if self.start_in_threads:
            for t in th:
                t.join()

        self.starting_up = False
        for listener in self.service_listeners:
            listener.service_started_up()
        self.started = True

        gobject.idle_add(self._monitor_session)

        # Watch for devices changing
        g15devices.device_added_listeners.append(self._device_added)
        g15devices.device_removed_listeners.append(self._device_removed)
Example #52
0
    def create_layout(self, layout):
        """Apply layout configuration"""
        def child_compare(a, b):
            order_a = children[a]['order']
            order_b = children[b]['order']

            if (order_a == order_b):
                return 0
            if (order_a < order_b):
                return -1
            if (order_a > order_b):
                return 1

        if not layout.has_key('children'):
            err('layout specifies no children: %s' % layout)
            return

        children = layout['children']
        if len(children) <= 1:
            #Notebooks should have two or more children
            err('incorrect number of children for Notebook: %s' % layout)
            return

        num = 0
        keys = children.keys()
        keys.sort(child_compare)

        for child_key in keys:
            child = children[child_key]
            dbg('Making a child of type: %s' % child['type'])
            if child['type'] == 'Terminal':
                pass
            elif child['type'] == 'VPaned':
                page = self.get_nth_page(num)
                self.split_axis(page, True)
            elif child['type'] == 'HPaned':
                page = self.get_nth_page(num)
                self.split_axis(page, False)
            num = num + 1

        num = 0
        for child_key in keys:
            page = self.get_nth_page(num)
            if not page:
                # This page does not yet exist, so make it
                self.newtab(children[child_key])
                page = self.get_nth_page(num)
            if layout.has_key('labels'):
                labeltext = layout['labels'][num]
                if labeltext and labeltext != "None":
                    label = self.get_tab_label(page)
                    label.set_custom_label(labeltext)
            page.create_layout(children[child_key])

            if layout.get('last_active_term', None):
                self.last_active_term[page] = make_uuid(
                    layout['last_active_term'][num])
            num = num + 1

        if layout.has_key('active_page'):
            # Need to do it later, or layout changes result
            GObject.idle_add(self.set_current_page, int(layout['active_page']))
        else:
            self.set_current_page(0)
    def unreveal(self):
        if self.disabled:
            return

        GObject.idle_add(self.set_reveal_child, False)
Example #54
0
 def quit(self):
     """Exit the UI event loop."""
     GObject.idle_add(Gtk.main_quit)
Example #55
0
 def on_edit_button_clicked(self, button):
     # The day's text is already in the editor.
     self.change_mode(preview=False)
     # Select (not only highlight) previously selected text by giving focus
     # to the day editor.
     GObject.idle_add(self.day_text_field.day_text_view.grab_focus)
Example #56
0
 def my_fn(*args, **kwargs):
     GObject.idle_add(fn, *args, **kwargs)
Example #57
0
    def importButton_clicked_cb(self, widget):
        """Callback executed when the user wants to import messages"""
        if self.currentProject is None:
            self.log.error("No project is open")
            return

        # retrieve symbol name
        symbolName = self._view.nameOfCreatedSymbolEntry.get_text()
        if symbolName is None or len(symbolName) < 1:
            self.displayErrorMessage(_("Specify the name of new symbol"))
            return

        found = False
        for symbol in self.currentProject.getVocabulary().getSymbols():
            if symbol.getName() == symbolName:
                found = True
                break

        if found:
            self.displayErrorMessage(
                _("The provided symbol name already exists."))
            return

        # Should we consider meta datas of excluded messages
        if self._view.removeDuplicatedMessagesCheckButton.get_active(
        ) and self._view.keepPropertiesOfDuplicatedMessagesCheckButton.get_active(
        ):
            # Retrieve the 'excluded' messages and retrieve their properties
            for message in self.excludedMessages:
                # search for an included message to register properties
                eq_message = None
                for importedMessage in self.importedMessages:
                    if importedMessage.getStringData(
                    ) == message.getStringData():
                        eq_message = importedMessage
                        break
                if eq_message is not None:
                    for property in message.getProperties():
                        eq_message.addExtraProperty(property)

        # We create a session with each message
        session = Session(str(uuid.uuid4()), "Session 1", "")
        for message in self.importedMessages:
            session.addMessage(message)
        # We register the session in the vocabulary of the project
        self.currentProject.getVocabulary().addSession(session)

        # We register each message in the vocabulary of the project
        for message in self.importedMessages:
            self.currentProject.getVocabulary().addMessage(message)
            message.setSession(session)

        # We create a default symbol dedicated for this
        symbol = Symbol(str(uuid.uuid4()), symbolName, self.currentProject)
        for message in self.importedMessages:
            symbol.addMessage(message)
        # We register the symbol in the vocabulary of the project
        self.currentProject.getVocabulary().addSymbol(symbol)

        # Add the environmental dependencies to the project
        #        if fetchEnv:
        #            project.getConfiguration().setVocabularyInferenceParameter(ProjectConfiguration.VOCABULARY_ENVIRONMENTAL_DEPENDENCIES,
        #                                                                       self.envDeps.getEnvData())
        # Computes current date
        date = datetime.now()
        description = "No description (yet not implemented)"

        # We also save the session and the messages in the workspace
        trace = ImportedTrace(str(uuid.uuid4()), date, self.importType,
                              description, self.currentProject.getName())
        trace.addSession(session)
        for message in self.importedMessages:
            trace.addMessage(message)

        self.currentWorkspace.addImportedTrace(trace)

        # Now we save the workspace
        self.currentWorkspace.saveConfigFile()

        self._view.destroy()

        if self.finish_cb is not None:
            GObject.idle_add(self.finish_cb)
 def reveal(self):
     if self.disabled:
         return
     GObject.idle_add(self._reveal_idle_callback)
Example #59
0
 def clicked(self, service_name, address, port):
     """
     This function is called in response to a menu_item click.
     Fire away.
     """
     GObject.idle_add(self.emit, "connect", (service_name, address, port))
Example #60
0
 def destroy(self):
     import gc
     GObject.idle_add(lambda: gc.collect())