Пример #1
0
 def on_apply_clicked(self, event):
     self.expander.set_expanded(False)
     self.expander.hide
     self.progress.show
     self.progress.pulse
     while gtk.events_pending():
         gtk.main_iteration()
     for show in available_show.values():
         try:
             deep = self.box_list[show].get_date_index()
             if deep not in (-1,3):
                 count = 1
                 canal.buildURLdico(show, deep+1, 'high', True)
                 for url in canal.URLdico:
                     self.progress.set_text(show+': '+str(count)+
                         ' sur '+str(deep+1))
                     #try:
                     #canal.downloadURL(url, True, True,True)
                     #except:
                     #    print 'Error when downloading '+url
                     self.progress.set_fraction(float(count)/(deep+1))
                     while gtk.events_pending():
                         gtk.main_iteration()
                     count += 1
                 canal.URLdico.clear()
         except AttributeError:
             print "Error: flvstreamer is not installed,\
Пример #2
0
 def main_thread(self):
     while self.can_exit == False:
         self.show_percentage()
         while gtk.events_pending(): gtk.main_iteration()
         time.sleep(0.1)
     self.show_percentage()
     while gtk.events_pending(): gtk.main_iteration()
     if self.exception:
         exception_happened(*self.exception)
         gtk.main() # show exception dialog
     else:
         dialog = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, message_format=_('Please press "OK" button to install icons. Authentication is required.'))
         dialog.set_position(gtk.WIN_POS_CENTER)
         dialog.run()
         dialog.destroy()
         try:
             self.install_icons()
         except:
             exception_happened(*sys.exc_info())
             gtk.main()
         else:
             dialog = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, message_format=_('Icons are successfully installed.'))
             dialog.run()
             dialog.destroy()
             sys.exit()
Пример #3
0
 def on_app_options_changed(self, plugin_name):
     '''
     .. versionchanged:: 2.23
         When real-time mode is toggled, trigger execution of step with
         :meth:`goto_step` instead of calling :meth:`run_step` directly.
     '''
     if plugin_name == self.name:
         data = self.get_data(self.name)
         if 'realtime_mode' in data:
             if self.realtime_mode != data['realtime_mode']:
                 self.realtime_mode = data['realtime_mode']
                 if self.protocol is not None:
                     self.protocol.goto_step(self.protocol
                                             .current_step_number)
         if 'log_file' in data and 'log_enabled' in data:
             self.apply_log_file_config(data['log_file'],
                                        data['log_enabled'])
         if 'log_level' in data:
             self._set_log_level(data['log_level'])
         if 'width' in data and 'height' in data:
             self.main_window_controller.view.resize(data['width'],
                                                     data['height'])
             # allow window to resize before other signals are processed
             while gtk.events_pending():
                 gtk.main_iteration()
         if data.get('x') is not None and data.get('y') is not None:
             self.main_window_controller.view.move(data['x'], data['y'])
             # allow window to resize before other signals are processed
             while gtk.events_pending():
                 gtk.main_iteration()
Пример #4
0
    def deleteall(self,widget):
        self.dstDir = self.destTxtBox.get_text()
        #now we need to delete all files from this folder.
        self.num_of_files = 0
        self.numnow = 0
        os.chdir(self.dstDir)
        self.ffiles = glob.glob("*.*")

        for f in self.ffiles:
            while gtk.events_pending():
               gtk.main_iteration()
            self.num_of_files = self.num_of_files + 1


        for f in self.ffiles:
            while gtk.events_pending():
               gtk.main_iteration()
            self.numnow = self.numnow + 1
            self.notice = "Deleting File: " + f + "(" + str(self.numnow) + " of " + str(self.num_of_files) + ")"
            self.pbar.set_text(self.notice)
            #self.pbar.pulse()
            self.percent = float(self.numnow) / float(self.num_of_files)
            self.pbar.set_fraction(self.percent)

            os.remove(self.dstDir + "/" + f)
            self.scanDestDir(None)
        self.pbar.set_text("All files deleted")
        self.pbar.set_fraction(1)
Пример #5
0
    def download_headers(self,group,first_unread,read_list,server_name):
        last_number=str(first_unread)
        #Here I deleted the controls I made on first_unread before I changed
        #the nntplib, it works with leafnode, I must test with other servers.
        first=int(first_unread)
        #Downloading headers
        self.main_win.progressbar.set_text(_("Fetching Headers"))
        self.main_win.progressbar.set_fraction(1/float(2))
        while gtk.events_pending():
            gtk.main_iteration(False)
        message,total_headers,last=self.connectionsPool[server_name].getHeaders(group,first)
        if last!=-1:
            last_number=str(last)
        self.main_win.statusbar.push(1,message)
        if total_headers:
            self.main_win.progressbar.set_text(_("Building Articles"))
        else:
            self.main_win.progressbar.set_text(_("No New Headers"))
        self.main_win.progressbar.set_fraction(2/float(2))
        while gtk.events_pending():
            gtk.main_iteration(False)
        
        self.art_db.createGroup(group)
        self.art_db.addHeaders(group,total_headers,server_name,self.connectionsPool,read_list)

        self.main_win.statusbar.push(1,_("Group subscribed"))
        self.main_win.progressbar.set_fraction(0)
        self.main_win.progressbar.set_text("")
        return last_number
