def _create_dialog_area(self, parent):
        panel = wx.Panel(parent, -1)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        # The image.
        if self.image is None:
            image_rc = ImageResource('warning')
        else:
            image_rc = self.image

        image = wx.StaticBitmap(panel, -1, image_rc.create_bitmap())
        sizer.Add(image, 0, wx.EXPAND | wx.ALL, 10)

        # The message.
        if self.informative:
            message = self.message + '\n\n' + self.informative
        else:
            message = self.message
        message = wx.StaticText(panel, -1, message)
        sizer.Add(message, 1, wx.EXPAND | wx.TOP, 15)

        # Resize the panel to match the sizer.
        sizer.Fit(panel)

        return panel
 def _set_window_icon(self):
     if self.icon is None:
         icon = ImageResource('application.png')
     else:
         icon = self.icon
     if self.control is not None:
         self.control.setWindowIcon(icon.create_icon())
Exemple #3
0
    def set_icon ( self, icon = None ):
        """ Sets the frame's icon.
        """
        from pyface.image_resource import ImageResource

        if not isinstance( icon, ImageResource ):
            icon = ImageResource( 'frame.ico' )
        self.control.SetIcon( icon.create_icon() )
Exemple #4
0
 def test_get_image(self):
     image = ImageResource("question")
     value_type = ConstantValue(image=image)
     self.assertEqual(value_type.get_image(self.model, [0], [0]), image)
Exemple #5
0
 def test_image_changed(self):
     value_type = ConstantValue()
     image = ImageResource("question")
     with self.assertTraitChanges(value_type, 'updated'):
         value_type.image = image
     self.assertEqual(value_type.image, image)
Exemple #6
0
class SMRCWindow(HasTraits):
    """
    SMRCWindow is the Mainwindow of the application SmartRecord. The window 
    shows the time and the current phase of the experiment when it's running. 
    Furthermore the window interacts with the SMRCModel and 
    make it possible that the user can start and 
    cancel the experiment by clicking a icon.
    """

    model = Instance(SMRCModel)

    smrc_handler = SMRCHandler()

    current_phase = Str("Current Phase - Not Started")

    clock = Str(secs_to_time(0))

    record_mode = Bool(True)

    def __init__(self, model):
        self.logger = getLogger("application")
        self.logger.debug("Initializes SMRCWindow")
        self.record_mode = model.record_mode
        self.model = model
        self.model.experiment.window = self

    def start_clock(self):
        """Run the clock in the status bar."""
        self.logger.info("Start the time-thread [SMRCWindow]")
        self.clock = secs_to_time(0)
        RunThread(target=self._run_clock)

    def _run_clock(self):
        # Updates the status bar time once every second.
        self.clock_running = True
        self.start_time = time()
        while self.clock_running:
            self.td = time() - self.start_time
            self.clock = secs_to_time(self.td)
            sleep(1.0)

    #=========================================================================
    # Traitsview
    #=========================================================================

    # Switch to stop the running thread
    clock_running = Bool(False)

    view = View(UItem("model", style="custom"),
                menubar=MenuBar(Menu(*file_actions, name="File"),
                                Menu(*configure_actions, name="Configuration"),
                                Menu(*import_action, name="Import"),
                                Menu(help_docs, name="Help")),
                toolbar=ToolBar(*toolbar_actions,
                                show_tool_names=False,
                                image_size=(30, 30)),
                statusbar=[
                    StatusItem(name="current_phase", width=0.5),
                    StatusItem(name="clock", width=85)
                ],
                handler=smrc_handler,
                resizable=True,
                height=680,
                width=1300,
                title="SmartRecord",
                icon=ImageResource("../../icons/smrc_icon.png"))
Exemple #7
0
        return values

    #=========================================================================
    # Help actions
    #=========================================================================

    def open_tutorial(self, info):
        """Opens the tutorial for the application"""
        self.logger.info("Open the tutorial [SMRCHandler]")
        path = realpath("../../docs/_build/html/tutorial.html")
        html_file = "file://" + path
        open(html_file, new=2)


toolbar_actions = [Action(action="_start",
                          image=ImageResource("../../icons/run.png"),
                          enabled_when="not model.started"),
                   Action(action="_cancel",
                          image=ImageResource("../../icons/stop.png"),
                          enabled_when="model.started"),
                   Action(action="_manually_trigger",
                          image=ImageResource("../../icons/manually.png"),
                          enabled_when="model.started")]

file_actions = [file_exit, Separator(), file_save_experiment, file_save_project,
                Separator(), file_load_experiment, file_load_project,
                Separator()]

configure_actions = [conf_server]

import_action = [import_project, import_dic_results]
    def _get_big_image(self):
        size = self.item.size
        if size > 65536:
            return ImageResource('red_ball')

        return (None, ImageResource('blue_ball'))[size > 16384]
Exemple #9
0
update_button = Action(name = "Update", action = "set_execute_callback_true", \
                             show_label=False)
reset_button = Action(name = "Reset", action = "set_execute_callback_true", \
                             show_label=False)
close_button = Action(name = "Close", action = "set_execute_callback_false", \
                             show_label=False)

from new import instancemethod

import sys, os
from pyface.image_resource import ImageResource

basedir = determine_path()
icon = ImageResource('icon',
                     search_path=['images',
                                  os.path.join(basedir, 'images')])


# Handler methods that can be associated with buttons.
def set_execute_callback_true(self, info):
    info.object.execute_callback = True
    info.object.handler_executed = True


def set_execute_callback_false(self, info):
    info.object.execute_callback = False
    info.object.handler_executed = True


