def __init__(self):
        super(PopupViewContentsExample, self).__init__()

        self.setSpacing(True)

        # ------
        # Static content for the minimized view
        # ------

        # Create the content for the popup
        content = Label('This is a simple Label component inside the popup. '
                        'You can place any Muntjac components here.')

        # The PopupView popup will be as large as needed by the content
        content.setWidth('300px')

        # Construct the PopupView with simple HTML text representing the
        # minimized view
        popup = PopupView('Static HTML content', content)
        self.addComponent(popup)

        # ------
        # Dynamic content for the minimized view
        # ------

        # In this sample we update the minimized view value with the content of
        # the TextField inside the popup.
        popup = PopupView(PopupTextField())
        popup.setDescription('Click to edit')
        popup.setHideOnMouseOut(False)
        self.addComponent(popup)
Exemplo n.º 2
0
    def __init__(self):
        super(PopupViewClosingExample, self).__init__()

        self.setSpacing(True)

        # Create the content for the popup
        content = Label('This popup will close as soon as you move the '
                'mouse cursor outside of the popup area.')
        # The PopupView popup will be as large as needed by the content
        content.setWidth('300px')
        # Construct the PopupView with simple HTML text representing the
        # minimized view
        popup = PopupView('Default popup', content)
        popup.setHideOnMouseOut(True)
        popup.addListener(self, IPopupVisibilityListener)
        self.addComponent(popup)

        content = Label('This popup will only close if you click '
                'the mouse outside the popup area.')
        # The PopupView popup will be as large as needed by the content
        content.setWidth('300px')
        popup = PopupView('Popup that won\'t auto-close', content)
        popup.setHideOnMouseOut(False)
        popup.addListener(self, IPopupVisibilityListener)
        self.addComponent(popup)
Exemplo n.º 3
0
    def __init__(self):
        super(WebLayoutWindow, self).__init__()

        # Our main layout is a horizontal layout
        main = HorizontalLayout()
        main.setMargin(True)
        main.setSpacing(True)
        self.setContent(main)

        # Tree to the left
        tree = Tree()
        tree.setContainerDataSource(ExampleUtil.getHardwareContainer())
        tree.setItemCaptionPropertyId(ExampleUtil.hw_PROPERTY_NAME)
        for idd in tree.rootItemIds():
            tree.expandItemsRecursively(idd)
        self.addComponent(tree)

        # vertically divide the right area
        left = VerticalLayout()
        left.setSpacing(True)
        self.addComponent(left)

        # table on top
        tbl = Table()
        tbl.setWidth('500px')
        tbl.setContainerDataSource(ExampleUtil.getISO3166Container())
        tbl.setSortDisabled(True)
        tbl.setPageLength(7)
        left.addComponent(tbl)

        # Label on bottom
        text = Label(ExampleUtil.lorem, Label.CONTENT_XHTML)
        text.setWidth('500px')  # some limit is good for text
        left.addComponent(text)
Exemplo n.º 4
0
    def __init__(self):
        super(WebLayoutWindow, self).__init__()

        # Our main layout is a horizontal layout
        main = HorizontalLayout()
        main.setMargin(True)
        main.setSpacing(True)
        self.setContent(main)

        # Tree to the left
        tree = Tree()
        tree.setContainerDataSource( ExampleUtil.getHardwareContainer() )
        tree.setItemCaptionPropertyId( ExampleUtil.hw_PROPERTY_NAME )
        for idd in tree.rootItemIds():
            tree.expandItemsRecursively(idd)
        self.addComponent(tree)

        # vertically divide the right area
        left = VerticalLayout()
        left.setSpacing(True)
        self.addComponent(left)

        # table on top
        tbl = Table()
        tbl.setWidth('500px')
        tbl.setContainerDataSource( ExampleUtil.getISO3166Container() )
        tbl.setSortDisabled(True)
        tbl.setPageLength(7)
        left.addComponent(tbl)

        # Label on bottom
        text = Label(ExampleUtil.lorem, Label.CONTENT_XHTML)
        text.setWidth('500px')  # some limit is good for text
        left.addComponent(text)
Exemplo n.º 5
0
    def _add_statusbar ( self ):
        """ Adds a statusbar to the dialog.
        """
        if self.ui.view.statusbar is not None:
            control = HorizontalLayout()
            control.setSizeGripEnabled(self.ui.view.resizable)
            listeners = []
            for item in self.ui.view.statusbar:
                # Create the status widget with initial text
                name = item.name
                item_control = Label()
                item_control.setValue(self.ui.get_extended_value(name))

                # Add the widget to the control with correct size
                width = abs(item.width)
                stretch = 0
                if width <= 1.0:
                    stretch = int(100 * width)
                else:
                    item_control.setWidth('%dpx' % width)
                control.addComponent(item_control)

                # Set up event listener for updating the status text
                col = name.find('.')
                obj = 'object'
                if col >= 0:
                    obj = name[:col]
                    name = name[col+1:]
                obj = self.ui.context[obj]
                set_text = self._set_status_text(item_control)
                obj.on_trait_change(set_text, name, dispatch='ui')
                listeners.append((obj, set_text, name))

            self.control.addComponent(control)
            self.ui._statusbar = listeners
Exemplo n.º 6
0
    def __init__(self):
        super(PopupViewContentsExample, self).__init__()

        self.setSpacing(True)

        # ------
        # Static content for the minimized view
        # ------

        # Create the content for the popup
        content = Label('This is a simple Label component inside the popup. '
                'You can place any Muntjac components here.')

        # The PopupView popup will be as large as needed by the content
        content.setWidth('300px')

        # Construct the PopupView with simple HTML text representing the
        # minimized view
        popup = PopupView('Static HTML content', content)
        self.addComponent(popup)

        # ------
        # Dynamic content for the minimized view
        # ------

        # In this sample we update the minimized view value with the content of
        # the TextField inside the popup.
        popup = PopupView( PopupTextField() )
        popup.setDescription('Click to edit')
        popup.setHideOnMouseOut(False)
        self.addComponent(popup)
    def createComponents(self):
        components = list()

        label = Label('This is a long text block that will wrap.')
        label.setWidth('120px')
        components.append(label)

        image = Embedded('', ThemeResource('../runo/icons/64/document.png'))
        components.append(image)

        documentLayout = CssLayout()
        documentLayout.setWidth('19px')
        for _ in range(5):
            e = Embedded(None, ThemeResource('../runo/icons/16/document.png'))
            e.setHeight('16px')
            e.setWidth('16px')
            documentLayout.addComponent(e)
        components.append(documentLayout)

        buttonLayout = VerticalLayout()
        button = Button('Button')

        button.addListener(ButtonClickListener(self), IClickListener)
        buttonLayout.addComponent(button)
        buttonLayout.setComponentAlignment(button, Alignment.MIDDLE_CENTER)
        components.append(buttonLayout)

        return components
