Exemple #1
0
    def test_window(self):
        """Test that the window appears."""

        rh = RotateHandler(capacity=20)
        rh.setLevel(logging.DEBUG)

        gtkh = GtkHandler(rotate_handler=rh)
        gtkh.setLevel(logging.ERROR)

        l = logging.getLogger("GtkHandlerTest")
        l.setLevel(logging.DEBUG)

        l.addHandler(rh)
        l.addHandler(gtkh)

        l.info("An info message")
        l.warn("A warn message")
        l.debug("A debug message")
        log_message = "Debug message"
        try:
            wibble
        except:
            l.error(log_message,exc_info=True)

        while Gtk.events_pending():
            Gtk.main_iteration()
Exemple #2
0
 def flush_events(self):
     # docstring inherited
     Gdk.threads_enter()
     while Gtk.events_pending():
         Gtk.main_iteration()
     Gdk.flush()
     Gdk.threads_leave()
Exemple #3
0
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()
Exemple #4
0
    def detect_click(self):
        '''Event loop to detect clicks'''
        while True:
            #hack para sugargame
            while Gtk.events_pending():
                Gtk.main_iteration()

            for event in pygame.event.get():
                if event.type == QUIT:
                    try:
                        pygame.quit()
                        sys.exit()
                        return
                    except Exception, e:
                        return
                elif event.type == pygame.MOUSEBUTTONUP:
                    pos = pygame.mouse.get_pos()
                    clicked_sprites = [s for s in self.menu_items \
                                       if s.rect.collidepoint(pos)]
                    for s in clicked_sprites:
                        self.click_callback(s)
                        break

                    if self.exit_button:
                        if self.exit_button.rect.collidepoint(pos):
                            try:
                                pygame.quit()
                                sys.exit()
                                return
                            except Exception, e:
                                return
	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
Exemple #6
0
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 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)
Exemple #8
0
def log_error(msg):
    ErrorDialog.format_secondary_text(msg)
    response = ErrorDialog.run()
    while Gtk.events_pending():
        Gtk.main_iteration()
    if response:
        ErrorDialog.hide()
Exemple #9
0
def log_warning(msg):
    WarningDialog.format_secondary_text(msg)
    response = WarningDialog.run()
    while Gtk.events_pending():
        Gtk.main_iteration()
    if response:
        WarningDialog.hide()
Exemple #10
0
    def calculateDiffs(self, menuItem, showNotification=True):
        self.setMenuEnabled(False)
        self.packageTitle.set_label('Calculating file diffs...')
        while Gtk.events_pending():
            Gtk.main_iteration()
        selected = self.getSelectedPackages()

        totalDiff = 0

        for package in selected:
            diff = self.bkup.getFileSizeDiff(package)
            totalDiff += diff
            print(self.bkup.humanPrint(diff))
            humanDiff = self.bkup.humanPrint(diff)
            newLabel = package + ' (' + humanDiff + ' change)'
            print(self.packages[package].set_label(newLabel))

        self.setMenuEnabled(True)
        self.packageTitle.set_label('Packages from bkup.yaml:')
        self.removeDiffLabelTime = time.time() + 60 * 5
        GObject.timeout_add(60 * 1000, self.checkDiffLabelRemovalTime)

        if showNotification:
            msg = Notify.Notification.new('Calculated file diffs', 'Bkup')
            msg.show()

        return totalDiff
Exemple #11
0
    def run(self):

        GObject.timeout_add(100, self._idle, priority=GObject.PRIORITY_HIGH)

        while True:
            Gtk.main_iteration()
            gevent.sleep(.001)
    def test_error_and_recover(self):
        dispatcher, repo, worker, conf, logger = self.__get_dependencies()

        recorder_service = RecorderService(dispatcher, repo, worker, conf, logger, autorecover=True, recorderklass=self.recorderklass)
        self.assertEqual(recorder_service.status, INIT_STATUS)
        recorder_service.preview()
        self.__sleep()
        recorder_service.record()
        self.assertEqual(recorder_service.error_msg, None)
        self.assertNotEqual(recorder_service.current_mediapackage, None)
        dispatcher.emit("recorder-error", "Test Error")
        self.assertEqual(recorder_service.status, ERROR_STATUS)
        self.assertEqual(recorder_service.is_error(), True)
        self.assertNotEqual(recorder_service.error_msg, None)
        dispatcher.emit("timer-long")
        while Gtk.events_pending():
            Gtk.main_iteration()
        self.assertEqual(recorder_service.status, PREVIEW_STATUS)
        self.assertEqual(recorder_service.error_msg, None)
        recorder_service.record()
        self.assertEqual(recorder_service.status, RECORDING_STATUS)
        self.assertNotEqual(recorder_service.current_mediapackage, None)
        dispatcher.emit("timer-long")
        self.assertEqual(recorder_service.status, RECORDING_STATUS)
        self.assertNotEqual(recorder_service.current_mediapackage, None)
 def _load_active_document_symbols(self):
     """ Load the symbols for the given URI. """
     self._sourcetree.clear()
     #while Gtk.events_pending(): # <-- segfault
         #Gtk.main_iteration()
     document = self.window.get_active_document()
     if document:
         location = document.get_location()
         if location:
             uri = location.get_uri()
             self._log.debug("Loading %s...", uri)
             if uri is not None:
                 if uri[:7] == "file://":
                     filename = uri[7:]
                     self._sourcetree.parse_file(filename, uri)
                 elif self.load_remote_files:
                     basename = location.get_basename()
                     fd, filename = tempfile.mkstemp('.'+basename)
                     contents = document.get_text(document.get_start_iter(),
                                                  document.get_end_iter(),
                                                  True)
                     os.write(fd, contents)
                     os.close(fd)
                     while Gtk.events_pending():
                         Gtk.main_iteration()
                     self._sourcetree.parse_file(filename, uri)
                     os.unlink(filename)
                 self._loaded_document = document
 def update(self, text, step):
     """ update is called regularly so that the gui can be redrawn """
     if text:
         self.status.set_text(text)
     self.progress.set_fraction(step/float(self.totalSteps))
     while Gtk.events_pending():
         Gtk.main_iteration()
