def test_show_monitors(exopy_qtbot, execution_view, dialog_sleep):
    """Test restoring the monitor window.

    """
    execution_view.show()
    wait_for_window_displayed(exopy_qtbot, execution_view)
    exopy_qtbot.wait(dialog_sleep)

    item = execution_view.widget

    mon_btn = item.dock_widget().widgets()[5]
    assert not mon_btn.enabled

    with enaml.imports():
        from exopy.measurement.workspace.monitors_window import MonitorsWindow

    meas = item.workspace.plugin.enqueued_measurements.measurements[0]
    mon_win = MonitorsWindow(item, measurement=meas)
    item.workspace.plugin.processor.monitors_window = mon_win

    assert not mon_win.visible

    mon_btn.clicked = True

    def assert_visible():
        assert mon_win.visible

    exopy_qtbot.wait_until(assert_visible)
Exemple #2
0
 def show(self):
    with imports():
        from e_Plotter import PlotMain
    app = QtApplication()
    view = PlotMain(plotr=self)
    view.show()
    app.start()
Exemple #3
0
    def _explore_views(self, modules, views, mod_var, failed):
        """ Explore a list of modules, looking for views.

        Parameters
        ----------
        modules : list
            The list of modules to explore

        views : dict
            A dict in which discovered views will be stored.

        mod_var : str
            Name of the module variable to look for.

        failed : list
            A list in which failed imports will be stored.

        """
        for mod in modules:
            try:
                with enaml.imports():
                    m = import_module('.' + mod, MODULE_ANCHOR)
            except Exception as e:
                log = logging.getLogger(__name__)
                mess = 'Failed to import {} : {}'.format(mod, e)
                log.error(mess)
                failed[mod] = mess
                continue

            if hasattr(m, mod_var):
                views.update(getattr(m, mod_var))
Exemple #4
0
def init_ui(data_muggler):
    """ Do the enaml import and set up of the UI

    Parameters
    ----------
    data_muggler : replay.pipeline.DataMuggler
    """
    with enaml.imports():
        from pipeline_w2d import PipelineView

    histogram_model = HistogramModel()
    c_c_combo_fitter = MultiFitController(valid_models=valid_models)
    scalar_collection = ScalarCollection()
    scalar_collection.data_muggler = data_muggler
    scalar_collection.multi_fit_controller = c_c_combo_fitter
    cs_model = CrossSectionModel(data_muggler=data_muggler,
                                 histogram_model=histogram_model)
    view = PipelineView(histogram_model=histogram_model)
    histogram_model.cmap = cs_model.cmap
    # provide the pipeline view with its attributes
    view.scalar_collection=scalar_collection
    view.multi_fit_controller = c_c_combo_fitter
    view.cs_model = cs_model
    view.start_observation = start_observation
    view.stop_observation = stop_observation
    view.clear_data = clear_datamuggler
    view.reinit_data = init_datamuggler
    cmap = cs_model.cmap
    cs_model.cmap = 'gray'
    cs_model.cmap = cmap
    return view
def show(a):
    app = QtApplication()
    with imports():
        from e_FundTemps import Main
    view=Main(instr=a)
    view.show()
    app.start() 
Exemple #6
0
    def load_plugins(self):
        """ Load all the plugins Inkcut is dependent on """
        w = self.workbench
        plugins = []
        with enaml.imports():
            #: TODO autodiscover these
            from inkcut.preview.manifest import PreviewManifest
            from inkcut.job.manifest import JobManifest
            from inkcut.device.manifest import DeviceManifest
            from inkcut.joystick.manifest import JoystickManifest
            from inkcut.console.manifest import ConsoleManifest
            from inkcut.monitor.manifest import MonitorManifest
            plugins.append(PreviewManifest)
            plugins.append(JobManifest)
            plugins.append(DeviceManifest)
            plugins.append(JoystickManifest)
            plugins.append(ConsoleManifest)
            plugins.append(MonitorManifest)

            #: Load any plugins defined as extension points
            for entry_point in pkg_resources.iter_entry_points(
                    group='inkcut.plugin', name=None):
                plugins.append(entry_point.load())

        #: Install all of them
        for Manifest in plugins:
            w.register(Manifest())
Exemple #7
0
def test_tree_widget(exopy_qtbot):
    """Test the ConditionalTask view.

    """
    with enaml.imports():
        from .test_tree_widget import Main
    show_and_close_widget(exopy_qtbot, Main())
Exemple #8
0
def main():
    with enaml.imports():
        from sample_plugin import SampleManifest

    workbench = UIWorkbench()
    workbench.register(SampleManifest())
    workbench.run()