Пример #6
0
def _init_league(teams, fast, num_turns, back_round):
    l = league.League(teams, num_turns, back_round)

    band = False
    
    while not l.league_completed and not band:
        i = l.get_round_number()
        progress_bar = None
        if fast:
            progress_bar = pbs.ProgressBarDialog(None,
                                                 _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(l.get_round(i).number_games)
            progress_bar_dialog.show()
            while gtk.events_pending():
                gtk.main_iteration(False)
        l.play_round(progress_bar, fast)
        r = l.get_round(i)
        
        classifications = l.get_actual_puntuations()
        results = r.get_round_results()
        
        R = round_results.roundResults(classifications, results,
                                       l.get_prev_round_number() + 1,
                                       l.get_number_of_rounds())
        if fast:
            progress_bar_dialog.hide()
        button_pressed = R.result_dialog.run()
        
        while gtk.events_pending():
            gtk.main_iteration(False)
            
        if button_pressed == -4 or button_pressed == 0:
            band = True
Пример #7
0
    def delete_trash_mails(self):
        delete = super(Folder, self).delete_trash_mails()

        if not self._loaded or not delete:
            return []

        self.progress.set_fraction(0)
        self.progress.set_text(_("Deleting Mails in %s") % self.label)
        self.show_progress(True)

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

        for progress in delete:
            self.progress.set_fraction(progress)
            self.progress.set_text("%i %%" % (progress * 100))
            while gtk.events_pending():
                gtk.main_iteration(False)
            if progress == 1:
                self.show_progress(False)
                deleted_keys = delete.next()

        deleted_iters = []
        row_iter = self.list_store.get_iter_root()
        while row_iter:
            if self.list_store.get_value(row_iter, 0).get_key() in deleted_keys:
                deleted_iters.append(row_iter)
            row_iter = self.list_store.iter_next(row_iter)
        for iter in deleted_iters:
            self.list_store.remove(iter)
Пример #8
0
 def editor_open(self, *args):
     step = 1000
     fcd = FileChooserDialog(self, action='open')
     fcd.run()
     if not self.path:
         return
     self.editor_path = self.path
     self.fcd_dir = os.path.dirname(self.path)
     self.path = ''
     text = open(self.editor_path).read()
     self.path = ''
     t_table = gtk.TextTagTable()
     tag = gtk.TextTag('output')
     t_table.add(tag)
     self.editor_buffer = gtk.TextBuffer(t_table)
     self.textview_edit.set_buffer(self.editor_buffer)
     self.assert_quit = True
     size=len(text)
     if size < step:
         self.editor_buffer.set_text(text)
     else:
         self.editor_buffer.set_text(text[:step])
         while gtk.events_pending():
             gtk.main_iteration_do(False)
         i = step
         while i < size-step:
             self.editor_buffer.insert(self.editor_buffer.get_end_iter(), text[i:i+step])
             i += step
             while gtk.events_pending():
                 gtk.main_iteration_do(False)
         self.editor_buffer.insert(self.editor_buffer.get_end_iter(), text[i:])
Пример #9
0
def run_actions(root, action_defs):
    for action_def in action_defs:
        while gtk.events_pending():
            gtk.main_iteration(False)
        run_action(root, *action_def)
    while gtk.events_pending():
        gtk.main_iteration(False)
Пример #10
0
	def check_button_clicked(self, widget, data=None):
            records_list = get_records()
            #print records_list
            self.running = False
            time = str(datetime.datetime.now()-self.start_time)
            self.time_label.set_text(time)
            self.start_button.set_sensitive(True)
            self.check_button.set_sensitive(False)
            lst =  self.collect_words()
            i = 0
            for word in lst:
                #print check_word(word)
                if check_word(word):
                    self.score += len(word) 
                    self.score_label.set_text(str(self.score))
                    self.icons[i].clear()
                    self.icons[i].set_from_stock(gtk.STOCK_SPELL_CHECK, gtk.ICON_SIZE_BUTTON)
                    self.icons[i].queue_draw()
                    while (gtk.events_pending ()):
                            gtk.main_iteration ();
                else:
                    self.icons[i].clear()
                    self.icons[i].set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
                    self.icons[i].queue_draw()
                    while (gtk.events_pending ()):
                            gtk.main_iteration ();
                i+=1

            utf_syll = self.syll[0].decode('utf-8')+self.syll[1].decode('utf-8')
            add_record(self.score, utf_syll, "None", time)
Пример #11
0
 def r_start(self, *args):
     try:
         self.glosR
     except AttributeError:
         if not self.r_load():
             return False
     #if len(self.glosR)==0:
     #    log.error('Input glossary has no word! Be sure to click "Load" before "Start", or just click "Apply" instead.')
     #    return
     oPath = self.entry_r_o.get_text()
     if not oPath:
         log.critical('Output file path is empty!');return
     self.progress(0.0, 'Starting....')
     self.pref_rev_update_var()
     self.pref['savePath']=oPath
     while gtk.events_pending():
         gtk.main_iteration_do(False)
     self.rWords = self.glosR.takeOutputWords()
     self.assert_quit=True
     #revTh = thread.start_new_thread(self.glosR.reverseDic, (self.rWords, self.pref))
     self.xml.get_widget('image_r_d').set_from_stock('gtk-media-pause', 'button')
     self.xml.get_widget('label_r_d').set_text('Stop')
     self.entry_r_i.set_editable(False)
     self.entry_r_o.set_editable(False)
     self.xml.get_widget('button_r_i').set_sensitive(False)
     self.xml.get_widget('button_r_load').set_sensitive(False)
     self.xml.get_widget('button_r_o').set_sensitive(False)
     self.xml.get_widget('vbox_options').set_sensitive(False)
     log.info('Number of input words:', len(self.rWords))
     log.info('Reversing glossary...')
     self.glosR.reverseDic(self.rWords, self.pref)
     while True:## FIXME
     #while not self.reverseStop:
         while gtk.events_pending():
             gtk.main_iteration_do(False)
 def imprimir(self, boton):
     """
     Prepara la vista preliminar para la impresión del informe.
     """
     from treeview2pdf import treeview2pdf
     from informes import abrir_pdf
     strfecha = "%s - %s" % (self.wids['e_fechainicio'].get_text(), self.wids['e_fechafin'].get_text())
     resp = utils.dialogo(titulo = "¿IMPRIMIR DESGLOSE?", 
                          texto = "Puede imprimir únicamente los productos o toda la información de la ventana.\n¿Desea imprimir toda la información desglosada?", 
                          padre = self.wids['ventana'])
     tv = clone_treeview(self.wids['tv_datos'])  # Para respetar el orden del treeview original y que no afecte a las filas 
                                                 # de totales que añado después. Si las añado al original directamente se 
                                                 # mostrarán en el orden que correspondería en lugar de al final.
     model = tv.get_model()
     fila_sep = model.append(None, ("===",) * 6)
     fila_total_gtx = model.append(None, ("Total m² geotextiles", self.wids['e_total_metros'].get_text(), "", "", "", ""))
     fila_total_fibra = model.append(None, ("Total kg fibra", self.wids['e_total_kilos'].get_text(), "", "", "", ""))
     fila_total_otros = model.append(None, ("Total € otros", self.wids['e_total_otros'].get_text(), "", "", "", ""))
     if resp:
         tv.expand_all()
         while gtk.events_pending(): gtk.main_iteration(False)
     else:
         tv.collapse_all()
         while gtk.events_pending(): gtk.main_iteration(False)
         tv = convertir_a_listview(tv)
         # Para este caso particular me sobran las tres últimas columnas
         tv.remove_column(tv.get_columns()[-1])
         tv.remove_column(tv.get_columns()[-1])
         tv.remove_column(tv.get_columns()[-1])
     abrir_pdf(treeview2pdf(tv, titulo = "Salidas de almacén agrupadas por producto", fecha = strfecha))
     model.remove(fila_sep)
     model.remove(fila_total_gtx)
     model.remove(fila_total_fibra)
     model.remove(fila_total_otros)
Пример #13
0
 def performBoxDetectionForReviewer(self, image_reviewer):
     window_size = self.configuration_manager.window_size
     if window_size == 'auto':
         window_size = None
     else:
         window_size = float(window_size)
     image_processor = ImageProcessor(image_reviewer.path_to_image, window_size)
     while gtk.events_pending():
         gtk.main_iteration()
     block_retriever = BlockRetriever(image_processor.imageToBinary())
     while gtk.events_pending():
         gtk.main_iteration()
     blocks = block_retriever.getAllBlocks()
     while gtk.events_pending():
         gtk.main_iteration()
     image_reviewer.selectable_boxes_area.clearAreas()
     image_reviewer.applyTextColors()
     for block in blocks:
         leftmost_x, highest_y, rightmost_x, lowest_y = (block.translateToUnits(image_processor.window_size))
         rightmost_x = min(rightmost_x, image_reviewer.image_pixbuf.get_width())
         lowest_y = min(lowest_y, image_reviewer.image_pixbuf.get_height())
         dimensions = graphics.getBoundsFromStartEndPoints((leftmost_x, highest_y), (rightmost_x, lowest_y))
         image_reviewer.selectable_boxes_area.addArea(dimensions)
         while gtk.events_pending():
             gtk.main_iteration()
Пример #14
0
def on_button1_clicked(widget, data=None):
		button1.set_sensitive(False)
		button1.set_label(" ")
		time1 = os.stat(folder+"/spirit-log").st_mtime
		os.system("./spirit-output")
		while 0 < 1:
			while os.stat(folder+"/spirit-log").st_mtime != time1:
				list = []
				file = open(folder+"/spirit-log", 'r')
				lettura = file.readlines()
				for riga in lettura:
					list.append(riga)
					while gtk.events_pending() == 1:
						gtk.main_iteration()
					time.sleep(0.1)
				last = list[-1]
				if last[:4] == "INFO":
					if label2.get_text() != last:
						label2.set_text(last)
						while gtk.events_pending() == 1:
							gtk.main_iteration()
							print last
				if last[:5] == "ERROR":
					if label2.get_text() != last:
						label2.set_text(last)
						print last
Пример #15
0
    def bloqueo(self):
        print "-----------para bloquear pantalla ------------"

        bit = "B"
        self.muro.show_all()
        while gtk.events_pending():
            gtk.main_iteration(False)

        # limpiar la columnas despues de desbloqueo
        self.lista_Cen.tV.set_model(None)
        self.lista_Der.tV.set_model(None)

        # se define la entrada serial
        usbport = "/dev/ttyUSB0"
        ser = serial.Serial(usbport, 9600, timeout=1)

        cont = 0
        while bit != "h":

            bit = ser.read(1)
            print cont
            cont = cont + 1

        self.muro.hide_all()
        while gtk.events_pending():
            gtk.main_iteration(False)
Пример #16
0
	def search(self, text, categorie):
		self.treeDisk.unselect_all()
		self.__searching = True
		self.app.toolbutton_buscar.set_stock_id(gtk.STOCK_STOP)
		self.refresh_statusbar(_("Searching..."));
		while (gtk.events_pending ()): gtk.main_iteration ();
		self.treeFiles.clear()
		if not categorie[1]:
			files = self.db.search_files(text, categorie = categorie[0] )
		else:
			files = self.db.search_files(text, mime_type = categorie[0] )
		pos= 0

		for i in files:
			if (pos % 100) == 0:
				while (gtk.events_pending ()): gtk.main_iteration ();
			pos = pos + 1
			if self.__cancel_action: break
			self.treeFiles.insert(i, search = True)

		self.__cancel_action = self.__searching = False
		self.app.toolbutton_buscar.set_stock_id(gtk.STOCK_FIND)

		self.refresh_statusbar()
		self.treeDisk.unselect_all()
Пример #17
0
    def dia_rebuild_indexes(self, widget, data=None):
        if self.obtain_global_lock():
            self.dia_confirm = gtk.MessageDialog(parent=None
                                                ,flags=0
                                                ,type=gtk.MESSAGE_WARNING
                                                ,buttons=(gtk.BUTTONS_YES_NO)
                                                ,message_format="Confirm rebuilding database indexes")
            diastring = "Please confirm that you want to rebuild the database indexes."
            self.dia_confirm.format_secondary_text(diastring)

            response = self.dia_confirm.run()
            if response == gtk.RESPONSE_YES:
                lbl = gtk.Label(" Rebuilding Indexes ... ")
                self.dia_confirm.vbox.add(lbl)
                lbl.show()
                while gtk.events_pending():
                    gtk.main_iteration_do(False)
                self.db.rebuild_indexes()

                lbl.set_text(" Cleaning Database ... ")
                while gtk.events_pending():
                    gtk.main_iteration_do(False)
                self.db.vacuumDB()

                lbl.set_text(" Analyzing Database ... ")
                while gtk.events_pending():
                    gtk.main_iteration_do(False)
                self.db.analyzeDB()
            elif response == gtk.RESPONSE_NO:
                print 'User cancelled rebuilding db indexes'

            self.dia_confirm.destroy()

        self.release_global_lock()
Пример #18
0
 def loadAdditionalData(self):
 
     for post in self.graph.objects(self.uri, SIOC['container_of']):
         if not self.hasValueForPredicate(post, SIOC['title']):
             print 'Resolving reference to get additional data (', post, ')...',
             self.graph.parse(post)
             
             if (self.pb != None):
                 self.pb.progress()
                 while gtk.events_pending():
                     gtk.main_iteration()
                     
             print 'OK, now', len(self.graph), 'triples'
 
     for user in self.graph.objects(self.uri, SIOC['has_subscriber']):
         if not self.hasValueForPredicate(user, SIOC['email_sha1sum']):
             print 'Resolving reference to get additional data (', user, ')...',
             self.graph.parse(user)
                
             if (self.pb != None):
                 self.pb.progress()
                 while gtk.events_pending():
                     gtk.main_iteration()
                     
             print 'OK, now', len(self.graph), 'triples' 
Пример #19
0
def _init_tournament(teams, num_turns, fast):
    t = tournament.Tournament(teams, num_turns)
    band = False
    
    while not t.tournament_completed and not band:
        i = t.get_round_number()
        progress_bar = None
        if fast:
            progress_bar = pbs.ProgressBarDialog(None,
                                                 _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(t.get_round(i).number_games)
            progress_bar_dialog.show()
            while gtk.events_pending():
                gtk.main_iteration(False)
        t.play_round(progress_bar, fast)
        r = t.get_round(i)

        classifications = []
        results = r.get_round_results()
        
        R = round_results.roundResults(classifications, results,
                                       t.get_prev_round_number() + 1,
                                       t.get_number_of_rounds(),
                                       show_classifications=False)
        if fast:
            progress_bar_dialog.hide()
        button_pressed = R.result_dialog.run()
        
        while gtk.events_pending():
            gtk.main_iteration(False)
            
        if button_pressed == -4 or button_pressed == 0:
            band = True
    print teams
Пример #20
0
 def update_ssn_file(self):
     print "*** Connecting to " + self.ssn_url
     if self.s_bar:
         context_id = self.s_bar.get_context_id("ssn_data_connecting")
         self.s_bar.push(context_id, _("Connecting to ") + self.ssn_url)
         while gtk.events_pending():
             gtk.main_iteration()
     try:
         f_name, header = urllib.urlretrieve(self.ssn_url, reporthook=self.progress_reporthook)
         shutil.copyfile(f_name, self.save_location)
         # todo delete the temp
         print "*** Disconnected from internet ***"
         if self.s_bar:
             context_id = self.s_bar.get_context_id("ssn_data_done")
             self.s_bar.push(context_id, _("Done"))
             while gtk.events_pending():
                 gtk.main_iteration()
         self.read_ssn_file()
     except:
         print "*** Failed to retrieve data ***"
         if self.s_bar:
             context_id = self.s_bar.get_context_id("ssn_data_done")
             self.s_bar.push(context_id, _("Error: Unable to retrieve data"))
             while gtk.events_pending():
                 gtk.main_iteration()
Пример #21
0
    def imprimir(self, boton):
        """
        Prepara la vista preliminar para la impresión del informe.
        """
        # TODO: Faltan totales
        resp = utils.dialogo(
            titulo="¿IMPRIMIR DESGLOSE?",
            texto="Puede imprimir un resumen o todo el contenido de la consulta\n¿Desea imprimir toda la información desglosada?",
            padre=self.wids["ventana"],
        )
        if resp:
            tv = self.wids["tv_datos"]
            tv.expand_all()
            while gtk.events_pending():
                gtk.main_iteration(False)
        else:
            tv = self.wids["tv_datos"]
            tv.collapse_all()
            while gtk.events_pending():
                gtk.main_iteration(False)
            from consulta_ventas_por_producto import convertir_a_listview

            tv = convertir_a_listview(tv)
        strfecha = "De %s a %s" % (self.wids["e_fechainicio"].get_text(), self.wids["e_fechafin"].get_text())
        abrir_pdf(treeview2pdf(tv, titulo="Beneficio sobre tarifa", fecha=strfecha))
Пример #22
0
 def onNewFileClicked(self,event,item):
     """
     Show new file dialog
     """
     newFileDialog = self.app.wTree.get_widget("newFileDialog")                
     newFileDialog.show()        
     response=newFileDialog.run()        
     newFileDialog.hide()
     if response==1:
         filePaths = newFileDialog.get_filenames()
         folder = self.app.repo.getObjectByPath(self.app.currentDirectory)
         for filePath in filePaths:                
             if not os.path.isdir(filePath):
                 f=open(filePath,"rb")
                 fnameparts=filePath.split("/")
                 fileName=fnameparts[len(fnameparts)-1]
                 self.app.statusbar.push(1,"Creating file "+fileName+ " ...");
                 while gtk.events_pending():
                     gtk.main_iteration()
                 try:        
                     folder.createDocument(fileName,{},f)
                 except:
                     self.app.util.errorMessage("uploading file failed! ")
                 self.app.statusbar.push(1,"Creating file "+fileName+ " ... done");
                 while gtk.events_pending():
                     gtk.main_iteration()   
         self.app.iconView.fillStore()
Пример #23
0
 def imprimir(self, boton):
     """
     Prepara la vista preliminar para la impresión del informe.
     """
     resp = utils.dialogo(titulo = "¿IMPRIMIR DESGLOSE?", 
                          texto = "Puede imprimir un resumen o todo el "
                                  "contenido de la consulta\n"
                                  "¿Desea imprimir toda la información "
                                  "desglosada?", 
                          padre = self.wids['ventana'])
     if resp:
         tv = self.wids['tv_datos']
         tv.expand_all()
         while gtk.events_pending(): gtk.main_iteration(False)
         colstotales = []
     else:
         tv = self.wids['tv_datos']
         tv.collapse_all()
         while gtk.events_pending(): gtk.main_iteration(False)
         from consulta_ventas_por_producto import convertir_a_listview
         tv = convertir_a_listview(tv)
         colstotales = [2, 3, 4]
     strfecha = "De %s a %s" % (self.wids['e_fechainicio'].get_text(), 
                                self.wids['e_fechafin'].get_text())
     abrir_pdf(treeview2pdf(tv, 
                            titulo = "Beneficio sobre tarifa (tickets)", 
                            fecha = strfecha, 
                            numcols_a_totalizar = colstotales))
Пример #24
0
    def sendQueuedArticles(self,obj):
        '''Send articles stored in outbox'''
        ordered_list=load_ordered_list()
        user_agent=self.VERSION
        try:
            articles=os.listdir(os.path.join(self.wdir,"outbox/news"))
        except:
            self.statusbar.push(1,_("Problems while opening News OutBox"))
        else:
            total=len(articles)
            news_sent=total
    
            cp=ConfigParser.ConfigParser()
            cp.read(os.path.join(get_wdir(),"dats","servers.txt"))
            self.connectionsPool=dict()        
            for server in cp.sections():
                if cp.get(server,"nntp_use_ssl")=="True":
                    self.connectionsPool[server]=SSLConnection(cp.get(server,"server"),cp.get(server,"port"),cp.get(server,"auth"),cp.get(server,"username"),cp.get(server,"password"))
                else:
                    self.connectionsPool[server]=Connection(cp.get(server,"server"),cp.get(server,"port"),cp.get(server,"auth"),cp.get(server,"username"),cp.get(server,"password"))

            i=0    
            for articleName in articles:
                i=i+1
                try:
                    f=open(os.path.join(self.wdir,"outbox/news/",articleName),"rb")
                except:
                    self.statusbar.push(1,_("Problems while opening article :")+articleName)
                else:
                    self.statusbar.push(1,_("Sending Article: ")+articleName)
                    while gtk.events_pending():
                        gtk.main_iteration(False)
                    draftArticle=cPickle.load(f)
                    f.close()
                    newsgroups=draftArticle.get("newsgroups","")
                    from_name=draftArticle.get("from_name","")
                    subject=draftArticle.get("subject","")
                    references=draftArticle.get("references","")
                    output_charset=draftArticle.get("output_charset","")
                    body=draftArticle.get("body","")
                    custom_names=draftArticle.get("custom_names",[])
                    custom_values=draftArticle.get("custom_values",[])
                    article_to_send=Article_To_Send(newsgroups,from_name,subject,references,user_agent,output_charset,ordered_list,body,custom_names,custom_values,self.configs["gen_mid"],self.configs["fqdn"])
                    article=article_to_send.get_article()
                    server_name=draftArticle.get("server_name","")

                    message,articlePosted=self.connectionsPool[server_name].sendArticle(article)
                    self.statusbar.push(1,message)
                    if articlePosted:
                        os.remove(os.path.join(self.wdir,"outbox/news/",articleName))
                        self.store_article(os.path.join(self.wdir,"sent/news"),draftArticle)
                    else:
                        news_sent=news_sent-1
                while gtk.events_pending():
                    gtk.main_iteration(False)
            self.statusbar.push(1,_("Sent %d Articles") % (news_sent,))
            for connection in self.connectionsPool.itervalues():
                connection.closeConnection()

            self.populateFolderTree()
Пример #25
0
 def imprimir(self, boton):
     """
     Prepara la vista preliminar para la impresión del informe.
     """
     resp = utils.dialogo(titulo = "¿IMPRIMIR DESGLOSE?", 
                          texto = "Puede imprimir un resumen o todo el contenido de la consulta\n¿Desea imprimir toda la información desglosada?", 
                          padre = self.wids['ventana'])
     if resp:
         tv = self.wids['tv_datos']
         tv.expand_all()
         while gtk.events_pending(): gtk.main_iteration(False)
     else:
         tv = self.wids['tv_datos']
         tv.collapse_all()
         while gtk.events_pending(): gtk.main_iteration(False)
         from consulta_ventas_por_producto import convertir_a_listview
         tv = convertir_a_listview(tv)
     strfecha = "De %s a %s" % (self.wids['e_fechainicio'].get_text(), self.wids['e_fechafin'].get_text())
     abrir_pdf(treeview2pdf(tv, titulo = "Beneficio sobre tarifa", 
                            fecha = strfecha, 
                            extra_data = (
                                 ["Facturado: ", 
                                  self.wids['e_total'].get_text()], 
                                 ["Facturación sin IVA: ", 
                                  self.wids['e_siniva'].get_text()],
                                 ["Beneficio neto: ", 
                                  self.wids['e_beneficio'].get_text()])))
Пример #26
0
def runProg(cmdline):
    sout = ""
    logging.debug("CMD:-%s", cmdline)
    try:
        p = subprocess.Popen(
            cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, close_fds=True
        )
        poll = select.poll()
        poll.register(p.stdout, select.POLLIN)
        while gtk.events_pending():
            gtk.main_iteration()
        while True:
            o = p.stdout.readline()
            if o == "" and p.poll() != None:
                break
            while gtk.events_pending():
                gtk.main_iteration()
            sout += o
        if p.poll() == 1:
            raise
    except OSError as e:
        err = "ERROR: Error running %s: %s" % (cmdline[0], e.strerror)
        return (False, err)
    except:
        logging.debug("ERR:%s", sout)
        return (False, sout)
    return (True, sout)
Пример #27
0
 def raw_write(self, source, target):
     data = Popen(['ls -l '+source], shell=True, stdout=PIPE, stderr=PIPE)
     src_size = float(data.stdout.readline().split()[4])*1.0
     progress = self.wTree.get_widget("progressbar")
     progress.set_sensitive(True)
     progress.set_text(_('Writing ')+source.split('/')[-1]+_(' to ')+self.dev)
     self.logger(_('Executing: dd if=')+source+' of='+target)
     while gtk.events_pending():
        gtk.main_iteration(True)
     output = Popen(['dd if='+source+' of='+target+' bs=1M'], stdout=PIPE, stderr=STDOUT, shell=True)
     self.ddpid = output.pid
     while output.stdout.readline():
         line = output.stdout.readline().strip()
         while gtk.events_pending():
             gtk.main_iteration(True)
         if line.endswith('MB/s'):
             target_size = line.split()[0]
             self.logger(_('Wrote: ')+target_size+' bytes')
             size = float(target_size)*100/float(src_size)
             while gtk.events_pending():
                 gtk.main_iteration(True)
             progress.set_fraction(float(size/100))
     pid, sts = os.waitpid(output.pid, 0)
     if sts != 0:
         self.logger(_('The dd process ended with an error !'))
         self.emergency()
         return False
     progress.set_fraction(1.0)
     self.logger(_('Image ')+source.split('/')[-1]+_(' successfully written to')+target)
     self.success()
Пример #28
0
    def raw_write(self, source, target):
      progress = self.wTree.get_widget("progressbar")
      progress.set_sensitive(True)
      progress.set_text(_('Writing ')+source.split('/')[-1]+_(' to ')+self.dev)
      self.logger(_('Starting copy from ')+source+' to '+target)
      while gtk.events_pending():
        gtk.main_iteration(True) 
      total_size = float(os.path.getsize(source))   
      # Add launcher string, only when not root
      launcher = ''
      size=''
      if os.geteuid() > 0:
	      launcher='pkexec'
	      output = Popen([launcher,'/usr/bin/python', '/usr/lib/mintstick/raw_write.py','-s',source,'-t',target], shell=False, stdout=PIPE)	
      else:
	      output = Popen(['/usr/bin/python', '/usr/lib/mintstick/raw_write.py','-s',source,'-t',target], shell=False, stdout=PIPE)	
      while output.stdout.readline():
        size = output.stdout.readline().strip()
        try:
          size = float(size)
          flag = True
        except ValueError:
          flag = False
        while gtk.events_pending():
            gtk.main_iteration(True)
        if flag:
          progress.set_fraction(size)
      if size == 1.0:
        self.logger(_('Image ')+source.split('/')[-1]+_(' successfully written to')+target)
        self.success()
      else:
        self.logger(_('The process ended with an error !'))
        self.emergency()
        return False
Пример #29
0
    def event_cb(self, source, event):

        # TODO: Emit leave event when leaving top level widget.
        if event.type == gtk.gdk.LEAVE_NOTIFY and self._entered:
            self._entered = False
            event = gtk.gdk.Event(gtk.gdk.LEAVE_NOTIFY)
            self.emit('leave-notify-event', event)
            while gtk.events_pending():
                gtk.main_iteration()

        try:
            if event.x >= self.allocation.x\
                and event.y >= self.allocation.y\
                and event.x <= self.allocation.x + self.allocation.width\
                and event.y <= self.allocation.y + self.allocation.height:
                    self.event(event)
                    if event.type == gtk.gdk.MOTION_NOTIFY:
                        if not self._entered:
                            self._entered = True
                            event = gtk.gdk.Event(gtk.gdk.ENTER_NOTIFY)
                            self.emit('enter-notify-event', event)
                            while gtk.events_pending():
                                gtk.main_iteration()
            else:
                if event.type == gtk.gdk.MOTION_NOTIFY:
                    if self._entered:
                        self._entered = False
                        event = gtk.gdk.Event(gtk.gdk.LEAVE_NOTIFY)
                        self.emit('leave-notify-event', event)
                        while gtk.events_pending():
                            gtk.main_iteration()
        except:
            pass
Пример #30
0
 def download_headers(self,group,articles_number,server_name):
     last_number=str(0)
     #Downloading headers
     self.progressbar.set_text(_("Fetching Headers"))
     self.progressbar.set_fraction(1/float(2))
     while gtk.events_pending():
         gtk.main_iteration(False)
     message,total_headers,last=self.connectionsPool[server_name].getHeaders(group,0,count=articles_number)
     if last!=-1:
         last_number=str(last)
     self.statusbar.push(1,message)
     if total_headers:
         self.progressbar.set_text(_("Building Articles"))
     else:
         self.progressbar.set_text(_("No New Headers"))
     self.progressbar.set_fraction(2/float(2))
     while gtk.events_pending():
         gtk.main_iteration(False)
     
     self.art_db.createGroup(group)
     self.art_db.addHeaders(group,total_headers,server_name,self.connectionsPool)
         
     
     self.statusbar.push(1,_("Group subscribed"))
     self.progressbar.set_fraction(0)
     self.progressbar.set_text("")
     return last_number,message
Пример #31
0
class rulescreen:
    def make(self, gameDisplay):

        pygame.init()
        sound = True

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

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

        crashed = False
        disp_width = 600
        disp_height = 600

        press = 0

        info = pygame.display.Info()
        gameDisplay = pygame.display.get_surface()

        if not (gameDisplay):

            gameDisplay = pygame.display.set_mode(
                (info.current_w, info.current_h))

        frame1 = pygame.image.load("images/rulescreen/ruleframes/frame1.png")
        frame2 = pygame.image.load("images/rulescreen/ruleframes/frame2.png")
        frame3 = pygame.image.load("images/rulescreen/ruleframes/frame3.png")
        frame4 = pygame.image.load("images/rulescreen/ruleframes/frame4.png")
        frame5 = pygame.image.load("images/rulescreen/ruleframes/frame5.png")
        frame6 = pygame.image.load("images/rulescreen/ruleframes/frame6.png")
        frame7 = pygame.image.load("images/rulescreen/ruleframes/frame7.png")
        frame8 = pygame.image.load("images/rulescreen/ruleframes/frame8.png")
        frame9 = pygame.image.load("images/rulescreen/ruleframes/frame9.png")
        frame10 = pygame.image.load("images/rulescreen/ruleframes/frame10.png")
        frame11 = pygame.image.load("images/rulescreen/ruleframes/frame11.png")
        frame12 = pygame.image.load("images/rulescreen/ruleframes/frame12.png")
        frame13 = pygame.image.load("images/rulescreen/ruleframes/frame13.png")
        frame14 = pygame.image.load("images/rulescreen/ruleframes/frame14.png")
        frame15 = pygame.image.load("images/rulescreen/ruleframes/frame15.png")
        frame16 = pygame.image.load("images/rulescreen/ruleframes/frame16.png")
        frame17 = pygame.image.load("images/rulescreen/ruleframes/frame17.png")
        frame18 = pygame.image.load("images/rulescreen/ruleframes/frame18.png")
        frame19 = pygame.image.load("images/rulescreen/ruleframes/frame19.png")
        frame20 = pygame.image.load("images/rulescreen/ruleframes/frame20.png")
        frame21 = pygame.image.load("images/rulescreen/ruleframes/frame21.png")
        frame22 = pygame.image.load("images/rulescreen/ruleframes/frame22.png")
        frame23 = pygame.image.load("images/rulescreen/ruleframes/frame23.png")
        frame24 = pygame.image.load("images/rulescreen/ruleframes/frame24.png")
        frame25 = pygame.image.load("images/rulescreen/ruleframes/frame25.png")

        play = pygame.image.load("images/rulescreen/back.png")

        button = pygame.image.load("images/rulescreen/button.png")

        hide = pygame.image.load("images/rulescreen/hideboard.png").convert()

        framelist = [
            frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8,
            frame9, frame10, frame11, frame12, frame13, frame14, frame15,
            frame16, frame17, frame18, frame19, frame20, frame21, frame22,
            frame23, frame24, frame25
        ]

        font_path = "fonts/Arimo.ttf"
        font_size = 20
        font1 = pygame.font.Font(font_path, font_size)
        font2 = pygame.font.Font("fonts/Arimo.ttf", 30)
        font3 = pygame.font.Font("fonts/Arimo.ttf", 40)
        font4 = pygame.font.Font("fonts/Arimo.ttf", 20)

        chichi = pygame.mixer.Sound("sound/bird/bonus_trigger_bird.ogg")
        eating_fruit = pygame.mixer.Sound("sound/eating_fruit.ogg")
        perfectsound = pygame.mixer.Sound("sound/perfect.ogg")

        i = k = 0
        press = 0
        flag1 = flag2 = flag3 = 0

        # 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

            mos_x, mos_y = pygame.mouse.get_pos()

            # print event

            i += 1

            if (i > 30):
                i = 0

            # gameDisplay.fill(white)

            if (i == 30):
                k += 1
                if (k == 25):
                    k = 0
                    flag1 = flag2 = flag3 = 0

            gameDisplay.blit(pygame.transform.scale(framelist[k], (491, 768)),
                             (350, 0))

            if (k == 18 and flag1 == 0):
                chichi.play(0)
                flag1 = 1

            if (k == 16 and flag2 == 0):
                perfectsound.play(0)
                flag2 = 1

            if (k == 7 and flag3 == 0):
                eating_fruit.play(0)
                flag3 = 1

            head1 = font1.render("To roll hero upside-down use UP arrow key",
                                 1, (white))
            gameDisplay.blit(head1, (400, 100))

            gameDisplay.blit(button, (540, 140))

            gameDisplay.blit(hide, (400, 600))
            gameDisplay.blit(play, (500, 600))

            if play.get_rect(center=(500 + 92,
                                     600 + 33)).collidepoint(mos_x, mos_y):
                gameDisplay.blit(pygame.transform.scale(play, (189, 70)),
                                 (500 - 2, 600 - 2))

                if (pygame.mouse.get_pressed())[0] == 1 and press == 0:

                    return 0

                if event.type == pygame.MOUSEBUTTONUP:
                    press = 0

            # left and right black background patches

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

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

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

            # Game crash or Close check
            if crashed == True:
                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()
Пример #32
0
    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))
