Пример #1
0
class StateDialogs(HasTraits):
    """Dialogs to show the process state."""

    successful = Str('The process was successful')

    cancel = Str('The process has been canceled')

    def open_successful(self):
        "Opens the dialog to show that the process was executed successfully."
        self.configure_traits(view='successful_view', kind='livemodal')

    def open_cancel(self):
        "Opens the dialog to show that the process wasn't executed successfully."
        self.configure_traits(view='cancel_view', kind='livemodal')

    successful_view = View(UItem('successful', style='readonly'),
                           buttons=['OK'],
                           resizable=True,
                           width=300,
                           height=75,
                           title='Process',
                           icon=ImageResource("../icons/smrc_icon.png"))

    cancel_view = View(UItem('cancel', style='readonly'),
                       buttons=['OK'],
                       resizable=True,
                       width=300,
                       height=75,
                       title='Process',
                       icon=ImageResource("../icons/smrc_icon.png"))
 def test_toolbar_changed(self):
     # test that toolbar gets changed as expected
     self.window.tool_bar_managers = [
         ToolBarManager(
             Action(name="New", image=ImageResource("core")),
             Action(name="Open", image=ImageResource("core")),
             Action(name="Save", image=ImageResource("core")),
             Action(name="Close", image=ImageResource("core")),
             Action(name="Quit", image=ImageResource("core")),
         )
     ]
     with self.event_loop():
         self.window._create()
     with self.event_loop():
         self.window.show(True)
     with self.event_loop():
         self.window.tool_bar_managers = [
             ToolBarManager(
                 Action(name="New", image=ImageResource("core")),
                 Action(name="Open", image=ImageResource("core")),
                 Action(name="Save", image=ImageResource("core")),
                 Action(name="Close", image=ImageResource("core")),
                 Action(name="Quit", image=ImageResource("core")),
             )
         ]
     with self.event_loop():
         self.window.show(False)
     with self.event_loop():
         self.window.close()
    def _get_big_image(self):
        size = self.item.size
        if size > 65536:
            return ImageResource('red_ball',
                      search_path=search_path)

        return (None, ImageResource('blue_ball',
               search_path=search_path))[size > 16384]
Пример #4
0
class WarningSystemDialogs(HasTraits):
    """Dialogs to warn the user that can lost some data by closing the app."""

    warning_icon = Image('../../icons/warning.png')

    exit_warning = Str("Do you want exit_view the program?")

    unsaved_warning = Str("The unsaved files will be permanently deleted")

    restart_warning = Str("Do you really want start a new experiment?")

    def open_restart(self):
        """
        Opens a dialog to inform the user that the process will delete data
        by starting a new experiment

        :returns: Returns True if the user press OK, False otherwise
        :rtype: Bool
        """
        return self.configure_traits(view='restart_view', kind='livemodal')

    def open_exit(self):
        """
        Opens a dialog to inform the user that the process will delete data
        by exit the application

        :returns: Returns True if the user press OK, False otherwise
        :rtype: Bool
        """
        return self.configure_traits(view='exit_view', kind='livemodal')

    exit_view = View(VGroup(HGroup(
        UItem('warning_icon'),
        spring,
    ), UItem('exit_warning', style='readonly'),
                            UItem('unsaved_warning', style='readonly')),
                     buttons=['OK', 'Cancel'],
                     resizable=True,
                     width=250,
                     title='Warning',
                     icon=ImageResource("../icons/smrc_icon.png"))

    restart_view = View(VGroup(
        HGroup(
            UItem('warning_icon'),
            spring,
        ),
        UItem('restart_warning', style='readonly'),
        UItem('unsaved_warning', style='readonly'),
    ),
                        buttons=['OK', 'Cancel'],
                        resizable=True,
                        width=300,
                        height=100,
                        title='Warning',
                        icon=ImageResource("../icons/smrc_icon.png"))
Пример #5
0
class StartDialog(HasTraits):
    """The StartDialog will show when initializing the application."""

    _close = Bool(False)

    startview = Image("../icons/startview.jpg")

    def __init__(self, parent):
        self.parent = parent
        self.application_window = None

    def initialize(self):
        """Performs the initializing of the application."""
        self.task()
        self.application_window = self.parent.window
        self._close = True

    def show(self, task):
        """
        Show the StartDialog and initialize the application in the background.

        :param task: Task 
        :type task: Built-in function
        """
        self.task = task
        RunThread(target=self.initialize)
        self.configure_traits()

    startdialog = View(UItem('startview'),
                       handler=StartDialogHandler(),
                       width=600,
                       height=300,
                       title="SmartRecord",
                       icon=ImageResource("../icons/smrc_icon.png"))