Exemple #9
0
def test_zipimport_subpackage():
    with enaml.imports():
        # Test import from libary.zip/package/form.enaml
        from package import form
        
        # Test import from libary.zip/package/subpackage/slider.enaml
        from package.subpackage import slider
def show(*agents):
    app = QtApplication()
    with imports():
        from e_Show import defaultView, showView, basicView#, LogWindow
    loc_chief=None
    for n, a in enumerate(agents):
        if hasattr(a, "view_window"):
            view=a.view_window
        else:
            view=defaultView(agent=a)
        if hasattr(a, "name"):
            view.name=a.name
        else:
            view.name="agent_{0}".format(n)
        if hasattr(a, "chief"):
            loc_chief=a.chief
        view.title=view.name
        view.show()
        if loc_chief is not None:
            if loc_chief.show_all or n==0:
                view.visible=True
    if loc_chief is None:
        view=basicView(title="Show Control", name="show_control")
    else:
        if hasattr(loc_chief, "view_window"):
            view=loc_chief.view_window
        else:
            view=showView(title="ShowControl", name="show_control", chief=loc_chief)
    view.show()

    app.start()
Exemple #11
0
def main():
    tile_layer = MBTileManager(filename = 'map.mbtiles',
                               min_level = 2,
                               max_level = 4)

    tile_layer = HTTPTileManager(min_level=0, max_level=15,
                              server='d.tiles.mapbox.com',
                              url='/v3/mapbox.mapbox-simple/%(zoom)d/%(row)d/%(col)d.png')

    canvas = MappingCanvas(tile_cache = tile_layer)
    canvas.overlays.append(GeoJSONOverlay(component=canvas,
                                          geojs_filename='counties.geojs'))

    viewport = MappingViewport(component=canvas, zoom_level=2,
                               geoposition=(37.09024, -95.712891))
    viewport.tools.append(ViewportPanTool(viewport))

    model = SingleMap(canvas=canvas,
                      viewport=viewport)

    import enaml
    with enaml.imports():
        from simple_view import Map
    window = Map(model=model)
    window.show()
def show(obj):
    with imports():
            from e_Electron import AtomMain
    app = QtApplication()
    view = AtomMain(elect=obj)
    view.show()
    app.start()
Exemple #13
0
def test_zipimport_module_from_cache(enaml_qtbot, enaml_sleep, zip_library):
    with enaml.imports():
        # Test import from
        # library.zip/__enamlcache__/slider-enaml-py<ver>-cv<ver>.enamlc
        import splitter

    assert_window_displays(enaml_qtbot, enaml_sleep, splitter.Main())
Exemple #14
0
def test_zipimport_package_from_cache(enaml_qtbot, enaml_sleep, zip_library):
    with enaml.imports():
        # Test import from enamlcache subpackage within zip
        # Test import from library.zip/package/subpackage/__enamlcache__/
        #                                 notebook-enaml-py<ver>-cv<ver>.enamlc
        from package.subpackage import notebook
    assert_window_displays(enaml_qtbot, enaml_sleep, notebook.Main())
def show(self):
    with imports():
            from e_Boss import AtomMain
    app = QtApplication()
    view = AtomMain(instr=self)
    view.show()
    app.start()
Exemple #16
0
def main():
    with enaml.imports():
        from widget_gallery import WidgetGallery

    img_path = os.path.join(os.path.dirname(__file__), "lena.png")
    view = WidgetGallery(fs_model=FSModel(), sin_plot=make_sin_plot(), html_data=make_html_table(), img_path=img_path)
    view.show()
def show_boss(self, instr=None):
    with imports():
        from e_Boss import BossMain
    app = QtApplication()
    view = BossMain(myinstr=instr, boss=self)
    view.show()
    app.start()
def ask_text(title, message, text='', parent=None):
    with enaml.imports():
        from enamlext.widgets._text_input_dialog import TextInputDialog
        dlg = TextInputDialog(parent=parent, title=title, message=message,
                              text=text)
        if dlg.exec_():
            return dlg.text
Exemple #19
0
    def test_load4(self, app_dir, monkeypatch):
        """Test loading preferences from non-default file for started plugin.

        """
        self.workbench.register(PreferencesManifest())
        c_man = PrefContributor()
        self.workbench.register(c_man)
        contrib = self.workbench.get_plugin(c_man.id)

        prefs_path = os.path.join(app_dir, 'preferences')
        path = os.path.join(prefs_path, 'custom.ini')
        conf = ConfigObj(path)
        conf[c_man.id] = {}
        conf[c_man.id]['string'] = 'test'
        conf.write()

        assert contrib.string == ''

        @classmethod
        def answer(*args, **kwargs):
            return path

        with enaml.imports():
            from ecpy.app.preferences.manifest import FileDialogEx
        monkeypatch.setattr(FileDialogEx, 'get_open_file_name', answer)
        core = self.workbench.get_plugin('enaml.workbench.core')
        core.invoke_command('ecpy.app.preferences.load',
                            {'path': prefs_path, 'ask_user': True}, self)

        assert contrib.string == 'test'
        assert self.workbench.get_plugin(PLUGIN_ID).last_directory == \
            prefs_path