class CallbackHandler(Handler):
Exemple #10
0
def run_gui():
    try:
        # if we're running as a one-click from a MacOS app,
        # we need to reset the working directory
        import os
        os.chdir(sys._MEIPASS)  # @UndefinedVariable
    except:
        # if we're not running as a one-click, fail gracefully
        pass

    # set the app scaling to support HiDPI displays
    from pyface.qt import QtGui, QtCore
    QtGui.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)

    # and shut up the warning about Open GL (see below)
    QtGui.QApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)

    # this is ridiculous, but here's the situation.  Qt5 now uses Chromium
    # as their web renderer.  Chromium needs OpenGL.  if you don't
    # initialize OpoenGL here, things crash on some platforms.

    # so now i guess we depend on opengl too.

    from OpenGL import GL  # @UnresolvedImport @UnusedImport

    # need to import these before a QCoreApplication is instantiated.  and that seems
    # to happen in .... 'import cytoflow' ??
    import pyface.qt.QtWebKit  # @UnusedImport

    # take care of the 3 places in the cytoflow module that
    # need different behavior in a GUI
    import cytoflow
    cytoflow.RUNNING_IN_GUI = True

    # check that we're using the right Qt API
    from pyface.qt import qt_api

    cmd_line = " ".join(sys.argv)

    if qt_api == "pyside":
        print("Cytoflow uses PyQT; but it is trying to use PySide instead.")
        print(" - Make sure PyQT is installed.")
        print(
            " - If both are installed, and you don't need both, uninstall PySide."
        )
        print(" - If you must have both installed, select PyQT by setting the")
        print("   environment variable QT_API to \"pyqt5\"")
        print("   * eg, on Linux, type on the command line:")
        print("     QT_API=\"pyqt5\" " + cmd_line)
        print("   * on Windows, try: ")
        print("     setx QT_API \"pyqt5\"")

        sys.exit(1)

    # parse args
    parser = argparse.ArgumentParser(description='Cytoflow GUI')
    parser.add_argument("--debug", action='store_true')
    parser.add_argument("filename", nargs='?', default="")

    args = parser.parse_args()

    # start the remote process

    remote_process, remote_workflow_connection, remote_canvas_connection, queue_listener = start_remote_process(
    )

    # getting real tired of the matplotlib deprecation warnings
    import warnings
    warnings.filterwarnings('ignore', '.*is deprecated and replaced with.*')

    # if we're frozen, add _MEIPASS to the pyface search path for icons etc
    if getattr(sys, 'frozen', False):
        from pyface.resource_manager import resource_manager
        resource_manager.extra_paths.append(sys._MEIPASS)  # @UndefinedVariable

    # these three lines stop pkg_resources from trying to load resources
    # from the __main__ module, which is frozen (and thus not loadable.)
    from pyface.image_resource import ImageResource
    icon = ImageResource('icon')
    icon.search_path = []

    # monkey patch the resource manager to use SVGs for icons
    import pyface.resource.resource_manager
    pyface.resource.resource_manager.ResourceManager.IMAGE_EXTENSIONS.append(
        '.svg')

    # monkey patch checklist editor to stop lowercasing
    import traitsui.qt4.check_list_editor  # @UnusedImport
    traitsui.qt4.check_list_editor.capitalize = lambda s: s

    # define and install a message handler for Qt errors
    from traits.api import push_exception_handler

    def QtMsgHandler(msg_type, msg_context, msg_string):
        # Convert Qt msg type to logging level
        log_level = [
            logging.DEBUG, logging.WARN, logging.ERROR, logging.FATAL
        ][int(msg_type)]
        logging.log(log_level, 'Qt message: ' + msg_string)

    from pyface.qt.QtCore import qInstallMessageHandler  # @UnresolvedImport
    qInstallMessageHandler(QtMsgHandler)

    # install a global (gui) error handler for traits notifications
    push_exception_handler(handler=log_notification_handler,
                           reraise_exceptions=False,
                           main=True)

    sys.excepthook = log_excepthook

    # Import, then load, the envisage plugins

    from envisage.core_plugin import CorePlugin
    from envisage.ui.tasks.tasks_plugin import TasksPlugin

    from cytoflowgui.flow_task import FlowTaskPlugin
    from cytoflowgui.export_task import ExportFigurePlugin
    from cytoflowgui.cytoflow_application import CytoflowApplication

    from cytoflowgui.op_plugins import (
        ImportPlugin, ThresholdPlugin, RangePlugin, QuadPlugin, Range2DPlugin,
        PolygonPlugin, BinningPlugin, GaussianMixture1DPlugin,
        GaussianMixture2DPlugin, DensityGatePlugin, BleedthroughLinearPlugin,
        BeadCalibrationPlugin, AutofluorescencePlugin, ColorTranslationPlugin,
        TasbePlugin, ChannelStatisticPlugin, TransformStatisticPlugin,
        RatioPlugin, FlowPeaksPlugin, KMeansPlugin, PCAPlugin)

    from cytoflowgui.view_plugins import (
        HistogramPlugin, Histogram2DPlugin, ScatterplotPlugin, BarChartPlugin,
        Stats1DPlugin, Kde1DPlugin, Kde2DPlugin, ViolinPlotPlugin, TablePlugin,
        Stats2DPlugin, DensityPlugin, ParallelCoordinatesPlugin, RadvizPlugin,
        ExportFCSPlugin)

    plugins = [
        CorePlugin(),
        TasksPlugin(),
        FlowTaskPlugin(),
        ExportFigurePlugin()
    ]

    # ordered as we want them to show up in the toolbar
    view_plugins = [
        HistogramPlugin(),
        ScatterplotPlugin(),
        Histogram2DPlugin(),
        DensityPlugin(),
        Kde1DPlugin(),
        Kde2DPlugin(),
        RadvizPlugin(),
        ParallelCoordinatesPlugin(),
        ViolinPlotPlugin(),
        BarChartPlugin(),
        Stats1DPlugin(),
        Stats2DPlugin(),
        TablePlugin(),
        ExportFCSPlugin()
    ]

    plugins.extend(view_plugins)

    op_plugins = [
        ImportPlugin(),
        ThresholdPlugin(),
        RangePlugin(),
        QuadPlugin(),
        Range2DPlugin(),
        PolygonPlugin(),
        ChannelStatisticPlugin(),
        TransformStatisticPlugin(),
        RatioPlugin(),
        BinningPlugin(),
        GaussianMixture1DPlugin(),
        GaussianMixture2DPlugin(),
        DensityGatePlugin(),
        KMeansPlugin(),
        FlowPeaksPlugin(),
        PCAPlugin(),
        AutofluorescencePlugin(),
        BleedthroughLinearPlugin(),
        BeadCalibrationPlugin(),
        ColorTranslationPlugin(),
        TasbePlugin()
    ]

    plugins.extend(op_plugins)

    # start the app

    app = CytoflowApplication(
        id='edu.mit.synbio.cytoflow',
        plugins=plugins,
        icon=icon,
        remote_process=remote_process,
        remote_workflow_connection=remote_workflow_connection,
        remote_canvas_connection=remote_canvas_connection,
        filename=args.filename,
        debug=args.debug)

    from pyface.qt import QtGui
    QtGui.QApplication.instance().setStyle(
        QtGui.QStyleFactory.create('Fusion'))

    app.run()

    remote_process.join()
    queue_listener.stop()
    logging.shutdown()
class EngineView(HasTraits):
    """ A view displaying the engine's object tree. """

    # The MayaVi engine we are a view of.
    engine = Instance(Engine, allow_none=True)

    # Path used to search for images
    _image_path = [
        join(resource_path(), 'images'),
    ]

    # The icon of the dialog
    icon = ImageResource('mv2.ico', search_path=_image_path)

    # Nodes on the tree.
    nodes = Any

    # TreeEditor
    tree_editor = Instance(TreeEditor)

    # Toolbar
    toolbar = Instance(ToolBar)

    # Toolbar actions.
    actions = List(Either(Action, Separator))

    # Some delegates, for the toolbar to update
    scenes = Delegate('engine')
    current_selection = Delegate('engine')

    ###########################################################################
    # `object` interface.
    ###########################################################################
    def __init__(self, **traits):
        super(EngineView, self).__init__(**traits)

    ###########################################################################
    # `HasTraits` interface.
    ###########################################################################
    def default_traits_view(self):
        """The default traits view of the Engine View.
        """

        view = View(Item(name='engine',
                         id='engine',
                         editor=self.tree_editor,
                         resizable=True,
                         show_label=False),
                    id='mayavi.engine',
                    help=False,
                    resizable=True,
                    scrollable=True,
                    undo=False,
                    revert=False,
                    ok=False,
                    cancel=False,
                    icon=self.icon,
                    title='Mayavi pipeline',
                    toolbar=self.toolbar,
                    handler=EngineViewHandler)
        return view

    def _nodes_default(self):
        """ The default value of the cached nodes list.
        """
        # Now setup the view.
        nodes = [
            TreeNode(
                node_for=[Engine],
                children='children_ui_list',
                label='=Mayavi',
                auto_open=False,
                copy=False,
                delete=False,
                rename=True,
            ),
            ObjectTreeNode(
                node_for=[Base],
                children='children_ui_list',
                label='name',
                auto_open=True,
                copy=True,
                delete=True,
                rename=True,
                tooltip='=Right click for more options',
            ),
            AdderTreeNode(
                node_for=[SceneAdderNode],
                icon_item='add_scene.png',
            ),
            AdderTreeNode(
                node_for=[SourceAdderNode],
                icon_item='add_source.png',
            ),
            AdderTreeNode(
                node_for=[ModuleFilterAdderNode],
                icon_item='add_module.png',
            ),
        ]
        return nodes

    def _tree_editor_default(self):
        return TreeEditor(editable=False,
                          hide_root=True,
                          on_dclick='handler._on_dclick',
                          on_select='handler._on_select',
                          orientation='vertical',
                          selected='object.engine.current_selection',
                          nodes=self.nodes)

    def _toolbar_default(self):
        toolbar = ToolBar(*self.actions)
        toolbar.image_size = (16, 16)
        toolbar.show_tool_names = False
        toolbar.show_divider = False
        return toolbar

    def _actions_default(self):
        add_scene = \
            Action(
                image=ImageResource('add_scene.png',
                                            search_path=self._image_path),
                tooltip="Create a new scene",
                defined_when='True',
                enabled_when='True',
                perform=self._perform_new_scene,
            )

        add_source = \
            Action(
                image=ImageResource('add_source.png',
                                            search_path=self._image_path),
                tooltip="Add a data source",
                defined_when='True',
                enabled_when='len(scenes) > 0',
                perform=self._perform_add_source,
            )

        add_module = \
            Action(
                image=ImageResource('add_module.png',
                                            search_path=self._image_path),
                tooltip="Add a visualization module",
                defined_when='True',
                # isinstance doesn't work in enabled_when
                enabled_when=\
                    'current_selection is not None and'
                    '( hasattr(current_selection, "output_info")'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_module,
            )

        add_filter = \
            Action(
                image=ImageResource('add_filter.png',
                                            search_path=self._image_path),
                tooltip="Add a processing filter",
                defined_when='True',
                enabled_when=\
                    'current_selection is not None and'
                    '( ( hasattr(current_selection, "output_info")'
                    ' and not current_selection.type in (" module", '
                    ' " module manager"))'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_filter,
             )

        help = \
            Action(
                image=ImageResource('help-action.png',
                                            search_path=self._image_path),
                tooltip="Help on the Mayavi pipeline",
                defined_when='True',
                enabled_when='True',
                perform=open_help_index,
            )

        tvtk_docs = \
            Action(
                image=ImageResource('reader.png',
                                            search_path=self._image_path),
                tooltip="Search the VTK class browser",
                defined_when='True',
                enabled_when='True',
                perform=open_tvtk_docs,
            )

        record = \
            Action(
                image=ImageResource('record.png',
                                     search_path=self._image_path),
                tooltip="Start/Stop script recording",
                style='toggle',
                checked=False,
                defined_when='True',
                enabled_when='engine is not None',
                perform=self._perform_record,
            )

        # Check the record icon if the engine already has a recorder
        # set.
        if self.engine is not None and self.engine.recorder is not None:
            record.checked = True

        return [
            tvtk_docs,
            Separator(), add_scene, add_source, add_module, add_filter,
            Separator(), help, record
        ]

    ###########################################################################
    # Private interface.
    ###########################################################################
    def _perform_new_scene(self):
        self.engine.new_scene()
        self.engine.current_selection = self.engine.current_scene

    def _perform_add_source(self):
        adder = SourceAdderNode(object=self.engine.current_scene)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_add_module(self):
        object = self.engine.current_selection
        if isinstance(object, AdderNode):
            object = object.object
        adder = ModuleAdderNode(object=object)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_add_filter(self):
        object = self.engine.current_selection
        if isinstance(object, AdderNode):
            object = object.object
        adder = FilterAdderNode(object=object)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_record(self):
        e = self.engine
        if e.recorder is None:
            start_recording(e, known=True, script_id='engine')
        else:
            stop_recording(e, save=False)

    def _recorder_changed_for_engine(self, recorder):
        """Called when the recorder trait on the engine trait of this
        object changes.

        This basically toggles the recording action when someone
        attaches a recorder to the engine.
        """
        record_action = None
        for action in self.actions:
            if hasattr(action, 'tooltip') and \
               action.tooltip.endswith('recording'):
                record_action = action
                break

        if record_action is not None:
            if recorder is not None:
                record_action.checked = True
            else:
                record_action.checked = False
    def _actions_default(self):
        add_scene = \
            Action(
                image=ImageResource('add_scene.png',
                                            search_path=self._image_path),
                tooltip="Create a new scene",
                defined_when='True',
                enabled_when='True',
                perform=self._perform_new_scene,
            )

        add_source = \
            Action(
                image=ImageResource('add_source.png',
                                            search_path=self._image_path),
                tooltip="Add a data source",
                defined_when='True',
                enabled_when='len(scenes) > 0',
                perform=self._perform_add_source,
            )

        add_module = \
            Action(
                image=ImageResource('add_module.png',
                                            search_path=self._image_path),
                tooltip="Add a visualization module",
                defined_when='True',
                # isinstance doesn't work in enabled_when
                enabled_when=\
                    'current_selection is not None and'
                    '( hasattr(current_selection, "output_info")'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_module,
            )

        add_filter = \
            Action(
                image=ImageResource('add_filter.png',
                                            search_path=self._image_path),
                tooltip="Add a processing filter",
                defined_when='True',
                enabled_when=\
                    'current_selection is not None and'
                    '( ( hasattr(current_selection, "output_info")'
                    ' and not current_selection.type in (" module", '
                    ' " module manager"))'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_filter,
             )

        help = \
            Action(
                image=ImageResource('help-action.png',
                                            search_path=self._image_path),
                tooltip="Help on the Mayavi pipeline",
                defined_when='True',
                enabled_when='True',
                perform=open_help_index,
            )

        tvtk_docs = \
            Action(
                image=ImageResource('reader.png',
                                            search_path=self._image_path),
                tooltip="Search the VTK class browser",
                defined_when='True',
                enabled_when='True',
                perform=open_tvtk_docs,
            )

        record = \
            Action(
                image=ImageResource('record.png',
                                     search_path=self._image_path),
                tooltip="Start/Stop script recording",
                style='toggle',
                checked=False,
                defined_when='True',
                enabled_when='engine is not None',
                perform=self._perform_record,
            )

        # Check the record icon if the engine already has a recorder
        # set.
        if self.engine is not None and self.engine.recorder is not None:
            record.checked = True

        return [
            tvtk_docs,
            Separator(), add_scene, add_source, add_module, add_filter,
            Separator(), help, record
        ]