Exemplo n.º 8
0
    def init(self):
        #        super(GoogleMapWidgetApp, self).__init__()

        self.setMainWindow(Window('Google Map add-on demo'))

        # Create a new map instance centered on the IT Mill offices
        self._googleMap = GoogleMap(self, (22.3, 60.4522), 8)

        self._googleMap.setWidth('640px')
        self._googleMap.setHeight('480px')

        # Create a marker at the IT Mill offices
        self._mark1 = BasicMarker(1L, (22.3, 60.4522), 'Test marker 1')
        self._mark2 = BasicMarker(2L, (22.4, 60.4522), 'Test marker 2')
        self._mark3 = BasicMarker(4L, (22.6, 60.4522), 'Test marker 3')
        self._mark4 = BasicMarker(5L, (22.7, 60.4522), 'Test marker 4')

        l = MarkerClickListener(self)
        self._googleMap.addListener(l, IMarkerClickListener)

        # Marker with information window pupup
        self._mark5 = BasicMarker(6L, (22.8, 60.4522), 'Marker 5')
        self._mark5.setInfoWindowContent(self._googleMap,
                                         Label('Hello Marker 5!'))

        content = Label('Hello Marker 2!')
        content.setWidth('60px')
        self._mark2.setInfoWindowContent(self._googleMap, content)

        self._googleMap.addMarker(self._mark1)
        self._googleMap.addMarker(self._mark2)
        self._googleMap.addMarker(self._mark3)
        self._googleMap.addMarker(self._mark4)
        self._googleMap.addMarker(self._mark5)
        self.getMainWindow().getContent().addComponent(self._googleMap)

        # Add a Marker click listener to catch marker click events.
        # Note, works only if marker has information window content
        l = MarkerClickListener2(self)
        self._googleMap.addListener(l, IMarkerClickListener)

        # Add a MarkerMovedListener to catch events when a marker is dragged to
        # a new location
        l = MarkerMovedListener(self)
        self._googleMap.addListener(l, IMarkerMovedListener)

        l = MapMoveListener(self)
        self._googleMap.addListener(l, IMapMoveListener)

        self._googleMap.addControl(MapControl.MapTypeControl)

        self.addTestButtons()  # Add buttons that trigger tests map features
Exemplo n.º 9
0
    def init(self):
#        super(GoogleMapWidgetApp, self).__init__()

        self.setMainWindow(Window('Google Map add-on demo'))

        # Create a new map instance centered on the IT Mill offices
        self._googleMap = GoogleMap(self, (22.3, 60.4522), 8)

        self._googleMap.setWidth('640px')
        self._googleMap.setHeight('480px')

        # Create a marker at the IT Mill offices
        self._mark1 = BasicMarker(1L, (22.3, 60.4522), 'Test marker 1')
        self._mark2 = BasicMarker(2L, (22.4, 60.4522), 'Test marker 2')
        self._mark3 = BasicMarker(4L, (22.6, 60.4522), 'Test marker 3')
        self._mark4 = BasicMarker(5L, (22.7, 60.4522), 'Test marker 4')

        l = MarkerClickListener(self)
        self._googleMap.addListener(l, IMarkerClickListener)

        # Marker with information window pupup
        self._mark5 = BasicMarker(6L, (22.8, 60.4522), 'Marker 5')
        self._mark5.setInfoWindowContent(self._googleMap,
                Label('Hello Marker 5!'))

        content = Label('Hello Marker 2!')
        content.setWidth('60px')
        self._mark2.setInfoWindowContent(self._googleMap, content)

        self._googleMap.addMarker(self._mark1)
        self._googleMap.addMarker(self._mark2)
        self._googleMap.addMarker(self._mark3)
        self._googleMap.addMarker(self._mark4)
        self._googleMap.addMarker(self._mark5)
        self.getMainWindow().getContent().addComponent(self._googleMap)

        # Add a Marker click listener to catch marker click events.
        # Note, works only if marker has information window content
        l = MarkerClickListener2(self)
        self._googleMap.addListener(l, IMarkerClickListener)

        # Add a MarkerMovedListener to catch events when a marker is dragged to
        # a new location
        l = MarkerMovedListener(self)
        self._googleMap.addListener(l, IMarkerMovedListener)

        l = MapMoveListener(self)
        self._googleMap.addListener(l, IMapMoveListener)

        self._googleMap.addControl(MapControl.MapTypeControl)

        self.addTestButtons()  # Add buttons that trigger tests map features
Exemplo n.º 10
0
    def __init__(self):
        super(PackageIconsExample, self).__init__()

        self._icons = ['arrow-down.png', 'arrow-left.png', 'arrow-right.png',
            'arrow-up.png', 'attention.png', 'calendar.png', 'cancel.png',
            'document.png', 'document-add.png', 'document-delete.png',
            'document-doc.png', 'document-image.png', 'document-pdf.png',
            'document-ppt.png', 'document-txt.png', 'document-web.png',
            'document-xsl.png', 'email.png', 'email-reply.png',
            'email-send.png', 'folder.png', 'folder-add.png',
            'folder-delete.png', 'globe.png', 'help.png', 'lock.png',
            'note.png', 'ok.png', 'reload.png', 'settings.png', 'trash.png',
            'trash-full.png', 'user.png', 'users.png']

        self._sizes = ['16', '32', '64']

        self.setSpacing(True)

        tabSheet = TabSheet()
        tabSheet.setStyleName(Reindeer.TABSHEET_MINIMAL)

        for size in self._sizes:
            iconsSideBySide = 2 if size == '64' else 3
            grid = GridLayout(iconsSideBySide * 2, 1)
            grid.setSpacing(True)
            grid.setMargin(True)
            tabSheet.addTab(grid, size + 'x' + size, None)

            tabSheet.addComponent(grid)
            for icon in self._icons:
                res = ThemeResource('../runo/icons/' + size + '/' + icon)

                e = Embedded(None, res)

                # Set size to avoid flickering when loading
                e.setWidth(size + 'px')
                e.setHeight(size + 'px')

                name = Label(icon)
                if size == '64':
                    name.setWidth('185px')
                else:
                    name.setWidth('150px')

                grid.addComponent(e)
                grid.addComponent(name)

                grid.setComponentAlignment(name, Alignment.MIDDLE_LEFT)

        self.addComponent(tabSheet)
Exemplo n.º 11
0
    def __init__(self):
        super(ApplicationLayoutWindow, self).__init__()

        # Our main layout is a horizontal layout
        main = HorizontalLayout()
        main.setSizeFull()
        self.setContent(main)

        # Tree to the left
        treePanel = Panel()  # for scrollbars
        treePanel.setStyleName(Reindeer.PANEL_LIGHT)
        treePanel.setHeight('100%')
        treePanel.setWidth(None)
        treePanel.getContent().setSizeUndefined()
        self.addComponent(treePanel)

        tree = Tree()
        tree.setContainerDataSource(ExampleUtil.getHardwareContainer())
        tree.setItemCaptionPropertyId(ExampleUtil.hw_PROPERTY_NAME)
        for idd in tree.rootItemIds():
            tree.expandItemsRecursively(idd)
        treePanel.addComponent(tree)

        # vertically divide the right area
        left = VerticalLayout()
        left.setSizeFull()
        self.addComponent(left)
        main.setExpandRatio(left, 1.0)  # use all available space

        # table on top
        tbl = Table()
        tbl.setWidth('100%')
        tbl.setContainerDataSource(ExampleUtil.getISO3166Container())
        tbl.setSortDisabled(True)
        tbl.setPageLength(7)
        left.addComponent(tbl)

        # Label on bottom
        textPanel = Panel()  # for scrollbars
        textPanel.setStyleName(Reindeer.PANEL_LIGHT)
        textPanel.setSizeFull()
        left.addComponent(textPanel)
        left.setExpandRatio(textPanel, 1.0)  # use all available space

        text = Label(ExampleUtil.lorem, Label.CONTENT_XHTML)
        text.setWidth('500px')  # some limit is good for text
        textPanel.addComponent(text)