def show(*agents):
    """a powerful showing function for any Atom object(s). Checks if object has a view_window property and otherwise uses a default.
    also provides a show control of the objects"""
    app = QtApplication()
    with imports():
        from chief_e import agentView, chiefView, basicView#, LogWindow
    loc_chief=None
    for n, a in enumerate(agents):
        if hasattr(a, "view_window"):
            view=a.view_window
        else:
            view=agentView(agent=a)
        if hasattr(a, "name"):
            view.name=a.name
        else:
            view.name="agent_{0}".format(n)
        if hasattr(a, "chief"):
            loc_chief=a.chief
        view.title=view.name
        view.show()
        if loc_chief is not None:
            if loc_chief.show_all or n==0:
                view.visible=True
    if loc_chief is None:
        view=basicView(title="Show Control", name="show_control")
    else:
        if hasattr(loc_chief, "view_window"):
            view=loc_chief.view_window
        else:
            view=chiefView(title="ShowControl", name="show_control", chief=loc_chief)
    view.show()
    app.start()
Exemple #21
0
    def test_save3(self, app_dir, monkeypatch):
        """Test saving to a specific file.

        """
        self.workbench.register(PreferencesManifest())
        c_man = PrefContributor()
        self.workbench.register(c_man)

        contrib = self.workbench.get_plugin(c_man.id)
        contrib.string = 'test_save'

        prefs_path = os.path.join(app_dir, 'preferences')
        path = os.path.join(prefs_path, 'custom.ini')

        @classmethod
        def answer(*args, **kwargs):
            return path

        with enaml.imports():
            from ecpy.app.preferences.manifest import FileDialogEx
        monkeypatch.setattr(FileDialogEx, 'get_save_file_name', answer)
        core = self.workbench.get_plugin('enaml.workbench.core')
        core.invoke_command('ecpy.app.preferences.save', {'path': prefs_path,
                                                          'ask_user': True})

        ref = {c_man.id: {'string': 'test_save', 'auto': ''}}
        assert os.path.isfile(path)
        assert ConfigObj(path).dict() == ref
        assert self.workbench.get_plugin(PLUGIN_ID).last_directory == \
            prefs_path
Exemple #22
0
def test_zipimport_cache():
    with enaml.imports():
        # Test import from enamlcache file within zip
        import splitter
        
        # Test import from subpackage within zip
        from package.subpackage import notebook
Exemple #23
0
    def start(self):
        """ Load all the plugins the device is dependent on """
        w = self.workbench
        plugins = []
        with enaml.imports():
            from .transports.raw.manifest import RawFdManifest
            from .transports.serialport.manifest import SerialManifest
            from .transports.printer.manifest import PrinterManifest
            from .transports.disk.manifest import FileManifest
            from inkcut.device.protocols.manifest import ProtocolManifest
            from inkcut.device.drivers.manifest import DriversManifest
            from inkcut.device.filters.manifest import FiltersManifest
            from inkcut.device.pi.manifest import PiManifest
            plugins.append(RawFdManifest)
            plugins.append(SerialManifest)
            plugins.append(PrinterManifest)
            plugins.append(FileManifest)
            plugins.append(ProtocolManifest)
            plugins.append(DriversManifest)
            plugins.append(FiltersManifest)
            plugins.append(PiManifest)

        for Manifest in plugins:
            w.register(Manifest())

        #: This refreshes everything else
        self._refresh_extensions()

        #: Restore state after plugins are loaded
        super(DevicePlugin, self).start()
Exemple #24
0
def initialize_default(extra_manifests,
                       workspace='psi.experiment.workspace'):

    with enaml.imports():
        from enaml.workbench.core.core_manifest import CoreManifest
        from enaml.workbench.ui.ui_manifest import UIManifest

        from psi.context.manifest import ContextManifest
        from psi.data.manifest import DataManifest
        from psi.experiment.manifest import ExperimentManifest

    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        workbench = Workbench()
        workbench.register(CoreManifest())
        workbench.register(UIManifest())
        workbench.register(ContextManifest())
        workbench.register(DataManifest())
        workbench.register(ExperimentManifest())
        for manifest in extra_manifests:
            workbench.register(manifest())

        core = workbench.get_plugin('enaml.workbench.core')
        ui = workbench.get_plugin('enaml.workbench.ui')
        ui.show_window()
        core.invoke_command('enaml.workbench.ui.select_workspace',
                            {'workspace': workspace})

        experiment = workbench.get_plugin('psi.experiment')
        return workbench