Exemple #15
0
    def __init__(self, parent, total, text=_("Saved %(count)s of %(total)s.")):
        Gtk.Window.__init__(self)
        self.count = 0
        self.total = total
        self.text = text

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

        self.get_child().add(vbox)

        self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
        self.show_all()
        while Gtk.events_pending():
            Gtk.main_iteration()
Exemple #16
0
    def execute (self):
        # Python stdout, stderr, stdin redirection
        sys.stdout, self.stdout = self.stdout, sys.stdout
        sys.stderr, self.stderr = self.stderr, sys.stderr
        sys.stdin,  self.stdin  = self.stdin,  sys.stdin

        # System stdout, stderr redirection
        sys_stdout = os.dup(1)
        sys_stderr = os.dup(2)
        os.dup2 (self.pipewrite, 1)
        os.dup2 (self.pipewrite, 2)

        self.shell.eval(self)
        self.view.scroll_mark_onscreen(self.buffer.get_insert())
        while Gtk.events_pending():
            Gtk.main_iteration()

        # Get system output and remove system redirection
        os.dup2 (sys_stdout, 1)
        os.dup2 (sys_stderr, 2)
        os.close (sys_stdout)
        os.close (sys_stderr)

        # Remove python redirection
        sys.stdout, self.stdout = self.stdout, sys.stdout
        sys.stderr, self.stderr = self.stderr, sys.stderr
        sys.stdin,  self.stdin  = self.stdin,  sys.stdin
Exemple #17
0
    def on_browse_button_clicked(self, widget=None):
        """ Callback for browse_button_clicked event """
        buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
        dialog = Gtk.FileChooserDialog(
                title=_("Choose external mixer"),
                action=Gtk.FileChooserAction.OPEN,
                buttons=buttons)
        dialog.set_current_folder("/usr/bin")
        dialog.set_default_response(Gtk.ResponseType.OK)
        dialog.set_show_hidden(False)

        file_filter_mixers = Gtk.FileFilter()
        file_filter_mixers.set_name(_("Sound Mixers"))
        file_filter_mixers.add_custom(
                Gtk.FileFilterFlags.FILENAME, self.custom_mixer_filter, None)
        file_filter_all = Gtk.FileFilter()
        file_filter_all.set_name(_("All files"))
        file_filter_all.add_pattern("*")
        dialog.add_filter(file_filter_mixers)
        dialog.add_filter(file_filter_all)

        response = dialog.run()
        filename = dialog.get_filename()
        dialog.destroy()

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

        if response == Gtk.ResponseType.OK:
            self.mixer_entry.set_text(filename)
            PREFS["mixer"] = filename
            return filename
        elif response == Gtk.ResponseType.CANCEL:
            return None
Exemple #18
0
    def __init__(self, parent, text=None, child=None,
                 decorated=True, mouse=False, modal=True):
        GObject.GObject.__init__(self, type=Gtk.WindowType.TOPLEVEL)
        self.set_type_hint(Gdk.WindowTypeHint.UTILITY)
        self.set_position(mouse and Gtk.WindowPosition.MOUSE or
                          Gtk.WindowPosition.CENTER_ALWAYS)

        if parent:
            self.set_transient_for(parent.get_toplevel())

        self.set_modal(modal)
        self.set_decorated(decorated)
        self.set_title("")

        if text:
            label = Gtk.Label(label=text)
            align = Gtk.Alignment()
            align.set_padding(20, 20, 20, 20)
            align.add(label)
            self.add(align)
        elif child:
            self.add(child)

        while Gtk.events_pending():
            Gtk.main_iteration()
Exemple #19
0
    def step(self, **values):
        """Advance the counter by one. Arguments are applied to the
        originally-supplied text as a format string.

        This function doesn't return if the dialog is paused (though
        the GTK main loop will still run), and returns True if stop
        was pressed.
        """

        if self.count:
            self.current += 1
            self._progress.set_fraction(
                max(0, min(1, self.current / float(self.count))))
        else:
            self._progress.pulse()
        values.setdefault("total", self.count)
        values.setdefault("current", self.current)
        if self.count:
            t = (time.time() - self._start_time) / self.current
            remaining = math.ceil((self.count - self.current) * t)
            values.setdefault("remaining", util.format_time_display(remaining))
        self._label.set_markup(self._text % values)

        while not self.quit and (self.paused or Gtk.events_pending()):
            Gtk.main_iteration()
        return self.quit
Exemple #20
0
def _run_chooser(parent, chooser):
    """Run the chooser ("blocking") and return a list of paths.

    Args:
        parent (Gtk.Widget)
        chooser (Gtk.FileChooser)
    Returns:
        List[fsnative]
    """

    chooser.set_current_folder(fsn2glib(get_current_dir()))
    chooser.set_transient_for(get_top_parent(parent))

    if _response is not None:
        response = _response
        while Gtk.events_pending():
            Gtk.main_iteration()
    else:
        response = chooser.run()

    if response == Gtk.ResponseType.ACCEPT:
        result = [glib2fsn(fn) for fn in chooser.get_filenames()]

        current_dir = chooser.get_current_folder()
        if current_dir:
            set_current_dir(glib2fsn(current_dir))
    else:
        result = []
    chooser.destroy()
    return result
    def fillstore(self):
        # use the watch cursor
        self.setBusy(True)
        # disconnect the view first
        self.treeview_update.set_model(None)
        self.store.clear()
        # clean most objects
        self.dl_size = 0

        self.scrolledwindow_update.show()

        # add security and update groups to self.store
        if self.list.security_groups:
            self._add_header(_("Security updates"), self.list.security_groups)
            self._add_groups(self.list.security_groups)
        if self.list.security_groups and self.list.update_groups:
            self._add_header(_("Other updates"), self.list.update_groups)
        if self.list.update_groups:
            self._add_groups(self.list.update_groups)

        self.treeview_update.set_model(self.store)
        self.update_count()
        self.setBusy(False)
        while Gtk.events_pending():
            Gtk.main_iteration()
        self.updates_changed()
        return False