Exemple #13
0
    # Define the view:
    view = View(VGroup(
        VGroup(
            Item('name',
                 show_label=False,
                 editor=ImageEditor(
                     image=ImageResource('info', search_path=search_path)))),
        VGroup(
            Item('name'),
            Item('dept'),
            Item('email'),
            Item('picture',
                 editor=ImageEditor(scale=True,
                                    preserve_aspect_ratio=True,
                                    allow_upscaling=True),
                 springy=True),
        )),
                resizable=True)


# Create the demo:
popup = Employee(name='William Murchison',
                 dept='Receiving',
                 email='*****@*****.**',
                 picture=ImageResource('e-logo-rev', search_path=search_path))

# Run the demo (if invoked form the command line):
if __name__ == '__main__':
    popup.configure_traits()
Exemple #14
0
class OpenFile(Action):
    name = "Open file"
    description = "Open the File Dialog where you can select a neuroimaging file"
    tooltip = "Open file"
    path = Str("MenuBar/File/LoadDataMenu")
    image = ImageResource("cff-open.png", search_path=[IMAGE_PATH])

    # Is the action enabled?
    enabled = Bool(True)

    # Is the action visible?
    visible = Bool(True)

    ###########################################################################
    # 'Action' interface.
    ###########################################################################
    def perform(self, event, cfile=None):
        """ Performs the action. """

        logger.info('Performing open connectome file action')

        # helper variable to use this function not only in the menubar
        exec_as_funct = True

        if cfile is None:
            # get the instance of the current CFile
            # with the help of the Service Registry
            cfile = self.window.application.get_service(
                'cviewer.plugins.cff2.cfile.CFile')
            exec_as_funct = False

        wildcard = "All files (*.*)|*.*" \
                   "Nifti-1 (*.nii.gz)|*.nii.gz|" \
                   "Gifti (*.gii)|*.gii|" \
                   "TrackVis tracks (*.trk)|*.trk|" \
                   "Network Pickle (*.gpickle)|*.gpickle|" \
                   "Network GraphML (*.graphml)|*.graphml|" \
                   "Numpy Data (*.npy)|*.npy|" \
                   "Pickle Data (*.pkl)|*.pkl|" \
                   "Text Data (*.txt)|*.txt|" \
                   "CSV Data (*.csv)|*.csv|"

        dlg = FileDialog(wildcard=wildcard,title="Choose a file",\
                         resizeable=False, \
                         default_directory=preference_manager.cviewerui.cffpath,)

        if dlg.open() == OK:

            if not os.path.isfile(dlg.path):
                logger.error("File '%s' does not exist!" % dlg.path)
                return

            logger.info('Read file: %s' % dlg.path)
            fname = os.path.split(dlg.paths[0])[-1]

            if os.path.exists(dlg.paths[0]) and (fname.endswith('.nii.gz')
                                                 or fname.endswith('.nii')):
                cvol = cfflib.CVolume.create_from_nifti(
                    name=fname, nii_filename=dlg.paths[0])
                cfile.obj.add_connectome_volume(cvol)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.gii'):
                csurf = cfflib.CSurface.create_from_gifti(
                    name=fname, gii_filename=dlg.paths[0])
                cfile.obj.add_connectome_surface(csurf)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.trk'):
                ctrk = cfflib.CTrack(name=fname, src=dlg.paths[0])
                cfile.obj.add_connectome_track(ctrk)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.gpickle'):
                ctrk = cfflib.CNetwork(name=fname,
                                       src=dlg.paths[0],
                                       fileformat="NXGPickle")
                cfile.obj.add_connectome_network(ctrk)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.graphml'):
                ctrk = cfflib.CNetwork.create_from_graphml(
                    name=fname, ml_filename=dlg.paths[0])
                cfile.obj.add_connectome_network(ctrk)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.npy'):
                cdat = cfflib.CData(name=fname,
                                    src=dlg.paths[0],
                                    fileformat='NumPy')
                cfile.obj.add_connectome_data(cdat)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.csv'):
                cdat = cfflib.CData(name=fname,
                                    src=dlg.paths[0],
                                    fileformat='CSV')
                cfile.obj.add_connectome_data(cdat)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.txt'):
                cdat = cfflib.CData(name=fname,
                                    src=dlg.paths[0],
                                    fileformat='TXT')
                cfile.obj.add_connectome_data(cdat)

            elif os.path.exists(dlg.paths[0]) and fname.endswith('.pkl'):
                cdat = cfflib.CData(name=fname,
                                    src=dlg.paths[0],
                                    fileformat='Pickle')
                cfile.obj.add_connectome_data(cdat)

            else:
                logger.info('Could not load file: ' + dlg.paths)

            cfile.update_children()