Пример #6
0
    def test_text_field_image(self):
        self._create_widget_control()
        image = ImageResource("question")

        # XXX can't validate icon values currently, so just a smoke test
        self.widget.image = image
        self.gui.process_events()
Пример #7
0
class ISplashScreen(IWindow):
    """ The interface for a splash screen. """

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

    #: The image to display on the splash screen.
    image = Instance(ImageResource, ImageResource("splash"))

    #: If log messages are to be displayed then this is the logging level. See
    #: the Python documentation for the 'logging' module for more details.
    log_level = Int(logging.DEBUG)

    #: Should the splash screen display log messages in the splash text?
    show_log_messages = Bool(True)

    #: Optional text to display on top of the splash image.
    text = Str()

    #: The text color.
    # FIXME v3: When TraitsUI supports PyQt then change this to 'Color',
    # (unless that needs the toolkit to be selected too soon, in which case it
    # may need to stay as Any - or Str?)
    # text_color = WxColor('black')
    text_color = Any()

    #: The text font.
    # FIXME v3: When TraitsUI supports PyQt then change this back to
    # 'Font(None)' with the actual default being toolkit specific.
    # text_font = Font(None)
    text_font = Any()

    #: The x, y location where the text will be drawn.
    # FIXME v3: Remove this.
    text_location = Tuple(5, 5)
Пример #8
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
     )
Пример #9
0
    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
Пример #10
0
def convert_image(value, level=3):
    """ Converts a specified value to an ImageResource if possible.
    """
    if not isinstance(value, str):
        return value

    key = value
    is_pyface_image = value.startswith("@")
    if not is_pyface_image:
        search_path = get_resource_path(level)
        key = "%s[%s]" % (value, search_path)

    result = image_resource_cache.get(key)
    if result is None:
        if is_pyface_image:
            try:
                from .image.image import ImageLibrary

                result = ImageLibrary.image_resource(value)
            except Exception as exc:
                logger.error("Can't load image resource '%s'." % value)
                logger.exception(exc)
                result = None
        else:
            from pyface.image_resource import ImageResource

            result = ImageResource(value, search_path=[search_path])

        image_resource_cache[key] = result

    return result
Пример #11
0
 def _get_icon(self):
     import matplotlib.pyplot as plt
     fig = plt.figure(figsize=(4, 4), facecolor='white')
     self.plot(fig)
     tf_handle, tf_name = tempfile.mkstemp('.png')
     fig.savefig(tf_name, dpi=35)
     return ImageResource(name=tf_name)
Пример #12
0
    def _about_dialog_default(self):
        about_dialog = myAboutDialog(image=ImageResource(
            name='about.png', search_path=paths.about_search_path))

        about_dialog.version_info = self.get_version_info()
        about_dialog.additions = self.about_additions
        return about_dialog
Пример #13
0
class SaveDialog(HasTraits):
    """Dialog to save files."""

    dir_name = Directory

    def open(self):
        """
        Opens a dialog to select to select the store-path

        :returns: The selected path
        :rtype: string
        """
        confirm = self.configure_traits(view='show_view', kind='livemodal')
        if confirm:
            return self.dir_name
        else:
            return None

    show_view = View(UItem('dir_name'),
                     title='Save',
                     buttons=['OK', 'Cancel'],
                     resizable=True,
                     width=300,
                     height=100,
                     icon=ImageResource("../icons/smrc_icon.png"))
Пример #14
0
 def update_images(self, sensors=None):
     try:
         if sensors != None:
             del self.sensors[:]
             for s in sensors:
                 self.sensors.append(s)
         udisplacements = get_all_files(displacement_u_dir)
         vdisplacements = get_all_files(displacement_v_dir)
         progress = ProcessDialog(max_n=self.max_image_number,
                                  title="Update")
         for i in range(self.max_image_number):
             img_name = self.images[i]
             progress.update(i, msg="Update image: {0}".format(img_name))
             udisp = loadtxt(join(displacement_u_dir, udisplacements[i]),
                             delimiter=',')
             vdisp = loadtxt(join(displacement_v_dir, vdisplacements[i]),
                             delimiter=',')
             img = imread(join(travel_sensor_images_dir, img_name))
             for t in self.sensors:
                 p1, p2 = t.points
                 x1, y1 = p1
                 x2, y2 = p2
                 u1, u2 = udisp[y1, x1], udisp[y2, x2]
                 v1, v2 = vdisp[y1, x1], vdisp[y2, x2]
                 img = self.sensor_draw.draw_travel_sensor(
                     img, t, u1, u2, v1, v2)
             imwrite(join(travel_sensor_draw_images_dir, img_name), img)
         self.ref_image = ImageResource(
             join(travel_sensor_draw_images_dir, self.fname))
     except Exception:
         dialog = ErrorDialogs()
         dialog.open_error("Some files are missing")
     progress.close()