Exemple #22
0
    def initiate_purchase(self, app, iconname, url=None, html=None):
        """
        initiates the purchase workflow inside the embedded webkit window
        for the item specified
        """
        if not self._ask_for_tos_acceptance_if_needed():
            self.emit("terms-of-service-declined")
            return False

        self.init_view()
        self.app = app
        self.iconname = iconname
        self.wk.webkit.load_html_string(self.LOADING_HTML, "file:///")
        self.wk.show()
        while Gtk.events_pending():
            Gtk.main_iteration()
        if url:
            self.wk.webkit.load_uri(url)
        elif html:
            self.wk.webkit.load_html_string(html, "file:///")
        else:
            self.wk.webkit.load_html_string(DUMMY_HTML, "file:///")
        self.pack_start(self.wk, True, True, 0)
        # only for debugging
        if os.environ.get("SOFTWARE_CENTER_DEBUG_BUY"):
            GObject.timeout_add_seconds(1, _generate_events, self)
        return True
Exemple #23
0
def on_Updater_ApplyButton_clicked(*args):
	UpdaterWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))
	while Gtk.events_pending():
		Gtk.main_iteration()
	error = transaction.sysupgrade(show_updates = False)
	if error:
		handle_error(error)
    def showGUI(self):
        """Show the splash screen dialog."""

        imageFile = os.path.join(orca_platform.prefix,
                    orca_platform.datadirname,
                    orca_platform.package,
                    "gfx",
                    "orca-splash.png")

        image = Gtk.Image()
        image.set_from_file(imageFile)

        self.add(image)

        try:
            self.realize()
        except:
            debug.printException(debug.LEVEL_FINEST)

        self.set_transient_for(None)
        self.grab_focus()
        self.show_all()

        GObject.timeout_add(3000, self.hideGUI)

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

        return self
 def parse_history(self):
     date = None
     when = None
     last_row = None
     day = self.store.get_iter_first()
     if day is not None:
         date = self.store.get_value(day, self.COL_WHEN)
     if len(self.history.transactions) == 0:
         logging.debug("AptHistory is currently empty")
         return
     new_last = self.history.transactions[0].start_date
     for trans in self.history.transactions:
         while Gtk.events_pending():
             Gtk.main_iteration()
         when = trans.start_date
         if self.last is not None and when <= self.last:
             break
         if when.date() != date:
             date = when.date()
             day = self.store.append(None, (date, self.ALL, None))
             last_row = None
         actions = {self.INSTALLED: trans.install,
                    self.REMOVED: trans.remove,
                    self.UPGRADED: trans.upgrade,
                   }
         for action, pkgs in actions.items():
             for pkgname in pkgs:
                 row = (when, action, pkgname)
                 last_row = self.store.insert_after(day, last_row, row)
     self.last = new_last
     self.update_view()
Exemple #26
0
 def update(self, percent=None):
     self.progressbar.show()
     if percent:
         self.progressbar.set_fraction(percent/100.0)
     #self.progressbar.set_text(self.op)
     while Gtk.events_pending():
         Gtk.main_iteration()
Exemple #27
0
    def update_model(self, filter=False, all=False):
        self.model.clear()

        mainwindow = self.get_toplevel().window

        if mainwindow:
            mainwindow.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
        while Gtk.events_pending ():
            Gtk.main_iteration ()

        theme = Gtk.IconTheme.get_default()

        for type in Gio.content_types_get_registered():
            if filter and filter != type.split('/')[0]:
                continue

            pixbuf = icon.get_from_mime_type(type)
            description = Gio.content_type_get_description(type)
            app = Gio.app_info_get_default_for_type(type, False)

            if app:
                appname = app.get_name()
                applogo = icon.get_from_app(app)
            elif all and not app:
                appname = _('None')
                applogo = None
            else:
                continue

            self.model.append((type, pixbuf, description, applogo, appname))

        if mainwindow:
            mainwindow.set_cursor(None)
Exemple #28
0
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 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)
Exemple #30
0
    def _load_active_document_symbols(self):
        """ Load the symbols for the given URI. """
        self._sourcetree.clear()
        self._is_loaded = False
        # do not load if not the active tab in the panel
        panel = self.window.get_side_panel()
        if panel.get_visible_child() != self._sourcetree:
            return

        document = self.window.get_active_document()
        if document:
            location = document.get_location()
            if location:
                uri = location.get_uri()
                self._log.debug("Loading %s...", uri)
                if uri is not None:
                    if uri[:7] == "file://":
                        # use get_parse_name() to get path in UTF-8
                        filename = location.get_parse_name() 
                        self._sourcetree.parse_file(filename, uri)
                    elif self.load_remote_files:
                        basename = location.get_basename()
                        fd, filename = tempfile.mkstemp('.'+basename)
                        contents = document.get_text(document.get_start_iter(),
                                                     document.get_end_iter(),
                                                     True)
                        os.write(fd, bytes(contents, 'UTF-8'))
                        os.close(fd)
                        while Gtk.events_pending():
                            Gtk.main_iteration()
                        self._sourcetree.parse_file(filename, uri)
                        os.unlink(filename)
                    self._loaded_document = document
        self._is_loaded = True
def gtk_sync():
    """Wait while all pending GTK events are processed."""
    while Gtk.events_pending():
        Gtk.main_iteration()
