Beispiel #1
0
    def update_kernel_model(self):
        self.set_busy()
        model = self.get_model()
        model.clear()
        self.mode = 'kernel'

        icon = get_icon_with_name('deb', 24)
        list = self.package_worker.list_unneeded_kerenl()
        self.total_num = len(list)
        self.__column.set_title(_('Packages'))

        while gtk.events_pending():
            gtk.main_iteration()

        for pkg in list:
            desc = self.package_worker.get_pkgsummary(pkg)

            iter = model.append()
            model.set(iter,
                   COLUMN_CHECK, False,
                   COLUMN_ICON, icon,
                   COLUMN_NAME, pkg,
                   COLUMN_DESC, desc,
                   COLUMN_DISPLAY, '<b>%s</b>\n%s' % (pkg, desc)
                )
        self.unset_busy()
Beispiel #2
0
 def _show_messages(self, trans):
     while gtk.events_pending():
         gtk.main_iteration()
     for msg in trans._messages:
         d = AptMessageDialog(msg.enum, msg.details, parent=self.window_main)
         d.run()
         d.hide()
 def runMainLoopWithReplay(self):
     while gtk.events_pending():
         gtk.main_iteration()
     if self.delay:
         time.sleep(self.delay)
     if self.isActive():
         self.describeAndRun()
Beispiel #4
0
    def update_cache_model(self):
        self.set_busy()
        model = self.get_model()
        model.clear()
        self.mode = 'cache'

        cache_dir = '/var/cache/apt/archives' 
        icon = get_icon_with_name('deb', 24)
        list = map(lambda file: '%s/%s' % (cache_dir, file),
                    filter(lambda x:x.endswith('deb'), os.listdir(cache_dir))) 
        self.total_num = len(list)
        self.__column.set_title(_('Package Cache'))

        while gtk.events_pending():
            gtk.main_iteration()

        for pkg in list:
            size = str(os.path.getsize(pkg))

            iter = model.append()
            model.set(iter,
                   COLUMN_ICON, icon,
                   COLUMN_CHECK, False,
                   COLUMN_NAME, pkg,
                   COLUMN_DESC, size,
                   COLUMN_DISPLAY, _('<b>%s</b>\nTake %s of disk space') % (os.path.basename(pkg), filesizeformat(size)) 

                )
        self.unset_busy()
    def createStatsTable(self, vbox, playerids, sitenos, limits, type, seats, groups, dates, games):
        startTime = time()
        show_detail = True

        # Scrolled window for summary table
        swin = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
        swin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        vbox.pack1(swin) #, resize=True)  don't use resize, self.height_inc relies on initial 
                         # height of pane being correct for one row

        # Display summary table at top of page
        # 3rd parameter passes extra flags, currently includes:
        #   holecards - whether to display card breakdown (True/False)
        #   numhands  - min number hands required when displaying all players
        #   gridnum   - index for grid data structures
        flags = [False, self.filters.getNumHands(), 0]
        self.addGrid(swin, 'playerDetailedStats', flags, playerids
                    ,sitenos, limits, type, seats, groups, dates, games)
        swin.show()

        if 'allplayers' in groups and groups['allplayers']:
            # can't currently do this combination so skip detailed table
            show_detail = False

        if show_detail: 
            # Separator
            vbox2 = gtk.VBox(False, 0)
            heading = gtk.Label(self.filterText['handhead'])
            heading.show()
            vbox2.pack_start(heading, expand=False, padding=3)

            # Scrolled window for detailed table (display by hand)
            swin2 = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
            swin2.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
            swin2.show()
            vbox2.pack_start(swin2, expand=True, padding=3)
            vbox.pack2(vbox2)
            vbox2.show()

            # Detailed table
            flags[0] = True
            flags[2] = 1
            self.addGrid(swin2, 'playerDetailedStats', flags, playerids
                        ,sitenos, limits, type, seats, groups, dates, games)

        if self.height_inc is None:
            self.height_inc = 0
            # need this to check whether scrollbar is visible:
            while gtk.events_pending(): # see http://faq.pygtk.org/index.py?req=index for more hints (3.7)
                gtk.main_iteration(False)
            hs = swin.get_hscrollbar()
            if hs is not None:
                #print "hs vis", hs.get_property('visible'), hs.get_property('visible').__class__
                if hs.get_property('visible'):
                    self.height_inc = hs.size_request()[1] + swin.style_get_property('scrollbar-spacing')
            #print "hh set to", self.height_inc
            self.stats_vbox.set_position(self.top_pane_height + self.height_inc)

        self.db.rollback()
        print (_("Stats page displayed in %4.2f seconds") % (time() - startTime))
    def update_disc_usage (self):
        if not self.update:
            return
        if self.source.total_duration > self.disc_size:
            self.__capacity_exceeded.show ()
            
        else:
            self.__capacity_exceeded.hide ()

        # Flush events so progressbar redrawing gets done
        while gtk.events_pending():
            gtk.main_iteration(True)
        
        if self.source.total_duration > 0:
            duration = self.__disc_size - self.source.total_duration
            if duration > 0:
                dur = _("%s remaining")  % self.__hig_duration (duration)
            else:
                dur = _("%s overlaping") % self.__hig_duration (abs (duration))
        else:
            dur = _("Empty")
        
        self.__usage_label.set_text (dur)
            
        e = operations.Event(self)
        for l in self.listeners:
            l.on_contents_changed (e)
    def setup_ubuntu_cn_mirror(self):
        window = self.get_toplevel().window
        if window:
            window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))

        if UNCONVERT:
            import ubuntutweak.common.sourcedata
            reload(ubuntutweak.common.sourcedata)
            global SOURCES_DATA
            from ubuntutweak.common.sourcedata import SOURCES_DATA
            proxy.replace_entry(UBUNTU_CN_STR, PPA_URL)
            self.update_model()
            self.emit('sourcechanged')
        else:
            iter = self.model.get_iter_first()
            while iter:
                while gtk.events_pending():
                    gtk.main_iteration()

                url  = self.model.get_value(iter, self.COLUMN_URL)

                if self.has_mirror_ppa(url):
                    new_url = url.replace(PPA_URL, UBUNTU_CN_STR)
                    proxy.replace_entry(url, new_url)
                    self.model.set_value(iter, self.COLUMN_URL, new_url)

                iter = self.model.iter_next(iter)

            self.emit('sourcechanged')
            self.update_ubuntu_cn_model()

        if window:
            window.set_cursor(None)
Beispiel #8
0
	def add(self, target):
		
		target = urllib.unquote(target).replace("file://", "")
		
		if target.endswith(".m3u"):  #load playlist files
			self.loadm3u(target)
			
		elif target.endswith(".pls"):
			self.loadpls(target)
		
		elif os.path.isdir(target):  #load directories
			
			targs = os.listdir(target)
			targs.sort()
			
			for t in targs:  #recurse through directory
				if not t.startswith("."):  #skip dotfiles
					self.add(target + "/" + t)
		
		else:  #add target to playlist
			self.counter, tid = self.counter + 1, self.counter
			
			if target.find("://") > -1: name = target
			else: name = os.path.basename(target)
			
			row = [tid, target, name, pango.WEIGHT_BOLD, False]
			self.view.get_model().append(row)
			
		gtk.main_iteration()  #allow other events to process
		return True
Beispiel #9
0
	def __init__(self, app_obj, image_filename):
		print "Splash:", image_filename
		self.app_obj = app_obj

		# Hook the application's error_dialog() method so that we can
		# make the splash screen disappear before the dialog box appears.
		self.real_error_dialog = self.app_obj.error_dialog
		self.app_obj.error_dialog = pykarta.misc.BoundMethodProxy(self.error_dialog_hook)

		# Create a white window
		self.window = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
		self.window.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("white"))

		# Ask the window manager not to decorate it and to put it in the center
		# of the screen. The way we do this is somewhat redundant because
		# we want to be sure to be understood.
		# FIXME: disabled because Ubuntu Unity loses the WM icon!
		#self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)	# enough under GNOME
		self.window.set_position(gtk.WIN_POS_CENTER)						# needed on Win32
		self.window.set_decorated(False)									# needed on Win32
		self.window.set_keep_above(True)

		# Load the image and put it in the white window.
		image = gtk.Image()
		image.set_from_file(image_filename)
		self.window.add(image)

		self.window.show_all()
		self.window.present()		# in case Win32 launcher was minimized

		while gtk.events_pending():
			gtk.main_iteration(False)
def refresh_screen():

	""" Refresh the widgets in the screen. Used mainly to update the progress
	bars during file conversion """

	while gtk.events_pending():
		gtk.main_iteration()
Beispiel #11
0
    def show(self):
        """
        Builds the splashscreen and connects the splash window to be destroyed 
        via a timeout callback in L{SplashScreen.DELAY}msec time.

        The splash can also be destroyed manually by the application
        """
        self.wSplash = gtk.Window(gtk.WINDOW_POPUP)
        self.wSplash.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)
        self.wSplash.set_decorated(False)

        wSplashScreen = gtk.Image()
        wSplashScreen.set_from_file(os.path.join(conduit.SHARED_DATA_DIR,"conduit-splash.png"))

        # Make a pretty frame
        wSplashFrame = gtk.Frame()
        wSplashFrame.set_shadow_type(gtk.SHADOW_OUT)
        wSplashFrame.add(wSplashScreen)
        self.wSplash.add(wSplashFrame)

        # OK throw up the splashscreen
        self.wSplash.set_position(gtk.WIN_POS_CENTER)
        
        #The splash screen is destroyed automatically (via timeout)
        #or when the application is finished loading
        self.destroyed = False

        self.wSplash.show_all()
        # ensure it is rendered immediately
        while gtk.events_pending():
            gtk.main_iteration() 
        # The idle timeout handler to destroy the splashscreen
        gobject.timeout_add(SplashScreen.DELAY,self.destroy)
def progress_timeout(pbobj):
	if pbobj.activity_check.get_active():
		pbobj.pbar.pulse()
	else:
		global samplecount
		global maxsamples
		if samplecount < parts:
			data,addr = UDPSock.recvfrom(buffer)
			samplecount += 1
        # Calculate the value of the progress bar using the
        # value range set in the adjustment object
		#new_val = pbobj.pbar.get_fraction() + 1.0/1000
			new_val = pbobj.pbar.get_fraction() + 1.0/parts
			#new_val = float(samplecount) / maxsamples
        # Set the new value
			if new_val > 1:
				new_val = 1.0
 			pbobj.pbar.set_fraction(new_val)
 			while gtk.events_pending():
 				gtk.main_iteration()
 			return True
	# As this is a timeout function, return TRUE so that it
	# continues to get called
		return False
	return True
    def __init__(self, directory, window="dialog-warning", manageGTK=True, callBack=None):
        """
        Print a small dialog screen
        
        @param callBack: method to be called with the directory chosen 
        @type callBack: method or function
        """
        logger.debug("WarningSc.init")
        self.directory = directory
        self.window = window
        self.manageGTK = manageGTK
        self.quit = True
        self.callBack = callBack
        self.guiFiler = None
        self.gui = gtk.glade.XML(unifiedglade, root=self.window)
        self.gui.signal_connect('on_dialog_destroy', self.destroy)
        self.gui.signal_connect('on_Select_clicked', self.filer)
        self.gui.signal_connect('on_cancel_clicked', self.destroy)
        self.gui.signal_connect('on_ok_clicked', self.continu)
        self.gui.signal_connect('on_dirname_editing_done', self.continu)
        self.gui.get_widget("dirname").set_text(directory)

        if self.manageGTK:
            gtk.main()
        else:
            while gtk.events_pending():
                gtk.main_iteration()
Beispiel #14
0
    def __init__(self):
        super(Splash, self).__init__()

        # These two lines are required here to make sure that unity shows the
        # correct information in the menu
        self.set_icon_from_file(W3AF_ICON)
        self.set_title('w3af - 0wn the Web')

        vbox = gtk.VBox()
        self.add(vbox)

        # content
        splash = os.path.join(ROOT_PATH, 'core', 'ui', 'gui', 'data',
                              'splash.png')
        img = gtk.image_new_from_file(splash)
        vbox.pack_start(img)
        self.label = gtk.Label()
        vbox.pack_start(self.label)

        # Splash screen doesn't have decoration (at least where supported)
        # https://github.com/andresriancho/w3af/issues/9084
        if not MacOSX.is_current_platform():
            self.set_decorated(False)

        # color and position
        color = gtk.gdk.color_parse('#f2f2ff')
        self.modify_bg(gtk.STATE_NORMAL, color)
        self.set_position(gtk.WIN_POS_CENTER)
        self.set_size_request(644, 315)

        # ensure it is rendered immediately
        self.show_all()

        while gtk.events_pending():
            gtk.main_iteration()
Beispiel #15
0
 def open_search(self,parent_window):
     self.titles = [""]
     self.ids = [""]
     if self.url.find('%s') > 0:
         self.url = self.url % self.title
         self.url = string.replace(self.url, ' ', '%20')
     else:
         self.url = string.replace(self.url+self.title, ' ', '%20')
     try:
         url = self.url.encode(self.encode)
     except UnicodeEncodeError:
         url = self.url.encode('utf-8')
     self.progress.set_data(parent_window, _("Searching"), _("Wait a moment"), False)
     retriever = Retriever(url, parent_window, self.progress)
     retriever.start()
     while retriever.isAlive():
         self.progress.pulse()
         if self.progress.status:
             retriever.join()
         while gtk.events_pending():
             gtk.main_iteration()
     try:
         if retriever.html:
             ifile = file(retriever.html[0], 'rb')
             self.page = ifile.read()
             # check for gzip compressed pages before decoding to unicode
             if len(self.page) > 2 and self.page[0:2] == '\037\213':
                 self.page = gutils.decompress(self.page)
             self.page = self.page.decode(self.encode, 'replace')
         else:
             return False
     except IOError:
         pass
     urlcleanup()
     return True
Beispiel #16
0
    def update(self, event, no_progress=False, new_total_events=None):
        """Show text corresponding to an event."""
        text = str(event)
        if new_total_events is not None:
            self.total_number_of_events = new_total_events
            self.event_count = 0.0

        if not no_progress:
            self.event_count += 1.0

        if self.total_number_of_events == 0:
            fraction = 1.0
        else:
            fraction = min(
                [1.0, self.event_count / self.total_number_of_events])
        self._stop_pulse()

        if not no_progress:
            gobject.idle_add(self.progress_bar.set_fraction, fraction)
            self._progress_fraction = fraction

        self.progress_bar.set_text(text)
        self._progress_message = text
        gobject.timeout_add(self.TIME_IDLE_BEFORE_PULSE,
                            self._start_pulse, fraction, text)

        if fraction == 1.0 and not no_progress:
            gobject.timeout_add(self.TIME_WAIT_FINISH,
                                lambda: self.finish())

        while gtk.events_pending():
            gtk.main_iteration()