Exemple #15
0
class OpenCFile(Action):
    """ An action that opens a data file depending on the supported
    extensions.  """

    name = "Open CFF File"
    description = "Open the File Dialog where you can select a .cff or meta.cml file"
    tooltip = "Open a CFF file"
    path = Str("MenuBar/File/LoadDataMenu")
    image = ImageResource("cff-open.png", search_path=[IMAGE_PATH])

    # Is the action enabled?
    enabled = Bool(True)

    # Is the action visible?
    visible = Bool(True)

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event, cfile=None):
        """ Performs the action. """

        logger.info('Performing open connectome file action')

        # helper variable to use this function not only in the menubar
        exec_as_funct = True

        if cfile is None:
            # get the instance of the current CFile
            # with the help of the Service Registry
            cfile = self.window.application.get_service(
                'cviewer.plugins.cff2.cfile.CFile')
            exec_as_funct = False

        wildcard = "Connectome Markup File v2.0 (meta.cml)|meta.cml|" \
                    "Connectome File Format v2.0 (*.cff)|*.cff|" \
                    "All files (*.*)|*.*"
        dlg = FileDialog(wildcard=wildcard,title="Choose a Connectome File",\
                         resizeable=False, \
                         default_directory=preference_manager.cviewerui.cffpath,)

        if dlg.open() == OK:

            if not os.path.isfile(dlg.path):
                logger.error("File '%s' does not exist!" % dlg.path)
                return

            # if file exists and has .cff ending
            if os.path.exists(
                    dlg.paths[0]) and (dlg.paths[0]).endswith('.cff'):

                # close the cfile if one is currently loaded
                cfile.close_cfile()

                # load cfile data
                cfile.load_cfile(dlg.paths[0])

                self.window.status_bar_manager.message = ''
            elif os.path.exists(
                    dlg.paths[0]) and (dlg.paths[0]).endswith('meta.cml'):
                cfile.close_cfile()
                cfile.load_cfile(dlg.paths[0], ismetacml=True)

            else:
                logger.info('Could not load file: ' + dlg.paths)
Exemple #16
0
class SplashScreen(MSplashScreen, Window):
    """ The toolkit specific implementation of a SplashScreen.  See the
    ISplashScreen interface for the API documentation.
    """

    # 'ISplashScreen' interface --------------------------------------------

    image = Instance(ImageResource, ImageResource("splash"))

    log_level = Int(DEBUG)

    show_log_messages = Bool(True)

    text = Str()

    text_color = Any()

    text_font = Any()

    text_location = Tuple(5, 5)

    # ------------------------------------------------------------------------
    # Protected 'IWidget' interface.
    # ------------------------------------------------------------------------

    def _create_control(self, parent):
        # Get the splash screen image.
        image = self.image.create_image()

        splash_screen = wx.adv.SplashScreen(
            # The bitmap to display on the splash screen.
            image.ConvertToBitmap(),
            # Splash Style.
            wx.adv.SPLASH_NO_TIMEOUT | wx.adv.SPLASH_CENTRE_ON_SCREEN,
            # Timeout in milliseconds (we don't currently timeout!).
            0,
            # The parent of the splash screen.
            parent,
            # wx Id.
            -1,
            # Window style.
            style=wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR,
        )

        # By default we create a font slightly bigger and slightly more italic
        # than the normal system font ;^)  The font is used inside the event
        # handler for 'EVT_PAINT'.
        self._wx_default_text_font = new_font_like(
            wx.NORMAL_FONT,
            point_size=wx.NORMAL_FONT.GetPointSize() + 1,
            style=wx.ITALIC,
        )

        # This allows us to write status text on the splash screen.
        splash_screen.Bind(wx.EVT_PAINT, self._on_paint)

        return splash_screen

    # ------------------------------------------------------------------------
    # Private interface.
    # ------------------------------------------------------------------------

    def _text_changed(self):
        """ Called when the splash screen text has been changed. """

        # Passing 'False' to 'Refresh' means "do not erase the background".
        if self.control is not None:
            self.control.Refresh(False)
            self.control.Update()
        wx.GetApp().Yield(True)

    def _on_paint(self, event):
        """ Called when the splash window is being repainted. """

        if self.control is not None:
            # Get the window that the splash image is drawn in.
            window = self.control  # .GetSplashWindow()

            dc = wx.PaintDC(window)

            if self.text_font is None:
                text_font = self._wx_default_text_font
            else:
                text_font = self.text_font

            dc.SetFont(text_font)

            if self.text_color is None:
                text_color = "black"
            else:
                text_color = self.text_color

            dc.SetTextForeground(text_color)

            x, y = self.text_location
            dc.DrawText(self.text, x, y)

        # Let the normal wx paint handling do its stuff.
        event.Skip()
 def post_setattr(self, object, name, value):
     """ Create a shadow variable that holds the actual image.
     """
     # fixme: Should this be try/except protected to prevent exceptions?
     ir = ImageResource(value)
     object.__dict__[name + '_'] = gc_image_for(ir.absolute_path)
