Example #1
0
    def createSearch(self):
        self._search = ComboBox()
        self._search.setWidth('160px')
        self._search.setNewItemsAllowed(False)
        self._search.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self._search.setNullSelectionAllowed(True)
        self._search.setImmediate(True)
        self._search.setInputPrompt('Search samples...')
        self._search.setContainerDataSource(self._app._allFeatures)

        for idd in self._app._allFeatures.getItemIds():
            if isinstance(idd, FeatureSet):
                pass  # FIXME: 'SamplerApplication' has no attribute 'getResourceAsStream'


#                self._search.setItemIcon(idd,
#                        ClassResource('folder.gif', self._app))

        self._search.addListener(SearchListener(self),
                                 prop.IValueChangeListener)

        # TODO add icons for section/sample
        # PopupView pv = new PopupView("", search) { public void
        # changeVariables(Object source, Map variables) {
        # super.changeVariables(source, variables); if (isPopupVisible()) {
        # search.focus(); } } };

        pv = PopupView('<span></span>', self._search)

        pv.addListener(PopupListener(self), IPopupVisibilityListener)
        pv.setStyleName('quickjump')
        pv.setDescription('Quick jump')

        return pv
Example #2
0
    def __init__(self):
        super(DateResolutionExample, self).__init__()

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_DAY)
        self._datetime.setImmediate(True)

        # Create selection
        self._localeSelection = ComboBox('Select resolution:')
        self._localeSelection.setNullSelectionAllowed(False)
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)

        # Fill the selection with choices, set captions correctly
        self._localeSelection.setContainerDataSource(
            self.getResolutionContainer())
        self._localeSelection.setItemCaptionPropertyId(
            self.resolution_PROPERTY_NAME)
        self._localeSelection.setItemCaptionMode(
            ComboBox.ITEM_CAPTION_MODE_PROPERTY)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)
Example #3
0
    def __init__(self):
        super(DateLocaleExample, self).__init__()

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_MIN)
        self._datetime.setImmediate(True)
        self._datetime.setShowISOWeekNumbers(True)

        # Create selection and fill it with locales
        self._localeSelection = ComboBox('Select date format:')
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)
        self._localeSelection.setContainerDataSource(
            ExampleUtil.getLocaleContainer())
        self._localeSelection.setNullSelectionAllowed(False)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)
Example #4
0
class PersonFieldFactory(DefaultFieldFactory):
    def __init__(self, c):
        self._c = c

        super(PersonFieldFactory, self).__init__()

        self.countries = ComboBox("Country")
        self.countries.setWidth("100%")
        self.countries.setContainerDataSource(ExampleUtil.getISO3166Container())
        self.countries.setItemCaptionPropertyId(ExampleUtil.iso3166_PROPERTY_NAME)
        self.countries.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG)
        self.countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH)

    def createField(self, item, propertyId, uiContext):
        if "countryCode" == propertyId:
            # filtering ComboBox w/ country names
            return self.countries
        elif "password" == propertyId:
            # Create a password field so the password is not shown
            f = self.createPasswordField(propertyId)
        else:
            # Use the super class to create a suitable field base
            # on the property type.
            f = super(PersonFieldFactory, self).createField(item, propertyId, uiContext)

        if "firstName" == propertyId:
            tf = f
            tf.setRequired(True)
            tf.setRequiredError("Please enter a First Name")
            tf.setWidth(self._c._COMMON_FIELD_WIDTH)
            tf.addValidator(StringLengthValidator("First Name must be 3-25 characters", 3, 25, False))
        elif "lastName" == propertyId:
            tf = f
            tf.setRequired(True)
            tf.setRequiredError("Please enter a Last Name")
            tf.setWidth(self._c._COMMON_FIELD_WIDTH)
            tf.addValidator(StringLengthValidator("Last Name must be 3-50 characters", 3, 50, False))
        elif "password" == propertyId:
            pf = f
            pf.setRequired(True)
            pf.setRequiredError("Please enter a password")
            pf.setWidth("10em")
            pf.addValidator(StringLengthValidator("Password must be 6-20 characters", 6, 20, False))
        elif "shoesize" == propertyId:
            tf = f
            tf.setNullRepresentation("")
            tf.setNullSettingAllowed(True)
            tf.addValidator(IntegerValidator("Shoe size must be an Integer"))
            tf.setWidth("4em")
        return f

    def createPasswordField(self, propertyId):
        pf = PasswordField()
        pf.setCaption(DefaultFieldFactory.createCaptionByPropertyId(propertyId))
        return pf
Example #5
0
class DateLocaleExample(VerticalLayout, IValueChangeListener):
    def __init__(self):
        super(DateLocaleExample, self).__init__()

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_MIN)
        self._datetime.setImmediate(True)
        self._datetime.setShowISOWeekNumbers(True)

        # Create selection and fill it with locales
        self._localeSelection = ComboBox('Select date format:')
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)
        self._localeSelection.setContainerDataSource(
            ExampleUtil.getLocaleContainer())
        self._localeSelection.setNullSelectionAllowed(False)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)

    def valueChange(self, event):
        selected = self._localeSelection.getItem(
            event.getProperty().getValue())
        self._datetime.setLocale(
            selected.getItemProperty(
                ExampleUtil.locale_PROPERTY_LOCALE).getValue())
        self._datetime.requestRepaint()
    def __init__(self):
        super(ComboBoxPlainExample, self).__init__()

        self.setSpacing(True)
        l = ComboBox('Please select a city')

        for c in self._cities:
            l.addItem(c)

        l.setFilteringMode(IFiltering.FILTERINGMODE_OFF)
        l.setImmediate(True)
        l.addListener(self, IValueChangeListener)
        self.addComponent(l)
Example #7
0
    def __init__(self, c):
        self._c = c

        super(PersonFieldFactory, self).__init__()

        self.countries = ComboBox('Country')
        self.countries.setWidth('100%')
        self.countries.setContainerDataSource(
            ExampleUtil.getISO3166Container())
        self.countries.setItemCaptionPropertyId(
            ExampleUtil.iso3166_PROPERTY_NAME)
        self.countries.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG)
        self.countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH)
Example #8
0
    def __init__(self):
        super(ComboBoxNewItemsExample, self).__init__()

        self._lastAdded = False

        self.setSpacing(True)
        self._l = ComboBox('Please select a city')
        for c in self._cities:
            self._l.addItem(c)

        self._l.setNewItemsAllowed(True)
        self._l.setNewItemHandler(self)
        self._l.setImmediate(True)
        self._l.addListener(self, IValueChangeListener)
        self.addComponent(self._l)
    def createSearch(self):
        self._search = ComboBox()
        self._search.setWidth('160px')
        self._search.setNewItemsAllowed(False)
        self._search.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self._search.setNullSelectionAllowed(True)
        self._search.setImmediate(True)
        self._search.setInputPrompt('Search samples...')
        self._search.setContainerDataSource( self._app._allFeatures )

        for idd in self._app._allFeatures.getItemIds():
            if isinstance(idd, FeatureSet):
                pass  # FIXME: 'SamplerApplication' has no attribute 'getResourceAsStream'