Beispiel #17
0
    def refresh_handler(self):
        '''
        At every REFRESH interval check the status of the user quota and 
        decide if a warning needs to be displayed.
        '''
        while gtk.events_pending():
            gtk.main_iteration(False)

        quotaInfo = self.getQuota()

        self.updateLabel(quotaInfo)
        self.updateProgressBar(quotaInfo)
        self.updateTip(quotaInfo)
        
        if (quotaInfo[1] > 0):
            used = float(quotaInfo[0]) / 1024
            total = float(quotaInfo[1]) / 1024
            free = float(quotaInfo[2]) / 1024
            percent = int(quotaInfo[3])

            # over MAX_WARN%, under MB_WARN MBs, they haven't clicked the checkbox 
            # and the window is not currently being displayed
            if percent >= MAX_WARN and free <= MAX_WARNMB and self.latch is False:
                window = self.wTree.get_widget('warning')
                value = window.get_property('visible')
                if value is False: window.set_property('visible', True)

        return True
Beispiel #18
0
    def close_session(self, do_exit=True):
        '''close session'''

        if self.timeout_id:
            gobject.source_remove(self.timeout_id)
            self.timeout_id = None

        if self.session is not None:
            self.session.quit()

        self.save_extensions_config()
        self._save_login_dimensions()

        if self.session is not None:
            self.session.save_config()
            self.session = None

        self.config.save(self.config_path)

        if self.conversations:
            self.conversations.get_parent().hide()
            self.conversations = None

        if do_exit:
            if self.tray_icon is not None:
                self.tray_icon.set_visible(False)
            self.window.hide()
            self.window = None

            while gtk.events_pending():
                gtk.main_iteration(False)

            sys.exit(0)
Beispiel #19
0
    def find_table_parameters(self):

#    This is called by __init__(). Find the poker table window of interest,
#    given the self.search_string. Then populate self.number, self.title, 
#    self.window, and self.parent (if required).

        self.number = None
        self.wnck_table_w = None

        # Flush GTK event loop before calling wnck.get_*
        while gtk.events_pending():
            gtk.main_iteration(False)

        for win in root.get_windows():
            w_title = win.get_name()
            if re.search(self.search_string, w_title, re.I):
                log.info('"%s" matches: "%s"' % (w_title, self.search_string))
                title = w_title.replace('"', '')
                if self.check_bad_words(title): continue
                # XXX: If we could connect to 'window-closed' here, it
                # would make things SOOO much easier... Alas, the signal
                # is not available for individual windows.
                self.wnck_table_w = win
                self.number = int(win.get_xid())
                self.title = title
                # XID is a consistent key
                WNCK_XTABLES.add(self.number)
                break

        if self.number is None:
            log.warning(_("No match in XTables for table '%s'.") % self.search_string)
            return None
Beispiel #20
0
def update_gui():
    """
    Flush any GTK Events.  Used for doing GUI testing.
    """
    import gtk
    while gtk.events_pending():
        gtk.main_iteration(block=False)
Beispiel #21
0
 def quit_cb (self, *args):
     self.w.hide()
     if (self.gsd.grid
         and self.gsd.grid.is_changed()
         and (not self.won)):
         self.save_game(self)
     if gtk.main_level() > 1:
         # If we are in an embedded mainloop, that means that one
         # of our "swallowed" dialogs is active, in which case we
         # have to quit that mainloop before we can quit
         # properly.
         if self.swallower.running:
             d = self.swallower.running
             d.response(gtk.RESPONSE_DELETE_EVENT)
         gtk.main_quit() # Quit the embedded mainloop
         gobject.idle_add(self.quit_cb, 100) # Call ourselves again
                                            # to quit the main
                                            # mainloop
         return
     # make sure we really go away before doing our saving --
     # otherwise we appear sluggish.
     while gtk.events_pending():
         gtk.main_iteration()
     self.stop_worker_thread()
     # allow KeyboardInterrupts, which calls quit_cb outside the main loop
     try:
         gtk.main_quit()
     except RuntimeError:
         pass
Beispiel #22
0
    def display_track_tags(self, serial):

        current_serial = serial

        try:
                m = self.youki.get_metadata()

                if m[mpx.AttributeId.ARTIST] and m[mpx.AttributeId.TITLE]:

                    instance = TrackTagsDataAcquire(m[mpx.AttributeId.ARTIST].get(), m[mpx.AttributeId.TITLE].get())
                    instance.start()

                    while not instance.is_finished():
                        while gtk.events_pending(): gtk.main_iteration()

                    tags = instance.get_tags()
            
                    if current_serial == self.serial:

                            self.tagview.clear()
                            self.tagview.display(False)

                            for t in tags:
                                self.tagview.add_tag(str(t[0]), float(t[1]))

                    else:
                            self.display_track_tags( self.serial )

                self.tagview.display(True)
        except:
                pass
Beispiel #23
0
	def report(self,status):
		_time = time.clock();
		_sincelast = _time - self.lasttime
		if status.getCurrentBlockNum() > self.blocknum:
			self.blocknum = status.getCurrentBlockNum()
			self.blockstart = _time

		if self.lasttime==0 or _sincelast > self.updateinterval:
			self.lasttime = _time;
			self.elapsed = _time - self.starttime
			self.totalelapsed = _time - self.studybegintime
			self.blocktime = _time - self.blockstart
			#print "UPDATING!"
			self.fill_values(status)

		while gtk.events_pending():
			gtk.main_iteration()

		self.guitime = self.guitime + (time.clock() - _time)

		if status.isConverged() or status.isDiverged() or status.isInterrupted():
			return 1
		if self.guiinterrupt:
			return 2
		return 0
Beispiel #24
0
    def __init__(self, parent, total, text=_("Saved %(count)s of %(total)s.")):
        gtk.Window.__init__(self)
        self.count = 0
        self.total = total
        self.text = text

        if parent:
            self.set_transient_for(parent)
        self.set_modal(True)
        self.set_decorated(False)
        self.set_resizable(False)
        self.set_focus_on_map(False)
        self.add(gtk.Frame())
        self.get_child().set_shadow_type(gtk.SHADOW_OUT)
        vbox = gtk.VBox(spacing=12)
        vbox.set_border_width(12)
        self._label = gtk.Label()
        self._label.set_use_markup(True)
        self._label.set_markup(self.text % {'count': 0, 'total': self.total})
        vbox.pack_start(self._label)
        self._progress = gtk.ProgressBar()
        self._progress.set_size_request(300, -1)
        vbox.pack_start(self._progress)

        self.get_child().add(vbox)

        self.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.show_all()
        while gtk.events_pending():
            gtk.main_iteration()
Beispiel #25
0
 def abrir_item(self, tv, path, view_column):
     self.wids['ventana'].window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
     while gtk.events_pending(): gtk.main_iteration(False)
     model = tv.get_model()
     if model[path].parent == None:
         # Empleado seleccionado
         idempleado = model[path][-1]
         empleado = pclases.Empleado.get(idempleado)
         from formularios import empleados
         self.wids['ventana'].window.set_cursor(None)
         ventanaempleado = empleados.Empleados(empleado)  # @UnusedVariable
     else:
         # Parte seleccionado.
         # OJO: Para identificar si es parte de producción o de trabajo miro la duración en producción en el model.
         if model[path][7] != "":    # Es de GTX:
             idparte = model[path][-1]
             parte = pclases.ParteDeProduccion.get(idparte)
             from formularios import partes_de_fabricacion_rollos
             self.wids['ventana'].window.set_cursor(None)
             ventanaparte = partes_de_fabricacion_rollos.PartesDeFabricacionRollos(parte)  # @UnusedVariable
         elif model[path][8] != "":   # Es de fibra
             idparte = model[path][-1]
             parte = pclases.ParteDeProduccion.get(idparte)
             from formularios import partes_de_fabricacion_balas
             self.wids['ventana'].window.set_cursor(None)
             ventanaparte = partes_de_fabricacion_balas.PartesDeFabricacionBalas(parte)  # @UnusedVariable
         else:   # Debe ser parte de trabajo, no queda otra.
             idparte = model[path][-1]
             parte = pclases.ParteDeTrabajo.get(idparte)
             from formularios import partes_de_trabajo
             self.wids['ventana'].window.set_cursor(None)
             ventanaparte = partes_de_trabajo.PartesDeTrabajo(parte)  # @UnusedVariable
Beispiel #26
0
 def fetch_picture(self):
     if self.image_url:
         tmp_dest = tempfile.mktemp(prefix='poster_', dir=self.locations['temp'])
         self.image = tmp_dest.split('poster_', 1)[1]
         dest = "%s.jpg" % tmp_dest
         try:
             self.progress.set_data(self.parent_window, _("Fetching poster"), _("Wait a moment"), False)
             retriever = Retriever(self.image_url, self.parent_window, self.progress, dest,
                                   useurllib2=self.useurllib2)
             retriever.start()
             while retriever.isAlive():
                 self.progress.pulse()
                 if self.progress.status:
                     retriever.join()
                 while gtk.events_pending():
                     gtk.main_iteration()
             urlcleanup()
         except:
             log.exception('')
             self.image = ""
             try:
                 os.remove("%s.jpg" % tmp_dest)
             except:
                 log.info("Can't remove %s file" % tmp_dest)
     else:
         self.image = ""
Beispiel #27
0
 def __del__(self):
     self._ventana.destroy()
     self.__seguir_actualizando = False
     while gtk.events_pending():
         gtk.main_iteration(False)
     while not gobject.source_remove(self.__tag):
         pass
    def on_btn_apply_clicked(self, widget, data=None):
        correct = True
        if len(self.formation_player) == 0:
            self.error_team.run()
            correct = False
        if len(self.rules_computer) == 0 and not self.random_computer:
            self.error_es_ia.run()
            correct = False
        if len(self.formation_computer) == 0 and not self.random_computer:
            self.error_team_ia.run()
            correct = False

        if correct:
            computer_team = None
            if self.random_computer:
                teams = selection.get_installed_teams()
                computer_team = teams[random.randint(0, len(teams)-1)]
            else:
                computer_team = (self.rules_computer, self.formation_computer)

            self.human_ia_dialog.destroy()
            
            while gtk.events_pending():
                gtk.main_iteration(False)
                
            try:
                # AQUÍ se lanza el juego de humano contra máquina
                human_game_handler.init_human_game(self.formation_player,
                                                   computer_team, self.human_team,
                                                   self.num_turns, self.dont_save_game)
                
            except human_game_handler.FileError as e:
                self.dlg_bad_file.format_secondary_text(e.msg)
                self.dlg_bad_file.run()
                self.quick_game.show()
Beispiel #29
0
    def __install_button_cb(self, button, data):
        if self.conf.check_policy('warning-download-update'):
            device_dialer = tgcm.core.FreeDesktop.DeviceDialer()
            device_manager = tgcm.core.FreeDesktop.DeviceManager()
            device = device_manager.get_main_device()
            if device_dialer.is_modem() and device.is_connected():
                tech_mm = device.get_access_technology()
                if tech_mm in (ACCESS_TECH_GSM, ACCESS_TECH_GSM_COMPACT, \
                        ACCESS_TECH_GPRS, ACCESS_TECH_EDGE):
                    markup = _("<b>Warning: slow connection</b>")
                    message = _("Your connection seems too slow and the download would take you quite a long time. Are you sure to continue?")

                    resp = question_dialog(message, markup=markup, parent=self.dialog)
                    if resp == gtk.RESPONSE_NO:
                        return

        self.progress_dialog = tgcm.ui.MSD.MSDProgressWindow(parent=self.dialog)
        self.progress_dialog.set_show_buttons(False)
        message = _("Please wait a minute...")
        self.progress_dialog.show(message, message)

        entry = self.__get_selected_row(self.updates_treeview)
        self.news_service.install_async(entry['id'], self.__on_install_callback)
        if gtk.events_pending():
            gtk.main_iteration(False)
Beispiel #30
0
def get_open_windows():
	gtk.main_iteration()
	screen = wnck.screen_get_default()
	screen.force_update()
	win = screen.get_windows()
	windows=[]
	for w in win:
			if  'NORMAL' in str(w.get_window_type()):
				if "ducklauncher!!!"==w.get_name():
					pass			
				elif w.is_sticky()!=True and "ducklauncher!!"!=w.get_name():
					window={}	
					window['id']=w.get_xid()
					window['title'] =w.get_name()
					window['app']=w.get_application().get_name()
					window['icon']=w.get_application().get_icon_name()
					pix=w.get_icon()
					pix= pix.scale_simple(128,128,gtk.gdk.INTERP_HYPER)
					ico_data=  pix.get_pixels_array()
					img = Image.fromarray(ico_data, 'RGBA')
					home = os.path.expanduser("~")+"/.duck"
					try:
    						os.stat(home)
					except:
    						os.mkdir(home)
Beispiel #31
0
    def run(self):
        self.oem_config.show()

        if os.getuid() != 0:
            title = ('This program must be run with administrative '
                     'privileges, and cannot continue without them.')
            dialog = gtk.MessageDialog(self.oem_config, gtk.DIALOG_MODAL,
                                       gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                                       title)
            dialog.run()
            sys.exit(1)

        self.glade.signal_autoconnect(self)

        # Some signals need to be connected by hand so that we have the
        # handler ids.
        self.username_changed_id = self.username.connect(
            'changed', self.on_username_changed)

        self.auto_login.hide()

        self.steps.set_current_page(self.steps.page_num(self.step_language))
        # TODO cjwatson 2006-07-07: why isn't on_steps_switch_page getting
        # invoked?
        self.set_current_page(self.steps.page_num(self.step_language))

        while self.current_page is not None:
            self.backup = False
            current_name = self.step_name(self.current_page)
            if current_name == 'step_language':
                self.dbfilter = language.Language(self)
            elif current_name == 'step_timezone':
                self.dbfilter = timezone.Timezone(self)
            elif current_name == 'step_keyboard':
                self.dbfilter = console_setup.ConsoleSetup(self)
            elif current_name == 'step_user':
                self.dbfilter = user.User(self)
            else:
                raise ValueError, "step %s not recognised" % current_name

            self.allow_change_step(False)
            self.dbfilter.start(auto_process=True)
            gtk.main()

            if self.backup:
                pass
            elif current_name == 'step_language':
                self.translate_widgets()
                self.steps.next_page()
            elif current_name == 'step_keyboard':
                self.info_loop(None)
                self.steps.next_page()
            elif current_name == 'step_user':
                self.allow_change_step(False)
                self.current_page = None
                self.apply_changes = True
            else:
                self.steps.next_page()

            while gtk.events_pending():
                gtk.main_iteration()

        # TODO: handle errors
        if self.apply_changes:
            dbfilter = language_apply.LanguageApply(self)
            dbfilter.run_command(auto_process=True)

            dbfilter = timezone_apply.TimezoneApply(self)
            dbfilter.run_command(auto_process=True)

            dbfilter = console_setup_apply.ConsoleSetupApply(self)
            dbfilter.run_command(auto_process=True)

        self.oem_config.hide()

        if self.apply_changes:
            return 0
        else:
            return 10