Exemple #25
0
def main():
    import argparse
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=__doc__,
    )
    parser.add_argument('-c', '--component', default='MainWindow',
        help="The component to view.")
    parser.add_argument('-t', '--toolkit', default='default',
        choices=['default', 'wx', 'qt', 'muntjac'],
        help='The toolkit backend to use')
    parser.add_argument('enaml_file', help='The .enaml file to show.')

    args = parser.parse_args()

    with open(args.enaml_file) as f:
        enaml_code = f.read()
    ast = parse(enaml_code)
    ns = {}

    with enaml.imports():
        EnamlCompiler.compile(ast, ns)

    with toolkits[args.toolkit]():
        if 'main' in ns:
            ns['main']()
        else:
            component = ns[args.component]
            window = component()
            window.show()
 def create_and_show():
     with enaml.imports():
         from .enaml.test_simple import Main
         w = Main()
         w.show()
         process_app_events()
         w.close()
Exemple #27
0
    def _explore_views(self, modules, views, interface_views, failed):
        """ Explore a list of modules, looking for views.

        Parameters
        ----------
        modules : list
            The list of modules to explore

        views : dict
            A dict in which discovered views will be stored.

        interface_views : dict
            A dict in which discovered interface views will be stored.

        failed : list
            A list in which failed imports will be stored.

        """
        for mod in modules:
            try:
                with enaml.imports():
                    m = import_module('.' + mod, MODULE_ANCHOR)
            except Exception as e:
                log = logging.getLogger(__name__)
                mess = 'Failed to import {} : {}'.format(mod, e)
                log.error(mess)
                failed[mod] = mess
                continue

            if hasattr(m, 'TASK_VIEW_MAPPING'):
                views.update(m.TASK_VIEW_MAPPING)

            if hasattr(m, 'INTERFACE_VIEW_MAPPING'):
                interface_views.update(m.INTERFACE_VIEW_MAPPING)
def test_show_monitors(execution_view, dialog_sleep):
    """Test restoring the monitor window.

    """
    execution_view.show()
    process_app_events()
    sleep(dialog_sleep)

    item = execution_view.widget

    mon_btn = item.dock_widget().widgets()[5]
    assert not mon_btn.enabled

    with enaml.imports():
        from ecpy.measure.workspace.monitors_window import MonitorsWindow

    meas = item.workspace.plugin.enqueued_measures.measures[0]
    mon_win = MonitorsWindow(item, measure=meas)
    item.workspace.plugin.processor.monitors_window = mon_win

    assert not mon_win.visible

    mon_btn.clicked = True
    process_app_events()
    assert mon_win.visible
Exemple #29
0
def main():
    usage = 'usage: %prog [options] enaml_file'
    parser = optparse.OptionParser(usage=usage, description=__doc__)
    parser.add_option('-c', '--component', default='Main',
                      help='The component to view')
    parser.add_option('-t', '--toolkit', default='default',
                      choices=['default', 'wx', 'qt'],
                      help='The toolkit backend to use')
    
    options, args = parser.parse_args()

    if len(args) == 0:
        print 'No .enaml file specified'
        sys.exit()
    elif len(args) > 1:
        print 'Too many files specified'
        sys.exit()
    else:
        enaml_file = args[0]

    pg = PersistGeometry(datadir=ETSConfig.get_application_home(create=True))
    with toolkits[options.toolkit]():
        try:
            factory, module = read_component(enaml_file, requested=options.component)
        except NameError, e:
            raise SystemExit('Error: ' + str(e))

        with imports():
            from enaml_debug.debug_ui import DebugLayoutUI, get_geometry

        window = DebugLayoutUI(root=factory().central_widget, persist_geometry=pg)
        window.show()
        pg.save(get_geometry(window))
Exemple #30
0
def list_manifests():
    """List the manifest that should be regsitered when the main Ecpy app is
    started.

    """
    with enaml.imports():
        from .manifest import PulsesManagerManifest
    return [PulsesManagerManifest]
Exemple #31
0
 def view_window(self):
     from enaml import imports
     with imports():
         from taref.instruments.instrument_e import GPIB_InstrumentView
     return GPIB_InstrumentView(instr=self)
 def view_window(self):
     with imports():
         from e_UserTemps import TextEditorWindow
     return TextEditorWindow(instr=self)
Exemple #33
0
 def view_window(self):
     with imports():
         from fig_format_e import Main
     view = Main(pltr=self)
     return view
Exemple #34
0
def imports():
    return enaml.imports(operators=TRAIT_OPERATORS)