Exemplo n.º 12
0
    def __init__(self):
        super(ApplicationLayoutWindow, self).__init__()

        # Our main layout is a horizontal layout
        main = HorizontalLayout()
        main.setSizeFull()
        self.setContent(main)

        # Tree to the left
        treePanel = Panel()  # for scrollbars
        treePanel.setStyleName(Reindeer.PANEL_LIGHT)
        treePanel.setHeight('100%')
        treePanel.setWidth(None)
        treePanel.getContent().setSizeUndefined()
        self.addComponent(treePanel)

        tree = Tree()
        tree.setContainerDataSource(ExampleUtil.getHardwareContainer())
        tree.setItemCaptionPropertyId(ExampleUtil.hw_PROPERTY_NAME)
        for idd in tree.rootItemIds():
            tree.expandItemsRecursively(idd)
        treePanel.addComponent(tree)

        # vertically divide the right area
        left = VerticalLayout()
        left.setSizeFull()
        self.addComponent(left)
        main.setExpandRatio(left, 1.0)  # use all available space

        # table on top
        tbl = Table()
        tbl.setWidth('100%')
        tbl.setContainerDataSource(ExampleUtil.getISO3166Container())
        tbl.setSortDisabled(True)
        tbl.setPageLength(7)
        left.addComponent(tbl)

        # Label on bottom
        textPanel = Panel()  # for scrollbars
        textPanel.setStyleName(Reindeer.PANEL_LIGHT)
        textPanel.setSizeFull()
        left.addComponent(textPanel)
        left.setExpandRatio(textPanel, 1.0)  # use all available space

        text = Label(ExampleUtil.lorem, Label.CONTENT_XHTML)
        text.setWidth('500px')  # some limit is good for text
        textPanel.addComponent(text)
Exemplo n.º 13
0
    def __init__(self):
        super(SliderHorizontalExample, self).__init__()

        self.setSpacing(True)

        self.setWidth('100%')

        value = Label('0')
        value.setWidth('3em')

        slider = Slider('Select a value between 0 and 100')
        slider.setWidth('100%')
        slider.setMin(0)
        slider.setMax(100)
        slider.setImmediate(True)

        slider.addListener(SliderListener(value), IValueChangeListener)

        self.addComponent(slider)
        self.setExpandRatio(slider, 1)
        self.addComponent(value)

        self.setComponentAlignment(value, Alignment.BOTTOM_LEFT)
Exemplo n.º 14
0
    def __init__(self):
        super(SliderHorizontalExample, self).__init__()

        self.setSpacing(True)

        self.setWidth('100%')

        value = Label('0')
        value.setWidth('3em')

        slider = Slider('Select a value between 0 and 100')
        slider.setWidth('100%')
        slider.setMin(0)
        slider.setMax(100)
        slider.setImmediate(True)

        slider.addListener(SliderListener(value), IValueChangeListener)

        self.addComponent(slider)
        self.setExpandRatio(slider, 1)
        self.addComponent(value)

        self.setComponentAlignment(value, Alignment.BOTTOM_LEFT)
Exemplo n.º 15
0
    def _add_items(self, content, outer=None):
        """Adds a list of Item objects, creating a layout if needed.  Return
           the outermost layout.
        """
        # Get local references to various objects we need:
        ui = self.ui
        info = ui.info
        handler = ui.handler

        group = self.group
        show_left = group.show_left
        padding = group.padding
        columns = group.columns

        # See if a label is needed.
        show_labels = False
        for item in content:
            show_labels |= item.show_label

        # See if a grid layout is needed.
        if show_labels or columns > 1:
            inner = GridLayout(columns * 2, len(content))
            inner.setSpacing(True)
            inner.setSizeUndefined()

            if outer is None:
                outer = inner
            else:
                outer.addComponent(inner)

            row = 0
            if show_left:
                label_alignment = Alignment.MIDDLE_RIGHT
            else:
                label_alignment = Alignment.MIDDLE_LEFT

        else:
            # Use the existing layout if there is one.
            if outer is None:
                if self.horizontal:
                    outer = HorizontalLayout()
                else:
                    outer = VerticalLayout()
                outer.setSizeUndefined()

            inner = outer

            row = -1
            label_alignment = 0

        # Process each Item in the list:
        col = -1
        for item in content:

            # Keep a track of the current logical row and column unless the
            # layout is not a grid.
            col += 1
            if row >= 0 and col >= columns:
                col = 0
                row += 1

            # Get the name in order to determine its type:
            name = item.name

            # Check if is a label:
            if name == '':
                label = item.label
                if label != "":

                    # Create the label widget.
                    if item.style == 'simple':
                        label = Label(label)
                    else:
                        label = heading_text(None, text=label).control

                    self._add_widget(inner, label, row, col, show_labels)

                    if item.emphasized:
                        self._add_emphasis(label)

                # Continue on to the next Item in the list:
                continue

            # Check if it is a separator:
            if name == '_':
                cols = columns

                # See if the layout is a grid.
                if row >= 0:
                    # Move to the start of the next row if necessary.
                    if col > 0:
                        col = 0
                        row += 1