Exemple #18
0
class SwiftConsole(HasTraits):
    """Traits-defined Swift Console.

    link : object
      Serial driver
    update : bool
      Update the firmware
    log_level_filter : str
      Syslog string, one of "ERROR", "WARNING", "INFO", "DEBUG".
    """

    link = Instance(sbpc.Handler)
    console_output = Instance(OutputList())
    python_console_env = Dict
    device_serial = Str('')
    dev_id = Str('')
    tracking_view = Instance(TrackingView)
    solution_view = Instance(SolutionView)
    baseline_view = Instance(BaselineView)
    skyplot_view = Instance(SkyplotView)
    observation_view = Instance(ObservationView)
    networking_view = Instance(SbpRelayView)
    observation_view_base = Instance(ObservationView)
    system_monitor_view = Instance(SystemMonitorView)
    settings_view = Instance(SettingsView)
    update_view = Instance(UpdateView)
    ins_view = Instance(INSView)
    mag_view = Instance(MagView)
    spectrum_analyzer_view = Instance(SpectrumAnalyzerView)
    log_level_filter = Enum(list(SYSLOG_LEVELS.values()))
    """"
  mode : baseline and solution view - SPP, Fixed or Float
  num_sat : baseline and solution view - number of satellites
  port : which port is Swift Device is connected to
  directory_name : location of logged files
  json_logging : enable JSON logging
  csv_logging : enable CSV logging

  """
    pos_mode = Str('')
    rtk_mode = Str('')
    ins_status_string = Str('')
    num_sats_str = Str('')
    cnx_desc = Str('')
    age_of_corrections = Str('')
    uuid = Str('')
    directory_name = Directory
    json_logging = Bool(True)
    csv_logging = Bool(False)
    show_csv_log = Bool(False)
    cnx_icon = Str('')
    heartbeat_count = Int()
    last_timer_heartbeat = Int()
    driver_data_rate = Str()
    solid_connection = Bool(False)

    csv_logging_button = SVGButton(
        toggle=True,
        label='CSV log',
        tooltip='start CSV logging',
        toggle_tooltip='stop CSV logging',
        filename=resource_filename('console/images/iconic/pause.svg'),
        toggle_filename=resource_filename('console/images/iconic/play.svg'),
        orientation='vertical',
        width=2,
        height=2,
    )
    json_logging_button = SVGButton(
        toggle=True,
        label='JSON log',
        tooltip='start JSON logging',
        toggle_tooltip='stop JSON logging',
        filename=resource_filename('console/images/iconic/pause.svg'),
        toggle_filename=resource_filename('console/images/iconic/play.svg'),
        orientation='vertical',
        width=2,
        height=2,
    )
    paused_button = SVGButton(
        label='',
        tooltip='Pause console update',
        toggle_tooltip='Resume console update',
        toggle=True,
        filename=resource_filename('console/images/iconic/pause.svg'),
        toggle_filename=resource_filename('console/images/iconic/play.svg'),
        width=8,
        height=8)
    clear_button = SVGButton(
        label='',
        tooltip='Clear console buffer',
        filename=resource_filename('console/images/iconic/x.svg'),
        width=8,
        height=8)

    view = View(VSplit(
        Tabbed(Tabbed(Item('tracking_view',
                           style='custom',
                           label='Signals',
                           show_label=False),
                      Item('skyplot_view',
                           style='custom',
                           label='Sky Plot',
                           show_label=False),
                      label="Tracking"),
               Item('solution_view', style='custom', label='Solution'),
               Item('baseline_view', style='custom', label='Baseline'),
               VSplit(
                   Item('observation_view', style='custom', show_label=False),
                   Item('observation_view_base',
                        style='custom',
                        show_label=False),
                   label='Observations',
               ),
               Item('settings_view', style='custom', label='Settings'),
               Item('update_view', style='custom', label='Update'),
               Tabbed(Item('system_monitor_view',
                           style='custom',
                           label='System Monitor'),
                      Item('ins_view', style='custom', label='INS'),
                      Item('mag_view', style='custom', label='Magnetometer'),
                      Item('networking_view',
                           label='Networking',
                           style='custom',
                           show_label=False),
                      Item('spectrum_analyzer_view',
                           label='Spectrum Analyzer',
                           style='custom'),
                      label='Advanced',
                      show_labels=False),
               show_labels=False),
        VGroup(
            VGroup(
                HGroup(
                    Spring(width=4, springy=False),
                    Item('paused_button',
                         show_label=False,
                         padding=0,
                         width=8,
                         height=8),
                    Item('clear_button', show_label=False, width=8, height=8),
                    Item('', label='Console Log', emphasized=True),
                    Item('csv_logging_button',
                         emphasized=True,
                         show_label=False,
                         visible_when='show_csv_log',
                         width=12,
                         height=-30,
                         padding=0),
                    Item('json_logging_button',
                         emphasized=True,
                         show_label=False,
                         width=12,
                         height=-30,
                         padding=0),
                    Item(
                        'directory_name',
                        show_label=False,
                        springy=True,
                        tooltip=
                        'Choose location for file logs. Default is home/SwiftNav.',
                        height=-25,
                        enabled_when='not(json_logging or csv_logging)',
                        editor_args={'auto_set': True}),
                    UItem(
                        'log_level_filter',
                        style='simple',
                        padding=0,
                        height=8,
                        show_label=True,
                        tooltip=
                        'Show log levels up to and including the selected level of severity.\nThe CONSOLE log level is always visible.'
                    ),
                ),
                Item('console_output',
                     style='custom',
                     editor=InstanceEditor(),
                     height=125,
                     show_label=False,
                     full_size=True),
            ),
            HGroup(
                Spring(width=4, springy=False),
                Item('',
                     label='Port:',
                     emphasized=True,
                     tooltip='Interface for communicating with Swift device'),
                Item('cnx_desc', show_label=False, style='readonly'),
                Item('',
                     label='Pos:',
                     emphasized=True,
                     tooltip='Device Position Mode: SPS, DGNSS, or RTK'),
                Item('pos_mode', show_label=False, style='readonly'),
                Item('',
                     label='RTK:',
                     emphasized=True,
                     tooltip='Device RTK Mode: Float or Fixed'),
                Item('rtk_mode', show_label=False, style='readonly'),
                Item('',
                     label='Sats:',
                     emphasized=True,
                     tooltip='Number of satellites used in solution'),
                Item('num_sats_str',
                     padding=2,
                     show_label=False,
                     style='readonly'),
                Item('',
                     label='Corr Age:',
                     emphasized=True,
                     tooltip=
                     'Age of corrections (-- means invalid / not present)'),
                Item('age_of_corrections',
                     padding=2,
                     show_label=False,
                     style='readonly'),
                Item('',
                     label='INS:',
                     emphasized=True,
                     tooltip='INS Status String'),
                Item('ins_status_string',
                     padding=2,
                     show_label=False,
                     style='readonly',
                     width=6),
                Spring(springy=True),
                Item('driver_data_rate', style='readonly', show_label=False),
                Item('cnx_icon',
                     show_label=False,
                     padding=0,
                     width=8,
                     height=8,
                     visible_when='solid_connection',
                     springy=False,
                     editor=ImageEditor(
                         allow_clipping=False,
                         image=ImageResource(
                             resource_filename(
                                 'console/images/iconic/arrows_blue.png')))),
                Item('cnx_icon',
                     show_label=False,
                     padding=0,
                     width=8,
                     height=8,
                     visible_when='not solid_connection',
                     springy=False,
                     editor=ImageEditor(
                         allow_clipping=False,
                         image=ImageResource(
                             resource_filename(
                                 'console/images/iconic/arrows_grey.png')))),
                Spring(width=4, height=-2, springy=False),
            ),
            Spring(height=1, springy=False),
        ),
    ),
                icon=icon,
                resizable=True,
                width=800,
                height=600,
                handler=ConsoleHandler(),
                title=CONSOLE_TITLE)

    def print_message_callback(self, sbp_msg, **metadata):
        try:
            encoded = sbp_msg.payload.encode('ascii', 'ignore')
            for eachline in reversed(encoded.split('\n')):
                self.console_output.write_level(
                    eachline, str_to_log_level(eachline.split(':')[0]))
        except UnicodeDecodeError as e:
            print("Error encoding msg_print: {}".format(e))

    def log_message_callback(self, sbp_msg, **metadata):
        encoded = sbp_msg.text.decode('utf8')
        for eachline in reversed(encoded.split('\n')):
            self.console_output.write_level(eachline, sbp_msg.level)

    def ext_event_callback(self, sbp_msg, **metadata):
        e = MsgExtEvent(sbp_msg)
        print(
            'External event: %s edge on pin %d at wn=%d, tow=%d, time qual=%s'
            % ("Rising" if
               (e.flags &
                (1 << 0)) else "Falling", e.pin, e.wn, e.tow, "good" if
               (e.flags & (1 << 1)) else "unknown"))

    def cmd_resp_callback(self, sbp_msg, **metadata):
        r = MsgCommandResp(sbp_msg)
        print("Received a command response message with code {0}".format(
            r.code))

    def _paused_button_fired(self):
        self.console_output.paused = not self.console_output.paused

    def _log_level_filter_changed(self):
        """
        Takes log level enum and translates into the mapped integer.
        Integer stores the current filter value inside OutputList.
        """
        self.console_output.log_level_filter = str_to_log_level(
            self.log_level_filter)

    def _clear_button_fired(self):
        self.console_output.clear()

    def _directory_name_changed(self):
        if self.baseline_view and self.solution_view:
            self.baseline_view.directory_name_b = self.directory_name
            self.solution_view.directory_name_p = self.directory_name
            self.solution_view.directory_name_v = self.directory_name
        if self.observation_view and self.observation_view_base:
            self.observation_view.dirname = self.directory_name
            self.observation_view_base.dirname = self.directory_name

    def update_on_heartbeat(self, sbp_msg, **metadata):
        self.heartbeat_count += 1

    def check_heartbeat(self):
        # if our heartbeat hasn't changed since the last timer interval the connection must have dropped
        if self.heartbeat_count == self.last_timer_heartbeat and self.heartbeat_count != 0:
            self.solid_connection = False
            self.ins_status_string = "None"
            self.pos_mode = "None"
            self.ins_mode = "None"
            self.num_sats_str = EMPTY_STR
            self.last_timer_heartbeat = self.heartbeat_count
        else:
            self.solid_connection = True
        self.last_timer_heartbeat = self.heartbeat_count

        bytes_diff = self.driver.bytes_read_since(self.last_driver_bytes_read)
        # 1024 bytes per KiloByte
        self.driver_data_rate = "{0:.2f} KB/s".format(
            (bytes_diff) / (HEARTBEAT_CHECK_PERIOD_SECONDS * 1024))
        self.last_driver_bytes_read = self.driver.total_bytes_read

        # if we aren't getting heartbeats and we have at some point gotten heartbeats, we don't have
        # a good connection and we should age out the data from the views
        if not self.solid_connection or self.driver_data_rate == 0:
            return
        # -- grab current time to use in logic
        current_time = monotonic()
        # --- determining which mode, llh or baseline, to show in the status bar ---
        llh_display_mode = "None"
        llh_num_sats = 0
        llh_is_rtk = False

        baseline_display_mode = "None"

        ins_status_string = EMPTY_STR

        # determine the latest llh solution mode
        if self.solution_view and (current_time -
                                   self.solution_view.last_stime_update) < 1:
            llh_solution_mode = self.solution_view.last_pos_mode
            llh_display_mode = pos_mode_dict.get(llh_solution_mode, EMPTY_STR)
            if llh_solution_mode > 0 and self.solution_view.last_soln:
                llh_num_sats = self.solution_view.last_soln.n_sats
            llh_is_rtk = (llh_solution_mode in RTK_MODES)
            if getattr(self.solution_view, 'ins_used',
                       False) and llh_solution_mode != DR_MODE:
                llh_display_mode += "+INS"

        # determine the latest baseline solution mode
        if (self.baseline_view and self.settings_view
                and self.settings_view.dgnss_enabled
                and (current_time - self.baseline_view.last_btime_update) < 1):
            baseline_solution_mode = self.baseline_view.last_mode
            baseline_display_mode = rtk_mode_dict.get(baseline_solution_mode,
                                                      EMPTY_STR)

        # if baseline solution mode is empty and POS mode is RTK, get the RTK mode from pos
        if baseline_display_mode not in rtk_mode_dict.values() and llh_is_rtk:
            baseline_display_mode = rtk_mode_dict.get(llh_solution_mode)

        # determine the latest INS mode
        if self.solution_view and (
                current_time -
                self.solution_view.last_ins_status_receipt_time) < 1:
            ins_flags = self.solution_view.ins_status_flags
            ins_mode = ins_flags & 0x7
            ins_type = (ins_flags >> 29) & 0x7
            odo_status = (ins_flags >> 8) & 0x3
            # ins_status has bug in odo.
            # If it says no odo, check if we have had tics in last 10 seconds from INS_UPDATES
            if odo_status != 1:
                if (current_time -
                        self.solution_view.last_odo_update_time) < 10:
                    odo_status = 1
            ins_error = (ins_flags >> 4) & 0xF
            if ins_error != 0:
                ins_status_string = ins_error_dict.get(ins_error, "Unk Error")
            else:
                ins_status_string = ins_type_dict.get(ins_type, "unk") + "-"
                ins_status_string += ins_mode_dict.get(ins_mode, "unk")
                if odo_status == 1:
                    ins_status_string += "+Odo"

        # get age of corrections from baseline view
        if self.baseline_view:
            if (self.baseline_view.age_corrections is not None
                    and (current_time -
                         self.baseline_view.last_age_corr_receipt_time) < 1):
                self.age_of_corrections = "{0} s".format(
                    self.baseline_view.age_corrections)
            else:
                self.age_of_corrections = EMPTY_STR

        # populate modes and #sats on status bar
            self.ins_status_string = ins_status_string
            self.rtk_mode = baseline_display_mode
            self.pos_mode = llh_display_mode
            self.num_sats_str = "{}".format(llh_num_sats)

        # --- end of status bar mode determination section ---

        if self.settings_view:  # for auto populating surveyed fields
            self.settings_view.lat = self.solution_view.latitude
            self.settings_view.lon = self.solution_view.longitude
            self.settings_view.alt = self.solution_view.altitude

    def _csv_logging_button_action(self):
        if self.csv_logging and self.baseline_view.logging_b and self.solution_view.logging_p and self.solution_view.logging_v:
            print("Stopped CSV logging")
            self.csv_logging = False
            self.baseline_view.logging_b = False
            self.solution_view.logging_p = False
            self.solution_view.logging_v = False

        else:
            print("Started CSV logging at %s" % self.directory_name)
            self.csv_logging = True
            self.baseline_view.logging_b = True
            self.solution_view.logging_p = True
            self.solution_view.logging_v = True

    def _start_json_logging(self, override_filename=None):
        if override_filename:
            filename = override_filename
        else:
            filename = time.strftime("swift-gnss-%Y%m%d-%H%M%S.sbp.json",
                                     time.localtime())
            filename = os.path.normpath(
                os.path.join(self.directory_name, filename))
        self.logger = s.get_logger(True, filename, self.expand_json)
        self.forwarder = sbpc.Forwarder(self.link, self.logger)
        self.forwarder.start()
        if self.settings_view:
            self.settings_view._settings_read_all()

    def _stop_json_logging(self):
        fwd = self.forwarder
        fwd.stop()
        self.logger.flush()
        self.logger.close()

    def _json_logging_button_action(self):
        if self.first_json_press and self.json_logging:
            print(
                "JSON Logging initiated via CMD line.  Please press button again to stop logging"
            )
        elif self.json_logging:
            self._stop_json_logging()
            self.json_logging = False
            print("Stopped JSON logging")
        else:
            self._start_json_logging()
            self.json_logging = True
        self.first_json_press = False

    def _json_logging_button_fired(self):
        if not os.path.exists(self.directory_name) and not self.json_logging:
            print(
                "The selected logging directory does not exist and will be created."
            )
        self._json_logging_button_action()

    def _csv_logging_button_fired(self):
        if not os.path.exists(self.directory_name) and not self.csv_logging:
            print(
                "The selected logging directory does not exist and will be created."
            )
        self._csv_logging_button_action()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.console_output.close()

    def __init__(self,
                 link,
                 driver,
                 update,
                 log_level_filter,
                 error=False,
                 cnx_desc=None,
                 json_logging=False,
                 show_csv_log=False,
                 log_dirname=None,
                 override_filename=None,
                 log_console=False,
                 connection_info=None,
                 expand_json=False,
                 hide_legend=False):
        self.error = error
        self.cnx_desc = cnx_desc
        self.connection_info = connection_info
        self.show_csv_log = show_csv_log
        self.dev_id = cnx_desc
        self.num_sats_str = EMPTY_STR
        self.mode = ''
        self.ins_status_string = "None"
        self.forwarder = None
        self.age_of_corrections = '--'
        self.expand_json = expand_json
        # if we have passed a logfile, we set our directory to it
        override_filename = override_filename
        self.last_status_update_time = 0
        self.last_driver_bytes_read = 0
        self.driver = driver

        if log_dirname:
            self.directory_name = log_dirname
            if override_filename:
                override_filename = os.path.join(log_dirname,
                                                 override_filename)
        else:
            self.directory_name = swift_path

        # Start swallowing sys.stdout and sys.stderr
        self.console_output = OutputList(tfile=log_console,
                                         outdir=self.directory_name)
        sys.stdout = self.console_output
        self.console_output.write("Console: " + CONSOLE_VERSION +
                                  " starting...")
        if not error:
            sys.stderr = self.console_output

        self.log_level_filter = log_level_filter
        self.console_output.log_level_filter = str_to_log_level(
            log_level_filter)
        try:
            self.link = link
            self.link.add_callback(self.print_message_callback,
                                   SBP_MSG_PRINT_DEP)
            self.link.add_callback(self.log_message_callback, SBP_MSG_LOG)
            self.link.add_callback(self.ext_event_callback, SBP_MSG_EXT_EVENT)
            self.link.add_callback(self.cmd_resp_callback,
                                   SBP_MSG_COMMAND_RESP)
            self.link.add_callback(self.update_on_heartbeat, SBP_MSG_HEARTBEAT)
            self.dep_handler = DeprecatedMessageHandler(link)
            settings_read_finished_functions = []
            self.tracking_view = TrackingView(self.link,
                                              legend_visible=(not hide_legend))
            self.solution_view = SolutionView(self.link,
                                              dirname=self.directory_name)
            self.baseline_view = BaselineView(self.link,
                                              dirname=self.directory_name)
            self.skyplot_view = SkyplotView(self.link, self.tracking_view)
            self.observation_view = ObservationView(
                self.link,
                name='Local',
                relay=False,
                dirname=self.directory_name,
                tracking_view=self.tracking_view)
            self.observation_view_base = ObservationView(
                self.link,
                name='Remote',
                relay=True,
                dirname=self.directory_name)
            self.system_monitor_view = SystemMonitorView(self.link)
            self.update_view = UpdateView(self.link,
                                          download_dir=swift_path,
                                          prompt=update,
                                          connection_info=self.connection_info)
            self.ins_view = INSView(self.link)
            self.mag_view = MagView(self.link)
            self.spectrum_analyzer_view = SpectrumAnalyzerView(self.link)
            settings_read_finished_functions.append(
                self.update_view.compare_versions)
            self.networking_view = SbpRelayView(self.link)
            self.json_logging = json_logging
            self.csv_logging = False
            self.first_json_press = True
            if json_logging:
                self._start_json_logging(override_filename)
                self.json_logging = True
            # we set timer interval to 1200 milliseconds because we expect a heartbeat each second
            self.timer_cancel = call_repeatedly(HEARTBEAT_CHECK_PERIOD_SECONDS,
                                                self.check_heartbeat)

            # Once we have received the settings, update device_serial with
            # the Swift serial number which will be displayed in the window
            # title. This callback will also update the header route as used
            # by the networking view.

            def update_serial():
                mfg_id = None
                try:
                    self.uuid = self.settings_view.settings['system_info'][
                        'uuid'].value
                    mfg_id = self.settings_view.settings['system_info'][
                        'serial_number'].value
                except KeyError:
                    pass
                if mfg_id:
                    self.device_serial = 'PK' + str(mfg_id)

            skip_settings_read = False
            if 'mode' in self.connection_info:
                if self.connection_info['mode'] == 'file':
                    skip_settings_read = True

            settings_read_finished_functions.append(update_serial)
            self.settings_view = SettingsView(self.link,
                                              settings_read_finished_functions,
                                              skip_read=skip_settings_read)
            self.update_view.settings = self.settings_view.settings
            self.python_console_env = {
                'send_message': self.link,
                'link': self.link,
            }
            self.python_console_env.update(
                self.tracking_view.python_console_cmds)
            self.python_console_env.update(
                self.solution_view.python_console_cmds)
            self.python_console_env.update(
                self.baseline_view.python_console_cmds)
            self.python_console_env.update(
                self.skyplot_view.python_console_cmds)
            self.python_console_env.update(
                self.observation_view.python_console_cmds)
            self.python_console_env.update(
                self.networking_view.python_console_cmds)
            self.python_console_env.update(
                self.system_monitor_view.python_console_cmds)
            self.python_console_env.update(
                self.update_view.python_console_cmds)
            self.python_console_env.update(self.ins_view.python_console_cmds)
            self.python_console_env.update(self.mag_view.python_console_cmds)
            self.python_console_env.update(
                self.settings_view.python_console_cmds)
            self.python_console_env.update(
                self.spectrum_analyzer_view.python_console_cmds)

        except:  # noqa
            import traceback
            traceback.print_exc()
            if self.error:
                os._exit(1)