Exemple #35
0
def generate_example_doc(docs_path, script_path):
    """ Generate an RST and a PNG for an example file.

    Parameters
    ----------
    docs_path : str
         Full path to enaml/docs/source/examples
    script_path : str
         Full path to the example enaml file
    """
    script_name = os.path.basename(script_path)
    script_name = script_name[:script_name.find('.')]
    print('generating doc for %s' % script_name)

    script_title = script_name.replace('_', ' ').title()
    script_image_name = 'ex_' + script_name + '.png'
    image_path = os.path.join(docs_path, 'images', script_image_name)
    rst_path = os.path.join(
        docs_path, 'ex_' + script_name + '.rst')
    relative_script_path = script_path[
        script_path.find('examples'):].replace('\\', '/')

    # Add the script to the Python Path
    old_python_path = sys.path
    sys.path = sys.path + [os.path.dirname(script_path)]

    snapshot_success = False
    with enaml.imports():
        try:
            mod = __import__(script_name)
            save_snapshot_of_module(mod, image_path)
            snapshot_success = True
        except Exception as err:
            print('Could not snapshot: %s' % script_name)
            print('    %s' % err)
        finally:
            # The import leaves behind a cache. Clean it up.
            enaml_cache_dir = os.path.join(
                os.path.dirname(script_path), '__enamlcache__')
            shutil.rmtree(enaml_cache_dir)

    # Restore Python path.
    sys.path = old_python_path

    with open(os.path.join(script_path)) as fid:
        script_text = fid.read()

    docstring = clean_docstring(extract_docstring(script_text))

    screenshot_rst = '' if not snapshot_success else (
            SCREENSHOT_RST_TEMPLATE.format(name=script_image_name))

    example_doc_rst = EXAMPLE_DOC_RST_TEMPLATE.format(
        title=script_title,
        name=script_name,
        path=relative_script_path,
        docstring_rst=docstring,
        screenshot_rst=screenshot_rst)

    with open(rst_path, 'wb') as rst_output_file:
        rst_output_file.write(example_doc_rst.lstrip().encode())
Exemple #36
0
def test_stop_button(exopy_qtbot, execution_view, monkeypatch, dialog_sleep):
    """Test the behavoir of the stop button.

    """
    execution_view.show()
    wait_for_window_displayed(exopy_qtbot, execution_view)
    exopy_qtbot.wait(dialog_sleep)

    item = execution_view.widget

    from exopy.measurement.workspace.workspace import MeasurementSpace
    spy = CallSpy()
    monkeypatch.setattr(MeasurementSpace, 'stop_current_measurement', spy)

    with enaml.imports():
        from exopy.measurement.workspace import measurement_execution
    qspy = CallSpy()
    monkeypatch.setattr(measurement_execution, 'question', qspy)
    st_btn = item.dock_widget().widgets()[2]

    # Check idle state.
    assert not st_btn.enabled
    assert st_btn.text == 'Stop'
    assert not st_btn.stopping

    # Check enabled when running.
    meas = item.workspace.plugin.enqueued_measurements.measurements[0]
    item.workspace.plugin.processor.running_measurement = meas
    item.workspace.plugin.processor.active = True
    assert st_btn.enabled

    # Stop and skip
    item.workspace.plugin.processor.continuous_processing = False
    skip = st_btn.children[0].children[0]
    skip.triggered = True

    def assert_called():
        assert spy.called
        assert spy.kwargs['no_post_exec']
        assert not spy.kwargs['force']
        assert not qspy.called

    exopy_qtbot.wait_until(assert_called)

    # Stop and don't skip
    item.workspace.plugin.processor.continuous_processing = True
    no_skip = st_btn.children[0].children[1]
    no_skip.triggered = True

    def assert_called():
        assert spy.called == 2
        assert not spy.kwargs.get('no_post_exec')
        assert not spy.kwargs['force']
        assert qspy.called
        assert not item.workspace.plugin.processor.continuous_processing

    exopy_qtbot.wait_until(assert_called)

    # Check stopping behavior
    meas.status = 'STOPPING'
    assert st_btn.stopping
    assert st_btn.text == 'Force stop'

    # Check force stopping and no question when no measurement remains in queue
    item.workspace.plugin.enqueued_measurements.remove(meas)
    qspy.called = 0
    no_skip.triggered = True

    def assert_called():
        assert spy.kwargs['force']
        assert not qspy.called

    exopy_qtbot.wait_until(assert_called)

    spy.kwargs = {}
    skip.triggered = True

    def assert_called():
        assert spy.kwargs['force']
        assert not qspy.called

    exopy_qtbot.wait_until(assert_called)
Exemple #37
0
                                    compile_tex)

from collections import OrderedDict