#                    # Skip the row we are about to do.
#                    row += 1

                    # Allow for the columns.
                    if show_labels:
                        cols *= 2

                for i in range(cols):
                    if self.horizontal:
                        # Add a vertical separator:
                        line = Panel()
                        line.setWidth('2px')
                        line.setHeight('-1px')
                        if row < 0:
                            inner.addComponent(line)
                        else:
                            inner.addComponent(line, row, i)
                    else:
                        # Add a horizontal separator:
                        line = Label('<hr />', Label.CONTENT_XHTML)
                        line.setWidth('100%')  # FIXME: explicit container size
                        if row < 0:
                            inner.addComponent(line)
                        else:
                            inner.addComponent(line, i, row)

                # Continue on to the next Item in the list:
                continue

            # Convert a blank to a 5 pixel spacer:
            if name == ' ':
                name = '5'

            # Check if it is a spacer:
            if all_digits.match( name ):

                # If so, add the appropriate amount of space to the layout:
                spacer = Label('')
                if self.horizontal:
                    # Add a horizontal spacer:
                    spacer.setWidth(name + 'px')
                else:
                    # Add a vertical spacer:
                    spacer.setHeight(name + 'px')

                self._add_widget(inner, spacer, row, col, show_labels)

                # Continue on to the next Item in the list:
                continue

            # Otherwise, it must be a trait Item:
            object      = eval( item.object_, globals(), ui.context )
            trait       = object.base_trait( name )
            desc        = trait.desc or ''
            fixed_width = False

            # Handle any label.
            if item.show_label:
                label = self._create_label(item, ui, desc)
                self._add_widget(inner, label, row, col, show_labels,
                                 label_alignment)
            else:
                label = None

            # Get the editor factory associated with the Item:
            editor_factory = item.editor
            if editor_factory is None:
                editor_factory = trait.get_editor()

                # If still no editor factory found, use a default text editor:
                if editor_factory is None:
                    from text_editor import ToolkitEditorFactory
                    editor_factory = ToolkitEditorFactory()

                # If the item has formatting traits set them in the editor
                # factory:
                if item.format_func is not None:
                    editor_factory.format_func = item.format_func

                if item.format_str != '':
                    editor_factory.format_str = item.format_str

                # If the item has an invalid state extended trait name, set it
                # in the editor factory:
                if item.invalid != '':
                    editor_factory.invalid = item.invalid

            # Create the requested type of editor from the editor factory:
            factory_method = getattr( editor_factory, item.style + '_editor' )
            editor         = factory_method( ui, object, name, item.tooltip,
                                        None).set(
                                 item        = item,
                                 object_name = item.object )

            # Tell the editor to actually build the editing widget.  Note that
            # "inner" is a layout.  This shouldn't matter as individual editors
            # shouldn't be using it as a parent anyway.  The important thing is
            # that it is not None (otherwise the main TraitsUI code can change
            # the "kind" of the created UI object).
            editor.prepare(inner)
            control = editor.control

            # Set the initial 'enabled' state of the editor from the factory:
            editor.enabled = editor_factory.enabled

            # Add emphasis to the editor control if requested:
            if item.emphasized:
                self._add_emphasis(control)

            # Give the editor focus if it requested it:
            if item.has_focus:
                control.focus()

            # Set the correct size on the control, as specified by the user:
            stretch = 0
            scrollable = editor.scrollable
            item_width = item.width
            item_height = item.height
            if (item_width != -1) or (item_height != -1):
                is_horizontal = self.horizontal

                min_size = control.minimumSizeHint()
                width = min_size.width()
                height = min_size.height()

                if (0.0 < item_width <= 1.0) and is_horizontal:
                    stretch = int(100 * item_width)

                item_width = int(item_width)
                if item_width < -1:
                    item_width  = -item_width
                else:
                    item_width = max(item_width, width)

                if (0.0 < item_height <= 1.0) and (not is_horizontal):
                    stretch = int(100 * item_height)

                item_height = int(item_height)
                if item_height < -1:
                    item_height = -item_height
                else:
                    item_height = max(item_height, height)

                control.setWidth(max(item_width, 0))
                control.setHeight(max(item_height, 0))

            # Bind the editor into the UIInfo object name space so it can be
            # referred to by a Handler while the user interface is active:
            Id = item.id or name
            info.bind( Id, editor, item.id )

            # Also, add the editors to the list of editors used to construct
            # the user interface:
            ui._editors.append( editor )

            # If the handler wants to be notified when the editor is created,
            # add it to the list of methods to be called when the UI is
            # complete:
            defined = getattr( handler, Id + '_defined', None )
            if defined is not None:
                ui.add_defined( defined )

            # If the editor is conditionally visible, add the visibility
            # 'expression' and the editor to the UI object's list of monitored
            # objects:
            if item.visible_when != '':
                ui.add_visible( item.visible_when, editor )

            # If the editor is conditionally enabled, add the enabling
            # 'expression' and the editor to the UI object's list of monitored
            # objects:
            if item.enabled_when != '':
                ui.add_enabled( item.enabled_when, editor )

            # Add the created editor control to the layout with the appropriate
            # size and stretch policies:
            ui._scrollable |= scrollable
#            item_resizable  = ((item.resizable is True) or
#                               ((item.resizable is Undefined) and scrollable))
#            if item_resizable:
#                stretch = stretch or 50
#                self.resizable = True
#            elif item.springy:
#                stretch = stretch or 50
#            policy = control.sizePolicy()
#            if self.horizontal:
#                policy.setHorizontalStretch(stretch)
#                if item_resizable or item.springy:
#                    policy.setHorizontalPolicy(QtGui.QSizePolicy.Expanding)
#            else:
#                policy.setVerticalStretch(stretch)
#                if item_resizable or item.springy:
#                    policy.setVerticalPolicy(QtGui.QSizePolicy.Expanding)
#            control.setSizePolicy(policy)

            # FIXME: Need to decide what to do about border_size and padding
            self._add_widget(inner, control, row, col, show_labels)

            # Save the reference to the label control (if any) in the editor:
            editor.label_control = label

        return outer