#                self._search.setItemIcon(idd,
#                        ClassResource('folder.gif', self._app))

        self._search.addListener(SearchListener(self),
                prop.IValueChangeListener)

        # TODO add icons for section/sample
        # PopupView pv = new PopupView("", search) { public void
        # changeVariables(Object source, Map variables) {
        # super.changeVariables(source, variables); if (isPopupVisible()) {
        # search.focus(); } } };

        pv = PopupView('<span></span>', self._search)

        pv.addListener(PopupListener(self),
                IPopupVisibilityListener)
        pv.setStyleName('quickjump')
        pv.setDescription('Quick jump')

        return pv
Example #10
0
    def __init__(self):
        super(DateResolutionExample, self).__init__()

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_DAY)
        self._datetime.setImmediate(True)

        # Create selection
        self._localeSelection = ComboBox('Select resolution:')
        self._localeSelection.setNullSelectionAllowed(False)
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)

        # Fill the selection with choices, set captions correctly
        self._localeSelection.setContainerDataSource(
                self.getResolutionContainer())
        self._localeSelection.setItemCaptionPropertyId(
                self.resolution_PROPERTY_NAME)
        self._localeSelection.setItemCaptionMode(
                ComboBox.ITEM_CAPTION_MODE_PROPERTY)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)
Example #11
0
    def create(self, parent):
        """ Creates a QComboBox.

        """
        self.widget = ComboBox()
        self.widget.setImmediate(True)
        parent.addComponent(self.widget)
Example #12
0
 def create_control ( self, parent ):
     """ Creates the initial editor control.
     """
     self.control = ComboBox()
     self.control.setMultiSelect(False)
     self.control.setNullSelectionAllowed(True)
     self.control.setImmediate(True)
     self.control.addListener(self, IValueChangeListener)
Example #13
0
    def __init__(self, c):
        self._c = c

        super(PersonFieldFactory, self).__init__()

        self.countries = ComboBox("Country")
        self.countries.setWidth("100%")
        self.countries.setContainerDataSource(ExampleUtil.getISO3166Container())
        self.countries.setItemCaptionPropertyId(ExampleUtil.iso3166_PROPERTY_NAME)
        self.countries.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG)
        self.countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH)
    def __init__(self):
        super(ComboBoxInputPromptExample, self).__init__()

        self.setMargin(True, False, False, False)  # for looks: more 'air'

        # Create & set input prompt
        l = ComboBox()
        l.setInputPrompt('Please select a city')

        # configure & load content
        l.setImmediate(True)
        l.addListener(self, IValueChangeListener)
        for c in self._cities:
            l.addItem(c)

        # add to the layout
        self.addComponent(l)
Example #15
0
    def createThemeSelect(self):
        self.theme = ComboBox()
        self.theme.setWidth('32px')
        self.theme.setNewItemsAllowed(False)
        self.theme.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self.theme.setImmediate(True)
        self.theme.setNullSelectionAllowed(False)
        for themeName in self._app._THEMES:
            idd = self._app._SAMPLER_THEME_NAME + '-' + themeName
            self.theme.addItem(idd)
            self.theme.setItemCaption(
                idd, themeName[:1].upper() + (themeName[1:]) + ' theme')
            self.theme.setItemIcon(idd, _EMPTY_THEME_ICON)
        currentWindowTheme = self.getTheme()
        self.theme.setValue(currentWindowTheme)
        self.theme.setItemIcon(currentWindowTheme, _SELECTED_THEME_ICON)

        self.theme.addListener(ThemeChangeListener(self, self._app),
                               prop.IValueChangeListener)
        self.theme.setStyleName('theme-select')
        self.theme.setDescription('Select Theme')
        return self.theme
    def createThemeSelect(self):
        self.theme = ComboBox()
        self.theme.setWidth('32px')
        self.theme.setNewItemsAllowed(False)
        self.theme.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self.theme.setImmediate(True)
        self.theme.setNullSelectionAllowed(False)
        for themeName in self._app._THEMES:
            idd = self._app._SAMPLER_THEME_NAME + '-' + themeName
            self.theme.addItem(idd)
            self.theme.setItemCaption(idd,
                    themeName[:1].upper() + (themeName[1:]) + ' theme')
            self.theme.setItemIcon(idd, _EMPTY_THEME_ICON)
        currentWindowTheme = self.getTheme()
        self.theme.setValue(currentWindowTheme)
        self.theme.setItemIcon(currentWindowTheme, _SELECTED_THEME_ICON)

        self.theme.addListener(ThemeChangeListener(self, self._app),
                prop.IValueChangeListener)
        self.theme.setStyleName('theme-select')
        self.theme.setDescription('Select Theme')
        return self.theme
class SamplerWindow(Window):
    """The main window for Sampler, contains the full application UI."""

    _TITLE = 'Muntjac Sampler'

    def __init__(self, app):
        super(SamplerWindow, self).__init__()

        self._app = app

        self._currentList = FeatureGrid(self._app)
        self._featureView = FeatureView()
        self._currentFeature = ObjectProperty(None, Feature)

        self._mainSplit = None
        self._navigationTree = None
#        self._webAnalytics = GoogleAnalytics('UA-658457-6', 'none')
        # "backbutton"
        self._uriFragmentUtility = UriFragmentUtility()

        # breadcrumbs
        self._breadcrumbs = BreadCrumbs(self)

        self._previousSample = None
        self._nextSample = None
        self._search = None
        self.theme = None

        # Main top/expanded-bottom layout
        mainExpand = VerticalLayout()
        self.setContent(mainExpand)
        self.setSizeFull()
        mainExpand.setSizeFull()
        self.setCaption(self._TITLE)
        self.setTheme(self._app._currentApplicationTheme)

        # topbar (navigation)
        nav = HorizontalLayout()
        mainExpand.addComponent(nav)
        nav.setHeight('44px')
        nav.setWidth('100%')
        nav.setStyleName('topbar')
        nav.setSpacing(True)
        nav.setMargin(False, True, False, False)

        # Upper left logo
        logo = self.createLogo()
        nav.addComponent(logo)
        nav.setComponentAlignment(logo, Alignment.MIDDLE_LEFT)

        # Breadcrumbs
        nav.addComponent(self._breadcrumbs)
        nav.setExpandRatio(self._breadcrumbs, 1)
        nav.setComponentAlignment(self._breadcrumbs, Alignment.MIDDLE_LEFT)

        # invisible analytics -component