def convert_image(value, level=3):
    """ Converts a specified value to an ImageResource if possible.
    """
    global image_resource_cache
    if not isinstance(value, str):
        return value

    key = value
    is_traits_image = (value[:1] == '@')
    if not is_traits_image:
        search_path = get_resource_path(level)
        key = '%s[%s]' % (value, search_path)
    result = image_resource_cache.get(key)

    if result is None:
        if is_traits_image:
            try:
                from .image.image import ImageLibrary
                result = ImageLibrary.image_resource(value)
            except:
                result = None
        else:
            from pyface.image_resource import ImageResource
            result = ImageResource(value, search_path=[search_path])

        image_resource_cache[key] = result

    return result
Пример #16
0
class WarningDialog(HasTraits):
    """Dialog to show warnings."""
    warning_icon = Image('../../icons/warning.png')

    msg = Str()

    def __init__(self, msg):
        self.msg = msg

    def open(self):
        """
        Opens a dialog to inform the user that the process will delete data
        by exit the application

        :returns: Returns True if the user press OK, False otherwise
        :rtype: Bool
        """
        return self.configure_traits(kind='livemodal')

    view = View(VGroup(
        HGroup(
            UItem('warning_icon'),
            spring,
        ),
        UItem('msg', style='readonly'),
    ),
                buttons=['OK', 'Cancel'],
                resizable=True,
                width=300,
                height=75,
                title='Warning',
                icon=ImageResource("../icons/smrc_icon.png"))
Пример #17
0
 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())
Пример #18
0
class Employee(HasTraits):

    # Define the traits:
    name = Str
    dept = Str
    email = Str

    # 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)
Пример #19
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())
Пример #20
0
 def _cur_image_number_changed(self):
     if self.cur_image_number >= self.max_image_number:
         self.cur_image_number = self.max_image_number - 1
     elif self.cur_image_number < 0:
         self.cur_image_number = 0
     self.fname = self.images[self.cur_image_number]
     self.ref_image = ImageResource(
         join(travel_sensor_draw_images_dir, self.fname))
Пример #21
0
def Tool(prefix='feature',
         image=ImageResource('tool_feature'),
         tooltip='Drag and drop this tool on a view',
         **metadata):
    return Str(tool=ToolDescription(prefix=prefix,
                                    image=image,
                                    tooltip=tooltip),
               **metadata)
Пример #22
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):
        label = QtGui.QLabel()

        if parent.parent() is not None:
            title = parent.parent().windowTitle()
        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)

        # Get the version numbers.
        py_version = sys.version[0:sys.version.find("(")]
        qt_version = QtCore.__version__

        # Set the page contents.
        label.setText(_DIALOG_TEXT % (path, additions, py_version, qt_version))

        # Create the button.
        buttons = QtGui.QDialogButtonBox()

        if self.ok_label:
            buttons.addButton(self.ok_label, QtGui.QDialogButtonBox.AcceptRole)
        else:
            buttons.addButton(QtGui.QDialogButtonBox.Ok)

        buttons.connect(buttons, QtCore.SIGNAL('accepted()'), parent,
                        QtCore.SLOT('accept()'))

        lay = QtGui.QVBoxLayout()
        lay.addWidget(label)
        lay.addWidget(buttons)

        parent.setLayout(lay)
Пример #23
0
    def traits_view(self):
        #         editor = ListEditor(mutable=False,
        #                           style='custom',
        #                           editor=InstanceEditor())
        #
        grp = HGroup(
            UItem('kind'),
            UItem('open_button', visible_when='kind=="File"'),
            UItem(
                selector_name('add_query_button'),
                style='custom',
                editor=ButtonEditor(
                    label='',
                    image=ImageResource(name='add.png',
                                        search_path=paths.icon_search_path),
                ),
                visible_when='kind=="Database"',
            ),
            UItem(
                selector_name('delete_query_button'),
                style='custom',
                editor=ButtonEditor(image=ImageResource(
                    name='delete.png', search_path=paths.icon_search_path)),
                visible_when='kind=="Database"',
            ),
        )
        filter_grp = HGroup(
            UItem(
                selector_name('search'),
                visible_when='kind=="Database"',
            ),
            UItem(
                selector_name('mass_spectrometer'),
                label='Spec.',
                editor=EnumEditor(name=selector_name('mass_spectrometers')),
            ),
            UItem(selector_name('analysis_type'),
                  editor=EnumEditor(name=selector_name('analysis_types'))),
            visible_when='kind=="Database"',
        )

        v = View(
            VSplit(self._results_group(),
                   VGroup(grp, filter_grp, self._query_group())))
        return v