Beispiel #32
0
class game:
    def make(self):
        pygame.init()
        sound = True
        try:
            pygame.mixer.init()
        except Exception, err:
            sound = False
            print 'error with sound', err

        i = 0
        gameDisplay = pygame.display.get_surface()
        if not (gameDisplay):
            info = pygame.display.Info()
            gameDisplay = pygame.display.set_mode(
                (info.current_w,
                 info.current_h))  # initializing display surface
            # window name
            pygame.display.set_caption("Buttons & Scissors")
            gameicon = pygame.image.load('buts/icon2.png')
            pygame.display.set_icon(gameicon)

        disp_width = 800
        disp_height = 600

        clock = pygame.time.Clock()
        timer = pygame.time.Clock()

        background = pygame.image.load(
            "buts/background.jpg").convert()  # background image load
        background = pygame.transform.scale(
            background, (disp_width + 100, disp_height + 250))
        home = pygame.transform.scale(pygame.image.load("buts/home.png"),
                                      (80, 80))
        restart = pygame.transform.scale(pygame.image.load("buts/restart.png"),
                                         (80, 80))
        undo = pygame.transform.scale(pygame.image.load("buts/undo.png"),
                                      (80, 80))
        hlp = pygame.transform.scale(pygame.image.load("buts/help.png"),
                                     (80, 80))
        stitch = pygame.transform.scale(pygame.image.load("buts/stitch.png"),
                                        (40, 40))

        # SOUND FILES LOADED
        b = welcome()  # Welcome Screen Call
        bvalue = b.make(gameDisplay, sound)
        crashed = False
        black = (0, 0, 0)
        white = (255, 255, 255)
        horizontal = vertical = rightd = leftd = 0
        rightd = leftd = lastx = lasty = 0
        buttonslist = []
        x = [370 + 280, 435 + 280, 500 + 280, 565 + 280, 630 + 280]
        y = [235, 300, 365, 430, 495]
        backup = []
        backflag = 0
        homeflag = 0
        backreset = 0
        totaltime = 0
        temp = track()
        flag = 0
        helpf = 0
        end = 0
        Biglist = []
        ru = 0
        buttonup = 0
        moves = 0
        lastb = 0

        if bvalue == 1:  # New Game
            buttonslist = list(setbuttons().buttonslist)
            backupbuttonslist = list(buttonslist)
            totaltime = 0
        if bvalue == 0:  # Continue
            with open('score.pkl', 'rb') as input:
                buttonslist = pickle.load(input)
                backup = pickle.load(input)
                backupbuttonslist = pickle.load(input)
                totaltime = pickle.load(input)
                moves = pickle.load(input)

        print moves

        showline = linetrack(buttonslist[0], buttonslist)

        if sound:
            pygame.mixer.Sound("sound/gamestart.ogg").play(0)

        while not crashed:  # MAIN GAME LOOP BEGINS
            # Gtk events
            while gtk.events_pending():
                gtk.main_iteration()
            event = pygame.event.poll()
            totaltime += timer.tick()
            if event.type == pygame.QUIT:
                totaltime += timer.tick()
                with open('score.pkl', 'wb') as output:
                    pickle.dump(buttonslist, output, pickle.HIGHEST_PROTOCOL)
                    pickle.dump(backup, output, pickle.HIGHEST_PROTOCOL)
                    pickle.dump(backupbuttonslist, output,
                                pickle.HIGHEST_PROTOCOL)
                    pickle.dump(totaltime, output, pickle.HIGHEST_PROTOCOL)
                    pickle.dump(moves, output, pickle.HIGHEST_PROTOCOL)

                crashed = True

            mos_x, mos_y = pygame.mouse.get_pos()

            if (not ((mos_x <= 675 + 280) and (mos_x >= 363 + 280) and
                     (mos_y <= 532) and (mos_y >= 225))):
                temp = track()
                vertical = horizontal = rightd = leftd = 0
                lastx = lasty = 0

            gameDisplay.fill(black)
            gameDisplay.blit(background, (0 - 50 + 280, 0 - 140))

            for i in x:  # loop to display all stitches on their respactive positions #
                for j in y:
                    gameDisplay.blit(stitch, (i, j))

            if home.get_rect(center=(270 + 280,
                                     255)).collidepoint(mos_x, mos_y):  # HOME
                gameDisplay.blit(pygame.transform.scale(home, (90, 90)),
                                 (250 + 280, 235))
                if (pygame.mouse.get_pressed())[0] == 1 and homeflag == 0:
                    homeflag = 1
                    if sound:
                        pygame.mixer.stop()
                    with open('score.pkl', 'wb') as output:
                        pickle.dump(buttonslist, output,
                                    pickle.HIGHEST_PROTOCOL)
                        pickle.dump(backup, output, pickle.HIGHEST_PROTOCOL)
                        pickle.dump(backupbuttonslist, output,
                                    pickle.HIGHEST_PROTOCOL)
                        pickle.dump(totaltime, output, pickle.HIGHEST_PROTOCOL)
                        pickle.dump(moves, output, pickle.HIGHEST_PROTOCOL)

                    b = welcome()  # Welcome Screen Call
                    bvalue = b.make(gameDisplay, sound)
                    if bvalue == 1:  # New Game
                        buttonslist = list(setbuttons().buttonslist)
                        backupbuttonslist = list(buttonslist)
                        totaltime = 0
                        lastb = 0
                        backup = []
                        moves = 0
                    if bvalue == 0:  # Continue
                        with open('score.pkl', 'rb') as input:
                            buttonslist = pickle.load(input)
                            backup = pickle.load(input)
                            backupbuttonslist = pickle.load(input)
                            totaltime = pickle.load(input)
                            moves = pickle.load(input)

                    print moves
                    backflag = 0
                    homeflag = 0
                    backreset = 0
                    helpf = 0
                    temp = track()
                    flag = 0
                    Biglist = []
                    lastb = 0
                    buttonup = 0

                    showline = linetrack(buttonslist[0], buttonslist)

                    if sound:
                        pygame.mixer.music.load("sound/gamestart.ogg")
                        pygame.mixer.music.play(0)

                if event.type == pygame.MOUSEBUTTONUP:
                    homeflag = 0
            else:
                gameDisplay.blit(home, (250 + 280, 235))

            if undo.get_rect(center=(270 + 280,
                                     335)).collidepoint(mos_x, mos_y):  # Undo
                gameDisplay.blit(pygame.transform.scale(undo, (90, 90)),
                                 (250 + 280, 315))
                if (pygame.mouse.get_pressed()
                    )[0] == 1 and len(backup) != 0 and backflag == 0:
                    if sound:
                        pygame.mixer.music.load("sound/undo1.ogg")
                        pygame.mixer.music.play(0)

                    for j in backup[len(backup) - 1]:
                        j.flag = 0
                        j.i = 0

                    for i in backup[len(backup) - 1]:
                        buttonslist.append(i)

                    backup.remove(backup[len(backup) - 1])

                    backflag = 1
                    moves -= 1
                    flag = 0

                if event.type == pygame.MOUSEBUTTONUP:
                    backflag = 0
                    flag = 0
            else:
                gameDisplay.blit(undo, (250 + 280, 315))

            if restart.get_rect(center=(270 + 280,
                                        415)).collidepoint(mos_x,
                                                           mos_y):  # Restart
                gameDisplay.blit(pygame.transform.scale(restart, (90, 90)),
                                 (250 + 280, 395))
                if (pygame.mouse.get_pressed())[0] == 1 and backreset == 0:
                    if sound:
                        pygame.mixer.music.load("sound/button.ogg")
                        pygame.mixer.music.play(0)
                    totaltime = 0
                    backup = []
                    backflag = 0
                    temp = track()
                    flag = 0
                    end = 0
                    Biglist = []
                    backreset = 1
                    moves = 0
                    lastb = 0
                    helpf = 0
                    buttonup = 0
                    for j in backupbuttonslist:
                        j.flag = 0
                        j.i = 0
                    buttonslist = list(backupbuttonslist)
                if event.type == pygame.MOUSEBUTTONUP:
                    backreset = 0

            else:
                gameDisplay.blit(restart, (250 + 280, 395))

            if hlp.get_rect(center=(270 + 280,
                                    495)).collidepoint(mos_x, mos_y):  # Help
                gameDisplay.blit(pygame.transform.scale(hlp, (90, 90)),
                                 (250 + 280, 475))
                if (pygame.mouse.get_pressed())[0] == 1 and helpf == 0:
                    if sound:
                        pygame.mixer.music.load("sound/button.ogg")
                        pygame.mixer.music.play(0)
                    ru = rule()
                    ru.make(gameDisplay, sound)
                    helpf = 1

                if event.type == pygame.MOUSEBUTTONUP:
                    helpf = 0
            else:
                gameDisplay.blit(hlp, (250 + 280, 475))

            # BUTTON TRACKING BEGINS......
            for t in buttonslist:
                if t.but.get_rect(center=(t.x_axis + 25, t.y_axis +
                                          25)).collidepoint(mos_x, mos_y):
                    if t.x_axis == lastx and t.y_axis == lasty:
                        break
                    button = t
                    buttoncheck = 1
                    diff = button.x_axis - button.y_axis
                    total = button.x_axis + button.y_axis

                    if (pygame.mouse.get_pressed())[0] == 1 and buttonup == 0:
                        flag = 1
                        if (len(temp.coordinatelist) != 0):
                            # SAME COLOR TEST ###
                            if (button.butno == temp.coordinatelist[
                                    len(temp.coordinatelist) - 1].butno):
                                if ((lastx == button.x_axis)
                                        or (lasty == button.y_axis)
                                        or (lastdiff == diff)
                                        or (lasttotal == total)):
                                    if (lastdiff == diff):
                                        chkf = 0
                                        for chk in buttonslist:
                                            if (chk.x_axis -
                                                    chk.y_axis == diff):
                                                if lasty > button.y_axis and lastx > button.x_axis:
                                                    if (chk.y_axis < lasty and
                                                            chk.x_axis < lastx
                                                        ) and (chk.y_axis >
                                                               button.y_axis
                                                               and chk.x_axis >
                                                               button.x_axis):
                                                        chkf = 1
                                                        break
                                                if lasty < button.y_axis and lastx < button.x_axis:
                                                    if (chk.y_axis > lasty and
                                                            chk.x_axis > lastx
                                                        ) and (chk.y_axis <
                                                               button.y_axis
                                                               and chk.x_axis <
                                                               button.x_axis):
                                                        chkf = 1
                                                        break
                                    elif (lasttotal == total):
                                        chkf = 0
                                        for chk in buttonslist:
                                            if (chk.x_axis +
                                                    chk.y_axis == total):
                                                if lasty > button.y_axis and lastx < button.x_axis:
                                                    if (chk.y_axis < lasty and
                                                            chk.x_axis > lastx
                                                        ) and (chk.y_axis >
                                                               button.y_axis
                                                               and chk.x_axis <
                                                               button.x_axis):
                                                        chkf = 1
                                                        break
                                                if lasty < button.y_axis and lastx > button.x_axis:
                                                    if (chk.y_axis > lasty and
                                                            chk.x_axis < lastx
                                                        ) and (chk.y_axis <
                                                               button.y_axis
                                                               and chk.x_axis >
                                                               button.x_axis):
                                                        chkf = 1
                                                        break
                                    elif (lastx == button.x_axis):
                                        chkf = 0
                                        for chk in buttonslist:
                                            if chk.x_axis == lastx:
                                                if lasty > button.y_axis:
                                                    if (chk.y_axis < lasty and
                                                            chk.x_axis == lastx
                                                        ) and (chk.y_axis >
                                                               button.y_axis
                                                               and chk.x_axis
                                                               == lastx):
                                                        chkf = 1
                                                        break
                                                if lasty < button.y_axis:
                                                    if (chk.y_axis > lasty and
                                                            chk.x_axis == lastx
                                                        ) and (chk.y_axis <
                                                               button.y_axis
                                                               and chk.x_axis
                                                               == lastx):
                                                        chkf = 1
                                                        break
                                    else:
                                        chkf = 0
                                        for chk in buttonslist:
                                            if chk.y_axis == lasty:
                                                if lastx > button.x_axis:
                                                    if (chk.x_axis < lastx and
                                                            chk.y_axis == lasty
                                                        ) and (chk.x_axis >
                                                               button.x_axis
                                                               and chk.y_axis
                                                               == lasty):
                                                        chkf = 1
                                                        break
                                                if lastx < button.x_axis:
                                                    if (chk.x_axis > lastx and
                                                            chk.y_axis == lasty
                                                        ) and (chk.x_axis <
                                                               button.x_axis
                                                               and chk.y_axis
                                                               == lasty):
                                                        chkf = 1
                                                        break
                                    if (vertical == 0 and horizontal == 0
                                            and rightd == 0 and leftd == 0):
                                        if chkf == 0:
                                            if lasttotal == total:
                                                rightd = 1
                                                temp.insert(button)
                                                lastdiff = button.x_axis - button.y_axis
                                                lasttotal = button.x_axis + button.y_axis
                                                lastx = button.x_axis
                                                lasty = button.y_axis
                                            elif lastdiff == diff:
                                                leftd = 1
                                                temp.insert(button)
                                                lastdiff = button.x_axis - button.y_axis
                                                lasttotal = button.x_axis + button.y_axis
                                                lastx = button.x_axis
                                                lasty = button.y_axis
                                            elif lastx == button.x_axis:
                                                vertical = 1
                                                temp.insert(button)
                                                lastdiff = button.x_axis - button.y_axis
                                                lasttotal = button.x_axis + button.y_axis
                                                lastx = button.x_axis
                                                lasty = button.y_axis
                                            else:
                                                horizontal = 1
                                                temp.insert(button)
                                                lastdiff = button.x_axis - button.y_axis
                                                lasttotal = button.x_axis + button.y_axis
                                                lastx = button.x_axis
                                                lasty = button.y_axis
                                        else:
                                            temp = track()
                                            buttonup = 1
                                            vertical = horizontal = rightd = leftd = 0
                                    else:
                                        if (vertical == 1):
                                            if (lastx == button.x_axis):
                                                if chkf == 0:
                                                    temp.insert(button)
                                                    lastdiff = button.x_axis - button.y_axis
                                                    lasttotal = button.x_axis + button.y_axis
                                                    lastx = button.x_axis
                                                    lasty = button.y_axis
                                                else:
                                                    temp = track()
                                                    buttonup = 1
                                                    vertical = horizontal = rightd = leftd = 0

                                        elif (horizontal == 1):
                                            if (lasty == button.y_axis):
                                                if chkf == 0:
                                                    temp.insert(button)
                                                    lastdiff = button.x_axis - button.y_axis
                                                    lasttotal = button.x_axis + button.y_axis
                                                    lastx = button.x_axis
                                                    lasty = button.y_axis
                                                else:
                                                    temp = track()
                                                    buttonup = 1
                                                    vertical = horizontal = rightd = leftd = 0

                                        elif (leftd == 1):
                                            if (lastdiff == diff):
                                                if chkf == 0:
                                                    temp.insert(button)
                                                    lastdiff = button.x_axis - button.y_axis
                                                    lasttotal = button.x_axis + button.y_axis
                                                    lastx = button.x_axis
                                                    lasty = button.y_axis
                                                else:
                                                    temp = track()
                                                    buttonup = 1
                                                    vertical = horizontal = rightd = leftd = 0
                                        else:
                                            if (lasttotal == total):
                                                if chkf == 0:
                                                    temp.insert(button)
                                                    lastdiff = button.x_axis - button.y_axis
                                                    lasttotal = button.x_axis + button.y_axis
                                                    lastx = button.x_axis
                                                    lasty = button.y_axis
                                                else:
                                                    temp = track()
                                                    buttonup = 1
                                                    vertical = horizontal = rightd = leftd = 0

                            else:  # to nullify the tracking if  other buttons are encountered in path
                                temp = track()
                                buttonup = 1
                                vertical = horizontal = rightd = leftd = 0
                                lastx = lasty = 0
                        else:
                            if sound:
                                pygame.mixer.music.load("sound/cbut.ogg")
                                pygame.mixer.music.play(0)
                            temp.insert(button)
                            lastdiff = button.x_axis - button.y_axis
                            lasttotal = button.x_axis + button.y_axis
                            lastx = button.x_axis
                            lasty = button.y_axis
                            showline = linetrack(temp.coordinatelist[0],
                                                 buttonslist)

                            vertical = horizontal = rightd = leftd = 0

            if flag == 1:
                if (pygame.mouse.get_pressed())[0] == 0:
                    if (len(temp.coordinatelist) != 0):
                        if (t.x_axis == temp.coordinatelist[0].x_axis
                                and t.y_axis == temp.coordinatelist[0].y_axis):
                            temp = track()
                            vertical = horizontal = rightd = leftd = 0

                    if (len(temp.coordinatelist) == 1):
                        temp = track()
                        vertical = horizontal = rightd = leftd = 0
                        flag = 0

                    if (len(temp.coordinatelist) > 1
                            and len(buttonslist) != 0):
                        for j in temp.coordinatelist:
                            buttonslist.remove(j)
                        lastbackup = list(temp.coordinatelist)
                        backup.append(list(temp.coordinatelist))
                        temp2 = scissorrun(list(temp.coordinatelist))
                        Biglist.append(temp2)
                    flag = 0
                    temp = track()
                    buttonup = 0
                    lastx = lasty = 0
                    vertical = horizontal = rightd = leftd = 0

            if (len(temp.coordinatelist) != 0):  # White Circle Blitting
                temp.display(gameDisplay)

            # Button Display List
            for i in range(len(buttonslist)):  # Non Movable Buttons
                buttonslist[i].display(gameDisplay)

            if flag == 1:  # White line display
                showline.displayline(gameDisplay)

            if (len(Biglist) != 0):
                for j in Biglist:  # Movable Buttons
                    if j.sentcoordinatelist[j.length - 1].y_axis + (
                            0.2 *
                        (j.sentcoordinatelist[j.length - 1].i**2)) > 620:
                        # checklist=j
                        Biglist.remove(j)
                        moves += 1
                        if len(buttonslist) == 0 and len(Biglist) == 0:
                            end = 1
                        continue
                    j.display(gameDisplay)

            if len(buttonslist) == 0 and end == 1:
                b = scores()
                b = b.make(gameDisplay, totaltime, moves, sound)
                if b == 1:
                    buttonslist = list(setbuttons().buttonslist)
                    backupbuttonslist = list(buttonslist)
                    totaltime = 0
                    backup = []
                    backflag = 0
                    homeflag = 0
                    backreset = 0
                    totaltime = 0
                    temp = track()
                    moves = 0
                    flag = 0
                    end = 0
                    Biglist = []
                    lastb = 0
                    helpf = 0
                    buttonup = 0
                    showline = linetrack(buttonslist[0], buttonslist)

                    if sound:
                        pygame.mixer.music.load("sound/gamestart.ogg")
                        pygame.mixer.music.play(0)
                if b == 2:
                    totaltime = 0
                    backup = []
                    backflag = 0
                    helpf = 0
                    temp = track()
                    flag = 0
                    end = 0
                    Biglist = []
                    lastb = 0
                    backreset = 1
                    moves = 0
                    buttonup = 0
                    for j in backupbuttonslist:
                        j.flag = 0
                        j.i = 0
                    buttonslist = list(backupbuttonslist)
                    if sound:
                        pygame.mixer.music.load("sound/gamestart.ogg")
                        pygame.mixer.music.play(0)

            pygame.display.update()
            clock.tick(50)

            if crashed == True:  # Game crash or Close check
                pygame.quit()
                sys.exit()

        # Just a window exception check condition
        event1 = pygame.event.get()
        if event1.type == pygame.QUIT:
            crashed = True

        if crashed == True:
            pygame.quit()
            sys.exit()