#        nav.addComponent(self._webAnalytics)

        # "backbutton"
        nav.addComponent(self._uriFragmentUtility)

        self._uriFragmentUtility.addListener(UriListener(self),
                IFragmentChangedListener)

        # Main left/right split; hidden menu tree
        self._mainSplit = HorizontalSplitPanel()
        self._mainSplit.setSizeFull()
        self._mainSplit.setStyleName('main-split')
        mainExpand.addComponent(self._mainSplit)
        mainExpand.setExpandRatio(self._mainSplit, 1)

        # Select theme
        themeSelect = self.createThemeSelect()
        nav.addComponent(themeSelect)
        nav.setComponentAlignment(themeSelect, Alignment.MIDDLE_LEFT)

        # Layouts for top area buttons
        quicknav = HorizontalLayout()
        arrows = HorizontalLayout()
        nav.addComponent(quicknav)
        nav.addComponent(arrows)
        nav.setComponentAlignment(quicknav, Alignment.MIDDLE_LEFT)
        nav.setComponentAlignment(arrows, Alignment.MIDDLE_LEFT)
        quicknav.setStyleName('segment')
        arrows.setStyleName('segment')

        # Previous sample
        self._previousSample = self.createPrevButton()
        arrows.addComponent(self._previousSample)

        # Next sample
        self._nextSample = self.createNextButton()
        arrows.addComponent(self._nextSample)

        # "Search" combobox
        searchComponent = self.createSearch()
        quicknav.addComponent(searchComponent)

        # Menu tree, initially shown
        menuLayout = CssLayout()
        allSamples = ActiveLink('All Samples', ExternalResource('#'))
        menuLayout.addComponent(allSamples)
        self._navigationTree = self.createMenuTree()
        menuLayout.addComponent(self._navigationTree)
        self._mainSplit.setFirstComponent(menuLayout)

        # Show / hide tree
        treeSwitch = self.createTreeSwitch()
        quicknav.addComponent(treeSwitch)

        self.addListener(WindowCloseListener(self, self._app),
                window.ICloseListener)
        self.updateFeatureList(self._currentList)


    def detach(self):
        super(SamplerWindow, self).detach()
        self._search.setContainerDataSource(None)
        self._navigationTree.setContainerDataSource(None)


    def removeSubwindows(self):
        wins = self.getChildWindows()
        if None is not wins:
            for w in wins:
                self.removeWindow(w)


    def setFeature(self, arg):
        """Displays a Feature(Set) or displays a Feature(Set) matching the
        given path, or the main view if no matching Feature(Set) is found.

        @param arg:
                   Either the Feature(Set) to show or the path of the
                   Feature(Set) to show
        """
        if isinstance(arg, basestring):
            path = arg
            f = FeatureSet.FEATURES.getFeature(path)
            self.setFeature(f)
        else:
            f = arg
            if f == FeatureSet.FEATURES:
                # "All" is no longer in the tree, use null instead
                f = None
            self._currentFeature.setValue(f)
            fragment = f.getFragmentName() if f is not None else ''

#            self._webAnalytics.trackPageview(fragment)
            self._uriFragmentUtility.setFragment(fragment, False)
            self._breadcrumbs.setPath( self._app.getFullPathFor(f) )

            self._previousSample.setEnabled(f is not None)
            self._nextSample.setEnabled(not self._app._allFeatures.isLastId(f))

            self.updateFeatureList(self._currentList)

            self.setCaption((f.getName() + ': ' if f is not None else '')
                    + self._TITLE)

    # SamplerWindow helpers

    def createSearch(self):
        self._search = ComboBox()
        self._search.setWidth('160px')
        self._search.setNewItemsAllowed(False)
        self._search.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self._search.setNullSelectionAllowed(True)
        self._search.setImmediate(True)
        self._search.setInputPrompt('Search samples...')
        self._search.setContainerDataSource( self._app._allFeatures )

        for idd in self._app._allFeatures.getItemIds():
            if isinstance(idd, FeatureSet):
                pass  # FIXME: 'SamplerApplication' has no attribute 'getResourceAsStream'
#                self._search.setItemIcon(idd,
#                        ClassResource('folder.gif', self._app))

        self._search.addListener(SearchListener(self),
                prop.IValueChangeListener)

        # TODO add icons for section/sample
        # PopupView pv = new PopupView("", search) { public void
        # changeVariables(Object source, Map variables) {
        # super.changeVariables(source, variables); if (isPopupVisible()) {
        # search.focus(); } } };

        pv = PopupView('<span></span>', self._search)

        pv.addListener(PopupListener(self),
                IPopupVisibilityListener)
        pv.setStyleName('quickjump')
        pv.setDescription('Quick jump')

        return pv


    def createThemeSelect(self):
        self.theme = ComboBox()
        self.theme.setWidth('32px')
        self.theme.setNewItemsAllowed(False)
        self.theme.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self.theme.setImmediate(True)
        self.theme.setNullSelectionAllowed(False)
        for themeName in self._app._THEMES:
            idd = self._app._SAMPLER_THEME_NAME + '-' + themeName
            self.theme.addItem(idd)
            self.theme.setItemCaption(idd,
                    themeName[:1].upper() + (themeName[1:]) + ' theme')
            self.theme.setItemIcon(idd, _EMPTY_THEME_ICON)
        currentWindowTheme = self.getTheme()
        self.theme.setValue(currentWindowTheme)
        self.theme.setItemIcon(currentWindowTheme, _SELECTED_THEME_ICON)

        self.theme.addListener(ThemeChangeListener(self, self._app),
                prop.IValueChangeListener)
        self.theme.setStyleName('theme-select')
        self.theme.setDescription('Select Theme')
        return self.theme


    def createLogo(self):
        logo = NativeButton('', LogoClickListener(self))
        logo.setDescription('Home')
        logo.setStyleName(BaseTheme.BUTTON_LINK)
        logo.addStyleName('logo')
        return logo


    def createNextButton(self):
        b = NativeButton('', NextClickListener(self, self._app))
        b.setStyleName('next')
        b.setDescription('Jump to the next sample')
        return b


    def createPrevButton(self):
        b = NativeButton('', PrevClickListener(self, self._app))
        b.setEnabled(False)
        b.setStyleName('previous')
        b.setDescription('Jump to the previous sample')
        return b


    def createTreeSwitch(self):
        b = NativeButton()
        b.setStyleName('tree-switch')
        b.addStyleName('down')
        b.setDescription('Toggle sample tree visibility')

        b.addListener(TreeClickListener(self),
                button.IClickListener)
        self._mainSplit.setSplitPosition(250, ISizeable.UNITS_PIXELS)
        return b


    def createMenuTree(self):
        tree = Tree()
        tree.setImmediate(True)
        tree.setStyleName('menu')
        tree.setContainerDataSource(self._app._allFeatures)

        self._currentFeature.addListener(FeatureChangeListener(self, tree),
                prop.IValueChangeListener)
        for f in FeatureSet.FEATURES.getFeatures():
            tree.expandItemsRecursively(f)
        tree.expandItemsRecursively(FeatureSet.FEATURES)

        tree.addListener(TreeChangeListener(self),
                prop.IValueChangeListener)

        tree.setItemStyleGenerator(TreeStyleGenerator())
        return tree


    def updateFeatureList(self, lst):
        self._currentList = lst
        val = self._currentFeature.getValue()
        if val is None:
            self._currentList.setFeatureContainer(self._app._allFeatures)
            self._mainSplit.setSecondComponent(self._currentList)
        elif isinstance(val, FeatureSet):
            self._currentList.setFeatureContainer(val.getContainer(True))
            self._mainSplit.setSecondComponent(self._currentList)
        else:
            self._mainSplit.setSecondComponent(self._featureView)
            self._featureView.setFeature(val)
