def realized(widget): """Makes sure the widget is realized. view = Gtk.TreeView() with realized(view): do_something(view) """ own_window = False toplevel = widget.get_toplevel() if not isinstance(toplevel, Gtk.Window): window = Gtk.Window(type=Gtk.WindowType.POPUP) window.add(widget) own_window = True else: window = toplevel # realize all widgets without showing them for sub in find_widgets(window, Gtk.Widget): sub.realize() widget.realize() while Gtk.events_pending(): Gtk.main_iteration() assert widget.get_realized() assert window.get_realized() yield widget if own_window: window.remove(widget) window.destroy() while Gtk.events_pending(): Gtk.main_iteration()
def start_shoebot(self): if not which('sbot'): textbuffer = self.output_widget.get_buffer() textbuffer.set_text('Cannot find sbot in path.') while Gtk.events_pending(): Gtk.main_iteration() return False if self.bot and self.bot.process.poll() == None: print('Has a bot already') return False # get the text buffer doc = self.window.get_active_document() if not doc: return title = doc.get_short_name_for_display() cwd = os.path.dirname(doc.get_uri_for_display()) or None start, end = doc.get_bounds() code = doc.get_text(start, end, False) if not code: return False textbuffer = self.output_widget.get_buffer() textbuffer.set_text('') while Gtk.events_pending(): Gtk.main_iteration() self.bot = ShoebotProcess(code, self.use_socketserver, self.show_varwindow, self.use_fullscreen, title, cwd=cwd) GObject.idle_add(self.update_shoebot)
def startlapse(self, *args): wiz2.hide() frames = spin1.get_value_as_int() delay = spin2.get_value_as_int() print frames, " frames will be shot" print "with ", delay, " seconds between each shot" wiz2.hide() wiz3.show_all() proc = subprocess.Popen(['gphoto2','--capture-image-and-download','-F',str(frames),'-I',str(delay)],stdout=subprocess.PIPE) print "starting processing loop WARNING : No error detection supported, if focus fails the app will hang" completed = 0 while completed == 0: if Gtk.events_pending():print "Rendering Progress bar updates" while Gtk.events_pending(): Gtk.main_iteration() line = proc.stdout.readline() if line != '': if line.find("Capturing frame #") != -1: print "[debug] progress found" newstr = line.replace("Capturing frame #","") newstr = newstr.split('...', 1)[0] newstr = newstr.split('/', 1) newstr = (int(newstr[0])/int(newstr[1])) progressbar1.set_fraction(newstr) print "[PROGRESS]", line else: print "complete" completed = 1 wiz4.show_all() wiz3.hide()
def upload(self, group): tab = self.window.get_active_tab() document = tab.get_document() filename = document.get_uri_for_display() panel = self.window.get_bottom_panel() panel.activate_item(self.textarea) visible = panel.get_property("visible") panel.set_property("visible", True) settings = Gio.Settings.new(SETTINGS_SCHEMA) server = settings.get_string('server') # get root base = 'org.gnome.gedit.plugins.filebrowser' settings = Gio.Settings.new(base) root = settings.get_string('virtual-root') if root is not None: root = re.sub(r'^file://','', root) dest = re.sub(root+'/', '', filename) p = subprocess.Popen("scp " + filename +" "+server+'/'+dest, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) txt = "'%s' uploading " % dest self.addtext(self.textarea, txt) while p.poll() is None: while Gtk.events_pending(): Gtk.main_iteration() self.addtext(self.textarea,".") time.sleep(0.1) if p.returncode == 0: self.addtext(self.textarea,"success\n") else: self.addtext(self.textarea,"Error: "+p.stderr.read()+"\n") while Gtk.events_pending(): Gtk.main_iteration() time.sleep(1) panel.set_property("visible", visible)
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()
def activewindows(self, search, actor): """ sort through open windows to activate """ found = False foundwin = [] tmpcount = 0 overlaycount = None self.getwindowlist() for items in self.open: if items[1] == actor: overlaycount = tmpcount window = self.openwindows[overlaycount] tmpname = window.get_name() tmppid = str(window.get_pid()) logops.write(LOGFILE, ('PIRUM: activating window\n NAME: ' + tmpname + '\n PID: ' + tmppid + '\n')) window.activate(int(time.time())) return True else: tmpcount = tmpcount + 1 # identify windows by title for windows in self.windowlist: tmpxid = windows.get_xid() tmppid = windows.get_pid() currentwindow = Wnck.Window.get(tmpxid) name = currentwindow.get_name().lower() pid = currentwindow.get_pid() # Activate windows with the same name from the overlay if search == name and tmppid == pid: foundwin.append(currentwindow) while Gtk.events_pending(): Gtk.main_iteration() #windows.activate(int(time.time())) found = True # search for split text in windows if not found: # if you can't find the exact window activate all matches for windows in self.windowlist: tmpxid = windows.get_xid() tmppid = windows.get_pid() currentwindow = Wnck.Window.get(tmpxid) name = currentwindow.get_name().lower() pid = currentwindow.get_pid() # Activate windows with the same name from the overlay if search == name.split()[0]: foundwin.append(currentwindow) while Gtk.events_pending(): Gtk.main_iteration() found = True if foundwin: logops.write(LOGFILE, ('PIRUM: activating window group')) for windows in foundwin: tmpname = windows.get_name() tmppid = str(windows.get_pid()) logops.write(LOGFILE, (' NAME: ' + tmpname + '\n PID: ' + tmppid + '\n')) windows.activate(int(time.time())) return True # Error, Window not activated. return False
def update_ssn_file(self): print("*** Connecting to " + self.ssn_url) if self.s_bar: self.s_bar.pop(self.s_bar_context) self.s_bar.push(self.s_bar_context , "Connecting to {:s}".format(self.ssn_url)) while Gtk.events_pending(): Gtk.main_iteration() try: f_name, header = urllib.request.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: self.s_bar.pop(self.s_bar_context) self.s_bar.push(self.s_bar_context, _("Done")) while Gtk.events_pending(): Gtk.main_iteration() self.read_ssn_file() except: print("*** Failed to retrieve data ***") if self.s_bar: self.s_bar.pop(self.s_bar_context) self.s_bar.push(self.s_bar_context, _("Error: Unable to retrieve data")) while Gtk.events_pending(): Gtk.main_iteration()
def build_packages(self, component=None): self.placeholder.set_markup("<span font='30.5'>Loading..</span>") for child in self.listbox_packages.get_children(): child.destroy() pkgs = component.packages appends = list() if len(pkgs) == 0: self.placeholder.set_markup("<big>No packages matched your query</big>") self.components_view.set_sensitive(True) return for pkg in component.packages: meta,pkg_ = pisi.api.info(pkg) package = meta.package old_package = self.installdb.get_package(pkg) if self.installdb.has_package(pkg) else None appends.append((package, old_package)) while (Gtk.events_pending()): Gtk.main_iteration() appends.sort(key=lambda x: x[0].name) for new,old in appends: label = PackageLabel(new,old, True) label.sig_id = label.connect('operation-selected', self.op_select) status = self.basket.operation_for_package(new) label.mark_status(status) self.listbox_packages.add(label) self.listbox_packages.show_all() while (Gtk.events_pending()): Gtk.main_iteration() self.components_view.set_sensitive(True)
def timer(self): try: if self.counting: if self.counter == 0: self.display = True for each in range(0,10): if self.counting: self.window.set_opacity(float("0."+str(each))) while gtk.events_pending(): gtk.main_iteration_do(True) self.window.show_all() self.window.move(100,150) self.icon.set_visible(not self.image_hide) self.speak(self.speech) if self.counter == 5: if self.window.get_opacity() != 0.0: for each in range(9,-1,-1): self.window.set_opacity(float("0."+str(each))) while gtk.events_pending(): gtk.main_iteration_do(True) time.sleep(0.02) self.window.hide() self.display = False self.counting = False self.counter += 1 elif len(self.queue) > 0 and self.display == False: data = self.queue[0] try: self.message.set_text("")
def show_index(self, f_letter, mdict): self.tree_dict.collapse_all() self.store_dict.clear() self.view_dict_bfr.set_text('') while (Gtk.events_pending()): Gtk.main_iteration() if mdict == 1 or mdict == 0: all_index = self.mydict.all_index('lisan', f_letter) if len(all_index) > 0: a1 = self.store_dict.append(None, ['لسان العرب', 'lisan']) for a in all_index: while (Gtk.events_pending()): Gtk.main_iteration() self.store_dict.append(a1, [a[0], 'lisan']) if mdict == 2 or mdict == 0: all_index = self.mydict.all_index('taje', f_letter) if len(all_index) > 0: a2 = self.store_dict.append(None, ['تاج العروس', 'taje']) for a in all_index: while (Gtk.events_pending()): Gtk.main_iteration() self.store_dict.append(a2, [a[0], 'taje']) if mdict == 3 or mdict == 0: all_index = self.mydict.all_index('assas', f_letter) if len(all_index) > 0: a3 = self.store_dict.append(None, ['أساس البلاغة', 'assas']) for a in all_index: self.store_dict.append(a3, [a[0], 'assas']) if mdict == 4 or mdict == 0: all_index = self.mydict.all_index('mekhtar', f_letter) if len(all_index) > 0: a4 = self.store_dict.append(None, ['مختار الصحاح', 'mekhtar']) for a in all_index: self.store_dict.append(a4, [a[0], 'mekhtar'])
def post(self, widget): if self.check_send_button(None) == False: return self.box.set_sensitive(False) while Gtk.events_pending(): Gtk.main_iteration() active = self.combo.get_active() request = Requests(None) account = self.settings["accounts"][active] if self.playing_entry == None: title = artist = album = "" else: title = self.playing_entry.get_string(RB.RhythmDBPropType.TITLE) artist = self.playing_entry.get_string(RB.RhythmDBPropType.ARTIST) album = self.playing_entry.get_string(RB.RhythmDBPropType.ALBUM) result = request.post(account, self.entry, title, album, artist) self.box.set_sensitive(True) while Gtk.events_pending(): Gtk.main_iteration() if result == True: self.entry.set_text("Done!") self.on_cancel_clicked(None)
def have_updates(): while Gtk.events_pending(): Gtk.main_iteration() UpdaterWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) while Gtk.events_pending(): Gtk.main_iteration() update_listore.clear() update_top_label.set_justify(Gtk.Justification.CENTER) updates = transaction.available_updates[1] if not updates: update_bottom_label.set_markup('') update_top_label.set_markup('<big><b>{}</b></big>'.format(_('Your system is up-to-date'))) UpdaterApplyButton.set_sensitive(False) else: UpdaterApplyButton.set_sensitive(True) dsize = 0 for name, version, db, tarpath, size in updates: dsize += size if size: size_str = common.format_size(size) else: size_str = '' update_listore.append([name+' '+version, size_str]) if dsize == 0: update_bottom_label.set_markup('') else: update_bottom_label.set_markup('<b>{} {}</b>'.format(_('Total download size:'), common.format_size(dsize))) if len(updates) == 1: update_top_label.set_markup('<big><b>{}</b></big>'.format(_('1 available update'))) else: update_top_label.set_markup('<big><b>{}</b></big>'.format(_('{number} available updates').format(number = len(updates)))) UpdaterWindow.get_window().set_cursor(None)
def test_main(self): cancel = Cancellable() data = [] def func(): data.append(threading.current_thread().name) def callback(result): data.append(threading.current_thread().name) call_async(func, cancel, callback) Gtk.main_iteration() while Gtk.events_pending(): Gtk.main_iteration() call_async_background(func, cancel, callback) Gtk.main_iteration() while Gtk.events_pending(): Gtk.main_iteration() main_name = threading.current_thread().name self.assertEqual(len(data), 4) self.assertNotEqual(data[0], main_name) self.assertEqual(data[1], main_name) self.assertNotEqual(data[2], main_name) self.assertEqual(data[3], main_name)
def run_gameGTK(widget) : print("RUNNING GAME!!!!") global win global rompath global emupath global rom global flow widgets = flow.get_selected_children() rom = widgets[0].get_children()[0].get_children()[0].get_text() print(rom) if rom == "" or rompath == "" or emupath == "" : print("Error, not a valid choice") else : win.hide() win.queue_draw() while(Gtk.events_pending()) : Gtk.main_iteration() st = emupath + ' "' + rompath + rom + '"' #print(st) os.system(st) win.show() while(Gtk.events_pending()) : Gtk.main_iteration()
def read(self, msg_len = 0, timeout = 500, end_char = '\r'): if (not self.is_open()): return((False, None)) self.buffer = '' # Command adapter to read until EOS is reached self._command("++read\n") start = datetime.now() if (msg_len <= 0): while(True): # read... until newline w = self.ser.inWaiting() if (w > 0): for i in range(w): c = self.ser.read(1) if (c == end_char): # done! self.buffer += c temp_buf = self.buffer self.buffer = '' return((True, temp_buf)) else: self.buffer += c delta = datetime.now() - start if ((delta.total_seconds()*1000.0) >= timeout): return((False, None)) # Keep GUI active while Gtk.events_pending(): Gtk.main_iteration_do(False) else: r = 0 while(True): w = self.ser.inWaiting() if (w > 0): if (w >= msg_len): self.buffer = self.ser.read(msg_len) return((True, self.buffer)) else: self.buffer += self.ser.read(w) r += w if (r >= msg_len): # Received complete message temp_buf = self.buffer[0:msg_len] self.buffer = '' return((True, temp_buf)) delta = datetime.now() - start if ((delta.total_seconds()*1000.0) >= timeout): return((False, None)) # Keep GUI active while Gtk.events_pending(): Gtk.main_iteration_do(False)
def import_playlists(self, action, parameter, shell): settings = Gio.Settings.new("org.gnome.rhythmbox.plugins.playlists_ie") folder = settings.get_string("ie-folder") #get the import-export folder if (os.path.isdir(folder)!=True): self.warn_for_no_present_dir() return self.create_progress_bar_win() pl_man = shell.props.playlist_manager pl_list = pl_man.get_playlists() pl_count = len(pl_list) processed_pl_count=0 for playlist in pl_list: while Gtk.events_pending(): Gtk.main_iteration() if( isinstance(playlist, RB.AutoPlaylistSource) ): #keep only auto playlists if( playlist.props.name == "Unnamed playlist" ): #this name is used for the newly imported playlists playlist.props.name = "Unnamed playlist_" else : #logging.error("deleting " + playlist.props.name) pl_man.delete_playlist(playlist.props.name) processed_pl_count=processed_pl_count+1 self.update_fraction(1-processed_pl_count/pl_count) pl_file_count=0 processed_pl_files=0 for pl_file in os.listdir(folder): if pl_file.endswith(".m3u"): pl_file_count=pl_file_count+1 for pl_file in os.listdir(folder): while Gtk.events_pending(): Gtk.main_iteration() if pl_file.endswith(".m3u"): pl_name = pl_file[:-4] pl_uri = os.path.join(folder,pl_name) pl_uri = "file://"+ pl_uri + ".m3u" pl_man.parse_file(pl_uri) #logging.error("importing "+pl_uri) for playlist in pl_man.get_playlists(): if(playlist.props.name == "Unnamed playlist"): #that's the one we imported last , so set it's name playlist.props.name = pl_name processed_pl_files=processed_pl_files+1 self.update_fraction(processed_pl_files/pl_file_count) self.progress_window.destroy()
def screenshot(windowtitle, lang, fn): while Gtk.events_pending(): Gtk.main_iteration() time.sleep(2) while Gtk.events_pending(): Gtk.main_iteration() fn = "help/%s/figures/%s" % (lang, fn) cmd = u'import -window %s %s' % (windowtitle, fn) print cmd os.system(cmd.encode("utf-8")) compress(fn)
def run(self): global frames_cache frame_levels = [None] * self.clip_media_length frames_cache[self.clip.path] = frame_levels Gdk.threads_enter() self.dialog.progress_bar.set_fraction(0.0) self.dialog.progress_bar.set_text(str(0) + "%") while(Gtk.events_pending()): Gtk.main_iteration() Gdk.threads_leave() time.sleep(0.2) for frame in range(0, len(frame_levels)): if self.abort: break self.temp_clip.seek(frame) mlt.frame_get_waveform(self.temp_clip.get_frame(), 10, 50) val = self.levels.get(RIGHT_CHANNEL) if val == None: val = 0.0 frame_levels[frame] = float(val) self.last_rendered_frame = frame if frame % 500 == 0: render_fraction = float(self.last_rendered_frame) / float(self.clip_media_length) Gdk.threads_enter() self.dialog.progress_bar.set_fraction(render_fraction) pros = int(render_fraction * 100) self.dialog.progress_bar.set_text(str(pros) + "%") while(Gtk.events_pending()): Gtk.main_iteration() Gdk.threads_leave() time.sleep(0.1) if not self.abort: self.clip.waveform_data = frame_levels write_file = file(self.file_cache_path, "wb") pickle.dump(frame_levels, write_file) Gdk.threads_enter() self.dialog.progress_bar.set_fraction(1.0) self.dialog.progress_bar.set_text(_("Saving to Hard Drive")) Gdk.threads_leave() else: frames_cache.pop(self.clip.path, None) updater.repaint_tline() # Set thread ref to None to flag that no waveforms are being created global waveform_thread waveform_thread = None _waveform_render_stop(self.dialog, None)
def on_search_treeview_selection_changed(widget): global current_filter while Gtk.events_pending(): Gtk.main_iteration() liste, line = search_selection.get_selected() if line: ManagerWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) while Gtk.events_pending(): Gtk.main_iteration() current_filter = (search_pkgs, (search_list[line][0], search_aur_button.get_active())) refresh_packages_list(search_pkgs((search_list[line][0], search_aur_button.get_active())))
def on_repos_treeview_selection_changed(widget): global current_filter while Gtk.events_pending(): Gtk.main_iteration() liste, line = repos_selection.get_selected() if line: ManagerWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) while Gtk.events_pending(): Gtk.main_iteration() current_filter = (get_repo_list, repos_list[line][0]) refresh_packages_list(get_repo_list(repos_list[line][0]))
def __real_update_account(self, acc): if acc in self.accounts_checking: logger.warn("The account %s is being checked" % (acc.get_name())) return logger.debug("Starting checker") if not acc.get_active(): logger.debug("The account %s is not active, it will not be updated" % (acc.get_name())) return self.accounts_checking.append(acc) max_notifications = int(float(self.config.get_prefs()["max_notifications"])) try: logger.debug('Updating account: ' + acc.get_name()) #Process events to show the main icon while Gtk.events_pending(): Gtk.main_iteration(False) self.am.update_account(acc) acc.error_notified = False if hasattr(acc, "indicator"): self.im.get_indicator().update_account(acc) #Process events to show the indicator menu while Gtk.events_pending(): Gtk.main_iteration(False) if acc.get_provider().has_notifications() and \ acc.get_show_notifications(): nots = acc.get_new_unread_notifications() message = None if len(nots) > max_notifications: notification.notify(acc.get_name(), _("New messages: ") + str(len(nots)), acc.get_icon()) if len(nots) > 0 and len(nots) <= max_notifications: for n in nots: if n.icon: icon = n.icon else: icon = acc.get_icon() notification.notify(acc.get_name() + ": " + n.sender, n.message, icon) self.emit("account-checked", acc) except notification.NotificationError, ne: logger.exception("Error trying to notify with libnotify: %s", e)
def write(self, text): if self.hasbuilder and self.filecount > 0: if text[:23] == "Processing changed file": self.currentfile += 1 p = self.currentfile / self.filecount self.builder.get_object("progressbar1").set_fraction(p) while Gtk.events_pending(): Gtk.main_iteration() self.text += text if self.haswidget and not self.quiet: self.output_buffer.insert(self.output_buffer.get_end_iter(), text) while Gtk.events_pending(): Gtk.main_iteration()
def test_populate(self): # Assert that active state works config.set("memory", "bar", "on") c = ConfigCheckMenuItem("dummy", "memory", "bar", populate=True) while Gtk.events_pending(): Gtk.main_iteration() self.failUnless(c.get_active()) # ...and inactive config.set("memory", "bar", "off") c = ConfigCheckMenuItem("dummy", "memory", "bar", populate=True) while Gtk.events_pending(): Gtk.main_iteration() self.failIf(c.get_active())
def get_updates(): while Gtk.events_pending(): Gtk.main_iteration() action_handler(_("Checking for updates") + "...") icon_handler("pamac-search") target_handler("") percent_handler(0) ProgressCancelButton.set_visible(False) ProgressCloseButton.set_visible(False) progress_expander.set_visible(False) ProgressWindow.show() while Gtk.events_pending(): Gtk.main_iteration() CheckUpdates()
def refresh(force_update=False): while Gtk.events_pending(): Gtk.main_iteration() action_handler(_("Refreshing") + "...") icon_handler("pamac-refresh") target_handler("") percent_handler(0) ProgressCancelButton.set_visible(True) ProgressCloseButton.set_visible(False) progress_expander.set_visible(True) ProgressWindow.show() while Gtk.events_pending(): Gtk.main_iteration() Refresh(force_update)
def on_package_open_button_clicked(*args): packages_paths = PackagesChooserDialog.get_filenames() if packages_paths: PackagesChooserDialog.hide() while Gtk.events_pending(): Gtk.main_iteration() for path in packages_paths: transaction.to_load.add(path) ManagerWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) while Gtk.events_pending(): Gtk.main_iteration() error = transaction.run() ManagerWindow.get_window().set_cursor(None) if error: handle_error(error)
def flush_events(self): # docstring inherited Gdk.threads_enter() while Gtk.events_pending(): Gtk.main_iteration() Gdk.flush() Gdk.threads_leave()
def recordLine(self): '''Listen to temperature data from the serial port, save to a log file (csv) and return as a list: return log = [datetime_stamp, temperature] ''' try: n = 0 while n < 5: # Record temp from the defined log number row = self.ser.readline() logger = row.split(' ')[0] temp = row.split(' ')[1] if int(logger) == self.log_no: print('row ', str(self.log_no), row) date_num = date2num(datetime.now()) self.log = [str(datetime.now()), float(temp)] #self.temp_read = self.log self.liststore.append(self.log) self.plotpoints() # Send email alert if temp > 5: sendEmailAlert(self.log_no, temp) row = None temp = None n += 1 while Gtk.events_pending(): Gtk.main_iteration() # runs the GTK main loop as needed except: print('Could not read serial device') self.temp_read = None return True
def install(self): if self._win is not None: self._win.blur() self._win.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) if not self._download_app(): return self._end(False) if self._check_if_installed: if not self._installed_check(): return self._end(False) if not self._get_sudo_pw(): return self._end(False) # Make sure the dialogs are gone before installing while Gtk.events_pending(): Gtk.main_iteration() rv = self._install() if rv and self._report_install: self._report() return self._end(rv)
def on_ChooseButton_clicked(*args): ChooseDialog.hide() while Gtk.events_pending(): Gtk.main_iteration() for row in choose_list: if row[0] is True: to_add.add(row[1].split(":")[0]) # split done in case of optdep choice
def run_loop(): while Gtk.events_pending(): Gtk.main_iteration()
def reset(self, title): from gi.repository import Gtk self.pm.set_header(title) self.title = title while Gtk.events_pending(): Gtk.main_iteration()
def update(self, count): from gi.repository import Gtk self.pm.step() while Gtk.events_pending(): Gtk.main_iteration()
class scorescreen: def run(self, gameDisplay, score, scoreflag): 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)) back = pygame.image.load("images/over.png") home = pygame.transform.scale(pygame.image.load("images/home.png"), (160, 60)) play = pygame.transform.scale(pygame.image.load("images/play.png"), (160, 60)) #herotr=hero #herotr=pygame.transform.scale(hero,(30,26)) #hero1=pygame.image.load("images/hero1.png") font_path = "fonts/sans.ttf" font_size = 55 font1 = pygame.font.Font(font_path, font_size) font2 = pygame.font.Font("fonts/sans.ttf", 30) font3 = pygame.font.Font("fonts/sans.ttf", 30) font4 = pygame.font.Font("fonts/sans.ttf", 20) down = 1 bounce = 0 i = 0 red = (255, 0, 0) keypressflag = 0 maxscore = 0 with open('score.pkl', 'rb') as input: #REading maxscore = pickle.load(input) buttonsound = pygame.mixer.Sound("sound/sound-button.ogg") # 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.KEYDOWN: return 1 if event.type == pygame.QUIT: crashed = True #print "help" mos_x, mos_y = pygame.mouse.get_pos() #print event gameDisplay.fill(white) gameDisplay.blit(pygame.transform.scale(back, (490, 768)), (350, 0)) scores = font2.render(str(score), 1, black) gameDisplay.blit(scores, (560, 250)) if (scoreflag == 1): maxscores = font2.render(str(maxscore) + " NEW!", 1, red) else: maxscores = font2.render(str(maxscore), 1, black) gameDisplay.blit(maxscores, (560, 325)) gameDisplay.blit(home, (430, 450)) gameDisplay.blit(play, (620, 450)) # GAME START # Home button if home.get_rect(center=(430 + (home.get_width() / 2), 450 + (home.get_height() / 2))).collidepoint( mos_x, mos_y): gameDisplay.blit( pygame.transform.scale( home, (home.get_width() + 4, home.get_height() + 4)), (430 - 2, 450 - 2)) if (pygame.mouse.get_pressed())[0] == 1 and press == 0: buttonsound.play(0) return 0 # Play Button if play.get_rect(center=(620 + (play.get_width() / 2), 450 + (play.get_height() / 2))).collidepoint( mos_x, mos_y): gameDisplay.blit( pygame.transform.scale( play, (play.get_width() + 4, play.get_height() + 4)), (620 - 2, 450 - 2)) if (pygame.mouse.get_pressed())[0] == 1 and press == 0: buttonsound.play(0) return 1 for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == 273: buttonsound.play(0) return 1 #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) 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()
def on_buttonSelectFiles_clicked(self, widget): logging.debug('>>') selectedFiles = fileChooserDialog( title=_("Choose a file (or files) to import activities from"), multiple=True).getFiles() while Gtk.events_pending(): # This allows the GUI to update Gtk.main_iteration() # before completion of this entire action if selectedFiles is None or len(selectedFiles) == 0: #Nothing selected logging.debug("No files selected") logging.debug('<<') return logging.debug("%s files selected" % len(selectedFiles)) for filename in selectedFiles: #Multiple files class_index = len(self.processClasses) #Validate file self.processClasses.append(self.validateFile(filename)) if self.processClasses[class_index] is not None: filetype = self.processClasses[class_index].getFileType() self.updateStatusbar(self.statusbarImportFile, _("Found file of type: %s") % filetype) logging.debug("Found file of type: %s" % filetype) activitiesSummary = self.processClasses[ class_index].getActivitiesSummary() activity_count = len(activitiesSummary) logging.debug("%s activities in file: %s", activity_count, filename) #Add file to files treeview iter = self.files_store.append() self.files_store.set( iter, 0, str(class_index), 1, True, 2, filename, 3, self.processClasses[class_index].getFileType(), 4, str(activity_count)) #File valid, so enable remove button self.buttonRemoveSelectedFiles.set_sensitive(1) #Get activities in file for activity in activitiesSummary: #Add activity details to TreeView store to display if not activity[1]: #Activity selected, so enable import button self.buttonFileImport.set_sensitive(1) note = "" else: note = _("Found in database") activity_iter = self.activities_store.append() # Status (#1) can be changed by user (via checkbox), we need another field to know if activity is in DB self.activities_store.set( activity_iter, 0, str(activity[0]), 1, not activity[1], 2, activity[2], 3, activity[3], 4, activity[4], 5, activity[5], 6, note, 7, str(class_index), 8, activity[1], ) else: #Selected file not understood by any of the process files #Display error logging.debug( "File %s is of unknown or unsupported file type" % filename) msg = _("File %s is of unknown or unsupported file type" ) % filename md = Gtk.MessageDialog(self.win_importdata, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, msg) md.set_title("Error") md.run() md.destroy() self.updateStatusbar(self.statusbarImportFile, "") logging.debug('<<')
def handle_events(): while Gtk.events_pending(): Gtk.main_iteration_do(blocking=False)
def flush_events(self): Gdk.threads_enter() while Gtk.events_pending(): Gtk.main_iteration() Gdk.flush() Gdk.threads_leave()
def do(self): while Gtk.events_pending(): Gtk.main_iteration()
def __init__(self): # Check if script is running self.scriptName = basename(__file__) self.scriptDir = abspath(dirname(__file__)) self.filesDir = join(self.scriptDir, "files") self.umglobal = UmGlobal() self.user = self.umglobal.getLoginName() # Initiate logging self.logFile = join('/var/log', self.umglobal.settings['log']) print(("UM log = %s" % self.logFile)) self.log = Logger(self.logFile, maxSizeKB=5120) # Remove scripts self.deleteScripts(self.umglobal.localUpdVersion) # Initialize self.ec = ExecCmd(loggerObject=self.log) self.apt = UmApt(self.umglobal) self.kernelVersion = self.umglobal.getKernelVersion() self.upgradables = [] self.upgradableUM = [] self.window = None # Handle arguments parser = argparse.ArgumentParser(description='Trail Update Manager') parser.add_argument('-q', '--quick', action="store_true", help='Quick upgrade') parser.add_argument('-r', '--reload', action="store_true", help='') args, extra = parser.parse_known_args() self.quickUpdate = False #print((">> opts = {} / args = {}".format(opts, args))) #print((">> opt = {} / arg = {}".format(opt, arg))) if args.quick: self.quickUpdate = True if args.reload: pids = self.umglobal.getScriptPids("updatemanager.py") if len(pids) > 1: print(("updatemanager.py already running - kill pid {}".format( pids[0]))) os.system("kill {}".format(pids[0])) # Set some global translations self.aptErrorText = _("Apt error") self.upgradablePackagesText = _( "The following packages will be upgraded:") self.newPackagesText = _( "The following NEW packages will be installed:") self.removedPackagesText = _("The following packages will be REMOVED:") self.heldbackPackagesText = _( "The following packages have been kept back:") self.downgradePackagesText = _( "The following packages are going to be downgraded:") # Cleanup first for fle in glob(join(self.filesDir, '.um*')): remove(fle) # Load window and widgets self.builder = Gtk.Builder() self.builder.add_from_file( join(self.scriptDir, '../../../share/trail/updatemanager/updatemanager.glade')) go = self.builder.get_object # Quick update if self.quickUpdate: #print((">> Run minimal upgrade")) # Refresh data self.umglobal.collectData() self.apt.createPackagesInfoList() self.apt.createPackageLists() self.fillTreeView() # Run upgrade nid = self.run_upgrade() if nid != "": self.on_command_done(None, 0, nid) #print((">> Minimal upgrade done")) sys.exit(2) # Make sure the files directory is set correctly self.checkFilesDir() # Main window objects self.window = go("windowMain") self.window.set_icon_from_file(self.umglobal.settings["icon-base"]) self.tvPck = go("tvPck") self.swTerminal = go("swTerminal") self.statusbar = go("statusbar") self.btnInstall = go("btnInstall") self.btnRefresh = go("btnRefresh") self.btnPackages = go("btnPackages") self.btnOutput = go("btnOutput") self.btnInfo = go("btnInfo") self.btnPreferences = go("btnPreferences") self.nbMain = go("nbMain") self.swInfo = go("swInfo") self.btnMaintenance = go("btnMaintenance") self.lblMaintenance = go("lblMaintenance") self.tvMaintenance = go("tvMaintenance") self.btnMaintenanceExecute = go("btnMaintenanceExecute") self.chkMaintenanceSelectAll = go("chkMaintenanceSelectAll") self.radUnneeded = go("radUnneeded") self.radCleanCache = go("radCleanCache") self.radDowngradable = go("radDowngradable") self.radNotavailable = go("radNotavailable") self.radOldKernel = go("radOldKernel") self.lblMaintenanceHelp = go("lblMaintenanceHelp") # Translations self.window.set_title(_("Trail Update Manager")) self.btnInstall.set_label(_("Install")) self.btnRefresh.set_label(_("Refresh")) self.btnOutput.set_label(_("Output")) self.btnInfo.set_label(_("Information")) self.btnPreferences.set_label(_("Preferences")) self.btnPackages.set_label(_("Packages")) self.uptodateText = _("Your system is up to date") self.lblMaintenance.set_label(_("Maintenance")) self.btnMaintenanceExecute.set_label(_("Execute")) self.chkMaintenanceSelectAll.set_label(_("Select all")) self.radCleanCache.set_label(_("Clean up the apt cache")) self.radUnneeded.set_label(_("Remove unneeded packages")) self.radNotavailable.set_label( _("Remove packages not available\nin the repositories")) self.radOldKernel.set_label(_("Remove old kernels")) self.radDowngradable.set_label( _("Downgrade packages with\nonly lower versions available")) self.lblMaintenanceHelp.set_label( _("Make sure you create\n" "a system image before you\n" "continue (e.g. Clonezilla).")) # VTE Terminal self.terminal = VirtualTerminal(userInputAllowed=self.umglobal. settings["allow-terminal-user-input"]) self.swTerminal.add(self.terminal) self.terminal.set_vexpand(True) self.terminal.set_hexpand(True) self.terminal.connect('command-done', self.on_command_done) self.terminal.connect('line-added', self.on_line_added) palletList = [ '#4A4A4A', '#BD1919', '#118011', '#CE6800', '#1919BC', '#8D138D', '#139494', '#A7A7A7' ] self.terminal.setTerminalColors("#000000", "#FFFFFF", palletList) self.swTerminal.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse("#FFFFFF")) # Disable all buttons self.btnInfo.set_sensitive(False) self.btnPreferences.set_sensitive(False) self.btnOutput.set_sensitive(False) self.btnRefresh.set_sensitive(False) self.btnInstall.set_sensitive(False) self.btnPackages.set_sensitive(False) self.btnMaintenance.set_sensitive(False) # Hide tabs if needed for tab in self.umglobal.settings["hide-tabs"]: if tab == "packages": self.nbMain.get_nth_page(0).set_visible(False) self.btnPackages.set_visible(False) elif tab == "output": self.nbMain.get_nth_page(1).set_visible(False) self.btnOutput.set_visible(False) elif tab == "info": self.nbMain.get_nth_page(2).set_visible(False) self.btnInfo.set_visible(False) elif tab == "maintenance": self.nbMain.get_nth_page(3).set_visible(False) self.btnMaintenance.set_visible(False) # Connect the signals and show the window self.builder.connect_signals(self) self.window.show() # Force the window to show while Gtk.events_pending(): Gtk.main_iteration() # Just show something that we're busy msg = _("Gathering information...") self.terminal.executeCommand('echo "%s"' % msg, 'init') self.showOutput() # Treeview handlers self.tvHandler = TreeViewHandler(self.tvPck) self.tvMaintenanceHandler = TreeViewHandler(self.tvMaintenance) # Version information ver = _("Version") pckVer = self.apt.getPackageVersion('updatemanager') versionInfo = "%(ver)s: %(pckVer)s" % {"ver": ver, "pckVer": pckVer} if self.umglobal.localUpdVersion != "2000.01.01": versionInfo = "%(ver)s: %(pckVer)s" % { "ver": ver, "pckVer": pckVer } self.pushMessage(versionInfo) # Log basic information self.log.write("==============================================", "UM.init", "debug") self.log.write("UM version = %s" % versionInfo, "UM.init", "debug") self.log.write("==============================================", "UM.init", "debug") mirrorsList = join(self.filesDir, basename(self.umglobal.settings["mirrors-list"])) if exists(mirrorsList): self.log.write("Mirrors list", "UM.init", "debug") with open(mirrorsList, 'r') as f: for line in f.readlines(): self.log.write(line, "UM.init", "debug") self.log.write("==============================================", "UM.init", "debug") # Load the initial information page self.loadInfo() # Refresh apt cache self.refresh() # Initialize maintenance screen self.fillTreeViewMaintenance()
def run(self): global XO1, XO2, DISPLAYSURF, WHITE, BLACK, DarkColor, LightColor, DarkColor, RED, GREY, fontObj, megaFont, ResX, ResY, FPS, fpsClock XO1, XO2 = profile.get_color().to_string().split(',') score = 0 hscore = 0 infoObject = pygame.display.Info() FPS = 30 fpsClock = pygame.time.Clock() ResX = infoObject.current_w ResY = infoObject.current_h DISPLAYSURF = pygame.display.set_mode((ResX, ResY), 0, 32) pygame.display.set_caption(('Number Rush')) WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREY = (200, 200, 200) DarkColor = hex_to_rgb(XO1) RED = (255, 0, 0) LightColor = hex_to_rgb(XO2) DarkColor = hex_to_rgb(XO1) LEFT = 'left' RIGHT = 'right' foodx = 0 foody = 100 food = 4 speed = ResY / 320 speedinc = 1 gap = (ResX) / (food + 1) direction = 'down' maxi = 10 boxx = gap boxy = ResY - 40 selection, n, x, y = randomOperation(maxi) if (n < 3): a = n + (1) b = n + (2) c = n + (3) else: a = n + (1) * (-1)**randint(1, 2) b = n + (2) * (-1)**randint(1, 2) c = n + (3) * (-1)**randint(1, 2) randomOptions = [a, b, c] fontObj = pygame.font.Font('freesansbold.ttf', 32) megaFont = pygame.font.Font('freesansbold.ttf', 70) counter = 0 rand = randint(1, 4) startAnimation() newGameAnimation() while True: DISPLAYSURF.fill(GREY) pygame.draw.rect(DISPLAYSURF, DarkColor, (0, 0, ResX, 50)) pygame.draw.rect(DISPLAYSURF, DarkColor, (0, 0, 100, ResY)) pygame.draw.rect(DISPLAYSURF, DarkColor, (ResX - 100, 0, ResX, ResY)) displayQuery(selection, x, y) for i in range(4): if (i + 1 == rand): texSurfaceObj = fontObj.render(str(n), True, BLACK) texRectObj = texSurfaceObj.get_rect() pygame.draw.circle(DISPLAYSURF, LightColor, (foodx + (i + 1) * gap, foody), 40, 0) texRectObj.center = (foodx + (i + 1) * gap, foody + 3) DISPLAYSURF.blit(texSurfaceObj, texRectObj) else: texSurfaceObj = fontObj.render(str(randomOptions[counter]), True, BLACK) counter += 1 texRectObj = texSurfaceObj.get_rect() pygame.draw.circle(DISPLAYSURF, LightColor, (foodx + (i + 1) * gap, foody), 40, 0) texRectObj.center = (foodx + (i + 1) * gap, foody + 3) DISPLAYSURF.blit(texSurfaceObj, texRectObj) counter = 0 pygame.draw.rect(DISPLAYSURF, DarkColor, (boxx - 40, boxy, boxx - boxx + 80, boxy)) scoreBoard(score, hscore) foody += speed if (score == 10 * speedinc): speed += 2 speedinc += 1 if foody > ResY - 1: if (foodx + (rand) * gap == boxx): score += 1 else: if (score > hscore): hscore = score ggAnimation(score, hscore) newGameAnimation() score = 0 speed = ResY / 320 speedinc = 1 foody = 100 selection, n, x, y = randomOperation(maxi) rand = randint(1, 4) if (n < 3): a = n + (1) b = n + (2) c = n + (3) else: a = n + (1) * (-1)**randint(1, 2) b = n + (2) * (-1)**randint(1, 2) c = n + (3) * (-1)**randint(1, 2) randomOptions = [a, b, c] counter = 0 while Gtk.events_pending(): Gtk.main_iteration() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if (event.key == K_LEFT or event.key == K_a): if (boxx > gap): boxx -= gap elif (event.key == K_RIGHT or event.key == K_d): if (boxx < ResX - gap): boxx += gap pygame.display.update() fpsClock.tick(FPS)
def run(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.VIDEORESIZE: pygame.display.set_mode(event.size, pygame.RESIZABLE) break g.init() if not self.journal: utils.load() self.pages = pages.Pages() self.map1 = map1.Map1() self.ctry = ctry.Ctry() load_save.retrieve() self.buttons_setup() if self.canvas is not None: self.canvas.grab_focus() ctrl = False 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 is not None: self.canvas.grab_focus() elif event.type == pygame.MOUSEBUTTONDOWN: g.redraw = True self.ctry.message = None g.pic = g.globe if event.button == 1: if self.do_click(): pass else: bu = buttons.check() if bu != '': self.do_button(bu) self.flush_queue() if event.button == 3: self.ctry.clear() elif event.type == pygame.KEYDOWN: # throttle keyboard repeat self.ctry.message = None g.pic = g.globe 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)
def savePicData(self, widget): logger.debug("User selected save image data control.") # Launch dialog to select file to save to. dlg = Gtk.FileChooserDialog("Save image data...", self.myWindow, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK)) f = Gtk.FileFilter() f.set_name("DAT Files") f.add_pattern("*.dat") dlg.add_filter(f) response = dlg.run() # Check for positive response, and get filename. fname = "" if ((response == Gtk.ResponseType.OK) or (response == Gtk.STOCK_SAVE)): fname = dlg.get_filename() # Destroy dialog. dlg.destroy() # If have a filename then save. if fname != "": # Force to PNG files pre, ext = os.path.splitext(fname) fname = pre + '.dat' # Open file for binary write. bf = open(fname, 'wb') # Write image size to file. bf.write(struct.pack('i', self.imageWidth)) bf.write(struct.pack('i', self.imageHeight)) # Write max iterations to file. bf.write(struct.pack('i', self.maxIterations)) # Write image centre to file. bf.write(struct.pack('f', self.centreReal)) bf.write(struct.pack('f', self.centreImag)) # Write pixel size to file. bf.write(struct.pack('f', self.pxSize)) # Write image scale to file. bf.write(struct.pack('f', self.imageScale)) # Write iteration data to the file. for r in range(0, self.imageHeight): for c in range(0, self.imageWidth): bf.write(struct.pack('f', self.iterations[r][c])) # Close binary file. bf.close() # Update status bar to wait for image. self.statusbar.pop(self.context_id) self.statusbar.push(self.context_id, "Image data saved to : {0:s}".format(fname)) # Check for Gtk events. Required to update status bar now. while Gtk.events_pending(): Gtk.main_iteration()
def loadPicData(self, widget): logger.debug("User selected load image data control.") # Inhibit the some menu items during image generation. self.blockMenus(False) # Start time for image generation timing. startTime = datetime.now() # Launch dialog to select file to read from. dlg = Gtk.FileChooserDialog("Load image data...", self.myWindow, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) f = Gtk.FileFilter() f.set_name("DAT Files") f.add_pattern("*.dat") dlg.add_filter(f) response = dlg.run() # Check for positive response, and get filename. fname = "" if ((response == Gtk.ResponseType.OK) or (response == Gtk.STOCK_OPEN)): fname = dlg.get_filename() # Destroy dialog. dlg.destroy() # If have a filename then open. if fname != "": # Open file for binary write. bf = open(fname, 'rb') # Read image size from file. dataWidth = struct.unpack('i', bf.read(4))[0] dataHeight = struct.unpack('i', bf.read(4))[0] # Check if iterations array needs to be resized. if ((dataWidth != self.imageWidth) or (dataHeight != self.imageHeight)): # Resize the array to suit data. logger.debug( "Resizing iterations array to width : {0:d}, height : {1:d}" .format(dataWidth, dataHeight)) self.iterations = [[0 for i in range(dataWidth)] for j in range(dataHeight)] self.imageWidth = dataWidth self.imageHeight = dataHeight # Initialise image as size changed. self.initPic() else: self.imageWidth = dataWidth self.imageHeight = dataHeight # Read max iterations from file. dataIterations = struct.unpack('i', bf.read(4))[0] # Resize space required for histogram if required. if (dataIterations != self.maxIterations): logger.debug( "Resizing histogram arrays to dimension : {0:d}".format( dataIterations)) self.bins = [(i + 1) for i in range(dataIterations)] self.hist = [0 for i in range(dataIterations)] # Update maximum iterations. self.maxIterations = dataIterations # Read image centre from file. self.centreReal = struct.unpack('f', bf.read(4))[0] self.centreImag = struct.unpack('f', bf.read(4))[0] # Read pixel size from file. self.pxSize = struct.unpack('f', bf.read(4))[0] # Read image scale from file. self.imageScale = struct.unpack('f', bf.read(4))[0] # Read iteration data from the file. for r in range(0, self.imageHeight): for c in range(0, self.imageWidth): self.iterations[r][c] = struct.unpack('f', bf.read(4))[0] # Close binary file. bf.close() self.renderImage(self.black) # Update image information. self.updateInfo() # End time and image generation elapsed time. endTime = datetime.now() self.genTime = "{0:s}".format(str(endTime - startTime)) # Update status bar to wait for image. self.statusbar.pop(self.context_id) self.statusbar.push( self.context_id, "Loaded image and completed render in : {0:s}".format( self.genTime)) # Enable menu items inhibited during image generation. self.blockMenus(True) # Check for Gtk events. Required to update status bar now. while Gtk.events_pending(): Gtk.main_iteration()
def make(self): self.initialize() # Variable Initialization black = (0, 0, 0) white = (255, 255, 255) clock = pygame.time.Clock() crashed = False # Sound loads self.hit = pygame.mixer.Sound("assets/sounds/hit.ogg") self.point = pygame.mixer.Sound("assets/sounds/point.ogg") # image loads land = pygame.image.load("assets/land.png").convert() land1 = pygame.transform.scale(land, (490, 150)) land2 = land1 sky = pygame.image.load("assets/sky.png").convert() sky = pygame.transform.scale(sky, (490, 200)) skyfill = pygame.image.load("assets/skyfill.png").convert() skyfill = pygame.transform.scale(skyfill, (490, 500)) # 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() if self.welcomeflag == 1: a = welcomescreen(self.gameDisplay) a.run() self.welcomeflag = 0 self.keyinit = 1 self.gameDisplay.fill(white) self.gameDisplay.blit(skyfill, (350, 0)) self.gameDisplay.blit(sky, (350, 400)) # Pillar Display for i in self.pillarlist: i.display(self.gameDisplay, self.pillarlist, self.birds, self) if(self.welcomeflag == 1): a = welcomescreen(self.gameDisplay) a.run() self.welcomeflag = 0 self.keyinit = 1 break # Platform blit self.gameDisplay.blit(land1, (self.land1x, 600)) self.gameDisplay.blit(land2, (self.land2x, 600)) self.land1x -= 3 self.land2x -= 3 if(self.land1x <= -140): self.land1x = 837 if(self.land2x <= -140): self.land2x = 837 if(self.keyinit == 1): self.birds.jump(land1, land2, self.land1x, self.land2x, self) if(self.welcomeflag == 1): a = welcomescreen(self.gameDisplay) a.run() self.welcomeflag = 0 self.keyinit = 1 continue if event.type == pygame.KEYDOWN and event.key == 273 and self.keytest == 0: self.keyinit = self.keytest = 1 if(self.birds.t > 25): self.birds.angle = 0 self.birds.t = 0 if event.type == pygame.KEYUP and event.key == 273 and self.musicflag: self.keytest = 0 self.musicflag = False if not(self.musicflag) and event.type == pygame.KEYDOWN and event.key == 273: pygame.mixer.music.load("assets/sounds/wing.ogg") pygame.mixer.music.play(0, 0) self.musicflag = True # bird display self.birds.display(self.gameDisplay, self.flag) head3 = self.font3.render(str(self.scores), 1, (white)) self.gameDisplay.blit(head3, (580, 30)) # BLACK RECTANGLES DISPLAY pygame.draw.line(self.gameDisplay, black, (350, 0), (350, 768), 1) pygame.draw.line(self.gameDisplay, black, (840, 0), (840, 768), 1) pygame.draw.rect(self.gameDisplay, black, (0, 0, 350, 768)) pygame.draw.rect(self.gameDisplay, black, (840, 0, 693, 768)) pygame.display.update() clock.tick(60) if crashed: # Game crash or Close check pygame.quit() sys.exit() # Just a window exception check condition event1 = pygame.event.get() if event1.type == pygame.QUIT: crashed = True if crashed: pygame.quit() sys.exit()
def gtk_process_events(*a): '''Method to simulate a few iterations of the gtk main loop''' assert Gtk is not None while Gtk.events_pending(): Gtk.main_iteration() return True # continue
def run(self): self.running = True screen = pygame.display.get_surface() width = screen.get_width() height = screen.get_height() dirty = [] dirty.append( pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(0, 0, width, height))) pygame.display.update(dirty) while self.running: dirty = [] # Pump GTK messages. while Gtk.events_pending(): Gtk.main_iteration() if not self.running: break # Pump PyGame messages. for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.VIDEORESIZE: pygame.display.set_mode(event.size, pygame.RESIZABLE) width = screen.get_width() height = screen.get_height() dirty.append( pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(0, 0, width, height))) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.direction = -1 elif event.key == pygame.K_RIGHT: self.direction = 1 # Move the ball if not self.paused: # Erase the ball dirty.append( pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), RADIUS)) self.x += self.vx * self.direction if self.direction == 1 and self.x > width - RADIUS: self.x = width - RADIUS self.direction = -1 elif self.direction == -1 and self.x < RADIUS: self.x = RADIUS self.direction = 1 self.y += self.vy if self.y > height - RADIUS: self.y = height - RADIUS self.vy = -self.vy self.vy += 5 # Draw the ball dirty.append( pygame.draw.circle(screen, (192, 0, 0), (self.x, self.y), RADIUS)) # Update Display pygame.display.update(dirty) # Try to stay at 30 FPS self.clock.tick(30)
def on_bttndwt_clicked(self, widget): image = cv2.imread( self.imgbuffer.get_text(self.imgbuffer.get_iter_at_line(0), self.imgbuffer.get_iter_at_offset(-1), 0)) height, width = image.shape[:2] image2 = waveleteTransform(image) self.progress_bar.set_fraction(0.284760845) while Gtk.events_pending(): Gtk.main_iteration() image3 = inverseWaveleteTransform(image2) self.progress_bar.set_fraction(0.56952169) while Gtk.events_pending(): Gtk.main_iteration() cv2.imwrite('/tmp/awal.jpeg', image) cv2.imwrite('/tmp/prosesdwt.jpeg', image2) cv2.imwrite('/tmp/resultdwt.jpeg', image3) show = Gtk.Window() headerBar = Gtk.HeaderBar() headerBar.set_show_close_button(True) show.set_border_width(10) show.set_default_size(400, 200) vboxP = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) # self.add(vboxP) hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vboxP.pack_start(hbox, 1, 1, 10) loadawal = Gtk.Image.new_from_file('/tmp/awal.jpeg') hbox.pack_start(loadawal, 1, 1, 5) loadproses = Gtk.Image.new_from_file('/tmp/prosesdwt.jpeg') hbox.pack_start(loadproses, 1, 1, 5) loadresult = Gtk.Image.new_from_file('/tmp/resultdwt.jpeg') hbox.pack_start(loadresult, 1, 1, 5) vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) vboxP.pack_start(vbox, 1, 1, 0) hboxheader = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxheader, 1, 1, 0) # GLCM CITRA AWAL glcmaw = GLCM(image, 0, 1) self.progress_bar.set_fraction(0.711902113) while Gtk.events_pending(): Gtk.main_iteration() kontrasaw, meanIaw, meanJaw, energyaw, homogenityaw = glcmaw.contrast() self.progress_bar.set_fraction(0.712458287) while Gtk.events_pending(): Gtk.main_iteration() taoIaw, taoJaw = glcmaw.tao() self.progress_bar.set_fraction(0.713014461) while Gtk.events_pending(): Gtk.main_iteration() korelasionaw = glcmaw.correlation() self.progress_bar.set_fraction(0.713570635) while Gtk.events_pending(): Gtk.main_iteration() gskontrasaw = rgb2gs(kontrasaw) gsenergyaw = rgb2gs(energyaw) gshomogenityaw = rgb2gs(homogenityaw) gskorelasiaw = rgb2gs(korelasionaw) # GLCM CITRA DWT glcm = GLCM(image3, 0, 1) self.progress_bar.set_fraction(0.855951058) while Gtk.events_pending(): Gtk.main_iteration() kontras, meanI, meanJ, energy, homogenity = glcm.contrast() self.progress_bar.set_fraction(0.856507232) while Gtk.events_pending(): Gtk.main_iteration() taoI, taoJ = glcm.tao() self.progress_bar.set_fraction(0.857063406) while Gtk.events_pending(): Gtk.main_iteration() korelasion = glcm.correlation() self.progress_bar.set_fraction(0.85761958) while Gtk.events_pending(): Gtk.main_iteration() gskontras = rgb2gs(kontras) gsenergy = rgb2gs(energy) gshomogenity = rgb2gs(homogenity) gskorelasi = rgb2gs(korelasion) # PSNR imagePSNR1 = cv2.imread("/tmp/awal.jpeg") imagePSNR2 = cv2.imread("/tmp/resultdwt.jpeg") MSE, PSNR = mse(imagePSNR1, imagePSNR2) gsmse = rgb2gs(MSE) gspsnr = rgb2gs(PSNR) labelkosong = Gtk.Label(" ") hboxheader.pack_start(labelkosong, 1, 1, 10) labeldwt = Gtk.Label("DWT") hboxheader.pack_end(labeldwt, 1, 1, 0) labelawal = Gtk.Label("Awal") hboxheader.pack_end(labelawal, 1, 1, 0) hboxhomo = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxhomo, 1, 1, 10) labelhomo = Gtk.Label("Homogenitas") hboxhomo.pack_start(labelhomo, 1, 1, 0) bufferhomodwt = Gtk.TextBuffer() viewhomodwt = Gtk.TextView() viewhomodwt.set_buffer(bufferhomodwt) bufferhomodwt.set_text("" + str(gshomogenity)) viewhomodwt.set_can_focus(0) hboxhomo.pack_end(viewhomodwt, 1, 1, 0) bufferhomoaw = Gtk.TextBuffer() viewhomoaw = Gtk.TextView() viewhomoaw.set_buffer(bufferhomoaw) bufferhomoaw.set_text("" + str(gshomogenityaw)) viewhomoaw.set_can_focus(0) hboxhomo.pack_end(viewhomoaw, 1, 1, 0) hboxkontras = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxkontras, 1, 1, 10) labelkontras = Gtk.Label("Kontras") hboxkontras.pack_start(labelkontras, 1, 1, 12) bufferkontrasdwt = Gtk.TextBuffer() viewkontrasdwt = Gtk.TextView() viewkontrasdwt.set_buffer(bufferkontrasdwt) bufferkontrasdwt.set_text("" + str(gskontras)) viewkontrasdwt.set_can_focus(0) hboxkontras.pack_end(viewkontrasdwt, 1, 1, 0) bufferkontrasaw = Gtk.TextBuffer() viewkontrasaw = Gtk.TextView() viewkontrasaw.set_buffer(bufferkontrasaw) bufferkontrasaw.set_text("" + str(gskontrasaw)) viewkontrasaw.set_can_focus(0) hboxkontras.pack_end(viewkontrasaw, 1, 1, 0) hboxenergy = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxenergy, 1, 1, 10) labelenergy = Gtk.Label("Energy") hboxenergy.pack_start(labelenergy, 1, 1, 16) bufferenergydwt = Gtk.TextBuffer() viewenergydwt = Gtk.TextView() viewenergydwt.set_buffer(bufferenergydwt) bufferenergydwt.set_text("" + str(gsenergy)) viewenergydwt.set_can_focus(0) hboxenergy.pack_end(viewenergydwt, 1, 1, 0) bufferenergyaw = Gtk.TextBuffer() viewenergyaw = Gtk.TextView() viewenergyaw.set_buffer(bufferenergyaw) bufferenergyaw.set_text("" + str(gsenergyaw)) viewenergyaw.set_can_focus(0) hboxenergy.pack_end(viewenergyaw, 1, 1, 0) hboxkorelasi = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxkorelasi, 1, 1, 10) labelkorelasi = Gtk.Label("Korelasi") hboxkorelasi.pack_start(labelkorelasi, 1, 1, 12) bufferkorelasidwt = Gtk.TextBuffer() viewkorelasidwt = Gtk.TextView() viewkorelasidwt.set_buffer(bufferkorelasidwt) bufferkorelasidwt.set_text("" + str(gskorelasi)) viewkorelasidwt.set_can_focus(0) hboxkorelasi.pack_end(viewkorelasidwt, 1, 1, 0) bufferkorelasiaw = Gtk.TextBuffer() viewkorelasiaw = Gtk.TextView() viewkorelasiaw.set_buffer(bufferkorelasiaw) bufferkorelasiaw.set_text("" + str(gskorelasiaw)) viewkorelasiaw.set_can_focus(0) hboxkorelasi.pack_end(viewkorelasiaw, 1, 1, 0) hboxmse = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxmse, 1, 1, 10) labelmse = Gtk.Label("MSE") hboxmse.pack_start(labelmse, 0, 0, 60) buffermsedwt = Gtk.TextBuffer() viewmsedwt = Gtk.TextView() viewmsedwt.set_buffer(buffermsedwt) buffermsedwt.set_text("" + str(gsmse)) viewmsedwt.set_can_focus(0) hboxmse.pack_end(viewmsedwt, 1, 1, 0) hboxpsnr = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) vbox.pack_start(hboxpsnr, 1, 1, 10) labelpsnr = Gtk.Label("PSNR") hboxpsnr.pack_start(labelpsnr, 0, 0, 60) bufferpsnrdwt = Gtk.TextBuffer() viewpsnrdwt = Gtk.TextView() viewpsnrdwt.set_buffer(bufferpsnrdwt) bufferpsnrdwt.set_text("" + str(gspsnr)) viewpsnrdwt.set_can_focus(0) hboxpsnr.pack_end(viewpsnrdwt, 1, 1, 0) self.progress_bar.set_fraction(1) while Gtk.events_pending(): Gtk.main_iteration() show.add(vboxP) show.connect("delete-event", Gtk.main_quit) show.show_all() self.progress_bar.set_fraction(0)
def _p(self): for i in range(5): time.sleep(0.1) while Gtk.events_pending(): Gtk.main_iteration()
def load_list(self): for a in ['0cat', 'com', 'shorts']: if a == '0cat': file0 = self.ifile_main else: file0 = self.ifile_spacial contents_main = Popen( ['mdb-export', '-d', 'new_col', '-R', '\nnew_row', file0, a], 0, stdout=PIPE, env={ 'MDB_JET3_CHARSET': 'cp1256' }).communicate()[0].decode("utf8") list_contents_main = contents_main.split('new_row') for p in range(len(list_contents_main)): contents0_main = re.sub(r'"', '', list_contents_main[p]) #contents0_main = contents0_main.strip() if p == 0: motif = contents0_main.split('\n') motif0 = motif[0].split('new_col') motif0 = list(map(lambda i: i.lower(), motif0)) cols = self.get_cols(a, motif0) else: motif0 = contents0_main.split('new_col') if len(motif0) == 1: continue else: if a == '0cat': while (Gtk.events_pending()): Gtk.main_iteration() ss = self.store_books.append( None, [ True, int(motif0[cols['id']]), motif0[cols['name']], 0, '', '', '', '', 0, 0 ]) self.get_books_part(motif0[cols['id']], ss) elif a == 'com': if int(motif0[cols['bk']]) in self.comments: ls = self.comments[int(motif0[cols['bk']])] ls1 = [[ int(motif0[cols['id']]), motif0[cols['com']] ]] self.comments[int( motif0[cols['bk']])] = ls + ls1 else: self.comments[int(motif0[cols['bk']])] = [ [ int(motif0[cols['id']]), motif0[cols['com']] ], ] elif a == 'shorts': if int(motif0[cols['bk']]) in self.shorts: ls = self.shorts[int(motif0[cols['bk']])] ls1 = [[ motif0[cols['ramz']], motif0[cols['nass']] ]] self.shorts[int(motif0[cols['bk']])] = ls + ls1 else: self.shorts[int(motif0[cols['bk']])] = [ [ motif0[cols['ramz']], motif0[cols['nass']] ], ]
def __flush_gtk_events(self): while Gtk.events_pending(): Gtk.main_iteration()
def set_total(self, count): from gi.repository import Gtk self.pm.set_pass(self.title, total=count + 1) while Gtk.events_pending(): Gtk.main_iteration()
def web_send(self, msg): self.viewer.run_javascript(msg, None, None, None) while Gtk.events_pending(): Gtk.main_iteration()
def update_menu(self, index): if not internet_on(): print('--- Not internet connection ---') if self.icon_light: icon = os.path.join( comun.ICONDIR, weatherservice.CONDITIONS['not available']['icon-light']) else: icon = os.path.join( comun.ICONDIR, weatherservice.CONDITIONS['not available']['icon-dark']) self.indicators[index].set_icon(icon) self.indicators[index].set_label('', '') msg = weatherservice.CONDITIONS['not available']['text'] msg += '\n'+_('Not Internet connection') image = os.path.join( comun.IMAGESDIR, weatherservice.CONDITIONS['not available']['image']) self.notifications[index].update( 'My-Weather-Indicator', msg, image) self.notifications[index].show() return print('--- Updating data in location %s ---' % (index)) if self.preferences[index]['autolocation']: lat, lon = ipaddress.get_current_location() location = geocodeapi.get_inv_direction(lat, lon)['city'] if location is None: location = '' print(lat, lon, location) if self.preferences[index]['latitude'] != lat and\ self.preferences[index]['longitude'] != lon: self.preferences[index]['latitude'] = lat self.preferences[index]['longitude'] = lon self.preferences[index]['location'] = location if self.ws == 'yahoo': self.weatherservices[index] =\ wyahooapi.YahooWeatherService( longitude=self.preferences[index]['longitude'], latitude=self.preferences[index]['latitude'], units=self.units) self.menus[index]['evolution'].hide() elif self.ws == 'worldweatheronline': self.weatherservices[index] =\ worldweatheronlineapi.WorldWeatherOnlineService( longitude=self.preferences[index]['longitude'], latitude=self.preferences[index]['latitude'], units=self.units, key=self.key) self.menus[index]['evolution'].hide() elif self.ws == 'openweathermap': self.weatherservices[index] =\ wopenweathermapapi.OWMWeatherService( longitude=self.preferences[index]['longitude'], latitude=self.preferences[index]['latitude'], units=self.units) self.menus[index]['evolution'].show() elif self.ws == 'wunderground': self.weatherservices[index] =\ wundergroundapi.UndergroundWeatherService( longitude=self.preferences[index]['longitude'], latitude=self.preferences[index]['latitude'], units=self.units, key=self.key) self.menus[index]['evolution'].hide() print('****** Updating weather') weather = self.weatherservices[index].get_weather() print('****** Updated weather') print(self.weathers[index]) if weather is None or (weather['ok'] is False and ( self.weathers[index] is not None and self.weathers[index]['ok'] is True)): return temporal_current_conditions = weather['current_conditions'] conditions_changed = False if len(temporal_current_conditions) != 0: self.current_conditions[index] = temporal_current_conditions self.weathers[index] = weather ######################################################## if self.preferences[index]['location']: self.menus[index]['location'].set_label( _('Location') + ': ' + self.preferences[index]['location']) self.menus[index]['temperature'].set_label(_('Temperature') + ': \ {0}{1:c}'.format(self.current_conditions[index]['temperature'], 176)) self.menus[index]['humidity'].set_label( _('Humidity') + ': ' + self.current_conditions[index]['humidity']) self.menus[index]['feels_like'].set_label(_('Feels like')+': \ {0}{1:c}'.format(self.current_conditions[index]['feels_like'], 176)) self.menus[index]['dew_point'].set_label(_('Dew Point') + ': \ {0}{1:c}'.format(self.current_conditions[index]['dew_point'], 176)) self.menus[index]['wind'].set_label( _('Wind') + ':' + self.current_conditions[index]['wind_condition']) if self.current_conditions[index]['wind_icon']: image = Gtk.Image.new_from_file( os.path.join(comun.IMAGESDIR, self.current_conditions[index]['wind_icon'])) self.menus[index]['wind'].set_image(image) self.menus[index]['condition'].set_label( self.current_conditions[index]['condition_text']) afile = os.path.join( comun.IMAGESDIR, self.current_conditions[index]['condition_image']) self.menus[index]['condition'].set_image( Gtk.Image.new_from_file(os.path.join( comun.IMAGESDIR, self.current_conditions[index]['condition_image']))) filename = os.path.join( comun.WIMAGESDIR, self.current_conditions[index]['condition_image']) if self.widgets[index] is not None: self.widgets[index].set_location( self.preferences[index]['location']) self.widgets[index].set_weather(weather) self.menus[index]['dawn'].set_label( _('Dawn')+': '+self.current_conditions[index]['dawn']) self.menus[index]['sunrise'].set_label( _('Sunrise')+': '+self.current_conditions[index]['sunrise']) self.menus[index]['sunset'].set_label( _('Sunset')+': '+self.current_conditions[index]['sunset']) self.menus[index]['dusk'].set_label( _('Dusk')+': '+self.current_conditions[index]['dusk']) self.menus[index]['moon_phase'].set_label( self.current_conditions[index]['moon_phase']) self.menus[index]['moon_phase'].set_image( Gtk.Image.new_from_file( os.path.join(comun.IMAGESDIR, self.current_conditions[index]['moon_icon']))) # pressure = ( self.current_conditions[index]['pressure'] is not None) visibility = ( self.current_conditions[index]['visibility'] is not None) cloudiness = ( self.current_conditions[index]['cloudiness'] is not None) solarradiation = ( self.current_conditions[index]['solarradiation'] is not None) UV = ( self.current_conditions[index]['UV'] is not None) precip_today = ( self.current_conditions[index]['precip_today'] is not None) self.menus[index]['pressure'].set_visible(pressure) self.menus[index]['visibility'].set_visible(visibility) self.menus[index]['cloudiness'].set_visible(cloudiness) self.menus[index]['uv'].set_visible(UV) self.menus[index]['precipitation'].set_visible(precip_today) if pressure: self.menus[index]['pressure'].set_label( ('%s: %s') % (_('Pressure'), self.current_conditions[index]['pressure'])) if visibility: value = self.current_conditions[index]['visibility'] self.menus[index]['visibility'].set_label( ('%s: %s') % (_('Visibility'), value)) if cloudiness: value = self.current_conditions[index]['cloudiness'] self.menus[index]['cloudiness'].set_label( ('%s: %s') % (_('Cloudiness'), value)) if UV: value = self.current_conditions[index]['UV'] self.menus[index]['uv'].set_label( ('%s: %s') % (_('UV'), value)) if precip_today: value = self.current_conditions[index]['precip_today'] self.menus[index]['precipitation'].set_label( ('%s: %s') % (_('Precipitation'), value)) if self.preferences[index]['show-temperature'] is True: value = self.current_conditions[index]['temperature'] self.indicators[index].set_label( '{0}{1:c}'.format(value, 176), '') else: self.indicators[index].set_label('', '') if self.preferences[index]['show'] is True: self.indicators[index].set_status( appindicator.IndicatorStatus.ACTIVE) else: self.indicators[index].set_status( appindicator.IndicatorStatus.PASSIVE) if self.icon_light: icon = os.path.join( comun.ICONDIR, self.current_conditions[index]['condition_icon_light']) else: icon = os.path.join( comun.ICONDIR, self.current_conditions[index]['condition_icon_dark']) self.indicators[index].set_icon(icon) if self.preferences[index]['show-notifications'] is True: msg = _('Conditions in')+' ' msg += self.preferences[index]['location'] + '\n' msg += _('Temperature')+': ' +\ self.current_conditions[index]['temperature'] + '\n' msg += _('Humidity') + ': ' + \ self.current_conditions[index]['humidity'] + '\n' msg += _('Wind') + ': ' +\ self.current_conditions[index]['wind_condition']+'\n' msg += self.current_conditions[index]['condition_text'] image = os.path.join( comun.IMAGESDIR, self.current_conditions[index]['condition_image']) self.notifications[index].update( 'My-Weather-Indicator', msg, image) self.notifications[index].show() while Gtk.events_pending(): Gtk.main_iteration() print('--- End of updating data in location %s ---' % (index)) self.last_update_time = time.time()
def show_progress_pulse(self): self._get_widget("progressbar_wait").pulse() while Gtk.events_pending(): Gtk.main_iteration()
def run(self, gameDisplay, scores): black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) clock = pygame.time.Clock() crashed = False press = 0 # image load land = pygame.image.load("assets/land.png").convert() land1 = pygame.transform.scale(land, (490, 150)) sky = pygame.image.load("assets/sky.png").convert() sky = pygame.transform.scale(sky, (490, 200)) skyfill = pygame.image.load("assets/skyfill.png").convert() skyfill = pygame.transform.scale(skyfill, (490, 500)) scoreboard = pygame.image.load("assets/scoreboard.png") scoreboard = pygame.transform.scale(scoreboard, (360, 450)) land1x = 350 replay = pygame.image.load("assets/replay.png") replay = pygame.transform.scale(replay, (150, 90)) # font load font2 = pygame.font.Font("fonts/Arimo.ttf", 30) # Scores load if os.path.getsize("score.pkl") == 0: with open('score.pkl', 'wb') as output: pickle.dump(0, output, pickle.HIGHEST_PROTOCOL) with open('score.pkl', 'rb') as input: # REading maxscore = pickle.load(input) newflag = 0 if (scores > maxscore): with open('score.pkl', 'wb') as output: pickle.dump(scores, output, pickle.HIGHEST_PROTOCOL) maxscore = scores newflag = 1 swoosh = pygame.mixer.Sound("assets/sounds/swoosh.ogg") # GAME LOOP BEGINS !!! while not crashed: # Gtk events while Gtk.events_pending(): Gtk.main_iteration() for event in pygame.event.get(): # totaltime+=timer.tick() if event.type == pygame.QUIT: crashed = True if event.type == pygame.KEYDOWN: swoosh.play(0) return 1 # print "help" mos_x, mos_y = pygame.mouse.get_pos() gameDisplay.fill(white) gameDisplay.blit(skyfill, (350, 0)) gameDisplay.blit(sky, (350, 400)) # Platform blit gameDisplay.blit(land1, (land1x, 600)) gameDisplay.blit(scoreboard, (420, 100)) gameDisplay.blit(replay, (530, 450)) if replay.get_rect( center=(530 + (replay.get_width() / 2), 450 + (replay.get_height() / 2))).collidepoint( mos_x, mos_y): gameDisplay.blit( pygame.transform.scale( replay, (replay.get_width() + 4, replay.get_height() + 4)), (530 - 2, 450 - 2)) if (pygame.mouse.get_pressed())[0] == 1 and press == 0: return # print scores scoress = font2.render(str(scores), 2, black) gameDisplay.blit(scoress, (630, 265)) if (newflag == 1): maxscores = font2.render(str(maxscore) + _(" NEW!"), 2, red) else: maxscores = font2.render(str(maxscore), 2, black) gameDisplay.blit(maxscores, (630, 330)) # 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) 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()
def _process_events(self): while Gtk.events_pending(): Gtk.main_iteration()
def run(self, restart=False): self.screen = pygame.display.get_surface() if not restart: pygame.init() pygame.display.init() # pygame.mixer.quit() self.pygame_started = True # Fake a Sugar cursor for the pyGame canvas area self.show_fake_cursor = True pygame.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0)) self.cursor_picture = pygame.image.load('standardcursor.png') self.cursor_picture.convert_alpha() self.canvas.connect('enter_notify_event', self.switch_on_fake_pygame_cursor_cb) self.canvas.connect('leave_notify_event', self.switch_off_fake_pygame_cursor_cb) self.canvas.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK) self.world = elements.Elements(self.screen.get_size()) self.world.renderer.set_surface(self.screen) self.world.add.ground() if self.opening_queue: path = self.opening_queue.encode('ascii', 'convert') if os.path.exists(path): self.world.json_load(path, serialized=True) if 'full_pos_list' in self.world.additional_vars: self.full_pos_list = \ self.world.additional_vars['full_pos_list'] if 'trackinfo' in self.world.additional_vars: self.trackinfo = self.world.additional_vars['trackinfo'] if 'tracked_bodies' in self.world.additional_vars: self.tracked_bodies = \ self.world.additional_vars['tracked_bodies'] while self.loop: while Gtk.events_pending(): Gtk.main_iteration() if not self.loop: pygame.quit() self.pygame_started = False break for event in pygame.event.get(): self.currentTool.handleEvents(event) if event.type == MOUSEBUTTONUP: # if event.button == 1: self.show_fake_cursor = True if self.in_focus: # Drive motors if self.world.run_physics: bodies_present = len(self.world.world.bodies) clear_all_active = self.activity.clear_all.get_sensitive() if (bodies_present > 2) and clear_all_active is False: self.activity.clear_all.set_sensitive(True) elif (bodies_present > 2) is False and \ clear_all_active is True: self.activity.clear_all.set_sensitive(False) poslist = self.full_pos_list clear_trace_active = \ self.activity.clear_trace.get_sensitive() if poslist: if not poslist[0]: if clear_trace_active: self.activity.clear_trace.set_sensitive(False) else: if clear_trace_active is False: self.activity.clear_trace.set_sensitive(True) for key, info in self.trackinfo.iteritems(): # [host_body, tracker, color, destroyed?] body = info[1] if info[3] is False: # Not destroyed the pen trackdex = info[4] def to_screen(pos): px = self.world.meter_to_screen(pos[0]) py = self.world.meter_to_screen(pos[1]) py = self.world.renderer.get_surface() \ .get_height() - py return (px, py) x = body.position.x y = body.position.y tupled_pos = to_screen((x, y)) posx = tupled_pos[0] posy = tupled_pos[1] try: self.full_pos_list[trackdex].append(posx) self.full_pos_list[trackdex].append(posy) except IndexError: self.full_pos_list.append([posx, posy]) ''' for body in self.world.world.GetBodyList(): if isinstance(body.userData, dict): if 'rollMotor' in body.userData: rollmotor = body.userData['rollMotor'] diff = rollmotor['targetVelocity'] - \ body.GetAngularVelocity() body.ApplyTorque(rollmotor['strength'] * \ diff * body.getMassData().I) ''' # Update & Draw World self.world.update(fps=self.box2d_fps) self.screen.fill((240, 240, 240)) # #f0f0f0, light-grey self.world.draw() # Draw output from tools self.currentTool.draw() # Show Sugar like cursor for UI consistancy if self.show_fake_cursor: self.screen.blit(self.cursor_picture, pygame.mouse.get_pos()) # Flip Display pygame.display.flip() # Stay < 30 FPS to help keep the rest of the platform responsive self.clock.tick(30) # Originally 50
def set_header(self, text): from gi.repository import Gtk self.__lbl.set_text(text) while Gtk.events_pending(): Gtk.main_iteration()
def _cmd(self, data): self.s.send(data) while Gtk.events_pending(): Gtk.main_iteration_do(True) if data.strip() != b"idle": return self.s.recv(99999)
def iterate(): while Gtk.events_pending(): Gtk.main_iteration()