Пример #33
0
 def _on_status_finished(self, progress):
     """Called when something finished."""
     self._on_status_changed(progress, _("Complete"), 100)
     while gtk.events_pending():
         gtk.main_iteration()
Пример #34
0
 def __tick__(self):
     while gtk.events_pending():
         gtk.main_iteration_do(block=False)
Пример #35
0
 def on_start_activate(self, button):
     if runtime.get_external().rt or runtime.get_external().redmine or runtime.get_external().jira:
         group_comments = self.aggregate_comments_checkbox.get_active()
         it = self.tree_store.get_iter_first()
         to_report_list = []
         while it:
             ticket_row = self.tree_store.get_value(it, 0)
             child_iter = self.tree_store.iter_children(it)
             # get children
             export_rows = []
             while child_iter:
                 export_rows.append(self.tree_store.get_value(child_iter, 0))
                 child_iter = self.tree_store.iter_next(child_iter)
             # report tickets
             if group_comments:
                 comment = "\n".join("%s - %s min" % (row.comment, row.time_worked) for row in export_rows)
                 time_worked = sum([row.time_worked for row in export_rows])
                 facts = [row.fact for row in export_rows]
                 to_report_list.append({
                     'id': ticket_row.id,
                     'name': ticket_row.name,
                     'comment': comment,
                     'time': time_worked,
                     'facts': facts,
                     'date': row.date
                 })
             else:
                 for row in export_rows:
                     to_report_list.append({
                         'id': ticket_row.id,
                         'name': ticket_row.name,
                         'comment': "%s - %s min" % (row.comment, row.time_worked),
                         'time': row.time_worked,
                         'facts': [row.fact],
                         'date': row.date
                     })
             it = self.tree_store.iter_next(it)
         to_report_len = len(to_report_list)
         self.progressbar.set_fraction(0.0)
         for i in range(to_report_len):
             to_report = to_report_list[i]
             self.progressbar.set_text(_("Reporting: #%s: %s - %smin") % (to_report['id'], to_report['name'], to_report['time']))
             self.progressbar.set_fraction(float(i)/to_report_len)
             while gtk.events_pending():
                 gtk.main_iteration()
             if self.source == SOURCE_RT:
                 self.__add_rt_worklog(to_report['id'], to_report['comment'], to_report['time'], to_report['facts'])
             elif self.source == SOURCE_REDMINE:
                 self.__add_redmine_worklog(
                     to_report['id'],
                     to_report['date'],
                     math.ceil(to_report['time']*100/60)/100,
                     to_report['comment'],
                     to_report['facts']
                 )
             elif self.source == SOURCE_JIRA:
                 self.__add_jira_worklog(to_report['id'], to_report['comment'], to_report['time'], to_report['facts'])
         self.progressbar.set_text("Done")
         self.progressbar.set_fraction(1.0)
     else:
         logging.warn(_("Not connected to/logged in RT"))
     self.start_button.set_sensitive(False)
     # TODO only if parent is overview
     self.parent.search()