Example #18
0
class SamplerWindow(Window):
    """The main window for Sampler, contains the full application UI."""

    _TITLE = 'Muntjac Sampler'

    def __init__(self, app):
        super(SamplerWindow, self).__init__()

        self._app = app

        self._currentList = FeatureGrid(self._app)
        self._featureView = FeatureView()
        self._currentFeature = ObjectProperty(None, Feature)

        self._mainSplit = None
        self._navigationTree = None
        #        self._webAnalytics = GoogleAnalytics('UA-658457-6', 'none')
        # "backbutton"
        self._uriFragmentUtility = UriFragmentUtility()

        # breadcrumbs
        self._breadcrumbs = BreadCrumbs(self)

        self._previousSample = None
        self._nextSample = None
        self._search = None
        self.theme = None

        # Main top/expanded-bottom layout
        mainExpand = VerticalLayout()
        self.setContent(mainExpand)
        self.setSizeFull()
        mainExpand.setSizeFull()
        self.setCaption(self._TITLE)
        self.setTheme(self._app._currentApplicationTheme)

        # topbar (navigation)
        nav = HorizontalLayout()
        mainExpand.addComponent(nav)
        nav.setHeight('44px')
        nav.setWidth('100%')
        nav.setStyleName('topbar')
        nav.setSpacing(True)
        nav.setMargin(False, True, False, False)

        # Upper left logo
        logo = self.createLogo()
        nav.addComponent(logo)
        nav.setComponentAlignment(logo, Alignment.MIDDLE_LEFT)

        # Breadcrumbs
        nav.addComponent(self._breadcrumbs)
        nav.setExpandRatio(self._breadcrumbs, 1)
        nav.setComponentAlignment(self._breadcrumbs, Alignment.MIDDLE_LEFT)

        # invisible analytics -component
        #        nav.addComponent(self._webAnalytics)

        # "backbutton"
        nav.addComponent(self._uriFragmentUtility)

        self._uriFragmentUtility.addListener(UriListener(self),
                                             IFragmentChangedListener)

        # Main left/right split; hidden menu tree
        self._mainSplit = HorizontalSplitPanel()
        self._mainSplit.setSizeFull()
        self._mainSplit.setStyleName('main-split')
        mainExpand.addComponent(self._mainSplit)
        mainExpand.setExpandRatio(self._mainSplit, 1)

        # Select theme
        themeSelect = self.createThemeSelect()
        nav.addComponent(themeSelect)
        nav.setComponentAlignment(themeSelect, Alignment.MIDDLE_LEFT)

        # Layouts for top area buttons
        quicknav = HorizontalLayout()
        arrows = HorizontalLayout()
        nav.addComponent(quicknav)
        nav.addComponent(arrows)
        nav.setComponentAlignment(quicknav, Alignment.MIDDLE_LEFT)
        nav.setComponentAlignment(arrows, Alignment.MIDDLE_LEFT)
        quicknav.setStyleName('segment')
        arrows.setStyleName('segment')

        # Previous sample
        self._previousSample = self.createPrevButton()
        arrows.addComponent(self._previousSample)

        # Next sample
        self._nextSample = self.createNextButton()
        arrows.addComponent(self._nextSample)

        # "Search" combobox
        searchComponent = self.createSearch()
        quicknav.addComponent(searchComponent)

        # Menu tree, initially shown
        menuLayout = CssLayout()
        allSamples = ActiveLink('All Samples', ExternalResource('#'))
        menuLayout.addComponent(allSamples)
        self._navigationTree = self.createMenuTree()
        menuLayout.addComponent(self._navigationTree)
        self._mainSplit.setFirstComponent(menuLayout)

        # Show / hide tree
        treeSwitch = self.createTreeSwitch()
        quicknav.addComponent(treeSwitch)

        self.addListener(WindowCloseListener(self, self._app),
                         window.ICloseListener)
        self.updateFeatureList(self._currentList)

    def detach(self):
        super(SamplerWindow, self).detach()
        self._search.setContainerDataSource(None)
        self._navigationTree.setContainerDataSource(None)

    def removeSubwindows(self):
        wins = self.getChildWindows()
        if None is not wins:
            for w in wins:
                self.removeWindow(w)

    def setFeature(self, arg):
        """Displays a Feature(Set) or displays a Feature(Set) matching the
        given path, or the main view if no matching Feature(Set) is found.

        @param arg:
                   Either the Feature(Set) to show or the path of the
                   Feature(Set) to show
        """
        if isinstance(arg, basestring):
            path = arg
            f = FeatureSet.FEATURES.getFeature(path)
            self.setFeature(f)
        else:
            f = arg
            if f == FeatureSet.FEATURES:
                # "All" is no longer in the tree, use null instead
                f = None
            self._currentFeature.setValue(f)
            fragment = f.getFragmentName() if f is not None else ''

            #            self._webAnalytics.trackPageview(fragment)
            self._uriFragmentUtility.setFragment(fragment, False)
            self._breadcrumbs.setPath(self._app.getFullPathFor(f))

            self._previousSample.setEnabled(f is not None)
            self._nextSample.setEnabled(not self._app._allFeatures.isLastId(f))

            self.updateFeatureList(self._currentList)

            self.setCaption((f.getName() + ': ' if f is not None else '') +
                            self._TITLE)

    # SamplerWindow helpers

    def createSearch(self):
        self._search = ComboBox()
        self._search.setWidth('160px')
        self._search.setNewItemsAllowed(False)
        self._search.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self._search.setNullSelectionAllowed(True)
        self._search.setImmediate(True)
        self._search.setInputPrompt('Search samples...')
        self._search.setContainerDataSource(self._app._allFeatures)

        for idd in self._app._allFeatures.getItemIds():
            if isinstance(idd, FeatureSet):
                pass  # FIXME: 'SamplerApplication' has no attribute 'getResourceAsStream'


#                self._search.setItemIcon(idd,
#                        ClassResource('folder.gif', self._app))

        self._search.addListener(SearchListener(self),
                                 prop.IValueChangeListener)

        # TODO add icons for section/sample
        # PopupView pv = new PopupView("", search) { public void
        # changeVariables(Object source, Map variables) {
        # super.changeVariables(source, variables); if (isPopupVisible()) {
        # search.focus(); } } };

        pv = PopupView('<span></span>', self._search)

        pv.addListener(PopupListener(self), IPopupVisibilityListener)
        pv.setStyleName('quickjump')
        pv.setDescription('Quick jump')

        return pv

    def createThemeSelect(self):
        self.theme = ComboBox()
        self.theme.setWidth('32px')
        self.theme.setNewItemsAllowed(False)
        self.theme.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS)
        self.theme.setImmediate(True)
        self.theme.setNullSelectionAllowed(False)
        for themeName in self._app._THEMES:
            idd = self._app._SAMPLER_THEME_NAME + '-' + themeName
            self.theme.addItem(idd)
            self.theme.setItemCaption(
                idd, themeName[:1].upper() + (themeName[1:]) + ' theme')
            self.theme.setItemIcon(idd, _EMPTY_THEME_ICON)
        currentWindowTheme = self.getTheme()
        self.theme.setValue(currentWindowTheme)
        self.theme.setItemIcon(currentWindowTheme, _SELECTED_THEME_ICON)

        self.theme.addListener(ThemeChangeListener(self, self._app),
                               prop.IValueChangeListener)
        self.theme.setStyleName('theme-select')
        self.theme.setDescription('Select Theme')
        return self.theme

    def createLogo(self):
        logo = NativeButton('', LogoClickListener(self))
        logo.setDescription('Home')
        logo.setStyleName(BaseTheme.BUTTON_LINK)
        logo.addStyleName('logo')
        return logo

    def createNextButton(self):
        b = NativeButton('', NextClickListener(self, self._app))
        b.setStyleName('next')
        b.setDescription('Jump to the next sample')
        return b

    def createPrevButton(self):
        b = NativeButton('', PrevClickListener(self, self._app))
        b.setEnabled(False)
        b.setStyleName('previous')
        b.setDescription('Jump to the previous sample')
        return b

    def createTreeSwitch(self):
        b = NativeButton()
        b.setStyleName('tree-switch')
        b.addStyleName('down')
        b.setDescription('Toggle sample tree visibility')

        b.addListener(TreeClickListener(self), button.IClickListener)
        self._mainSplit.setSplitPosition(250, ISizeable.UNITS_PIXELS)
        return b

    def createMenuTree(self):
        tree = Tree()
        tree.setImmediate(True)
        tree.setStyleName('menu')
        tree.setContainerDataSource(self._app._allFeatures)

        self._currentFeature.addListener(FeatureChangeListener(self, tree),
                                         prop.IValueChangeListener)
        for f in FeatureSet.FEATURES.getFeatures():
            tree.expandItemsRecursively(f)
        tree.expandItemsRecursively(FeatureSet.FEATURES)

        tree.addListener(TreeChangeListener(self), prop.IValueChangeListener)

        tree.setItemStyleGenerator(TreeStyleGenerator())
        return tree

    def updateFeatureList(self, lst):
        self._currentList = lst
        val = self._currentFeature.getValue()
        if val is None:
            self._currentList.setFeatureContainer(self._app._allFeatures)
            self._mainSplit.setSecondComponent(self._currentList)
        elif isinstance(val, FeatureSet):
            self._currentList.setFeatureContainer(val.getContainer(True))
            self._mainSplit.setSecondComponent(self._currentList)
        else:
            self._mainSplit.setSecondComponent(self._featureView)
            self._featureView.setFeature(val)