Exemple #32
0
 def fill_string(self, files, destin):
     """ function to replace the variables with the tags for each file """
     tmp_title = None
     tmp_artist = None
     tmp_album = None
     tmp_albumartist = None
     tmp_genre = None
     tmp_track = None
     tmp_disc = None
     tmp_year = None
     tmp_comment = None
     try:
         item = eyeD3.Tag()
         item.link(files)
         item.setVersion(eyeD3.ID3_V2_4)
         item.setTextEncoding(eyeD3.UTF_8_ENCODING)
     except:
         # Tag error
         item = None
     # pull tag info for the current item
     if item:
         tmp_title = item.getTitle()
         if tmp_title == 'None':
             tmp_title = None
         if tmp_title:
             tmp_title = tmp_title.replace('/', '_')
         tmp_artist = item.getArtist('TPE1')
         if tmp_artist == 'None':
             tmp_artist = None
         if tmp_artist:
             tmp_artist = tmp_artist.replace('/', '_')
         tmp_album = item.getAlbum()
         if tmp_album == 'None':
             tmp_album = None
         if tmp_album:
             tmp_album = tmp_album.replace('/', '_')
         tmp_albumartist = item.getArtist('TPE2')
         if tmp_albumartist == 'None':
             tmp_albumartist = None
         if tmp_albumartist:
             tmp_albumartist = tmp_albumartist.replace('/', '_')
         try:
             tmp_genre = str(item.getGenre())
         except eyeD3.tag.GenreException:
             tmp_genre = None
         if tmp_genre == 'None':
             tmp_genre = None
         if tmp_genre:
             tmp_genre = tmp_genre.replace('/', '_')
             if ')' in tmp_genre:
                 tmp_genre = tmp_genre.split(')')[1]
         tmp_track = str(item.getTrackNum()[0])
         if tmp_track == 'None':
             tmp_track = None
         if tmp_track:
             if '/' in tmp_track:
                 tmp_track = tmp_track.split('/')[0]
             if len(tmp_track) == 1:
                 tmp_track = '0' + str(tmp_track)
             if len(tmp_track) > 2:
                 tmp_track = tmp_track[:2]
         tmp_disc = str(item.getDiscNum()[0])
         if tmp_disc == 'None':
             tmp_disc = None
         if tmp_disc:
             if '/' in tmp_disc:
                 tmp_disc = tmp_disc.split('/')[0]
             if len(tmp_disc) == 2:
                 tmp_disc = tmp_disc[-1]
         tmp_year = item.getYear()
         if tmp_year == 'None':
             tmp_year = None
         tmp_comment = item.getComment()
         if tmp_comment == 'None':
             tmp_comment = None
         if tmp_comment:
             tmp_comment = tmp_comment.replace('/', '_')
         # replace temp strings with actual tags
         if tmp_title:
             destin = destin.replace('%title%', tmp_title)
         if tmp_albumartist:
             destin = destin.replace('%albumartist%', tmp_albumartist)
         else:
             destin = destin.replace('%albumartist%', '%artist%')
         if tmp_artist:
             destin = destin.replace('%artist%', tmp_artist)
         if tmp_album:
             destin = destin.replace('%album%', tmp_album)
         if tmp_genre:
             destin = destin.replace('%genre%', tmp_genre)
         if tmp_track:
             destin = destin.replace('%track%', tmp_track)
         if tmp_disc:
             destin = destin.replace('%disc%', tmp_disc)
         if tmp_year:
             destin = destin.replace('%year%', tmp_year)
         if tmp_comment:
             destin = destin.replace('%comment%', tmp_comment)
         destin = destin + files[(files.rfind('.')):]
         while Gtk.events_pending():
             Gtk.main_iteration()
         return destin
     return
Exemple #33
0
def on_Updater_RefreshButton_clicked(*args):
    UpdaterWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))
    while Gtk.events_pending():
        Gtk.main_iteration()
    transaction.refresh()
Exemple #34
0
def on_TransValidButton_clicked(*args):
    UpdaterWindow.get_window().set_cursor(None)
    transaction.ConfDialog.hide()
    while Gtk.events_pending():
        Gtk.main_iteration()
    transaction.finalize()
Exemple #35
0
                            signal_name="EmitTransactionDone")
    bus.add_signal_receiver(handle_error,
                            dbus_interface="org.manjaro.pamac",
                            signal_name="EmitTransactionError")
    bus.add_signal_receiver(handle_updates,
                            dbus_interface="org.manjaro.pamac",
                            signal_name="EmitAvailableUpdates")
    bus.add_signal_receiver(reload_config,
                            dbus_interface="org.manjaro.pamac",
                            signal_name="EmitReloadConfig")


if common.pid_file_exists():
    transaction.ErrorDialog.format_secondary_text(
        _('Pamac is already running'))
    response = transaction.ErrorDialog.run()
    if response:
        transaction.ErrorDialog.hide()
else:
    common.write_pid_file()
    interface.connect_signals(signals)
    transaction.get_dbus_methods()
    transaction.config_dbus_signals()
    config_dbus_signals()
    UpdaterWindow.show()
    UpdaterWindow.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))
    while Gtk.events_pending():
        Gtk.main_iteration()
    transaction.refresh()
    Gtk.main()