Beispiel #33
0
    def run(self):
        self.ksHandler = makeVersion()

        if self.file:
            self.parser = KickstartParser(self.ksHandler)

            msg = None

            try:
                self.parser.readKickstart(self.file)
            except (KickstartParseError, KickstartValueError) as e:
                msg = _("The following error was found while parsing your "
                        "kickstart configuration:\n\n%s" % e)
            except KickstartError:
                msg = _(
                    "The kickstart file %s could not be opened.") % self.file

            if msg:
                dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR,
                                        gtk.BUTTONS_OK, msg)
                dlg.set_title(_("Error Parsing Kickstart Config"))
                dlg.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
                dlg.set_modal(True)
                dlg.run()
                dlg.destroy()
                sys.exit(0)

        self.xml = xml
        name_tag = (_("Kickstart"))
        comment_tag = (_("Create a kickstart file"))

        self.toplevel = xml.get_widget("main_window")
        self.toplevel.connect("destroy", self.destroy)
        self.toplevel.set_icon(iconPixbuf)

        #bring in widgets from glade file
        self.options_notebook = xml.get_widget("options_notebook")
        self.install_radiobutton = xml.get_widget("install_radiobutton")
        self.category_clist = xml.get_widget("category_clist")
        self.open_menu = xml.get_widget("open_menu")
        self.preview_menu = xml.get_widget("preview_menu")
        self.save_menu = xml.get_widget("save_menu")
        self.quit_menu = xml.get_widget("quit_menu")
        self.about_menu = xml.get_widget("about_menu")

        #populate category list
        self.category_view = xml.get_widget("list_view")
        self.category_store = gtk.ListStore(gobject.TYPE_STRING)
        self.category_view.set_model(self.category_store)

        col = gtk.TreeViewColumn(_("Subsection"),
                                 gtk.CellRendererText(),
                                 text=0)
        col.set_sort_column_id(0)
        self.category_view.append_column(col)

        self.category_list = [(_("Basic Configuration")),
                              (_("Installation Method")),
                              (_("Boot Loader Options")),
                              (_("Partition Information")),
                              (_("Network Configuration")),
                              (_("Authentication")),
                              (_("Firewall Configuration")),
                              (_("Display Configuration")),
                              (_("Package Selection")),
                              (_("Pre-Installation Script")),
                              (_("Post-Installation Script"))]

        for item in self.category_list:
            iter = self.category_store.append()
            self.category_store.set_value(iter, 0, item)

#bring in basic functions
        self.basic_class = basic.basic(self, xml, self.options_notebook,
                                       self.ksHandler)

        # Now that we've loaded the UI elements for the first active thing in the notebook,
        # draw it so we can display a progress bar when yum starts doing stuff.
        self.toplevel.show()
        while gtk.events_pending():
            gtk.main_iteration()

        self.bootloader_class = bootloader.bootloader(xml,
                                                      self.options_notebook,
                                                      self.ksHandler)
        self.install_class = install.install(self, xml, self.category_store,
                                             self.category_view,
                                             self.options_notebook,
                                             self.ksHandler)
        self.partition_class = partition.partition(xml, self.ksHandler)
        self.network_class = network.network(xml, self.ksHandler)
        self.auth_class = auth.auth(xml, self.ksHandler)
        self.firewall_class = firewall.Firewall(xml, self.ksHandler)
        self.X_class = xconfig.xconfig(xml, self.ksHandler)
        self.progress_window = progressWindow.ProgressWindow(self.toplevel)
        self.packages_class = packages.Packages(xml, self.ksHandler,
                                                self.progress_window)
        self.scripts_class = scripts.scripts(xml, self.ksHandler)

        self.open_menu.connect("activate", self.on_activate_open)
        self.preview_menu.connect("activate", self.on_activate_preview_options)
        self.save_menu.connect("activate", self.on_activate_save_options)
        self.quit_menu.connect("activate", gtk.main_quit)
        self.about_menu.connect("activate", self.on_about_activate)
        self.category_view.connect("cursor_changed",
                                   self.on_list_view_row_activated)
        self.options_notebook.connect("switch-page", self.on_notebook_changed)

        #show gui
        self.applyKickstart()
        self.toplevel.show()

        gtk.main()
 def progressNotify(self):
     "A callback to the interface while events are pending"
     import gtk, pygtk
     while gtk.events_pending():
         gtk.main_iteration(False)
Beispiel #35
0
 def mySetArrowCursor():
     cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR)
     self.mainWin.window.set_cursor(cursor)
     while gtk.events_pending():
         gtk.main_iteration(False)
Beispiel #36
0
 def mySetBusyCursor():
     cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
     self.mainWin.window.set_cursor(cursor)
     while gtk.events_pending():
         gtk.main_iteration(False)
Beispiel #37
0
def update():
    """Refreshes GTK """
    while gtk.events_pending():
        gtk.main_iteration(False)
Beispiel #38
0
    new_x = xp + o
    w.set_geometry('current', 'x', new_x, yp, wp, hp)
    if m:
        w.maximize_horizontally()


def on_key_press_event(widget, event):

    return


if __name__ == "__main__":
    default = wnck.screen_get_default()

    while gtk.events_pending():
        gtk.main_iteration(False)

    top = [None, None]
    inactive_display = 0
    window_list = default.get_windows_stacked()
    active_win = None
    offset = 0
    if len(window_list) == 0:
        pass
    else:
        for win in window_list:
            xp, yp, wp, hp = win.get_geometry()
            if win.is_most_recently_activated():
                if xp < 1920:
                    inactive_display = 1
                    offset = 1920
Beispiel #39
0
class pane3window:
    def run(self, gameDisplay, info):

        crashed = False
        orientation1 = 0
        orientation2 = 0
        orientation3 = 0
        orientation4 = 0
        orientation5 = 0
        orientation6 = 0

        leftmove = 350
        midmove = 555
        rightmove = 761

        limit1 = limit2 = 0

        leftman = pygame.image.load("data/images/man.png")
        rightman = pygame.transform.flip(leftman, True, False)
        background = pygame.image.load("data/images/3pane.png")
        lspike = pygame.image.load("data/images/Spike.png")
        rspike = pygame.transform.flip(lspike, True, False)
        background = pygame.transform.scale(background, (600, info.current_h))
        y_axis1 = 700
        y_axis2 = y_axis1 + 370

        y_axisa = 750
        y_axisb = y_axisa + 370

        y_axisx = 761
        y_axisy = y_axisx + 370

        leftquad = leftman
        midquad = leftman
        rightquad = leftman

        f1 = f2 = f3 = 0
        m1 = m2 = m3 = 0
        time1 = time2 = 0

        font_path = "fonts/arial.ttf"
        font_size = 50
        font1 = pygame.font.Font(font_path, font_size)
        score = 0

        x_axis1 = x_axis2 = 350
        x_axisa = x_axisb = 659
        x_axisx = x_axisy = 761
        speed = 7
        flag = 1

        black = (0, 0, 0)
        white = (255, 255, 255)
        clock = pygame.time.Clock()
        timer = pygame.time.Clock()

        sound = True
        try:
            pygame.mixer.init()
        except Exception, err:
            sound = False
            print 'error with sound', err

        jump = pygame.mixer.Sound("data/sound/jump.wav")
        scoremusic = pygame.mixer.Sound("data/sound/score.wav")
        collide = pygame.mixer.Sound("data/sound/fall.wav")

        while not crashed:
            # Gtk events

            while gtk.events_pending():
                gtk.main_iteration()
            event = pygame.event.poll()
            # totaltime+=timer.tick()
            if event.type == pygame.QUIT:
                # totaltime+=timer.tick()
                crashed = True

            gameDisplay.fill(black)
            gameDisplay.blit(background, (0 + 350, 0))

            # Keypress orientation change

            if event.type == pygame.KEYDOWN and event.key == 276 and f1 == 0:
                jump.play(0)
                f1 = 1
                m1 = 1  # start moving

            if event.type == pygame.KEYDOWN and event.key == 274 and f2 == 0:
                jump.play(0)
                f2 = 1
                m2 = 1  # start moving

            if event.type == pygame.KEYDOWN and event.key == 275 and f3 == 0:
                jump.play(0)
                f3 = 1
                m3 = 1  # start moving

            # Check for when to stop

            if leftmove > 484 + 20:  # left move
                leftquad = rightman
                m1 = f1 = 0
                leftmove = 484 + 20
                time1 = 0

            if leftmove < 350:
                leftquad = leftman
                m1 = f1 = 0
                leftmove = 350
                time1 = 0

            if midmove < 555:  # mid move
                midquad = leftman
                m2 = f2 = 0
                midmove = 555
                time2 = 0

            if midmove > 690 + 20:
                midquad = rightman
                m2 = f2 = 0
                midmove = 690 + 20
                time2 = 0

            if rightmove < 761:  # right move move
                rightquad = leftman
                m3 = f3 = 0
                rightmove = 761
                time2 = 0

            if rightmove > 761 + 156:
                rightquad = rightman
                m3 = f3 = 0
                rightmove = 761 + 156
                time2 = 0

            if m1 == 1:

                if leftquad == leftman:
                    leftmove += 30
                if leftquad == rightman:
                    leftmove -= 30
                time1 += 1

            if m2 == 1:

                if midquad == leftman:
                    midmove += 30
                if midquad == rightman:
                    midmove -= 30
                time2 += 1

            if m3 == 1:

                if rightquad == leftman:
                    rightmove += 30
                if rightquad == rightman:
                    rightmove -= 30
                time2 += 1

            #[350,608]   [659, 916]

            # Guy Display

            if leftquad == leftman or leftquad == rightman:
                gameDisplay.blit(leftquad, (leftmove, 100))

            if midquad == leftman or midquad == rightman:
                gameDisplay.blit(midquad, (midmove, 100))

            if rightquad == leftman or rightquad == rightman:
                gameDisplay.blit(rightquad, (rightmove, 100))

            ######### SPIKE PART###########

            if orientation1 == 0:  # orientation change
                x_axis1 = 350
                gameDisplay.blit(lspike, (x_axis1, y_axis1))

            if orientation1 == 1:
                x_axis1 = 485
                gameDisplay.blit(rspike, (x_axis1, y_axis1))

            if orientation2 == 0:
                x_axis2 = 350
                gameDisplay.blit(lspike, (x_axis2, y_axis2))

            if orientation2 == 1:
                x_axis2 = 485
                gameDisplay.blit(rspike, (x_axis2, y_axis2))

            # mid side spikes
            if orientation3 == 0:
                x_axisa = 555
                gameDisplay.blit(lspike, (x_axisa, y_axisa))

            if orientation3 == 1:
                x_axisa = 691
                gameDisplay.blit(rspike, (x_axisa, y_axisa))

            if orientation4 == 0:
                x_axisb = 555
                gameDisplay.blit(lspike, (x_axisb, y_axisb))

            if orientation4 == 1:
                x_axisb = 691
                gameDisplay.blit(rspike, (x_axisb, y_axisb))

            # right side spikes

            if orientation5 == 0:
                x_axisx = 761
                gameDisplay.blit(lspike, (x_axisx, y_axisx))

            if orientation5 == 1:
                x_axisx = 761 + 136
                gameDisplay.blit(rspike, (x_axisx, y_axisx))

            if orientation6 == 0:
                x_axisy = 761
                gameDisplay.blit(lspike, (x_axisy, y_axisy))

            if orientation6 == 1:
                x_axisy = 761 + 136
                gameDisplay.blit(rspike, (x_axisy, y_axisy))

            y_axis1 -= speed
            y_axis2 -= speed

            y_axisa -= speed
            y_axisb -= speed

            y_axisx -= speed
            y_axisy -= speed
            '''
            
            if score==15 or score==45 or score==70:
                flag=1
            
            if score==15 and flag==1 :
                flag=0
                speed+=0.1
              
            if score==45 and flag==1:
                flag=0
                speed+=0.1
              
            if score==70 and flag==1:
                flag=0
                speed+=0.1
            '''

            if y_axis1 <= -40 or y_axis2 <= -40 or y_axisa <= -40 or y_axisb <= -40 or \
               y_axisx <= -40 or y_axisy <= -40:
                scoremusic.play(0)
                score += 1

            if (y_axis1 < -40):
                orientation1 = randint(0, 1)

                y_axis1 = 700

            if (y_axis2 < -40):
                orientation2 = randint(0, 1)

                y_axis2 = 700

            if (y_axisa < -40):
                orientation3 = randint(0, 1)

                y_axisa = 700

            if (y_axisb < -40):
                orientation4 = randint(0, 1)

                y_axisb = 700

            if (y_axisx < -40):
                orientation5 = randint(0, 1)

                y_axisx = 700

            if (y_axisy < -40):
                orientation6 = randint(0, 1)

                y_axisy = 700

            scores = font1.render(str(score), 1, (0, 0, 0))
            gameDisplay.blit(scores, (200 + 650, 30))

            if leftquad.get_rect(center=(leftmove + 5, 100 + 10)).collidepoint(x_axis1 + 8, y_axis1) \
                    or leftquad.get_rect(center=(leftmove + 5, 100 + 10)).collidepoint(x_axis2 + 8, y_axis2):
                pygame.mixer.music.load("data/sound/fall.wav")
                pygame.mixer.music.play(0)
                # collide.play(0)
                return score

            if midquad.get_rect(center=(midmove + 5, 100 + 10)).collidepoint(x_axisa + 8, y_axisa) \
                    or midquad.get_rect(center=(midmove + 5, 100 + 10)).collidepoint(x_axisb + 8, y_axisb):
                pygame.mixer.music.load("data/sound/fall.wav")
                pygame.mixer.music.play(0)
                # collide.play(0)
                return score

            if rightquad.get_rect(center=(rightmove + 5, 100 + 10)).collidepoint(x_axisx + 8, y_axisx) \
                    or rightquad.get_rect(center=(rightmove + 5, 100 + 10)).collidepoint(x_axisy + 8, y_axisy):
                pygame.mixer.music.load("data/sound/fall.wav")
                pygame.mixer.music.play(0)
                # collide.play(0)
                return score

            pygame.display.update()
            clock.tick(60)

            if crashed == True:  # Game crash or Close check
                pygame.quit()
                sys.exit()

        # Just a window exception check condition

        event1 = pygame.event.get()
        if event1.type == pygame.QUIT:
            crashed = True

        if crashed == True:
            pygame.quit()
            sys.exit()