from taref.core.agent import Operative
#from taref.core.universal import write_text
from taref.core.log import f_top, log_debug
from enaml.qt.qt_application import QtApplication
from taref.filer.filer import Folder
from taref.filer.read_file import Read_TXT
from taref.filer.save_file import Save_TXT
from subprocess import call
from os.path import relpath
from taref.core.interact import Interact, File_Parser
from enaml import imports
with imports():
    from tex_e import TEX_Window


class TEX(Operative):
    """A laTeX/python report maker. source tex and images are included from the source folder. tex and python are written out to the save_file and save_code.
    various subfunctions give easy access to including analysis written in python in a laTeX report"""

    base_name = "tex"
    #initial_size=(800,800)
    tex_type = Enum("simple", "revtex 2 column", "revtex 1 column")

    folder = Folder(
        base_dir=
        "/Users/thomasaref/Dropbox (Clan Aref)/Current stuff/test_data",
        main_dir="tex_processed",
Exemple #38
0
 def view_window2(self):
     from enaml import imports
     with imports():
         from taref.saw.idt_e import IDT_View
     return IDT_View(idt=self)
Exemple #39
0
 def test_import_failure(self):
     with self.assertRaises(ImportError):
         with enaml.imports():
             from traits_enaml.widgets.gl_canvas import GLCanvas  # noqa
Exemple #40
0
def editor_item_factory():
    with enaml.imports():
        from .view import EditorDockItem
    return EditorDockItem
Exemple #41
0
def test_zipimport_from_subpackage(enaml_qtbot, enaml_sleep, zip_library):
    with enaml.imports():
        # Test import from library.zip/package/subpackage/slider.enaml
        from package.subpackage import slider

    assert_window_displays(enaml_qtbot, enaml_sleep, slider.Main())
Exemple #42
0
def test_zipimport_from_package(enaml_qtbot, enaml_sleep, zip_library):
    with enaml.imports():
        # Test import from library.zip/package/form.enaml
        from package import form

    assert_window_displays(enaml_qtbot, enaml_sleep, form.Main())
Exemple #43
0
def test_zipimport_from_module(enaml_qtbot, enaml_sleep, zip_library):
    with enaml.imports():
        # Test import from library.zip/buttons.enaml
        import buttons

    assert_window_displays(enaml_qtbot, enaml_sleep, buttons.Main())
Exemple #44
0
 def view_window(self):
     with imports():
         from taref.filer.filer_e import SaveMain
     return SaveMain(save_file=self, read_file=Read_HDF5(file_path=self.file_path))
Exemple #45
0
from .tasks.instr_task import InstrumentTask

from .tasks.task_interface import (InterfaceableTaskMixin, TaskInterface,
                                   InterfaceableInterfaceMixin, IInterface)
from .tasks.string_evaluation import FORMATTER_TOOLTIP, EVALUATER_TOOLTIP

from .tasks import validators

from .declarations import (Tasks, Task, Interfaces, Interface, TaskConfig)
from .filters import (TaskFilter, SubclassTaskFilter, GroupTaskFilter,
                      MetadataTaskFilter)

from .configs.base_configs import BaseTaskConfig

from .utils.building import build_task_from_config

with enaml.imports():
    from .configs.base_config_views import BaseConfigView
    from .tasks.base_views import BaseTaskView
    from .tasks.instr_view import InstrTaskView

__all__ = [
    'BaseTask', 'SimpleTask', 'ComplexTask', 'RootTask', 'InstrumentTask',
    'BaseTaskView', 'InstrTaskView', 'InterfaceableTaskMixin', 'TaskInterface',
    'InterfaceableInterfaceMixin', 'IInterface', 'Tasks', 'Task', 'Interfaces',
    'Interface', 'TaskConfig', 'TaskFilter', 'SubclassTaskFilter',
    'GroupTaskFilter', 'MetadataTaskFilter', 'BaseTaskConfig',
    'BaseConfigView', 'build_task_from_config', 'FORMATTER_TOOLTIP',
    'EVALUATER_TOOLTIP'
]
Exemple #46
0
def test_pulse_view(exopy_qtbot, workbench, pulse, dialog_sleep):
    """Test the view of the Pulse class.

    """
    import enaml
    from exopy.testing.util import show_widget
    with enaml.imports():
        from exopy_pulses.pulses.sequences.views.base_sequences_views\
            import RootSequenceView

    pulse.kind = 'Analogical'
    root = pulse.root
    root.add_child_item(0, pulse)
    core = workbench.get_plugin('enaml.workbench.core')
    root_view = RootSequenceView(item=root, core=core)
    pulse_view = root_view.view_for(pulse)
    show_widget(exopy_qtbot, root_view)
    exopy_qtbot.wait(dialog_sleep)

    # Test swithcing between logical and analogical
    widgets_num = len(pulse_view.widgets())
    pulse.kind = 'Logical'

    def assert_widgets():
        assert widgets_num - 1 == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)

    pulse.kind = 'Analogical'

    def assert_widgets():
        assert widgets_num == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)

    # Test selecting a shape
    shape_select = pulse_view.widgets()[-1].widgets()[-1]
    shape_select.selected = 'exopy_pulses.SquareShape'

    def assert_widgets():
        assert widgets_num + 1 == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)

    shape_select.selected = ''

    def assert_widgets():
        assert widgets_num == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)

    # Test adding a modulation
    mod_check = pulse_view.widgets()[-1].widgets()[0]
    mod_check.checked = True

    def assert_widgets():
        assert widgets_num + 1 == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)
    mod_check.checked = False

    def assert_widgets():
        assert widgets_num == len(pulse_view.widgets())

    exopy_qtbot.wait_until(assert_widgets)
    exopy_qtbot.wait(dialog_sleep)
