Exemplo n.º 1
0
 def default_traits_view(self):
     # XXX need to do this to hide the instantiation of ToolBar from null
     # toolkit tests.  It would be preferable to have this be declarative.
     return View(
         Item(
             name="model",
             id="model",
             show_label=False,
             editor=demo_tree_editor,
         ),
         id="traitsui.demos.demo.Demo",
         toolbar=ToolBar(
             previous_tool, parent_tool, next_tool, show_tool_names=True
         ),
         resizable=True,
         width=1200,
         height=700,
     )
Exemplo n.º 2
0
    def traits_view(self):
        sp = [os.path.join(os.path.dirname(__file__), 'icons')]

        sa = Action(name='save',
                    action='do_save',
                    image=ImageResource(name='file_pdf.png', search_path=sp))
        aa = Action(name='add band',
                    action='do_add_band',
                    image=ImageResource(name='add.png', search_path=sp))

        da = Action(name='delete band',
                    action='do_delete_band',
                    image=ImageResource(name='delete.png', search_path=sp))

        tb = ToolBar(sa, aa, da)

        main_grp = Group(Item('path'))
        highlight_bands_grp = UItem('highlighter', style='custom')
        v = View(VGroup(main_grp, Group(highlight_bands_grp, layout='tabbed')),
                 resizable=True,
                 width=800,
                 height=800,
                 toolbar=tb)
        return v