Пример #36
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/comicsans.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()
Пример #37
0
 def flush_events(self):
     gtk.gdk.threads_enter()
     while gtk.events_pending():
         gtk.main_iteration(True)
     gtk.gdk.flush()
     gtk.gdk.threads_leave()
Пример #38
0
    def run(self):
        g.init()
        if not self.journal: utils.load()
        self.tr = [None, None, None, None]
        self.menu = menu.Menu(4, 4, g.sy(.2), g.sy(1.3), g.sy(.2))
        load_save.retrieve()
        self.buttons_setup()
        self.slider = [None, None]
        self.slider[0] = slider.Slider(g.sx(16), g.sy(20.8), 2, utils.GREEN)
        self.slider[1] = slider.Slider(g.sx(16), g.sy(20.8), 3, utils.GREEN)
        self.levels = [1] * 16
        if self.canvas <> None: self.canvas.grab_focus()
        ctrl = False
        pygame.key.set_repeat(600, 120)
        key_ms = pygame.time.get_ticks()
        going = True
        while going:
            if self.journal:
                # Pump GTK messages.
                while gtk.events_pending():
                    gtk.main_iteration()

            # Pump PyGame messages.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    if not self.journal: utils.save()
                    going = False
                elif event.type == pygame.MOUSEMOTION:
                    g.pos = event.pos
                    g.redraw = True
                    if self.canvas <> None: self.canvas.grab_focus()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    g.redraw = True
                    if event.button == 1:
                        if self.do_click():
                            pass
                        else:
                            if g.state == 'jigsaw':
                                bu = buttons.check()
                                if bu != '':
                                    self.do_button(bu)
                                    self.flush_queue()
                elif event.type == pygame.KEYDOWN:
                    # throttle keyboard repeat
                    if pygame.time.get_ticks() - key_ms > 110:
                        key_ms = pygame.time.get_ticks()
                        if ctrl:
                            if event.key == pygame.K_q:
                                if not self.journal: utils.save()
                                going = False
                                break
                            else:
                                ctrl = False
                        if event.key in (pygame.K_LCTRL, pygame.K_RCTRL):
                            ctrl = True
                            break
                        self.do_key(event.key)
                        g.redraw = True
                        self.flush_queue()
                elif event.type == pygame.KEYUP:
                    ctrl = False
            if not going: break
            if g.redraw:
                self.display()
                if g.version_display: utils.version_display()
                g.screen.blit(g.pointer, g.pos)
                pygame.display.flip()
                g.redraw = False
            g.clock.tick(40)
Пример #39
0
 def gtk_main_tick():
     while gtk.events_pending():
         gtk.main_iteration()
Пример #40
0
 def set_fraction(self, fraction):
   self.progressbar.set_fraction(fraction)
   while gtk.events_pending():   
     gtk.main_iteration_do(False)
Пример #41
0
 def _on_status_timeout(self, progress):
     """Called when timeout happens."""
     self._expander.set_expanded(True)
     while gtk.events_pending():
         gtk.main_iteration()
Пример #42
0
    def run(self):
        self.running = True

        if pygame.mixer and not pygame.mixer.get_init():
            print 'Warning, no sound'
            pygame.mixer = None

        #set the screen up
        winstyle = 0  # |FULLSCREEN
        bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
        screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

        # load images here
        # for gifs  img = load_image('filename.gif')
        # for bmps img = pygame.image.load('filename.bmp') but our function handles that for us
        # a note for graphics blit means copy pixels from screen.blit()
        iconImg = load_image('blocku.png')
        background = load_image('background.png')
        # load images to pipe to the sprite classes
        blockImg = load_image('block.png')
        Block.images = [blockImg]
        gridImg = load_image('grid.png')
        # the test will need rects and positions i sugest make some kind of default
        # this information can be held by each block as they are created but is made here

        #get the image and screen in the same format
        if background.get_bitsize() == 8:
            screen.set_palette(background.get_palette())
        else:
            background = background.convert()

        background.blit(gridImg, (200, 200))
        screen.blit(background, (0, 0))
        pygame.display.flip()

        #to set the icon up and to decorate the game window
        icon = pygame.transform.scale(iconImg, (32, 32))
        pygame.display.set_icon(icon)
        pygame.display.set_caption('Blocku')

        #this next call is sort of like sprite batch . draw
        spriteBatch = pygame.sprite.RenderUpdates()

        #main blocku code structs
        blocks = pygame.sprite.Group()
        Block.containers = blocks, spriteBatch
        #blocks are Block(n,s,e,w,x,y) xy= starting position
        aBlock = Block(1, 2, 3, 4, 200, 200)
        bBlock = Block(5, 6, 7, 8, 300, 300)

        global debugText
        debugText = ''
        #see if there is a sprite font
        if pygame.font:
            spriteBatch.add(Text('Drawing call test '))
            spriteBatch.add(mouseUpdate())

        #if a key is down
        global keyDown
        keyDown = False
        # it is important to note that like xna the origin is 0,0
        # the top left of the current window
        # print is trace in console
        # and increases as you go down and to the right
        # pygame has a collision detector under pygame.sprite.spritecollide(group,group,dokill)
        # this will return a list of colliders, dokill will remove the colliders from the parrent group if true

        while self.running:
            # Pump GTK messages.
            while gtk and gtk.events_pending():
                gtk.main_iteration()

            # Pump PyGame messages.
            for e in event.get():
                if e.type == QUIT or \
                    (e.type == KEYDOWN and e.key == K_ESCAPE):
                    return
                elif e.type == pygame.VIDEORESIZE:
                    pygame.display.set_mode(e.size, pygame.RESIZABLE)
                if e.type == MOUSEBUTTONDOWN:
                    event.set_grab(1)
                elif e.type == MOUSEBUTTONUP:
                    event.set_grab(0)

            # get the state of the keyboard for input
            keystate = pygame.key.get_pressed()
            if not keystate[K_SPACE]:
                keyDown = False
            # for key test use keystate[key] and a return of true will occur when key down
            # clear/erase the last drawn sprites
            spriteBatch.clear(screen, background)
            # update all the sprites
            spriteBatch.update()
            # handle player input
            if keystate[K_UP]:
                aBlock.move(0)
            if keystate[K_RIGHT]:
                aBlock.move(1)
            if keystate[K_DOWN]:
                aBlock.move(2)
            if keystate[K_LEFT]:
                aBlock.move(3)
            if keystate[K_SPACE] and not keyDown:
                aBlock.rotate()
                keyDown = True

            #for block in blocks:
            x, y = mouse.get_pos()

            if event.get_grab():
                debugText = 'holding mouse button 1'
                if aBlock.rect.collidepoint(x, y):
                    aBlock.grab(mouse.get_pos())
                    debugText += 'grabed aBlock'
                elif bBlock.rect.collidepoint(x, y):
                    bBlock.grab(mouse.get_pos())
                    debugText += 'grabed bBlock'
            else:
                debugText = ''
            # note random here is random.random()
            # note foreach here is for object in

            # draw call for the screen
            draw = spriteBatch.draw(screen)
            pygame.display.update(draw)

            # Try to stay at 30 FPS
            self.clock.tick(30)
Пример #43
0
    def run(self, name):
        """Import movies, function called in a loop over source files"""
        from add import validate_details, edit_movie
        from sqlalchemy import select
        import gtk

        name = name.decode('utf-8')
        if not self.set_source(name):
            log.info("Can't read data from file %s", name)
            return False

        self.widgets['pwindow'].show()
        while gtk.events_pending():  # give GTK some time for updates
            gtk.main_iteration()

        # progressbar
        update_on = []
        count = self.count_movies()
        if count > 0:
            for i in range(0, 100):
                update_on.append(int(float(i) / 100 * count))

        session = self.db.Session()
        session.bind = self.db.session.bind

        # move some stuff outside the loop to speed it up
        set_fraction = self.widgets['progressbar'].set_fraction
        set_text = self.widgets['progressbar'].set_text
        main_iteration = gtk.main_iteration

        # get some values from DB to avoid queries in the loop
        statement = select([db.Movie.number, db.Movie.title, db.Movie.o_title])
        data = session.execute(statement).fetchall()
        numbers = set(i[0] for i in data)
        titles = set(i[1].lower() for i in data if i[1])
        o_titles = set(i[2].lower() for i in data if i[2])

        gc_was_enabled = gc.isenabled()
        if gc_was_enabled:
            gc.collect()
            gc.disable()

        begin = time.time()
        processed = 0
        try:
            while self._continue:
                details = self.get_movie_details()
                if details is None:
                    break

                processed += 1
                if processed in update_on:
                    set_fraction(float(processed) / count)
                    main_iteration()
                    set_text("%s (%s/%s)" % (self.imported, processed, count))
                    main_iteration()
                    main_iteration()  # extra iteration for abort button

                o_title_lower = details.get('o_title', '').lower()
                title_lower = details.get('title', '').lower()

                if o_title_lower or title_lower:
                    if o_title_lower and o_title_lower in o_titles:
                        if title_lower and title_lower in titles:
                            log.info(
                                "movie already exists (o_title=%s, title=%s)",
                                details['o_title'], details['title'])
                            continue
                    elif title_lower and title_lower in titles:  # o_title is not available so lets check title only
                        log.info("movie already exists (title=%s)",
                                 details['title'])
                        continue
                    if self.edit:  # XXX: not used for now
                        validate_details(details, self.fields_to_import)
                        response = edit_movie(
                            self.parent, details
                        )  # FIXME: wait until save or cancel button pressed
                        if response == 1:
                            self.imported += 1
                    else:
                        # get the number and make it unique. number is needed later
                        number = details.get('number', 1)
                        while number in numbers:
                            number += 1
                        if 'tags' in details:
                            tags = details.pop('tags')
                        else:
                            tags = None
                        poster = None
                        if 'poster' in details:
                            poster = details.pop('poster')
                        elif 'image' in details:
                            poster = details.pop('image')
                        try:
                            # optional: do mapping of lookup data
                            if not self.foreignkeymaps:
                                self._loadmappings()
                            for fkcolumnname in self.foreignkeymaps:
                                try:
                                    if fkcolumnname in details and details[
                                            fkcolumnname]:
                                        fkcolumn_id = int(
                                            details[fkcolumnname])
                                except:
                                    try:
                                        fkcolumn_id = self.normalizename(
                                            details[fkcolumnname])
                                        currentmap = self.foreignkeymaps[
                                            fkcolumnname]
                                        if fkcolumn_id in currentmap:
                                            details[fkcolumnname] = currentmap[
                                                fkcolumn_id]
                                        else:
                                            details[
                                                fkcolumnname] = self._addmappingvalue(
                                                    fkcolumnname,
                                                    details[fkcolumnname])
                                    except:
                                        log.exception(fkcolumnname)
                                        details[fkcolumnname] = None
                            # validation before insertion
                            validate_details(details, self.fields_to_import)
                            # set number here again because if it is not selected validate_details will remove it
                            details['number'] = number
                            # insert the movie in the database
                            movie = db.tables.movies.insert(
                                bind=self.db.session.bind).execute(details)
                            self.imported += 1
                            # optional: adding tags
                            if tags:
                                if self.tagmap is None:
                                    self.loadmappings()
                                for tag in tags:
                                    try:
                                        if isinstance(tag, (str, unicode)):
                                            # TODO: adding new tag names?
                                            tag_id = self.tagmap[tag.lower()]
                                        else:
                                            tag_id = int(tag)
                                        db.tables.movie_tag.insert(
                                            bind=self.db.session.bind).execute(
                                                {
                                                    'movie_id':
                                                    movie.lastrowid,
                                                    'tag_id': tag_id
                                                })
                                    except:
                                        pass
                            self.db.session.commit()
                            # adding poster
                            if poster:
                                if len(poster) > 4:
                                    # check for JPEG/PNG header otherwise it should be a filename
                                    header = struct.unpack_from('4s',
                                                                poster)[0]
                                    if header == '\xff\xd8\xff\xe0' or \
                                       header == '\x89\x50\x4e\x47':
                                        # make a temporary file
                                        try:
                                            posterfilefd, posterfilename = mkstemp(
                                                '.img')
                                            try:
                                                os.write(posterfilefd, poster)
                                            finally:
                                                os.close(posterfilefd)
                                            edit.update_image(
                                                self.parent, number,
                                                posterfilename)
                                        finally:
                                            if os.path.isfile(posterfilename):
                                                os.remove(posterfilename)
                                    else:
                                        edit.update_image(
                                            self.parent, number, poster)
                        except Exception:
                            log.exception(
                                "movie details are not unique, skipping")
                        numbers.add(number)
                else:
                    log.info('skipping movie without title and original title')
        finally:
            log.info("Import process took %s s; %s/%s movies imported",
                     (time.time() - begin), processed, count)
            if gc_was_enabled:
                gc.enable()
            self.widgets['pwindow'].hide()
        return True
