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
class TextAreaExample(HorizontalLayout, IValueChangeListener): _initialText = 'The quick brown fox jumps over the lazy dog.' def __init__(self): super(TextAreaExample, self).__init__() self.setSpacing(True) self.setWidth('100%') self._editor = TextArea(None, self._initialText) self._editor.setRows(20) self._editor.setColumns(20) self._editor.addListener(self, IValueChangeListener) self._editor.setImmediate(True) self.addComponent(self._editor) # the TextArea is immediate, and it's valueCahnge updates the Label, # so this button actually does nothing self.addComponent(Button('>')) self._plainText = Label(self._initialText) self._plainText.setContentMode(Label.CONTENT_XHTML) self.addComponent(self._plainText) self.setExpandRatio(self._plainText, 1) # Catch the valuechange event of the textfield and update the value of the # label component def valueChange(self, event): text = self._editor.getValue() if text is not None: # replace newline with BR, because we're using Label.CONTENT_XHTML text = text.replace('\n', '<br/>') self._plainText.setValue(text)
class ReadonlyEditor ( Editor ): """ Base class for read-only style editors, which displays a read-only text field, containing a text representation of the object trait value. """ #--------------------------------------------------------------------------- # 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.control = Label() self.control.setImmediate(True) self.control.setValue( str(self.str_value) ) # if self.item.resizable is True or self.item.height != -1.0: # self.control.setSizePolicy(QtGui.QSizePolicy.Expanding, # QtGui.QSizePolicy.Expanding) # self.control.setWordWrap(True) self.set_tooltip() #--------------------------------------------------------------------------- # 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. """ self.control.setValue( str(self.str_value) )
class LabelRichExample(VerticalLayout, IClickListener): def __init__(self): super(LabelRichExample, self).__init__() self.setSpacing(True) self._editor = RichTextArea() self._richText = Label('<h1>Rich text example</h1>' '<p>The <b>quick</b> brown fox jumps <sup>over</sup> ' 'the <b>lazy</b> dog.</p>' '<p>This text can be edited with the <i>Edit</i> -button</p>') self._richText.setContentMode(Label.CONTENT_XHTML) self.addComponent(self._richText) self._b = Button('Edit') self._b.addListener(self, IClickListener) self.addComponent(self._b) self._editor.setWidth('100%') def buttonClick(self, event): if self.getComponentIterator().next() == self._richText: self._editor.setValue(self._richText.getValue()) self.replaceComponent(self._richText, self._editor) self._b.setCaption('Apply') else: self._richText.setValue(self._editor.getValue()) self.replaceComponent(self._editor, self._richText) self._b.setCaption('Edit')
class LabelRichExample(VerticalLayout, IClickListener): def __init__(self): super(LabelRichExample, self).__init__() self.setSpacing(True) self._editor = RichTextArea() self._richText = Label( '<h1>Rich text example</h1>' '<p>The <b>quick</b> brown fox jumps <sup>over</sup> ' 'the <b>lazy</b> dog.</p>' '<p>This text can be edited with the <i>Edit</i> -button</p>') self._richText.setContentMode(Label.CONTENT_XHTML) self.addComponent(self._richText) self._b = Button('Edit') self._b.addListener(self, IClickListener) self.addComponent(self._b) self._editor.setWidth('100%') def buttonClick(self, event): if self.getComponentIterator().next() == self._richText: self._editor.setValue(self._richText.getValue()) self.replaceComponent(self._richText, self._editor) self._b.setCaption('Apply') else: self._richText.setValue(self._editor.getValue()) self.replaceComponent(self._editor, self._richText) self._b.setCaption('Edit')
class Calc2(Application, IClickListener): """A simple calculator using Muntjac.""" def __init__(self): super(Calc2, self).__init__() # All variables are automatically stored in the session. self._current = 0.0 self._stored = 0.0 self._lastOperationRequested = 'C' self.pure_calc = PureCalc() # User interface components self._display = Label('0.0') def init(self): layout = GridLayout(4, 5) self.setMainWindow(Window('Calculator Application', layout)) layout.addComponent(self._display, 0, 0, 3, 0) operations = ['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '=', 'C', '+'] for caption in operations: # Create a button and use this application for event handling button = Button(caption) button.addListener(self) # Add the button to our main layout layout.addComponent(button) def buttonClick(self, event): # Event handler for button clicks. Called for all the buttons in # the application. # Get the button that was clicked button = event.getButton() # Get the requested operation from the button caption requestedOperation = button.getCaption()[0] self.pure_calc.proc_char(requestedOperation) if self.pure_calc.digit_operation(requestedOperation): newValue = self.pure_calc._current else: newValue = self.pure_calc._stored # Update the result label with the new value self._display.setValue(newValue)
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)
class MuntjacLabel(MuntjacControl, AbstractTkLabel): """ A Muntjac implementation of Label. """ #-------------------------------------------------------------------------- # Setup methods #-------------------------------------------------------------------------- def create(self, parent): """ Creates the underlying Label control. """ self.widget = Label() parent.addComponent(self.widget) def initialize(self): """ Initializes the attributes on the underlying control. """ super(MuntjacLabel, self).initialize() self.set_label(self.shell_obj.text) #-------------------------------------------------------------------------- # Implementation #-------------------------------------------------------------------------- def shell_text_changed(self, text): """ The change handler for the 'text' attribute. """ self.set_label(text) # If the text in the label changes, then the size hint of # label will have changed, and the layout system needs to # be informed. self.shell_obj.size_hint_updated = True def set_label(self, label): """ Sets the label on the underlying control. """ self.widget.setValue(label)
class MuntjacLabel(MuntjacControl, AbstractTkLabel): """ A Muntjac implementation of Label. """ #-------------------------------------------------------------------------- # Setup methods #-------------------------------------------------------------------------- def create(self, parent): """ Creates the underlying Label control. """ self.widget = Label() parent.addComponent(self.widget) def initialize(self): """ Initializes the attributes on the underlying control. """ super(MuntjacLabel, self).initialize() self.set_label(self.shell_obj.text) #-------------------------------------------------------------------------- # Implementation #-------------------------------------------------------------------------- def shell_text_changed(self, text): """ The change handler for the 'text' attribute. """ self.set_label(text) # If the text in the label changes, then the size hint of # label will have changed, and the layout system needs to # be informed. self.shell_obj.size_hint_updated = True def set_label(self, label): """ Sets the label on the underlying control. """ self.widget.setValue(label)
class MuntjacHtml(MuntjacControl, AbstractTkHtml): """ A Muntjac implementation of Html. """ #-------------------------------------------------------------------------- # Setup methods #-------------------------------------------------------------------------- def create(self, parent): """ Creates the underlying widget to display HTML. """ self.widget = Label() self.widget.setContentMode(Label.CONTENT_XHTML) parent.addComponent(self.widget) def initialize(self): """ Initializes the attributes of the control. """ super(MuntjacHtml, self).initialize() self.set_page_source(self.shell_obj.source) #-------------------------------------------------------------------------- # Implementation #-------------------------------------------------------------------------- def shell_source_changed(self, source): """ The change handler for the 'source' attribute. """ self.set_page_source(source) def set_page_source(self, source): """ Sets the page source for the underlying control. """ self.widget.setValue(source)
def setFeatureContainer(self, c): self._grid.removeAllComponents() features = c.getItemIds() rootSet = CssLayout() rootTitle = None highlightRow = CssLayout() highlightRow.setStyleName('highlight-row') sampleCount = 0 for f in features: if isinstance(f, FeatureSet): if c.isRoot(f): if rootTitle is not None: rootTitle.setValue(('<em>' + str(sampleCount) + ' samples</em>' + rootTitle.getValue())) sampleCount = 0 desc = f.getDescription() try: idx = desc.index(".") except ValueError: idx = -1 rootTitle = Label("<h2>" + f.getName() + "</h2><span>" + desc[:idx + 1] + "</span>", Label.CONTENT_XHTML) rootTitle.setSizeUndefined() if f.getRelatedFeatures() is not None: rootTitle.setValue('<em>' + len(f.getRelatedFeatures()) + ' samples</em>' + rootTitle.getValue()) rootSet = CssLayout() rootSet.setStyleName('root') rootTitle.setStyleName('root-section') self._grid.addComponent(rootTitle) self._grid.addComponent(rootSet) else: sampleCount += 1 resId = '75-' + f.getIconName() res = self._app.getSampleIcon(resId) if rootSet.getParent() is None: # This sample is directly inside a non root feature # set, we present these with higher priority if rootTitle is None: parent = self._app._allFeatures.getParent(f) rootTitle = Label("<h2>" + parent.getName() + "</h2>", Label.CONTENT_XHTML) rootTitle.setStyleName('root-section highlights-title') rootTitle.setSizeUndefined() self._grid.addComponent(rootTitle) if parent.getDescription() is not None: desc = Label(parent.getDescription(), Label.CONTENT_XHTML) desc.setStyleName('highlights-description') desc.setSizeUndefined() self._grid.addComponent(desc) # Two samples per row if sampleCount % 2 == 1: highlightRow = CssLayout() highlightRow.setStyleName('highlight-row') self._grid.addComponent(highlightRow) l = CssLayout() l.setStyleName('highlight') er = ExternalResource('#' + f.getFragmentName()) sample = ActiveLink(f.getName(), er) sample.setIcon(res) # if f.getSinceVersion().isNew(): # sample.addStyleName('new') l.addComponent(sample) if (f.getDescription() is not None and f.getDescription() != ''): d = f.getDescription() desc = Label(d[:d.index(".") + 1], Label.CONTENT_XHTML) desc.setSizeUndefined() l.addComponent(desc) highlightRow.addComponent(l) else: sample = ActiveLink(f.getName(), ExternalResource('#' + f.getFragmentName())) sample.setStyleName(BaseTheme.BUTTON_LINK) sample.addStyleName('screenshot') if (f.getDescription() is not None and f.getDescription() != ''): desc = f.getDescription() try: idx = desc.index('.') except ValueError: idx = -1 sample.setDescription(desc[:idx + 1]) # if f.getSinceVersion().isNew(): # sample.addStyleName('new') sample.setIcon(res) rootSet.addComponent(sample) if rootTitle is not None: rootTitle.setValue('<em>' + str(sampleCount) + ' samples</em>' + rootTitle.getValue())
class UploadWithProgressMonitoringExample(VerticalLayout): def __init__(self): super(UploadWithProgressMonitoringExample, self).__init__() self.setSpacing(True) self._state = Label() self._result = Label() self._fileName = Label() self._textualProgress = Label() self._pi = ProgressIndicator() self._counter = LineBreakCounter() self._upload = Upload(None, self._counter) self.addComponent(Label('Upload a file and we\'ll count the number ' 'of line break characters (\\n) found in it.')) # make analyzing start immediatedly when file is selected self._upload.setImmediate(True) self._upload.setButtonCaption('Upload File') self.addComponent(self._upload) handBrake = CheckBox('Simulate slow server') handBrake.setValue(True) self._counter.setSlow(True) handBrake.setDescription('Sleep for 100ms after each kilobyte to ' 'simulate slower processing/bandwidth. This is to show ' 'progress indicator even with rather small files.') handBrake.addListener(HandBrakeListener(self), button.IClickListener) cancelProcessing = Button('Cancel') cancelProcessing.addListener(CancelListener(self), button.IClickListener) cancelProcessing.setVisible(False) cancelProcessing.setStyleName('small') handBrake.setImmediate(True) self.addComponent(handBrake) p = Panel('Status') p.setSizeUndefined() l = FormLayout() l.setMargin(True) p.setContent(l) stateLayout = HorizontalLayout() stateLayout.setSpacing(True) stateLayout.addComponent(self._state) stateLayout.addComponent(cancelProcessing) stateLayout.setCaption('Current state') self._state.setValue('Idle') l.addComponent(stateLayout) self._fileName.setCaption('File name') l.addComponent(self._fileName) self._result.setCaption('Line breaks counted') l.addComponent(self._result) self._pi.setCaption('Progress') self._pi.setVisible(False) l.addComponent(self._pi) self._textualProgress.setVisible(False) l.addComponent(self._textualProgress) self.addComponent(p) self._upload.addListener(StartedListener(self), upload.IStartedListener) self._upload.addListener(ProgressListener(self), upload.IProgressListener) self._upload.addListener(SucceededListener(self), upload.ISucceededListener) self._upload.addListener(FailedListener(self), upload.IFailedListener) self._upload.addListener(FinishedListener(self), upload.IFinishedListener)
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
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
class Calc(Application, IClickListener): """A simple calculator using Muntjac.""" def __init__(self): super(Calc, self).__init__() # All variables are automatically stored in the session. self._current = 0.0 self._stored = 0.0 self._lastOperationRequested = 'C' # User interface components self._display = Label('0.0') def init(self): # Application.init is called once for each application. Here it # creates the UI and connects it to the business logic. # Create the main layout for our application (4 columns, 5 rows) layout = GridLayout(4, 5) # Create the main window for the application using the main layout. # The main window is shown when the application is starts. self.setMainWindow(Window('Calculator Application', layout)) # Create a result label that over all 4 columns in the first row layout.addComponent(self._display, 0, 0, 3, 0) # The operations for the calculator in the order they appear on the # screen (left to right, top to bottom) operations = ['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '=', 'C', '+'] for caption in operations: # Create a button and use this application for event handling button = Button(caption) button.addListener(self) # Add the button to our main layout layout.addComponent(button) def buttonClick(self, event): # Event handler for button clicks. Called for all the buttons in # the application. # Get the button that was clicked button = event.getButton() # Get the requested operation from the button caption requestedOperation = button.getCaption()[0] # Calculate the new value newValue = self.calculate(requestedOperation) # Update the result label with the new value self._display.setValue(newValue) def calculate(self, requestedOperation): # Calculator "business logic" implemented here to keep the example # minimal if '0' <= requestedOperation and requestedOperation <= '9': self._current = ((self._current * 10) + float('' + requestedOperation)) return self._current last = self._lastOperationRequested if last == '+': self._stored += self._current elif last == '-': self._stored -= self._current elif last == '/': try: self._stored /= self._current except ZeroDivisionError: pass elif last == '*': self._stored *= self._current elif last == 'C': self._stored = self._current self._lastOperationRequested = requestedOperation self._current = 0.0 if requestedOperation == 'C': self._stored = 0.0 return self._stored
def setFeatureContainer(self, c): self._grid.removeAllComponents() features = c.getItemIds() rootSet = CssLayout() rootTitle = None highlightRow = CssLayout() highlightRow.setStyleName('highlight-row') sampleCount = 0 for f in features: if isinstance(f, FeatureSet): if c.isRoot(f): if rootTitle is not None: rootTitle.setValue( ('<em>' + str(sampleCount) + ' samples</em>' + rootTitle.getValue())) sampleCount = 0 desc = f.getDescription() try: idx = desc.index(".") except ValueError: idx = -1 rootTitle = Label( "<h2>" + f.getName() + "</h2><span>" + desc[:idx + 1] + "</span>", Label.CONTENT_XHTML) rootTitle.setSizeUndefined() if f.getRelatedFeatures() is not None: rootTitle.setValue('<em>' + len(f.getRelatedFeatures()) + ' samples</em>' + rootTitle.getValue()) rootSet = CssLayout() rootSet.setStyleName('root') rootTitle.setStyleName('root-section') self._grid.addComponent(rootTitle) self._grid.addComponent(rootSet) else: sampleCount += 1 resId = '75-' + f.getIconName() res = self._app.getSampleIcon(resId) if rootSet.getParent() is None: # This sample is directly inside a non root feature # set, we present these with higher priority if rootTitle is None: parent = self._app._allFeatures.getParent(f) rootTitle = Label("<h2>" + parent.getName() + "</h2>", Label.CONTENT_XHTML) rootTitle.setStyleName('root-section highlights-title') rootTitle.setSizeUndefined() self._grid.addComponent(rootTitle) if parent.getDescription() is not None: desc = Label(parent.getDescription(), Label.CONTENT_XHTML) desc.setStyleName('highlights-description') desc.setSizeUndefined() self._grid.addComponent(desc) # Two samples per row if sampleCount % 2 == 1: highlightRow = CssLayout() highlightRow.setStyleName('highlight-row') self._grid.addComponent(highlightRow) l = CssLayout() l.setStyleName('highlight') er = ExternalResource('#' + f.getFragmentName()) sample = ActiveLink(f.getName(), er) sample.setIcon(res) # if f.getSinceVersion().isNew(): # sample.addStyleName('new') l.addComponent(sample) if (f.getDescription() is not None and f.getDescription() != ''): d = f.getDescription() desc = Label(d[:d.index(".") + 1], Label.CONTENT_XHTML) desc.setSizeUndefined() l.addComponent(desc) highlightRow.addComponent(l) else: sample = ActiveLink( f.getName(), ExternalResource('#' + f.getFragmentName())) sample.setStyleName(BaseTheme.BUTTON_LINK) sample.addStyleName('screenshot') if (f.getDescription() is not None and f.getDescription() != ''): desc = f.getDescription() try: idx = desc.index('.') except ValueError: idx = -1 sample.setDescription(desc[:idx + 1]) # if f.getSinceVersion().isNew(): # sample.addStyleName('new') sample.setIcon(res) rootSet.addComponent(sample) if rootTitle is not None: rootTitle.setValue('<em>' + str(sampleCount) + ' samples</em>' + rootTitle.getValue())
class UploadWithProgressMonitoringExample(VerticalLayout): def __init__(self): super(UploadWithProgressMonitoringExample, self).__init__() self.setSpacing(True) self._state = Label() self._result = Label() self._fileName = Label() self._textualProgress = Label() self._pi = ProgressIndicator() self._counter = LineBreakCounter() self._upload = Upload(None, self._counter) self.addComponent( Label('Upload a file and we\'ll count the number ' 'of line break characters (\\n) found in it.')) # make analyzing start immediatedly when file is selected self._upload.setImmediate(True) self._upload.setButtonCaption('Upload File') self.addComponent(self._upload) handBrake = CheckBox('Simulate slow server') handBrake.setValue(True) self._counter.setSlow(True) handBrake.setDescription( 'Sleep for 100ms after each kilobyte to ' 'simulate slower processing/bandwidth. This is to show ' 'progress indicator even with rather small files.') handBrake.addListener(HandBrakeListener(self), button.IClickListener) cancelProcessing = Button('Cancel') cancelProcessing.addListener(CancelListener(self), button.IClickListener) cancelProcessing.setVisible(False) cancelProcessing.setStyleName('small') handBrake.setImmediate(True) self.addComponent(handBrake) p = Panel('Status') p.setSizeUndefined() l = FormLayout() l.setMargin(True) p.setContent(l) stateLayout = HorizontalLayout() stateLayout.setSpacing(True) stateLayout.addComponent(self._state) stateLayout.addComponent(cancelProcessing) stateLayout.setCaption('Current state') self._state.setValue('Idle') l.addComponent(stateLayout) self._fileName.setCaption('File name') l.addComponent(self._fileName) self._result.setCaption('Line breaks counted') l.addComponent(self._result) self._pi.setCaption('Progress') self._pi.setVisible(False) l.addComponent(self._pi) self._textualProgress.setVisible(False) l.addComponent(self._textualProgress) self.addComponent(p) self._upload.addListener(StartedListener(self), upload.IStartedListener) self._upload.addListener(ProgressListener(self), upload.IProgressListener) self._upload.addListener(SucceededListener(self), upload.ISucceededListener) self._upload.addListener(FailedListener(self), upload.IFailedListener) self._upload.addListener(FinishedListener(self), upload.IFinishedListener)
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