Exemplo n.º 16
0
class FeatureView(HorizontalLayout):

    _MSG_SHOW_SRC = 'View Source'

    def __init__(self):
        super(FeatureView, self).__init__()

        self._right = None
        self._left = None
        self._controls = None
        self._title = Label("", Label.CONTENT_XHTML)
        self._showSrc = None
        self._exampleCache = dict()
        self._currentFeature = None
        self._srcWindow = None

        self.setWidth('100%')
        self.setMargin(True)
        self.setSpacing(True)
        self.setStyleName('sample-view')

        self._left = VerticalLayout()
        self._left.setWidth('100%')
        self._left.setSpacing(True)
        self._left.setMargin(False)
        self.addComponent(self._left)
        self.setExpandRatio(self._left, 1)

        rightLayout = VerticalLayout()
        self._right = Panel(rightLayout)
        rightLayout.setMargin(True, False, False, False)
        self._right.setStyleName(Reindeer.PANEL_LIGHT)
        self._right.addStyleName('feature-info')
        self._right.setWidth('319px')
        self.addComponent(self._right)

        self._controls = HorizontalLayout()
        self._controls.setWidth('100%')
        self._controls.setStyleName('feature-controls')

        self._title.setStyleName('title')
        self._controls.addComponent(self._title)
        self._controls.setExpandRatio(self._title, 1)

        resetExample = NativeButton('Reset', ResetListener(self))
        resetExample.setStyleName(BaseTheme.BUTTON_LINK)
        resetExample.addStyleName('reset')
        resetExample.setDescription('Reset Sample')
        self._controls.addComponent(resetExample)
        self._showSrc = ActiveLink()
        self._showSrc.setDescription(
            'Right / middle / ctrl / shift -click for browser window/tab')

        self._showSrc.addListener(ShowSrcListener(self),
                                  ILinkActivatedListener)
        self._showSrc.setCaption(self._MSG_SHOW_SRC)
        self._showSrc.addStyleName('showcode')
        self._showSrc.setTargetBorder(Link.TARGET_BORDER_NONE)
        self._controls.addComponent(self._showSrc)

    def showSource(self, source):
        if self._srcWindow is None:
            self._srcWindow = Window('Python source')
            self._srcWindow.getContent().setSizeUndefined()
            self._srcWindow.setWidth('70%')
            self._srcWindow.setHeight('60%')
            self._srcWindow.setPositionX(100)
            self._srcWindow.setPositionY(100)

        self._srcWindow.removeAllComponents()
        self._srcWindow.addComponent(CodeLabel(source))

        if self._srcWindow.getParent() is None:
            self.getWindow().addWindow(self._srcWindow)

    def resetExample(self):
        if self._currentFeature is not None:
            w = self.getWindow()
            w.removeSubwindows()
            f = self._currentFeature
            self._currentFeature = None
            if f in self._exampleCache:
                del self._exampleCache[f]
            self.setFeature(f)

    def setFeature(self, feature):

        from muntjac.demo.sampler.SamplerApplication import SamplerApplication

        if feature != self._currentFeature:
            self._currentFeature = feature
            self._right.removeAllComponents()
            self._left.removeAllComponents()

            self._left.addComponent(self._controls)
            self._title.setValue('<span>' + feature.getName() + '</span>')
            #            if feature.getSinceVersion().isNew():
            #                self._title.addStyleName('new')
            #            else:
            #                self._title.removeStyleName('new')

            self._left.addComponent(self.getExampleFor(feature))

            self._right.setCaption('Description and Resources')

            # Do not show parent description if it's directly inside the root
            alll = SamplerApplication.getAllFeatures()
            parent = alll.getParent(feature)
            isRoot = alll.getParent(parent) is None
            desc = parent.getDescription()
            hasParentDesc = False

            if parent is not None and not isRoot:
                parentLabel = Label(parent.getDescription())
                if desc is not None and desc != '':
                    parentLabel.setContentMode(Label.CONTENT_XHTML)
                    self._right.addComponent(parentLabel)
                    hasParentDesc = True
            desc = feature.getDescription()
            if desc is not None and desc != '':
                # Sample description uses additional decorations if a parent
                # description is found
                l = Label(
                    ("<div class=\"outer-deco\"><div class=\"deco\">"
                     "<span class=\"deco\"></span>") + desc + "</div></div>",
                    Label.CONTENT_XHTML)
                self._right.addComponent(l)
                if hasParentDesc:
                    l.setStyleName('sample-description')
                else:
                    l.setStyleName('description')

            # open src in new window -link
            self._showSrc.setTargetName(self._currentFeature.getFragmentName())
            er = ExternalResource(self.getApplication().getURL() + 'src/' +
                                  self._currentFeature.getFragmentName())
            self._showSrc.setResource(er)

            resources = feature.getRelatedResources()
            if resources is not None:
                res = VerticalLayout()
                self.caption = Label("<span>Additional Resources</span>",
                                     Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                res.addComponent(self.caption)
                res.setMargin(False, False, True, False)
                for r in resources:
                    l = Link(r.getName(), r)
                    l.setIcon(ThemeResource('../runo/icons/16/note.png'))
                    res.addComponent(l)
                self._right.addComponent(res)

            apis = feature.getRelatedAPI()
            if apis is not None:
                api = VerticalLayout()
                self.caption = Label("<span>API Documentation</span>",
                                     Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                api.addComponent(self.caption)
                api.setMargin(False, False, True, False)
                for r in apis:
                    l = Link(r.getName(), r)
                    ic = ThemeResource('../runo/icons/16/document-txt.png')
                    l.setIcon(ic)
                    api.addComponent(l)
                self._right.addComponent(api)

            features = feature.getRelatedFeatures()
            if features is not None:
                rel = VerticalLayout()
                self.caption = Label("<span>Related Samples</span>",
                                     Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                rel.addComponent(self.caption)
                rel.setMargin(False, False, True, False)
                for c in features:
                    f = SamplerApplication.getFeatureFor(c)
                    if f is not None:
                        er = ExternalResource(self.getApplication().getURL() +
                                              '#' + f.getFragmentName())
                        al = ActiveLink(f.getName(), er)
                        if isinstance(f, FeatureSet):
                            ic = ThemeResource('../sampler/icons/category.gif')
                        else:
                            ic = ThemeResource('../sampler/icons/sample.png')
                        al.setIcon(ic)

                        al.addListener(LinkListener(self, f),
                                       ILinkActivatedListener)
                        rel.addComponent(al)
                self._right.addComponent(rel)

    def getExampleFor(self, f):
        ex = self._exampleCache.get(f)
        if ex is None:
            ex = f.getExample()
            self._exampleCache[f] = ex
        return ex
Exemplo n.º 17
0
class FeatureView(HorizontalLayout):

    _MSG_SHOW_SRC = 'View Source'

    def __init__(self):
        super(FeatureView, self).__init__()

        self._right = None
        self._left = None
        self._controls = None
        self._title = Label("", Label.CONTENT_XHTML)
        self._showSrc = None
        self._exampleCache = dict()
        self._currentFeature = None
        self._srcWindow = None

        self.setWidth('100%')
        self.setMargin(True)
        self.setSpacing(True)
        self.setStyleName('sample-view')

        self._left = VerticalLayout()
        self._left.setWidth('100%')
        self._left.setSpacing(True)
        self._left.setMargin(False)
        self.addComponent(self._left)
        self.setExpandRatio(self._left, 1)

        rightLayout = VerticalLayout()
        self._right = Panel(rightLayout)
        rightLayout.setMargin(True, False, False, False)
        self._right.setStyleName(Reindeer.PANEL_LIGHT)
        self._right.addStyleName('feature-info')
        self._right.setWidth('319px')
        self.addComponent(self._right)

        self._controls = HorizontalLayout()
        self._controls.setWidth('100%')
        self._controls.setStyleName('feature-controls')

        self._title.setStyleName('title')
        self._controls.addComponent(self._title)
        self._controls.setExpandRatio(self._title, 1)

        resetExample = NativeButton('Reset', ResetListener(self))
        resetExample.setStyleName(BaseTheme.BUTTON_LINK)
        resetExample.addStyleName('reset')
        resetExample.setDescription('Reset Sample')
        self._controls.addComponent(resetExample)
        self._showSrc = ActiveLink()
        self._showSrc.setDescription('Right / middle / ctrl / shift -click for browser window/tab')

        self._showSrc.addListener(ShowSrcListener(self), ILinkActivatedListener)
        self._showSrc.setCaption(self._MSG_SHOW_SRC)
        self._showSrc.addStyleName('showcode')
        self._showSrc.setTargetBorder(Link.TARGET_BORDER_NONE)
        self._controls.addComponent(self._showSrc)


    def showSource(self, source):
        if self._srcWindow is None:
            self._srcWindow = Window('Python source')
            self._srcWindow.getContent().setSizeUndefined()
            self._srcWindow.setWidth('70%')
            self._srcWindow.setHeight('60%')
            self._srcWindow.setPositionX(100)
            self._srcWindow.setPositionY(100)

        self._srcWindow.removeAllComponents()
        self._srcWindow.addComponent( CodeLabel(source) )

        if self._srcWindow.getParent() is None:
            self.getWindow().addWindow(self._srcWindow)


    def resetExample(self):
        if self._currentFeature is not None:
            w = self.getWindow()
            w.removeSubwindows()
            f = self._currentFeature
            self._currentFeature = None
            if f in self._exampleCache:
                del self._exampleCache[f]
            self.setFeature(f)


    def setFeature(self, feature):

        from muntjac.demo.sampler.SamplerApplication import SamplerApplication

        if feature != self._currentFeature:
            self._currentFeature = feature
            self._right.removeAllComponents()
            self._left.removeAllComponents()

            self._left.addComponent(self._controls)
            self._title.setValue('<span>' + feature.getName() + '</span>')
            if feature.getSinceVersion().isNew():
                self._title.addStyleName('new')
            else:
                self._title.removeStyleName('new')

            self._left.addComponent(self.getExampleFor(feature))

            self._right.setCaption('Description and Resources')

            # Do not show parent description if it's directly inside the root
            alll = SamplerApplication.getAllFeatures()
            parent = alll.getParent(feature)
            isRoot = alll.getParent(parent) is None
            desc = parent.getDescription()
            hasParentDesc = False

            if parent is not None and not isRoot:
                parentLabel = Label(parent.getDescription())
                if desc is not None and desc != '':
                    parentLabel.setContentMode(Label.CONTENT_XHTML)
                    self._right.addComponent(parentLabel)
                    hasParentDesc = True
            desc = feature.getDescription()
            if desc is not None and desc != '':
                # Sample description uses additional decorations if a parent
                # description is found
                l = Label(("<div class=\"outer-deco\"><div class=\"deco\">"
                        "<span class=\"deco\"></span>")
                        + desc + "</div></div>", Label.CONTENT_XHTML)
                self._right.addComponent(l)
                if hasParentDesc:
                    l.setStyleName('sample-description')
                else:
                    l.setStyleName('description')

            # open src in new window -link
            self._showSrc.setTargetName(self._currentFeature.getFragmentName())
            er = ExternalResource(self.getApplication().getURL()
                    + 'src/' + self._currentFeature.getFragmentName())
            self._showSrc.setResource(er)

            resources = feature.getRelatedResources()
            if resources is not None:
                res = VerticalLayout()
                self.caption = Label("<span>Additional Resources</span>",
                        Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                res.addComponent(self.caption)
                res.setMargin(False, False, True, False)
                for r in resources:
                    l = Link(r.getName(), r)
                    l.setIcon( ThemeResource('../runo/icons/16/note.png') )
                    res.addComponent(l)
                self._right.addComponent(res)

            apis = feature.getRelatedAPI()
            if apis is not None:
                api = VerticalLayout()
                self.caption = Label("<span>API Documentation</span>",
                        Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                api.addComponent(self.caption)
                api.setMargin(False, False, True, False)
                for r in apis:
                    l = Link(r.getName(), r)
                    ic = ThemeResource('../runo/icons/16/document-txt.png')
                    l.setIcon(ic)
                    api.addComponent(l)
                self._right.addComponent(api)

            features = feature.getRelatedFeatures()
            if features is not None:
                rel = VerticalLayout()
                self.caption = Label("<span>Related Samples</span>",
                        Label.CONTENT_XHTML)
                self.caption.setStyleName('section')
                self.caption.setWidth('100%')
                rel.addComponent(self.caption)
                rel.setMargin(False, False, True, False)
                for c in features:
                    f = SamplerApplication.getFeatureFor(c)
                    if f is not None:
                        er = ExternalResource(self.getApplication().getURL()
                                + '#' + f.getFragmentName())
                        al = ActiveLink(f.getName(), er)
                        if isinstance(f, FeatureSet):
                            ic = ThemeResource('../sampler/icons/category.gif')
                        else:
                            ic = ThemeResource('../sampler/icons/sample.png')
                        al.setIcon(ic)

                        al.addListener(LinkListener(self, f),
                                ILinkActivatedListener)
                        rel.addComponent(al)
                self._right.addComponent(rel)


    def getExampleFor(self, f):
        ex = self._exampleCache.get(f)
        if ex is None:
            ex = f.getExample()
            self._exampleCache[f] = ex
        return ex
Exemplo n.º 18
0
    def init(self):
        # We'll build the whole UI here, since the application will not
        # contain any logic. Otherwise it would be more practical to
        # separate parts of the UI into different classes and methods.

        # Main (browser) window, needed in all Muntjac applications
        rootLayout = VerticalLayout()
        root = Window('MuntjacTunes', rootLayout)

        # We'll attach the window to the browser view already here, so
        # we won't forget it later.
        self.setMainWindow(root)

        root.showNotification(('This is an example of how you can do layouts '
                'in Muntjac.<br/>It is not a working sound player.'),
                Notification.TYPE_HUMANIZED_MESSAGE)

        # Our root window contains one VerticalLayout, let's make
        # sure it's 100% sized, and remove unwanted margins
        rootLayout.setSizeFull()
        rootLayout.setMargin(False)

        # Top area, containing playback and volume controls, play status,
        # view modes and search
        top = HorizontalLayout()
        top.setWidth('100%')
        top.setMargin(False, True, False, True)  # Enable horizontal margins
        top.setSpacing(True)

        # Let's attach that one straight away too
        root.addComponent(top)

        # Create the placeholders for all the components in the top area
        playback = HorizontalLayout()
        volume = HorizontalLayout()
        status = HorizontalLayout()
        viewmodes = HorizontalLayout()
        search = ComboBox()

        # Add the components and align them properly
        top.addComponent(playback)
        top.addComponent(volume)
        top.addComponent(status)
        top.addComponent(viewmodes)
        top.addComponent(search)
        top.setComponentAlignment(playback, Alignment.MIDDLE_LEFT)
        top.setComponentAlignment(volume, Alignment.MIDDLE_LEFT)
        top.setComponentAlignment(status, Alignment.MIDDLE_CENTER)
        top.setComponentAlignment(viewmodes, Alignment.MIDDLE_LEFT)
        top.setComponentAlignment(search, Alignment.MIDDLE_LEFT)

        # We want our status area to expand if the user resizes the root
        # window, and we want it to accommodate as much space as there is
        # available. All other components in the top layout should stay fixed
        # sized, so we don't need to specify any expand ratios for them (they
        # will automatically revert to zero after the following line).
        top.setExpandRatio(status, 1.0)

        # Playback controls
        prev = NativeButton('Previous')
        play = NativeButton('Play/pause')
        nextt = NativeButton('Next')
        playback.addComponent(prev)
        playback.addComponent(play)
        playback.addComponent(nextt)
        # Set spacing between the buttons
        playback.setSpacing(True)

        # Volume controls
        mute = NativeButton('mute')
        vol = Slider()
        vol.setOrientation(Slider.ORIENTATION_HORIZONTAL)
        vol.setWidth('100px')
        maxx = NativeButton('max')
        volume.addComponent(mute)
        volume.addComponent(vol)
        volume.addComponent(maxx)

        # Status area
        status.setWidth('80%')
        status.setSpacing(True)

        toggleVisualization = NativeButton('Mode')
        timeFromStart = Label('0:00')

        # We'll need another layout to show currently playing track and
        # progress
        trackDetails = VerticalLayout()
        trackDetails.setWidth('100%')
        track = Label('Track Name')
        album = Label('Album Name - Artist')
        track.setWidth(None)
        album.setWidth(None)
        progress = Slider()
        progress.setOrientation(Slider.ORIENTATION_HORIZONTAL)
        progress.setWidth('100%')
        trackDetails.addComponent(track)
        trackDetails.addComponent(album)
        trackDetails.addComponent(progress)
        trackDetails.setComponentAlignment(track, Alignment.TOP_CENTER)
        trackDetails.setComponentAlignment(album, Alignment.TOP_CENTER)

        timeToEnd = Label('-4:46')
        jumpToTrack = NativeButton('Show')

        # Place all components to the status layout and align them properly
        status.addComponent(toggleVisualization)
        status.setComponentAlignment(toggleVisualization,
                Alignment.MIDDLE_LEFT)
        status.addComponent(timeFromStart)
        status.setComponentAlignment(timeFromStart, Alignment.BOTTOM_LEFT)
        status.addComponent(trackDetails)
        status.addComponent(timeToEnd)
        status.setComponentAlignment(timeToEnd, Alignment.BOTTOM_LEFT)
        status.addComponent(jumpToTrack)
        status.setComponentAlignment(jumpToTrack, Alignment.MIDDLE_LEFT)

        # Then remember to specify the expand ratio
        status.setExpandRatio(trackDetails, 1.0)

        # View mode buttons
        viewAsTable = NativeButton('Table')
        viewAsGrid = NativeButton('Grid')
        coverflow = NativeButton('Coverflow')
        viewmodes.addComponent(viewAsTable)
        viewmodes.addComponent(viewAsGrid)
        viewmodes.addComponent(coverflow)

        # That covers the top bar. Now let's move on to the sidebar
        # and track listing

        # We'll need one splitpanel to separate the sidebar and track listing
        bottom = HorizontalSplitPanel()
        root.addComponent(bottom)

        # The splitpanel is by default 100% x 100%, but we'll need to
        # adjust our main window layout to accommodate the height
        root.getContent().setExpandRatio(bottom, 1.0)

        # Give the sidebar less space than the listing
        bottom.setSplitPosition(200, ISizeable.UNITS_PIXELS)

        # Let's add some content to the sidebar
        # First, we need a layout to but all components in
        sidebar = VerticalLayout()
        sidebar.setSizeFull()
        bottom.setFirstComponent(sidebar)

        # Then we need some labels and buttons, and an album cover image The
        # labels and buttons go into their own vertical layout, since we want
        # the 'sidebar' layout to be expanding (cover image in the bottom).
        # VerticalLayout is by default 100% wide.
        selections = VerticalLayout()
        library = Label('Library')
        music = NativeButton('Music')
        music.setWidth('100%')

        store = Label('Store')
        muntjacTunesStore = NativeButton('MuntjacTunes Store')
        muntjacTunesStore.setWidth('100%')
        purchased = NativeButton('Purchased')
        purchased.setWidth('100%')

        playlists = Label('Playlists')
        genius = NativeButton('Geniues')
        genius.setWidth('100%')
        recent = NativeButton('Recently Added')
        recent.setWidth('100%')

        # Lets add them to the 'selections' layout
        selections.addComponent(library)
        selections.addComponent(music)
        selections.addComponent(store)
        selections.addComponent(muntjacTunesStore)
        selections.addComponent(purchased)
        selections.addComponent(playlists)
        selections.addComponent(genius)
        selections.addComponent(recent)

        # Then add the selections to the sidebar, and set it expanding
        sidebar.addComponent(selections)
        sidebar.setExpandRatio(selections, 1.0)

        # Then comes the cover artwork (we'll add the actual image in the
        # themeing section)
        cover = Embedded('Currently Playing')
        sidebar.addComponent(cover)

        # And lastly, we need the track listing table It should fill the whole
        # left side of our bottom layout
        listing = Table()
        listing.setSizeFull()
        listing.setSelectable(True)
        bottom.setSecondComponent(listing)

        # Add the table headers
        listing.addContainerProperty('Name', str, '')
        listing.addContainerProperty('Time', str, '0:00')
        listing.addContainerProperty('Artist', str, '')
        listing.addContainerProperty('Album', str, '')
        listing.addContainerProperty('Genre', str, '')
        listing.addContainerProperty('Rating', NativeSelect, NativeSelect())

        # Lets populate the table with random data
        tracks = ['Red Flag', 'Millstone', 'Not The Sun', 'Breath',
                'Here We Are', 'Deep Heaven', 'Her Voice Resides',
                'Natural Tan', 'End It All', 'Kings', 'Daylight Slaving',
                'Mad Man', 'Resolve', 'Teargas', 'African Air', 'Passing Bird']
        times = ['4:12', '6:03', '5:43', '4:32', '3:42', '4:45', '2:56',
                '9:34', '2:10', '3:44', '5:49', '6:30', '5:18', '7:42',
                '3:13', '2:52']
        artists = ['Billy Talent', 'Brand New', 'Breaking Benjamin',
                'Becoming The Archetype', 'Bullet For My Valentine',
                'Chasing Victory', 'Chimaira', 'Danko Jones', 'Deadlock',
                'Deftones', 'From Autumn To Ashes', 'Haste The Day',
                'Four Year Strong', 'In Flames', 'Kemopetrol', 'John Legend']
        albums = ['Once Again', 'The Caitiff Choir', 'The Devil And God',
                'Light Grenades', 'Dicthonomy', 'Back In Black', 'Dreamer',
                'Come Clarity', 'Year Zero', 'Frames', 'Fortress', 'Phobia',
                'The Poison', 'Manifesto', 'White Pony', 'The Big Dirty']
        genres = ['Rock', 'Metal', 'Hardcore', 'Indie', 'Pop', 'Alternative',
                'Blues', 'Jazz', 'Hip Hop', 'Electronica', 'Punk', 'Hard Rock',
                'Dance', 'R\'n\'B', 'Gospel', 'Country']

        for i in range(100):
            s = NativeSelect()
            s.addItem('1 star')
            s.addItem('2 stars')
            s.addItem('3 stars')
            s.addItem('4 stars')
            s.addItem('5 stars')
            s.select('%d stars' % (i % 5))
            index = i % 16
            listing.addItem([tracks[index], times[index],
                    artists[index], albums[index], genres[index], s], i)

        # We'll align the track time column to right as well
        listing.setColumnAlignment('Time', Table.ALIGN_RIGHT)

        # TODO: the footer

        # Now what's left to do? Themeing of course.
        self.setTheme('vaadintunes')

        # Let's give a namespace to our application window. This way, if
        # someone uses the same theme for different applications, we don't
        # get unwanted style conflicts.
        root.setStyleName('tTunes')

        top.setStyleName('top')
        top.setHeight('75px')  # Same as the background image height

        playback.setStyleName('playback')
        playback.setMargin(False, True, False, False)  # Add right-side margin
        play.setStyleName('play')
        nextt.setStyleName('next')
        prev.setStyleName('prev')
        playback.setComponentAlignment(prev, Alignment.MIDDLE_LEFT)
        playback.setComponentAlignment(nextt, Alignment.MIDDLE_LEFT)

        volume.setStyleName('volume')
        mute.setStyleName('mute')
        maxx.setStyleName('max')
        vol.setWidth('78px')

        status.setStyleName('status')
        status.setMargin(True)
        status.setHeight('46px')  # Height of the background image

        toggleVisualization.setStyleName('toggle-vis')
        jumpToTrack.setStyleName('jump')

        viewAsTable.setStyleName('viewmode-table')
        viewAsGrid.setStyleName('viewmode-grid')
        coverflow.setStyleName('viewmode-coverflow')

        sidebar.setStyleName('sidebar')

        music.setStyleName('selected')

        cover.setSource(ThemeResource('images/album-cover.jpg'))
        # Because this is an image, it will retain it's aspect ratio
        cover.setWidth('100%')
Exemplo n.º 19
0
class SimpleSliderEditor ( BaseRangeEditor ):
    """ Simple style of range editor that displays a slider and a text field.

    The user can set a value either by moving the slider or by typing a value
    in the text field.
    """

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

    # Low value for the slider range
    low = Any

    # High value for the slider range
    high = Any

    # Formatting string used to format value and labels
    format = Str

    #---------------------------------------------------------------------------
    #  Finishes initializing the editor by creating the underlying toolkit
    #  widget:
    #---------------------------------------------------------------------------

    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        factory = self.factory
        if not factory.low_name:
            self.low = factory.low

        if not factory.high_name:
            self.high = factory.high

        self.format = factory.format

        self.evaluate = factory.evaluate
        self.sync_value( factory.evaluate_name, 'evaluate', 'from' )

        self.sync_value( factory.low_name,  'low',  'from' )
        self.sync_value( factory.high_name, 'high', 'from' )

        self.control = panel = HorizontalLayout()
        panel.setMargin(False)
        panel.setSizeUndefined()

        fvalue = self.value

        try:
            if not (self.low <= fvalue <= self.high):
                fvalue = self.low
            fvalue_text = self.format % fvalue
        except:
            fvalue_text = ''
            fvalue      = self.low

        ivalue = self._convert_to_slider(fvalue)

        self._label_lo = Label()
        if factory.label_width > 0:
            self._label_lo.setWidth(factory.label_width, 'px')
        panel.addComponent(self._label_lo)
        panel.setComponentAlignment(self._label_lo, Alignment.MIDDLE_RIGHT)

        self.control.slider = slider = Slider()
        slider.setImmediate(True)
        slider.setOrientation(Slider.ORIENTATION_HORIZONTAL)

        slider.setMin(self.low)
        slider.setMax(self.high)

        slider.setValue(ivalue)
        slider.addCallback(self.update_object_on_scroll, ValueChangeEvent)
        panel.addComponent(slider)
        panel.setComponentAlignment(slider, Alignment.MIDDLE_RIGHT)

        self._label_hi = Label()
        panel.addComponent(self._label_hi)
        panel.setComponentAlignment(self._label_hi, Alignment.MIDDLE_RIGHT)
        if factory.label_width > 0:
            self._label_hi.setWidth(factory.label_width, 'px')

        self.control.text = text = TextField()
        text.setValue( str(fvalue_text) )
        text.addCallback(self.update_object_on_enter, BlurEvent)

        # The default size is a bit too big and probably doesn't need to grow.
        z = log10( float(self.high) )
        text.setWidth(z + 1, ISizeable.UNITS_EM)

        panel.addComponent(text)

        low_label = factory.low_label
        if factory.low_name != '':
            low_label = self.format % self.low

        high_label = factory.high_label
        if factory.high_name != '':
            high_label = self.format % self.high

        self._label_lo.setValue(str(low_label))
        self._label_hi.setValue(str(high_label))

        self.set_tooltip(slider)
        self.set_tooltip(self._label_lo)
        self.set_tooltip(self._label_hi)
        self.set_tooltip(text)

    #---------------------------------------------------------------------------
    #  Handles the user changing the current slider value:
    #---------------------------------------------------------------------------

    def update_object_on_scroll ( self, event ):
        """ Handles the user changing the current slider value.
        """
        pos = event.getProperty().getValue()
        value = self._convert_from_slider(pos)
        self.control.text.setValue( str(self.format % value) )
        self.value = value

    #---------------------------------------------------------------------------
    #  Handle the user pressing the 'Enter' key in the edit control:
    #---------------------------------------------------------------------------

    def update_object_on_enter ( self, event ):
        """ Handles the user pressing the Enter key in the text field.
        """
        try:
            try:
                value = eval(unicode(self.control.text.getValue()).strip())
            except Exception:
                # The entered something that didn't eval as a number, (e.g.,
                # 'foo') pretend it didn't happen
                value = self.value
                self.control.text.setValue(str(value))

            if not self.factory.is_float:
                value = int(value)

            self.value = value
            self.control.slider.setValue(self._convert_to_slider(self.value))
        except TraitError:
            pass

    #---------------------------------------------------------------------------
    #  Updates the editor when the object trait changes external to the editor:
    #---------------------------------------------------------------------------

    def update_editor ( self ):
        """ Updates the editor when the object trait changes externally to the
            editor.
        """
        value = self.value
        low   = self.low
        high  = self.high
        try:
            text = self.format % value
            1 / (low <= value <= high)
        except:
            text  = ''
            value = low

        ivalue = self._convert_to_slider(value)

        self.control.text.setValue( str(text) )

#        blocked = self.control.slider.blockSignals(True)
        self.control.slider.setValue(ivalue)
#        self.control.slider.blockSignals(blocked)

    #---------------------------------------------------------------------------
    #  Returns the editor's control for indicating error status:
    #---------------------------------------------------------------------------

    def get_error_control ( self ):
        """ Returns the editor's control for indicating error status.
        """
        return self.control.text

    #---------------------------------------------------------------------------
    #  Handles the 'low'/'high' traits being changed:
    #---------------------------------------------------------------------------

    def _low_changed ( self, low ):
        if self.value < low:
            if self.factory.is_float:
                self.value = float( low )
            else:
                self.value = int( low )

        if self.control is not None:
            self.control.slider.setMin(low)

        if self._label_lo is not None:
            self._label_lo.setValue( str(self.format % low) )
            self.update_editor()

    def _high_changed ( self, high ):
        if self.value > high:
            if self.factory.is_float:
                self.value = float( high )
            else:
                self.value = int( high )

        if self.control is not None:
            self.control.slider.setMax(high)

        if self._label_hi is not None:
            self._label_hi.setValue( str(self.format % high) )
            self.update_editor()

    def _convert_to_slider(self, value):
        """ Returns the slider setting corresponding to the user-supplied value.
        """
        if self.high > self.low:
#            ivalue = int( (float( value - self.low ) /
#                           (self.high - self.low)) * 10000.0 )
            ivalue = int(value)
        else:
            ivalue = self.low

            if ivalue is None:
                ivalue = 0

        if ivalue < self.low:
            ivalue = self.low
        elif ivalue > self.high:
            ivalue = self.high

        return ivalue

    def _convert_from_slider(self, ivalue):
        """ Returns the float or integer value corresponding to the slider
        setting.
        """
#        value = self.low + ((float( ivalue ) / 10000.0) *
#                            (self.high - self.low))
        value = ivalue
        if not self.factory.is_float:
            value = int(round(value))
        return value