Exemplo n.º 3
0
class MainWindow(HasTraits):
    '''The main window for the Beams application.'''

    # Current folder for file dialog
    _current_folder = None

    camera = Instance(Camera)
    id_string = DelegatesTo('camera')
    resolution = DelegatesTo('camera')
    status = Str()
    screen = Instance(CameraImage, args=())
    cmap = DelegatesTo('screen')
    display_frame_rate = Range(1, 60, 15)
    transform_plugins = List(Instance(TransformPlugin))
    display_plugins = List(Instance(DisplayPlugin))
    acquisition_thread = Instance(AcquisitionThread)  # default: None
    processing_thread = Instance(ProcessingThread)  # default: None
    processing_queue = Instance(queue.Queue, kw={'maxsize': MAX_QUEUE_SIZE})
    cameras_dialog = Instance(CameraDialog, args=())

    # Actions
    about = Action(name='&About...',
                   tooltip='About Beams',
                   image=find_icon('about'),
                   action='action_about')
    save = Action(name='&Save Image',
                  accelerator='Ctrl+S',
                  tooltip='Save the current image to a file',
                  image=find_icon('save'),
                  action='action_save')
    quit = Action(name='&Quit',
                  accelerator='Ctrl+Q',
                  tooltip='Exit the application',
                  image=find_icon('quit'),
                  action='_on_close')
    choose_camera = Action(name='Choose &Camera...',
                           tooltip='Choose from a number of camera plugins',
                           action='action_choose_camera')
    take_video = Action(name='Take &Video',
                        style='toggle',
                        tooltip='Start viewing the video feed from the camera',
                        image=find_icon('camera-video'),
                        action='action_take_video')
    take_photo = Action(name='Take &Photo',
                        tooltip='Take one snapshot from the camera',
                        image=find_icon('camera-photo'),
                        action='action_take_photo',
                        enabled_when='self.take_video.checked == False')

    find_resolution = Button()
    view = View(
        VGroup(
            HSplit(
                Tabbed(
                    VGroup(Item('id_string', style='readonly', label='Camera'),
                           Item('resolution',
                                style='readonly',
                                format_str=u'%i \N{multiplication sign} %i'),
                           Group(Item('camera',
                                      show_label=False,
                                      style='custom'),
                                 label='Camera properties',
                                 show_border=True),
                           label='Camera'),
                    VGroup(Item('cmap',
                                label='Color scale',
                                editor=EnumEditor(
                                    values={
                                        None: '0:None (image default)',
                                        gray: '1:Grayscale',
                                        bone: '2:Bone',
                                        pink: '3:Copper',
                                        jet: '4:Rainbow (considered harmful)',
                                        isoluminant: '5:Isoluminant',
                                        awesome: '6:Low-intensity contrast'
                                    })),
                           Item('screen',
                                show_label=False,
                                editor=ColorMapEditor(width=256)),
                           Item('display_frame_rate'),
                           label='Video'),
                    # FIXME: mutable=False means the items can't be deleted,
                    # added, or rearranged, but we do actually want them to
                    # be rearranged.
                    VGroup(Item('transform_plugins',
                                show_label=False,
                                editor=ListEditor(style='custom',
                                                  mutable=False)),
                           label='Transform'),
                    VGroup(Item('display_plugins',
                                show_label=False,
                                editor=ListEditor(style='custom',
                                                  mutable=False)),
                           label='Math')),
                Item('screen',
                     show_label=False,
                     width=640,
                     height=480,
                     style='custom')),
            Item('status', style='readonly', show_label=False)),
        menubar=MenuBar(
            # vertical bar is undocumented but it seems to keep the menu
            # items in the order they were specified in
            Menu('|', save, '_', quit, name='&File'),
            Menu(name='&Edit'),
            Menu(name='&View'),
            Menu('|',
                 choose_camera,
                 '_',
                 take_photo,
                 take_video,
                 name='&Camera'),
            Menu(name='&Math'),
            Menu(about, name='&Help')),
        toolbar=ToolBar('|', save, '_', take_photo, take_video),
        title='Beams',
        resizable=True,
        handler=MainHandler)

    def _find_resolution_fired(self):
        return self.view.handler.action_find_resolution(None)

    def _display_frame_rate_changed(self, value):
        self.processing_thread.update_frequency = value

    def _transform_plugins_default(self):
        plugins = []
        for name in ['Rotator', 'BackgroundSubtract']:
            module = __import__(name, globals(), locals(), [name])
            plugins.append(getattr(module, name)())
        return plugins

    def _display_plugins_default(self):
        plugins = []
        for name in [
                'BeamProfiler', 'MinMaxDisplay', 'DeltaDetector', 'Centroid'
        ]:
            module = __import__(name, globals(), locals(), [name])
            plugins.append(getattr(module, name)(screen=self.screen))
        return plugins

    def __init__(self, **traits):
        super(MainWindow, self).__init__(**traits)

        # Build the camera selection dialog box
        self.cameras_dialog.on_trait_change(self.on_cameras_response, 'closed')
        self.on_cameras_response()

        self.processing_thread = ProcessingThread(self, self.processing_queue,
                                                  self.display_frame_rate)
        self.processing_thread.start()

    def on_cameras_response(self):
        plugin_obj = self.cameras_dialog.get_plugin_object()
        try:
            self.select_plugin(plugin_obj)
        except ImportError:
            # some module was not available, select the dummy
            error(
                None, 'Loading the {} camera plugin failed. '
                'Taking you back to the dummy plugin.'.format(
                    plugin_obj['name']))
            self.cameras_dialog.select_fallback()
            info = self.cameras_dialog.get_plugin_info()
            self.select_plugin(*info)

    # Select camera plugin
    def select_plugin(self, plugin_obj):
        # Set up image capturing
        self.camera = plugin_obj()
        try:
            self.camera.open()
        except CameraError:
            error(None,
                  'No camera was detected. Did you forget to plug it in?')
            sys.exit()