Exemple #47
0
 def on_open(self):
     with enaml.imports():
         from gui import Main
     mainWindow=Main()
     mainWindow.AO=AO()
     self.windows.append(mainWindow)
Exemple #48
0
def main():
    with enaml.imports():
        from myapp import Main

    view = Main()
    view.generateHTML()
Exemple #49
0
def viewer_factory():
    with enaml.imports():
        from .view import ViewerDockItem
    return ViewerDockItem
 def view_window(self):
     """stand alone for showing filer."""
     with imports():
         from enaml_Filer import ReadBoxMain
     return ReadBoxMain(read_file=self)
Exemple #51
0
 def view_window(self):
     with imports():
         from e_Show import JDFView
     return JDFView(jdf=self)
Exemple #52
0
 def view_log(self):
     from enaml import imports
     with imports():
         from taref.core.log_e import LogWindow
     return LogWindow(visible=False)
Exemple #53
0
 def view_window(self):
     with imports():
         from taref.core.plotter_e import PlotMain
     return PlotMain(plotr=self)
 def view_window(self):
     with imports():
         from taref.ebl.wafer_coords_e import WaferCoordsView
     view=WaferCoordsView(wc=self)
     return view
 def view_window(self):
     from enaml import imports
     with imports():
         from instrument_e import InstrMain
     return InstrMain(instrin=self)
Exemple #56
0
 def get_options_view(cls):
     with enaml.imports():
         from .options import OptionsForm
         return OptionsForm
Exemple #57
0
def generate_example_doc(app, docs_path, script_path):
    """ Generate an RST and a PNG for an example file.

    Parameters
    ----------
    app : QtApplication instance
    docs_path : str
         Full path to enaml/docs/source/examples
    script_path : str
         Full path to the example enaml file
    """
    script_name = os.path.basename(script_path)
    script_name = script_name[:script_name.find('.')]
    print('generating doc for %s' % script_name)

    script_title = script_name.replace('_', ' ').title()
    script_image_name = 'ex_' + script_name + '.png'
    image_path = os.path.join(docs_path, 'images', script_image_name)
    rst_path = os.path.join(docs_path, 'ex_' + script_name + '.rst')
    relative_script_path = script_path[script_path.find('examples'):].replace(
        '\\', '/')

    with open(os.path.join(script_path)) as fid:
        script_text = fid.read()

    docstring = script_text[script_text.find('"""') + 3:]
    docstring = docstring[:docstring.find('"""')]
    docstring = docstring.replace('<< autodoc-me >>\n', '').strip()

    rst_template = """
{0} Example
===============================================================================

:download:`{1} <../../../{2}>`

::

    {3}

::

 $ enaml-run {1}

.. image:: images/{4}

.. literalinclude:: ../../../{2}
    :language: enaml

""".format(script_title, script_name, relative_script_path,
           docstring.replace('\n', '\n    '), script_image_name)

    with open(rst_path, 'wb') as fid:
        fid.write(rst_template.lstrip().encode())

    temp_path = os.path.join(docs_path, os.path.basename(script_path))

    with open(temp_path, 'wb') as fid:
        fid.write(script_text.encode())

    with enaml.imports():
        try:
            mod = __import__(script_name)
        except Exception as err:
            print('Could not create: %s' % script_name)
            print('    %s' % err)
            os.remove(temp_path)
            return
    try:
        view = mod.Main()
        snapshot = SnapShot(path=image_path, view=view)
        view.show()
        app.start()
    except Exception as err:
        print('Could not create: %s' % script_name)
        print('    %s' % err)
    finally:
        os.remove(temp_path)
Exemple #58
0
 def view_window(self):
     from enaml import imports
     with imports():
         from taref.ebl.jdf_e import JDF_View
     return JDF_View(jdf=self)