Example #19
0
class ComboBoxNewItemsExample(VerticalLayout, IValueChangeListener,
            abstract_select.INewItemHandler):

    _cities = ['Berlin', 'Brussels', 'Helsinki', 'Madrid', 'Oslo',
            'Paris', 'Stockholm']

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

        self._lastAdded = False

        self.setSpacing(True)
        self._l = ComboBox('Please select a city')
        for c in self._cities:
            self._l.addItem(c)

        self._l.setNewItemsAllowed(True)
        self._l.setNewItemHandler(self)
        self._l.setImmediate(True)
        self._l.addListener(self, IValueChangeListener)
        self.addComponent(self._l)

    # Shows a notification when a selection is made.
    def valueChange(self, event):
        if not self._lastAdded:
            self.getWindow().showNotification('Selected city: '
                    + str(event.getProperty()))
        self._lastAdded = False


    def addNewItem(self, newItemCaption):
        if not self._l.containsId(newItemCaption):
            self.getWindow().showNotification('Added city: '
                    + newItemCaption)
            self._lastAdded = True
            self._l.addItem(newItemCaption)
            self._l.setValue(newItemCaption)
Example #20
0
class SimpleEditor ( EditorWithList, IValueChangeListener ):
    """ Simple style of editor for checklists, which displays a combo box.
    """

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

    # Checklist item names
    names = List( Unicode )

    # Checklist item values
    values = List

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

    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        self.create_control( parent )
        super( SimpleEditor, self ).init( parent )
        self.set_tooltip()

    #---------------------------------------------------------------------------
    #  Creates the initial editor control:
    #---------------------------------------------------------------------------

    def create_control ( self, parent ):
        """ Creates the initial editor control.
        """
        self.control = ComboBox()
        self.control.setMultiSelect(False)
        self.control.setNullSelectionAllowed(True)
        self.control.setImmediate(True)
        self.control.addListener(self, IValueChangeListener)

    #---------------------------------------------------------------------------
    #  Handles the list of legal check list values being updated:
    #---------------------------------------------------------------------------

    def list_updated ( self, values ):
        """ Handles updates to the list of legal checklist values.
        """
        sv = self.string_value
        if (len( values ) > 0) and isinstance( values[0], basestring ):
            values = [ ( x, sv( x, capitalize ) ) for x in values ]
        self.values = valid_values = [ x[0] for x in values ]
        self.names  =                [ x[1] for x in values ]

        # Make sure the current value is still legal:
        modified  = False
        cur_value = parse_value( self.value )
        for i in range( len( cur_value ) - 1, -1, -1 ):
            if cur_value[i] not in valid_values:
                try:
                    del cur_value[i]
                    modified = True
                except TypeError:
                    logger.warn('Unable to remove non-current value [%s] from '
                        'values %s', cur_value[i], values)
        if modified:
            if isinstance( self.value, basestring ):
                cur_value = ','.join( cur_value )
            self.value = cur_value

        self.rebuild_editor()

    #---------------------------------------------------------------------------
    #  Rebuilds the editor after its definition is modified:
    #---------------------------------------------------------------------------

    def rebuild_editor ( self ):
        """ Rebuilds the editor after its definition is modified.
        """
        control = self.control
        c = IndexedContainer()
        for name in self.names:
            c.addItem(name)
        control.setContainerDataSource(c)
        self.update_editor()

    #---------------------------------------------------------------------------
    #  Handles the user selecting a new value from the combo box:
    #---------------------------------------------------------------------------

    def valueChange(self, event):
        v = str(event.getProperty())
        self.update_object(v)

    def update_object ( self, text ):
        """ Handles the user selecting a new value from the combo box.
        """
        if unicode(text) in self.names:
            value = self.values[self.names.index(unicode(text))]
            if not isinstance(self.value, basestring):
                value = [value]
        elif not isinstance(self.value, basestring):
            value = []
        else:
            value = ''
        self.value = value

    #---------------------------------------------------------------------------
    #  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.
        """
        try:
            self.control.select( parse_value(self.value)[0] )
        except:
            pass
    def __init__(self):
        super(ComboBoxStartsWithExample, self).__init__()

        self.setSpacing(True)

        # Creates a new combobox using an existing container
        l = ComboBox('Please select your country',
                ExampleUtil.getISO3166Container())

        # Sets the combobox to show a certain property as the item caption
        l.setItemCaptionPropertyId(ExampleUtil.iso3166_PROPERTY_NAME)
        l.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY)

        # Sets the icon to use with the items
        l.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG)

        # Set a reasonable width
        l.setWidth(350, self.UNITS_PIXELS)

        # Set the appropriate filtering mode for this example
        l.setFilteringMode(IFiltering.FILTERINGMODE_STARTSWITH)
        l.setImmediate(True)
        l.addListener(self, IValueChangeListener)

        # Disallow null selections
        l.setNullSelectionAllowed(False)
        self.addComponent(l)
Example #22
0
class PersonFieldFactory(DefaultFieldFactory):

    def __init__(self, c):
        self._c = c

        super(PersonFieldFactory, self).__init__()

        self.countries = ComboBox('Country')
        self.countries.setWidth(self._c._COMMON_FIELD_WIDTH)
        self.countries.setContainerDataSource(
                ExampleUtil.getISO3166Container())
        self.countries.setItemCaptionPropertyId(
                ExampleUtil.iso3166_PROPERTY_NAME)
        self.countries.setItemIconPropertyId(
                ExampleUtil.iso3166_PROPERTY_FLAG)
        self.countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH)


    def createField(self, item, propertyId, uiContext):
        if 'countryCode' == propertyId:
            # filtering ComboBox w/ country names
            return self.countries
        elif 'password' == propertyId:
            # Create a password field so the password is not shown
            f = self.createPasswordField(propertyId)
        else:
            # Use the super class to create a suitable field base on the
            # property type.
            f = super(PersonFieldFactory, self).createField(item,
                    propertyId, uiContext)

        if 'firstName' == propertyId:
            tf = f
            tf.setRequired(True)
            tf.setRequiredError('Please enter a First Name')
            tf.setWidth(self._c._COMMON_FIELD_WIDTH)
            tf.addValidator(StringLengthValidator(
                    'First Name must be 3-25 characters', 3, 25, False))
        elif 'lastName' == propertyId:
            tf = f
            tf.setRequired(True)
            tf.setRequiredError('Please enter a Last Name')
            tf.setWidth(self._c._COMMON_FIELD_WIDTH)
            tf.addValidator(StringLengthValidator(
                    'Last Name must be 3-50 characters', 3, 50, False))
        elif 'password' == propertyId:
            pf = f
            pf.setRequired(True)
            pf.setRequiredError('Please enter a password')
            pf.setWidth('10em')
            pf.addValidator(StringLengthValidator(
                    'Password must be 6-20 characters', 6, 20, False))
        elif 'shoesize' == propertyId:
            tf = f
            tf.setNullRepresentation('')
            tf.setNullSettingAllowed(True)
            tf.addValidator(IntegerValidator('Shoe size must be an Integer'))
            tf.setWidth('2em')
        elif 'uuid' == propertyId:
            tf = f
            tf.setWidth('20em')

        return f


    def createPasswordField(self, propertyId):
        pf = PasswordField()
        pf.setCaption(DefaultFieldFactory.createCaptionByPropertyId(propertyId))
        return pf
Example #23
0
class DateResolutionExample(VerticalLayout, IValueChangeListener):

    resolution_PROPERTY_NAME = 'name'

    # Resolution fields from DateField
    _resolutions = [
        InlineDateField.RESOLUTION_YEAR,
        InlineDateField.RESOLUTION_MONTH,
        InlineDateField.RESOLUTION_DAY,
        InlineDateField.RESOLUTION_HOUR,
        InlineDateField.RESOLUTION_MIN,
        InlineDateField.RESOLUTION_SEC,
        InlineDateField.RESOLUTION_MSEC
    ]

    _resolutionNames = [
        'Year', 'Month', 'Day', 'Hour', 'Minute', 'Second', 'Millisecond'
    ]

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

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_DAY)
        self._datetime.setImmediate(True)

        # Create selection
        self._localeSelection = ComboBox('Select resolution:')
        self._localeSelection.setNullSelectionAllowed(False)
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)

        # Fill the selection with choices, set captions correctly
        self._localeSelection.setContainerDataSource(
                self.getResolutionContainer())
        self._localeSelection.setItemCaptionPropertyId(
                self.resolution_PROPERTY_NAME)
        self._localeSelection.setItemCaptionMode(
                ComboBox.ITEM_CAPTION_MODE_PROPERTY)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)


    def valueChange(self, event):
        self._datetime.setResolution(event.getProperty().getValue())
        self._datetime.requestRepaint()


    def getResolutionContainer(self):
        resolutionContainer = IndexedContainer()
        resolutionContainer.addContainerProperty(
                self.resolution_PROPERTY_NAME, str, None)

        for i, res in enumerate(self._resolutions):
            added = resolutionContainer.addItem(res)
            added.getItemProperty(
                    self.resolution_PROPERTY_NAME).setValue(
                            self._resolutionNames[i])

        return resolutionContainer
Example #24
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%')
Example #25
0
class DateResolutionExample(VerticalLayout, IValueChangeListener):

    resolution_PROPERTY_NAME = 'name'

    # Resolution fields from DateField
    _resolutions = [
        InlineDateField.RESOLUTION_YEAR, InlineDateField.RESOLUTION_MONTH,
        InlineDateField.RESOLUTION_DAY, InlineDateField.RESOLUTION_HOUR,
        InlineDateField.RESOLUTION_MIN, InlineDateField.RESOLUTION_SEC,
        InlineDateField.RESOLUTION_MSEC
    ]

    _resolutionNames = [
        'Year', 'Month', 'Day', 'Hour', 'Minute', 'Second', 'Millisecond'
    ]

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

        self.setSpacing(True)

        self._datetime = InlineDateField('Please select the starting time:')

        # Set the value of the PopupDateField to current date
        self._datetime.setValue(datetime.today())

        # Set the correct resolution
        self._datetime.setResolution(InlineDateField.RESOLUTION_DAY)
        self._datetime.setImmediate(True)

        # Create selection
        self._localeSelection = ComboBox('Select resolution:')
        self._localeSelection.setNullSelectionAllowed(False)
        self._localeSelection.addListener(self, IValueChangeListener)
        self._localeSelection.setImmediate(True)

        # Fill the selection with choices, set captions correctly
        self._localeSelection.setContainerDataSource(
            self.getResolutionContainer())
        self._localeSelection.setItemCaptionPropertyId(
            self.resolution_PROPERTY_NAME)
        self._localeSelection.setItemCaptionMode(
            ComboBox.ITEM_CAPTION_MODE_PROPERTY)

        self.addComponent(self._datetime)
        self.addComponent(self._localeSelection)

    def valueChange(self, event):
        self._datetime.setResolution(event.getProperty().getValue())
        self._datetime.requestRepaint()

    def getResolutionContainer(self):
        resolutionContainer = IndexedContainer()
        resolutionContainer.addContainerProperty(self.resolution_PROPERTY_NAME,
                                                 str, None)

        for i, res in enumerate(self._resolutions):
            added = resolutionContainer.addItem(res)
            added.getItemProperty(self.resolution_PROPERTY_NAME).setValue(
                self._resolutionNames[i])

        return resolutionContainer
Example #26
0
class CustomEditor ( Editor ):
    """ Custom style of editor for instances. If selection among instances is
    allowed, the editor displays a combo box listing instances that can be
    selected. If the current instance is editable, the editor displays a panel
    containing trait editors for all the instance's traits.
    """

    # Background color when an item can be dropped on the editor:
    ok_color = DropColor

    # The orientation of the instance editor relative to the instance selector:
    orientation = 'vertical'

    # Class constant:
    extra = 0

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

    # List of InstanceChoiceItem objects used by the editor
    items = Property

    # The view to use for displaying the instance
    view = AView

    #---------------------------------------------------------------------------
    #  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 factory.name != '':
            self._object, self._name, self._value = \
                self.parse_extended_name( factory.name )

        # Create a panel to hold the object trait's view:
        if factory.editable:
            self.control = self._panel = parent = Panel()

        # Build the instance selector if needed:
        selectable = factory.selectable
        droppable  = factory.droppable
        items      = self.items
        for item in items:
            droppable  |= item.is_droppable()
            selectable |= item.is_selectable()

        if selectable:
            self._object_cache = {}
            item = self.item_for( self.value )
            if item is not None:
                self._object_cache[ id( item ) ] = self.value

            self._choice = ComboBox()
            self._choice.addCallback(self.update_object, ValueChangeEvent)

            self.set_tooltip( self._choice )

            if factory.name != '':
                self._object.on_trait_change( self.rebuild_items,
                                              self._name, dispatch = 'ui' )
                self._object.on_trait_change( self.rebuild_items,
                                 self._name + '_items', dispatch = 'ui' )

            factory.on_trait_change( self.rebuild_items, 'values',
                                     dispatch = 'ui' )
            factory.on_trait_change( self.rebuild_items, 'values_items',
                                     dispatch = 'ui' )

            self.rebuild_items()

        elif droppable:
            self._choice = TextField()
            self._choice.setReadOnly(True)
            self.set_tooltip( self._choice )

        if droppable:
            raise NotImplementedError
#            self._choice.SetDropTarget( PythonDropTarget( self ) )

        orientation = factory.orientation
        if orientation == 'default':
            orientation = self.orientation

        if (selectable or droppable) and factory.editable:
            if orientation == 'vertical':
                layout = VerticalLayout()
            else:
                layout = HorizontalLayout()
            layout.setSizeUndefined()
            parent.addComponent(layout)
#            layout.setParent(parent)
            layout.setMargin(False)
            layout.addComponent(self._choice)

            if orientation == 'vertical':
                hline = Label('<hr />', Label.CONTENT_XHTML)
                layout.addComponent(hline)  # FIXME: explicit parent size

            self.create_editor(parent, layout)
        elif self.control is None:
            if self._choice is None:
                self._choice = ComboBox()
                self._choice.addCallback(self.update_object, ValueChangeEvent)

            self.control = self._choice
        else:
            if orientation == 'vertical':
                layout = VerticalLayout()
            else:
                layout = HorizontalLayout()
            parent.addComponent(layout)
            layout.setMargin(False)
            layout.setSizeUndefined()
            self.create_editor(parent, layout)

        # Synchronize the 'view' to use:
        # fixme: A normal assignment can cause a crash (for unknown reasons) in
        # some cases, so we make sure that no notifications are generated:
        self.trait_setq( view = factory.view )
        self.sync_value( factory.view_name, 'view', 'from' )

    #---------------------------------------------------------------------------
    #  Creates the editor control:
    #---------------------------------------------------------------------------

    def create_editor(self, parent, layout):
        """ Creates the editor control.
        """
        self._panel = Panel()
        layout.addComponent(self._panel)

    #---------------------------------------------------------------------------
    #  Gets the current list of InstanceChoiceItem items:
    #---------------------------------------------------------------------------

    def _get_items ( self ):
        """ Gets the current list of InstanceChoiceItem items.
        """
        if self._items is not None:
            return self._items

        factory = self.factory
        if self._value is not None:
            values = self._value() + factory.values
        else:
            values = factory.values

        items = []
        adapter = factory.adapter
        for value in values:
            if not isinstance( value, InstanceChoiceItem ):
                value = adapter( object = value )
            items.append( value )

        self._items = items

        return items

    #---------------------------------------------------------------------------
    #  Rebuilds the object selector list:
    #---------------------------------------------------------------------------

    def rebuild_items ( self ):
        """ Rebuilds the object selector list.
        """
        # Clear the current cached values:
        self._items = None

        # Rebuild the contents of the selector list:
        name   = -1
        value  = self.value
        choice = self._choice
        choice.removeAllItems()
        for i, item in enumerate(self.items):
            if item.is_selectable():
                choice.addItem( str(item.get_name()) )
                if item.is_compatible( value ):
                    name = i

        # Reselect the current item if possible:
        if name >= 0:
            ids = choice.getContainerPropertyIds()
            choice.select( ids[name] )
        else:
            # Otherwise, current value is no longer valid, try to discard it:
            try:
                self.value = None
            except:
                pass

    #---------------------------------------------------------------------------
    #  Returns the InstanceChoiceItem for a specified object:
    #---------------------------------------------------------------------------

    def item_for ( self, object ):
        """ Returns the InstanceChoiceItem for a specified object.
        """
        for item in self.items:
            if item.is_compatible( object ):
                return item

        return None

    #---------------------------------------------------------------------------
    #  Returns the view to use for a specified object:
    #---------------------------------------------------------------------------

    def view_for ( self, object, item ):
        """ Returns the view to use for a specified object.
        """
        view = ''
        if item is not None:
            view = item.get_view()

        if view == '':
            view = self.view

        return self.ui.handler.trait_view_for( self.ui.info, view, object,
                                               self.object_name, self.name )

    #---------------------------------------------------------------------------
    #  Handles the user selecting a new value from the combo box:
    #---------------------------------------------------------------------------

    def update_object(self, event):
        """ Handles the user selecting a new value from the combo box.
        """
        text = event.getProperty().getValue()
        name = unicode(text)
        for item in self.items:
            if name == item.get_name():
                id_item = id( item )
                object  = self._object_cache.get( id_item )
                if object is None:
                    object = item.get_object()
                    if (not self.factory.editable) and item.is_factory:
                        view = self.view_for( object, self.item_for( object ) )
                        view.ui( object, self.control, 'modal' )

                    if self.factory.cachable:
                        self._object_cache[ id_item ] = object

                self.value = object
                self.resynch_editor()
                break

    #---------------------------------------------------------------------------
    #  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.
        """
        # Synchronize the editor contents:
        self.resynch_editor()

        # Update the selector (if any):
        choice = self._choice
        item   = self.item_for( self.value )
        if (choice is not None) and (item is not None):
            name = item.get_name( self.value )
            if self._object_cache is not None:
                idx = choice.findText(name)
                if idx < 0:
                    idx = choice.count()
                    choice.addItem( str(name) )

                ids = choice.getContainerPropertyIds()
                choice.setCurrentIndex( ids[idx] )
            else:
                choice.setValue(name)

    #---------------------------------------------------------------------------
    #  Resynchronizes the contents of the editor when the object trait changes
    #  external to the editor:
    #---------------------------------------------------------------------------

    def resynch_editor ( self ):
        """ Resynchronizes the contents of the editor when the object trait
        changes externally to the editor.
        """
        panel = self._panel
        if panel is not None:
            # Dispose of the previous contents of the panel:
            layout = panel.getParent()
            if layout is None:
                layout = VerticalLayout()
                panel.addComponent(layout)