Exemple #36
0
    def wait(self):
        """ Check if there are still processes running and
            waits for them to finish """
        must_wait = False
        for proc in self.process_list:
            if proc.is_alive():
                must_wait = True
                break

        if not must_wait:
            return

        txt1 = _("Ranking mirrors")
        txt1 = "<big>{0}</big>".format(txt1)

        txt2 = _("Cnchi is still updating and optimizing your mirror lists.")
        txt2 += "\n\n"
        txt2 += _("Please be patient...")
        txt2 = "<i>{0}</i>".format(txt2)

        wait_ui = Gtk.Builder()
        ui_file = os.path.join(self.ui_dir, "wait.ui")
        wait_ui.add_from_file(ui_file)

        lbl1 = wait_ui.get_object("label1")
        lbl1.set_markup(txt1)

        lbl2 = wait_ui.get_object("label2")
        lbl2.set_markup(txt2)

        progress_bar = wait_ui.get_object("progressbar")

        wait_window = wait_ui.get_object("wait_window")
        wait_window.set_modal(True)
        wait_window.set_transient_for(self.get_main_window())
        wait_window.set_default_size(320, 240)
        wait_window.set_position(Gtk.WindowPosition.CENTER)
        wait_window.show_all()

        ask_box = self.ui.get_object("ask")
        if ask_box:
            ask_box.set_sensitive(False)

        logging.debug("Waiting for all external processes to finish...")
        while must_wait:
            must_wait = False
            for proc in self.process_list:
                # This waits until process finishes, no matter the time.
                if proc.is_alive():
                    must_wait = True
            # Just wait...
            time.sleep(0.1)
            # Update our progressbar dialog
            progress_bar.pulse()
            while Gtk.events_pending():
                Gtk.main_iteration()
        logging.debug(
            "All external processes are finished. Installation can go on")
        wait_window.hide()

        if ask_box:
            ask_box.set_sensitive(True)