Exemplo n.º 4
0
class BMCSWindow(HasStrictTraits):
    '''View object for a cross section state.
    '''
    root = Instance(BMCSTreeNode)

    selected_node = Instance(HasStrictTraits)

    def _selected_node_changed(self):
        self.selected_node.ui = self

    plot_dock_pane = Instance(PlotDockPane, ())

    data_changed = Event

    replot = Button

    def _replot_fired(self):
        self.figure.clear()
        self.selected_node.plot(self.figure)
        self.data_changed = True

    clear = Button()

    def _clear_fired(self):
        self.figure.clear()
        self.data_changed = True

    #time = self.root.time

    view = View(
        HSplit(
            Group(
                Item(
                    'root',
                    id='bmcs.hsplit.left.tree.id',
                    dock='tab',
                    editor=tree_editor,
                    resizable=True,
                    show_label=False,
                    width=300,
                    height=200,
                ),
                #                Item('selected_node@'),
                id='bmcs.hsplit.left.id',
                dock='tab',
            ),
            Group(
                Item(
                    'plot_dock_pane@',
                    show_label=False,
                    id='bmcs.hsplit.viz3d.notebook.id',
                    dock='tab',
                ),
                # Item('self.root.time', label='t/T_max'),
                dock='tab',
                id='bmcs.hsplit.viz3d.id',
                label='plot sheet',
            ),
            dock='tab',
            id='bmcs.hsplit.id',
        ),
        #        dock='tab',
        id='bmcs.id',
        width=1.0,
        height=1.0,
        title='BMCS',
        resizable=True,
        handler=BMCSTreeViewHandler(),
        toolbar=ToolBar(*toolbar_actions),
        menubar=MenuBar(
            Menu(menu_exit, Separator(), menu_save, menu_open, name='File')))
Exemplo n.º 5
0
class ImageView(ModelView):
    """A model view of an image with actions.
    """

    #: The image model being viewed.
    model = Instance(ImageModel, (), allow_none=False)

    #: The image to display.
    image = Image()

    def rotate_left(self):
        """Rotate the image anticlockwise."""
        self.model.rotate("anticlockwise")

    def rotate_right(self):
        """Rotate the image clockwise."""
        self.model.rotate("clockwise")

    def flip_horizontal(self):
        """Flip the image horizontally."""
        self.model.flip("horizontal")

    def flip_vertical(self):
        """Flip the image vertically."""
        self.model.flip("vertical")

    def reload(self):
        """Reload the image from disk."""
        self.model.load_image()

    @observe('model.data')
    def _update_image(self, event):
        self.image = ArrayImage(data=self.model.data)

    def _image_default(self):
        return ArrayImage(data=self.model.data)

    view = View(
        HSplit(
            Item(
                'model.image_path',
                editor=FileEditor(
                    dialog_style='open',
                    filter=["*.png", "*.jpg", "*.jpeg"]
                ),
                style='custom',
            ),
            Item(
                'image',
                editor=ImageEditor(
                    scale=True,
                    preserve_aspect_ratio=True,
                    allow_upscaling=True,
                ),
                springy=True,
                resizable=True,
            ),
            show_labels=False,
            # NOTE: this id means the position of the sash will be saved
            id='viewer_split'
        ),
        resizable=True,
        toolbar=ToolBar(
            ActionGroup(
                Action(
                    name="Rotate Left",
                    tooltip="Rotate Left",
                    action='rotate_left',
                    image='rotate_left',
                ),
                Action(
                    name="Rotate Right",
                    tooltip="Rotate Right",
                    action='rotate_right',
                    image='rotate_right',
                ),
                Action(
                    name="Flip Horizontally",
                    tooltip="Flip Horizontally",
                    action='flip_horizontal',
                    image='flip_horizontal',
                ),
                Action(
                    name="Flip Vertically",
                    tooltip="Flip Vertically",
                    action='flip_vertical',
                    image='flip_vertical',
                ),
                name="Transpose Group",
                id="transpose_group",
            ),
            ActionGroup(
                Action(
                    name="Denoise",
                    tooltip="Denoise",
                    action='denoise',
                    image='denoise',
                ),
                name="Filter Group",
                id="filter_group",
            ),
            image_size=(24, 24),
            show_tool_names=False,
        ),
        menubar=MenuBar(
            Menu(
                Action(name="Revert Image", action="revert"),
                name="File",
                id="file_menu",
            ),
            Menu(
                ActionGroup(
                    Action(name="Rotate Left", action='rotate_left'),
                    Action(name="Rotate Right", action='rotate_right'),
                    Action(name="Flip Horizontally", action='flip_horizontal'),
                    Action(name="Flip Vertically", action='flip_vertical'),
                    name="Transpose Group",
                    id="transpose_group",
                ),
                ActionGroup(
                    Action(name="Denoise", action='denoise'),
                    name="Filter Group",
                    id="filter_group",
                ),
                name="Edit",
                id="edit_menu",
            ),
        ),
        # NOTE: this id means the size of the window will be saved
        id='image_preview',
    )