#                layout.setParent(panel)
                layout.setMargin(False)
            elif self._ui is not None:
                self._ui.dispose()
                self._ui = None
            else:
                layout.removeAllComponents()

            # Create the new content for the panel:
            stretch = 0
            value   = self.value
            if not isinstance( value, HasTraits ):
                str_value = ''
                if value is not None:
                    str_value = self.str_value
                control = Label()
                control.setValue(str_value)
            else:
                view    = self.view_for( value, self.item_for( value ) )
                context = value.trait_context()
                handler = None
                if isinstance( value, Handler ):
                    handler = value
                context.setdefault( 'context', self.object )
                context.setdefault( 'context_handler', self.ui.handler )
                self._ui = ui = view.ui( context, panel, 'subpanel',
                                         value.trait_view_elements(), handler,
                                         self.factory.id )
                control         = ui.control
                self.scrollable = ui._scrollable
                ui.parent       = self.ui

                if view.resizable or view.scrollable or ui._scrollable:
                    stretch = 1

            # FIXME: Handle stretch.
            layout.addComponent(control)

    #---------------------------------------------------------------------------
    #  Disposes of the contents of an editor:
    #---------------------------------------------------------------------------

    def dispose ( self ):
        """ Disposes of the contents of an editor.
        """
        # Make sure we aren't hanging on to any object refs:
        self._object_cache = None

        if self._ui is not None:
            self._ui.dispose()

        if self._choice is not None:
            if self._object is not None:
                self._object.on_trait_change( self.rebuild_items,
                                              self._name, remove = True )
                self._object.on_trait_change( self.rebuild_items,
                                 self._name + '_items', remove = True )

            self.factory.on_trait_change( self.rebuild_items, 'values',
                                          remove = True )
            self.factory.on_trait_change( self.rebuild_items,
                                          'values_items', remove = True )

        super( CustomEditor, self ).dispose()

    #---------------------------------------------------------------------------
    #  Handles an error that occurs while setting the object's trait value:
    #---------------------------------------------------------------------------

    def error ( self, excp ):
        """ Handles an error that occurs while setting the object's trait value.
        """
        pass

    #---------------------------------------------------------------------------
    #  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._choice or self.control)

    #-- UI preference save/restore interface -----------------------------------

    #---------------------------------------------------------------------------
    #  Restores any saved user preference information associated with the
    #  editor:
    #---------------------------------------------------------------------------

    def restore_prefs ( self, prefs ):
        """ Restores any saved user preference information associated with the
            editor.
        """
        ui = self._ui
        if (ui is not None) and (prefs.get( 'id' ) == ui.id):
            ui.set_prefs( prefs.get( 'prefs' ) )

    #---------------------------------------------------------------------------
    #  Returns any user preference information associated with the editor:
    #---------------------------------------------------------------------------

    def save_prefs ( self ):
        """ Returns any user preference information associated with the editor.
        """
        ui = self._ui
        if (ui is not None) and (ui.id != ''):
            return { 'id':    ui.id,
                     'prefs': ui.get_prefs() }

        return None

    #-- Traits event handlers --------------------------------------------------

    def _view_changed ( self, view ):
        self.resynch_editor()