Exemple #37
0
    def make(self, gameDisplay):

        sound = True

        try:
            pygame.mixer.init()
        except Exception as 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()

        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 = int(sx(20))
        font1 = pygame.font.Font(font_path, font_size)
        font2 = pygame.font.Font("fonts/Arimo.ttf", int(sx(30)))
        font3 = pygame.font.Font("fonts/Arimo.ttf", int(sx(40)))
        font4 = pygame.font.Font("fonts/Arimo.ttf", int(sx(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
            mouse_button_up = False
            while Gtk.events_pending():
                Gtk.main_iteration()
            for event in pygame.event.get():
                # totaltime+=timer.tick()
                if event.type == pygame.QUIT:
                    crashed = True
                elif event.type == pygame.MOUSEBUTTONUP:
                    mouse_button_up = 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],
                                       (int(sx(491)), int(sy(768)))),
                (sx(350, True), 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, (sx(400, 1), sy(100)))

            gameDisplay.blit(button, (sx(550), sy(140)))

            gameDisplay.blit(hide, (sx(400, 1), sy(600)))
            gameDisplay.blit(pygame.transform.scale(play, (189, 70)),
                             (sx(500), sy(600)))

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

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

                if mouse_button_up:
                    press = 0

            # left and right black background patches

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

            pygame.draw.rect(gameDisplay, black,
                             (sx(839, 1), 0, sx(693), sy(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()
Exemple #38
0
 def set_cursor(self, cursor):
     self.canvas.get_property("window").set_cursor(cursord[cursor])
     Gtk.main_iteration()
Exemple #39
0
def gtk_refresh():
    """ Tell Gtk loop to run pending events """
    from gi.repository import Gtk

    while Gtk.events_pending():
        Gtk.main_iteration()
Exemple #40
0
 def _do(self):
     while Gtk.events_pending():
         Gtk.main_iteration()
     self.failUnless(self.expected is None)
 def runLoop(self):
     while Gtk.events_pending():
         Gtk.main_iteration()
Exemple #42
0
def refresh():
    while Gtk.events_pending():
        Gtk.main_iteration()
Exemple #43
0
 def close_window(self, *data):
     self.window.destroy()
     while gtk.events_pending():
         gtk.main_iteration()
     gtk.main_quit()
Exemple #44
0
    def run(self):
        g.init()
        if not self.journal: utils.load()
        load_save.retrieve()
        self.buttons_setup()
        self.slider=slider.Slider(g.sx(16),g.sy(20.5),9,utils.GREEN)
        self.grid=ah.Grid()
        self.grid.new1(); self.grid.setup()
        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.grid.click():
                            pass
                        elif self.slider.mouse():
                            self.grid.new1(); self.grid.setup(); buttons.clear() # level changed
                        else:
                            bu=buttons.check()
                            if bu!='': self.do_button(bu)
                            else: self.grid.colour_ind=0
                        self.flush_queue()
                    elif event.button==3:
                        self.do_button('reset')
                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 self.grid.complete():
                buttons.clear()
            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
            self.score=g.score; self.level=g.level
            g.clock.tick(40)
 def set_cursor(self, cursor):
     window = self.canvas.get_property("window")
     if window is not None:
         window.set_cursor(cursord[cursor])
         Gtk.main_iteration()
Exemple #46
0
    def __init__(self,
                 dbstate,
                 uistate,
                 track=[],
                 filter=None,
                 skip=set(),
                 show_search_bar=True,
                 default=None):
        """Set up the dialog with the dbstate and uistate, track of parent
            windows for ManagedWindow, initial filter for the model, skip with
            set of handles to skip in the view, and search_bar to show the
            SearchBar at the top or not.
        """
        self.filter = (2, filter, False)

        # Set window title, some selectors may set self.title in their __init__
        if not hasattr(self, 'title'):
            self.title = self.get_window_title()

        ManagedWindow.__init__(self, uistate, track, self)

        self.renderer = Gtk.CellRendererText()
        self.track_ref_for_deletion("renderer")
        self.renderer.set_property('ellipsize', Pango.EllipsizeMode.END)

        self.db = dbstate.db
        self.tree = None
        self.model = None

        self.glade = Glade()

        window = self.glade.toplevel
        self.showall = self.glade.get_object('showall')
        title_label = self.glade.get_object('title')
        vbox = self.glade.get_object('select_person_vbox')
        self.tree = self.glade.get_object('plist')
        self.tree.set_headers_visible(True)
        self.tree.set_headers_clickable(True)
        self.tree.connect('row-activated', self._on_row_activated)
        self.tree.grab_focus()

        # connect to signal for custom interactive-search
        self.searchbox = InteractiveSearchBox(self.tree)
        self.tree.connect('key-press-event', self.searchbox.treeview_keypress)

        #add the search bar
        self.search_bar = SearchBar(dbstate,
                                    uistate,
                                    self.build_tree,
                                    apply_clear=self.apply_clear)
        filter_box = self.search_bar.build()
        self.setup_filter()
        vbox.pack_start(filter_box, False, False, 0)
        vbox.reorder_child(filter_box, 1)

        self.set_window(window, title_label, self.title)

        #set up sorting
        self.sort_col = 0
        self.setupcols = True
        self.columns = []
        self.sortorder = Gtk.SortType.ASCENDING

        self.skip_list = skip
        self.selection = self.tree.get_selection()
        self.track_ref_for_deletion("selection")

        self._local_init()
        self._set_size()

        self.show()
        #show or hide search bar?
        self.set_show_search_bar(show_search_bar)
        #Hide showall if no filter is specified
        if self.filter[1] is not None:
            self.showall.connect('toggled', self.show_toggle)
            self.showall.show()
        else:
            self.showall.hide()
        while Gtk.events_pending():
            Gtk.main_iteration()
        self.build_tree()
        loading = self.glade.get_object('loading')
        loading.hide()

        if default:
            self.goto_handle(default)
Exemple #47
0
def _gtk_main_loop():
    from gi.repository import Gtk
    while True:
        while Gtk.events_pending():
            Gtk.main_iteration()
        gevent.sleep(0.1)
class pane6window:
    def run(self, gameDisplay, info):

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

        leftmove = leftdownmove = 350
        midmove = middownmove = 555
        rightmove = rightdownmove = 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/6up.png")
        background1 = pygame.image.load("data/images/6down.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 / 2))
        background1 = pygame.transform.scale(background1,
                                             (600, info.current_h / 2))

        y_axis1 = 700
        y_axis2 = 800

        y_axisa = 750
        y_axisb = 890

        y_axisx = 761
        y_axisy = 920

        leftquad = leftman
        midquad = leftman
        rightquad = leftman

        leftdown = middown = rightdown = leftman

        f1 = f2 = f3 = f4 = f5 = f6 = 0
        m1 = m2 = m3 = m4 = m5 = m6 = 0
        time1 = time2 = 0

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

        x_axis1 = x_axis2 = 350
        x_axisa = x_axisb = 659
        x_axisx = x_axisy = 761
        speed = 4
        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
            # print event

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

            # Keypress orientation change

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

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

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

            # down control

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

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

            if event.type == pygame.KEYDOWN and event.key == 275 and f6 == 0:
                jump.play(0)
                f6 = 1
                m6 = 1

            # 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
                rightquad = leftman
                m3 = f3 = 0
                rightmove = 761
                time2 = 0

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

            # Check for when to stop

            if leftdownmove > 484 + 20:  # left down move
                leftdown = rightman
                m4 = f4 = 0
                leftdownmove = 484 + 20
                time1 = 0

            if leftdownmove < 350:
                leftdown = leftman
                m4 = f4 = 0
                leftdownmove = 350
                time1 = 0

            if middownmove < 555:  # mid down move
                middown = leftman
                m5 = f5 = 0
                middownmove = 555
                time2 = 0

            if middownmove > 690 + 20:
                middown = rightman
                m5 = f5 = 0
                middownmove = 690 + 20
                time2 = 0

            if rightdownmove < 761:  # right down move
                rightdown = leftman
                m6 = f6 = 0
                rightdownmove = 761
                time2 = 0

            if rightdownmove > 761 + 156:
                rightdown = rightman
                m6 = f6 = 0
                rightdownmove = 761 + 156
                time2 = 0

            # Upper section

            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

            # lower section

            if m4 == 1:

                if leftdown == leftman:
                    leftdownmove += 30
                if leftdown == rightman:
                    leftdownmove -= 30
                time1 += 1

            if m5 == 1:

                if middown == leftman:
                    middownmove += 30
                if middown == rightman:
                    middownmove -= 30
                time2 += 1

            if m6 == 1:

                if rightdown == leftman:
                    rightdownmove += 30
                if rightdown == rightman:
                    rightdownmove -= 30
                time2 += 1

            #[350,608]   [659, 916]

            # upper Guy Display

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

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

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

            ######### UPPER 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))

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

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

            # right side spikes

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

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

            y_axis1 -= speed
            y_axis2 -= speed

            y_axisa -= speed
            y_axisb -= speed

            y_axisx -= speed
            y_axisy -= speed

            # Scores increment

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

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

                y_axis1 = 400

            if (y_axis2 < 380):
                orientation4 = randint(0, 1)

                y_axis2 = 700

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

                y_axisa = 400

            if (y_axisb < 380):
                orientation5 = randint(0, 1)

                y_axisb = 700

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

                y_axisx = 400

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

                y_axisy = 700

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

            gameDisplay.blit(background1, (0 + 350, 380))

            ######### LOWER SPIKE PART###########

            # left side spike

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

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

            # mid side spikes

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

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

            # right side spikes

            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))

            # lower guys display

            if leftdown == leftman or leftdown == rightman:
                gameDisplay.blit(leftdown, (leftdownmove, 400))

            if middown == leftman or middown == rightman:
                gameDisplay.blit(middown, (middownmove, 400))

            if rightdown == leftman or rightdown == rightman:
                gameDisplay.blit(rightdown, (rightdownmove, 400))

            # upper half detection

            if leftquad.get_rect(center=(leftmove + 5, 30 + 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, 30 + 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,
                                          30 + 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

            # lower section detection

            if leftdown.get_rect(center=(leftdownmove + 5,
                                         400 + 10)).collidepoint(
                                             x_axis2 + 8, y_axis2):
                # 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 middown.get_rect(center=(middownmove + 5,
                                        400 + 10)).collidepoint(
                                            x_axisb + 8, y_axisb):
                # 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 rightdown.get_rect(center=(rightdownmove + 5,
                                          400 + 10)).collidepoint(
                                              x_axisy + 8, y_axisy):
                # 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()
Exemple #49
0
 def render(self):
     while gtk.events_pending():
         gtk.main_iteration()
Exemple #50
0
 def run(self, id, activity=None):  #TODO Convert to use activity...
     logging.debug(">>")
     try:
         uri = "http://api.openstreetmap.org/api/0.6/gpx/create"  #URI for uploading traces to OSM
         if 'username' not in self.options or self.options[
                 'username'] == "" or 'password' not in self.options or self.options[
                     'password'] == "":
             logging.error("Must have username and password configured")
             raise Exception("Must have username and password configured")
         username = self.options['username']
         password = self.options['password']
         gpx_file = "%s/gpx/%s.gpx" % (self.conf_dir, id)
         if not os.path.isfile(gpx_file):
             raise Exception(str(gps_file) + ' File not found')
         #GPX file is ok and found, so open it
         logging.debug("GPX file: %s found, size: %d" %
                       (gpx_file, os.path.getsize(gpx_file)))
         f = open(gpx_file, 'r')
         file_contents = f.read()
         #TODO Fix to use etree functionality.....
         if file_contents.find(
                 "<?xml version='1.0' encoding='ASCII'?>") != -1:
             logging.debug(
                 "GPX file: %s has ASCII encoding - updating to UTF-8 for OSM support"
                 % gpx_file)
             f.close()  #Close readonly file
             f = open(gpx_file, 'w')  #and open file for writing
             file_contents = file_contents.replace(
                 "<?xml version='1.0' encoding='ASCII'?>",
                 "<?xml version='1.0' encoding='UTF-8'?>", 1)
             f.write(file_contents)  #Write new content
             f.close()  #Close
             f = open(gpx_file, 'r')  #Reopen in readonly mode
         #Get extra info from user
         response = self.display_options_window()
         if not response == Gtk.ResponseType.ACCEPT:
             f.close()
             logging.debug("User abort")
             return
         if self.makeanon:
             logging.debug("User requested anonymizing of GPX data")
             f.close()  #Close standard gpxfile
             gpx_file = self.make_gpx_private(gpx_file)
             f = open(gpx_file,
                      'r')  #Open anonymous gpxfile in readonly mode
         fields = (("description", self.description), ("tags", self.tags),
                   ("visibility", self.visibility))
         logging.debug("Added fields: %s" % str(fields))
         #Multipart encode the request
         boundary, body = self.multipart_encode(fields=fields,
                                                files=(("file", f), ))
         content_type = 'multipart/form-data; boundary=%s' % boundary
         #Finished with the file so close it
         f.close()
         #Add the http headers to the request
         h = httplib2.Http()
         headers = {'Content-Type': content_type}
         #Add basic authentication credentials to the request
         h.add_credentials(username, password)
         #Show user something is happening
         msg = _(
             "Posting GPX trace to Openstreetmap\n\nPlease wait this could take several minutes"
         )
         md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1,
                                Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                Gtk.MessageType.INFO, Gtk.ButtonsType.NONE,
                                msg)
         md.set_title(_("Openstreetmap Extension Processing"))
         md.set_modal(True)
         md.show()
         while Gtk.events_pending():  # This allows the GUI to update
             Gtk.main_iteration()  # before completion of this entire action
         logging.debug("before request posting")
         #POST request to OSM
         res, content = h.request(uri, 'POST', body=body, headers=headers)
         logging.debug("after request posting")
         logging.debug("Got response status: %s, reason: %s, content: %s" %
                       (res.status, res.reason, content))
         if res.reason == 'OK':
             res_msg = "Successfully posted to OSM.\nYou should get an email with the outcome of the upload soon\n\nTrace id is %s" % content
         else:
             res_msg = "Some error occured\nGot a status %s, reason %s\nContent was: %s" % (
                 res.status, res.reason, content)
         #Close 'Please wait' dialog
         md.destroy()
         #Show the user the result
         md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1,
                                Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                Gtk.MessageType.INFO, Gtk.ButtonsType.OK,
                                res_msg)
         md.set_title(_("Openstreetmap Extension Upload Complete"))
         md.set_modal(False)
         md.run()
         md.destroy()
     except Exception as e:
         msg = _("Error while uploading file to OSM: " + str(e))
         md = Gtk.MessageDialog(self.pytrainer_main.windowmain.window1,
                                Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                Gtk.MessageType.ERROR,
                                Gtk.ButtonsType.CLOSE, msg)
         md.set_title(_("Openstreetmap Extension Error"))
         md.run()
         md.destroy()
         return
     finally:
         logging.debug("<<")
    def run(self):
        black = (0, 0, 0)
        white = (255, 255, 255)
        clock = pygame.time.Clock()
        crashed = False
        # image load
        land = pygame.image.load("assets/land.png").convert()
        land1 = pygame.transform.scale(land, (490, 150))
        land2 = land1
        sky = pygame.image.load("assets/sky.png").convert()
        sky = pygame.transform.scale(sky, (490, 200))
        skyfill = pygame.image.load("assets/skyfill.png").convert()
        skyfill = pygame.transform.scale(skyfill, (490, 500))
        scoreboard = pygame.image.load("assets/scoreboard.png")
        scoreboard = pygame.transform.scale(scoreboard, (360, 450))
        land1x = 350
        land2x = 840
        replay = pygame.image.load("assets/replay.png")
        replay = pygame.transform.scale(replay, (150, 90))
        rules = pygame.image.load("assets/splash.png")
        font2 = pygame.font.Font("fonts/Arimo.ttf", 25)
        flag = 1
        birds = bird()
        button = pygame.image.load("assets/button.png")
        logo = pygame.image.load("assets/logo.png")
        logo = pygame.transform.scale(logo, (280, 80))

        # GAME LOOP BEGINS !!!
        while not crashed:
            # Gtk events
            while Gtk.events_pending():
                Gtk.main_iteration()
            for event in pygame.event.get():
                # totaltime+=timer.tick()
                if event.type == pygame.QUIT:
                    crashed = True
                if event.type == pygame.KEYDOWN and event.key == 273:
                    return

            mos_x, mos_y = pygame.mouse.get_pos()
            self.gameDisplay.fill(white)
            self.gameDisplay.blit(skyfill, (350, 0))
            self.gameDisplay.blit(sky, (350, 400))
            # Platform blit
            self.gameDisplay.blit(land1, (land1x, 600))
            self.gameDisplay.blit(land2, (land2x, 600))
            land1x -= 3
            land2x -= 3
            if(land1x <= -140):
                land1x = 837
            if(land2x <= -140):
                land2x = 837
            # bird display
            birds.display(self.gameDisplay, flag)
            self.gameDisplay.blit(rules, (500, 140))
            self.gameDisplay.blit(button, (700, 330))
            head3 = font2.render(_("Use this button ->"), 1, (white))
            self.gameDisplay.blit(head3, (480, 320))
            head3 = font2.render(_("to play the game"), 1, (white))
            self.gameDisplay.blit(head3, (480, 340))
            self.gameDisplay.blit(logo, (455, 30))
            # left and right black background patches
            pygame.draw.rect(self.gameDisplay, black, (0, 0, 350, 768))
            pygame.draw.rect(self.gameDisplay, black, (840, 0, 693, 768))
            pygame.display.update()
            clock.tick(60)

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

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

        if crashed:
            pygame.quit()
            sys.exit()