Exemplo n.º 6
0
class FormingTaskAnim3D(HasStrictTraits):
    '''Coordinate a camera and movement of visualization object along the timeline.
    '''

    ftv = Instance(FTV)
    '''Folding task view.
    '''
    init_cam_station = Instance(CamStation)

    anim_delay = Range(low=0.0, high=1.0, value=0.0,
                       label='Animation delay [s]',
                       auto_set=False, enter_set=True, input=True)

    def _init_cam_station_default(self):
        return CamStation()

    def init_view(self, a, e, d, f, r):
        self.init_cam_station.set(
            azimuth=a, elevation=e, distance=d, focal_point=f, roll=r)
        if self.ftv.scene.renderer:
            # encapsulate this in ftv
            self.ftv.mlab.view(a, e, d, f, figure=self.ftv.scene)
            self.ftv.mlab.roll(r, figure=self.ftv.scene)

    def plot(self):
        self.ftv.plot()

    cam_stations = List(Instance(CamStation))

    def _cam_stations_default(self):
        return [self.init_cam_station]

    cam_moves = List(Instance(CamMove))

    selected_cam_move = Instance(CamMove, None)

    def _selected_cam_move_changed(self):
        self.set_cam_pos()

    def add_cam_move(self, **kw):
        '''Add a new visualization object.'''
        prev_cam_station = self.cam_stations[-1]

        a = kw.pop('a', prev_cam_station.azimuth)
        e = kw.pop('e', prev_cam_station.elevation)
        d = kw.pop('d', prev_cam_station.distance)
        f = kw.pop('f', prev_cam_station.focal_point)
        r = kw.pop('r', prev_cam_station.roll)
        vot_start = kw.pop('vot_start', 0)
        vot_end = kw.pop('vot_end', 1)

        if prev_cam_station.prev_move:
            prev_move = prev_cam_station.prev_move
            n = kw.pop('n', prev_move.n_t)
        else:
            n = kw.pop('n', 20)
        next_cam_station = CamStation(azimuth=a, elevation=e, distance=d,
                                      focal_point=f, roll=r,
                                      )
        self.cam_stations.append(next_cam_station)
        cm = CamMove(fta=self, ftv=self.ftv,
                     from_station=prev_cam_station,
                     to_station=next_cam_station, n_t=n,
                     vot_start=vot_start, vot_end=vot_end, **kw)
        next_cam_station.prev_move = cm
        self.cam_moves.append(cm)
        self.selected_cam_move = cm

    def del_cam_move(self):
        '''Delete currently selected cam move.
        '''
        from_station = self.selected_cam_move.from_station
        to_station = self.selected_cam_move.to_station
        move_idx = self.cam_moves.index(self.selected_cam_move)
        stat_idx = self.cam_stations.index(to_station)
        del self.cam_stations[stat_idx]
        if move_idx < len(self.cam_moves) - 1:
            next_cam_move = self.cam_moves[move_idx + 1]
            next_cam_move.from_station = from_station
        del self.cam_moves[move_idx]
        if move_idx == len(self.cam_moves):
            move_idx -= 1

        self.selected_cam_move = self.cam_moves[move_idx]

    def capture_init_cam_pos(self):
        '''Get the current position from the ftv and set it to the target
        station of the cam move.
        '''
        a, e, d, f = self.ftv.mlab.view()
        r = self.ftv.mlab.roll()
        init_station = self.cam_moves[0].from_station
        init_station.set(azimuth=a, elevation=e, distance=d,
                         focal_point=tuple(f), roll=r)

    def capture_cam_pos(self):
        '''Get the current position from the ftv and set it to the target
        station of the cam move.
        '''
        a, e, d, f = self.ftv.mlab.view()
        r = self.ftv.mlab.roll()
        to_station = self.selected_cam_move.to_station
        to_station.set(azimuth=a, elevation=e, distance=d,
                       focal_point=tuple(f), roll=r)
        self.selected_cam_move.changed = True

    def set_cam_pos(self):
        '''Get the current position from the ftv and set it to the target
        station of the cam move.
        '''
        if (self.selected_cam_move == None or
                self.ftv.scene.renderer == None):
            return
        to_station = self.selected_cam_move.to_station
        self.ftv.mlab.view(azimuth=to_station.azimuth,
                           elevation=to_station.elevation,
                           distance=to_station.distance,
                           focalpoint=to_station.focal_point,
                           figure=self.ftv.mlab.figure)
        self.ftv.mlab.roll(to_station.roll,
                           figure=self.ftv.mlab.figure)

    def anim(self):
        for cam_move in self.cam_moves:
            cam_move.take(self.ftv)

    figsize_factor = Float(1.0)

    def render(self):
        self.ftv.mlab.options.offscreen = True
        self.ftv.mlab.clf()
        self.plot()

        im_files = []
        fname_base = 'anim'
        tdir = tempfile.mkdtemp()
        fname_path = os.path.join(tdir, fname_base)

        idx_offset = 0
        for cam_move in self.cam_moves:
            take_im_files = cam_move.render_take(
                self.ftv, fname_path, 'png', idx_offset, self.figsize_factor)
            idx_offset += len(take_im_files)
            im_files.append(take_im_files)

        self.ftv.mlab.options.offscreen = False

        return im_files

    def save_timeline(self):
        raise NotImplementedError

    def load_timeline(self):
        raise NotImplementedError

    trait_view = View(
        VSplit(
            UItem('ftv'),
            VGroup(
                HSplit(
                    VGroup(
                        Item('cam_moves',
                             style='custom', editor=cam_move_list_editor,
                             show_label=False, springy=True, width=150),
                        VGroup(
                            UItem('anim_delay'),
                            label='animation delay'
                        ),
                    ),
                    Item('selected_cam_move@', show_label=False,
                         springy=True,
                         width=800, height=200),
                    show_border=True,
                ),
                scrollable=True,
            ),
        ),
        toolbar=ToolBar(*actions),
        resizable=True,
        height=400,
        kind='subpanel',
        title='Timeline editor',
    )