Beispiel #40
0
    def renumber_annotations(self, m, at):
        """Renumber all annotations of a given type.
        """
        d = gtk.Dialog(title=_("Renumbering annotations of type %s") %
                       self.get_title(at),
                       parent=None,
                       flags=gtk.DIALOG_DESTROY_WITH_PARENT,
                       buttons=(
                           gtk.STOCK_CANCEL,
                           gtk.RESPONSE_CANCEL,
                           gtk.STOCK_OK,
                           gtk.RESPONSE_OK,
                       ))
        l = gtk.Label()
        l.set_markup(
            _("<b>Renumber all annotations according to their order.</b>\n\n<i>Note that this action cannot be undone.</i>\nReplace the first numeric value of the annotation content with the new annotation number.\nIf no numeric value is found and the annotation is structured, it will insert the number.\nIf no numeric value is found and the annotation is of type text/plain, it will overwrite the annotation content.\nThe offset parameter allows you to renumber from a given annotation."
              ))
        l.set_line_wrap(True)
        l.show()
        d.vbox.add(l)

        hb = gtk.HBox()
        l = gtk.Label(_("Offset"))
        hb.pack_start(l, expand=False)
        s = gtk.SpinButton()
        s.set_range(1, len(at.annotations))
        s.set_value(1)
        s.set_increments(1, 5)
        hb.add(s)
        d.vbox.pack_start(hb, expand=False)

        d.connect('key-press-event', dialog.dialog_keypressed_cb)
        d.show_all()
        dialog.center_on_mouse(d)

        res = d.run()
        if res == gtk.RESPONSE_OK:
            re_number = re.compile('(\d+)')
            re_struct = re.compile('^num=(\d+)$', re.MULTILINE)
            offset = s.get_value_as_int() - 1
            l = at.annotations
            l.sort(key=lambda a: a.fragment.begin)
            l = l[offset:]
            size = float(len(l))
            dial = gtk.Dialog(
                _("Renumbering %d annotations") % size, None,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
            prg = gtk.ProgressBar()
            dial.vbox.pack_start(prg, expand=False)
            dial.show_all()

            for i, a in enumerate(l[offset:]):
                prg.set_text(_("Annotation #%d") % i)
                prg.set_fraction(i / size)
                while gtk.events_pending():
                    gtk.main_iteration()

                if a.type.mimetype == 'application/x-advene-structured':
                    if re_struct.search(a.content.data):
                        # A 'num' field is present. Update it.
                        data = re_struct.sub("num=%d" % (i + 1),
                                             a.content.data)
                    else:
                        # Insert the num field
                        data = ("num=%d\n" % (i + 1)) + a.content.data
                elif re_number.search(a.content.data):
                    # There is a number. Simply substitute the new one.
                    data = re_number.sub(str(i + 1), a.content.data)
                elif a.type.mimetype == 'text/plain':
                    # Overwrite the contents
                    data = str(i + 1)
                else:
                    data = None
                if data is not None and a.content.data != data:
                    a.content.data = data
            self.controller.notify('PackageActivate',
                                   package=self.controller.package)
            dial.destroy()

        d.destroy()
        return True
 def send_data(self, data):
     for i in range(0, len(data)):
         ser.write(data[i])
         time.sleep(0.1)
         while gtk.events_pending():
             gtk.main_iteration()
Beispiel #42
0
def akkumatik_command(string, what):
    """ Send a Command to the Akkumatik """
    def serial_send_command(tname, com_str, retry_count):  #{{{
        """ Send command and wait for Ack (or not) """

        retry_count += 1
        if retry_count > (cfg.COMMAND_RETRY):
            cfg.COMMAND_ABORT = True  #skip on further soon to arrive commands
            return

        if retry_count == (cfg.COMMAND_RETRY):
            failed_string = " Failed"
            failed_color = "#cc6666"
        else:
            failed_string = " Resend"
            failed_color = "#cccccc"

        try:
            cfg.SER.write(com_str)
        except serial.SerialException, err:
            tmp = "%s" % err
            tmp += ":" + com_str + ", " + tname
            print(tmp)
            cfg.FLOG.write(tmp)
            gtk_stuff.message_dialog(None, tmp)

        okk = False
        i = 0
        #Status
        if len(tname) > 6:
            tname = tname[:6]
        label_txt = "[%-5s]: " % (tname)

        cfg.EVENT_BOX_LSTATUS.modify_bg(gtk.STATE_NORMAL, \
                cfg.EVENT_BOX_LSTATUS.get_colormap().alloc_color("#cccccc"))

        cfg.LABEL_STATUS.show()
        cfg.LABEL_STATUS.set_text(label_txt)
        while gtk.events_pending():
            gtk.main_iteration()
        while i < 50:
            time.sleep(0.08)
            label_txt += "."
            cfg.LABEL_STATUS.set_text(label_txt)
            while gtk.events_pending():
                gtk.main_iteration()
            i += 1
            #put on True before sending. - here waiting for False
            if cfg.COMMAND_WAIT == False:
                okk = True
                #Status
                label_txt += " OK"
                cfg.EVENT_BOX_LSTATUS.modify_bg(gtk.STATE_NORMAL, \
                   cfg.EVENT_BOX_LSTATUS.get_colormap().alloc_color("#66cc66"))
                cfg.LABEL_STATUS.set_text(label_txt)
                while gtk.events_pending():
                    gtk.main_iteration()
                time.sleep(2.0)
                break

        if okk == False:
            #Status
            cfg.EVENT_BOX_LSTATUS.modify_bg(gtk.STATE_NORMAL, \
                    cfg.EVENT_BOX_LSTATUS.get_colormap().alloc_color(failed_color))
            label_txt += failed_string
            cfg.LABEL_STATUS.set_text(label_txt)
            while gtk.events_pending():
                gtk.main_iteration()
            time.sleep(2.0)
            serial_send_command(tname, com_str, retry_count)

        cfg.LABEL_STATUS.hide()
Beispiel #43
0
def repaintGui():
    # Force repaint: ugly, but gui gets repainted so fast that gtk objects don't show it
    while gtk.events_pending():
        gtk.main_iteration(False)
Beispiel #44
0
 def flush_events(self):
     gtk.gdk.threads_enter()
     while gtk.events_pending():
         gtk.main_iteration(True)
     gtk.gdk.flush()
     gtk.gdk.threads_leave()
Beispiel #45
0
 def ui_callback(progress):
     self.view["gen_progress_bar"].set_fraction(progress)
     while gtk.events_pending():
         gtk.main_iteration()
Beispiel #46
0
 def __wait_connection(self, event, progressbar):
     while not event.isSet():
         progressbar.pulse()
         event.wait(0.1)
         while gtk.events_pending():
             gtk.main_iteration(False)
Beispiel #47
0
def wait():
   while gtk.events_pending():
         gtk.main_iteration()
Beispiel #48
0
    def run(self, *args):
        """Make the deformation."""
        self.output.set_text("")
        if not self.setup_atoms():
            return
        deform_axes = self.get_deformation_axes()
        if deform_axes is False:
            return  #Nothing to do!

        # Prepare progress bar
        if self.radio_relax_on.get_active():
            fmax = self.fmax.value
            mininame = self.minimizers[self.algo.get_active()]
            self.begin(mode="scale/min",
                       algo=mininame,
                       fmax=fmax,
                       steps=self.steps.value,
                       scalesteps=self.nsteps.value)
        else:
            self.begin(mode="scale", scalesteps=self.nsteps.value)
        try:
            logger_func = self.gui.simulation['progress'].get_logger_stream
        except (KeyError, AttributeError):
            logger = None
        else:
            logger = logger_func()  # Don't catch errors in the function.

        # Display status message
        self.status_label.set_text(_("Running ..."))
        self.status_label.modify_fg(gtk.STATE_NORMAL,
                                    gtk.gdk.color_parse('#AA0000'))
        while gtk.events_pending():
            gtk.main_iteration()

        # Do the scaling
        scale = self.max_scale.value
        if self.pull.get_active():
            steps = np.linspace(0, scale, self.nsteps.value)
        else:
            steps = np.linspace(-scale, scale, self.nsteps.value)
            steps += self.scale_offset.value
        undef_cell = self.atoms.get_cell()
        results = []
        #txt = "Strain\t\tEnergy [eV]\n"
        txt = ""
        # If we load all configurations, prepare it.
        if self.radio_results_all.get_active():
            self.prepare_store_atoms()

        stored_atoms = False
        try:
            # Now, do the deformation
            for i, d in enumerate(steps):
                deformation = np.diag(1.0 + d * deform_axes)
                self.atoms.set_cell(np.dot(undef_cell, deformation),
                                    scale_atoms=True)
                if self.gui.simulation.has_key('progress'):
                    self.gui.simulation['progress'].set_scale_progress(i)
                if self.radio_relax_on.get_active():
                    algo = getattr(ase.optimize, mininame)
                    if mininame == "MDMin":
                        minimizer = algo(self.atoms,
                                         logfile=logger,
                                         dt=self.mdmin_dt.value)
                    else:
                        minimizer = algo(self.atoms, logfile=logger)
                    minimizer.run(fmax=fmax, steps=self.steps.value)
                e = self.atoms.get_potential_energy()
                results.append((d, e))
                txt = txt + ("%.5f\t\t%.5f\n" % (d, e))
                self.output.set_text(txt)
                if self.radio_results_all.get_active():
                    self.store_atoms()
                    stored_atoms = True
        except AseGuiCancelException:
            # Update display to reflect cancellation of simulation.
            self.status_label.set_text(_("Calculation CANCELLED."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))
        except MemoryError:
            self.status_label.set_text(
                _("Out of memory, consider using "
                  "LBFGS instead"))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#AA4000'))

        else:
            # Update display to reflect succesful end of simulation.
            self.status_label.set_text(_("Calculation completed."))
            self.status_label.modify_fg(gtk.STATE_NORMAL,
                                        gtk.gdk.color_parse('#007700'))

        if results:
            self.do_fit(np.array(results))
            if self.radio_results_optimal.get_active():
                if self.minimum_ok:
                    deformation = np.diag(1.0 + self.x0 * deform_axes)
                    self.atoms.set_cell(np.dot(undef_cell, deformation),
                                        scale_atoms=True)
                    if self.radio_relax_on.get_active():
                        if self.gui.simulation.has_key('progress'):
                            self.gui.simulation['progress'].set_scale_progress(
                                len(steps))
                        algo = getattr(ase.optimize, mininame)
                        minimizer = algo(self.atoms, logfile=logger)
                        minimizer.run(fmax=fmax, steps=self.steps.value)
                    # Store the optimal configuration.
                    self.prepare_store_atoms()
                    self.store_atoms()
                    stored_atoms = True
                else:
                    oops(_("No trustworthy minimum: Old configuration kept."))
            self.activate_output()
            if stored_atoms:
                self.gui.notify_vulnerable()
        self.end()

        # If we store all configurations: Open movie window and energy graph
        if stored_atoms and self.gui.images.nimages > 1:
            self.gui.movie()
            assert not np.isnan(self.gui.images.E[0])
            if not self.gui.plot_graphs_newatoms():
                expr = 'i, e - E[-1]'
                self.gui.plot_graphs(expr=expr)
            # Continuations should use the best image
            nbest = np.argmin(np.array(results)[:, 1])
            self.start_nth_adj.value = nbest
Beispiel #49
0
def _flush_interface():
    """ Sometimes we need to 'flush' interface, so that the dialog has some
    time to disaperar before we send a blocking command to the printer
    """
    while gtk.events_pending():
        gtk.main_iteration()
Beispiel #50
0
 def idle_func(self):
     while gtk.events_pending():
         gtk.main_iteration()
 def _force_update(self):
     # This is necessary for the GTK progress bar to be updated properly.
     # See http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp
     while gtk.events_pending():
         gtk.main_iteration()
Beispiel #52
0
    def run(self):

        black = (0, 0, 0)
        white = (255, 255, 255)
        clock = pygame.time.Clock()

        crashed = False

        # image load

        land = pygame.image.load("assets/land.png").convert()
        land1 = pygame.transform.scale(land, (490, 150))
        land2 = land1

        sky = pygame.image.load("assets/sky.png").convert()
        sky = pygame.transform.scale(sky, (490, 200))

        skyfill = pygame.image.load("assets/skyfill.png").convert()
        skyfill = pygame.transform.scale(skyfill, (490, 500))

        scoreboard = pygame.image.load("assets/scoreboard.png")
        scoreboard = pygame.transform.scale(scoreboard, (360, 450))

        land1x = 350
        land2x = 840

        replay = pygame.image.load("assets/replay.png")
        replay = pygame.transform.scale(replay, (150, 90))

        rules = pygame.image.load("assets/splash.png")

        font2 = pygame.font.Font("fonts/Arimo.ttf", 25)

        flag = 1

        birds = bird()

        button = pygame.image.load("assets/button.png")
        logo = pygame.image.load("assets/logo.png")
        logo = pygame.transform.scale(logo, (280, 80))

        # GAME LOOP BEGINS !!!

        while not crashed:
            # Gtk events

            while gtk.events_pending():
                gtk.main_iteration()
            for event in pygame.event.get():
                # totaltime+=timer.tick()
                if event.type == pygame.QUIT:
                    crashed = True

                if event.type == pygame.KEYDOWN and event.key == 273:
                    return

            # print "help"
            mos_x, mos_y = pygame.mouse.get_pos()

            self.gameDisplay.fill(white)

            self.gameDisplay.blit(skyfill, (350, 0))
            self.gameDisplay.blit(sky, (350, 400))

            # Platform blit
            self.gameDisplay.blit(land1, (land1x, 600))
            self.gameDisplay.blit(land2, (land2x, 600))

            land1x -= 3
            land2x -= 3

            if (land1x <= -140):
                land1x = 837

            if (land2x <= -140):
                land2x = 837

            # bird display

            birds.display(self.gameDisplay, flag)

            self.gameDisplay.blit(rules, (500, 140))
            self.gameDisplay.blit(button, (700, 330))

            head3 = font2.render(_("Use this button ->"), 1, (white))
            self.gameDisplay.blit(head3, (480, 320))

            head3 = font2.render(_("to play the game"), 1, (white))
            self.gameDisplay.blit(head3, (480, 340))

            self.gameDisplay.blit(logo, (455, 30))

            # left and right black background patches

            pygame.draw.rect(self.gameDisplay, black, (0, 0, 350, 768))

            pygame.draw.rect(self.gameDisplay, black, (840, 0, 693, 768))

            pygame.display.update()
            clock.tick(60)

            if crashed:  # Game crash or Close check
                pygame.quit()
                sys.exit()

        # Just a window exception check condition

        event1 = pygame.event.get()
        if event1.type == pygame.QUIT:
            crashed = True

        if crashed:
            pygame.quit()
            sys.exit()
Beispiel #53
0
 def preview_array(self, event):
     if self.xCEntry.get_text():
         columns = int(self.xCEntry.get_text())
     else:
         columns = 0
     if self.yCEntry.get_text():
         rows = int(self.yCEntry.get_text())
     else:
         rows = 0
     if self.xOEntry.get_text():
         xOffset = float(self.xOEntry.get_text())
     else:
         xOffset = 0
     if self.yOEntry.get_text():
         yOffset = float(self.yOEntry.get_text())
     else:
         yOffset = 0
     if columns > 0 and rows > 0 and (columns == 1 or
                                      (columns > 1 and xOffset <> 0)) and (
                                          rows == 1 or
                                          (rows > 1 and yOffset <> 0)):
         self.fCode = '{}/array_code.ngc'.format(self.tmpDir)
         if self.shapeMode:
             fPre = '{}/array_preamble.ngc'.format(self.tmpDir)
             fPst = '{}/array_postamble.ngc'.format(self.tmpDir)
             outCod = open(self.fCode, 'w')
             outPre = open(fPre, 'w')
             outPst = open(fPst, 'w')
             inWiz = open(self.fOriginal, 'r')
             while (1):
                 d = inWiz.readline()
                 if d.startswith('(wizard'):
                     outCod.write(d)
                     break
                 outPre.write(d)
             while (1):
                 d = inWiz.readline()
                 if d.startswith('(postamble'):
                     outPst.write(d)
                     break
                 outCod.write(d)
             while (1):
                 d = inWiz.readline()
                 if not d: break
                 outPst.write(d)
             outCod.close()
             outPre.close()
             outPst.close()
             inWiz.close()
             self.fNgc = '{}/array.ngc'.format(self.tmpDir)
             outNgc = open(self.fNgc, 'w')
             inPre = open(fPre, 'r')
             for line in inPre:
                 outNgc.write(line)
             inPre.close()
             for row in range(rows):
                 for column in range(columns):
                     outNgc.write('\n(row:{}  column:{})\n'.format(
                         row + 1, column + 1))
                     inCod = open(self.fCode, 'r')
                     for line in inCod:
                         raw = line.strip().lower()
                         if raw.startswith('g0') or raw.startswith(
                                 'g1') or raw.startswith(
                                     'g2') or raw.startswith('g3'):
                             a, b = raw.split('x')
                             c, d = b.split('y')
                             if ('i') in d:
                                 e, f = d.split('i')
                                 f = 'i' + f
                             else:
                                 e = d
                                 f = ''
                             outNgc.write('{}x{} y{} {}\n'.format(
                                 a,
                                 float(c) + column * xOffset,
                                 float(e) + row * yOffset, f))
                         else:
                             outNgc.write(line)
                     inCod.close()
             inPst = open(fPst, 'r')
             for line in inPst:
                 outNgc.write(line)
             inPst.close()
             outNgc.close()
             self.load_file(self.fNgc)
         else:
             self.s.poll()
             mUnits = self.s.linear_units
             if self.previewed:
                 md = gtk.MessageDialog(self.W,
                                        gtk.DIALOG_DESTROY_WITH_PARENT,
                                        gtk.MESSAGE_INFO, gtk.BUTTONS_NONE,
                                        'ARRAY\n\nCalculating.....')
                 md.set_keep_above(True)
                 md.set_position(gtk.WIN_POS_CENTER_ALWAYS)
                 md.set_default_size(200, 100)
                 md.show_all()
                 self.c.program_open(self.fOriginal)
                 watchdog = time.time() + 5
                 while (1):
                     self.s.poll()
                     if os.path.basename(self.s.file) == os.path.basename(
                             self.fOriginal):
                         n = time.time() + 1
                         while (1):
                             if time.time() > n:
                                 break
                             while gtk.events_pending():
                                 gtk.main_iteration()
                         break
                     if time.time() > watchdog:
                         md.destroy()
                         self.dialog_error('Array file error')
                         return
             shutil.copyfile(self.s.file, self.fCode)
             inCod = open(self.fCode, 'r')
             units = 1
             for line in inCod:
                 if 'G21' in line.upper().replace(' ', '') and mUnits != 1:
                     units = 25.4
                     break
                 if 'G20' in line.upper().replace(' ', '') and mUnits == 1:
                     units = 0.03937
                     break
             self.fNgc = '{}/array.ngc'.format(self.tmpDir)
             outNgc = open(self.fNgc, 'w')
             xPos = (self.s.g5x_offset[0] - self.s.g92_offset[0]) * units
             yPos = (self.s.g5x_offset[1] - self.s.g92_offset[1]) * units
             for row in range(rows):
                 for column in range(columns):
                     outNgc.write('\n(row:{}  column:{})\n'.format(
                         row + 1, column + 1))
                     outNgc.write('G10 L2 P0 X{} Y{}\n'.format(
                         xPos + column * xOffset * units,
                         yPos + row * yOffset * units))
                     inCod = open(self.fCode, 'r')
                     for line in inCod:
                         a = b = c = ''
                         a = line.upper().replace(' ', '')
                         if 'M2' in a or 'M30' in a:
                             b = a.replace('M2', '')
                             c = b.replace('M30', '')
                             outNgc.write(c)
                         else:
                             outNgc.write(line)
                     inCod.close()
             outNgc.write('G10 L2 P0 X{} Y{}\n'.format(xPos, yPos))
             outNgc.write('M30\n')
             outNgc.close()
             self.load_file(self.fNgc)
             if self.previewed:
                 md.destroy()
         hal.set_p('plasmac_run.preview-tab', '1')
     else:
         msg = ''
         if columns <= 0:
             msg += 'Columns are required\n\n'
         if rows <= 0:
             msg += 'Rows are required\n\n'
         if xOffset == 0 and columns > 1:
             msg += 'Column Offset is required\n\n'
         if yOffset == 0 and rows > 1:
             msg += 'Row Offset is required'
         self.dialog_error(msg)
         return
     self.previewed = True
     self.data_changed = False
    def make(self, gameDisplay, totaltime, moves, sound):

        i = 0
        white = (255, 255, 255)
        disp_width = 900
        disp_height = 715
        crashed = False
        clock = pygame.time.Clock()
        pygame.font.init()
        mintime = 864000
        ex = 0
        newb = 0
        maxscore = 0
        scores = 0
        maxi = 0

        if os.path.getsize("lasttime.pkl") > 0:
            with open('lasttime.pkl', 'rb') as input:
                mintime = pickle.load(input)

        if os.path.getsize("maxscore.pkl") > 0:
            with open('maxscore.pkl', 'rb') as input:
                maxscore = pickle.load(input)

        if totaltime < mintime:
            newb = 1

        if totaltime < 30000:
            ex = 1

        if totaltime < mintime:
            with open('lasttime.pkl', 'wb') as output:
                pickle.dump(totaltime, output, pickle.HIGHEST_PROTOCOL)

        background = pygame.image.load(
            "buts/scorescreen/scorescreen.jpg").convert()
        background = pygame.transform.scale(background,
                                            (disp_width, disp_height))
        play = pygame.transform.scale(
            pygame.image.load("buts/scorescreen/play.png"), (80, 80))
        restart = pygame.transform.scale(
            pygame.image.load("buts/scorescreen/restart.png"), (80, 80))

        hours = 00
        minutes = 00
        seconds = 00
        totaltime = int(totaltime / 1000)  ## seconds total
        black = (0, 0, 0)

        t = (100000 / (moves * totaltime))
        print t
        scores = int(t)

        if scores > maxscore:
            with open('maxscore.pkl', 'wb') as output:
                pickle.dump(scores, output, pickle.HIGHEST_PROTOCOL)

            maxi = 1

        if (int(totaltime / 3600) > 0):
            hours = int(totaltime / 3600)
            totaltime = int(totaltime % 3600)
        if (int(totaltime / 60) > 0):
            minutes = int(totaltime / 60)
            totaltime = int(totaltime % 60)

        seconds = int(totaltime)
        check = 0

        font_path = "fonts/comicsans.ttf"
        font_size = 50
        font1 = pygame.font.Font(font_path, font_size)

        font2 = pygame.font.Font(font_path, 25)
        checkimg = pygame.transform.scale(
            pygame.image.load("buts/scorescreen/check.png"), (30, 30))

        #Level=font.render("Score:"+str(score), 1,(255,255,255))
        Level = font1.render("Level", 1, (255, 255, 161))
        completed = font1.render("completed!", 1, (255, 255, 161))

        Score = font2.render(
            "Time: " + str(hours) + ':' + str(minutes) + ':' + str(seconds), 1,
            (255, 255, 161))
        t = 0
        scorex = -50

        Mintime = font2.render(str(mintime), 1, (255, 255, 161))

        Excellent = font2.render("Excellent!", 1, (255, 255, 161))

        Newbest = font2.render("New best score!", 1, (255, 255, 161))
        scores = font2.render("Score: " + str(scores), 1, (255, 255, 161))

        newhighscore = font2.render("New High Score!", 1, (255, 255, 161))
        if sound:
            pygame.mixer.stop()
            success = pygame.mixer.Sound("sound/levelcomplete.ogg")
            success.play(0)

        while not crashed:
            # Gtk events
            while gtk.events_pending():
                gtk.main_iteration()

            event = pygame.event.poll()
            if event.type == pygame.KEYDOWN:
                #swoosh.play(0)
                return 1

            if event.type == pygame.QUIT:
                crashed = True

            mos_x, mos_y = pygame.mouse.get_pos()

            gameDisplay.fill(black)
            gameDisplay.blit(background, (0 + 280, 0))

            if play.get_rect(center=(280 + 10 + 280 + 10, 400 + 10 + 20 +
                                     50)).collidepoint(mos_x, mos_y):  #PLAY
                gameDisplay.blit(pygame.transform.scale(play, (90, 90)),
                                 (280 + 280 + 10, 400 + 20 + 50))
                if (pygame.mouse.get_pressed())[0] == 1 and check == 0:
                    return 1
                    check = 1
                if event.type == pygame.MOUSEBUTTONUP:
                    check = 0

            else:
                gameDisplay.blit(play, (280 + 280 + 10, 400 + 20 + 50))

            if restart.get_rect(center=(440 + 10 + 280 + 10, 400 + 10 + 20 +
                                        50)).collidepoint(mos_x,
                                                          mos_y):  #restart
                gameDisplay.blit(pygame.transform.scale(restart, (90, 90)),
                                 (440 + 280 + 10, 400 + 20 + 50))
                if (pygame.mouse.get_pressed())[0] == 1 and check == 0:
                    return 2
                    check = 1
                if event.type == pygame.MOUSEBUTTONUP:
                    check = 0

            else:
                gameDisplay.blit(restart, (440 + 280 + 10, 400 + 20 + 50))

            t += 1
            gameDisplay.blit(Level, (340 + 280 + 10, 50))
            gameDisplay.blit(completed, (280 + 280 + 10, 100))
            '''
            gameDisplay.blit(Excellent,(scorex,300))
            gameDisplay.blit(Newbest,(scorex,300))
            '''

            if (scorex + 280 > 0):
                gameDisplay.blit(Score, (scorex + 280, 230))
                gameDisplay.blit(scores, (scorex + 280, 260 + 10))
                if ex == 1:
                    gameDisplay.blit(Excellent,
                                     (scorex + 5 + 10 + 280, 300 + 30))
                    gameDisplay.blit(checkimg,
                                     (scorex - 40 + 10 + 280, 305 + 30))
                if newb == 1:
                    gameDisplay.blit(Newbest,
                                     (scorex + 5 + 10 + 280, 380 + 30))
                    gameDisplay.blit(checkimg,
                                     (scorex - 40 + 10 + 280, 385 + 30))
                if maxi == 1:
                    gameDisplay.blit(newhighscore,
                                     (scorex + 5 + 10 + 280, 340 + 30))
                    gameDisplay.blit(checkimg,
                                     (scorex - 40 + 10 + 280, 345 + 30))

            if (scorex + 280 < 320 + 280):
                scorex += 0.1 * (t**2)

            pygame.display.update()
            clock.tick(50)

            if crashed == True:  # Game crash or Close check
                pygame.quit()
                sys.exit()

        event1 = pygame.event.get()
        if event1.type == pygame.QUIT:
            crashed = True

        if crashed == True:
            pygame.quit()
            sys.exit()
Beispiel #55
0
    def execute(self, command, hint=None, cwd=None, extra_env=None):
        if not command:
            raise CommandError(_('No command given'))

        if isinstance(command, (str, unicode)):
            short_command = command.split()[0]
        else:
            short_command = command[0]

        if vte is None:
            textbuffer = self.terminal.get_buffer()

            if isinstance(command, (str, unicode)):
                self.terminal.get_buffer().insert_with_tags_by_name(
                    textbuffer.get_end_iter(), ' $ ' + command + '\n', 'stdin')
            else:
                self.terminal.get_buffer().insert_with_tags_by_name(
                    textbuffer.get_end_iter(),
                    ' $ ' + ' '.join(command) + '\n', 'stdin')

            kws = {
                'close_fds': True,
                'shell': isinstance(command, (str, unicode)),
                'stdin': subprocess.PIPE,
                'stdout': subprocess.PIPE,
                'stderr': subprocess.PIPE,
            }

            if cwd is not None:
                kws['cwd'] = cwd

            if extra_env is not None:
                kws['env'] = os.environ.copy()
                kws['env'].update(extra_env)

            command = self._prepare_execute(command)

            try:
                p = subprocess.Popen(command, **kws)
            except OSError, e:
                raise CommandError(str(e))
            self.child_pid = p.pid

            p.stdin.close()

            def make_non_blocking(fd):
                fl = fcntl.fcntl(fd, fcntl.F_GETFL)
                fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY)

            make_non_blocking(p.stdout)
            make_non_blocking(p.stderr)

            build_paused = False
            read_set = [p.stdout, p.stderr]

            while read_set:
                # Allow the frontend to get a little time
                while gtk.events_pending():
                    gtk.main_iteration()
                    if self.quit:
                        raise ExitRequestedException()

                rlist, wlist, xlist = select.select(read_set, [], [], 0)

                if p.stdout in rlist:
                    chunk = p.stdout.read()
                    if chunk == '':
                        p.stdout.close()
                        read_set.remove(p.stdout)
                    textbuffer.insert_with_tags_by_name(
                        textbuffer.get_end_iter(), chunk, 'stdout')

                if p.stderr in rlist:
                    chunk = p.stderr.read()
                    if chunk == '':
                        p.stderr.close()
                        read_set.remove(p.stderr)
                    textbuffer.insert_with_tags_by_name(
                        textbuffer.get_end_iter(), chunk, 'stderr')

                if textbuffer.get_line_count() > 200:
                    textbuffer.delete(
                        textbuffer.get_start_iter(),
                        textbuffer.get_iter_at_line_offset(
                            textbuffer.get_line_count() - 200, 0))

                mark = textbuffer.get_mark('end')
                if mark:
                    textbuffer.move_mark(mark, textbuffer.get_end_iter())
                else:
                    mark = textbuffer.create_mark('end',
                                                  textbuffer.get_end_iter(),
                                                  False)

                if self.terminal_sclwin.get_vadjustment().upper == \
                        (self.terminal_sclwin.size_request()[1] +
                         self.terminal_sclwin.get_vadjustment().get_value()):
                    # currently at the bottom of the textview, therefore scroll
                    # automatically
                    self.terminal.scroll_to_mark(mark, 0.05, True, 0.0, 1.0)

                # See if we should pause the current command
                if not build_paused and self.is_build_paused():
                    os.kill(p.pid, signal.SIGSTOP)
                    build_paused = True
                elif build_paused and not self.is_build_paused():
                    os.kill(p.pid, signal.SIGCONT)
                    build_paused = False

                time.sleep(0.05)

            rc = p.wait()
            self.child_pid = None