Exemple #59
0
def test_edition_window(exopy_qtbot, text_monitor_workbench, dialog_sleep,
                        monkeypatch):
    """Test the capabalities of the widget used to edit a text monitor.

    """
    p = text_monitor_workbench.get_plugin(
        'exopy.measurement.monitors.text_monitor')
    m = p.create_monitor(False)
    m.rules.append(p.build_rule(dict(id='test', class_id='exopy.FormatRule',
                                     new_entry_formatting='{index}/{number}',
                                     suffixes=['index', 'number'],
                                     new_entry_suffix='progress')))
    assert m.rules[0]
    m.custom_entries.append(MonitoredEntry(name='dummy', path='dummy',
                                           formatting='2*{root/test}',
                                           depend_on=['root/test']))
    m.handle_database_entries_change(('added', 'root/test', 0))
    m.handle_database_entries_change(('added', 'root/simp/t_test2', 0))
    m.handle_database_entries_change(('added', 'root/comp/t_index', 0))
    m.handle_database_entries_change(('added', 'root/comp/t_number', 0))
    assert len(m.displayed_entries) == 4
    assert len(m.hidden_entries) == 2

    w = ContainerTestingWindow(widget=TextMonitorEdit(monitor=m))
    w.show()
    wait_for_window_displayed(exopy_qtbot, w)
    exopy_qtbot.wait(dialog_sleep)
    editor = w.widget

    # Test hide all
    editor.widgets()[6].clicked = True

    def assert_displayed_entries():
        assert not m.displayed_entries
    exopy_qtbot.wait_until(assert_displayed_entries)
    exopy_qtbot.wait(dialog_sleep)

    # Test show one
    editor.widgets()[1].selected_item = m.undisplayed_entries[0]
    editor.widgets()[5].clicked = True

    def assert_displayed_entries():
        assert m.displayed_entries
    exopy_qtbot.wait_until(assert_displayed_entries)
    exopy_qtbot.wait(dialog_sleep)

    # Test hide one
    editor.widgets()[3].selected_item = m.displayed_entries[0]
    editor.widgets()[7].clicked = True

    def assert_displayed_entries():
        assert not m.displayed_entries
    exopy_qtbot.wait_until(assert_displayed_entries)
    exopy_qtbot.wait(dialog_sleep)

    # Test show all
    editor.widgets()[4].clicked = True

    def assert_displayed_entries():
        assert not m.undisplayed_entries
    exopy_qtbot.wait_until(assert_displayed_entries)
    exopy_qtbot.wait(dialog_sleep)

    # Test show hidden
    editor.widgets()[8].checked = True

    def assert_hidden():
        assert m.hidden_entries
    exopy_qtbot.wait_until(assert_hidden)

    for e in m.hidden_entries:
        assert e in m.undisplayed_entries

    # Test edit rules
    def handle_rule_edition(bot, dialog):
        dialog.monitor.rules.append(RejectRule(id='__dummy',
                                               suffixes=['test2']))
        dialog.monitor.refresh_monitored_entries()

    with handle_dialog(exopy_qtbot, handler=handle_rule_edition):
        editor.widgets()[9].clicked = True

    assert 't_test2' not in [e.name for e in m.displayed_entries]

    # Test add entry
    def handle_entry_creation(bot, dialog):
        dialog.entry = MonitoredEntry(name='new_entry')

    with handle_dialog(exopy_qtbot, handler=handle_entry_creation):
        editor.widgets()[10].clicked = True

    assert 'new_entry' in [e.name for e in m.displayed_entries]

    # Test edit entry
    e = [e for e in m.displayed_entries if e.name == 'new_entry'][0]
    editor.selected = e
    with handle_dialog(exopy_qtbot, 'reject'):
        editor.widgets()[11].clicked = True

    # Test delete entry
    with enaml.imports():
        from exopy.measurement.monitors.text_monitor import monitor_views

    def false_question(*args, **kwargs):
        class Obj(object):
            action = 'reject'
        return Obj

    monkeypatch.setattr(monitor_views, 'question', false_question)
    editor.widgets()[12].clicked = True

    def assert_entry():
        assert e in m.displayed_entries
    exopy_qtbot.wait_until(assert_entry)
    exopy_qtbot.wait(dialog_sleep)

    m.add_entries('undisplayed', [e])
    with enaml.imports():
        from exopy.measurement.monitors.text_monitor import monitor_views

    def false_question(*args, **kwargs):
        class Obj(object):
            action = 'accept'
        return Obj

    monkeypatch.setattr(monitor_views, 'question', false_question)
    editor.widgets()[12].clicked = True
    assert e not in m.displayed_entries
    exopy_qtbot.wait(dialog_sleep)