Exemplo n.º 7
0
class BMCSWindow(BMCSStudy):

    selected_node = Instance(HasStrictTraits)

    def _selected_node_changed(self):
        self.selected_node.ui = self

    def get_vot_range(self):
        return self.viz_sheet.get_vot_range()

    vot = DelegatesTo('viz_sheet')

    data_changed = Event

    replot = Button

    def _replot_fired(self):
        self.figure.clear()
        self.selected_node.plot(self.figure)
        self.data_changed = True

    clear = Button()

    def _clear_fired(self):
        self.figure.clear()
        self.data_changed = True

    view = View(
        HSplit(
            VGroup(
                Item(
                    'model',
                    id='bmcs.hsplit.left.tree.id',
                    dock='tab',
                    editor=tree_editor,
                    resizable=True,
                    show_label=False,
                    width=300,
                    height=200,
                ),
                #                Item('selected_node@'),
                id='bmcs.hsplit.left.id',
                dock='tab',
            ),
            VGroup(
                Item(
                    'viz_sheet@',
                    show_label=False,
                    id='bmcs.hsplit.viz3d.notebook.id',
                    dock='tab',
                ),
                dock='tab',
                id='bmcs.hsplit.viz3d.id',
                label='viz sheet',
            ),
            dock='tab',
            id='bmcs.hsplit.id',
        ),
        #        dock='tab',
        id='bmcs.id',
        width=1.0,
        height=1.0,
        title='BMCS',
        resizable=True,
        handler=BMCSTreeViewHandler(),
        key_bindings=key_bindings,
        toolbar=ToolBar(*toolbar_actions,
                        image_size=(32, 32),
                        show_tool_names=False,
                        show_divider=True,
                        name='view_toolbar'),
        menubar=MenuBar(
            Menu(menu_exit, Separator(), menu_save, menu_open, name='File'),
            Menu(menu_tools_report_tex, menu_tools_report_pdf, name='Tools'),
        ))
Exemplo n.º 8
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"))