def _add_path(paths): for path in paths: if path.is_dir(): _add_path(p for p in path.glob("**/*") if p.is_file()) elif path.is_file(): app.add_image(path) Gtk.main_iteration_do(True)
def killSubProcess(self): #print 'killSubProcess' # kill currently running subprocess, if any if os.name != 'nt': # linux # use python subprocess.kill try: if self.subProcess.poll() is None: self.subProcess.kill() except AttributeError: pass else: # windows # use system kill try: if self.subProcess.poll() is None: subprocess.call([ 'taskkill', '/F', '/T', '/PID', str(self.subProcess.pid) ]) except AttributeError: pass # force events processing while Gtk.events_pending(): Gtk.main_iteration_do(True)
def do_drawing(self, size, frame, cairo_ctx): ''' Update the backing store from a cairo context and schedule a redraw (expose event) :param size: width, height in pixels of bot :param frame: frame # thar was drawn :param cairo_ctx: cairo context the bot was drawn on ''' if self.get_window() and not self.bot_size: # Get initial size for window self.set_size_request(*size) self.bot_size = size self.backing_store = BackingStore.get_backingstore(self.width, self.height) cr = pycairo.Context(self.backing_store.surface) if self.scale_fit: self.scale_context_and_center(cr) cairo_ctx = driver.ensure_pycairo_context(cairo_ctx) cr.set_source_surface(cairo_ctx.get_target()) # Create the cairo context cr.set_operator(cairo.OPERATOR_SOURCE) cr.paint() self.queue_draw() while Gtk.events_pending(): Gtk.main_iteration_do(False)
def test_next_nosong_536(self): self.pl.go_to(1) self.pl.repeat = True self.pl.order = ORDERS[1](self.pl) self.pl.set([]) Gtk.main_iteration_do(False) self.pl.next()
def on_render_button_clicked(button): try: global piece_filepath global values_for_channels global csound_is_performing csound_is_performing = False csd_text = create_csd_text( "-+msg_color=0 -d -m195 -f -RWo" + output_soundfile_filepath, "", orc, sco) csound.stop() csound.cleanup() csound.reset() csound.compileCsdText(csd_text) csound.start() load_ui() log_print("Restoring {} channels...".format(len(values_for_channels))) for name, value in values_for_channels.items(): log_print("initialize channel: {} value {} {}".format( name, value, type(value))) if isinstance(value, str): csound.setStringChannel(name, value) else: csound.setControlChannel(name, value) csound_is_performing = True while csound.performBuffer() == 0: # Keep the UI responsive during performance. Gtk.main_iteration_do(False) csound.stop() csound.cleanup() csound.reset() post_process() except: print(traceback.format_exc())
def _pack_archive(self, archive_path): """Create a new archive with the chosen files.""" self.set_sensitive(False) self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) while Gtk.events_pending(): Gtk.main_iteration_do(False) image_files = self._image_area.get_file_listing() other_files = self._other_area.get_file_listing() try: tmp_path = tempfile.mkstemp( suffix='.%s' % os.path.basename(archive_path), prefix='tmp.', dir=os.path.dirname(archive_path))[1] fail = False except: fail = True if not fail: packer = archive.Packer(image_files, other_files, tmp_path, os.path.splitext(os.path.basename(archive_path))[0]) packer.pack() packing_success = packer.wait() if packing_success: os.rename(tmp_path, archive_path) _close_dialog() else: fail = True if fail: self.get_window().set_cursor(None) dialog = Gtk.MessageDialog(self._window, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, _("The new archive could not be saved!")) dialog.format_secondary_text( _("The original files have not been removed.")) dialog.run() dialog.destroy() self.set_sensitive(True)
def timer(self): try: if self.counting: if self.counter == 0: self.display = True for each in range(0,10): if self.counting: self.window.set_opacity(float("0."+str(each))) while gtk.events_pending(): gtk.main_iteration_do(True) self.window.show_all() self.window.move(100,150) self.icon.set_visible(not self.image_hide) self.speak(self.speech) if self.counter == 5: if self.window.get_opacity() != 0.0: for each in range(9,-1,-1): self.window.set_opacity(float("0."+str(each))) while gtk.events_pending(): gtk.main_iteration_do(True) time.sleep(0.02) self.window.hide() self.display = False self.counting = False self.counter += 1 elif len(self.queue) > 0 and self.display == False: data = self.queue[0] try: self.message.set_text("")
def gtk_iteration(task): """ Handles the gtk events and lets as many GUI iterations run as needed. """ while Gtk.events_pending(): Gtk.main_iteration_do(False) return task.cont
def setUp(self): self.mod = self.modules["mpd_server"] config.init() init_fake_app() MPDServerPlugin = self.mod.MPDServerPlugin MPDConnection = self.mod.main.MPDConnection MPDService = self.mod.main.MPDService class Server(object): service = MPDService(app, MPDServerPlugin()) def _remove_connection(self, conn): pass server = Server() s, c = socket.socketpair() self.s = s c.setblocking(False) s.settimeout(1) self.conn = MPDConnection(server, c) self.conn.handle_init(server) while Gtk.events_pending(): Gtk.main_iteration_do(True) self.s.recv(9999)
def rotate(self, widget, clockwise): """Rotate children in this window""" self.set_pos_by_ratio = True maker = Factory() # collect all paned children in breadth-first order paned = [] child = self.get_child() # If our child is a Notebook, reset to work from its visible child if maker.isinstance(child, 'Notebook'): pagenum = child.get_current_page() child = child.get_nth_page(pagenum) if maker.isinstance(child, 'Paned'): paned.append(child) for p in paned: for child in p.get_children(): if child not in paned and maker.isinstance(child, 'Paned'): paned.append(child) # then propagate the rotation for p in paned: p.rotate(widget, clockwise) self.show_all() while Gtk.events_pending(): Gtk.main_iteration_do(False) widget.grab_focus() self.set_pos_by_ratio = False
def menu_activate_cb(self, menu, files): #List the valid files videos = [f for f in files if not f.is_gone() and self.is_valid(f)] # Get the file paths from gvfs so we support non local file systems, yay! g = Gio.Vfs.get_default() videos = map(lambda f: g.get_file_for_uri(f.get_uri()).get_path(), videos) # Download the subtitles in a new process and get the results in this process via a Queue queue = Queue() invoker = PeriscopeInvoker(videos, self.cache_folder, queue) invoker.start() result = [] while not result: try: result = queue.get_nowait() except Empty: pass finally: Gtk.main_iteration_do( False ) # a blocking version with timeout would have been nice sleep(0.01) [found, notfound] = result self.notify(found, notfound) invoker.join()
def __expanded(self, iter, path, model): window = self.get_window() if window: window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH)) Gtk.main_iteration_do(False) try: try: if model is None: return while model.iter_has_child(iter): model.remove(model.iter_children(iter)) folder = model[iter][0] for path in listdir(folder): try: if not os.path.isdir(path): continue for filename in listdir(path): if os.path.isdir(filename): niter = model.append(iter, [path]) model.append(niter, ["dummy"]) break else: model.append(iter, [path]) except OSError: pass if not model.iter_has_child(iter): return True except OSError: pass finally: if window: window.set_cursor(None)
def test_go_to_saves_current(self): self.pl.go_to(5) self.failUnlessEqual(self.pl.current, 5) self.pl.set([5, 10, 15, 20]) Gtk.main_iteration_do(False) self.pl.next() self.failUnlessEqual(self.pl.current, 10)
def __init__(self): filename = "../Setup/templates/popup.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.title = self.builder.get_object("lblTitle") self.message = self.builder.get_object("lblMessage") self.titleBox = self.builder.get_object("labelbox") self.titleBox.connect("button-release-event", self.on_clicked) self.exit = self.builder.get_object("exitbox") self.exit.connect("button-release-event", self.close_notify) self.icon = self.builder.get_object("imgIcon") self.window.set_gravity(gdk.Gravity.NORTH_WEST) self.display = False self.window.set_keep_above(True) self.counter = 0 self.counter2 = 0 self.counting = False self.queue = [] self.info = lispeak.getInfo() gobject.timeout_add_seconds(1, self.timer) try: gobject.timeout_add_seconds(0.2, self.display_notify) except: print "Reverting to 1 second check" gobject.timeout_add_seconds(1, self.display_notify) gobject.timeout_add_seconds(30, self.message_system) while gtk.events_pending(): gtk.main_iteration_do(True) self.message_system()
def _wait(self, msg=""): start = time.time() while not self._replies: Gtk.main_iteration_do(False) if time.time() - start > MAX_TIME: self.fail("Timed out waiting for replies (%s)" % msg) return self._replies.pop(0)
def do_drawing(self, size, frame, cairo_ctx): """ Update the backing store from a cairo context and schedule a redraw (expose event) :param size: width, height in pixels of bot :param frame: frame # thar was drawn :param cairo_ctx: cairo context the bot was drawn on """ if self.get_window() and not self.bot_size: # Get initial size for window self.set_size_request(*size) self.bot_size = size self.backing_store = BackingStore.get_backingstore( self.width, self.height) cr = pycairo.Context(self.backing_store.surface) if self.scale_fit: self.scale_context_and_center(cr) cairo_ctx = driver.ensure_pycairo_context(cairo_ctx) cr.set_source_surface(cairo_ctx.get_target()) # Create the cairo context cr.set_operator(cairo.OPERATOR_SOURCE) cr.paint() self.queue_draw() while Gtk.events_pending(): Gtk.main_iteration_do(False)
def update_jump_list(self): self._logger.debug("entered update_jump_list") treestore = self._gtk_builder.get_object("treestore") treestore.clear() for row in self._static_jump_location_list: window_name = row[0] self._logger.debug("adding window_name %s", window_name) piter = treestore.append(None, [window_name]) for row in self._dyanmic_fill_list: self._logger.debug("invoking function %s", row[1]) window_unique_keys = row[1]() self._logger.debug("function %s returned %s", row[1], window_unique_keys) if window_unique_keys == []: self._logger.debug("dynamic window %s has no children", row[0]) else: self._logger.debug("adding dynamic window_name %s", row[0]) piter = treestore.append(None, [row[0]]) for window_unique_key in window_unique_keys: self._logger.debug("adding dynamic window key %s", window_unique_key) treestore.append(piter, [window_unique_key]) self._logger.debug("treestore filled with %d items, %s", len(treestore), print_tree_store(treestore)) jump_menu_button = self._gtk_builder.get_object("jump_menu_button") if jump_menu_button.get_active(): i = 0 treeview = self._gtk_builder.get_object("jump_treeview") while Gtk.events_pending(): Gtk.main_iteration_do(False) i += 1 self._logger.debug("%d events processed", i)
def type_coloured_text(self, string): ''' Adds colour to the string and prints string with a typing effect. Args: string (str): Text we want to print with a typing effect Returns: None ''' lines = self.__parse_string(string) for line in lines: self.__style_char( line['letter'], # TODO: get size tag working [line['colour'], line['bold']] ) if line['letter'] == '\n': time.sleep(NEWLINE_SLEEP) else: time.sleep(OTHER_SLEEP) while Gtk.events_pending(): Gtk.main_iteration_do(False)
def rotate(self, widget, clockwise): """Rotate children in this window""" self.set_pos_by_ratio = True maker = Factory() child = self.get_child() # If our child is a Notebook, reset to work from its visible child if maker.isinstance(child, 'Notebook'): pagenum = child.get_current_page() child = child.get_nth_page(pagenum) if maker.isinstance(child, 'Paned'): parent = child.get_parent() # Need to get the allocation before we remove the child, # otherwise _sometimes_ we get incorrect values. alloc = child.get_allocation() parent.remove(child) child.rotate_recursive(parent, alloc.width, alloc.height, clockwise) self.show_all() while Gtk.events_pending(): Gtk.main_iteration_do(False) widget.grab_focus() self.set_pos_by_ratio = False
def repaint(): '''Easy function to clean up the event queue and force a repaint.''' # I've been unable to find any other way to repaint the interface. :-( while Gtk.events_pending(): # Blocking: True/false Gtk.main_iteration_do(False)
def wait_for(self, predicate): '''Runs Gtk main loop until the predicate function returns true''' start = time.time() while not predicate() and time.time() - start < _TEST_WAIT_TIMEOUT: gtk.main_iteration_do(blocking=False) if time.time() - start >= _TEST_WAIT_TIMEOUT: raise AssertionError("Timeout reached while waiting for predicate to become True")
def __init__(self): filename = "popup.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.title = self.builder.get_object("lblTitle") self.message = self.builder.get_object("lblMessage") self.titleBox = self.builder.get_object("labelbox") self.titleBox.connect("button-release-event", self.on_clicked) self.exit = self.builder.get_object("exitbox") self.exit.connect("button-release-event", self.close_notify) self.icon = self.builder.get_object("imgIcon") self.window.set_gravity(gdk.Gravity.NORTH_WEST) self.display = False self.window.set_keep_above(True) color = gdk.color_parse('#F7A900') for wid in [self.window, self.exit, self.titleBox]: wid.modify_bg(Gtk.StateFlags.NORMAL, color) self.counter = 0 self.counter2 = 0 self.counting = False self.queue = [] gobject.timeout_add_seconds(1, self.timer) gobject.timeout_add_seconds(0.2, self.display_notify) gobject.timeout_add_seconds(30, self.message_system) while gtk.events_pending(): gtk.main_iteration_do(True) self.message_system()
def type_coloured_text(self, string): ''' Adds colour to the string and prints string with a typing effect. Args: string (str): Text we want to print with a typing effect Returns: None ''' lines = self.__parse_string(string) for line in lines: self.__style_char( line['letter'], # TODO: get size tag working [line['colour'], line['bold']]) if line['letter'] == '\n': time.sleep(NEWLINE_SLEEP) else: time.sleep(OTHER_SLEEP) while Gtk.events_pending(): Gtk.main_iteration_do(False)
def __init__(self): filename = "../Setup/templates/popup.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.title = self.builder.get_object("lblTitle") self.message = self.builder.get_object("lblMessage") self.titleBox = self.builder.get_object("labelbox") self.titleBox.connect("button-release-event", self.on_clicked) self.exit = self.builder.get_object("exitbox") self.exit.connect("button-release-event",self.close_notify) self.icon = self.builder.get_object("imgIcon") self.window.set_gravity(gdk.Gravity.NORTH_WEST) self.display = False self.window.set_keep_above(True) color = gdk.color_parse('#F7A900') for wid in [self.window,self.exit,self.titleBox]: wid.modify_bg(Gtk.StateFlags.NORMAL, color) self.counter = 0 self.counter2 = 0 self.counting = False self.queue = [] gobject.timeout_add_seconds(1, self.timer) gobject.timeout_add_seconds(0.2, self.display_notify) gobject.timeout_add_seconds(30, self.message_system) while gtk.events_pending(): gtk.main_iteration_do(True) self.message_system()
def ext_wine(file_path, dest_dir): """Unpack installer using wine""" wineprefix_path = dest_dir + '/wine_prefix' os.environ['WINEPREFIX'] = wineprefix_path os.environ['WINEDEBUG'] = '-all' os.environ['WINEDLLOVERRIDES'] = 'mshtml,mscoree=d' if not os.path.exists(wineprefix_path): os.makedirs(wineprefix_path) dest_dir = dest_dir + '/game' proc = subprocess.Popen(['winepath', '-w', dest_dir], stdout=subprocess.PIPE) dest_dir_win = proc.stdout.readline().decode('utf-8').strip() subprocess.call([ 'wine', file_path, '/DIR=' + dest_dir_win, '/VERYSILENT', '/SUPPRESSMSGBOXES' ]) if not os.path.exists(dest_dir): simple_message(Gtk.MessageType.INFO, "Info", "Do not change the installation path!") while Gtk.events_pending(): Gtk.main_iteration_do(False) subprocess.call([ 'wine', file_path, '/LANG=english', '/DIR=' + dest_dir_win, ])
def a(self, widget, event, jk): ser = serial.Serial('/dev/ttyACM0', 9600 * 2) # Establish the connection on a print "hi" while True: arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for l in range(0, 14): i = ser.readline().split( ',') # Read the newest output from the Arduin if i[0] == "S": op = ser.readline() arr[int(i[1].split("\\")[0])] = int(op.split("\\")[0]) sleep(.05) # Delay for one tenth of a second for i in range(0, 14): if arr[i] == 1: im = self.build.get_object("image" + str(i + 1)) im.set_from_file("s1.jpeg") else: im = self.build.get_object("image" + str(i + 1)) im.set_from_file("s2.jpeg") self.win.show() while Gtk.events_pending(): Gtk.main_iteration_do(True)
def layout_done(self): """Layout operations have finished, record that fact""" self.doing_layout = False maker = Factory() window_last_active_term_mapping = {} for window in self.windows: if window.is_child_notebook(): source = window.get_toplevel().get_children()[0] else: source = window window_last_active_term_mapping[window] = copy.copy( source.last_active_term) for terminal in self.terminals: if not terminal.pid: terminal.spawn_child() for window in self.windows: if not window.is_child_notebook(): # For windows without a notebook ensure Terminal is visible and focussed if window_last_active_term_mapping[window]: term = self.find_terminal_by_uuid( window_last_active_term_mapping[window].urn) term.ensure_visible_and_focussed() # Build list of new windows using prelayout list new_win_list = [] if self.prelayout_windows: for window in self.windows: if window not in self.prelayout_windows: new_win_list.append(window) # Make sure all new windows get bumped to the top for window in new_win_list: window.show() window.grab_focus() try: t = GdkX11.x11_get_server_time(window.get_window()) except (NameError, TypeError, AttributeError): t = 0 window.get_window().focus(t) # Awful workaround to be sure that the last focused window is actually the one focused. # Don't ask, don't tell policy on this. Even this is not 100% if self.last_active_window: window = self.find_window_by_uuid(self.last_active_window.urn) count = 0 while count < 1000 and Gtk.events_pending(): count += 1 Gtk.main_iteration_do(False) window.show() window.grab_focus() try: t = GdkX11.x11_get_server_time(window.get_window()) except (NameError, TypeError, AttributeError): t = 0 window.get_window().focus(t) self.prelayout_windows = None
def __init__(self): filename = "../Setup/templates/popup.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.title = self.builder.get_object("lblTitle") self.message = self.builder.get_object("lblMessage") self.titleBox = self.builder.get_object("labelbox") self.titleBox.connect("button-release-event", self.on_clicked) self.exit = self.builder.get_object("exitbox") self.exit.connect("button-release-event",self.close_notify) self.icon = self.builder.get_object("imgIcon") self.window.set_gravity(gdk.Gravity.NORTH_WEST) self.display = False self.window.set_keep_above(True) self.counter = 0 self.counter2 = 0 self.counting = False self.queue = [] self.info = lispeak.getInfo() gobject.timeout_add_seconds(1, self.timer) try: gobject.timeout_add_seconds(0.2, self.display_notify) except: print "Reverting to 1 second check" gobject.timeout_add_seconds(1, self.display_notify) gobject.timeout_add_seconds(30, self.message_system) while gtk.events_pending(): gtk.main_iteration_do(True) self.message_system()
def tracer(self, toplevel): """ para todos los rayos para todos los objetos para el impacto mas cercano - luz ambiente (color) para cada fuente de luz para cada objeto ver si permite la luz si llega luz, determinar el ángulo de la luz determinamos intensidad la luz -> difusa determinar luz especular """ self.toplevel = toplevel w = toplevel.config.conf["image"]["width"] h = toplevel.config.conf["image"]["height"] if len(self.els["cameras"]) != 1: return "Tiene que existir exactamente una sola cámara. Hay {}.".format( len(self.els["cameras"])) if len(self.els["objects"]) == 0: return "No hay objetos en la escena" self.cam = self.els["cameras"][0] ray_gen = self.cam.ray_generator(w, h) GLib.timeout_add(500, self.on_timeout) self.timer_runs = True for ray, x0, y0 in ray_gen: Gtk.main_iteration_do(False) nearest_hit = self.find_nearest_thing_hit(ray) if nearest_hit is None: # No hay impactos: No ejecutamos el resto continue nearest_color = nearest_hit.thing.get_color() pixel_color = nearest_color * toplevel.config.conf["scene"][ "ambient"] for light in self.els["lights"]: light_loc = light.param("location") light_color = light.param("rgb") incident = (ray.at(nearest_hit.impact) - light_loc).normalized() light_ray = Ray(light_loc, incident) nearest_light_hit = self.find_nearest_thing_hit(light_ray) if nearest_light_hit is None: # imposible continue light_to_hit = abs(light_loc - ray.at(nearest_hit.impact)) if (nearest_light_hit.impact - light_to_hit) > -epsilon: cos_ang = -(nearest_light_hit.normal * incident) diffuse = nearest_color * light_color pixel_color += diffuse * cos_ang self.cam.set_pixel(x0, h - y0 - 1, pixel_color) self.timer_runs = False
def dlProgress(count, blockSize, totalSize): global updating_step1, percent percent = int(count*blockSize*100/totalSize) total = str(round(totalSize/1024/1024.0*10)/10.0) label_updating_step1.set_text(_('Downloading')+" (%s Мб)... %d%%" %(total, percent)) # redraw window while Gtk.events_pending(): Gtk.main_iteration_do(True)
def set_text(self, text): self.label.set_text(text) # include this to give more time to watch # import time # time.sleep(1) while Gtk.events_pending(): Gtk.main_iteration_do(False) return
def usleep(msec): got_clock = time.clock() + float(msec) / 1000 #print got_clock while True: if time.clock() > got_clock: break Gtk.main_iteration_do(False)
def on_miCalloutSize_activate(self, widget): ''' 吹き出しサイズ変更 ''' self.calloutSize = widget.get_child().get_text() while Gtk.events_pending(): Gtk.main_iteration_do(False) self.timeout2 = GLib.timeout_add(100, self.chanegSize_callback, self)
def execute(self): thread = Thread(self.handler) self.handler.create_modal() while(thread.alive()): while Gtk.events_pending(): Gtk.main_iteration_do(True) self.handler.delete_modal()
def disable_ui_callback(): self._currently_focused_widget = self.get_focus() self.spinner_revealer.set_reveal_child(True) self.preset_list.set_sensitive(False) self.theme_edit.set_sensitive(False) Gtk.main_iteration_do(False) self.spinner_message.set_text(message) self.spinner.start()
def set_text(self, text): if is_custom_design_enabled() and not global_design_config.get_config_value("SPLASH_SCREEN_SHOW_TEXT", True): return logger.info(text) self.label.set_text(text) while Gtk.events_pending(): Gtk.main_iteration_do(False) return
def update_progressbar_message(self, message="Llevamos un ", step=0.143): progress_bar = self.builder.get_object('progress_bar') fraction = round(progress_bar.get_fraction() + step, 3) progress_bar.set_fraction(fraction) progress_bar.set_text('{} {}%'.format(message, int(fraction*100))) while gtk.events_pending(): #force to update the progress bar gtk.main_iteration_do(True)
def _search_callback(results, path): if results is not None: self._update_results( results, State.get(query) ) # we finish the search even if another search is running. If we returned False, the search would be cancelled- while Gtk.events_pending(): Gtk.main_iteration_do(blocking=False) return True
def set_fraction(self, fraction): # update only by 10% fractions if int(fraction * 100) % 10 == 0: self._pb.set_fraction(fraction) self._pb.queue_draw() # force updating the progressbar while Gtk.events_pending(): Gtk.main_iteration_do(True)
def _check_messages(self): while not self._debugger.messages_queue.empty(): method_name, data = self._debugger.messages_queue.get_nowait() # call the handler self._gui_handlers[method_name](*data) while Gtk.events_pending(): Gtk.main_iteration_do(False) return self._debugging
def read(self, msg_len = 0, timeout = 500, end_char = '\r'): if (not self.is_open()): return((False, None)) self.buffer = '' # Command adapter to read until EOS is reached self._command("++read\n") start = datetime.now() if (msg_len <= 0): while(True): # read... until newline w = self.ser.inWaiting() if (w > 0): for i in range(w): c = self.ser.read(1) if (c == end_char): # done! self.buffer += c temp_buf = self.buffer self.buffer = '' return((True, temp_buf)) else: self.buffer += c delta = datetime.now() - start if ((delta.total_seconds()*1000.0) >= timeout): return((False, None)) # Keep GUI active while Gtk.events_pending(): Gtk.main_iteration_do(False) else: r = 0 while(True): w = self.ser.inWaiting() if (w > 0): if (w >= msg_len): self.buffer = self.ser.read(msg_len) return((True, self.buffer)) else: self.buffer += self.ser.read(w) r += w if (r >= msg_len): # Received complete message temp_buf = self.buffer[0:msg_len] self.buffer = '' return((True, temp_buf)) delta = datetime.now() - start if ((delta.total_seconds()*1000.0) >= timeout): return((False, None)) # Keep GUI active while Gtk.events_pending(): Gtk.main_iteration_do(False)
def on_continue_clicked(self, button): page = self.get_current_page() #print("apply emited") if page == 5: self.commit() self.set_current_page(5) while Gtk.events_pending(): Gtk.main_iteration_do(self) self.set_current_page(6)
def refresh_gui(vimiv=None): """Refresh the GUI as the Gtk.main() loop is not running when testing. Args: delay: Time to wait before refreshing. """ current_pos = vimiv.index while current_pos == vimiv.index: Gtk.main_iteration_do(False)
def close(self): ''' Things to do before the plugin closes. ''' # don't close the plugin until we have finished writing while True: if not self.write_in_progress: break gtk.main_iteration_do(True)
def set_sensitive_buttons(self, val): self.debug_action.set_sensitive(not val) self.step_into_action.set_sensitive(val) self.step_over_action.set_sensitive(val) self.step_out_action.set_sensitive(val) self.step_continue_action.set_sensitive(val) self.step_stop_action.set_sensitive(val) while Gtk.events_pending(): Gtk.main_iteration_do(False)
def img_crypter(self, ACTION): txtpass_obj = self.gui.get_object("txt_CIPass") state = self.gui.get_object("lbl_CIState") passw = txtpass_obj.get_text() imgpath = self.CIdata["OR_IMG_PATH"] if imgpath: if passw: advise = "Se cifrara " + imgpath advise += " toma en cuenta que puede tardar dependiendo" advise += " la resolucion de la imagen." #change status to working state.set_markup( "<span color='red'>[*] Working, please wait ...</span>" ) self.info( self.CryptImageWindow, advise ) while Gtk.events_pending(): Gtk.main_iteration_do(False) trg = TurangaImageCryp(imgpath, ".temp_ci_img", passw) if ACTION == "CRYPT": trg.cryp() done = True else: done = trg.decryp() if not done: m = "Error al procesar la clave, quiza la contraseña" m += " sea incorrecta o el archivo de clave no existe." self.msg(self.CryptImageWindow, m) #change status to error state.set_markup( "<span color='red'>[!] Error</span>" ) if done: #change status to nothing state.set_text("") #set new img imgres = self.gui.get_object("img_CIResult") imgres.set_from_file(".temp_ci_img.png") self.CIdata["RE_IMG_PATH"] = ".temp_ci_img" else: self.msg(self.CryptImageWindow, "Password?!") else: self.msg(self.CryptImageWindow, "Open any image!")
def on_button_release(self, widget, event): """Handle button presses on a Pane""" if event.button == 1: if self.last_balance_time > (time.time() - 1): # Dumb loop still needed, or some terms get squished on a Super rebalance for i in range(3): while Gtk.events_pending(): Gtk.main_iteration_do(False) self.do_redistribute(*self.last_balance_args) return False
def _login_cb(self, event=None, button=None): logger.debug('Sending username to LightDM') self.login_btn.start_spinner() Gtk.main_iteration_do(True) # The call below will simply initiate the login flow. # The greeter library will inform us through callbacks # See: http://web.mit.edu/Source/debathena/config/lightdm-config/debian/debathena-lightdm-greeter self.greeter.authenticate(self.user)
def wait_for(cond: typing.Callable[[], bool], timeout: float= 5): start_time = time.time() while True: if cond(): return if time.time() - start_time > timeout: raise AssertionError('Timeout expired') Gtk.main_iteration_do(False)
def close_notify(self,a=None,b=None,c=None): print "Closing" for each in range(10,-1,-1): self.window.set_opacity(float("0."+str(each))) while gtk.events_pending(): gtk.main_iteration_do(True) time.sleep(0.05) self.display = False self.window.hide() self.counting = False
def write_to_textview(io, condition, tw): if condition is GLib.IO_HUP: GLib.source_remove(self.source_id_out) GLib.source_remove(self.source_id_err) return False line = io.readline() tw.props.buffer.insert_at_cursor(line) scroll_to_end(tw) while Gtk.events_pending(): Gtk.main_iteration_do(False) return True