def test_formatter(self): """ Test setting the formatter of a handler. """ if not QtApplication.instance(): QtApplication() core = self.workbench.get_plugin(u'enaml.workbench.core') model = PanelModel() handler = GuiHandler(model=model) core.invoke_command(u'hqc_meas.logging.add_handler', { 'id': 'ui', 'handler': handler, 'logger': 'test' }, self) formatter = logging.Formatter('toto : %(message)s') core.invoke_command(u'hqc_meas.logging.set_formatter', { 'formatter': formatter, 'handler_id': 'ui' }, self) logger = logging.getLogger('test') logger.info('test') app = QtApplication.instance()._qapp app.flush() app.processEvents() core.invoke_command(u'hqc_meas.logging.remove_handler', {'id': 'ui'}, self) assert_equal(model.text, 'toto : test\n')
def test_formatter(self): """ Test setting the formatter of a handler. """ if not QtApplication.instance(): QtApplication() core = self.workbench.get_plugin(u'enaml.workbench.core') model = PanelModel() handler = GuiHandler(model=model) core.invoke_command(u'hqc_meas.logging.add_handler', {'id': 'ui', 'handler': handler, 'logger': 'test'}, self) formatter = logging.Formatter('toto : %(message)s') core.invoke_command(u'hqc_meas.logging.set_formatter', {'formatter': formatter, 'handler_id': 'ui'}, self) logger = logging.getLogger('test') logger.info('test') app = QtApplication.instance()._qapp app.flush() app.processEvents() core.invoke_command(u'hqc_meas.logging.remove_handler', {'id': 'ui'}, self) assert_equal(model.text, 'toto : test\n')
def test_logger_thread(): """ Test the logger thread. """ logger = logging.getLogger('test') queue = Queue() handler = QueueHandler(queue) logger.addHandler(handler) logger.info('test') logger.removeHandler(handler) queue.put(None) model = PanelModel() handler = GuiHandler(model) logger.addHandler(handler) thread = QueueLoggerThread(queue) thread.start() thread.join(2) if thread.is_alive(): raise qapp = QtApplication.instance()._qapp qapp.flush() qapp.processEvents() assert_equal(model.text, 'test\n')
def make_tex_file(self): """saves the tex file using the latest version of input_code and tex_list if the GUI is active. also saves a copy of the input_code with the preamble and postamble reattached""" if QtApplication.instance() is not None: self.process_source() self.simulate_tex() self.save_file.save(self.tex_list, write_mode="w", flush_buffer=True) self.save_code.save(["\n".join(self.file_reader.preamble), self.input_code, "\n".join(self.file_reader.postamble)], write_mode="w", flush_buffer=True)
def process_app_events(): """Manually run the Qt event loop so that windows are shown and event propagated. """ qapp = QtApplication.instance()._qapp qapp.flush() qapp.processEvents() qapp.sendPostedEvents()
def close_all_windows(): qapp = QtApplication.instance()._qapp qapp.flush() qapp.processEvents() sleep(0.1) for window in Window.windows: window.close() qapp.flush() qapp.processEvents()
def setUp(self): qt_app = QApplication.instance() if qt_app is None: qt_app = QApplication([]) self.qt_app = qt_app enaml_app = QtApplication.instance() if enaml_app is None: enaml_app = QtApplication() self.enaml_app = enaml_app self.event_loop_helper = EventLoopHelper(qt_app=self.qt_app)
def qt_app(): """Make sure a QtApplication is active. """ app = QtApplication.instance() if app is None: app = QtApplication() yield app app.stop() else: yield app
def _observe_name(self, change): from enaml.qt.qt_application import QtApplication app = QtApplication.instance() from declaracad.occ import api self.declaration = getattr(api, self.name) factory = app.resolver.factories.get(self.name) if factory: self.proxy = factory() self.doc = inspect.getdoc(self.declaration)
def app(): """Make sure a QtApplication is active. """ app = QtApplication.instance() if app is None: app = QtApplication() yield app app.stop() else: yield app
def make_tex_file(self): """saves the tex file using the latest version of input_code and tex_list if the GUI is active. also saves a copy of the input_code with the preamble and postamble reattached""" self.plots_to_save=[] if QtApplication.instance() is not None: self.process_source() self.simulate_tex() self.save_file.save(self.tex_list, write_mode="w", flush_buffer=True) for pl in self.plots_to_save: pl.savefig(dir_path=self.folder.dir_path+self.folder.divider, fig_name=pl.fig_name) self.interact.get_member("code_str").reset(self) self.save_code.save(self.interact.code_str, write_mode="w", flush_buffer=True)
def display_startup_error_dialog(text, content, details=''): """Show a nice dialog showing to the user what went wrong during start up. """ if not QtApplication.instance(): QtApplication() # pragma: no cover dial = MessageBox(title='Ecpy failed to start', text=text, content=content, details=details, buttons=[DialogButton(str('Close'), str('reject'))]) dial.exec_() sys.exit(1)
def display_startup_error_dialog(text, content, details=''): """Show a nice dialog showing to the user what went wrong during start up. """ if not QtApplication.instance(): QtApplication() # pragma: no cover dial = MessageBox() dial = MessageBox(title='Ecpy failed to start', text=text, content=content, details=details, buttons=[DialogButton(str('Close'), str('reject'))]) dial.exec_() sys.exit(1)
def make_tex_file(self): """saves the tex file using the latest version of input_code and tex_list if the GUI is active. also saves a copy of the input_code with the preamble and postamble reattached""" self.plots_to_save = [] if QtApplication.instance() is not None: self.process_source() self.simulate_tex() self.save_file.save(self.tex_list, write_mode="w", flush_buffer=True) for pl in self.plots_to_save: pl.savefig(dir_path=self.folder.dir_path + self.folder.divider, fig_name=pl.fig_name) self.interact.get_member("code_str").reset(self) self.save_code.save(self.interact.code_str, write_mode="w", flush_buffer=True)
def qt_app(): """Make sure a QtApplication is active. """ try: from enaml.qt.qt_application import QtApplication except Exception: pytest.skip('No Qt binding found: %s' % format_exc()) app = QtApplication.instance() if app is None: app = QtApplication() yield app app.stop() else: yield app
def shower(*agents, **kwargs): """A powerful showing function for any Atom object(s) specified in agents. Checks if an object has a view_window and otherwise uses a default window for the object. Checks kwargs for particular keywords: * ``start_it``: boolean representing whether to go through first time setup prior to starting app * ``app``: defaults to existing QtApplication instance and will default to a new instance if none exists chief_cls: if not included defaults to the first agent and defaults to Backbone if no agents are passed. show_log: shows the log_window of chief_cls if it has one, defaults to not showing show_ipy: shows the interactive_window of chief_cls if it has one, defaults to not showing show_code: shows the code_window of chief_cls if it has one, defaults to not showing shower also provides a chief_window (generally for controlling which agents are visible) which defaults to Backbone's chief_window if chief_cls does not have one. attributes of chief_window can be modified with the remaining kwargs""" start_it=kwargs.pop("start_it", False) app=QtApplication.instance() if app is None: app = QtApplication() start_it=True for n, agent in enumerate(agents): #view=get_view_window(agent, default_name="window_{0}".format(n)) view=getattr(agent, "view_window", None) if view is None: view=AutoAgentView(agent=agent) view.name=getattr(agent, "name", "window_{0}".format(n)) if view.title=="": view.title=view.name view.show() if start_it: chief_cls=kwargs.pop("chief_cls", agents[0] if agents!=() else Backbone) chief_view=getattr(chief_cls, "chief_window", Backbone.chief_window) chief_view.chief_cls=chief_cls for key in kwargs: setattr(chief_view, key, kwargs[key]) chief_view.show() if hasattr(chief_cls, "interact"): chief_cls.interact.make_input_code() try: app.start() finally: if hasattr(chief_cls, "clean_up"): chief_cls.clean_up()
def shower(*agents, **kwargs): """A powerful showing function for any Atom object(s) specified in agents. Checks if an object has a view_window and otherwise uses a default window for the object. Checks kwargs for particular keywords: * ``start_it``: boolean representing whether to go through first time setup prior to starting app * ``app``: defaults to existing QtApplication instance and will default to a new instance if none exists chief_cls: if not included defaults to the first agent and defaults to Backbone if no agents are passed. show_log: shows the log_window of chief_cls if it has one, defaults to not showing show_ipy: shows the interactive_window of chief_cls if it has one, defaults to not showing show_code: shows the code_window of chief_cls if it has one, defaults to not showing shower also provides a chief_window (generally for controlling which agents are visible) which defaults to Backbone's chief_window if chief_cls does not have one. attributes of chief_window can be modified with the remaining kwargs""" start_it = kwargs.pop("start_it", False) app = QtApplication.instance() if app is None: app = QtApplication() start_it = True with imports(): from taref.core.agent_e import AutoAgentView for n, agent in enumerate(agents): view = get_view_window(agent, AutoAgentView(agent=agent), "window_{0}".format(n)) view.show() if start_it: chief_cls = kwargs.pop("chief_cls", agents[0] if agents != () else Backbone) chief_view = getattr(chief_cls, "chief_window", Backbone.chief_window) chief_view.chief_cls = chief_cls for key in kwargs: setattr(chief_view, key, kwargs[key]) chief_view.show() if hasattr(chief_cls, "interact"): chief_cls.interact.make_input_code() try: app.start() finally: if hasattr(chief_cls, "clean_up"): chief_cls.clean_up()
def test_stream_redirection2(): """ Test the redirection of a stream toward a logger : DEBUG. """ model = PanelModel() handler = GuiHandler(model) logger = logging.getLogger('test') logger.addHandler(handler) qapp = QtApplication.instance()._qapp stdout = sys.stdout sys.stdout = StreamToLogRedirector(logger) try: print '<DEBUG>test' finally: sys.stdout = stdout qapp.flush() qapp.processEvents() assert_equal(model.text, 'DEBUG: test\n')
def test_stream_redirection6(): """ Test the redirection of a stream toward a logger, stderr. """ model = PanelModel() handler = GuiHandler(model) logger = logging.getLogger('test') logger.addHandler(handler) qapp = QtApplication.instance()._qapp stdout = sys.stdout sys.stdout = StreamToLogRedirector(logger, stream_type='stderr') try: print '<CRITICAL>test' finally: sys.stdout = stdout qapp.flush() qapp.processEvents() answer = 'An error occured please check the log file for more details.\n' assert_equal(model.text, answer)
def test_gui_handler(): """ Test the gui handler. """ model = PanelModel() handler = GuiHandler(model) logger = logging.getLogger('test') logger.addHandler(handler) qapp = QtApplication.instance()._qapp logger.info('test') qapp.flush() qapp.processEvents() assert_equal(model.text, 'test\n') model.text = '' logger.debug('test') qapp.flush() qapp.processEvents() assert_equal(model.text, 'DEBUG: test\n') model.text = '' logger.warn('test') qapp.flush() qapp.processEvents() assert_equal(model.text, 'WARNING: test\n') model.text = '' logger.error('test') qapp.flush() qapp.processEvents() assert_equal(model.text, 'ERROR: test\n') model.text = '' logger.critical('test') qapp.flush() qapp.processEvents() answer = 'An error occured please check the log file for more details.\n' assert_equal(model.text, answer) model.text = ''
if i == 1: axis = self.widget.plotItem.getAxis('right') elif i > 1: axis = AxisItem('right') axis.setZValue(-10000) self.widget.plotItem.layout.addItem(axis, 2, 3) axis.linkToView(view) view.setXLink(self.widget.plotItem) view.addItem(PlotCurveItem(**plot)) else: self.widget.plot(**plot) if i > 0: def syncViews(): for v in views: v.setGeometry(self.widget.plotItem.vb.sceneBoundingRect()) v.linkedViewChanged(self.widget.plotItem.vb, v.XAxis) syncViews() self.widget.plotItem.vb.sigResized.connect(syncViews) self._views = views def plot_view_factory(): return QtPlotView # Inject the factory QtApplication.instance().resolver.factories.update( {'PlotView': plot_view_factory})
class Backbone(Atom): """ tarefdoc-process-docstring Class combining primary functions for viewer operation. Extends __init__ to allow extra setup. extends __setattr__ to perform low/high check on params""" __metaclass__ = BackboneAtomMeta unit_dict = UNIT_DICT app = QtApplication.instance() @private_property def view_window(self): return AutoAgentView(agent=self) chief_window = BasicView() interact = Interact() @private_property def reserved_names(self): return get_reserved_names(self) @private_property def all_params(self): return get_all_params(self) @private_property def all_main_params(self): return get_all_main_params(self) @private_property def main_params(self): """defaults to all members in all_params that are not tagged as sub. Can be overwritten to allow some minimal custom layout control, e.g. order of presentation and which members are shown. Use all_main_params to get a list of all members that could be in main_params""" return self.all_main_params @private_property def property_dict(self): """returns a dict mapping property_names to Property items""" return dict([(name, self.get_member(name)) for name in self.all_params if isinstance(self.get_member(name), Property)]) @private_property def property_names(self): """returns property_dict.keys() (cached)""" return self.property_dict.keys() @private_property def property_values(self): """returns property dict.values() (cached)""" return self.property_dict.values() def extra_setup(self, param, typer): """Performs extra setup during initialization where param is name of parameter and typer is it's Atom type. Can be customized in child classes. default extra setup handles units, auto tags low and high for Ranges, and makes Callables into instancemethods""" setup_callables(self, param, typer) setup_ranges(self, param, typer) setup_units(self, param, typer) # def call_func(self, name, **kwargs): # """calls a func using keyword assignments. If name corresponds to a Property, calls the get func. # otherwise, if name_mangled func "_get_"+name exists, calls that. Finally calls just the name if these are not the case""" # if name in self.property_names: # return self.property_dict[name].fget(self, **kwargs) # elif name in self.all_params and hasattr(self, "_get_"+name): # return getattr(self, "_get_"+name)(self, **kwargs) # return getattr(self, name)(**kwargs) def __setattr__(self, name, value): """uses __setattr__ perform lowhigh_check on all_params""" if name in self.all_params: value = lowhigh_check(self, name, value) super(Backbone, self).__setattr__(name, value) def instancemethod(self, func): """decorator for adding instancemethods defined outside of class (meant for Callables)""" make_instancemethod(self, func) def __init__(self, **kwargs): """extends __init__ to allow extra setup for all params""" super(Backbone, self).__init__(**kwargs) for param in self.all_params: typer = get_type(self, param) self.extra_setup(param, typer) def latex_table_entry(self, param=None, value=None, expression=None, comment=None): if param is None: return [self.name, r"Value", r"Expression", r"Comment"] tex_str = get_tag(self, param, "tex_str") if tex_str is None: tex_str = param.replace("_", " ") label = get_tag(self, param, "label") if label is not None: tex_str = label + ", " + tex_str unit = get_tag(self, param, "unit") if value is None: if unit is None: if type(getattr(self, param)) in (int, float, float64): value = (r"{0:." + str(get_tag(self, param, "precision", 4)) + "g}").format(getattr(self, param)) else: value = str(getattr(self, param)) else: value = unit.show_unit( getattr(self, param) / unit, get_tag(self, param, "precision", 4)) if expression is None: expression = get_tag(self, param, "expression", r"{}") if comment is None: comment = get_tag(self, param, "desc", r"{}") return [tex_str, value, expression, comment] def latex_table(self, param_list=None): if param_list is None: param_list = self.main_params lt = [self.latex_table_entry()] for param in param_list: lt.append(self.latex_table_entry(param)) return lt def latex_table2(self, param_list=None): if param_list is None: param_list = self.main_params lt = [ [self.name, r"Value", r"Expression", r"Comment"], ] for param in param_list: unit = get_tag(self, param, "unit") #print param, type(getattr(self, param)) in (int, float, float64) if type(getattr(self, param)) in (int, float, float64): format_str = getattr(unit, "format_str", r"{0:.3g}") else: format_str = getattr(unit, "format_str", "{0}") print param, format_str if unit is not None: unit.show_unit() value = getattr(self, param) / unit else: value = getattr(self, param) tex_str = get_tag(self, param, "tex_str") if tex_str is None: tex_str = param.replace("_", " ") label = get_tag(self, param, "label") if label is not None: tex_str = label + ", " + tex_str lt.append([ tex_str, format_str.format(value), get_tag(self, param, "expression", r"{}"), get_tag(self, param, "desc", r"{}") ]) return lt
def process_app_events(): qapp = QtApplication.instance()._qapp qapp.flush() qapp.processEvents()
views.append(view) self.widget.plotItem.scene().addItem(view) if i==1: axis = self.widget.plotItem.getAxis('right') elif i>1: axis = AxisItem('right') axis.setZValue(-10000) self.widget.plotItem.layout.addItem(axis,2,3) axis.linkToView(view) view.setXLink(self.widget.plotItem) view.addItem(PlotCurveItem(**plot)) else: #view.setYLink(self.widget.plotItem) self.widget.plot(**plot) if i>0: def syncViews(): for v in views: v.setGeometry(self.widget.plotItem.vb.sceneBoundingRect()) v.linkedViewChanged(self.widget.plotItem.vb,v.XAxis) syncViews() self.widget.plotItem.vb.sigResized.connect(syncViews) self._views = views def plot_view_factory(): return QtPlotView # Inject the factory from enaml.qt.qt_application import QtApplication QtApplication.instance().resolver.factories.update({ 'PlotView': plot_view_factory })