Beispiel #56
0
    def __init__(self, no_dialog=False):
        self.settings = EventCore()
        self.gui_is_active = False
        # during initialization any dialog (e.g. "Unit change") is not allowed
        # we set the final value later
        self.no_dialog = True
        self._batch_queue = []
        self._undo_states = []
        self.gui = gtk.Builder()
        gtk_build_file = get_ui_file_location(GTKBUILD_FILE)
        if gtk_build_file is None:
            gtk.main_quit()
        self.gui.add_from_file(gtk_build_file)
        if pycam.Utils.get_platform() == pycam.Utils.PLATFORM_WINDOWS:
            gtkrc_file = get_ui_file_location(GTKRC_FILE_WINDOWS)
            if gtkrc_file:
                gtk.rc_add_default_file(gtkrc_file)
                gtk.rc_reparse_all_for_settings(gtk.settings_get_default(),
                                                True)
        self.window = self.gui.get_object("ProjectWindow")
        self.settings.set("main_window", self.window)
        # show stock items on buttons
        # increase the initial width of the window (due to hidden elements)
        self.window.set_default_size(400, -1)
        # initialize the RecentManager (TODO: check for Windows)
        if False and pycam.Utils.get_platform(
        ) == pycam.Utils.PLATFORM_WINDOWS:
            # The pyinstaller binary for Windows fails mysteriously when trying
            # to display the stock item.
            # Error message: Gtk:ERROR:gtkrecentmanager.c:1942:get_icon_fallback: assertion failed: (retval != NULL)
            self.recent_manager = None
        else:
            try:
                self.recent_manager = gtk.recent_manager_get_default()
            except AttributeError:
                # GTK 2.12.1 seems to have problems with "RecentManager" on
                # Windows. Sadly this is the version, that is shipped with the
                # "appunti" GTK packages for Windows (April 2010).
                # see http://www.daa.com.au/pipermail/pygtk/2009-May/017052.html
                self.recent_manager = None
        # file loading
        self.last_dirname = None
        self.last_task_settings_uri = None
        self.last_model_uri = None
        # define callbacks and accelerator keys for the menu actions
        for objname, callback, data, accel_key in (
            ("LoadTaskSettings", self.load_task_settings_file, None,
             "<Control>t"), ("SaveTaskSettings", self.save_task_settings_file,
                             lambda: self.last_task_settings_uri, None),
            ("SaveAsTaskSettings", self.save_task_settings_file, None,
             None), ("OpenModel", self.load_model_file, None,
                     "<Control>o"), ("Quit", self.destroy, None, "<Control>q"),
            ("GeneralSettings", self.toggle_preferences_window, None,
             "<Control>p"), ("UndoButton", self._restore_undo_state, None,
                             "<Control>z"), ("HelpUserManual", self.show_help,
                                             "User_Manual", "F1"),
            ("HelpIntroduction", self.show_help, "Introduction", None),
            ("HelpSupportedFormats", self.show_help, "SupportedFormats",
             None), ("HelpModelTransformations", self.show_help,
                     "ModelTransformations",
                     None), ("HelpToolTypes", self.show_help, "ToolTypes",
                             None), ("HelpProcessSettings", self.show_help,
                                     "ProcessSettings", None),
            ("HelpBoundsSettings", self.show_help, "BoundsSettings",
             None), ("HelpTaskSetup", self.show_help, "TaskSetup", None),
            ("HelpGCodeExport", self.show_help, "GCodeExport",
             None), ("HelpTouchOff", self.show_help, "TouchOff",
                     None), ("HelpSimulation", self.show_help, "Simulation",
                             None), ("Help3DView", self.show_help, "3D_View",
                                     None), ("HelpServerMode", self.show_help,
                                             "ServerMode", None),
            ("HelpCommandLine", self.show_help, "CommandlineExamples",
             None), ("HelpHotkeys", self.show_help, "KeyboardShortcuts",
                     None), ("ProjectWebsite", self.show_help,
                             "http://pycam.sourceforge.net",
                             None), ("DevelopmentBlog", self.show_help,
                                     "http://fab.senselab.org/pycam", None),
            ("Forum", self.show_help,
             "http://sourceforge.net/projects/pycam/forums", None),
            ("BugTracker", self.show_help,
             "http://sourceforge.net/tracker/?group_id=237831&atid=1104176",
             None),
            ("FeatureRequest", self.show_help,
             "http://sourceforge.net/tracker/?group_id=237831&atid=1104179",
             None)):
            item = self.gui.get_object(objname)
            action = "activate"
            if data is None:
                item.connect(action, callback)
            else:
                item.connect(action, callback, data)
            if accel_key:
                key, mod = gtk.accelerator_parse(accel_key)
                accel_path = "<pycam>/%s" % objname
                item.set_accel_path(accel_path)
                gtk.accel_map_change_entry(accel_path, key, mod, True)
        # LinkButton does not work on Windows: https://bugzilla.gnome.org/show_bug.cgi?id=617874
        if pycam.Utils.get_platform() == pycam.Utils.PLATFORM_WINDOWS:

            def open_url(widget, data=None):
                webbrowser.open(widget.get_uri())

            gtk.link_button_set_uri_hook(open_url)
        # no undo is allowed at the beginning
        self.gui.get_object("UndoButton").set_sensitive(False)
        self.settings.register_event("model-change-before",
                                     self._store_undo_state)
        self.settings.register_event(
            "model-change-after",
            lambda: self.settings.emit_event("visual-item-updated"))
        # set the availability of ODE
        self.enable_ode_control = self.gui.get_object("SettingEnableODE")
        self.settings.add_item("enable_ode",
                               self.enable_ode_control.get_active,
                               self.enable_ode_control.set_active)
        self.settings.register_event("parallel-processing-changed",
                                     self.update_ode_settings)
        # configure drag-n-drop for config files and models
        self.settings.set("configure-drag-drop-func",
                          self.configure_drag_and_drop)
        self.settings.get("configure-drag-drop-func")(self.window)
        # other events
        self.window.connect("destroy", self.destroy)
        self.window.connect("delete-event", self.destroy)
        # the settings window
        self.gui.get_object("CloseSettingsWindow").connect(
            "clicked", self.toggle_preferences_window, False)
        self.gui.get_object("ResetPreferencesButton").connect(
            "clicked", self.reset_preferences)
        self.preferences_window = self.gui.get_object("GeneralSettingsWindow")
        self.preferences_window.connect("delete-event",
                                        self.toggle_preferences_window, False)
        self._preferences_window_position = None
        self._preferences_window_visible = False
        # "about" window
        self.about_window = self.gui.get_object("AboutWindow")
        self.about_window.set_version(VERSION)
        self.gui.get_object("About").connect("activate",
                                             self.toggle_about_window, True)
        # we assume, that the last child of the window is the "close" button
        # TODO: fix this ugly hack!
        self.gui.get_object("AboutWindowButtons").get_children()[-1].connect(
            "clicked", self.toggle_about_window, False)
        self.about_window.connect("delete-event", self.toggle_about_window,
                                  False)
        # menu bar
        uimanager = gtk.UIManager()
        self.settings.set("gtk-uimanager", uimanager)
        self._accel_group = uimanager.get_accel_group()

        # send a "delete" event on "CTRL-w" for every window
        def handle_window_close(accel_group, window, *args):
            window.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE))

        self._accel_group.connect_group(ord('w'), gtk.gdk.CONTROL_MASK,
                                        gtk.ACCEL_LOCKED, handle_window_close)
        self.settings.add_item("gtk-accel-group", lambda: self._accel_group)
        for obj in self.gui.get_objects():
            if isinstance(obj, gtk.Window):
                obj.add_accel_group(self._accel_group)
        # preferences tab
        preferences_book = self.gui.get_object("PreferencesNotebook")

        def clear_preferences():
            for child in preferences_book.get_children():
                preferences_book.remove(child)

        def add_preferences_item(item, name):
            preferences_book.append_page(item, gtk.Label(name))

        self.settings.register_ui_section("preferences", add_preferences_item,
                                          clear_preferences)
        for obj_name, label, priority in (("GeneralSettingsPrefTab", "General",
                                           -50), ("ProgramsPrefTab",
                                                  "Programs", 50)):
            obj = self.gui.get_object(obj_name)
            obj.unparent()
            self.settings.register_ui("preferences", label, obj, priority)
        # general preferences
        general_prefs = self.gui.get_object("GeneralPreferencesBox")

        def clear_general_prefs():
            for item in general_prefs.get_children():
                general_prefs.remove(item)

        def add_general_prefs_item(item, name):
            general_prefs.pack_start(item, expand=False, padding=3)

        self.settings.register_ui_section("preferences_general",
                                          add_general_prefs_item,
                                          clear_general_prefs)
        for obj_name, priority in (("SettingEnableODE", 10),
                                   ("TaskSettingsDefaultFileBox", 30)):
            obj = self.gui.get_object(obj_name)
            obj.unparent()
            self.settings.register_ui("preferences_general", None, obj,
                                      priority)
        # set defaults
        self.cutter = None
        # add some dummies - to be implemented later ...
        self.settings.add_item("cutter", lambda: self.cutter)
        main_tab = self.gui.get_object("MainTabs")

        def clear_main_tab():
            while main_tab.get_n_pages() > 0:
                main_tab.remove_page(0)

        def add_main_tab_item(item, name):
            main_tab.append_page(item, gtk.Label(name))

        # TODO: move these to plugins, as well
        self.settings.register_ui_section("main", add_main_tab_item,
                                          clear_main_tab)
        main_window = self.gui.get_object("WindowBox")

        def clear_main_window():
            main_window.foreach(lambda x: main_window.remove(x))

        def add_main_window_item(item, name, **extra_args):
            # some widgets may want to override the defaults
            args = {"expand": False, "fill": False}
            args.update(extra_args)
            main_window.pack_start(item, **args)

        main_tab.unparent()
        self.settings.register_ui_section("main_window", add_main_window_item,
                                          clear_main_window)
        self.settings.register_ui("main_window",
                                  "Tabs",
                                  main_tab,
                                  -20,
                                  args_dict={
                                      "expand": True,
                                      "fill": True
                                  })
        # autoload task settings file on startup
        autoload_enable = self.gui.get_object("AutoLoadTaskFile")
        autoload_box = self.gui.get_object("StartupTaskFileBox")
        autoload_source = self.gui.get_object("StartupTaskFile")

        # TODO: fix the extension filter
        #for one_filter in get_filters_from_list(FILTER_CONFIG):
        #    autoload_source.add_filter(one_filter)
        #    autoload_source.set_filter(one_filter)
        def get_autoload_task_file(autoload_source=autoload_source):
            if autoload_enable.get_active():
                return autoload_source.get_filename()
            else:
                return ""

        def set_autoload_task_file(filename):
            if filename:
                autoload_enable.set_active(True)
                autoload_box.show()
                autoload_source.set_filename(filename)
            else:
                autoload_enable.set_active(False)
                autoload_box.hide()
                autoload_source.unselect_all()

        def autoload_enable_switched(widget, box):
            if not widget.get_active():
                set_autoload_task_file(None)
            else:
                autoload_box.show()

        autoload_enable.connect("toggled", autoload_enable_switched,
                                autoload_box)
        self.settings.add_item("default_task_settings_file",
                               get_autoload_task_file, set_autoload_task_file)

        def disable_gui():
            self.menubar.set_sensitive(False)
            main_tab.set_sensitive(False)

        def enable_gui():
            self.menubar.set_sensitive(True)
            main_tab.set_sensitive(True)

        self.settings.register_event("gui-disable", disable_gui)
        self.settings.register_event("gui-enable", enable_gui)
        # configure locations of external programs
        for auto_control_name, location_control_name, browse_button, key in (
            ("ExternalProgramInkscapeAuto", "ExternalProgramInkscapeControl",
             "ExternalProgramInkscapeBrowse", "inkscape"),
            ("ExternalProgramPstoeditAuto", "ExternalProgramPstoeditControl",
             "ExternalProgramPstoeditBrowse", "pstoedit")):
            self.gui.get_object(auto_control_name).connect(
                "clicked", self._locate_external_program, key)
            location_control = self.gui.get_object(location_control_name)
            self.settings.add_item("external_program_%s" % key,
                                   location_control.get_text,
                                   location_control.set_text)
            self.gui.get_object(browse_button).connect(
                "clicked", self._browse_external_program_location, key)
        # set the icons (in different sizes) for all windows
        gtk.window_set_default_icon_list(*get_icons_pixbuffers())
        # load menu data
        gtk_menu_file = get_ui_file_location(GTKMENU_FILE)
        if gtk_menu_file is None:
            gtk.main_quit()
        uimanager.add_ui_from_file(gtk_menu_file)
        # make the actions defined in the GTKBUILD file available in the menu
        actiongroup = gtk.ActionGroup("menubar")
        for action in [
                action for action in self.gui.get_objects()
                if isinstance(action, gtk.Action)
        ]:
            actiongroup.add_action(action)
        # the "pos" parameter is optional since 2.12 - we can remove it later
        uimanager.insert_action_group(actiongroup, pos=-1)
        # the "recent files" sub-menu
        if not self.recent_manager is None:
            recent_files_menu = gtk.RecentChooserMenu(self.recent_manager)
            recent_files_menu.set_name("RecentFilesMenu")
            recent_menu_filter = gtk.RecentFilter()
            case_converter = pycam.Utils.get_case_insensitive_file_pattern
            for filter_name, patterns in FILTER_MODEL:
                if not isinstance(patterns, (list, set, tuple)):
                    patterns = [patterns]
                # convert it into a mutable list (instead of set/tuple)
                patterns = list(patterns)
                for index in range(len(patterns)):
                    patterns[index] = case_converter(patterns[index])
                for pattern in patterns:
                    recent_menu_filter.add_pattern(pattern)
            recent_files_menu.add_filter(recent_menu_filter)
            recent_files_menu.set_show_numbers(True)
            # non-local files (without "file://") are not supported. yet
            recent_files_menu.set_local_only(False)
            # most recent files to the top
            recent_files_menu.set_sort_type(gtk.RECENT_SORT_MRU)
            # show only ten files
            recent_files_menu.set_limit(10)
            uimanager.get_widget("/MenuBar/FileMenu/OpenRecentModelMenu")\
                    .set_submenu(recent_files_menu)
            recent_files_menu.connect("item-activated",
                                      self.load_recent_model_file)
        else:
            self.gui.get_object("OpenRecentModel").set_visible(False)
        # load the menubar and connect functions to its items
        self.menubar = uimanager.get_widget("/MenuBar")
        # dict of all merge-ids
        menu_merges = {}

        def clear_menu(menu_key):
            for merge in menu_merges.get(menu_key, []):
                uimanager.remove_ui(merge)

        def append_menu_item(menu_key, base_path, widget, name):
            merge_id = uimanager.new_merge_id()
            if widget:
                action_group = widget.props.action_group
                if not action_group in uimanager.get_action_groups():
                    uimanager.insert_action_group(action_group, -1)
                widget_name = widget.get_name()
                item_type = gtk.UI_MANAGER_MENUITEM
            else:
                widget_name = name
                item_type = gtk.UI_MANAGER_SEPARATOR
            uimanager.add_ui(merge_id, base_path, name, widget_name, item_type,
                             False)
            if not menu_key in menu_merges:
                menu_merges[menu_key] = []
            menu_merges[menu_key].append(merge_id)

        def get_menu_funcs(menu_key, base_path):
            append_func = lambda widget, name: \
                    append_menu_item(menu_key, base_path, widget, name)
            clear_func = lambda: clear_menu(menu_key)
            return append_func, clear_func

        for ui_name, base_path in (("view_menu", "/MenuBar/ViewMenu"),
                                   ("file_menu", "/MenuBar/FileMenu"),
                                   ("edit_menu", "/MenuBar/EditMenu"),
                                   ("export_menu",
                                    "/MenuBar/FileMenu/ExportMenu")):
            append_func, clear_func = get_menu_funcs(ui_name, base_path)
            self.settings.register_ui_section(ui_name, append_func, clear_func)
        self.settings.register_ui("file_menu", "Quit",
                                  self.gui.get_object("Quit"), 100)
        self.settings.register_ui("file_menu", "QuitSeparator", None, 95)
        self.settings.register_ui("main_window", "Main", self.menubar, -100)
        # initialize plugins
        self.plugin_manager = pycam.Plugins.PluginManager(core=self.settings)
        self.plugin_manager.import_plugins()
        # some more initialization
        self.reset_preferences()
        # TODO: preferences are not loaded until the new format is stable
        #self.load_preferences()
        #self.load_task_settings()
        self.settings.register_event("notify-file-saved",
                                     self.add_to_recent_file_list)
        self.settings.register_event("notify-file-opened",
                                     self.add_to_recent_file_list)
        # fallback - in case of a failure when opening a model file
        model = pycam.Importers.TestModel.get_test_model()
        self.settings.get("models").add_model(model, "Tiny pyramid")
        # Without this "gkt.main_iteration" loop the task settings file
        # control would not be updated in time.
        while gtk.events_pending():
            gtk.main_iteration()
        autoload_task_filename = self.settings.get(
            "default_task_settings_file")
        if autoload_task_filename:
            self.open_task_settings_file(autoload_task_filename)
        self.update_all_controls()
        self.no_dialog = no_dialog
        if not self.no_dialog:
            # register a logging handler for displaying error messages
            pycam.Utils.log.add_gtk_gui(self.window, logging.ERROR)
            self.window.show()