Пример #44
0
    def grind(self):
        while gtk.events_pending():
            gtk.main_iteration(False)

        self.prog.pulse()
Пример #45
0
def gtk_process_events():
    while gtk.events_pending():
        gtk.main_iteration()
Пример #46
0
    def set(self, fraction):
        while gtk.events_pending():
            gtk.main_iteration(False)

        self.prog.set_fraction(fraction)
Пример #47
0
    def run(self):
        g.init()
        g.journal = self.journal
        if not self.journal:
            utils.load()
            self.best = g.best
        else:
            g.best = self.best
        self.castle = cas.Castle(4)  # 4x4 - 3x3 is ok too
        self.castle.setup()
        self.bu_setup()
        going = True
        while going:
            ms = pygame.time.get_ticks()
            g.mx, g.my = pygame.mouse.get_pos()
            # Pump GTK messages.
            while gtk.events_pending():
                gtk.main_iteration()

            # Pump PyGame messages.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    if not self.journal: utils.save()
                    going = False
                elif event.type == pygame.MOUSEMOTION:
                    g.redraw = True
                    if self.canvas <> None: self.canvas.grab_focus()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    g.redraw = True
                    if event.button == 2:  # centre button
                        g.version_display = not g.version_display
                        break
                    if g.state == 1:
                        if g.telep_ms <> None:
                            g.telep_ms = None
                            break  # stop teleporting
                        bu = buttons.check()
                        if bu != '':
                            self.do_button(bu)
                            break
                    if g.health > 0: self.click()
                elif event.type == pygame.MOUSEBUTTONUP:
                    g.redraw = True
                    if event.button == 1:
                        self.bu_clear()
                elif event.type == pygame.KEYDOWN:
                    if g.direction == '': self.do_key(event.key)
                elif event.type == pygame.KEYUP:
                    g.redraw = True
                    self.bu_clear()
            if not going: break
            self.castle.move(g.direction)
            self.castle.update()
            if g.health == 0: self.bus_off()
            if g.redraw:
                self.display()
                if g.version_display: utils.version_display()
                if g.my > g.pointer.get_height():
                    g.screen.blit(g.pointer, (g.mx, g.my))
                pygame.display.flip()
                g.redraw = False
            if g.best < g.score: g.best = g.score
            self.best = g.best
            g.clock.tick(40)
            d = pygame.time.get_ticks() - ms
            g.frame_rate = int(1000 / d)
Пример #48
0
def update_ui():
    if gtk.events_pending():
        while gtk.events_pending():
            gtk.main_iteration(False)
Пример #49
0
 def destroy(self):
     gtk.Window.destroy(self)
     while gtk.events_pending():
         gtk.main_iteration()
Пример #50
0
 def flush(self):
     #_STDOUT.write('*** flush called ***')
     while gtk.events_pending():
         gtk.main_iteration(False)
     return
Пример #51
0
 def find_in_all_nodes(self, father_tree_iter):
     """Search for a pattern in all the Tree Nodes"""
     if not self.from_find_iterated:
         self.latest_node_offset = {}
         iter_insert = self.dad.curr_buffer.get_iter_at_mark(self.dad.curr_buffer.get_insert())
         iter_bound = self.dad.curr_buffer.get_iter_at_mark(self.dad.curr_buffer.get_selection_bound())
         entry_predefined_text = self.dad.curr_buffer.get_text(iter_insert, iter_bound)
         if entry_predefined_text:
             self.dad.search_replace_dict['find'] = entry_predefined_text
         if self.replace_active:
             if father_tree_iter: title = _("Replace in Selected Node and Subnodes")
             else: title = _("Replace in All Nodes")
         else:
             if father_tree_iter: title = _("Search in Selected Node and Subnodes")
             else: title = _("Search in All Nodes")
         pattern = self.dad.dialog_search(title, self.replace_active)
         if entry_predefined_text != "":
             self.dad.curr_buffer.move_mark(self.dad.curr_buffer.get_insert(), iter_insert)
             self.dad.curr_buffer.move_mark(self.dad.curr_buffer.get_selection_bound(), iter_bound)
         if pattern != None:
             if not father_tree_iter: self.curr_find = ["in_all_nodes", pattern]
             else: self.curr_find = ["in_sel_nod_n_sub", pattern]
         else: return
     else: pattern = self.curr_find[1]
     starting_tree_iter = self.dad.curr_tree_iter.copy()
     current_cursor_pos = self.dad.curr_buffer.get_property(cons.STR_CURSOR_POSITION)
     forward = self.dad.search_replace_dict['fw']
     if self.from_find_back:
         forward = not forward
         self.from_find_back = False
     first_fromsel = self.dad.search_replace_dict['a_ff_fa'] == 1
     all_matches = self.dad.search_replace_dict['a_ff_fa'] == 0
     if first_fromsel or father_tree_iter:
         self.first_useful_node = False # no one node content was parsed yet
         node_iter = self.dad.curr_tree_iter.copy()
     else:
         self.first_useful_node = True # all range will be parsed so no matter
         if forward: node_iter = self.dad.treestore.get_iter_first()
         else: node_iter = self.dad.get_tree_iter_last_sibling(None)
     self.matches_num = 0
     if all_matches: self.liststore.clear()
     config.get_tree_expanded_collapsed_string(self.dad)
     # searching start
     if self.dad.user_active:
         self.dad.user_active = False
         user_active_restore = True
     else: user_active_restore = False
     self.processed_nodes = 0
     self.latest_matches = 0
     self.dad.update_num_nodes()
     if all_matches:
         self.dad.progressbar.set_text("0")
         self.dad.progresstop.show()
         self.dad.progressbar.show()
         while gtk.events_pending(): gtk.main_iteration()
     search_start_time = time.time()
     while node_iter:
         self.all_matches_first_in_node = True
         while self.parse_given_node_content(node_iter, pattern, forward, first_fromsel, all_matches):
             self.matches_num += 1
             if not all_matches or self.dad.progress_stop: break
         if self.matches_num == 1 and not all_matches: break
         if father_tree_iter and not self.from_find_iterated: break
         last_top_node_iter = node_iter.copy() # we need this if we start from a node that is not in top level
         if forward: node_iter = self.dad.treestore.iter_next(node_iter)
         else: node_iter = self.dad.get_tree_iter_prev_sibling(self.dad.treestore, node_iter)
         if not node_iter and father_tree_iter: break
         # code that, in case we start from a node that is not top level, climbs towards the top
         while not node_iter:
             node_iter = self.dad.treestore.iter_parent(last_top_node_iter)
             if node_iter:
                 last_top_node_iter = node_iter.copy()
                 # we do not check the parent on purpose, only the uncles in the proper direction
                 if forward: node_iter = self.dad.treestore.iter_next(node_iter)
                 else: node_iter = self.dad.get_tree_iter_prev_sibling(self.dad.treestore, node_iter)
             else: break
         if self.dad.progress_stop: break
         self.processed_nodes += 1
         if all_matches:
             self.update_all_matches_progress()
     search_end_time = time.time()
     print search_end_time - search_start_time, "sec"
     if user_active_restore: self.dad.user_active = True
     config.set_tree_expanded_collapsed_string(self.dad)
     if not self.matches_num or all_matches:
         self.dad.treeview_safe_set_cursor(starting_tree_iter)
         self.dad.objects_buffer_refresh()
         self.dad.sourceview.grab_focus()
         self.dad.curr_buffer.place_cursor(self.dad.curr_buffer.get_iter_at_offset(current_cursor_pos))
         self.dad.sourceview.scroll_to_mark(self.dad.curr_buffer.get_insert(), 0.3)
     if not self.matches_num:
         support.dialog_info(_("The pattern '%s' was not found") % pattern, self.dad.window)
     else:
         if all_matches:
             self.allmatchesdialog.set_title(str(self.matches_num) + cons.CHAR_SPACE + _("Matches"))
             self.allmatchesdialog.run()
             self.allmatchesdialog.hide()
         else:
             self.dad.treeview_safe_set_cursor(self.dad.curr_tree_iter)
             if self.dad.search_replace_dict['idialog']:
                 self.iterated_find_dialog()
     if all_matches:
         assert self.processed_nodes == self.dad.num_nodes or self.dad.progress_stop
         self.dad.progresstop.hide()
         self.dad.progressbar.hide()
         self.dad.progress_stop = False
Пример #52
0
 def _on_status_started(self, progress):
     """Called when something starts."""
     self._on_status_changed(progress, _("Starting..."), 0)
     while gtk.events_pending():
         gtk.main_iteration()
