def _update_timeout(self): """Update the duration for self.timeout and self._seconds_timeout Sets the period of self.timeout to a value small enough to make the slider of self.progressScale move smoothly based on the current song duration and progressScale length. self._seconds_timeout is always set to a fixed value, short enough to hide irregularities in GLib event timing from the user, for updating the songPlaybackTimeLabel. """ # Don't run until progressScale has been realized if self.progressScale.get_realized() == False: return # Update self.timeout width = self.progressScale.get_allocated_width() padding = self.progressScale.get_style_context().get_padding( Gtk.StateFlags.NORMAL) width -= padding.left + padding.right duration = self.player.query_duration(Gst.Format.TIME)[1] / 10**9 timeout_period = min(1000 * duration // width, 1000) if self.timeout: GLib.source_remove(self.timeout) self.timeout = GLib.timeout_add( timeout_period, self._update_position_callback) # Update self._seconds_timeout if not self._seconds_timeout: self.seconds_period = 1000 self._seconds_timeout = GLib.timeout_add( self.seconds_period, self._update_seconds_callback)
def _check_lock_state(assistant, receiver, count=2): if not assistant.is_drawable(): if _log.isEnabledFor(_DEBUG): _log.debug("assistant %s destroyed, bailing out", assistant) return False if receiver.status.get(_K.ERROR): # receiver.status.new_device = _fake_device(receiver) _pairing_failed(assistant, receiver, receiver.status.pop(_K.ERROR)) return False if receiver.status.new_device: device, receiver.status.new_device = receiver.status.new_device, None _pairing_succeeded(assistant, receiver, device) return False if not receiver.status.lock_open: if count > 0: # the actual device notification may arrive after the lock was paired, # so have a little patience GLib.timeout_add(_STATUS_CHECK, _check_lock_state, assistant, receiver, count - 1) else: _pairing_failed(assistant, receiver, "failed to open pairing lock") return False return True
def on_motor_position_change(self, motor: Optional[Motor], pos: Optional[float]): if motor is None or pos is None: logger.debug('Faked motor position changed signal caught by ShutterFrame.') else: logger.debug( 'Motor position changed signal caught by ShutterFrame. Motor: {}. Position: {}'.format(motor.name, pos)) try: logger.debug('Stored motor position is {}'.format(motor.where())) except KeyError: logger.debug('Stored motor position not yet available.') try: if motor is not None: beamstopstate = self.instrument.get_beamstop_state(**{motor.name: pos}) else: beamstopstate = self.instrument.get_beamstop_state() logger.debug('beamstopstate: {}'.format(beamstopstate)) except KeyError: # can happen at program initialization, when the motor position has not yet been read. logger.debug('No beamstop state yet.') GLib.timeout_add(1000, lambda m=motor, p=pos: self.on_motor_position_change(m, p)) return False if beamstopstate == 'in': self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-in', Gtk.IconSize.BUTTON) self.builder.get_object('beamstop_in_button').set_sensitive(False) self.builder.get_object('beamstop_out_button').set_sensitive(True) elif beamstopstate == 'out': self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-out', Gtk.IconSize.BUTTON) self.builder.get_object('beamstop_in_button').set_sensitive(True) self.builder.get_object('beamstop_out_button').set_sensitive(False) else: self.builder.get_object('beamstopstate_image').set_from_icon_name('beamstop-inconsistent', Gtk.IconSize.BUTTON) self.builder.get_object('beamstop_in_button').set_sensitive(True) self.builder.get_object('beamstop_out_button').set_sensitive(True) return False
def __init__(self): Gtk.Window.__init__(self) self.image = None GLib.timeout_add(50, self.save_image) self.connect("delete-event", self.on_quit) # Status self.status = Gst.State.NULL # Video Area self.video_area = Gtk.DrawingArea() # Disable Double Buffered self.video_area.set_double_buffered(False) # playbin self.player = Gst.parse_launch("tcpclientsrc host=" + sys.argv[1] +" port=5000 ! gdpdepay ! rtph264depay ! avdec_h264 ! videoconvert ! xvimagesink name=xv") bus = self.player.get_bus() bus.add_signal_watch() bus.enable_sync_message_emission() bus.connect("message", self.on_message) bus.connect("sync-message::element", self.on_sync_message) # DnD dnd_list = Gtk.TargetEntry.new("text/uri-list", 0, 0) # pack vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0) vbox.pack_start(self.video_area, True, True, 0) self.add(vbox) self.resize(640, 480) self.show_all() self.player.set_state(Gst.State.PLAYING)
def test_gtk_schedule_action_absolute(self): scheduler = GtkScheduler() gate = threading.Semaphore(0) starttime = default_now() endtime = None def action(scheduler, state): nonlocal endtime endtime = default_now() due = scheduler.now + timedelta(milliseconds=100) scheduler.schedule_absolute(due, action) def done(data): Gtk.main_quit() gate.release() return False GLib.timeout_add(200, done, None) Gtk.main() gate.acquire() assert endtime is not None diff = endtime - starttime assert diff > timedelta(milliseconds=80)
def close(self, *a): """ Closes revealer (with animation), removes it from parent and calls destroy() """ self.set_reveal_child(False) GLib.timeout_add(self.get_transition_duration() + 50, self._cb_destroy)
def enabled(self): if not self.running: wm = WatchManager() self.event_handler = LibraryEvent(app.library) # Choose event types to watch for # FIXME: watch for IN_CREATE or for some reason folder copies # are missed, --nickb FLAGS = ['IN_DELETE', 'IN_CLOSE_WRITE',# 'IN_MODIFY', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_CREATE'] mask = reduce(lambda x, s: x | EventsCodes.ALL_FLAGS[s], FLAGS, 0) if self.USE_THREADS: print_d("Using threaded notifier") self.notifier = ThreadedNotifier(wm, self.event_handler) # Daemonize to ensure thread dies on exit self.notifier.daemon = True self.notifier.start() else: self.notifier = Notifier(wm, self.event_handler, timeout=100) GLib.timeout_add(1000, self.unthreaded_callback) for path in get_scan_dirs(): print_d('Watching directory %s for %s' % (path, FLAGS)) # See https://github.com/seb-m/pyinotify/wiki/ # Frequently-Asked-Questions wm.add_watch(path, mask, rec=True, auto_add=True) self.running = True
def run_dbus_service(self, timeout=None, send_usr1=False): '''Run D-BUS server. If no timeout is given, the server will run forever, otherwise it will return after the specified number of seconds. If send_usr1 is True, this will send a SIGUSR1 to the parent process once the server is ready to take requests. ''' dbus.service.Object.__init__(self, self.bus, '/DeviceDriver') self.main_loop = GLib.MainLoop() self._timeout = False if timeout: def _t(): self.main_loop.quit() return True GLib.timeout_add(timeout * 1000, _t) # send parent process a signal that we are ready now if send_usr1: os.kill(os.getppid(), signal.SIGUSR1) # run until we time out while not self._timeout: if timeout: self._timeout = True self.main_loop.run()
def execute(self, file_path): # ask for interpreter diag = InterpretersDialog(PYTHON_RUNTIMES) pythexec = diag.run() if not pythexec: return # poll messages from queue self.setDebugging(True) GLib.timeout_add(100, self._check_messages) self._debugger = CallbackFrontend(breakpoints=self._breakpoints) self._debugger.init(cont=True) cdir, filen = os.path.split(file_path) if not cdir: cdir = "." cwd = os.getcwd() try: os.chdir(cdir) cmd = pythexec + " -u " + QDB_LAUNCHER_PATH + ' ' + file_path print("Executing: ", cmd) proc = subprocess.Popen([cmd], shell=True, close_fds=True) retries = 0 self._attach() except Exception as e: self.setDebugging(False) raise finally: os.chdir(cwd)
def do_show(self): """ Init signals, set color and go party mode if nothing is playing """ self._signal1_id = Lp().player.connect('current-changed', self.on_current_changed) self._signal2_id = Lp().player.connect('status-changed', self.on_status_changed) if Lp().player.current_track.id is None: Lp().player.set_party(True) else: self.on_status_changed(Lp().player) self.on_current_changed(Lp().player) if self._timeout1 is None: self._timeout1 = GLib.timeout_add(1000, self._update_position) Gtk.Window.do_show(self) now = datetime.now() self._datetime.set_label(now.strftime('%a %d %b, %X')[:-3]) if self._timeout2 is None: second = datetime.now().second if 60 - second > 0: GLib.timeout_add((60-second)*1000, self._update_datetime) else: self._timeout2 = GLib.timeout_add(60000, self._update_datetime) self._update_position() self.fullscreen() self._next_popover.set_relative_to(self._album_label) if Lp().player.next_track.id != Type.RADIOS: self._next_popover.show()
def preview(self, page, position, doc, temp=False): """ Preview from `position` with a video player. Use ``True`` for `temp` to always use a temporary file for preview regardless of whether the file is changed or not. """ command = gaupol.util.get_preview_command() offset = gaupol.conf.preview.offset encoding = ("utf_8" if gaupol.conf.preview.force_utf_8 else None) try: out = page.project.preview(position, doc, command, offset, encoding, temp) process, command, fout = out except aeidon.ProcessError as error: return self._show_process_error_dialog(str(error)) except (IOError, OSError) as error: return self._show_io_error_dialog(str(error)) except UnicodeError: return self._show_encoding_error_dialog() # GLib.child_watch_add does not appear to work on Windows, # so let's watch the process by polling it at regular intervals. GLib.timeout_add(1000, self._check_process_state, page, process, fout, command)
def set_archivo(self, archivo): # Setea el archivo cuyo codigo debe mostrarse. self.new_handle(False) if archivo: archivo = os.path.realpath(archivo) if os.path.exists(archivo): self.archivo = archivo texto_file = open(self.archivo, 'r') texto = texto_file.read() texto = self.__limpiar_codigo(texto) texto_file.close() self.set_buffer(GtkSource.Buffer()) self.get_buffer().begin_not_undoable_action() self.lenguaje = self.lenguaje_manager.guess_language( self.archivo, "text") self.get_buffer().set_highlight_syntax(True) self.get_buffer().set_language(self.lenguaje) GLib.timeout_add(3, self.__force_emit_new_select) self.get_buffer().set_text(texto) self.control = os.path.getmtime(self.archivo) else: self.set_buffer(GtkSource.Buffer()) self.get_buffer().begin_not_undoable_action() self.get_buffer().end_not_undoable_action() self.get_buffer().set_modified(False) # Necesario cuando se guarda cambiando el nombre del archivo. self.emit("update-label", self.archivo) self.new_handle(True)
def __init__(self, parent, service, ok_cb, err_cb): self.parent = parent self.ok_cb = ok_cb self.err_cb = err_cb self.device = None self.connection = None parent.bus.add_signal_receiver(self.on_nm_device_added, "DeviceAdded", "org.freedesktop.NetworkManager") parent.bus.add_signal_receiver(self.on_nma_new_connection, "NewConnection", self.parent.settings_interface) self.device = self.parent.find_device(service.device['Address']) self.connection = self.parent.find_connection(service.device['Address'], "panu") if not self.connection: # This is for compatibility with network-manager < 0.9.8.6. Newer versions that support BlueZ 5 add a # default connection automatically addr_bytes = bytearray.fromhex(str.replace(str(service.device['Address']), ':', ' ')) parent.nma.AddConnection({ 'connection': {'id': '%s on %s' % (service.name, service.device['Alias']), 'uuid': str(uuid1()), 'autoconnect': False, 'type': 'bluetooth'}, 'bluetooth': {'bdaddr': dbus.ByteArray(addr_bytes), 'type': 'panu'}, 'ipv4': {'method': 'auto'}, 'ipv6': {'method': 'auto'} }) GLib.timeout_add(1000, self.signal_wait_timeout) else: self.init_connection()
def _on_map_duck(self, widget): """ Load on map @param widget as Gtk.Viewport """ self._on_child_unmap(widget) self.__jump_button.hide() if self.__current_track.id is None: self.__current_track = Lp().player.current_track Lp().settings.set_value('infoswitch', GLib.Variant('s', 'duck')) if self.__artist_ids: artists = [] for artist_id in self.__artist_ids: artists.append(Lp().artists.get_name(artist_id)) search = ", ".join(artists) else: title = self.__current_track.name artists = ", ".join(Lp().player.current_track.artists) search = "%s+%s" % (artists, title) url = "https://duckduckgo.com/?q=%s&kl=%s&kd=-1&k5=2&kp=1&k1=-1"\ % (search, Gtk.get_default_language().to_string()) # Delayed load due to WebKit memory loading and Gtk animation web = self.WebView(False, True) web.show() widget.add(web) GLib.timeout_add(250, web.load, url, OpenLink.NEW)
def on_login_clicked(self, *args): # Make the buttons UI while we work. self._okButton.set_sensitive(False) self._cancelButton.set_sensitive(False) self._loginButton.set_sensitive(False) self._loginConditionNotebook.set_current_page(0) self._set_login_sensitive(False) spinner = self.builder.get_object("loginSpinner") spinner.start() spinner.set_visible(True) spinner.show() # Are we reusing the credentials from the discovery step? If so, grab them # out of the UI again here. They should still be there. page = self._loginAuthNotebook.get_current_page() if page == 3: credentials = discoverMap[self._authNotebook.get_current_page()](self.builder) else: credentials = loginMap[page](self.builder) threadMgr.add(AnacondaThread(name=constants.THREAD_ISCSI_LOGIN, target=self._login, args=(credentials,))) GLib.timeout_add(250, self._check_login)
def _save_selected_subtitle (self): cursor = Gdk.Cursor.new (Gdk.CursorType.WATCH) self._dialog.get_window ().set_cursor (cursor) model, rows = self._tree_view.get_selection ().get_selected_rows () if rows: subtitle_iter = model.get_iter (rows[0]) subtitle_id = model.get_value (subtitle_iter, 3) subtitle_format = model.get_value (subtitle_iter, 1) bpath = self._cache_subtitles_dir() directory = Gio.file_new_for_path (bpath) try: directory.make_directory_with_parents (None); except: pass thread = DownloadThread (self._model, subtitle_id) thread.start () GLib.idle_add (self._save_subtitles, thread, subtitle_format) self._progress.set_text (_(u'Downloading the subtitles…')) GLib.timeout_add (350, self._progress_bar_increment, thread) else: #warn user! pass
def on_dialog_file_activated(dialog): new_dir = dialog.get_filename() dialog.destroy() self.dir_entry.set_text(new_dir) self.app.conf[self.conf_name] = new_dir GLib.timeout_add(500, self.move_items, new_dir) return
def test(): from gi.repository import GLib import random def timer(): grafico.add_valor(0, random.randint(0,100)) #~ grafico.add_valor(1, random.randint(20,30)) #~ grafico.add_valor(2, random.randint(70,90)) grafico.update() return True intervalo_muestreo = 1 duracion = 5 * 60 grafico = StripChart(900,150, tipo = 'puntos', font_face = 'Noto Sans', font_size=10) grafico.set_ejes(duracion, intervalo_muestreo, None, None, 2) grafico.add_serie(titulo='T. exterior (ºC)', color=Color.asulito) #~ grafico.add_serie('T. interior (ºC)', Color.morado) #~ grafico.add_serie('H. exterior (ºC)', Color.naranja) window = Gtk.Window() window.add(grafico) window.connect("destroy", Gtk.main_quit) window.show_all() GLib.timeout_add(intervalo_muestreo*1000,timer) timer() Gtk.main()
def _volume_down(self, playbin, plugins, duration): """ Make volume going down smoothly @param playbin as Gst.Bin @param plugins as PluginsPlayer @param duration as int """ # We are again the active playbin, stop all if self._playbin == playbin: return if duration > 0: vol = plugins.volume.props.volume steps = duration / 0.25 vol_down = vol / steps rate = vol - vol_down if rate > 0: plugins.volume.props.volume = rate GLib.timeout_add(250, self._volume_down, playbin, plugins, duration - 0.25) else: plugins.volume.props.volume = 0.0 playbin.set_state(Gst.State.NULL) else: plugins.volume.props.volume = 0.0 playbin.set_state(Gst.State.NULL)
def startgtkloop(errors, argparser): """ We start the gtk loop and run the function to start up Gramps """ GLib.timeout_add(100, __startgramps, errors, argparser, priority=100) if os.path.exists(os.path.join(DATA_DIR, "gramps.accel")): Gtk.AccelMap.load(os.path.join(DATA_DIR, "gramps.accel")) Gtk.main()
def __start_action(): # Use Glib's timeout_add, since GPS.Timeout doesn't seem to be run # correctly when running python's Gtk.Dialog.run (for instance for the # coding standard editor). GLib.timeout_add(msecs, __on_timeout) action_fn() return False
def wait_until_match(self, pattern, timeout=0): """ Called by user. Make a promise to them that: I'll let you know when the pattern is matched/never matches and return the remaining output if the pattern matched. Matching is only attempted of the text output since the last call to wait_until_match. Promise made here will be resolved with either a string (the current output) or None (when the process has terminated. :param str|re.Pattern pattern: the regular expression to match on the output of `self`. :param int timeout: give up matching pattern after this many milliseconds, or wait for ever if 0. """ # process has already terminated, return nothing if self.finished: return None if isinstance(pattern, str): self.__current_pattern = re.compile(pattern, re.MULTILINE) else: self.__current_pattern = pattern p = self.__current_promise = Promise() # Can we resolve immediately ? self.__check_pattern_and_resolve() if self.__current_promise: # if user defines a timeout, set up to # close output check after that timeout if timeout > 0: GLib.timeout_add(timeout, self.__on_timeout) return p
def test_update_report(self, *args): '''Updating an existing report''' self.app.report_file = None def cont(*args): if self.app.tree_model.get_iter_first() is None: return True self.app.w('continue_button').clicked() return False # upload empty report id = self.app.crashdb.upload({}) self.assertEqual(id, 0) self.app.options.update_report = 0 self.app.options.package = 'bash' GLib.timeout_add(200, cont) self.app.run_update_report() # no new bug reported self.assertEqual(self.app.crashdb.latest_id(), 0) # bug was updated r = self.app.crashdb.download(0) self.assertTrue(r['Package'].startswith('bash ')) self.assertTrue('libc' in r['Dependencies']) self.assertTrue('DistroRelease' in r) # No URL in this mode self.assertEqual(self.app.open_url.call_count, 0)
def _load_track(self, track, sql=None): stop = False # Stop if needed if self.context.next == NextContext.STOP_TRACK: stop = True # Stop if album changed if self.context.next == NextContext.STOP_ALBUM and\ self.current_track.album_id != track.album_id: stop = True # Stop if aartist changed if self.context.next == NextContext.STOP_ARTIST and\ self.current_track.aartist_id != track.aartist_id: stop = True if stop: return False self.current_track = track if self.current_track.uri is not None: try: self._playbin.set_property('uri', self.current_track.uri) except Exception as e: # Gstreamer error, stop print("BinPlayer::_load_track(): ", e) self.stop() return False else: GLib.timeout_add(2000, self.next) return False return True
def on_start_clicked(self, *args): # First, update some widgets to not be usable while discovery happens. self._startButton.hide() self._cancelButton.set_sensitive(False) self._okButton.set_sensitive(False) self._conditionNotebook.set_current_page(1) self._set_configure_sensitive(False) self._initiatorEntry.set_sensitive(False) # Now get the node discovery credentials. credentials = discoverMap[self._authNotebook.get_current_page()](self.builder) discoveredLabelText = _("The following nodes were discovered using the iSCSI initiator "\ "<b>%(initiatorName)s</b> using the target IP address "\ "<b>%(targetAddress)s</b>. Please select which nodes you "\ "wish to log into:") % \ {"initiatorName": escape_markup(credentials.initiator), "targetAddress": escape_markup(credentials.targetIP)} discoveredLabel = self.builder.get_object("discoveredLabel") discoveredLabel.set_markup(discoveredLabelText) bind = self._bindCheckbox.get_active() spinner = self.builder.get_object("waitSpinner") spinner.start() threadMgr.add(AnacondaThread(name=constants.THREAD_ISCSI_DISCOVER, target=self._discover, args=(credentials, bind))) GLib.timeout_add(250, self._check_discover)
def __run(self, dialog): # cargar proyecto archivo = os.path.join(self.proyecto_path, "proyecto.ide") arch = open(archivo, "r") self.proyecto = json.load(arch, "utf-8") arch.close() # crear estructura path = os.path.join(CONFPATH, self.proyecto["nombre"]) if os.path.exists(path): shutil.rmtree(path) # copiar proyecto commands.getoutput('cp -r \"%s\" \"%s\"' % ( self.proyecto_path, CONFPATH)) self.proyecto_path = path archivo = open(os.path.join(BASEPATH, "installmodel.txt")) texto = u"%s" % archivo.read() archivo.close() texto = texto.replace('mainfile', self.proyecto["main"]) texto = texto.replace('GnomeCat', self.proyecto["categoria"]) texto = texto.replace('GnomeMimeTypes', self.proyecto["mimetypes"]) page = ScrollPage(os.path.join( self.proyecto_path, "install.py"), "python", texto) self.append_page(page, Gtk.Label("Instalador")) self.set_tab_reorderable(page, True) page.source.guardar() self.show_all() GLib.timeout_add(30, self.__hide)
def test_io_add_watch_pyfile(self): call_data = [] cmd = subprocess.Popen('sleep 0.1; echo hello; sleep 0.2; echo world', shell=True, stdout=subprocess.PIPE) def cb(file, condition): call_data.append((file, condition, file.readline())) if len(call_data) == 2: # avoid having to wait for the full timeout ml.quit() return True # io_add_watch() takes an IOChannel, calling with a Python file is deprecated with warnings.catch_warnings(record=True) as warn: warnings.simplefilter('always') GLib.io_add_watch(cmd.stdout, GLib.IOCondition.IN, cb) self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) ml = GLib.MainLoop() GLib.timeout_add(2000, ml.quit) ml.run() cmd.wait() self.assertEqual(call_data, [(cmd.stdout, GLib.IOCondition.IN, b'hello\n'), (cmd.stdout, GLib.IOCondition.IN, b'world\n')])
def _createmap(self, person): """ Create all markers for each family's person in the database which has a lat/lon. """ dbstate = self.dbstate self.cal = config.get('preferences.calendar-format-report') self.place_list = [] self.person_list = [] self.count = dict() self.place_without_coordinates = [] self.minlat = self.maxlat = self.minlon = self.maxlon = 0.0 latitude = "" longitude = "" self.message_layer.clear_messages() self.place_without_coordinates = [] self.minlat = self.maxlat = self.minlon = self.maxlon = 0.0 if person is None: person = self.dbstate.db.get_person_from_handle(self.uistate.get_active('Person')) if not person: return self.message_layer.add_message(_("All descendance for %s") % _nd.display(person)) color = Gdk.color_parse(self._config.get('geography.color_base')) GLib.timeout_add(int(self._config.get("geography.generation_interval")), self.animate_moves, 0, person, color)
def load_external(self, files): # We wait as selection list is threaded, # we don't want to insert item before populated if self._list_one_restore is None: start_new_thread(self._scanner.add, (files,)) else: GLib.timeout_add(250, self.load_external, files)
def modal_dialog(action_fn, msecs=300): """ This primitive executes a blocking function in the context of a workflow. This should rarely be used, but is sometimes needed for some modal dialogs that block GPS without executing the python script. Example: yield modal_dialog( 300, lambda: GPS.execute_action('open project properties')) """ p = Promise() def __on_timeout(): p.resolve() return False def __start_action(): # Use Glib's timeout_add, since GPS.Timeout doesn't seem to be run # correctly when running python's Gtk.Dialog.run (for instance for the # coding standard editor). GLib.timeout_add(msecs, __on_timeout) action_fn() return False # Since action is blocking, and we want modal_dialog to return the # promise, we need to start the action in a timeout. GLib.timeout_add(10, __start_action) return p
def menuChanged(self, *a): if self.timer: GLib.Source.remove(self.timer) self.timer = None self.timer = GLib.timeout_add(3, self.loadUpdates)
def enable_periodic_scroll(): self.__scroll_periodic = GLib.timeout_add(50, periodic_scroll) self.__scroll_delay = None
def _authloop(self, fname, fn, *args, **kwds): self._passes = 0 c = self._connection retry = False while True: try: if self._perform_authentication() == 0: break if c != self._connection: # We have reconnected. fn = getattr(self._connection, fname) c = self._connection cups.setUser(self._use_user) result = fn.__call__(*args, **kwds) if fname == 'adminGetServerSettings': # Special case for a rubbish bit of API. if result == {}: # Authentication failed, but we aren't told that. raise cups.IPPError(cups.IPP_NOT_AUTHORIZED, '') break except cups.IPPError as e: (e, m) = e.args if self._use_pk and m == 'pkcancel': raise cups.IPPError(0, _("Operation canceled")) if not self._cancel and (e == cups.IPP_NOT_AUTHORIZED or e == cups.IPP_FORBIDDEN or e == cups.IPP_AUTHENTICATION_CANCELED): self._failed(e == cups.IPP_FORBIDDEN) elif not self._cancel and e == cups.IPP_SERVICE_UNAVAILABLE: debugprint("Got IPP_SERVICE_UNAVAILABLE") debugprint(m) if self._lock: self._gui_event.clear() GLib.timeout_add(1, self._ask_retry_server_error, m) self._gui_event.wait() else: self._ask_retry_server_error(m) if self._retry_response == Gtk.ResponseType.OK: debugprint("retrying operation...") retry = True self._passes -= 1 self._has_failed = True else: self._cancel = True raise else: if self._cancel and not self._cannot_auth: raise cups.IPPError(0, _("Operation canceled")) debugprint("%s: %s" % (e, repr(m))) raise except cups.HTTPError as e: (s, ) = e.args if not self._cancel: self._failed(s == cups.HTTP_FORBIDDEN) else: raise return result
def message(self, msg, timeout=1500): self.stop() self.set_label(msg) self.set_cancellable(False) GLib.timeout_add(timeout, self.finalize)
scrolledWindow.add(webview) window = Gtk.Window() if (sys.argv[3] == "false"): window.set_decorated(False) window.set_default_size(int(sys.argv[1]), int(sys.argv[2])) window.set_title(sys.argv[4]) window.set_icon_from_file(sys.argv[6]) window.add(scrolledWindow) window.show_all() def quit(args): Gtk.main_quit() window.connect("destroy", quit) def checkClose(): theFile = open("output.json", "r") theFileParsed = json.load(theFile) if (theFileParsed['close'] == sys.argv[4]): Gtk.main_quit() GLib.timeout_add(100, checkClose) Gtk.main()
def __init__(self, main_class, contact_id=0): #Connection.__init__(self) Gtk.Builder.__init__(self) self.add_from_file(UI_FILE) self.connect_signals(self) self.main = main_class self.db = main_class.db self.cursor = self.db.cursor() self.contact_id = contact_id self.name_widget = self.get_object('entry1') self.ext_name_widget = self.get_object('entry2') self.address_widget = self.get_object('entry3') self.city_widget = self.get_object('entry4') self.state_widget = self.get_object('entry5') self.zip_code = self.get_object('entry6') self.phone_widget = self.get_object('entry7') self.fax_widget = self.get_object('entry8') self.email_widget = self.get_object('entry9') self.terms_store = self.get_object('terms_store') self.markup_percent_store = self.get_object('markup_percent_store') #self.tax_exempt_widget = self.get_object('checkbutton1') self.tax_exempt_number_widget = self.get_object('entry10') self.misc_widget = self.get_object('entry11') self.vendor_widget = self.get_object('checkbutton2') self.customer_widget = self.get_object('checkbutton3') self.employee_widget = self.get_object('checkbutton4') self.service_provider_widget = self.get_object('checkbutton1') self.custom1_widget = self.get_object("entry16") self.custom2_widget = self.get_object("entry26") self.custom3_widget = self.get_object("entry27") self.custom4_widget = self.get_object("entry28") self.note = self.get_object("textbuffer1") self.contact_store = self.get_object('contact_store') self.individual_contact_store = self.get_object( 'individual_contact_store') self.filtered_contact_store = self.get_object('filtered_contact_store') self.contact_filter_list = "" self.filtered_contact_store.set_visible_func(self.contact_filter_func) self.treeview = self.get_object('treeview1') self.populate_contacts() self.populate_terms_combo() self.populate_zip_codes() if self.contact_id == 0: self.new_contact(None) else: self.select_contact() if main.is_admin == True: self.get_object('treeview1').set_tooltip_column(0) self.initiate_mailing_info() self.window = self.get_object('window1') self.window.show_all() self.data_queue = Queue() self.scanner_store = self.get_object("scanner_store") thread = Process(target=self.get_scanners) thread.start() GLib.timeout_add(100, self.populate_scanners) self.set_window_layout_from_settings()
def open_project(new_project): stop_autosave() gui.editor_window.window.handler_block(window_resize_id) gui.editor_window.window.handler_block(window_state_id) audiomonitoring.close_audio_monitor() audiowaveformrenderer.clear_cache() audiowaveform.frames_cache = {} editorstate.project = new_project editorstate.media_view_filter = appconsts.SHOW_ALL_FILES editorstate.tline_render_mode = appconsts.TLINE_RENDERING_OFF # Inits widgets with project data init_project_gui() # Inits widgets with current sequence data init_sequence_gui() # Set and display current sequence tractor display_current_sequence() # Editor and modules need some more initializing init_editor_state() # For save time message on close projectaction.save_time = None # Delete autosave file after it has been loaded global loaded_autosave_file if loaded_autosave_file != None: print("Deleting", loaded_autosave_file) os.remove(loaded_autosave_file) loaded_autosave_file = None editorstate.update_current_proxy_paths() editorstate.fade_length = -1 editorstate.transition_length = -1 editorstate.clear_trim_clip_cache() audiomonitoring.init_for_project_load() tlinerender.init_session() start_autosave() if new_project.update_media_lengths_on_load == True: projectaction.update_media_lengths() gui.editor_window.set_default_edit_tool() editorstate.trim_mode_ripple = False updater.set_timeline_height() gui.editor_window.window.handler_unblock(window_resize_id) gui.editor_window.window.handler_unblock(window_state_id) global resize_timeout_id resize_timeout_id = GLib.timeout_add(500, _do_window_resized_update) projectaction.clear_changed_since_last_save_flags() # Set scrubbing editorstate.player.set_scrubbing(editorpersistance.prefs.audio_scrubbing)
def main(root_path): """ Called at application start. Initializes application with a default project. """ # DEBUG: Direct output to log file if log file set if _log_file != None: log_print_output_to_file() set_quiet_if_requested() print("Application version: " + editorstate.appversion) # Print OS, Python version and GTK+ version try: os_release_file = open("/etc/os-release", "r") os_text = os_release_file.read() s_index = os_text.find("PRETTY_NAME=") e_index = os_text.find("\n", s_index) print("OS: " + os_text[s_index + 13:e_index - 1]) except: pass print("Python", sys.version) gtk_version = "%s.%s.%s" % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) print("GTK+ version:", gtk_version) editorstate.gtk_version = gtk_version try: editorstate.mlt_version = mlt.LIBMLT_VERSION except: editorstate.mlt_version = "0.0.99" # magic string for "not found" # Create user folders if needed and determine if we're using xdg or dotfile user folders. userfolders.init() # Set paths. respaths.set_paths(root_path) # Load editor prefs and list of recent projects editorpersistance.load() if editorpersistance.prefs.theme != appconsts.LIGHT_THEME: respaths.apply_dark_theme() if editorpersistance.prefs.display_all_audio_levels == False: editorstate.display_all_audio_levels = False editorpersistance.save() # Init translations module with translations data translations.init_languages() translations.load_filters_translations() mlttransitions.init_module() # Apr-2017 - SvdB - Keyboard shortcuts shortcuts.load_shortcut_files() shortcuts.load_shortcuts() # Aug-2019 - SvdB - AS # The test for len != 4 is to make sure that if we change the number of values below the prefs are reset to the correct list # So when we add or remove a value, make sure we also change the len test # Only use positive numbers. if (not editorpersistance.prefs.AUTO_SAVE_OPTS or len(editorpersistance.prefs.AUTO_SAVE_OPTS) != 4): print("Initializing Auto Save Options") editorpersistance.prefs.AUTO_SAVE_OPTS = ((0, _("No Autosave")), (1, _("1 min")), (2, _("2 min")), (5, _("5 min"))) # We respaths and translations data available so we need to init in a function. workflow.init_data() # RHEL7/CentOS compatibility fix if gtk_version == "3.8.8": GObject.threads_init() # Init gtk threads Gdk.threads_init() Gdk.threads_enter() # Handle userfolders init error and quit. if userfolders.get_init_error() != None: _xdg_error_exit(userfolders.get_init_error()) return # After moving to Python 3 we need at least MLT 6.18 if editorstate.mlt_version_is_greater_correct("6.17.99") == False: _too_low_mlt_version_exit() return # Themes if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME: success = gui.apply_gtk_css() if not success: editorpersistance.prefs.theme = appconsts.LIGHT_THEME editorpersistance.save() if editorpersistance.prefs.theme != appconsts.LIGHT_THEME: Gtk.Settings.get_default().set_property( "gtk-application-prefer-dark-theme", True) # Load drag'n'drop images dnd.init() # Save screen size data and modify rendering based on screen size/s and number of monitors. scr_w, scr_h = _set_screen_size_data() _set_draw_params() # Refuse to run on too small screen. if scr_w < 1151 or scr_h < 767: _too_small_screen_exit() return # Splash screen if editorpersistance.prefs.display_splash_screen == True: show_splash_screen() # Init MLT framework repo = mlt.Factory().init() processutils.prepare_mlt_repo(repo) # Set numeric locale to use "." as radix, MLT initilizes this to OS locale and this causes bugs. locale.setlocale(locale.LC_NUMERIC, 'C') # Check for codecs and formats on the system. mltenv.check_available_features(repo) renderconsumer.load_render_profiles() # Load filter and compositor descriptions from xml files. mltfilters.load_filters_xml(mltenv.services) mlttransitions.load_compositors_xml(mltenv.transitions) # Replace some services if better replacements available. mltfilters.replace_services(mltenv.services) # Create list of available mlt profiles. mltprofiles.load_profile_list() # If we have crashed we could have large amount of disk space wasted unless we delete all files here. tlinerender.app_launch_clean_up() # Save assoc file path if found in arguments. global assoc_file_path assoc_file_path = get_assoc_file_path() # There is always a project open, so at startup we create a default project. # Set default project as the project being edited. editorstate.project = projectdata.get_default_project() check_crash = True # Audiomonitoring being available needs to be known before GUI creation. audiomonitoring.init(editorstate.project.profile) # Set trim view mode to current default value. editorstate.show_trim_view = editorpersistance.prefs.trim_view_default # Check for tools and init tools integration. gmic.test_availablity() toolsintegration.init() # Create player object. create_player() # Create main window and set widget handles in gui.py for more convenient reference. create_gui() # Inits widgets with project data. init_project_gui() # Inits widgets with current sequence data. init_sequence_gui() # Launch player now that data and gui exist launch_player() # Editor and modules need some more initializing. init_editor_state() # Tracks need to be recentered if window is resized. # Connect listener for this now that the tline panel size allocation is sure to be available. global window_resize_id, window_state_id window_resize_id = gui.editor_window.window.connect( "size-allocate", lambda w, e: updater.window_resized()) window_state_id = gui.editor_window.window.connect( "window-state-event", lambda w, e: updater.window_resized()) # Get existing autosave files autosave_files = get_autosave_files() # Show splash if ((editorpersistance.prefs.display_splash_screen == True) and len(autosave_files) == 0 ) and not editorstate.runtime_version_greater_then_test_version( editorpersistance.prefs.workflow_dialog_last_version_shown, editorstate.appversion): global splash_timeout_id splash_timeout_id = GLib.timeout_add(2600, destroy_splash_screen) splash_screen.show_all() appconsts.SAVEFILE_VERSION = projectdata.SAVEFILE_VERSION # THIS IS A QUESTIONABLE IDEA TO SIMPLIFY IMPORTS, NOT DRY. WHEN DOING TOOLS THAT RUN IN ANOTHER PROCESSES AND SAVE PROJECTS, THIS LINE NEEDS TO BE THERE ALSO. # Every running instance has unique autosave file which is deleted at exit set_instance_autosave_id() # Existance of autosave file hints that program was exited abnormally. if check_crash == True and len(autosave_files) > 0: if len(autosave_files) == 1: GObject.timeout_add(10, autosave_recovery_dialog) else: GObject.timeout_add(10, autosaves_many_recovery_dialog) else: tlinerender.init_session() start_autosave() projectaction.clear_changed_since_last_save_flags() # We prefer to monkeypatch some callbacks into some modules, usually to # maintain a simpler and/or non-circular import structure. monkeypatch_callbacks() # File in assoc_file_path is opened after very short delay. if not (check_crash == True and len(autosave_files) > 0): if assoc_file_path != None: print("Launch assoc file:", assoc_file_path) global assoc_timeout_id assoc_timeout_id = GObject.timeout_add(10, open_assoc_file) if editorpersistance.prefs.theme == appconsts.FLOWBLADE_THEME: gui.apply_flowblade_theme_fixes() # SDL 2 consumer needs to created after Gtk.main() has run enough for window to be visble #if editorstate.get_sdl_version() == editorstate.SDL_2: # needs more state considerion still # print "SDL2 timeout launch" # global sdl2_timeout_id # sdl2_timeout_id = GObject.timeout_add(1500, create_sdl_2_consumer) # In PositionNumericalEntries we are using Gtk.Entry objects in a way that works for us nicely, but is somehow "error" for Gtk, so we just kill this. Gtk.Settings.get_default().set_property("gtk-error-bell", False) # Show first run worflow info dialog if not shown for this version of application. if editorstate.runtime_version_greater_then_test_version( editorpersistance.prefs.workflow_dialog_last_version_shown, editorstate.appversion): GObject.timeout_add(500, show_worflow_info_dialog) # Copy to XDG. if userfolders.data_copy_needed(): GObject.timeout_add(500, show_user_folders_copy_dialog) else: print("No user folders actions needed.") global disk_cache_timeout_id disk_cache_timeout_id = GObject.timeout_add(2500, check_disk_cache_size) # Launch gtk+ main loop Gtk.main() Gdk.threads_leave()
def remove_packages(self): GLib.timeout_add(self._timeout, self._do_remove_packages) self.loop.run()
def system_upgrade(self): GLib.timeout_add(self._timeout, self._do_system_upgrade) self.loop.run()
def refresh(self): GLib.timeout_add(self._timeout, self._do_refresh) self.loop.run()
def install_packages(self): if self.refresh_before_install: GLib.timeout_add(self._timeout, self._do_refresh) else: GLib.timeout_add(self._timeout, self._do_install_packages) self.loop.run()
def _perform_authentication(self): self._passes += 1 creds = global_authinfocache.lookup_auth_info(host=self._server, port=self._port) if creds != None: if (creds[0] != 'root' or self._try_as_root): (self._use_user, self._use_password) = creds del creds debugprint("Authentication pass: %d" % self._passes) if self._passes == 1: # Haven't yet tried the operation. Set the password # callback and return > 0 so we try it for the first time. self._has_failed = False self._forbidden = False self._auth_called = False self._cancel = False self._cannot_auth = False self._dialog_shown = False cups.setPasswordCB(self._password_callback) debugprint("Authentication: password callback set") return 1 debugprint("Forbidden: %s" % self._forbidden) if not self._has_failed: # Tried the operation and it worked. Return 0 to signal to # break out of the loop. debugprint("Authentication: Operation successful") return 0 # Reset failure flag. self._has_failed = False if self._passes >= 2: # Tried the operation without a password and it failed. if (self._try_as_root and self._user != 'root' and (self._server[0] == '/' or self._forbidden)): # This is a UNIX domain socket connection so we should # not have needed a password (or it is not a UDS but # we got an HTTP_FORBIDDEN response), and so the # operation must not be something that the current # user is authorised to do. They need to try as root, # and supply the password. However, to get the right # prompt, we need to try as root but with no password # first. debugprint("Authentication: Try as root") self._use_user = '******' self._auth_called = False try: self._connect(allow_pk=False) except RuntimeError: raise cups.IPPError(cups.IPP_SERVICE_UNAVAILABLE, 'server-error-service-unavailable') return 1 if not self._prompt_allowed: debugprint("Authentication: prompting not allowed") self._cancel = True return 1 if not self._auth_called: # We aren't even getting a chance to supply credentials. debugprint("Authentication: giving up") self._cancel = True self._cannot_auth = True return 1 # Reset the flag indicating whether we were given an auth callback. self._auth_called = False # If we're previously prompted, explain why we're prompting again. if self._dialog_shown: if self._lock: self._gui_event.clear() GLib.timeout_add(1, self._show_not_authorized_dialog) self._gui_event.wait() else: self._show_not_authorized_dialog() if self._lock: self._gui_event.clear() GLib.timeout_add(1, self._perform_authentication_with_dialog) self._gui_event.wait() else: self._perform_authentication_with_dialog() if self._cancel: debugprint("cancelled") return -1 cups.setUser(self._use_user) debugprint("Authentication: Reconnect") try: self._connect(allow_pk=False) except RuntimeError: raise cups.IPPError(cups.IPP_SERVICE_UNAVAILABLE, 'server-error-service-unavailable') return 1
def stopwatch(self, time, alert_callback): if self.stopwatch_running: GLib.source_remove(self.stopwatch_timer) time = self.time_interval self.stopwatch_timer = GLib.timeout_add(time * 1000, alert_callback) self.stopwatch_running = True
def threadmouse(self,widget,event): #print 'sub thread id : ', thread.get_ident() global MouseLocation if MouseLocation: GLib.timeout_add(100, self.ThreadMouse)
def scroll_to_bottom_messages(self): GLib.timeout_add( 50, lambda: self.messages_adjustment.set_value( self.messages_adjustment.get_upper() ) )
def run(self): self.timeout_id = GLib.timeout_add(750, self.update)
def on_close_button_clicked(self, button): try: self.tree.get_object('mainwindow').hide() except: pass GLib.timeout_add(10, self.quit)
def schedule_timer(self): if not self.populate_timer: self.populate_table() self.populate_timer = GLib.timeout_add(1000, self.populate_table)
def run(self): self.xbacklight_max_brightness = self.read_max_brightness() self.timeout_id = GLib.timeout_add(10 * 1000, self.on_timeout) if self.model in NEEDS_BRIGHTNESS_ACPI: self.timeout_id = GLib.timeout_add(100, self.update_xbacklight)
def play(self): self.is_playing = True self.player.set_state(Gst.State.PLAYING) #starting up a timer to check on the current playback value GLib.timeout_add(1000, self.update_slider)
def SetContext(self, context): self.Context = context GLib.timeout_add(2000, self.Update)
def _on_configure_event(self, widget, event): if self.window_size_update_timeout is None: self.window_size_update_timeout = GLib.timeout_add(500, self.store_window_size_and_position, widget)
def test_button_clicked(self, widget, event): if event.type == Gdk.EventType._2BUTTON_PRESS: widget.set_label(_("Success!")) GLib.timeout_add(1000, self.reset_test_button, widget) return True
def refresh(self): GUIObject.refresh(self) self._createBox() GLib.timeout_add(100, self._update_spokes)
def __init__(self, app): Gtk.ApplicationWindow.__init__(self, title=tca.config.APPLICATION_TITLE, application=app) self.app = app self.set_role(tca.config.APPLICATION_WM_CLASS) # XXX: set_wm_class is deprecated, but it's the only way I found to set taskbar title self.set_wmclass(tca.config.APPLICATION_WM_CLASS, tca.config.APPLICATION_WM_CLASS) self.set_title(tca.config.APPLICATION_TITLE) # self.state collects data from user interactions. Its main key is the step name self.state: Dict[str, Any] = { "hide": {}, "bridge": {}, "proxy": {}, "progress": {}, "step": "hide", "offline": {}, } if self.app.args.debug_statefile is not None: log.debug("loading statefile") with open(self.app.args.debug_statefile) as buf: content = json.load(buf) log.debug("content found %s", content) self.state.update(content) else: data = self.app.configurator.read_conf() if data and data.get("ui"): for key in ["hide", "bridge"]: self.state[key].update(data["ui"].get(key, {})) self.state["progress"]["started"] = (data["ui"].get( "progress", {}).get("started", False)) self.state["progress"]["success"] = self.app.is_tor_working if self.state["progress"]["success"]: self.state["step"] = "progress" self.current_language = "en" self.connect("delete-event", self.cb_window_delete_event, None) self.set_position(Gtk.WindowPosition.CENTER) # Load custom CSS css_provider = Gtk.CssProvider() css_provider.load_from_path( os.path.join(tca.config.data_path, CSS_FILE)) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) # Load UI interface definition self.builder = builder = Gtk.Builder() builder.set_translation_domain(self.get_translation_domain()) builder.add_from_file(tca.config.data_path + MAIN_UI_FILE) builder.connect_signals(self) self.main_container = builder.get_object( "box_main_container_image_step") self.stack = builder.get_object("box_main_container_stack") for step in self.STEPS_ORDER: box = builder.get_object("step_{}_box".format(step)) box.show() self.stack.add_named(box, step) self.connection_progress = ConnectionProgress(self) GLib.timeout_add(1000, self.connection_progress.tick) self.add(self.main_container) self.show() self.change_box(self.state["step"])
def run(self, counter): self.number = counter if self.show_window: self.window.show_all() self.timeoutId = GLib.timeout_add(1000 / FPS, self.onTimeout, self.window) self.starttime = time.time()
def refresh(self): ''' Run to periodically refresh the display ''' self.redraw() if not self.killed: GLib.timeout_add(int(REFRESH * 1000), self.refresh)
def start_widgets_updater(self): if self.widgets_updater > 0: GLib.source_remove(self.widgets_updater) self.update_widgets() self.widgets_updater = GLib.timeout_add(500, self.update_widgets)
def start_animation(self): """Start the animation""" if self.ticker == 0: self.ticker = GLib.timeout_add(200, self._advance)