Exemple #19
0
try:
    from apptools.io import File
except ImportError:
    File = None

try:
    from apptools.naming.api import Binding
except ImportError:
    Binding = None

from pyface.image_resource import ImageResource

from .editor import Editor

# The image to use when the editor accepts files:
file_image = ImageResource("file").create_image()

# The image to use when the editor accepts objects:
object_image = ImageResource("object").create_image()

# The image to use when the editor is disabled:
inactive_image = ImageResource("inactive").create_image()

# String types:
string_type = (str, str)

# -------------------------------------------------------------------------
#  'SimpleEditor' class:
# -------------------------------------------------------------------------

Exemple #20
0
    id_lbl = None

    if code_is_glo(code):
        freq_lbl = 'F{sat:0=+3d}'.format(sat=sat)
        if sat in extra:
            id_lbl = 'R{slot:02d}'.format(slot=extra[sat])
        else:
            id_lbl = 'R{slot:02d}'.format(slot=sat)
    elif code_is_sbas(code):
        id_lbl = 'S{sat:3d}'.format(sat=sat)
    elif code_is_bds(code):
        id_lbl = 'C{sat:02d}'.format(sat=sat)
    elif code_is_qzss(code):
        id_lbl = 'J{sat:3d}'.format(sat=sat)
    elif code_is_galileo(code):
        id_lbl = 'E{sat:02d}'.format(sat=sat)
    else:
        id_lbl = 'G{sat:02d}'.format(sat=sat)

    return (code_lbl, freq_lbl, id_lbl)