Example #27
0
class MuntjacComboBox(MuntjacControl, AbstractTkComboBox):
    """ A Muntjac implementation of ComboBox.

    Use a combo box to select a single item from a collection of items.

    """
    #--------------------------------------------------------------------------
    # Setup methods
    #--------------------------------------------------------------------------
    def create(self, parent):
        """ Creates a QComboBox.

        """
        self.widget = ComboBox()
        self.widget.setImmediate(True)
        parent.addComponent(self.widget)

    def initialize(self):
        """ Intializes the widget with the attributes of this instance.

        """
        super(MuntjacComboBox, self).initialize()
        shell = self.shell_obj
        self.set_items(shell.labels)
        self.set_selection(shell.index)

    def bind(self):
        """ Connects the event handlers for the combo box.

        """
        super(MuntjacComboBox, self).bind()
        self.widget.currentIndexChanged.connect(self.on_selected)

    #--------------------------------------------------------------------------
    # Implementation
    #--------------------------------------------------------------------------
    def shell_index_changed(self, index):
        """ The change handler for the 'index' attribute on the shell
        object.

        """
        self.set_selection(index)

    def shell_labels_changed(self, labels):
        """ The change handler for the 'labels' attribute on the shell
        object.

        """
        self.set_items(labels)

    def on_selected(self):
        """ The event handler for a combo box selection event.

        """
        if not guard.guarded(self, 'updating'):
            shell = self.shell_obj
            curr_index = self._selected_index()
            shell.index = curr_index

            # Only fire the selected event if we have a valid selection
            if curr_index != -1:
                shell.selected = shell.value

    def set_items(self, str_items):
        """ Sets the items in the combo box.

        """
        # We need to avoid a feedback loop when updating the items in
        # the combo box. Qt will emit index changed signals when the
        # items are updated. But, the shell object has already computed
        # the proper index for the new items, so we use that to update
        # the index of the control after updating the items. The flag
        # is read by the on_selected handler to ignore updates during
        # this process.
        with guard(self, 'updating'):
            widget = self.widget
            widget.removeAllItems()
            for item in str_items:
                widget.addItem(item)
            ids = widget.getItemIds()
            widget.select(ids[self.shell_obj.index])

    def set_selection(self, index):
        """ Sets the value in the combo box, or resets the combo box
        if the value is not in the list of items.

        """
        # We need to avoid a feedback loop when updating the selection
        # in the combo box. Qt will emit index changed signals when the
        # selectino is updated. But, the shell object has already computed
        # the proper index for the new selection so we don't need to feed
        # back while doing this.
        with guard(self, 'updating'):
            ids = self.widget.getItemIds()
            self.widget.select(ids[index])

    #--------------------------------------------------------------------------
    # Helper Methods
    #--------------------------------------------------------------------------
    def _selected_index(self):
        widget = self.widget
        ids = widget.getItemIds()
        val = widget.getValue()
        if val in ids:
            curr_index = ids.index(val)
        else:
            curr_index = -1
        return curr_index
