def exit_app(self, src): if self.err is None: # Already in cleanup return self.cleanup() if debug_ref_leaks: objs = self.config.get_objects() # Engine will always appear to leak objs.remove(self.object_key) if src.object_key in objs: # UI that initiates the app exit will always appear to leak objs.remove(src.object_key) for name in objs: logging.debug("Leaked %s", name) logging.debug("Exiting app normally.") # We need this if there are any asyncdialog fobjs running if Gtk.main_level(): logging.debug("%s other gtk main loops running, killing them.", Gtk.main_level()) for ignore in range(Gtk.main_level()): Gtk.main_quit() self.application.remove_window(self._appwindow)
def run(self): (success, args) = Gtk.init_check(None) if not success: raise RuntimeError("Failed to initialize Gtk") if Gtk.main_level() > 0: # Gtk main loop running. That means python-meh caught exception # and runs its main loop. Do not crash Gtk by running another one # from a different thread and just wait until python-meh is # finished, then quit. unbusyCursor() log.error("Unhandled exception caught, waiting for python-meh to "\ "exit") while Gtk.main_level() > 0: time.sleep(2) sys.exit(0) while not self._currentAction: self._currentAction = self._instantiateAction(self._actions[0]) if not self._currentAction: self._actions.pop(0) if not self._actions: return self._currentAction.initialize() self._currentAction.refresh() self._currentAction.window.set_beta(not self._isFinal) #nkwin7 add by yuwan #self._currentAction.window.set_property("distribution", self._distributionText().upper()) self._currentAction.window.set_property("distribution", self._distributionText()) #nkwin7 done # Set some program-wide settings. settings = Gtk.Settings.get_default() settings.set_property("gtk-font-name", "Cantarell") settings.set_property("gtk-icon-theme-name", "gnome") # nkwin7 add by yuwan # Apply the application stylesheet provider = Gtk.CssProvider() provider.load_from_path("/usr/share/anaconda/anaconda-gtk.css") Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) #nkwin7 done self._currentAction.window.show_all() # Do this at the last possible minute. unbusyCursor() Gtk.main()
def _timeout_cb(self): if self.success: # dispose of previous waiters. return False self._timeout_count += 1 try: self.poll() except: if self._ldtp_debug: print(traceback.format_exc()) if self._ldtp_debug_file: with open(self._ldtp_debug_file, "a") as fp: fp.write(traceback.format_exc()) if self._timeout_count * self.timeout_seconds > self.timeout or \ self.success: try: # Required for wnck functions if _main_loop: _main_loop.quit() else: if gtk.main_level(): gtk.main_quit() except RuntimeError: # In Mandriva RuntimeError exception is thrown # If, gtk.main was already quit pass return False return True
def update_view(self): """Redraw callback. """ # Are we open for business or # still initializing? if not Gtk.main_level(): return # Deep copy all current graphs gvs = {} self.glock.acquire() for name in self.graphs: gvs[name] = self.graphs[name].copy() self.glock.release() # Make sure a window for each graph exists for name in gvs: if not name in self.windows: window = GraphWindow( gvs[name], self._ring_layout(gvs[name]), (800, 400), fit_area=0.95) window.graph.handler_block_by_func( window.graph.motion_notify_event) window.graph.handler_block_by_func( window.graph.button_press_event) window.graph.handler_block_by_func( window.graph.button_release_event) window.graph.handler_block_by_func(window.graph.scroll_event) window.graph.handler_block_by_func( window.graph.key_press_event) window.graph.handler_block_by_func( window.graph.key_release_event) window.connect("delete_event", self.__killall) window.set_title(name) window.show_all() self.windows[name] = window gw = self.windows[name].graph # Regen GraphWidget contents gw.g = gvs[name] gw.pos = self._ring_layout(gvs[name]) gw.vprops["text"] = gvs[name].new_vp("string") gw.vprops["fill_color"] = gw.g.own_property(self.vcolors[name]) gw.vprops["text_position"] = 0 gw.vprops["size"] = 10 gw.selected = gvs[name].new_vertex_property("bool", False) gw.highlight = gvs[name].new_vertex_property("bool", False) gw.sel_edge_filt = gvs[name].new_edge_property("bool", False) gw.fit_to_window() gw.vprops["text"] = gw.g.own_property(self.vlabels[name]) # Insert edges self.elocks[name].acquire() gvs[name].add_edge_list(self.edgequeue[name]) self.edgequeue[name] = [] self.elocks[name].release() gw.regenerate_surface() gw.queue_draw() return self.alive
def quit (self, *args): """Quit the application.""" if gtk.main_level(): gtk.main_quit() else: self.do_quit = True return True
def new_hook(etype, evalue, etb): old_hook(etype, evalue, etb) while Gtk.main_level(): Gtk.main_quit() sys.exit()
def quit_cb (self, *args): self.w.hide() if (self.gsd.grid and self.gsd.grid.is_changed() and (not self.won)): self.save_game(self) if Gtk.main_level() > 1: # If we are in an embedded mainloop, that means that one # of our "swallowed" dialogs is active, in which case we # have to quit that mainloop before we can quit # properly. if self.swallower.running: d = self.swallower.running d.response(Gtk.ResponseType.DELETE_EVENT) Gtk.main_quit() # Quit the embedded mainloop GObject.idle_add(self.quit_cb, 100) # Call ourselves again # to quit the main # mainloop return # make sure we really go away before doing our saving -- # otherwise we appear sluggish. while Gtk.events_pending(): Gtk.main_iteration() self.stop_worker_thread() # allow KeyboardInterrupts, which calls quit_cb outside the main loop try: Gtk.main_quit() except RuntimeError: pass
def evaluate_js(self, script): def _evaluate_js(): self.webview.run_javascript(code, None, None, None) unique_id = uuid1().hex result_semaphore = Semaphore(0) self.js_results[unique_id] = {'semaphore': result_semaphore, 'result': None} code = 'document.title = JSON.stringify({{"type": "eval", "uid": "{0}", "result": {1}}})'.format(unique_id, script) self.load_event.wait() glib.idle_add(_evaluate_js) result_semaphore.acquire() if not gtk.main_level(): # Webview has been closed, don't proceed return None result = self.js_results[unique_id]['result'] result = None if result == 'undefined' or result == 'null' or result is None else result if result == '' else json.loads(result) del self.js_results[unique_id] return result
def on_window_main_delete_event(self, *args): if self.window_main.get_property("sensitive"): if Gtk.main_level() > 0: Gtk.main_quit() return False else: return True
def on_destroy(self, widget): print 'destroy', widget if self.player: self.set_player_state(Gst.State.NULL) del self.player if Gtk.main_level() > 0: Gtk.main_quit()
def crash(self): selectreactor.SelectReactor.crash(self) from gi.repository import Gtk as gtk # mainquit is deprecated in newer versions if gtk.main_level(): if hasattr(gtk, 'main_quit'): gtk.main_quit() else: gtk.mainquit()
def _our_mainquit(): # XXX: gtk.main_quit() (which is used for crash()) raises an exception if # gtk.main_level() == 0; however, all the tests freeze if we use this # function to stop the reactor. what gives? (I believe this may have been # a stupid mistake where I forgot to import gtk here... I will remove this # comment if the tests pass) from gi.repository import Gtk as gtk if gtk.main_level(): gtk.main_quit()
def run(self) -> dict: """ Start Gtk main. """ self._loop_level = Gtk.main_level() + 1 Gtk.main() return self._result
def on_destroy(self, widget, event): LOG.debug('Destroying application') LOG.debug('Parent PID: {0}'.format(os.getppid())) LOG.debug('FreeStationApp PID: {0}'.format(os.getpid())) Gtk.main_quit() if Gtk.main_level() > 0: Gtk.main_quit() self.destroy()
def destroy_window(self, *args): # This method is not to be called directly # only from remove_figure if there are no more figures if self._window: self._window.destroy() self._window = None FM.managers.remove(self) if len(FM.managers) == 0 and not matplotlib.is_interactive() and \ Gtk.main_level() >= 1: Gtk.main_quit()
def destroy(self, *args): self.vbox.destroy() self.window.destroy() self.canvas.destroy() if self.toolbar: self.toolbar.destroy() if (Gcf.get_num_fig_managers() == 0 and not matplotlib.is_interactive() and Gtk.main_level() >= 1): Gtk.main_quit()
def close_app(self, widget): """ close the app """ if Gtk.main_level() == 0: LOG.info("closing before the regular main loop was run") sys.exit(0) self.destroy() try: Gtk.main_quit() except: LOG.exception("Gtk.main_quit failed") sys.exit(0)
def run(self) -> dict: """ Run the dialog. """ self._window.show_all() self._name_entry.grab_focus() self._loop_level = Gtk.main_level() + 1 Gtk.main() return self._result
def destroy(self, *args): if _debug: print('FigureManagerGTK3.%s' % fn_name()) self.vbox.destroy() self.window.destroy() self.canvas.destroy() if self.toolbar: self.toolbar.destroy() if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ Gtk.main_level() >= 1: Gtk.main_quit()
def destroy(self, *args): if _debug: print 'FigureManagerGTK3.%s' % fn_name() self.vbox.destroy() self.window.destroy() self.canvas.destroy() if self.toolbar: self.toolbar.destroy() self.__dict__.clear() #Is this needed? Other backends don't have it. if Gcf.get_num_fig_managers()==0 and \ not matplotlib.is_interactive() and \ Gtk.main_level() >= 1: Gtk.main_quit()
def _close_dialog(self, button: object, response: int): """ Close the dialog and set the result. """ if response == Gtk.ResponseType.OK: self._result['name'] = self._name_entry.get_text() self._result['uri'] = self._uri_entry.get_text() if Gtk.main_level() == self._loop_level: Gtk.main_quit() self._window.destroy()
def close_application(self, widget, event=None, data=None): """Termination""" if self.rendering_thread: self.rendering_thread.quit = True self.rendering_thread.join() if os.path.isdir(self.tmp_dir): shutil.rmtree(self.tmp_dir) if Gtk.main_level(): Gtk.main_quit() else: sys.exit(0) return False
def _dialog_response_cb(self, dialog, resp, trace): if resp == self.RESPONSE_QUIT and Gtk.main_level() > 0: if not callable(self.quit_confirmation_func): sys.exit(1) # Exit code is important for IDEs else: if self.quit_confirmation_func(): sys.exit(1) # Exit code is important for IDEs else: dialog.destroy() self.exception_dialog_active = False else: dialog.destroy() self.exception_dialog_active = False
def _close_dialog(self, widget: object, response: int): """ Close the dialog. """ if response == Gtk.ResponseType.OK: self._result['new-folder'] = self._new_folder_list self._result['move'] = self._selected self._result['changed'] = ( self._name_entry.get_text(), self._uri_entry.get_text() ) if Gtk.main_level() == self._loop_level: Gtk.main_quit() self._window.destroy()
def _event_cb(self, event): try: self.event_cb(event) except: if self._ldtp_debug: print(traceback.format_exc()) if self.success: try: # Required for wnck functions if _main_loop: _main_loop.quit() else: if gtk.main_level(): gtk.main_quit() except RuntimeError: # In Mandriva RuntimeError exception is thrown # If, gtk.main was already quit pass
def quit(self): """Gracefully shut down application.""" try: self._pa_mgr.close() except AttributeError: pass if Gtk.main_level() > 0: try: self._preferences.response(0) except AttributeError: pass try: self._about_win.close() except AttributeError: pass Gtk.main_quit() else: exit(1)
def terminate_program(self, *args): """Run clean-up tasks and exit the program.""" self.hide() if Gtk.main_level() > 0: Gtk.main_quit() if prefs["auto load last file"] and self.file_handler.file_loaded: prefs["path to last file"] = self.file_handler.get_real_path() prefs["page of last file"] = self.file_handler.get_current_page() else: prefs["path to last file"] = "" prefs["page of last file"] = 1 self.file_handler.cleanup() preferences.write_preferences_file() self.ui_manager.bookmarks.write_bookmarks_file() # This hack is to avoid Python issue #1856. for thread in threading.enumerate(): if thread is not threading.currentThread(): thread.join() print "Bye!" sys.exit(0)
def gtkcrashhandler_wrapped_run(*args, **kwargs): try: run(*args, **kwargs) except Exception as ee: lock = threading.Lock() lock.acquire() tb = sys.exc_info()[2] if Gtk.main_level() > 0: GObject.idle_add( lambda ee=ee, tb=tb, thread=threading.currentThread(): _replacement_excepthook(ee.__class__, ee, tb, thread=thread)) else: # ugly hack, seems like threads that are started before # running Gtk.main() cause this one to crash. # This delay allows Gtk.main() to initialize properly. # My advice: run Gtk.main() before starting any threads or # don't run Gtk.main() at all time.sleep(0.1) _replacement_excepthook(ee.__class__, ee, tb, thread=threading.currentThread()) lock.release()
def mainloop(): if Gtk.main_level() == 0: Gtk.main()
def handle_sigterm(signal, frame): from gi.repository import Gtk logger.info('Got SIGTERM, quit') if Gtk.main_level() > 0: Gtk.main_quit()
def quit(self, *args): self.backend.cancel_install() if Gtk.main_level() > 0: Gtk.main_quit()
def quit(self): self.handle_events() self.window.hide() print(Gtk.main_level()) Gtk.main_quit()
def new_hook(etype, evalue, etb): old_hook(etype, evalue, etb) # do stuff here while Gtk.main_level(): Gtk.main_quit() sys.exit()
def _excepthook(*args): orig_excepthook(*args) while Gtk.main_level(): Gtk.main_quit() sys.exit()
def quit(self): '''Menu action for quit. @emits: quit ''' if Gtk.main_level() > 0: Gtk.main_quit()
def mainloop(): if Gtk.main_level() == 0: cbook._setup_new_guiapp() Gtk.main()
def _handle_action(self, action, *args): log.debug("_handle_action({0}, {1})".format(action, args)) main = self.main_window page = main.current_page flow_graph = page.flow_graph if page else None def flow_graph_update(fg=flow_graph): main.vars.update_gui(fg.blocks) fg.namespace.clear() fg.update() ################################################## # Initialize/Quit ################################################## if action == Actions.APPLICATION_INITIALIZE: log.debug("APPLICATION_INITIALIZE") file_path_to_show = self.config.file_open() for file_path in (self.init_file_paths or self.config.get_open_files()): if os.path.exists(file_path): main.new_page(file_path, show=file_path_to_show == file_path) if not main.current_page: main.new_page() # ensure that at least a blank page exists main.btwin.search_entry.hide() """ Only disable certain actions on startup. Each of these actions are conditionally enabled in _handle_action, so disable them first. - FLOW_GRAPH_UNDO/REDO are set in gui/StateCache.py - XML_PARSER_ERRORS_DISPLAY is set in RELOAD_BLOCKS TODO: These 4 should probably be included, but they are not currently enabled anywhere else: - PORT_CONTROLLER_DEC, PORT_CONTROLLER_INC - BLOCK_INC_TYPE, BLOCK_DEC_TYPE TODO: These should be handled better. They are set in update_exec_stop(), but not anywhere else - FLOW_GRAPH_GEN, FLOW_GRAPH_EXEC, FLOW_GRAPH_KILL """ for action in (Actions.ERRORS_WINDOW_DISPLAY, Actions.ELEMENT_DELETE, Actions.BLOCK_PARAM_MODIFY, Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, Actions.BLOCK_VALIGN_TOP, Actions.BLOCK_VALIGN_MIDDLE, Actions.BLOCK_VALIGN_BOTTOM, Actions.BLOCK_HALIGN_LEFT, Actions.BLOCK_HALIGN_CENTER, Actions.BLOCK_HALIGN_RIGHT, Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS, Actions.BLOCK_CREATE_HIER, Actions.OPEN_HIER, Actions.BUSSIFY_SOURCES, Actions.BUSSIFY_SINKS, Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO, Actions.XML_PARSER_ERRORS_DISPLAY): action.disable() # Load preferences for action in ( Actions.TOGGLE_BLOCKS_WINDOW, Actions.TOGGLE_CONSOLE_WINDOW, Actions.TOGGLE_HIDE_DISABLED_BLOCKS, Actions.TOGGLE_SCROLL_LOCK, Actions.TOGGLE_AUTO_HIDE_PORT_LABELS, Actions.TOGGLE_SNAP_TO_GRID, Actions.TOGGLE_SHOW_BLOCK_COMMENTS, Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB, Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR, Actions.TOGGLE_HIDE_VARIABLES, Actions.TOGGLE_SHOW_PARAMETER_EXPRESSION, Actions.TOGGLE_SHOW_PARAMETER_EVALUATION, Actions.TOGGLE_SHOW_BLOCK_IDS, ): action.set_enabled(True) if hasattr(action, 'load_from_preferences'): action.load_from_preferences() # Hide the panels *IF* it's saved in preferences main.update_panel_visibility( main.BLOCKS, Actions.TOGGLE_BLOCKS_WINDOW.get_active()) main.update_panel_visibility( main.CONSOLE, Actions.TOGGLE_CONSOLE_WINDOW.get_active()) main.update_panel_visibility( main.VARIABLES, Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR.get_active()) # Force an update on the current page to match loaded preferences. # In the future, change the __init__ order to load preferences first page = main.current_page if page: page.flow_graph.update() self.init = True elif action == Actions.APPLICATION_QUIT: if main.close_pages(): while Gtk.main_level(): Gtk.main_quit() exit(0) ################################################## # Selections ################################################## elif action == Actions.ELEMENT_SELECT: pass # do nothing, update routines below elif action == Actions.NOTHING_SELECT: flow_graph.unselect() elif action == Actions.SELECT_ALL: if main.btwin.search_entry.has_focus(): main.btwin.search_entry.select_region(0, -1) else: flow_graph.select_all() ################################################## # Enable/Disable ################################################## elif action in (Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, Actions.BLOCK_BYPASS): changed = flow_graph.change_state_selected( new_state={ Actions.BLOCK_ENABLE: 'enabled', Actions.BLOCK_DISABLE: 'disabled', Actions.BLOCK_BYPASS: '******', }[action]) if changed: flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False ################################################## # Cut/Copy/Paste ################################################## elif action == Actions.BLOCK_CUT: Actions.BLOCK_COPY() Actions.ELEMENT_DELETE() elif action == Actions.BLOCK_COPY: self.clipboard = flow_graph.copy_to_clipboard() elif action == Actions.BLOCK_PASTE: if self.clipboard: flow_graph.paste_from_clipboard(self.clipboard) flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False ################################################## # Create hier block ################################################## elif action == Actions.BLOCK_CREATE_HIER: selected_blocks = [] pads = [] params = set() for block in flow_graph.selected_blocks(): selected_blocks.append(block) # Check for string variables within the blocks for param in block.params.values(): for variable in flow_graph.get_variables(): # If a block parameter exists that is a variable, create a parameter for it if param.get_value() == variable.name: params.add(param.get_value()) for flow_param in flow_graph.get_parameters(): # If a block parameter exists that is a parameter, create a parameter for it if param.get_value() == flow_param.name: params.add(param.get_value()) x_min = min(block.coordinate[0] for block in selected_blocks) y_min = min(block.coordinate[1] for block in selected_blocks) for connection in flow_graph.connections: # Get id of connected blocks source = connection.source_block sink = connection.sink_block if source not in selected_blocks and sink in selected_blocks: # Create Pad Source pads.append({ 'key': connection.sink_port.key, 'coord': source.coordinate, # Ignore the options block 'block_index': selected_blocks.index(sink) + 1, 'direction': 'source' }) elif sink not in selected_blocks and source in selected_blocks: # Create Pad Sink pads.append({ 'key': connection.source_port.key, 'coord': sink.coordinate, # Ignore the options block 'block_index': selected_blocks.index(source) + 1, 'direction': 'sink' }) # Copy the selected blocks and paste them into a new page # then move the flowgraph to a reasonable position Actions.BLOCK_COPY() main.new_page() flow_graph = main.current_page.flow_graph Actions.BLOCK_PASTE() coords = (x_min, y_min) flow_graph.move_selected(coords) # Set flow graph to heir block type top_block = flow_graph.get_block("top_block") top_block.params['generate_options'].set_value('hb') # this needs to be a unique name top_block.params['id'].set_value('new_hier') # Remove the default samp_rate variable block that is created remove_me = flow_graph.get_block("samp_rate") flow_graph.remove_element(remove_me) # Add the param blocks along the top of the window x_pos = 150 for param in params: param_id = flow_graph.add_new_block('parameter', (x_pos, 10)) param_block = flow_graph.get_block(param_id) param_block.params['id'].set_value(param) x_pos = x_pos + 100 for pad in pads: # add the pad sources and sinks within the new hier block if pad['direction'] == 'sink': # add new pad_sink block to the canvas pad_id = flow_graph.add_new_block('pad_sink', pad['coord']) # setup the references to the sink and source pad_block = flow_graph.get_block(pad_id) pad_sink = pad_block.sinks[0] source_block = flow_graph.get_block( flow_graph.blocks[pad['block_index']].name) source = source_block.get_source(pad['key']) # ensure the port types match if pad_sink.dtype != source.dtype: if pad_sink.dtype == 'complex' and source.dtype == 'fc32': pass else: pad_block.params['type'].value = source.dtype pad_sink.dtype = source.dtype # connect the pad to the proper sinks new_connection = flow_graph.connect(source, pad_sink) elif pad['direction'] == 'source': pad_id = flow_graph.add_new_block('pad_source', pad['coord']) # setup the references to the sink and source pad_block = flow_graph.get_block(pad_id) pad_source = pad_block.sources[0] sink_block = flow_graph.get_block( flow_graph.blocks[pad['block_index']].name) sink = sink_block.get_sink(pad['key']) # ensure the port types match if pad_source.dtype != sink.dtype: if pad_source.dtype == 'complex' and sink.dtype == 'fc32': pass else: pad_block.params['type'].value = sink.dtype pad_source.dtype = sink.dtype # connect the pad to the proper sinks new_connection = flow_graph.connect(pad_source, sink) flow_graph_update(flow_graph) ################################################## # Move/Rotate/Delete/Create ################################################## elif action == Actions.BLOCK_MOVE: page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action in Actions.BLOCK_ALIGNMENTS: if flow_graph.align_selected(action): page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.BLOCK_ROTATE_CCW: if flow_graph.rotate_selected(90): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.BLOCK_ROTATE_CW: if flow_graph.rotate_selected(-90): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.ELEMENT_DELETE: if flow_graph.remove_selected(): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) Actions.NOTHING_SELECT() page.saved = False elif action == Actions.ELEMENT_CREATE: flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) Actions.NOTHING_SELECT() page.saved = False elif action == Actions.BLOCK_INC_TYPE: if flow_graph.type_controller_modify_selected(1): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.BLOCK_DEC_TYPE: if flow_graph.type_controller_modify_selected(-1): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.PORT_CONTROLLER_INC: if flow_graph.port_controller_modify_selected(1): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False elif action == Actions.PORT_CONTROLLER_DEC: if flow_graph.port_controller_modify_selected(-1): flow_graph_update() page.state_cache.save_new_state(flow_graph.export_data()) page.saved = False ################################################## # Window stuff ################################################## elif action == Actions.ABOUT_WINDOW_DISPLAY: Dialogs.show_about(main, self.platform.config) elif action == Actions.HELP_WINDOW_DISPLAY: Dialogs.show_help(main) elif action == Actions.GET_INVOLVED_WINDOW_DISPLAY: Dialogs.show_get_involved(main) elif action == Actions.TYPES_WINDOW_DISPLAY: Dialogs.show_types(main) elif action == Actions.KEYBOARD_SHORTCUTS_WINDOW_DISPLAY: Dialogs.show_keyboard_shortcuts(main) elif action == Actions.ERRORS_WINDOW_DISPLAY: Dialogs.ErrorsDialog(main, flow_graph).run_and_destroy() elif action == Actions.TOGGLE_CONSOLE_WINDOW: action.set_active(not action.get_active()) main.update_panel_visibility(main.CONSOLE, action.get_active()) action.save_to_preferences() elif action == Actions.TOGGLE_BLOCKS_WINDOW: # This would be better matched to a Gio.PropertyAction, but to do # this, actions would have to be defined in the window not globally action.set_active(not action.get_active()) main.update_panel_visibility(main.BLOCKS, action.get_active()) action.save_to_preferences() elif action == Actions.TOGGLE_SCROLL_LOCK: action.set_active(not action.get_active()) active = action.get_active() main.console.text_display.scroll_lock = active if active: main.console.text_display.scroll_to_end() action.save_to_preferences() elif action == Actions.CLEAR_CONSOLE: main.console.text_display.clear() elif action == Actions.SAVE_CONSOLE: file_path = FileDialogs.SaveConsole(main, page.file_path).run() if file_path is not None: main.console.text_display.save(file_path) elif action == Actions.TOGGLE_HIDE_DISABLED_BLOCKS: action.set_active(not action.get_active()) flow_graph_update() action.save_to_preferences() page.state_cache.save_new_state(flow_graph.export_data()) Actions.NOTHING_SELECT() elif action == Actions.TOGGLE_AUTO_HIDE_PORT_LABELS: action.set_active(not action.get_active()) action.save_to_preferences() for page in main.get_pages(): page.flow_graph.create_shapes() elif action in (Actions.TOGGLE_SNAP_TO_GRID, Actions.TOGGLE_SHOW_BLOCK_COMMENTS, Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB): action.set_active(not action.get_active()) action.save_to_preferences() elif action == Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY: action.set_active(not action.get_active()) action.save_to_preferences() for page in main.get_pages(): flow_graph_update(page.flow_graph) elif action == Actions.TOGGLE_SHOW_PARAMETER_EXPRESSION: action.set_active(not action.get_active()) action.save_to_preferences() flow_graph_update() elif action == Actions.TOGGLE_SHOW_PARAMETER_EVALUATION: action.set_active(not action.get_active()) action.save_to_preferences() flow_graph_update() elif action == Actions.TOGGLE_HIDE_VARIABLES: action.set_active(not action.get_active()) active = action.get_active() # Either way, triggering this should simply trigger the variable editor # to be visible. varedit = Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR if active: log.debug( "Variables are hidden. Forcing the variable panel to be visible." ) varedit.disable() else: varedit.enable() # Just force it to show. varedit.set_active(True) main.update_panel_visibility(main.VARIABLES) Actions.NOTHING_SELECT() action.save_to_preferences() varedit.save_to_preferences() flow_graph_update() elif action == Actions.TOGGLE_SHOW_BLOCK_IDS: action.set_active(not action.get_active()) active = action.get_active() Actions.NOTHING_SELECT() action.save_to_preferences() flow_graph_update() elif action == Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR: # TODO: There may be issues at startup since these aren't triggered # the same was as Gtk.Actions when loading preferences. action.set_active(not action.get_active()) # Just assume this was triggered because it was enabled. main.update_panel_visibility(main.VARIABLES, action.get_active()) action.save_to_preferences() # Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR.set_enabled(action.get_active()) action.save_to_preferences() elif action == Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR: action.set_active(not action.get_active()) if self.init: Dialogs.MessageDialogWrapper( main, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, markup= "Moving the variable editor requires a restart of GRC." ).run_and_destroy() action.save_to_preferences() elif action == Actions.ZOOM_IN: page.drawing_area.zoom_in() elif action == Actions.ZOOM_OUT: page.drawing_area.zoom_out() elif action == Actions.ZOOM_RESET: page.drawing_area.reset_zoom() ################################################## # Param Modifications ################################################## elif action == Actions.BLOCK_PARAM_MODIFY: selected_block = args[0] if args[0] else flow_graph.selected_block if selected_block: self.dialog = PropsDialog(self.main_window, selected_block) response = Gtk.ResponseType.APPLY while response == Gtk.ResponseType.APPLY: # rerun the dialog if Apply was hit response = self.dialog.run() if response in (Gtk.ResponseType.APPLY, Gtk.ResponseType.ACCEPT): page.state_cache.save_new_state( flow_graph.export_data()) # Following line forces a complete update of io ports flow_graph_update() page.saved = False if response in (Gtk.ResponseType.REJECT, Gtk.ResponseType.ACCEPT): n = page.state_cache.get_current_state() flow_graph.import_data(n) flow_graph_update() if response == Gtk.ResponseType.APPLY: # null action, that updates the main window Actions.ELEMENT_SELECT() self.dialog.destroy() self.dialog = None elif action == Actions.EXTERNAL_UPDATE: page.state_cache.save_new_state(flow_graph.export_data()) flow_graph_update() if self.dialog is not None: self.dialog.update_gui(force=True) page.saved = False elif action == Actions.VARIABLE_EDITOR_UPDATE: page.state_cache.save_new_state(flow_graph.export_data()) flow_graph_update() page.saved = False ################################################## # View Parser Errors ################################################## elif action == Actions.XML_PARSER_ERRORS_DISPLAY: pass ################################################## # Undo/Redo ################################################## elif action == Actions.FLOW_GRAPH_UNDO: n = page.state_cache.get_prev_state() if n: flow_graph.unselect() flow_graph.import_data(n) flow_graph_update() page.saved = False elif action == Actions.FLOW_GRAPH_REDO: n = page.state_cache.get_next_state() if n: flow_graph.unselect() flow_graph.import_data(n) flow_graph_update() page.saved = False ################################################## # New/Open/Save/Close ################################################## elif action == Actions.FLOW_GRAPH_NEW: main.new_page() args = (GLib.Variant('s', 'qt_gui'), ) flow_graph = main.current_page.flow_graph flow_graph.options_block.params['generate_options'].set_value( str(args[0])[1:-1]) flow_graph.options_block.params['author'].set_value(getuser()) flow_graph_update(flow_graph) elif action == Actions.FLOW_GRAPH_NEW_TYPE: main.new_page() if args: flow_graph = main.current_page.flow_graph flow_graph.options_block.params['generate_options'].set_value( str(args[0])[1:-1]) flow_graph_update(flow_graph) elif action == Actions.FLOW_GRAPH_OPEN: file_paths = args[0] if args[0] else FileDialogs.OpenFlowGraph( main, page.file_path).run() if file_paths: # Open a new page for each file, show only the first for i, file_path in enumerate(file_paths): main.new_page(file_path, show=(i == 0)) self.config.add_recent_file(file_path) main.tool_bar.refresh_submenus() main.menu.refresh_submenus() elif action == Actions.FLOW_GRAPH_OPEN_QSS_THEME: file_paths = FileDialogs.OpenQSS( main, self.platform.config.install_prefix + '/share/gnuradio/themes/').run() if file_paths: self.platform.config.default_qss_theme = file_paths[0] elif action == Actions.FLOW_GRAPH_CLOSE: main.close_page() elif action == Actions.FLOW_GRAPH_OPEN_RECENT: file_path = str(args[0])[1:-1] main.new_page(file_path, show=True) self.config.add_recent_file(file_path) main.tool_bar.refresh_submenus() main.menu.refresh_submenus() elif action == Actions.FLOW_GRAPH_SAVE: # read-only or undefined file path, do save-as if page.get_read_only() or not page.file_path: Actions.FLOW_GRAPH_SAVE_AS() # otherwise try to save else: try: self.platform.save_flow_graph(page.file_path, flow_graph) flow_graph.grc_file_path = page.file_path page.saved = True except IOError: Messages.send_fail_save(page.file_path) page.saved = False elif action == Actions.FLOW_GRAPH_SAVE_AS: file_path = FileDialogs.SaveFlowGraph(main, page.file_path).run() if file_path is not None: if flow_graph.options_block.params['id'].get_value( ) == 'default': file_name = os.path.basename(file_path).replace(".grc", "") flow_graph.options_block.params['id'].set_value(file_name) flow_graph_update(flow_graph) page.file_path = os.path.abspath(file_path) try: self.platform.save_flow_graph(page.file_path, flow_graph) flow_graph.grc_file_path = page.file_path page.saved = True except IOError: Messages.send_fail_save(page.file_path) page.saved = False self.config.add_recent_file(file_path) main.tool_bar.refresh_submenus() main.menu.refresh_submenus() elif action == Actions.FLOW_GRAPH_SAVE_COPY: try: if not page.file_path: # Make sure the current flowgraph has been saved Actions.FLOW_GRAPH_SAVE_AS() else: dup_file_path = page.file_path # Assuming .grc extension at the end of file_path dup_file_name = '.'.join( dup_file_path.split('.')[:-1]) + "_copy" dup_file_path_temp = dup_file_name + Constants.FILE_EXTENSION count = 1 while os.path.exists(dup_file_path_temp): dup_file_path_temp = '{}({}){}'.format( dup_file_name, count, Constants.FILE_EXTENSION) count += 1 dup_file_path_user = FileDialogs.SaveFlowGraph( main, dup_file_path_temp).run() if dup_file_path_user is not None: self.platform.save_flow_graph(dup_file_path_user, flow_graph) Messages.send('Saved Copy to: "' + dup_file_path_user + '"\n') except IOError: Messages.send_fail_save( "Can not create a copy of the flowgraph\n") elif action == Actions.FLOW_GRAPH_DUPLICATE: previous = flow_graph # Create a new page main.new_page() page = main.current_page new_flow_graph = page.flow_graph # Import the old data and mark the current as not saved new_flow_graph.import_data(previous.export_data()) flow_graph_update(new_flow_graph) page.state_cache.save_new_state(new_flow_graph.export_data()) page.saved = False elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE: file_path, background_transparent = FileDialogs.SaveScreenShot( main, page.file_path).run() if file_path is not None: try: Utils.make_screenshot(flow_graph, file_path, background_transparent) except ValueError: Messages.send('Failed to generate screen shot\n') ################################################## # Gen/Exec/Stop ################################################## elif action == Actions.FLOW_GRAPH_GEN: self.generator = None if not page.process: if not page.saved or not page.file_path: Actions.FLOW_GRAPH_SAVE( ) # only save if file path missing or not saved if page.saved and page.file_path: generator = page.get_generator() try: Messages.send_start_gen(generator.file_path) generator.write() self.generator = generator except Exception as e: Messages.send_fail_gen(e) elif action == Actions.FLOW_GRAPH_EXEC: if not page.process: Actions.FLOW_GRAPH_GEN() if self.generator: xterm = self.platform.config.xterm_executable if self.config.xterm_missing() != xterm: if not os.path.exists(xterm): Dialogs.show_missing_xterm(main, xterm) self.config.xterm_missing(xterm) if page.saved and page.file_path: # Save config before execution self.config.save() Executor.ExecFlowGraphThread( flow_graph_page=page, xterm_executable=xterm, callback=self.update_exec_stop) elif action == Actions.FLOW_GRAPH_KILL: if page.process: try: page.process.terminate() except OSError: print("could not terminate process: %d" % page.process.pid) elif action == Actions.PAGE_CHANGE: # pass and run the global actions flow_graph_update() elif action == Actions.RELOAD_BLOCKS: self.platform.build_library() main.btwin.repopulate() # todo: implement parser error dialog for YAML # Force a redraw of the graph, by getting the current state and re-importing it main.update_pages() elif action == Actions.FIND_BLOCKS: main.update_panel_visibility(main.BLOCKS, True) main.btwin.search_entry.show() main.btwin.search_entry.grab_focus() elif action == Actions.OPEN_HIER: for b in flow_graph.selected_blocks(): grc_source = b.extra_data.get('grc_source', '') if grc_source: main.new_page(grc_source, show=True) elif action == Actions.BUSSIFY_SOURCES: for b in flow_graph.selected_blocks(): b.bussify('source') flow_graph._old_selected_port = None flow_graph._new_selected_port = None Actions.ELEMENT_CREATE() elif action == Actions.BUSSIFY_SINKS: for b in flow_graph.selected_blocks(): b.bussify('sink') flow_graph._old_selected_port = None flow_graph._new_selected_port = None Actions.ELEMENT_CREATE() elif action == Actions.TOOLS_RUN_FDESIGN: subprocess.Popen('gr_filter_design', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) else: log.warning('!!! Action "%s" not handled !!!' % action) ################################################## # Global Actions for all States ################################################## page = main.current_page # page and flow graph might have changed flow_graph = page.flow_graph if page else None selected_blocks = list(flow_graph.selected_blocks()) selected_block = selected_blocks[0] if selected_blocks else None # update general buttons Actions.ERRORS_WINDOW_DISPLAY.set_enabled(not flow_graph.is_valid()) Actions.ELEMENT_DELETE.set_enabled(bool(flow_graph.selected_elements)) Actions.BLOCK_PARAM_MODIFY.set_enabled(bool(selected_block)) Actions.BLOCK_ROTATE_CCW.set_enabled(bool(selected_blocks)) Actions.BLOCK_ROTATE_CW.set_enabled(bool(selected_blocks)) # update alignment options for act in Actions.BLOCK_ALIGNMENTS: if act: act.set_enabled(len(selected_blocks) > 1) # update cut/copy/paste Actions.BLOCK_CUT.set_enabled(bool(selected_blocks)) Actions.BLOCK_COPY.set_enabled(bool(selected_blocks)) Actions.BLOCK_PASTE.set_enabled(bool(self.clipboard)) # update enable/disable/bypass can_enable = any(block.state != 'enabled' for block in selected_blocks) can_disable = any(block.state != 'disabled' for block in selected_blocks) can_bypass_all = (all(block.can_bypass() for block in selected_blocks) and any(not block.get_bypassed() for block in selected_blocks)) Actions.BLOCK_ENABLE.set_enabled(can_enable) Actions.BLOCK_DISABLE.set_enabled(can_disable) Actions.BLOCK_BYPASS.set_enabled(can_bypass_all) Actions.BLOCK_CREATE_HIER.set_enabled(bool(selected_blocks)) Actions.OPEN_HIER.set_enabled(bool(selected_blocks)) Actions.BUSSIFY_SOURCES.set_enabled(bool(selected_blocks)) Actions.BUSSIFY_SINKS.set_enabled(bool(selected_blocks)) Actions.RELOAD_BLOCKS.enable() Actions.FIND_BLOCKS.enable() self.update_exec_stop() Actions.FLOW_GRAPH_SAVE.set_enabled(not page.saved) main.update() flow_graph.update_selected() page.drawing_area.queue_draw() return True # Action was handled
def show(self): self.window.show_all() if gtk.main_level() == 0: gtk.main()
def handleException(self, dump_info): """ Our own handleException method doing some additional stuff before calling the original python-meh's one. :type dump_info: an instance of the meh.DumpInfo class :see: python-meh's ExceptionHandler.handleException """ log.debug("running handleException") ty = dump_info.exc_info.type value = dump_info.exc_info.value if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \ or (issubclass(ty, OSError) and value.errno == errno.EIO): # hardware fault or '[Errno 5] Input/Output error' hw_error_msg = _("The installation was stopped due to what " "seems to be a problem with your hardware. " "The exact error message is:\n\n%s.\n\n " "The installer will now terminate.") % str(value) self.intf.messageWindow(_("Hardware error occured"), hw_error_msg) sys.exit(0) elif (issubclass(ty, CmdlineError)): cmdline_error_msg = _( "\nThe installation was stopped due to " "incomplete spokes detected while running " "in non-interactive cmdline mode. Since there " "can not be any questions in cmdline mode, " "edit your kickstart file and retry " "installation.\nThe exact error message is: " "\n\n%s.\n\nThe installer will now terminate.") % str(value) # since there is no UI in cmdline mode and it is completely # non-interactive, we can't show a message window asking the user # to acknowledge the error; instead, print the error out and sleep # for a few seconds before exiting the installer print(cmdline_error_msg) time.sleep(10) sys.exit(0) else: try: from gi.repository import Gtk # XXX: Gtk stopped raising RuntimeError if it fails to # initialize. Horay! But will it stay like this? Let's be # cautious and raise the exception on our own to work in both # cases initialized = Gtk.init_check(None)[0] if not initialized: raise RuntimeError() if Gtk.main_level() > 0: # main loop is running, don't crash it by running another one # potentially from a different thread log.debug("Gtk running, queuing exception handler to the " "main loop") GLib.idle_add(self.run_handleException, dump_info) else: log.debug("Gtk not running, starting Gtk and running " "exception handler in it") super(AnacondaExceptionHandler, self).handleException(dump_info) except (RuntimeError, ImportError): log.debug("Gtk cannot be initialized") # X not running (Gtk cannot be initialized) if threadMgr.in_main_thread(): log.debug("In the main thread, running exception handler") print "An unknown error has occured, look at the "\ "/tmp/anaconda-tb* file(s) for more details" # in the main thread, run exception handler super(AnacondaExceptionHandler, self).handleException(dump_info) else: log.debug("In a non-main thread, sending a message with " "exception data") # not in the main thread, just send message with exception # data and let message handler run the exception handler in # the main thread exc_info = dump_info.exc_info hubQ.send_exception( (exc_info.type, exc_info.value, exc_info.stack))
def do_quit(self): '''Quit zim.''' if Gtk.main_level() > 0: Gtk.main_quit()
def handleException(self, dump_info): """ Our own handleException method doing some additional stuff before calling the original python-meh's one. :type dump_info: an instance of the meh.DumpInfo class :see: python-meh's ExceptionHandler.handleException """ log.debug("running handleException") ty = dump_info.exc_info.type value = dump_info.exc_info.value if (issubclass(ty, blivet.errors.StorageError) and value.hardware_fault) \ or (issubclass(ty, OSError) and value.errno == errno.EIO): # hardware fault or '[Errno 5] Input/Output error' hw_error_msg = _("The installation was stopped due to what " "seems to be a problem with your hardware. " "The exact error message is:\n\n%s.\n\n " "The installer will now terminate.") % str(value) self.intf.messageWindow(_("Hardware error occured"), hw_error_msg) sys.exit(0) else: try: from gi.repository import Gtk # XXX: Gtk stopped raising RuntimeError if it fails to # initialize. Horay! But will it stay like this? Let's be # cautious and raise the exception on our own to work in both # cases initialized = Gtk.init_check(None)[0] if not initialized: raise RuntimeError() if Gtk.main_level() > 0: # main loop is running, don't crash it by running another one # potentially from a different thread log.debug("Gtk running, queuing exception handler to the " "main loop") GLib.idle_add(self.run_handleException, dump_info) else: log.debug("Gtk not running, starting Gtk and running " "exception handler in it") super(AnacondaExceptionHandler, self).handleException( dump_info) except RuntimeError: log.debug("Gtk cannot be initialized") # X not running (Gtk cannot be initialized) if threadMgr.in_main_thread(): log.debug("In the main thread, running exception handler") print "An unknown error has occured, look at the "\ "/tmp/anaconda-tb* file(s) for more details" # in the main thread, run exception handler super(AnacondaExceptionHandler, self).handleException( dump_info) else: log.debug("In a non-main thread, sending a message with " "exception data") # not in the main thread, just send message with exception # data and let message handler run the exception handler in # the main thread exc_info = dump_info.exc_info hubQ.send_exception((exc_info.type, exc_info.value, exc_info.stack))
def is_running(): return bool(gtk.main_level())
def do_start_XpraClient(self, conn, display_desc): log("do_start_XpraClient(%s, %s) client=%s", conn, display_desc, self.client) self.client.encoding = self.config.encoding self.client.display_desc = display_desc self.client.init_ui(self.config) self.client.setup_connection(conn) self.set_info_text("Connection established") log("start_XpraClient() client initialized") if self.config.password: self.client.password = self.config.password def do_quit(*args): log("do_quit%s", args) self.clean_client() self.destroy() Gtk.main_quit() def handle_client_quit(exit_launcher=False): w = self.window log("handle_quit(%s) window=%s", exit_launcher, w) self.clean_client() if exit_launcher: #give time for the main loop to run once after calling cleanup GLib.timeout_add(100, do_quit) else: if w: self.set_sensitive(True) GLib.idle_add(w.show) def reconnect(exit_code): log("reconnect(%s) config reconnect=%s", EXIT_STR.get(exit_code, exit_code), self.config.reconnect) if not self.config.reconnect or exit_code not in RETRY_EXIT_CODES: return False self.clean_client() #give time for the main loop to run once after calling cleanup GLib.timeout_add(100, self.start_client, display_desc) return True def warn_and_quit_override(exit_code, warning): log("warn_and_quit_override(%s, %s)", exit_code, warning) password_warning = warning.find("invalid password") >= 0 if password_warning: self.password_warning() elif reconnect(exit_code): return if self.exit_code is None: self.exit_code = exit_code err = exit_code != 0 or password_warning if not self.current_error: self.current_error = warning self.set_info_color(err) self.set_info_text(warning) handle_client_quit(not err) def quit_override(exit_code): log("quit_override(%s)", exit_code) if reconnect(exit_code): return if self.exit_code is None: self.exit_code = exit_code handle_client_quit(self.exit_code == 0) self.client.warn_and_quit = warn_and_quit_override self.client.quit = quit_override def after_handshake(): self.set_info_text("Handshake complete") self.client.after_handshake(after_handshake) def first_ui_received(*_args): self.set_info_text("Running") self.window.hide() self.client.connect("first-ui-received", first_ui_received) if Gtk.main_level() > 0: #no need to start a new main loop: self.client.gtk_main = noop try: r = self.client.run() log("client.run() returned %s", r) except Exception as e: log.error("client error", exc_info=True) self.handle_exception(e) if self.client.gtk_main == noop: return log("exit_launcher=%s", self.exit_launcher) #if we're using "autoconnect", #the main loop was running from here, #so we have to force exit if the launcher window had been closed: if self.exit_launcher: sys.exit(0)