Пример #24
0
 def dialog_view(self):
     """ Returns a view with an icon and a title.
     """
     view = self.trait_view()
     icon = self._icon_path + os.sep + 'images' + os.sep + self.icon
     view.icon = ImageResource(icon)
     view.title = "Edit%s: %s" % (self.type, self.name)
     view.buttons = ['OK', 'Cancel']
     return view
Пример #25
0
    def test_init_local_image(self):
        from pyface.image_resource import ImageResource

        image_class = ImageClass(image=ImageResource('core.png'))

        self.assertIsInstance(image_class.image, ImageResource)
        self.assertEqual(image_class.image.name, 'core.png')
        self.assertEqual(image_class.image.absolute_path,
                         os.path.abspath(IMAGE_PATH))
Пример #26
0
def image(name):
    name = add_extension(name, '.png')
    for si in paths.image_search_path:
        if si and os.path.isfile(os.path.join(si, name)):
            break
    else:
        print('no image for "{}"'.format(name))

    return ImageResource(name=name, search_path=paths.image_search_path)
Пример #27
0
class SplashScreen(MSplashScreen, Window):
    """ The toolkit specific implementation of a SplashScreen.  See the
    ISplashScreen interface for the API documentation.
    """

    implements(ISplashScreen)

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

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

    log_level = Int(DEBUG)

    show_log_messages = Bool(True)

    text = Unicode

    text_color = Any

    text_font = Any

    text_location = Tuple(5, 5)

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

    def _create_control(self, parent):
        splash_screen = QtGui.QSplashScreen(self.image.create_image())
        self._qt4_show_message(splash_screen)

        return splash_screen

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

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

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

    def _qt4_show_message(self, control):
        """ Set the message text for a splash screen control. """

        if self.text_font is not None:
            control.setFont(self.text_font)

        if self.text_color is None:
            text_color = QtCore.Qt.black
        else:
            # Until we get the type of this trait finalised (ie. when TraitsUI
            # supports PyQt) convert it explcitly to a colour.
            text_color = QtGui.QColor(self.text_color)

        control.showMessage(self.text, QtCore.Qt.AlignLeft, text_color)
Пример #28
0
class IAboutDialog(IDialog):
    """ The interface for a simple 'About' dialog. """

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

    #: Additional strings to be added to the dialog.
    additions = List(Unicode)

    #: The image displayed in the dialog.
    image = Instance(ImageResource, ImageResource('about'))
    def _set_window_icon(self):
        if self.icon is None:
            icon = ImageResource('application.ico')
        else:
            icon = self.icon

        if self.control is not None:
            self.control.SetIcon(icon.create_icon())

        return
Пример #30
0
class PopupMenuFeature(DockWindowFeature):

    #---------------------------------------------------------------------------
    #  Class variables:
    #---------------------------------------------------------------------------

    # The user interface name of the feature:
    feature_name = 'Popup Menu'

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

    # The current image to display on the feature bar:
    image = ImageResource('popup_menu_feature')

    # The tooltip to display when the mouse is hovering over the image:
    tooltip = 'Click to display the menu.'

    #---------------------------------------------------------------------------
    #  Handles the user left clicking on the feature image:
    #---------------------------------------------------------------------------

    def click(self):
        """ Handles the user left clicking on the feature image.
        """
        object = self.dock_control.object
        menu = object.popup_menu
        if not isinstance(menu, Menu):
            try:
                # It might be a method which returns a menu:
                menu = menu()
            except:
                pass

        if not isinstance(menu, Menu):
            menu = no_menu

        self.popup_menu(menu)

#-- Overidable Class Methods ---------------------------------------------------

#---------------------------------------------------------------------------
#  Returns whether or not the DockWindowFeature is a valid feature for a
#  specified DockControl:
#---------------------------------------------------------------------------

    def is_feature_for(self, dock_control):
        """ Returns whether or not the DockWindowFeature is a valid feature for
            a specified DockControl.
        """
        object = dock_control.object
        return ((object is not None) and hasattr(object, 'popup_menu'))

    is_feature_for = classmethod(is_feature_for)