Exemple #52
0
    def show(self):
        Gtk.Window.show(self)

        # Give the dialog window a chance to display.
        while Gtk.events_pending():
           Gtk.main_iteration()
Exemple #53
0
 def refresh(self, force_update = False):
     while Gtk.events_pending():
         Gtk.main_iteration()
     while Gtk.events_pending():
         Gtk.main_iteration()
Exemple #54
0
 def update_progress_bar(clip):
     progress = progress_bar.get_fraction() + 1 / clip.nframes
     progress_bar.set_fraction(progress)
     while Gtk.events_pending():
         Gtk.main_iteration()
Exemple #55
0
 def flush_events(self):
     Gdk.threads_enter()
     while Gtk.events_pending():
         Gtk.main_iteration()
     Gdk.flush()
     Gdk.threads_leave()
Exemple #56
0
    def sort(self, mode, column=None):
        if self.connected():
            if not self.store:
                return

            while Gtk.events_pending():
                Gtk.main_iteration()
            songs = []
            track_num = 0

            if mode[0:3] == 'col':
                col_num = int(mode.replace('col', ''))
                if column.get_sort_indicator():
                    # If this column was already sorted, reverse list:
                    self.column_sorted = (column, self.column_sorted[1])
                    self.on_sort_reverse(None)
                    return
                else:
                    self.column_sorted = (column, Gtk.SortType.DESCENDING)
                mode = "col"

            # If the first tag in the format is song length, we will make
            # sure to compare the same number of items in the song length
            # string (e.g. always use ##:##:##) and pad the first item to two
            # (e.g. #:##:## -> ##:##:##)
            custom_sort = False
            if mode == 'col':
                custom_sort, custom_pos = self.sort_get_first_format_tag(
                    self.config.currentformat, col_num, 'L')

            for track in (item[0] for item in self.store):
                record = {}
                # Those items that don't have the specified tag will be put at
                # the end of the list (hence the 'zzzzzzz'):
                zzz = 'zzzzzzzz'
                if mode == 'artist':
                    record["sortby"] = (misc.lower_no_the(track.artist or zzz),
                                        (track.album or zzz).lower(),
                                        track.disc, track.track)
                elif mode == 'album':
                    record["sortby"] = ((track.album or zzz).lower(),
                                        track.disc, track.track)
                elif mode == 'file':
                    record["sortby"] = os.path.basename(track.file
                                                        or zzz).lower()
                elif mode == 'dirfile':
                    record["sortby"] = (track.file or zzz).lower()
                elif mode == 'col':
                    # Sort by column:
                    record["sortby"] = self.store.get_value(
                        self.store.get_iter((track_num, 0)), col_num).lower()
                    if custom_sort:
                        record["sortby"] = self.sanitize_songlen_for_sorting(
                            record["sortby"], custom_pos)
                else:
                    record["sortby"] = track.get(mode, zzz).lower()

                record["id"] = track.id
                songs.append(record)
                track_num = track_num + 1

            songs.sort(key=lambda x: x["sortby"])

            pos = 0
            self.mpd.command_list_ok_begin()
            for item in songs:
                self.mpd.moveid(item["id"], pos)
                pos += 1
            self.mpd.command_list_end()
            self.iterate_now()

            self.header_update_column_indicators()
Exemple #57
0
 def step(self):
     self.count += 1
     self._progress.set_fraction(common.clamp(self.count / float(self.total), 0, 1))
     self._label.set_markup(self.text % {'count': self.count, 'total': self.total})
     while Gtk.events_pending():
         Gtk.main_iteration()
 def _p(self):
     for i in range(20):
         time.sleep(0.1)
         while Gtk.events_pending():
             Gtk.main_iteration()
Exemple #59
0
def do_events():
    while Gtk.events_pending():
        Gtk.main_iteration()
Exemple #60
0
def doGtkEvents():
    '''

    '''
    while Gtk.events_pending():  # process Gtk events
        Gtk.main_iteration()