resource_filename = partial(pkg_resources.resource_filename, 'piksi_tools')
resource_stream = partial(pkg_resources.resource_stream, 'piksi_tools')
icon = ImageResource(resource_filename('console/images/icon.png'))

(language_code, encoding) = locale.getdefaultlocale()
home_path_raw = os.path.expanduser(b"~")
home_path = home_path_raw.decode(encoding if encoding is not None else 'ascii')
swift_path = os.path.normpath(os.path.join(home_path, 'SwiftNav'))
Exemple #21
0
from traitsui.menu import *

from pyface.dock.api import *

from pyface.image_resource import ImageResource

# -------------------------------------------------------------------------------
#  Global data:
# -------------------------------------------------------------------------------

# DockControl style to use:
style1 = "horizontal"
style2 = "vertical"

image1 = ImageResource("folder")
image2 = ImageResource("gear")

# -------------------------------------------------------------------------------
#  Creates a DockWindow as a Traits UI widget:
# -------------------------------------------------------------------------------


def create_dock_window(parent, editor):
    """ Creates a window for editing a workflow canvas.
    """
    window = DockWindow(parent).control
    button1 = wx.Button(window, -1, "Button 1")
    button2 = wx.Button(window, -1, "Button 2")
    button3 = wx.Button(window, -1, "Button 3")
    button4 = wx.Button(window, -1, "Button 4")
Exemple #22
0
    def default_icon(self):
        """Return a default icon for a TraitsUI dialog."""
        from pyface.image_resource import ImageResource

        return ImageResource("frame.png")
    def _get_big_image(self):
        size = self.item.size
        if size > 65536:
            return ImageResource('red_ball')

        return (None, ImageResource('blue_ball'))[size > 16384]


#-- Tabular Editor Definition --------------------------------------------

tabular_editor = TabularEditor(editable=False,
                               selected='file_info',
                               adapter=FileInfoAdapter(),
                               operations=[],
                               images=[
                                   ImageResource('blue_ball',
                                                 search_path=search_path),
                                   ImageResource('red_ball',
                                                 search_path=search_path)
                               ])

#-- PythonBrowser Class Definition ---------------------------------------


class PythonBrowser(HasPrivateTraits):

    #-- Trait Definitions ----------------------------------------------------

    dir = Directory()
    files = List(FileInfo)
    file_info = Instance(FileInfo)
    code = Code()
Exemple #24
0
class AboutDialog(MAboutDialog, Dialog):
    """ The toolkit specific implementation of an AboutDialog.  See the
    IAboutDialog interface for the API documentation.
    """

    implements(IAboutDialog)

    #### 'IAboutDialog' interface #############################################

    additions = List(Unicode)

    image = Instance(ImageResource, ImageResource('about'))

    ###########################################################################
    # Protected 'IDialog' interface.
    ###########################################################################

    def _create_contents(self, parent):
        if parent.GetParent() is not None:
            title = parent.GetParent().GetTitle()

        else:
            title = ""

        # Set the title.
        self.title = "About %s" % title

        # Load the image to be displayed in the about box.
        image = self.image.create_image()
        path = self.image.absolute_path

        # The additional strings.
        additions = '<br />'.join(self.additions)

        # The width of a wx HTML window is fixed (and  is given in the
        # constructor). We set it to the width of the image plus a fudge
        # factor! The height of the window depends on the content.
        width = image.GetWidth() + 80
        html = wx.html.HtmlWindow(parent, -1, size=(width, -1))

        # Get the version numbers.
        py_version = sys.version[0:sys.version.find("(")]
        wx_version = wx.VERSION_STRING

        # Get the text of the OK button.
        if self.ok_label is None:
            ok = "OK"
        else:
            ok = self.ok_label

        # Set the page contents.
        html.SetPage(_DIALOG_TEXT %
                     (path, additions, py_version, wx_version, ok))

        # Make the 'OK' button the default button.
        ok_button = html.FindWindowById(wx.ID_OK)
        ok_button.SetDefault()

        # Set the height of the HTML window to match the height of the content.
        internal = html.GetInternalRepresentation()
        html.SetSize((-1, internal.GetHeight()))

        # Make the dialog client area big enough to display the HTML window.
        # We add a fudge factor to the height here, although I'm not sure why
        # it should be necessary, the HTML window should report its required
        # size!?!
        width, height = html.GetSize()
        parent.SetClientSize((width, height + 10))
Exemple #25
0
def default_icon():
    from pyface.image_resource import ImageResource
    return ImageResource('frame.png')
Exemple #26
0
class HeadingText(MHeadingText, Widget):
    """ The toolkit specific implementation of a HeadingText.  See the
    IHeadingText interface for the API documentation.
    """


    #### 'IHeadingText' interface #############################################

    level = Int(1)

    text = Unicode('Default')

    image = Instance(ImageResource, ImageResource('heading_level_1'))

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __init__(self, parent, **traits):
        """ Creates the panel. """

        # Base class constructor.
        super(HeadingText, self).__init__(**traits)

        # Create the toolkit-specific control that represents the widget.
        self.control = self._create_control(parent)

        return

    ###########################################################################
    # Private interface.
    ###########################################################################

    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        # The background image (it is tiled).
        image = self.image.create_image()
        self._bmp = image.ConvertToBitmap()

        sizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN | wx.SIMPLE_BORDER)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)

        # Create a suitable font.
        self._font = new_font_like(wx.NORMAL_FONT, family=wx.SWISS)

        width, height = self._get_preferred_size(self.text, self._font)
        panel.SetMinSize((width, height))

        wx.EVT_PAINT(panel, self._on_paint_background)
        wx.EVT_ERASE_BACKGROUND(panel, self._on_erase_background)

        return panel

    def _get_preferred_size(self, text, font):
        """ Calculates the preferred size of the widget. """

        dc = wx.ScreenDC()

        dc.SetFont(font)
        width, height = dc.GetTextExtent(text)

        return (width + 10, height + 10)

    def _tile_background_image(self, dc, width, height):
        """ Tiles the background image. """

        w = self._bmp.GetWidth()
        h = self._bmp.GetHeight()

        x = 0
        while x < width:
            y = 0
            while y < height:
                dc.DrawBitmap(self._bmp, x, y)
                y = y + h

            x = x + w

        return

    #### Trait event handlers #################################################

    def _text_changed(self, new):
        """ Called when the text is changed. """

        if self.control is not None:
            self.control.Refresh()

        return

    #### wx event handlers ####################################################

    def _on_paint_background(self, event):
        """ Called when the background of the panel is painted. """

        dc = wx.PaintDC(self.control)
        size = self.control.GetClientSize()

        # Tile the background image.
        self._tile_background_image(dc, size.width, size.height)

        # Render the text.
        dc.SetFont(self._font)
        dc.DrawText(self.text, 5, 4)

        return

    def _on_erase_background(self, event):
        """ Called when the background of the panel is erased. """

        dc = event.GetDC()
        size = self.control.GetClientSize()

        # Tile the background image.
        self._tile_background_image(dc, size.width, size.height)

        # Render the text.
        dc.SetFont(self._font)
        dc.DrawText(self.text, 5, 4)

        return