Example #28
0
    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        factory = self.factory
        if factory.name != '':
            self._object, self._name, self._value = \
                self.parse_extended_name( factory.name )

        # Create a panel to hold the object trait's view:
        if factory.editable:
            self.control = self._panel = parent = Panel()

        # Build the instance selector if needed:
        selectable = factory.selectable
        droppable  = factory.droppable
        items      = self.items
        for item in items:
            droppable  |= item.is_droppable()
            selectable |= item.is_selectable()

        if selectable:
            self._object_cache = {}
            item = self.item_for( self.value )
            if item is not None:
                self._object_cache[ id( item ) ] = self.value

            self._choice = ComboBox()
            self._choice.addCallback(self.update_object, ValueChangeEvent)

            self.set_tooltip( self._choice )

            if factory.name != '':
                self._object.on_trait_change( self.rebuild_items,
                                              self._name, dispatch = 'ui' )
                self._object.on_trait_change( self.rebuild_items,
                                 self._name + '_items', dispatch = 'ui' )

            factory.on_trait_change( self.rebuild_items, 'values',
                                     dispatch = 'ui' )
            factory.on_trait_change( self.rebuild_items, 'values_items',
                                     dispatch = 'ui' )

            self.rebuild_items()

        elif droppable:
            self._choice = TextField()
            self._choice.setReadOnly(True)
            self.set_tooltip( self._choice )

        if droppable:
            raise NotImplementedError
#            self._choice.SetDropTarget( PythonDropTarget( self ) )

        orientation = factory.orientation
        if orientation == 'default':
            orientation = self.orientation

        if (selectable or droppable) and factory.editable:
            if orientation == 'vertical':
                layout = VerticalLayout()
            else:
                layout = HorizontalLayout()
            layout.setSizeUndefined()
            parent.addComponent(layout)
#            layout.setParent(parent)
            layout.setMargin(False)
            layout.addComponent(self._choice)

            if orientation == 'vertical':
                hline = Label('<hr />', Label.CONTENT_XHTML)
                layout.addComponent(hline)  # FIXME: explicit parent size

            self.create_editor(parent, layout)
        elif self.control is None:
            if self._choice is None:
                self._choice = ComboBox()
                self._choice.addCallback(self.update_object, ValueChangeEvent)

            self.control = self._choice
        else:
            if orientation == 'vertical':
                layout = VerticalLayout()
            else:
                layout = HorizontalLayout()
            parent.addComponent(layout)
            layout.setMargin(False)
            layout.setSizeUndefined()
            self.create_editor(parent, layout)

        # Synchronize the 'view' to use:
        # fixme: A normal assignment can cause a crash (for unknown reasons) in
        # some cases, so we make sure that no notifications are generated:
        self.trait_setq( view = factory.view )
        self.sync_value( factory.view_name, 'view', 'from' )