Beispiel #57
0
            if cwd:
                kws['directory'] = cwd

            self.vte_fork_running = True
            self.vte_child_exit_status = None
            # In earlier python-vte versions,
            #  - the environment had to be passed as a sequence of strings
            #    ("FOO=1", "BAR=2") (GNOME bug 583078)
            #  - directory keyword could not be set to None (GNOME bug 583129)
            # The bugs have been fixed, but for compatibility reasons the old
            # compatibility code is still in place.
            self.child_pid = self.terminal.fork_command(command=command[0],
                                                        argv=command,
                                                        **kws)
            while self.vte_fork_running:
                gtk.main_iteration()
                if self.quit:
                    raise ExitRequestedException()
            self.child_pid = None
            if os.WIFEXITED(self.vte_child_exit_status):
                rc = os.WEXITSTATUS(self.vte_child_exit_status)
            elif os.WIFSIGNALED(self.vte_child_exit_status):
                raise CommandError(
                    _('%(command)s died with signal %(rc)s') % {
                        'command': short_command,
                        'rc': os.WTERMSIG(self.vte_child_exit_status)
                    })

        if rc:
            raise CommandError(
                _('%(command)s returned with an error code (%(rc)s)') % {
Beispiel #58
0
    def load_clicked(self, widget, data=None):
        if self.cbfilter.get_model()[self.cbfilter.get_active()][0] == (
                _("Please select site")):
            self.progressbar.set_text(_("Please select site"))
            return
        stored = None
        dups = None
        partial = None
        errs = None
        ttime = None
        # Does the lock acquisition need to be more sophisticated for multiple dirs?
        # (see comment above about what to do if pipe already open)
        if self.settings['global_lock'].acquire(
                wait=False, source="GuiBulkImport"
        ):  # returns false immediately if lock not acquired
            #try:
            self.progressbar.set_text(_("Importing"))
            self.progressbar.pulse()
            while gtk.events_pending(
            ):  # see http://faq.pygtk.org/index.py?req=index for more hints (3.7)
                gtk.main_iteration(False)
            self.timer = gobject.timeout_add(100, self.dopulse)

            #    get the dir to import from the chooser
            selected = self.chooser.get_filenames()

            #    get the import settings from the gui and save in the importer
            self.importer.setHandCount(int(self.spin_hands.get_text()))
            self.importer.setQuiet(self.chk_st_st.get_active())
            self.importer.setThreads(int(self.spin_threads.get_text()))
            self.importer.setHandsInDB(self.n_hands_in_db)
            cb_model = self.cb_dropindexes.get_model()
            cb_index = self.cb_dropindexes.get_active()
            cb_hmodel = self.cb_drophudcache.get_model()
            cb_hindex = self.cb_drophudcache.get_active()

            #self.lab_info.set_markup('<span foreground="blue">Importing ...</span>') # uses pango markup!

            if cb_index:
                self.importer.setDropIndexes(cb_model[cb_index][0])
            else:
                self.importer.setDropIndexes("auto")
            if cb_hindex:
                self.importer.setDropHudCache(cb_hmodel[cb_hindex][0])
            else:
                self.importer.setDropHudCache("auto")
            sitename = self.cbfilter.get_model()[self.cbfilter.get_active()][0]
            #self.importer.setFailOnError(self.chk_fail.get_active())
            if self.is_archive.get_active():
                if sitename == "PokerStars":
                    self.importer.setStarsArchive(True)
                if sitename == "Full Tilt Poker":
                    self.importer.setFTPArchive(True)

            for selection in selected:
                self.importer.addBulkImportImportFileOrDir(selection,
                                                           site=sitename)
            self.importer.setCallHud(self.cb_testmode.get_active())
            self.importer.bHudTest = self.cb_testmode.get_active()
            starttime = time()
            #                try:
            (stored, dups, partial, errs, ttime) = self.importer.runImport()
            #                except:
            #                    print "*** EXCEPTION DURING BULKIMPORT!!!"
            #                    raise Exceptions.FpdbError
            #                finally:
            gobject.source_remove(self.timer)

            ttime = time() - starttime
            if ttime == 0:
                ttime = 1

            completionMessage = _('Bulk import done: Stored: %d, Duplicates: %d, Partial: %d, Errors: %d, Time: %s seconds, Stored/second: %.0f')\
                % (stored, dups, partial, errs, ttime, (stored+0.0) / ttime)
            print completionMessage
            log.info(completionMessage)

            self.importer.clearFileList()

            if self.n_hands_in_db == 0 and stored > 0:
                self.cb_dropindexes.set_sensitive(True)
                self.cb_dropindexes.set_active(0)
                self.lab_drop.set_sensitive(True)
                self.cb_drophudcache.set_sensitive(True)
                self.cb_drophudcache.set_active(0)
                self.lab_hdrop.set_sensitive(True)

            self.progressbar.set_text(_("Import Complete"))
            self.progressbar.set_fraction(0)
            #except:
            #err = traceback.extract_tb(sys.exc_info()[2])[-1]
            #print "*** BulkImport Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1])
            #self.settings['global_lock'].release()
            self.settings['global_lock'].release()
        else:
            print _("bulk import aborted - global lock not available")
Beispiel #59
0
 def gtk_main_tick():
     if gtk2compat.USE_GTK3:
         # FIXME: use something better
         return
     while gtk.events_pending():
         gtk.main_iteration(False)
Beispiel #60
0
    def handle_error(self, module, phase, nextphase, error, altphases):
        summary = _('Error during phase %(phase)s of %(module)s') % {
            'phase': phase,
            'module': module.name
        }
        try:
            error_message = error.args[0]
            self.message('%s: %s' % (summary, error_message))
        except:
            error_message = None
            self.message(summary)

        if not self.is_active():
            self.set_urgency_hint(True)
        self.notify.notify(summary=summary,
                           body=error_message,
                           icon=gtk.STOCK_DIALOG_ERROR,
                           expire=5)

        self.error_label.set_markup('<b>%s</b>' % _(summary))
        self.error_resolution_model.clear()
        iter = self.error_resolution_model.append(
            ('<i>%s</i>' % _('Pick an Action'), ''))
        self.error_resolution_model.append(('', ''))
        self.error_resolution_model.append(
            (_('Rerun phase %s') % phase, phase))
        if nextphase:
            self.error_resolution_model.append(
                (_('Ignore error and continue to %s') % nextphase, nextphase))
        else:
            self.error_resolution_model.append(
                (_('Ignore error and continue to next module'), '_done'))
        self.error_resolution_model.append((_('Give up on module'), 'fail'))
        for altphase in altphases:
            try:
                altphase_label = _(
                    getattr(getattr(module, 'do_' + altphase), 'label'))
            except AttributeError:
                altphase_label = altphase
            self.error_resolution_model.append(
                (_('Go to phase "%s"') % altphase_label, altphase))
        self.error_resolution_model.append(('', ''))
        self.error_resolution_model.append((_('Open Terminal'), 'shell'))

        self.error_combo.set_active_iter(iter)
        self.error_hbox.set_sensitive(True)
        self.error_hbox.show_all()
        self.error_resolution = None

        while True:
            self.error_resolution = None
            while gtk.events_pending():
                gtk.main_iteration()
                if self.quit:
                    return 'fail'
            if not self.error_resolution:
                continue
            self.set_urgency_hint(False)
            if self.error_resolution == 'shell':
                # set back combobox to "Pick an action"
                self.error_combo.set_active_iter(iter)
                if os.fork() == 0:
                    cmd = [
                        'gnome-terminal', '--working-directory',
                        module.get_builddir(self)
                    ]
                    os.execvp('gnome-terminal', cmd)
                    sys.exit(0)
                continue
            if self.error_resolution == '_done':
                self.error_resolution = None
            # keep the error hox visible during all of this module duration
            self.error_hbox.set_sensitive(False)
            return self.error_resolution