Пример #53
0
def parseAndGenerate(dirName, XMLChain, installDirName):
    cleanGenerator()
    global g_bSaveVideo  # Passando todas as variaveis globais devolta ao default
    global g_bLive
    global g_bVideo
    global g_bCameras
    global g_bFrameRate
    global g_ShowCount
    g_ShowCount = 0
    g_bSaveVideo = []
    g_bVideo = []
    g_bCameras = []
    g_bFrameRate = 0.1
    g_bLive = False  # this shall be a list containing the "blockNumbers" for each live acquisition block; len(g_bLive) works just like it is now..
    yield [_("Starting Up Generator")]
    #doc = binderytools.bind_file(XMLChain)
    doc = XMLParser(XMLChain)
    ########################Create the blocks from XMLChain############################

    ##################################################################################
    #				in the future we may want to show some kind of progress bar..
    #							the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
    ##################################################################################
    # t_nBlockCount = 0.0
    # for block in (doc.harpia.properties.block):
    # t_nBlockCount += 1.0
    # t_nItCount = 0.0
    yield [_("Generating Code")]
    blocks = doc.getTag("harpia").getTag("properties").getChildTags("block")
    for blockIter in blocks:
        # print str(100.0*(t_nItCount/t_nBlockCount)) + "%"
        # t_nItCount += 1.0
        tmpBlock = blockTemplate()
        tmpBlock.blockType = blockIter.type
        tmpBlock.blockNumber = blockIter.id
        tmpBlock.properties = []
        tmpBlock.myConnections = []
        tmpBlock.outputsToSave = []
        try:
            block_properties = blockIter.getChildTags("property")
            for propIter in block_properties:
                tmpBlock.properties.append((propIter.name, propIter.value))
        except AttributeError:
            pass
        ID = tmpBlock.blockNumber
        tmpBlock.getBlockOutputTypes()

        net_blocks = doc.getTag("harpia").getTag("network").getChildTags(
            "block")
        for block in net_blocks:
            if (block.id == ID and int(block.type) <> 10):
                portCount = -1
                outputs = block.getTag("outputs").getChildTags("output")
                for output in outputs:
                    tmpConnection = connection()
                    portCount += 1
                    if output.inBlock != '--':
                        tmpConnection.sourceOutput = output.id
                        tmpConnection.destinationInput = output.input
                        tmpConnection.destinationNumber = output.inBlock
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        # !!!!!!cpscotti type-oriented connections...!!!!!
                        tmpConnection.connType = tmpBlock.outTypes[
                            int(tmpConnection.sourceOutput) - 1]
                        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        tmpBlock.myConnections.append(tmpConnection)
                    else:
                        tmpConnection.destinationNumber = '--'
                        tmpBlock.myConnections.append(tmpConnection)
                    try:
                        if output.grab == 'True':
                            tmpBlock.outputsToSave.append(output.id)
                    except:
                        pass
                    ###################################################################################
                    # ADDING TO EACH BLOCK OBJECT THE RESULTING CODE , THEN ADDING THE BLOCK IN A LIST #
                    ###################################################################################
                    ##Please, do not change the sequence
        tmpBlock.blockCodeWriter()
        tmpBlock.connectorCodeWriter()
        tmpBlock.saverCodeWriter()
        blockList.append(tmpBlock)
    ###################################################################################

    weights = []

    # Apply the weights on each connection of each block in listOfBlocks, then return a list with its connections
    def applyWeightsOnConnections(listOfBlocks):
        # def applyWeightsOnConnections(listOfBlocks,RollinList):
        ##For each block on listt:
        returnList = []
        for block in listOfBlocks:
            ##Put the connections on returnList
            for connection in block.myConnections:
                ##and apply the weight on this connection
                for tmpBlock in blockList:
                    if tmpBlock.blockNumber == connection.destinationNumber:
                        tmpBlock.weight += block.weight
                        if tmpBlock not in returnList:
                            # if tmpBlock not in RollinList:
                            returnList.append(tmpBlock)
                        # RollinList.append(tmpBlock)
        return returnList

    for block in blockList:
        # cpscotti..
        # if block.blockType == '00':
        if len(s2idirectory.block[int(
                block.blockType)]["InTypes"]) == 0 and len(
                    s2idirectory.block[int(block.blockType)]["OutTypes"]) <> 0:
            tmpList = []
            # RollinPathList = []
            tmpList.append(block)
            # RollinPathList.append(block)
            organizedChain = applyWeightsOnConnections(
                tmpList)  # ,RollinPathList)
            while organizedChain <> []:
                organizedChain = applyWeightsOnConnections(
                    organizedChain)  # ,RollinPathList)
            ###Recursive tests... future functionality
            # print "Start: "
            # for block in organizedChain:
            # print "\t"+str(block.blockNumber)

    biggestWeight = -1
    for block in blockList:
        if block.weight >= biggestWeight:
            biggestWeight = block.weight

    for activeWeight in range(biggestWeight):
        activeWeight += 1
        for block in blockList:
            if block.weight == activeWeight:
                arguments.append(block.functionArguments)
                images.append(block.imagesIO)
                functionCalls.append("//Weight: " + str(block.weight) + "\n")
                functionCalls.append(block.functionCall)
                deallocations.append(block.dealloc)
                outDeallocations.append(block.outDealloc)

    header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

#define PI 3.1415926535898
double rads(double degs)
{
	return (PI/180 * degs);
}
		"""
    global usesFindSquares
    if usesFindSquares == 1:
        header += r"""

//Routines to findSquares
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
{
		double dx1 = pt1->x - pt0->x;
		double dy1 = pt1->y - pt0->y;
		double dx2 = pt2->x - pt0->x;
		double dy2 = pt2->y - pt0->y;
		return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

CvSeq* findSquares4( IplImage* img, CvMemStorage* storage, int minArea, int maxArea)
{
		CvSeq* contours;
		int i, c, l, N = 11;
		int thresh = 50;
		CvSize sz = cvSize( img->width & -2, img->height & -2 );
		IplImage* timg = cvCloneImage( img ); // make a copy of input image
		IplImage* gray = cvCreateImage( sz, 8, 1 ); 
		IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
		IplImage* tgray;
		CvSeq* result;
		double s, t;

		if(minArea == -1)
			minArea = 0;
		if(maxArea == -1)
			maxArea = (img->width * img->height);

		CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
		

		cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
		
		// down-scale and upscale the image to filter out the noise
		cvPyrDown( timg, pyr, CV_GAUSSIAN_5x5 );
		cvPyrUp( pyr, timg, CV_GAUSSIAN_5x5 );
		tgray = cvCreateImage( sz, 8, 1 );
		
		// find squares in every color plane of the image
		for( c = 0; c < 3; c++ )



		{
				// extract the c-th color plane
				cvSetImageCOI( timg, c+1 );
				cvCopy( timg, tgray, 0 );
				for( l = 0; l < N; l++ )
				{
						if( l == 0 )
						{
								cvCanny( tgray, gray, 0, thresh, 5 );
								cvDilate( gray, gray, 0, 1 );
						}
						else
						{
								cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
						}
						cvFindContours( gray, storage, &contours, sizeof(CvContour),
								CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
						while( contours )
						{
								result = cvApproxPoly( contours, sizeof(CvContour), storage,
										CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
								if( result->total == 4 &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) > minArea &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) < maxArea &&
										cvCheckContourConvexity(result) )
								{
										s = 0;
										
										for( i = 0; i < 5; i++ )
										{
												if( i >= 2 )
												{
														t = fabs(angle(
														(CvPoint*)cvGetSeqElem( result, i ),
														(CvPoint*)cvGetSeqElem( result, i-2 ),
														(CvPoint*)cvGetSeqElem( result, i-1 )));
														s = s > t ? s : t;
												}
										}
										if( s < 0.3 )
												for( i = 0; i < 4; i++ )
														cvSeqPush( squares,
																(CvPoint*)cvGetSeqElem( result, i ));
								}
								contours = contours->h_next;
						}
				}
		}
		cvReleaseImage( &gray );
		cvReleaseImage( &pyr );
		cvReleaseImage( &tgray );
		cvReleaseImage( &timg );
		return squares;
}

double drawSquares( IplImage* cpy, CvSeq* squares )
{
		CvSeqReader reader;
		int i;
		cvStartReadSeq( squares, &reader, 0 );
		for( i = 0; i < squares->total; i += 4 )
		{
				CvPoint pt[4], *rect = pt;
				int count = 4;
				CV_READ_SEQ_ELEM( pt[0], reader );
				CV_READ_SEQ_ELEM( pt[1], reader );
				CV_READ_SEQ_ELEM( pt[2], reader );
				CV_READ_SEQ_ELEM( pt[3], reader );
				cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
		}
	return (double)squares->total;
}

//End of routines to findSquares

			"""
    global usesFindColor
    if usesFindColor == 1:
        header += r"""

int GetColor(IplImage * imagem, int x, int y)
{
	return   (int)(((uchar*)(imagem->imageData + imagem->widthStep*y))[x]);
}

void SetColor(IplImage * imagem, int x, int y, uchar color)
{
	((uchar*)(imagem->imageData + imagem->widthStep*y))[x] = color;
}


void CheckImg(IplImage * img, uchar c_value, uchar tolerance)
{
	uchar min,max;
	int y_It,x_It;
	if((int)c_value < (int)tolerance)
		tolerance = c_value;

	if(((int)c_value+(int)tolerance) > 255)
		tolerance = 255 - c_value;

	min = c_value - tolerance;
	max = c_value + tolerance;

	for(y_It=0;y_It<(img->height);y_It++)
		for(x_It=0;x_It<(img->width);x_It++)
		{
				uchar val;
				val = GetColor(img,x_It,y_It);
				if(val >= min && val <= max)
					SetColor(img,x_It,y_It,255);
				else
					SetColor(img,x_It,y_It,0);
		}
}

CvPoint GetCenter(IplImage * src, long int * nOfPts)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	long int posXsum;
	long int posYsum;
	int x_It, y_It;
	CvPoint Center;
	
	posXsum = 0;
	posYsum = 0;
	numOfMatchingPoints = 0;

	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				posXsum += x_It;
				posYsum += y_It;
				numOfMatchingPoints++;
			}

	if(numOfMatchingPoints > 0)
	{
		Center.x = (int)(posXsum/numOfMatchingPoints);
		Center.y = (int)(posYsum/numOfMatchingPoints);
	}
	else
		numOfMatchingPoints = -1;
// 	(*numOfPoints) = numOfMatchingPoints;
	if(nOfPts)
		*nOfPts = numOfMatchingPoints;

	return Center;
}


double dist22Points(CvPoint a, CvPoint b)
{
	int xD,yD;
	xD = a.x - b.x;
	yD = a.y - b.y;

	xD = (xD>0)?xD:-xD;
	yD = (yD>0)?yD:-yD;

	return (double)(xD*xD + yD*yD);
}

double GetVariance(IplImage * src,CvPoint center)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	double distSquaresSum;
	double variance;
	int x_It,y_It;

	numOfMatchingPoints = 0;
	distSquaresSum = 0.0;


	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				numOfMatchingPoints++;
				distSquaresSum += dist22Points(center,cvPoint(x_It,y_It));
			}

	if(numOfMatchingPoints)
		variance = distSquaresSum/numOfMatchingPoints;
	else
		variance = -1;


	return variance;
}