Exemple #27
0
def run_gui():
    debug = ("--debug" in sys.argv)

    remote_process, remote_connection = start_remote_process(debug)

    # We want matplotlib to use our backend .... in both the GUI and the
    # remote process

    import matplotlib
    matplotlib.use('module://cytoflowgui.matplotlib_backend')

    # getting real tired of the matplotlib deprecation warnings
    import warnings
    warnings.filterwarnings('ignore', '.*is deprecated and replaced with.*')

    from traits.api import push_exception_handler

    def QtMsgHandler(msg_type, msg_string):
        # Convert Qt msg type to logging level
        log_level = [
            logging.DEBUG, logging.WARN, logging.ERROR, logging.FATAL
        ][int(msg_type)]
        logging.log(log_level, 'Qt message: ' + msg_string.decode('utf-8'))

    ## monkey-patch envisage for a py3k bug.  this is fixed in envisage HEAD,
    ## so check for version
    import envisage
    if envisage.__version__ == '4.6.0':
        import pickle
        from envisage.ui.tasks.tasks_application import TasksApplication, TasksApplicationState
        logger = logging.getLogger(__name__)
        logger.info("Monkey-patching envisage 4.6.0")

        def _envisage_load_state(self):
            """ Loads saved application state, if possible.
            """
            state = TasksApplicationState()
            filename = os.path.join(self.state_location, 'application_memento')
            if os.path.exists(filename):
                # Attempt to unpickle the saved application state.
                try:
                    with open(filename, 'rb') as f:
                        restored_state = pickle.load(f)
                    if state.version == restored_state.version:
                        state = restored_state
                    else:
                        logger.warn('Discarding outdated application layout')
                except:
                    # If anything goes wrong, log the error and continue.
                    logger.exception('Restoring application layout from %s',
                                     filename)

            self._state = state

        def _envisage_save_state(self):
            """ Saves the application state.
            """
            # Grab the current window layouts.
            window_layouts = [w.get_window_layout() for w in self.windows]
            self._state.previous_window_layouts = window_layouts

            # Attempt to pickle the application state.
            filename = os.path.join(self.state_location, 'application_memento')
            try:
                with open(filename, 'wb') as f:
                    pickle.dump(self._state, f)
            except:
                # If anything goes wrong, log the error and continue.
                logger.exception('Saving application layout')

        TasksApplication._load_state = _envisage_load_state
        TasksApplication._save_state = _envisage_save_state

    from envisage.core_plugin import CorePlugin
    from envisage.ui.tasks.tasks_plugin import TasksPlugin
    from pyface.image_resource import ImageResource

    from cytoflowgui.flow_task import FlowTaskPlugin
    from cytoflowgui.cytoflow_application import CytoflowApplication
    from cytoflowgui.op_plugins import (
        ImportPlugin,
        ThresholdPlugin,
        RangePlugin,
        QuadPlugin,
        Range2DPlugin,
        PolygonPlugin,
        BinningPlugin,
        GaussianMixture1DPlugin,
        GaussianMixture2DPlugin,
        BleedthroughLinearPlugin,  #BleedthroughPiecewisePlugin,
        BeadCalibrationPlugin,
        AutofluorescencePlugin,
        ColorTranslationPlugin,
        TasbePlugin,
        ChannelStatisticPlugin,
        TransformStatisticPlugin,
        RatioPlugin)

    from cytoflowgui.view_plugins import (
        HistogramPlugin,
        Histogram2DPlugin,
        ScatterplotPlugin,
        BarChartPlugin,
        Stats1DPlugin,
        Kde1DPlugin,  #Kde2DPlugin,
        ViolinPlotPlugin,
        TablePlugin,
        Stats2DPlugin)
    #    assert(multiprocessing.get_start_method() == "spawn")

    from cytoflow.utility.custom_traits import Removed, Deprecated
    Removed.gui = True
    Deprecated.gui = True

    from pyface.qt import qt_api

    cmd_line = " ".join(sys.argv)

    if qt_api == "pyside":
        print("Cytoflow uses PyQT; but it is trying to use PySide instead.")
        print(" - Make sure PyQT is installed.")
        print(
            " - If both are installed, and you don't need both, uninstall PySide."
        )
        print(" - If you must have both installed, select PyQT by setting the")
        print("   environment variable QT_API to \"pyqt\"")
        print("   * eg, on Linux, type on the command line:")
        print("     QT_API=\"pyqt\" " + cmd_line)
        print("   * on Windows, try: ")
        print("     setx QT_API \"pyqt\"")

        sys.exit(1)

    from pyface.qt.QtCore import qInstallMsgHandler  # @UnresolvedImport
    qInstallMsgHandler(QtMsgHandler)

    # if we're frozen, add _MEIPASS to the pyface search path for icons etc
    if getattr(sys, 'frozen', False):
        from pyface.resource_manager import resource_manager
        resource_manager.extra_paths.append(sys._MEIPASS)  # @UndefinedVariable

    # install a global (gui) error handler for traits notifications
    push_exception_handler(handler=log_notification_handler,
                           reraise_exceptions=debug,
                           main=True)

    sys.excepthook = log_excepthook

    plugins = [
        CorePlugin(),
        TasksPlugin(),
        FlowTaskPlugin(debug=debug, remote_connection=remote_connection)
    ]

    # reverse of the order on the toolbar
    view_plugins = [
        TablePlugin(),
        Stats2DPlugin(),
        Stats1DPlugin(),
        BarChartPlugin(),
        ViolinPlotPlugin(),
        #                     Kde2DPlugin(),    # disabled until we can make it faster
        Kde1DPlugin(),
        Histogram2DPlugin(),
        ScatterplotPlugin(),
        HistogramPlugin()
    ]

    plugins.extend(view_plugins)

    op_plugins = [
        RatioPlugin(),
        TransformStatisticPlugin(),
        ChannelStatisticPlugin(),
        TasbePlugin(),
        ColorTranslationPlugin(),
        AutofluorescencePlugin(),
        BeadCalibrationPlugin(),
        #                   BleedthroughPiecewisePlugin(),
        BleedthroughLinearPlugin(),
        GaussianMixture2DPlugin(),
        GaussianMixture1DPlugin(),
        BinningPlugin(),
        PolygonPlugin(),
        QuadPlugin(),
        Range2DPlugin(),
        RangePlugin(),
        ThresholdPlugin(),
        ImportPlugin()
    ]

    plugins.extend(op_plugins)

    # these two lines stop pkg_resources from trying to load resources
    # from the __main__ module, which is frozen (and thus not loadable.)
    icon = ImageResource('icon')
    icon.search_path = []

    app = CytoflowApplication(id='edu.mit.synbio.cytoflow',
                              plugins=plugins,
                              icon=icon,
                              debug=debug)
    app.run()
    remote_process.join()
    logging.shutdown()
from pyface.image_resource import ImageResource
from .dock_window import DockWindow
from .dock_sizer import (
    DockSizer,
    DockSection,
    DockRegion,
    DockControl,
    DOCK_RIGHT,
)

# -------------------------------------------------------------------------------
#  Constants:
# -------------------------------------------------------------------------------

# DockWindowShell frame icon:
FrameIcon = ImageResource("shell.ico")

# -------------------------------------------------------------------------------
#  'DockWindowShell' class:
# -------------------------------------------------------------------------------


class DockWindowShell(HasPrivateTraits):

    # ---------------------------------------------------------------------------
    #  Trait definitions:
    # ---------------------------------------------------------------------------

    # The wx.Frame window which is the actual shell:
    control = Instance(wx.Frame)