long int CheckForColor(IplImage * src, IplImage * dst, uchar * c_value, uchar * tolerance, CvPoint * pointCenter, double * variance)
{
	uchar B,B_T,G,G_T,R,R_T;
	int i;
	long int numOfPoints;
	CvPoint centro;
	IplImage * m_pChans[3] = {NULL,NULL,NULL};

	numOfPoints = 0;

	B = c_value[0];
	G = c_value[1];
	R = c_value[2];

	B_T = tolerance[0];
	G_T = tolerance[1];
	R_T = tolerance[2];

	for(i=0;i<3;i++)
		m_pChans[i] = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U, 1);

	cvSplit(src,m_pChans[0],m_pChans[1],m_pChans[2], NULL);

	CheckImg(m_pChans[0],B,B_T);
	CheckImg(m_pChans[1],G,G_T);
	CheckImg(m_pChans[2],R,R_T);

	cvAnd(m_pChans[0], m_pChans[1], dst, NULL );
	cvAnd(m_pChans[2], dst, dst, NULL );

	centro = GetCenter(dst,&numOfPoints);//,&numOfPoints);

	if(numOfPoints != -1)
		*variance = GetVariance(dst,centro);

	pointCenter->x = centro.x;
	pointCenter->y = centro.y;

	cvReleaseImage( &m_pChans[0] );
	cvReleaseImage( &m_pChans[1] );
	cvReleaseImage( &m_pChans[2] );

	return numOfPoints;
}
			"""
    header += "\nint main(int argc, char ** argv)\n{"

    declaration = "\n\t//declaration block\n"

    for x in arguments:
        declaration = declaration + x

    for x in images:
        declaration = declaration + x

    if g_bLive:
        declaration += \
            'int end;  end = 0; int key; \n'
        for aCapture in g_bVideo:
            declaration += 'CvCapture * block' + aCapture[
                0] + '_capture = NULL; \n IplImage * block' + aCapture[
                    0] + '_frame = NULL; \n block' + aCapture[
                        0] + '_capture = cvCreateFileCapture("' + aCapture[
                            1] + '"); \n'
        for aCamera in g_bCameras:
            declaration += 'CvCapture * block' + aCamera[
                0] + '_capture = NULL; \n IplImage * block' + aCamera[
                    0] + '_frame = NULL; \n block' + aCamera[
                        0] + '_capture = cvCaptureFromCAM(' + aCamera[
                            1] + '); \n'
        declaration += 'while(!end) \n {\t \n'

        for aCapture in g_bVideo:
            declaration += 'cvGrabFrame (block' + aCapture[
                0] + '_capture); \n block' + aCapture[
                    0] + '_frame = cvRetrieveFrame (block' + aCapture[
                        0] + '_capture); \n'

        for aCamera in g_bCameras:
            declaration += 'cvGrabFrame (block' + aCamera[
                0] + '_capture); \n block' + aCamera[
                    0] + '_frame = cvRetrieveFrame (block' + aCamera[
                        0] + '_capture); \n'

    execution = "\n\t//execution block\n"
    for x in functionCalls:
        execution += x
    if g_ShowCount == 0:
        execution += '\n\tcvNamedWindow("Control Window",CV_WINDOW_AUTOSIZE );'
    if g_bLive:
        execution += '\n\tkey = cvWaitKey (' + str(
            int((1.0 / g_bFrameRate) *
                1000.0)) + ');\n if(key != -1)\n end = 1;'

        deallocating = "\n\t//deallocation block\n"
        for x in deallocations:
            deallocating += x

        deallocating += "}"

    else:
        deallocating = "\n\t//deallocation block\n"

        for x in deallocations:
            deallocating += x

    closing = ""
    closing += "\n"
    for outDea in outDeallocations:
        closing += outDea
    if g_bLive:
        for aCapture in g_bVideo:
            closing += 'cvReleaseCapture(&block' + aCapture[0] + '_capture);\n'
        for aCamera in g_bCameras:
            closing += 'cvReleaseCapture(&block' + aCamera[0] + '_capture);\n'
    for vWriter in g_bSaveVideo:
        closing += 'cvReleaseVideoWriter(&block' + vWriter + '_vidWriter);\n'
    closing += "return 0;\n } //closing main()\n"

    # Final code assembly
    entireCode = header + declaration + execution + deallocating + closing

    yield [_("Saving Code")]
    # saving code file
    os.chdir(tmpDir + dirName)
    codeFilename = dirName + '.c'
    codeFile = open(codeFilename, 'w')
    codeFile.write(entireCode)
    codeFile.close()

    yield [_("Building Makefile")]
    # Assembly of "necessary" makefiles
    # ...windows..
    makeFilename = 'Makefile' + dirName + '.bat'
    makeFileEntry = '"' + installDirName + '\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[:
                                                                                                     -2] + ".exe -lcv -lcxcore -lhighgui"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    # ...posix..
    makeFilename = 'Makefile.' + dirName
    makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:" + installDirName + "/lib/; export PKG_CONFIG_PATH=" + installDirName + "/lib/pkgconfig/;g++ " + codeFilename + " -o " + codeFilename[:
                                                                                                                                                                                                    -2] + " `pkg-config --cflags --libs opencv`"
    makeFile = open(makeFilename, 'w')
    makeFile.write(makeFileEntry)
    makeFile.close()

    yield [_("Compiling ...")]
    if os.name == "nt":
        i, o = os.popen4('Makefile' + dirName + '.bat')

        o.readlines()
        o.close()
        i.close()
        yield [_("Running ...")]
        i, o = os.popen4(codeFilename[:-2] + '.exe')

        ## ERROR LOG
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error = Error + element

        SetErrorLog(Error)

        o.readlines()
        o.close()
        i.close()
    else:
        i, o = os.popen4("sh " + makeFilename)

        ## appending compile errors too.. helps finding bugs! =]
        CompilingErrors = ''
        CerrorList = o.readlines()

        if len(CerrorList) <> 0:
            CompilingErrors += "Something was detected while compiling the source code.\n" + \
                               "There is a huge chance you've found a bug, please report to [email protected] \n" + \
                               "sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
                               "We appreciate your help!\n"
        for element in CerrorList:
            CompilingErrors += element

        o.close()
        i.close()
        if g_bLive:
            yield [
                _("Running, press any key (on the video output window) to terminate."
                  ), CompilingErrors
            ]
        else:
            yield [_("Running ..."), CompilingErrors]

        # cpscotti, xunxo bunitinho pra nao travar a interface qndo tive rodando o live =]
        t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./" +
                        codeFilename[:-2])
        t_oPrg.start()
        while t_oPrg.isAlive():
            t_oPrg.join(0.4)
            while gtk.events_pending():
                gtk.main_iteration(False)

        # fim do "xunx"

        ## ERROR LOG
        o = open("RunErrorLog", "r")
        Error = ''
        errorList = o.readlines()
        for element in errorList:
            Error += element

        yield [_("Leaving.."), Error]
        SetErrorLog(CompilingErrors + Error)

        o.close()
        i.close()
Пример #54
0
    def _send(self, widg):
        '''Actually sends the manual requests.

        :param widget: who sent the signal.
        '''
        (tsup, tlow) = self.reqresp.request.get_both_texts()

        busy = gtk.gdk.Window(self.window, gtk.gdk.screen_width(),
                              gtk.gdk.screen_height(), gtk.gdk.WINDOW_CHILD, 0,
                              gtk.gdk.INPUT_ONLY)
        busy.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
        busy.show()

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

        # Get the fix content length value
        fix_content_len = self._fix_content_len_cb.get_active()

        # threading game
        event = threading.Event()
        print repr(tsup)
        print repr(tlow)
        impact = ThreadedURLImpact(self.w3af, tsup, tlow, event,
                                   fix_content_len)

        def impact_done():
            if not event.isSet():
                return True
            busy.destroy()

            if impact.ok:
                self.reqresp.response.set_sensitive(True)
                self.reqresp.response.show_object(impact.httpResp)
                self.reqresp.nb.next_page()

            elif hasattr(impact, 'exception'):
                e_kls = impact.exception.__class__
                if e_kls in (w3afException, w3afMustStopException,
                             w3afMustStopOnUrlError,
                             w3afMustStopByKnownReasonExc, w3afProxyException):
                    msg = "Stopped sending requests because of the following"\
                          " unexpected error:\n\n%s" % str(impact.exception)

                else:
                    raise impact.exception

                self.reqresp.response.clear_panes()
                self.reqresp.response.set_sensitive(False)
                gtk.gdk.threads_enter()
                helpers.FriendlyExceptionDlg(msg)
                gtk.gdk.threads_leave()

            else:
                # This is a very strange case, because impact.ok == False
                # but impact.exception does not exist!
                self.reqresp.response.clear_panes()
                self.reqresp.response.set_sensitive(False)
                gtk.gdk.threads_enter()
                helpers.FriendlyExceptionDlg(
                    'Errors occurred while sending the HTTP request.')
                gtk.gdk.threads_leave()

            return False

        impact.start()
        gobject.timeout_add(200, impact_done)
Пример #55
0
def gtk_iteration():
    while gtk.events_pending():
        gtk.main_iteration(gtk.FALSE)
Пример #56
0
    def cut_file_by_cutlist(self, filename, cutlist=None, program_config_value=None):
        """ Cuts a otr file with x264 and mkvmerge frame accurate. 
            returns: name of cut video, error_message """
        # configuration
        videolist = []                                              # result list for smart rendering simulation
        audio_import_files = [filename]                 # otr files which have audio streams  and needs to be cutted (e.g. OTR avi and ac3) 
        process_list = []                                        # list of started processes
        mkvmerge_list = []                                     # list of started mkvmerge processes
        video_splitframes = ''                               # mkvmerge split string for cutting the video at keyframes 
        audio_timecodes = ''                                # mkvmerge split timecodes for cutting the audio
        ac3_file = None                                         # AC3 source file
        warning_msg = None
        mkvmerge =  self.config.get_program('mkvmerge')
        x264 = self.config.get_program('x264')
        ffmpeg = self.config.get_program('ffmpeg')
        encoder_engine = self.config.get('smartmkvmerge', 'encoder_engine')
        # env
        my_env = os.environ.copy()
        my_env["LANG"] = "C"
        my_env["LC_COLLATE"] = "C"
        my_env["LC_ALL"] = "C"

        # analyse file
        fps, dar, sar, max_frames, ac3_stream, error = self.analyse_mediafile(filename)
        if error:
            return None, "Konnte FPS nicht bestimmen: " + error

        # codec configuration string
        format, ac3_file, bframe_delay = self.get_format(filename)
        if format == Format.HQ:
            if encoder_engine == 'x264':
                codec, codec_core = self.complete_x264_opts(
                    self.config.get('smartmkvmerge', 'x264_hq_string').split(' '), filename)
            elif encoder_engine == 'ffmpeg':
                codec, codec_core = self.__ffmpeg_codec_options(
                    self.config.get('smartmkvmerge', 'ffmpeg_hq_x264_options').split(' '), filename)
        elif format == Format.HD:
            if encoder_engine == 'x264':
                codec, codec_core = self.complete_x264_opts(
                    self.config.get('smartmkvmerge', 'x264_hd_string').split(' '), filename)
            elif encoder_engine == 'ffmpeg':
                codec, codec_core = self.__ffmpeg_codec_options(
                    self.config.get('smartmkvmerge', 'ffmpeg_hd_x264_options').split(' '), filename)
        elif format == Format.MP4:
            if encoder_engine == 'x264':
                codec, codec_core = self.complete_x264_opts(
                    self.config.get('smartmkvmerge', 'x264_mp4_string').split(' '), filename)
            elif encoder_engine == 'ffmpeg':
                codec, codec_core = self.__ffmpeg_codec_options(
                    self.config.get('smartmkvmerge', 'ffmpeg_mp4_x264_options').split(' '), filename)
        elif format == Format.AVI:
            encoder_engine = 'ffmpeg'
            codec = self.config.get('smartmkvmerge', 'ffmpeg_avi_mpeg4_options').split(' ')
            codec_core = 125
        else:
            return None, "Format nicht unterstützt (Nur MP4 H264, HQ H264 und HD H264 sind möglich)."

        logging.debug(codec)
        logging.debug(codec_core)
        
        if codec_core != 125:
            warning_msg ="Unbekannte Kodierung entdeckt. Diese Datei genau prüfen und notfalls mit intern-Virtualdub und Codec ffdshow schneiden."
            return None,  warning_msg
            
        # test workingdir
        if os.access(self.config.get('smartmkvmerge', 'workingdir').rstrip('/'),  os.W_OK):
            self.workingdir = os.path.abspath(self.config.get('smartmkvmerge', 'workingdir')).rstrip('/')
        else:
            return None, "Ungültiges Temp Verzeichnis. Schreiben nicht möglich."
          
        # threads  
        flag_singlethread = self.config.get('smartmkvmerge', 'single_threaded')
        
        if self.config.get('smartmkvmerge', 'single_threaded_automatic'):
            try:
                memory = self.meminfo()
                if self.available_cpu_count() > 1 and memory['MemFree'] > (os.stat(filename).st_size/1024):
                    flag_singlethread = True
                else:
                    flag_singlethread = False
            except Exception  as e:
                flag_singlethread = self.config.get('smartmkvmerge', 'single_threaded')
            
        logging.debug(flag_singlethread)
                            
        # audio part 1 - cut audio 
        if ac3_file:
            audio_import_files.append(ac3_file)

        audio_timecodes = (',+'.join([self.get_timecode(start) + '-' + self.get_timecode(start+duration) for start, duration in cutlist.cuts_seconds]))        
        audio_timecodes = audio_timecodes.lstrip(',+')
        
        command = [mkvmerge, '--ui-language',  'en_US',  '-D',  '--split',  'parts:'+audio_timecodes,  '-o',  self.workingdir + '/audio_copy.mkv'] + audio_import_files
        logging.debug(command)
        try:
            blocking_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True,  env=my_env)
        except OSError as e:
            return None,  e.strerror + ": " + mkvmerge
        mkvmerge_list.append(blocking_process)
        if flag_singlethread:
            self.show_progress(blocking_process)

        # video part 1 - read keyframes
        keyframes, error = self.get_keyframes_from_file(filename)
        if keyframes == None:
            return None,  "Keyframes konnten nicht ausgelesen werden."
        logging.debug(keyframes)

        # video part 2 - simulate smart rendering process
        for frame_start, frames_duration in cutlist.cuts_frames:
            result = self.__simulate_smart_mkvmerge(int(frame_start), int(frames_duration), keyframes)
            if result != None:
                videolist += result
            else:
                return None,  'Cutlist oder zu schneidende Datei passen nicht zusammen oder sind fehlerhaft.'
        logging.debug(videolist)
    
        # video part 3 - encode small parts - smart rendering part (1/2) 
        for encode, start,  duration,  video_part_filename in videolist:
            self.video_files.append('+'+ self.workingdir +'/' + video_part_filename)
            if encoder_engine == 'x264':
                command = [x264] + codec + ['--demuxer','ffms','--index', self.workingdir + '/x264.index','--seek',  str(start),'--frames',  str(duration),  '--output',  self.workingdir + '/' + video_part_filename,  filename ]
            elif encoder_engine == 'ffmpeg':
                command = [ffmpeg,  '-ss', str(self.get_timecode((start+bframe_delay)/fps)),  '-i',  filename, '-vframes',  str(duration), '-vf',  'setsar=' + str(sar), '-threads',  '0',  '-an',  '-sn',  '-dn', '-y',   self.workingdir + '/' + video_part_filename]
                command[5:5]=codec
            else:
                return None,  "Keine unterstützte Render-Engine zum Kodieren eingestellt"
            logging.debug(command)
            if encode:
                try:
                    non_blocking_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
                except OSError as e:
                    return None, e.strerror + ": " + 'Render Engine nicht vorhanden'
                process_list.append(non_blocking_process)
                if flag_singlethread:
                    self.show_progress(non_blocking_process)
            else:
                video_splitframes += ','+str(start)+'-'+str(duration)

        self.video_files[0]=self.video_files[0].lstrip('+')
        video_splitframes = video_splitframes.lstrip(',')
        
        # video part 4 - cut the big parts out the file (keyframe accurate) - smart rendering part (2/2)
        command = [mkvmerge,  '--ui-language',  'en_US','-A',  '--split',  'parts-frames:'+video_splitframes,  '-o',  self.workingdir + '/video_copy.mkv', filename ]
        logging.debug(command)
        try:
            non_blocking_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, env=my_env)
        except OSError as e:
            return None, e.strerror + ": " + mkvmerge
        mkvmerge_list.append(non_blocking_process)
        if flag_singlethread:
            self.show_progress(non_blocking_process)

        # audio part 2 - encode audio to AAC
        if 'MP3 Spur kopieren' in self.config.get('smartmkvmerge', 'first_audio_stream') and 'AC3 Spur kopieren' in self.config.get('smartmkvmerge', 'second_audio_stream'):
            self.audio_files.append(self.workingdir + '/audio_copy.mkv')
        else:
                self.show_progress(blocking_process)
                blocking_process.wait()
                ffmpeginput_file = self.workingdir + '/audio_copy.mkv'
                ffmpegoutput_file = self.workingdir + '/audio_encode.mkv'
                
                audiofilter = []
                # convert first audio stream to aac
                if 'AAC' in self.config.get('smartmkvmerge', 'first_audio_stream') and 'AAC' in self.config.get('smartmkvmerge', 'second_audio_stream'):
                    aacaudiostreams = '-c:a'
                    if self.config.get('smartmkvmerge', 'normalize_audio'):
                        vol0,  error = self.get_norm_volume(ffmpeginput_file, '0')
                        vol1,  error = self.get_norm_volume(ffmpeginput_file, '1')
                        audiofilter = ['-af:0', 'volume=volume=' + vol0,  '-af:1', 'volume=volume=' + vol1]
                elif 'AAC' in self.config.get('smartmkvmerge', 'second_audio_stream') and 'MP3' in self.config.get('smartmkvmerge', 'first_audio_stream'):
                    aacaudiostreams = '-c:a:1'
                    if self.config.get('smartmkvmerge', 'normalize_audio'):
                        vol,  error = self.get_norm_volume(ffmpeginput_file, '1')
                        audiofilter = ['-af:1', 'volume=volume=' + vol]
                elif 'AAC' in self.config.get('smartmkvmerge', 'first_audio_stream'):
                    aacaudiostreams = '-c:a:0'
                    if self.config.get('smartmkvmerge', 'normalize_audio'):
                        vol,  error = self.get_norm_volume(ffmpeginput_file, '0')
                        audiofilter = ['-af:0', 'volume=volume=' + vol]
                else:
                    aacaudiostreams = '-c:a:2'
                    
                if 'nonfree' in ffmpeg:
                    # nonfree ffmpeg version with fdk support available
                    audiocodec = ['-c:a',  'copy',  aacaudiostreams,  'libfdk_aac',  '-flags',  '+qscale',  '-profile:a',  'aac_low',  '-global_quality',  '5' ,'-afterburner',  '1']
                else:
                    # only gpl version of ffmpeg available -> use standard aac codec
                    audiocodec = ['-c:a',  'copy',  aacaudiostreams,  'aac', '-strict', '-2','-profile:a',  'aac_low',  '-ab' ,'192k',  '-cutoff',  '18000']
                    
                if '2-Kanal' in self.config.get('smartmkvmerge', 'first_audio_stream'):
                    audiocodec.extend(['-ac:0',  '2'])

                if ac3_file == None:
                    # no ac3 stream found - all streams are muxed 
                    map = ['-map',  '0']
                else:
                    if 'AC3' in self.config.get('smartmkvmerge', 'first_audio_stream') :
                        map = ['-map',  '0:a:1']
                    else:
                        map = ['-map',  '0:a:0']
                    if not 'AC3 Spur entfernen' in self.config.get('smartmkvmerge', 'second_audio_stream') :
                        map.extend(['-map',  '0:a:1'])
                    
                args = [ffmpeg, "-loglevel", "info", "-y", "-drc_scale", "1.0", "-i", ffmpeginput_file, "-vn", "-vsync", "1", '-async',  '200000',  "-dts_delta_threshold", "100", '-threads',  '0',    ffmpegoutput_file]
                map.extend(audiocodec)
                map.extend(audiofilter)
                args[8:8] = map
                logging.debug(args)
                try:
                    non_blocking_process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
                except OSError as e:
                    return None, e.strerror + ": " + ffmpeg
                process_list.append(non_blocking_process)
                self.audio_files.append(self.workingdir + '/audio_encode.mkv')
                if flag_singlethread:
                    self.show_progress(non_blocking_process)

        # wait until all threads are terminated
        for blocking_process in mkvmerge_list + process_list:
            self.show_progress(blocking_process)

        # check all processes
        for blocking_process in mkvmerge_list:
            returncode = blocking_process.wait()
            if returncode != 0 and returncode != 1:
                return None,  'beim Schneiden der Originaldatei...'
        for blocking_process in process_list:
            returncode = blocking_process.wait()
            if returncode != 0:
                return None,  'beim Kodieren ...'

        # clean up
        if os.path.isfile (self.workingdir + '/video_copy.mkv'):
            os.rename(self.workingdir + '/video_copy.mkv', self.workingdir + '/video_copy-001.mkv')
        if vars().has_key('ffmpeginput_file'):
            if os.path.isfile (ffmpeginput_file):
                os.remove(ffmpeginput_file)        
            
        # mux all together
        if self.config.get('smartmkvmerge', 'remux_to_mp4'):
            cut_video = self.workingdir + '/' + os.path.basename(os.path.splitext(self.generate_filename((filename),1))[0] + ".mkv")
        else:
            cut_video = os.path.splitext(self.generate_filename(filename,1))[0] + ".mkv"
        command = [mkvmerge,  '--engage', 'no_cue_duration', '--engage',  'no_cue_relative_position', '--ui-language',  'en_US',  '-o',  cut_video] + self.video_files + self.audio_files
        logging.debug(command)
        try:
            blocking_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, env=my_env)
        except OSError:
            return None, "MKVMerge konnte nicht aufgerufen werden oder zu alt (6.5.0 benötigt)"
        self.show_progress(blocking_process)
        
        returncode = blocking_process.wait()
        if returncode != 0 and returncode != 1:
            return None,  'beim Schreiben des geschnittenen MKVs...'

        # remove all temporary files
        for n in self.video_files + self.audio_files:
            if os.path.isfile(n.lstrip('+')):
                os.remove(n.lstrip('+'))

        # mux to mp4 
        if self.config.get('smartmkvmerge', 'remux_to_mp4'):
            # split files with eac3to
            with ChangeDir(self.workingdir):
                command = ['wine', path.get_tools_path('intern-eac3to/eac3to.exe'), os.path.basename(cut_video),  '-demux',  '-silence',  '-keepDialnorm']
                logging.debug(command)
                try:
                    blocking_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
                except OSError:
                    return None, 'Eac3to konnte nicht aufgerufen werden'
                
                file_match = re.compile(r".*\"(.* - (\d{1,}) - .*)\".*")
                self.gui.main_window.set_tasks_text('Extrahiere Streams')
                self.gui.main_window.set_tasks_progress(50)
                while events_pending():
                    main_iteration(False)

                while blocking_process.poll() == None:
                    line = blocking_process.stdout.readline().strip()
                    if 'Creating file' in line:
                        m = re.search(file_match,line)
                        if m:
                            self.rawstreams[m.group(2)] = m.group(1).decode("iso-8859-1").encode("utf-8")
                        else:
                            pass
                            
                returncode = blocking_process.wait()
                if returncode != 0:
                    if os.path.isfile(cut_video):
                        os.remove(cut_video)
                    return None,  'Fehler beim Extrahieren der Streams mit Eac3to'
                
                # remove mkv + log file
                if os.path.isfile(cut_video):
                    os.remove(cut_video)
                if os.path.isfile(os.path.splitext(cut_video)[0]+ ' - Log.txt'):
                    os.remove(os.path.splitext(cut_video)[0]+ ' - Log.txt')

                args = [self.config.get_program('mp4box'), '-new',  '-keep-all',  '-isma',  '-inter',  '500']
                
                for index in sorted(self.rawstreams.keys()):
                    args.append('-add')
                    if '.dx50' in self.rawstreams[index]:
                        (root_dx50, dx50) = os.path.splitext(self.rawstreams[index])
                        os.rename(self.rawstreams[index], root_dx50 + '.m4v')
                        self.rawstreams[index] = root_dx50 + '.m4v'
                    args.append(self.rawstreams[index])

                cut_video = os.path.splitext(self.generate_filename(filename,1))[0] + ".mp4"
                args.append(cut_video)
                
                # mux to mp4 (mp4box) 
                logging.debug(args)
                try:
                    blocking_process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
                except OSError:
                    return None, 'MP4Box konnte nicht aufgerufen werden'
                    
                self.gui.main_window.set_tasks_text('Muxe MP4')                    
                self.show_progress(blocking_process)
                returncode = blocking_process.wait()
                if returncode != 0:
                    return None,  'Fehler beim Erstellen der MP4'
                    
        return cut_video, warning_msg
Пример #57
0
        def create(widget, other=None):
            theme_name = msg_input(
                '',
                _('Enter your plymouth theme name. eg. respin Theme (please use only alphanumeric characters)'
                  ), _('Name:'), 'respin Theme')
            if theme_name == False or theme_name == None:
                return
            elif theme_name == '':
                msg_error(_("You must specify theme name!"))
                return

            theme_name_fixed = theme_name.replace(' ', '-').replace(
                '/', '-').replace('..', '-').replace('\\', '-')
            theme_dir = "/lib/plymouth/themes/" + theme_name_fixed

            if os.path.exists(theme_dir):
                overwrite = msg_confirm(
                    _('The theme "%s" already exists! Do you want to overwrite it?'
                      ) % theme_name)
                if overwrite:
                    shutil.rmtree(theme_dir)
                else:
                    return

            dialog = gtk.FileChooserDialog(
                title=_("Select 1920x1080 PNG image..."),
                action=gtk.FILE_CHOOSER_ACTION_OPEN,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                         gtk.RESPONSE_OK))
            dialog.set_default_response(gtk.RESPONSE_OK)
            dialog.set_current_folder(self.working_dir)

            filter = gtk.FileFilter()
            filter.set_name(_("PNG Images"))
            filter.add_mime_type("image/png")
            dialog.add_filter(filter)

            filter = gtk.FileFilter()
            filter.set_name(_("All files"))
            filter.add_pattern("*")
            dialog.add_filter(filter)

            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                filename = dialog.get_filename()
                self.working_dir = os.path.dirname(filename)
                dialog.destroy()
                while gtk.events_pending():
                    gtk.main_iteration_do()
                os.makedirs(theme_dir)
                now = datetime.datetime.now()
                theme_pic = os.path.join(theme_dir, os.path.basename(filename))
                shutil.copy(filename, theme_pic)
                shutil.copy(
                    '/etc/respin/plymouth/respin-theme/progress_bar.png',
                    theme_dir + '/progress_bar.png')
                shutil.copy(
                    '/etc/respin/plymouth/respin-theme/progress_box.png',
                    theme_dir + '/progress_box.png')
                script_name = "/lib/plymouth/themes/" + theme_name_fixed + "/" + theme_name_fixed + ".script"
                script = open(
                    "/etc/respin/plymouth/respin-theme/respin-theme.script"
                ).read().replace("__THEMEPIC__", os.path.basename(theme_pic))
                open(script_name, 'w+').write(script)

                config_name = "/lib/plymouth/themes/" + theme_name_fixed + "/" + theme_name_fixed + ".plymouth"
                config = open(
                    "/etc/respin/plymouth/respin-theme/respin-theme.plymouth"
                ).read()
                config = config.replace("__THEMENAME__", theme_name)
                config = config.replace("__THEMEDIR__", theme_name_fixed)
                open(config_name, 'w+').write(config)

                os.system(
                    'update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth "%(config_name)s" 80'
                    % ({
                        'config_name': config_name
                    }))
                os.system(
                    'update-alternatives --set default.plymouth "%(config_name)s"'
                    % ({
                        'config_name': config_name
                    }))

                ns.window.get_widget("checkbutton1").set_active(False)

                update_initramfs()

                msg_info(
                    _("Your plymouth theme named %(theme_name)s with the picture %(theme_pic)s has been created."
                      ) % ({
                          'theme_name': theme_name,
                          'theme_pic': theme_pic
                      }))
            else:
                dialog.destroy()
                shutil.rmtree(theme_dir)
            list_themes()
Пример #58
0
    return res


def run_from_file(src_file,
                  team_a=('equipoA', xdg_data_path('images/piece-orange.png')),
                  team_b=('equipoB',
                          xdg_data_path('images/piece-violete.png')),
                  path_piece_def=xdg_data_path('images/piece-default.png'),
                  xml_file=xdg_data_path('layouts/alternative-layout.xml')):
    """
    Muestra un juego en pantalla directamente desde un fichero de un juego
    previamente simulado
    """
    name_a, name_b = filenames.extract_names_from_file(src_file)

    team_a = (name_a, team_a[1])
    team_b = (name_b, team_b[1])

    _load_game_from_file(src_file, team_a, team_b, path_piece_def, xml_file)


def show_dialog_result((team_a, team_b), winner):
    """
    Simple function that show a dialog with the result of a game
    """
    _not_dig = notify_result.notifyResult((team_a, team_b), winner)
    _not_dig.dlg_result.run()

    while gtk.events_pending():
        gtk.main_iteration(False)
Пример #59
0
 def hide_terminal(self):
     """Hide the expander with the terminal widget."""
     self._expander.hide()
     while gtk.events_pending():
         gtk.main_iteration()
Пример #60
0
def catchup(block=False):
    while gtk.events_pending():
        gtk.main_iteration(block)