class BlankParagraphEditor (AbstractViewSchema.NodeAbstractView): def __init__(self, worksheet, blockEditor): super( BlankParagraphEditor, self ).__init__( worksheet, None ) self._style = 'normal' paraAttrs = RichTextAttributes.fromValues({ 'style' : self._style }, None) self._editorModel = WSEditor.RichTextController.WorksheetRichTextController.instance.editorModelParagraph( None, [ '' ], paraAttrs ) self._incr = IncrementalValueMonitor() self._blockEditor = blockEditor def getText(self): self._incr.onAccess() return '' def setContents(self, contents): self._editorModel.setModelContents( WSEditor.RichTextController.WorksheetRichTextController.instance, contents ) if len( contents ) == 0: return elif len( contents ) == 1 and contents[0] == '': return p = ParagraphEditor.newParagraph( contents, self._style ) self._blockEditor.appendEditorNode( p ) def getStyle(self): self._incr.onAccess() return self._style def setStyle(self, style): self._style = style self._incr.onChanged() def _refreshResults(self, module): pass
class InlinePythonCodeAbstractView(NodeAbstractView): STYLE_MINIMAL_RESULT = 0 STYLE_RESULT = 1 STYLE_CODE_AND_RESULT = 2 STYLE_EDITABLE_CODE_AND_RESULT = 3 _styleToName = { STYLE_MINIMAL_RESULT: 'minimal_result', STYLE_RESULT: 'result', STYLE_CODE_AND_RESULT: 'code_result', STYLE_EDITABLE_CODE_AND_RESULT: 'editable_code_result' } _nameToStyle = { 'minimal_result': STYLE_MINIMAL_RESULT, 'result': STYLE_RESULT, 'code_result': STYLE_CODE_AND_RESULT, 'editable_code_result': STYLE_EDITABLE_CODE_AND_RESULT } def __init__(self, worksheet, model): NodeAbstractView.__init__(self, worksheet, model) self._incr = IncrementalValueMonitor(self) self._result = None def getExpr(self): return self._model['expr'] def getStyle(self): name = self._model['style'] try: return self._nameToStyle[name] except KeyError: return self.STYLE_CODE_AND_RESULT def isCodeVisible(self): style = self.getStyle() return style == self.STYLE_CODE_AND_RESULT or style == self.STYLE_EDITABLE_CODE_AND_RESULT def isCodeEditable(self): style = self.getStyle() return style == self.STYLE_EDITABLE_CODE_AND_RESULT def isResultMinimal(self): style = self.getStyle() return style == self.STYLE_MINIMAL_RESULT def getResult(self): self._incr.onAccess() return self._result def _refreshResults(self, module): self._result = Execution.getResultOfEvaluationWithinModule( self.getExpr(), module) self._incr.onChanged()
class EmbeddedDisplay(object): def __init__(self): self._expr = EmbeddedPython2Expr() self._code = None self._values = [] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return {'expr': self._expr} def __setstate__(self, state): self._expr = state['expr'] self._code = None self._values = [] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return [self._expr] def __py_compile_visit__(self, codeGen): self._code = codeGen.compileForEvaluation(self._expr.model) def __py_eval__(self, _globals, _locals, codeGen): value = eval(self._code, _globals, _locals) self._values.append(value) self._incr.onChanged() return value def __py_replacement__(self): return deepcopy(self._expr.model['expr']) def __present__(self, fragment, inheritedState): def _embeddedDisplayMenu(element, menu): def _onClear(item): del self._values[:] self._incr.onChanged() menu.add( MenuItem.menuItemWithLabel('Clear collected values', _onClear)) return False self._incr.onAccess() #exprPres = pyPerspective.applyTo( self._expr ) exprPres = self._expr valuesPres = ObjectBox( 'Values', Column([Paragraph([value]) for value in self._values])) contents = Column([exprPres, valuesPres]) return ObjectBox( 'Embedded display', contents).withContextMenuInteractor(_embeddedDisplayMenu)
class _TreeView (object): def __init__(self): self._incr = IncrementalValueMonitor() self.initialise() def __getstate__(self): return { None : None } def __setstate__(self, state): self._incr = IncrementalValueMonitor() self.initialise() def initialise(self): self._incr.onChanged() self._rootFrames = [] self._currentFrame = None def begin(self): self._incr.onChanged() # Open a new frame prevFrame = self._currentFrame self._currentFrame = _Frame() if prevFrame is not None: prevFrame.childFrames.append( self._currentFrame ) else: self._rootFrames.append( self._currentFrame ) return prevFrame def end(self, state): prevFrame = state self._currentFrame = prevFrame def logValue(self, monitoredExpression, value): self._incr.onChanged() if self._currentFrame is not None: self._currentFrame.values.logValue( monitoredExpression, value ) def __present__(self, fragment, inheritedState): self._incr.onAccess() valuesLive = LiveValue( Blank() ) tree = Column( [ x._presentFrameSubtree( valuesLive ) for x in self._rootFrames ] ) return Column( [ tree, Spacer( 0.0, 10.0 ), valuesLive ] )
class _TableView (object): def __init__(self): self._incr = IncrementalValueMonitor() self._schema = None self._tableEditor = None self._tableContent = None self._tableRow = None self._numTableRows = None def initialise(self, schema): self._schema = schema self._tableEditor = GenericTableEditor( [ v._name for v in schema._monitoredExpressions ], True, True, False, False ) self._tableContent = GenericTableModel( lambda: '', lambda x: x ) self._tableRow = None self._numTableRows = None def __getstate__(self): return { None : None } def __setstate__(self, state): self._incr = IncrementalValueMonitor() self._schema = None self._tableEditor = None self._tableContent = None self._tableRow = None self._numTableRows = None def begin(self): state = self._tableRow self._numTableRows = self._numTableRows + 1 if self._numTableRows is not None else 0 self._tableRow = self._numTableRows return state def end(self, state): self._tableRow = state self._incr.onChanged() def logValue(self, monitoredExpression, value): index = self._schema._monitoredExpressionToindex[monitoredExpression] self._tableContent.set( index, self._tableRow, value ) def __present__(self, fragment, inheritedState): self._incr.onAccess() return self._tableEditor.editTable( self._tableContent ) if self._tableEditor is not None else Blank()
class ConstantDefinition(object): def __init__(self): self._target = EmbeddedPython2Target() self._value = EmbeddedPython2Expr() self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return {'target': self._target, 'value': self._value} def __setstate__(self, state): self._target = state['target'] self._value = state['value'] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return [self.target, self.value] def __copy__(self): d = ConstantDefinition() d.target = self.target d.value = self.value return d def __deepcopy__(self, memo): d = ConstantDefinition() d.target = deepcopy(self.target, memo) d.value = deepcopy(self.value, memo) return d def _getTarget(self): self._incr.onAccess() return self._target def _setTarget(self, target): self._target = deepcopy(target) self._incr.onChanged() def _getValue(self): self._incr.onAccess() return self._value def _setValue(self, value): self._value = deepcopy(value) self._incr.onChanged() target = property(_getTarget, _setTarget) value = property(_getValue, _setValue)
class _TempBlankPara(elem.MRTElem): def __init__(self, projection_table, block): super(_TempBlankPara, self).__init__(projection_table, None) self._block = block self._style = 'normal' self._incr = IncrementalValueMonitor() para_attrs = RichTextAttributes.fromValues({'style': self._style}, None) self._editorModel = controller.MallardRichTextController.instance.editorModelParagraph( [], para_attrs) def setContents(self, contents): if len(contents) == 0: return elif len(contents) == 1 and contents[0] == '': return p = Para.new_p(self._projection_table, contents) self._block.append(p) def getContents(self): self._incr.onAccess() return [] def setStyle(self, style): self._style = style self._incr.onChanged() _styleMap = { 'normal': NormalText, 'h1': Heading1, 'h2': Heading2, 'h3': Heading3, 'h4': Heading4, 'h5': Heading5, 'h6': Heading6, 'title': Title } def __present__(self, fragment, inheritedState): self._incr.onAccess() x = NormalText('') x = controller.MallardRichTextController.instance.editableParagraph( self, x) return x def __repr__(self): return '<blank_para'
class ConsoleBlock (object): def __init__(self, pythonModule, execResult): self._incr = IncrementalValueMonitor( self ) self._pythonModule = pythonModule self._execResult = execResult def getPythonModule(self): self._incr.onAccess() return self._pythonModule def getExecResult(self): self._incr.onAccess() return self._execResult def __present__(self, fragment, inheritedState): pythonModule = self.getPythonModule() executionResult = self.getExecResult() caughtException = executionResult.getCaughtException() result = executionResult.getResult() streams = executionResult.getStreams() moduleView = StyleSheet.style( Primitive.editable( False ) ).applyTo( Python2.python2EditorPerspective.applyTo( pythonModule ) ) caughtExceptionView = ApplyPerspective.defaultPerspective( caughtException ) if caughtException is not None else None resultView = ApplyPerspective.defaultPerspective( result[0] ) if result is not None else None code = _pythonModuleBorderStyle.applyTo( Border( moduleView.alignHExpand() ).alignHExpand() ) outputContents = [] for stream in streams: if stream.name == 'out': outputContents.append( execStdout( stream.richString, True ) ) elif stream.name == 'err': outputContents.append( execStderr( stream.richString, True ) ) else: raise ValueError, 'Unreckognised stream \'{0}\''.format( stream.name ) if caughtExceptionView is not None: outputContents.append( execException( caughtExceptionView ) ) if resultView is not None: outputContents.append( execResult( resultView ) ) outputColumn = _blockOutputStyle.applyTo( Column( outputContents ).alignHExpand() ) return _blockStyle.applyTo( Border( Column( [ code, outputColumn ] ) ) ).alignHExpand()
class LiterateExpression(object): def __init__(self, expr=None): if expr is None: expr = EmbeddedPython2Expr() self._expr = expr self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return {'expr': self._expr} def __setstate__(self, state): self._expr = state['expr'] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return [self._expr] def __py_evalmodel__(self, codeGen): return self._expr.model def __py_replacement__(self): return deepcopy(self._expr.model['expr']) def _new_reference(self): return LiterateExpression(self._expr) def __present__(self, fragment, inheritedState): self._incr.onAccess() exprPres = self._expr header = Row([ self._angleQuoteStyle(Label(u'\u00ab')), self._angleQuoteStyle(Label(u'\u00bb')), Spacer(9.0, 0.0) ]).withDragSource(_dragSource) return ObjectBorder(Row([header.alignVCentre(), exprPres])) _angleQuoteStyle = StyleSheet.style( Primitive.foreground(Color(0.15, 0.15, 0.45)), Primitive.fontBold(True), Primitive.fontSize(12))
class MRTAbstractText(elem.MRTElem): contents_query = None # Abstract def __init__(self, projection_table, elem, contents=None): super(MRTAbstractText, self).__init__(projection_table, elem) self.contents_query.change_listener = self._on_changed self._editorModel = None self._incr = IncrementalValueMonitor() if contents is not None: self.setContents(contents) def _on_changed(self): self._editorModel.setModelContents( controller.MallardRichTextController.instance, self.contents_query) self._incr.onChanged() def setContents(self, contents): self.contents_query = contents def getContents(self): self._incr.onAccess() return self.contents_query[:]
class ConstantTable(object): def __init__(self): self._definitions_ = [] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return {'definitions': self._definitions_} def __setstate__(self, state): self._definitions_ = state['definitions'] self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return self._definitions.__get_trackable_contents__() def __len__(self): self._incr.onAccess() return len(self._definitions) def __iter__(self): self._incr.onAccess() return iter(self._definitions) def __getitem__(self, i): self._incr.onAccess() return self._definitions[i] def __setitem__(self, i, x): self._definitions[i] = x self._incr.onChanged() def __delitem__(self, i): del self._definitions[i] self._incr.onChanged() def append(self, x): self._definitions.append(x) self._incr.onChanged() def __py_execmodel__(self, codeGen): assigns = [] for definition in self._definitions_: target = definition.target.model['target'] value = definition.value.model['expr'] assign = Py.AssignStmt(targets=[target], value=value) assigns.append(assign) return Py.PythonSuite(suite=assigns) __py_hide_expansion__ = True def __present__(self, fragment, inheritedState): return _tableEditor.editTable(self) @TrackedListProperty def _definitions(self): return self._definitions_
class Block(elem.MRTElem): contents_query = elem_query.children(['p', 'section', 'note']).project_to_objects( mappings.block_contents_mapping) def __init__(self, projection_table, elem, contents=None): super(Block, self).__init__(projection_table, elem) self.contents_query.change_listener = self._on_changed self._editorModel = controller.MallardRichTextController.instance.editorModelBlock( []) self._incr = IncrementalValueMonitor() if contents is not None: self.setContents(contents) def node_init(self): self._editorModel.setModelContents( controller.MallardRichTextController.instance, list(self.contents_query)) def _filterContents(self, xs): return [x for x in xs if not isinstance(x, para._TempBlankPara)] def _on_changed(self): self._editorModel.setModelContents( controller.MallardRichTextController.instance, list(self.contents_query)) self._incr.onChanged() def setContents(self, contents): self.contents_query = self._filterContents(list(contents)) def append(self, para): self.contents_query.append(para) def insertAfter(self, para, p): index = -1 for (i, x) in enumerate(self.contents_query): if p is x: index = i self.contents_query.insert(index + 1, para) def removeParagraph(self, para): index = -1 for (i, x) in enumerate(self.contents_query): if para is x: index = i if index != -1: del self.contents_query[index] else: raise ValueError, 'could not find para' def __present__(self, fragment, inheritedState): self._incr.onAccess() contents = self.contents_query xs = list(contents) if len(contents) > 0 else [ para._TempBlankPara(self._projection_table, self) ] #xs = self._contents + [_TempBlankPara( self )] x = Body(xs) x = controller.MallardRichTextController.instance.editableBlock( self, x) return x
class LiterateSuite(object): def __init__(self, definition=None, expanded=True): if definition is None: definition = LiterateSuiteDefinition() self._definition = definition self._expanded = expanded self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return {'definition': self._definition, 'expanded': self._expanded} def __setstate__(self, state): self._definition = state.get('definition') self._expanded = state.get('expanded', True) if self._definition is None: self._definition = LiterateSuiteDefinition() self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return [self._definition] def __py_execmodel__(self, codeGen): return self._definition._suite.model def __py_replacement__(self): return deepcopy(self._definition._suite.model['suite']) def _new_reference(self): return LiterateSuite(self._definition) def getName(self): return self._definition.getName() def setName(self, name): self._definition.setName(name) def isExpanded(self): return self._expanded def setExpanded(self, expanded): oldExpanded = self._expanded self._expanded = expanded self._incr.onChanged() if self.__change_history__ is not None: self.__change_history__.addChange( lambda: self.setExpanded(expanded), lambda: self.setExpanded(oldExpanded), 'Literate suite set expanded') def __present__(self, fragment, inheritedState): def _literateExpressionMenu(element, menu): def _onToggleExpanded(item): self.setExpanded(not self._expanded) menuItemName = 'Start as contracted' if self._expanded else 'Start as expanded' menu.add( MenuItem.menuItemWithLabel(menuItemName, _onToggleExpanded)) return False self._incr.onAccess() self._definition._incr.onAccess() suitePres = self._definition._suite nameLabel = self._nameStyle(Label(self._definition._name)) liveName = LiveValue(nameLabel) class _NameEntryListener(TextEntry.TextEntryListener): def onAccept(listener, textEntry, text): self.setName(text) def onCancel(listener, textEntry, orignalText): liveName.setLiteralValue(nameLabel) def _onNameButton(button, event): nameEntry = TextEntry(self._definition._name, _NameEntryListener()) nameEntry.grabCaretOnRealise() nameEntry = self._nameStyle(nameEntry) liveName.setLiteralValue(nameEntry) renameButton = self._nameButtonStyle( Button.buttonWithLabel('...', _onNameButton)) header = Row([ self._angleQuoteStyle(Label(u'\u00ab')), liveName, self._angleQuoteStyle(Label(u'\u00bb')), Spacer(10.0, 0.0), renameButton ]).withDragSource(_dragSource) dropDown = self._dropDownStyle( DropDownExpander(header, suitePres, self._expanded, None)) return ObjectBorder(dropDown).withContextMenuInteractor( _literateExpressionMenu) _nameStyle = StyleSheet.style( Primitive.foreground(Color(0.15, 0.15, 0.45)), Primitive.fontSize(12)) _nameButtonStyle = StyleSheet.style(Primitive.fontSize(10)) _angleQuoteStyle = StyleSheet.style( Primitive.foreground(Color(0.15, 0.15, 0.45)), Primitive.fontBold(True), Primitive.fontSize(12)) _dropDownStyle = StyleSheet.style( Controls.dropDownExpanderHeaderArrowSize(10.0), Controls.dropDownExpanderPadding(12.0))
class StandardInlineTest (AbstractInlineTest): def __init__(self, name='test'): super( StandardInlineTest, self ).__init__() self._name = TrackedLiveValue( name ) self._suite = EmbeddedPython2Suite() self.__change_history__ = None self.__passes = None self.__failures = None self._incr = IncrementalValueMonitor() def __getstate__(self): state = super( StandardInlineTest, self ).__getstate__() state['name'] = self._name.getStaticValue() state['suite'] = self._suite return state def __setstate__(self, state): super( StandardInlineTest, self ).__setstate__( state ) self._name = TrackedLiveValue( state['name'] ) self._suite = state['suite'] self.__change_history__ = None self.__passes = None self.__failures = None self._incr = IncrementalValueMonitor() def __get_trackable_contents__(self): return [ self._name, self._suite ] def reset(self): super( StandardInlineTest, self ).reset() self.__passes = None self.__failures = None self._incr.onChanged() def _runTestsOnInstance(self, instance): self.__passes = 0 self.__failures = [] for name in self._testClass.__dict__: if name.startswith( 'test' ): # Run this test method try: getattr( instance, name )() except Exception: caughtException = JythonException.getCurrentException() self.__failures.append( (name, caughtException) ) else: self.__passes += 1 self._incr.onChanged() @property def _desiredClassName(self): return 'Test_' + self._name.getValue() def _createTestClassBodyStmts(self, codeGen, testedBlock): return self._suite.model['suite'] __embed_hide_frame__ = True def __present__(self, fragment, inheritedState): self._incr.onAccess() title = SectionHeading2( 'Unit tests' ) nameEntry = _nameBorder.surround( EditableLabel( self._name, _notSet ).regexValidated( Tokens.identifierPattern, 'Please enter a valid identifier' ) ) header = Row( [ title, Spacer( 25.0, 0.0 ), nameEntry ] ) contents = [ header.padY( 0.0, 5.0 ), _standardCodeBorder.surround( self._suite ).padY( 3.0 ).alignHExpand() ] if self.__passes is not None and self.__failures is not None: resultsTitle = SectionHeading3( 'Test results:' ) passes = _standardPassStyle( Label( '%d / %d test(s) passed' % ( self.__passes, self.__passes + len( self.__failures ) ) ) ) failuresLabel = _standardFailStyle( Label( '%d test(s) failed:' % len( self.__failures ) ) ) failures = [ Column( [ _standardFailedTestStyle( Label( name ) ), Pres.coerce( exception ).padX( 5.0, 0.0 ) ] ).padX( 5.0, 0.0 ) for name, exception in self.__failures ] results = _standardResultsBorder.surround( Column( [ resultsTitle, passes, failuresLabel ] + failures ) ).pad( 3.0, 3.0 ) contents.append( results ) return _standardInlineTestBorder.surround( Column( contents ) )
class IntEditorSpinEntry(Editor): def __init__(self, model=None, value=0): super(IntEditorSpinEntry, self).__init__(model, value) self._min = -1000000 self._max = 1000000 self._step = 1 self._page = 10 self._incr = IncrementalValueMonitor() def __getstate__(self): state = super(IntEditorSpinEntry, self).__getstate__() state['min'] = self._min state['max'] = self._max state['step'] = self._step state['page'] = self._page return state def __setstate__(self, state): super(IntEditorSpinEntry, self).__setstate__(state) self._min = state.get('min', -1000000) self._max = state.get('max', 1000000) self._step = state.get('step', 1) self._page = state.get('page', 10) self._incr = IncrementalValueMonitor() def _newModel(self, value): if not isinstance(value, int): value = 0 return Model(value) def _createSettingsPres(self): def _listener(attrName): class _Listener(TextEntry.TextEntryListener): def onTextChanged(listener, textEntry): if textEntry.isDisplayedTextValid(): setattr(self, attrName, int(textEntry.getDisplayedText())) self._incr.onChanged() return _Listener() min = [ Label('Min'), TextEntry(str(self._min), _listener('_min')).regexValidated( Tokens.decimalIntegerPattern, 'Please enter an integer value') ] max = [ Label('Max'), TextEntry(str(self._max), _listener('_max')).regexValidated( Tokens.decimalIntegerPattern, 'Please enter an integer value') ] step = [ Label('Step'), TextEntry(str(self._step), _listener('_step')).regexValidated( Tokens.decimalIntegerPattern, 'Please enter an integer value') ] page = [ Label('Page'), TextEntry(str(self._page), _listener('_page')).regexValidated( Tokens.decimalIntegerPattern, 'Please enter an integer value') ] return Table([min, max, step, page]) def buildEditorPres(self, fragment, inheritedState): self._incr.onAccess() return IntSpinEntry(self._model.liveValue, self._min, self._max, self._step, self._page)
class LiveList(object): __slots__ = ['__change_history__', '_items', '_incr', '__changeListener'] def __init__(self, xs=None): self._items = [] if xs is not None: self._items[:] = xs[:] self.__change_history__ = None self._incr = IncrementalValueMonitor() self.__changeListener = None @property def changeListener(self): return self.__changeListener @changeListener.setter def changeListener(self, x): self.__changeListener = x def __getstate__(self): self._incr.onAccess() return {'items': self._items} def __setstate__(self, state): self._items = state['items'] self.__change_history__ = None self._incr = IncrementalValueMonitor() self.__changeListener = None def __copy__(self): self._incr.onAccess() t = type(self) return t(self._items) def __deepcopy__(self, memo): self._incr.onAccess() t = type(self) return t(deepcopy(self._items, memo)) def __eq__(self, other): if isinstance(other, LiveList): other = other._items return self._items == other def __ne__(self, other): if isinstance(other, LiveList): other = other._items return self._items != other def __str__(self): return str(self._items) def __repr__(self): return 'LiveList( {0} )'.format(repr(self._items)) def __get_trackable_contents__(self): return self._items def __clipboard_copy__(self, memo): self._incr.onAccess() t = type(self) return t([memo.copy(x) for x in self]) def __iter__(self): self._incr.onAccess() return _LiveListIter(iter(self._items), self._incr) def __contains__(self, x): self._incr.onAccess() return x in self._items def __add__(self, xs): self._incr.onAccess() return self._items + xs def __mul__(self, x): self._incr.onAccess() return self._items * x def __rmul__(self, x): self._incr.onAccess() return x * self._items def __getitem__(self, index): self._incr.onAccess() return self._items[index] def __len__(self): self._incr.onAccess() return len(self._items) def index(self, x, i=None, j=None): self._incr.onAccess() if i is None: return self._items.index(x) elif j is None: return self._items.index(x, i) else: return self._items.index(x, i, j) def count(self, x): self._incr.onAccess() return self._items.count(x) def __setitem__(self, index, x): if isinstance(index, int) or isinstance(index, long): oldX = self._items[index] if self.__changeListener is not None: oldContents = self._items[:] self._items[index] = x onTrackedListSetItem(self.__change_history__, self, index, oldX, x, 'Live list set item') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) else: oldContents = self._items[:] self._items[index] = x newContents = self._items[:] onTrackedListSetContents(self.__change_history__, self, oldContents, newContents, 'Live list set item') if self.__changeListener is not None: self.__changeListener(oldContents, newContents) self._incr.onChanged() def __delitem__(self, index): oldContents = self._items[:] del self._items[index] newContents = self._items[:] onTrackedListSetContents(self.__change_history__, self, oldContents, newContents, 'Live list del item') if self.__changeListener is not None: self.__changeListener(oldContents, newContents) self._incr.onChanged() def append(self, x): if self.__changeListener is not None: oldContents = self._items[:] self._items.append(x) onTrackedListAppend(self.__change_history__, self, x, 'Live list append') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() def extend(self, xs): if self.__changeListener is not None: oldContents = self._items[:] self._items.extend(xs) onTrackedListExtend(self.__change_history__, self, xs, 'Live list extend') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() def insert(self, i, x): if self.__changeListener is not None: oldContents = self._items[:] self._items.insert(i, x) onTrackedListInsert(self.__change_history__, self, i, x, 'Live list insert') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() def pop(self): if self.__changeListener is not None: oldContents = self._items[:] x = self._items.pop() onTrackedListPop(self.__change_history__, self, x, 'Live list pop') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() return x def remove(self, x): if self.__changeListener is not None: oldContents = self._items[:] i = self._items.index(x) xFromList = self._items[i] del self._items[i] onTrackedListRemove(self.__change_history__, self, i, xFromList, 'Live list remove') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() def reverse(self): if self.__changeListener is not None: oldContents = self._items[:] self._items.reverse() onTrackedListReverse(self.__change_history__, self, 'Live list reverse') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged() def sort(self, cmp=None, key=None, reverse=None): oldContents = self._items[:] self._items.sort(cmp, key, reverse) newContents = self._items[:] onTrackedListSetContents(self.__change_history__, self, oldContents, newContents, 'Live list sort') if self.__changeListener is not None: self.__changeListener(oldContents, newContents) self._incr.onChanged() def _setContents(self, xs): oldContents = self._items[:] self._items[:] = xs onTrackedListSetContents(self.__change_history__, self, oldContents, xs, 'Live list set contents') if self.__changeListener is not None: self.__changeListener(oldContents, self._items[:]) self._incr.onChanged()
class PythonCodeAbstractView(NodeAbstractView): STYLE_MINIMAL_RESULT = 0 STYLE_RESULT = 1 STYLE_CODE_AND_RESULT = 2 STYLE_CODE = 3 STYLE_EDITABLE_CODE_AND_RESULT = 4 STYLE_EDITABLE_CODE = 5 STYLE_ERRORS = 6 STYLE_HIDDEN = 7 _styleToName = { STYLE_MINIMAL_RESULT: 'minimal_result', STYLE_RESULT: 'result', STYLE_CODE_AND_RESULT: 'code_result', STYLE_CODE: 'code', STYLE_EDITABLE_CODE_AND_RESULT: 'editable_code_result', STYLE_EDITABLE_CODE: 'editable_code', STYLE_ERRORS: 'errors', STYLE_HIDDEN: 'hidden' } _nameToStyle = { 'minimal_result': STYLE_MINIMAL_RESULT, 'result': STYLE_RESULT, 'code_result': STYLE_CODE_AND_RESULT, 'code': STYLE_CODE, 'editable_code_result': STYLE_EDITABLE_CODE_AND_RESULT, 'editable_code': STYLE_EDITABLE_CODE, 'errors': STYLE_ERRORS, 'hidden': STYLE_HIDDEN } def __init__(self, worksheet, model): NodeAbstractView.__init__(self, worksheet, model) self._incr = IncrementalValueMonitor(self) self._result = None def getCode(self): return self._model['code'] def getStyle(self): name = self._model['style'] try: return self._nameToStyle[name] except KeyError: return self.STYLE_CODE_AND_RESULT def isCodeVisible(self): style = self.getStyle() return style == self.STYLE_CODE or style == self.STYLE_CODE_AND_RESULT or style == self.STYLE_EDITABLE_CODE or style == self.STYLE_EDITABLE_CODE_AND_RESULT def isCodeEditable(self): style = self.getStyle() return style == self.STYLE_EDITABLE_CODE or style == self.STYLE_EDITABLE_CODE_AND_RESULT def isResultVisible(self): style = self.getStyle() return style == self.STYLE_MINIMAL_RESULT or style == self.STYLE_RESULT or style == self.STYLE_CODE_AND_RESULT or style == self.STYLE_EDITABLE_CODE_AND_RESULT def isResultMinimal(self): style = self.getStyle() return style == self.STYLE_MINIMAL_RESULT def isMinimal(self): style = self.getStyle() return style == self.STYLE_MINIMAL_RESULT or style == self.STYLE_ERRORS def isVisible(self): style = self.getStyle() if style == self.STYLE_HIDDEN: return False elif style == self.STYLE_ERRORS: result = self.getResult() return result.hasErrors() else: return True def getResult(self): self._incr.onAccess() return self._result def _refreshResults(self, module): self._result = Execution.getResultOfExecutionWithinModule( self.getCode(), module, self.isResultVisible()) self._incr.onChanged()
class MonitoredExpression (object): _currentSuite = None def __init__(self): self._name = 'value' self._expr = EmbeddedPython2Expr() self._suite = None self._code = None self._incr = IncrementalValueMonitor() self.__change_history__ = None def __getstate__(self): return { 'name' : self._name, 'expr' : self._expr } def __setstate__(self, state): self._name = state['name'] self._expr = state['expr'] self._suite = None self._code = None self._incr = IncrementalValueMonitor() self.__change_history__ = None def __get_trackable_contents__(self): return [ self._name, self._expr ] def __py_compile_visit__(self, codeGen): self._code = codeGen.compileForEvaluation( self._expr.model ) self._suite = self._currentSuite if self._suite is not None: self._suite._registerMonitoredExpression( self ) def __py_eval__(self, _globals, _locals, codeGen): value = eval( self._code, _globals, _locals ) if self._suite is not None: self._suite._logValue( self, value ) return value def __py_replacement__(self): return deepcopy( self._expr.model['expr'] ) def __present__(self, fragment, inheritedState): self._incr.onAccess() def _setName(editableLabel, text): self._name = text self._incr.onChanged() namePres = EditableLabel( self._name, self._nameNotSetStyle( Label( '<not set>' ) ), _setName ).regexValidated( Pattern.compile( '[a-zA-Z_][a-zA-Z0-9_]*' ), 'Please enter a valid identifier' ) exprPres = self._expr contents = Row( [ namePres, Label( ': ' ), exprPres ] ) return ObjectBox( 'Monitored exp.', contents ) _nameNotSetStyle = StyleSheet.style( Primitive.foreground( Color( 0.5, 0.0, 0.0 ) ), Primitive.fontItalic( True ) )
class EvalFieldInstance(FieldInstance): """ A field that contains a value, which can alternatively have an expression that generates the required value """ def __init__(self, field, object_instance, wrapped_source_value): super(EvalFieldInstance, self).__init__(field, object_instance, wrapped_source_value) self.__change_history__ = None if wrapped_source_value is not None: source_value = wrapped_source_value[0] if isinstance(source_value, _EvalFieldState): constantValue = source_value.constantValue expr = source_value.expr else: constantValue = source_value expr = None else: constantValue = field._getDefaultValue() expr = None self._live = TrackedLiveValue(constantValue) self._expr = expr self.__incr = IncrementalValueMonitor() def isConstant(self): return self._expr is None @property def constantValue(self): return self._live.getValue() @constantValue.setter def constantValue(self, x): self._live.setLiteralValue(x) @property def constantValueLive(self): return self._live @property def expr(self): return self._expr @expr.setter def expr(self, exp): oldExpr = self._expr self._expr = exp if self.__change_history__ is not None: if oldExpr is not None: self.__change_history__.stopTracking(oldExpr) def setExpression(): self.expr = exp def revertExpression(): self.expr = oldExpr self.__change_history__.addChange(setExpression, revertExpression, 'Set expression') if exp is not None: self.__change_history__.track(exp) self.__incr.onChanged() def _addTrackableContentsTo(self, contents): contents.append(self) def __field_getstate__(self): return _EvalFieldState(self._live.getValue(), self._expr) def __field_getstate_for_clipboard_copy__(self, memo): return _EvalFieldState(memo.copy(self._live.getValue()), memo.copy(self._expr)) def getValueForEditor(self): return self._live.getValue() def __py_evalmodel__(self, codeGen): self.__incr.onAccess() if self._expr is None: return self.__fixedvalue_py_evalmodel__(self._live.getValue(), codeGen) else: return self._expr.model def __fixedvalue_py_evalmodel__(self, value, codeGen): return Py.coerceToModel(value) def __get_trackable_contents__(self): if self._expr is not None: return [self._live, self._expr] else: return [self._live] def editUI(self, controlFactoryFn): self.__incr.onAccess() valueControl = controlFactoryFn(self._live) if self._expr is None: def _onAdd(button, event): self.expr = EmbeddedPython2Expr() addButton = Button(self._addButtonContents, _onAdd).alignHPack() return Row([valueControl, Spacer(10.0, 0.0), addButton]) else: def _onRemove(button, event): self.expr = None removeButton = Button(self._removeButtonContents, _onRemove).alignHPack() return Column([ valueControl, Row([ removeButton, Spacer(10.0, 0.0), exprBorder.surround(self._expr) ]) ]) _addStyle = StyleSheet.style(Primitive.foreground(Color(0.0, 0.5, 0.0)), Primitive.fontBold(True), Primitive.fontSize(11)) _removeStyle = StyleSheet.style(Primitive.foreground(Color(0.5, 0.0, 0.0)), Primitive.fontBold(True), Primitive.fontSize(11)) _fStyle = StyleSheet.style(Primitive.foreground(Color(0.0, 0.25, 0.5)), Primitive.fontItalic(True), Primitive.fontSize(11)) _parenStyle = StyleSheet.style(Primitive.foreground(Color(0.3, 0.3, 0.3)), Primitive.fontSize(11)) _addButtonContents = Row([ _addStyle(Label('+ ')), _fStyle(Label('f')), _parenStyle(Label('()')) ]) _removeButtonContents = Row([ _removeStyle(Label('- ')), _fStyle(Label('f')), _parenStyle(Label('()')) ])
class TraceVisualisation (object): def __init__(self): self._suite = EmbeddedPython2Suite() self._code = None self._incr = IncrementalValueMonitor() self.__change_history__ = None self._tableSchema = None self._tableView = _TableView() self._treeView = _TreeView() def __getstate__(self): return { 'suite' : self._suite, 'tableView' : self._tableView, 'treeView' : self._treeView } def __setstate__(self, state): self._suite = state['suite'] self._tableView = state.get( 'tableView', _TableView() ) self._treeView = state.get( 'treeView', _TreeView() ) self._code = None self._incr = IncrementalValueMonitor() self.__change_history__ = None self._tableSchema = None def __get_trackable_contents__(self): return [ self._suite ] def _initTableSchema(self): self._tableSchema = _TableSchema() def _initTableView(self): self._tableView.initialise( self._tableSchema ) self._incr.onChanged() def _initTreeView(self): self._treeView.initialise() self._incr.onChanged() def _registerMonitoredExpression(self, monitoredExpression): self._tableSchema.registerMonitoredExpression( monitoredExpression ) def _logValue(self, monitoredExpression, value): self._tableView.logValue( monitoredExpression, value ) self._treeView.logValue( monitoredExpression, value ) def _clear(self): self._initTableView() self._initTreeView() def __py_compile_visit__(self, codeGen): self._initTableSchema() prevSuite = MonitoredExpression._currentSuite MonitoredExpression._currentSuite = self self._code = codeGen.compileForExecution( self._suite.model ) MonitoredExpression._currentSuite = prevSuite self._initTableView() self._initTreeView() def __py_exec__(self, _globals, _locals, codeGen): tableState = self._tableView.begin() treeState = self._treeView.begin() exec self._code in _globals, _locals self._treeView.end( treeState ) self._tableView.end( tableState ) def __py_replacement__(self): return deepcopy( self._suite.model['suite'] ) def __present__(self, fragment, inheritedState): def _embeddedDisplayMenu(element, menu): def _onClear(item): self._clear() menu.add( MenuItem.menuItemWithLabel( 'Clear collected values', _onClear ) ) return False self._incr.onAccess() suitePres = self._suite valuesPres = TabbedBox( [ [ Label( 'Tree' ), self._treeView ], [ Label( 'Table' ), self._tableView ] ], None ) contents = Column( [ suitePres, valuesPres ] ) return ObjectBox( 'Trace visualisation', contents ).withContextMenuInteractor( _embeddedDisplayMenu ).withCommands( _mxCommands )
class Console (object): class Output (object): def __init__(self): self._builder = None def write(self, text): if not ( isinstance( text, str ) or isinstance( text, unicode ) ): raise TypeError, 'argument 1 must be string, not %s' % type( text ) if self._builder is None: self._builder = StringBuilder() self._builder.append( text ) def getText(self): if self._builder is not None: return self._builder.toString() else: return None def __init__(self, name, showBanner=True): self._incr = IncrementalValueMonitor( self ) self._blocks = [] self._currentPythonModule = Python2.py25NewModuleAsRoot() self._before = [] self._after = [] self._module = imp.new_module( name ) self._showBanner = showBanner LoadBuiltins.loadBuiltins( self._module ) def getBlocks(self): self._incr.onAccess() return copy( self._blocks ) def getCurrentPythonModule(self): self._incr.onAccess() return self._currentPythonModule def _commit(self, module, execResult): self._blocks.append( ConsoleBlock( module, execResult ) ) for a in self._after: if not Python2.isEmptyTopLevel(a): self._before.append( a ) if not Python2.isEmptyTopLevel(module): self._before.append( deepcopy( module ) ) self._after = [] self._currentPythonModule = Python2.py25NewModuleAsRoot() self._incr.onChanged() def backwards(self): if len( self._before ) > 0: self._after.insert( 0, self._currentPythonModule ) self._currentPythonModule = self._before.pop() self._incr.onChanged() def forwards(self): if len( self._after ) > 0: self._before.append( self._currentPythonModule ) self._currentPythonModule = self._after[0] del self._after[0] self._incr.onChanged() def assignVariable(self, name, value): setattr( self._module, name, value ) self._blocks.append( ConsoleVarAssignment( name, value ) ) self._incr.onChanged() def execute(self, bEvaluate=True): module = self.getCurrentPythonModule() if not Python2.isEmptyTopLevel(module): execResult = Execution.getResultOfExecutionWithinModule( module, self._module, bEvaluate ) self._commit( module, execResult ) def executeModule(self, module, bEvaluate=True): if not Python2.isEmptyTopLevel(module): execResult = Execution.getResultOfExecutionWithinModule( module, self._module, bEvaluate ) self._commit( module, execResult ) def __present__(self, fragment, inheritedState): blocks = self.getBlocks() currentModule = Python2.python2EditorPerspective.applyTo( self.getCurrentPythonModule() ) def _onDrop(element, pos, data, action): class _VarNameEntryListener (TextEntry.TextEntryListener): def onAccept(listenerSelf, entry, text): self.assignVariable( text, data.getModel() ) _finish( entry ) def onCancel(listenerSelf, entry, text): _finish( entry ) def _finish(entry): caret.moveTo( marker ) dropPromptLive.setLiteralValue( Blank() ) dropPrompt = _dropPrompt( _VarNameEntryListener() ) rootElement = element.getRootElement() caret = rootElement.getCaret() marker = caret.getMarker().copy() dropPromptLive.setLiteralValue( dropPrompt ) rootElement.grabFocus() return True # Header if self._showBanner: bannerVersionText = [ _bannerTextStyle.applyTo( NormalText( v ) ) for v in sys.version.split( '\n' ) ] helpText1 = Row( [ _bannerHelpKeyTextStyle.applyTo( Label( 'Ctrl+Enter' ) ), _bannerHelpTextStyle.applyTo( Label( ' - execute and evaluate, ' ) ), _bannerHelpKeyTextStyle.applyTo( Label( 'Ctrl+Shift+Enter' ) ), _bannerHelpTextStyle.applyTo( Label( ' - execute only' ) ) ] ) helpText2 = Row( [ _bannerHelpKeyTextStyle.applyTo( Label( 'Alt+Up' ) ), _bannerHelpTextStyle.applyTo( Label( ' - previous, ' ) ), _bannerHelpKeyTextStyle.applyTo( Label( 'Alt+Down' ) ), _bannerHelpTextStyle.applyTo( Label( ' - next' ) ) ] ) bannerText = Column( bannerVersionText + [ helpText1, helpText2 ] ).alignHPack() banner = _bannerBorder.surround( bannerText ) else: banner = None dropDest = ObjectDndHandler.DropDest( FragmentData, _onDrop ) def _onExecute(element): self.execute( True ) def _onExecuteNoEval(element): self.execute( False ) def _onHistoryPrev(element): self.backwards() def _onHistoryNext(element): self.forwards() currentModule = Span( [ currentModule ] ) currentModule = currentModule.withShortcut( _executeShortcut, _onExecute ) currentModule = currentModule.withShortcut( _executeNoEvalShortcut, _onExecuteNoEval ) currentModule = currentModule.withShortcut( _historyPreviousShortcut, _onHistoryPrev ) currentModule = currentModule.withShortcut( _historyNextShortcut, _onHistoryNext ) m = _pythonModuleBorderStyle.applyTo( Border( currentModule.alignHExpand() ) ).alignHExpand() m = m.withDropDest( dropDest ) def _ensureCurrentModuleVisible(element, ctx, style): element.ensureVisible() m = m.withCustomElementAction( _ensureCurrentModuleVisible ) dropPromptLive = LiveValue( Span( [] ) ) dropPromptView = dropPromptLive consoleColumnContents = [ banner.alignVRefY() ] if self._showBanner else [] if len( blocks ) > 0: blockList = _consoleBlockListStyle.applyTo( Column( blocks ) ).alignHExpand() consoleColumnContents += [ blockList.alignVRefY(), dropPromptView.alignVRefY(), m.alignVRefY() ] else: consoleColumnContents += [ dropPromptView.alignVRefY(), m.alignVRefY() ] return _consoleStyle.applyTo( Column( consoleColumnContents ) ).alignHExpand().alignVTop()
class PathsConfigurationPage (ConfigurationPage): def __init__(self): super( PathsConfigurationPage, self ).__init__() self._pluginPaths = [] self._libraryPaths = [] self._incr = IncrementalValueMonitor() def __getstate__(self): state = super( PathsConfigurationPage, self ).__getstate__() state['pluginPaths'] = self._pluginPaths state['libraryPaths'] = self._libraryPaths return state def __setstate__(self, state): super( PathsConfigurationPage, self ).__setstate__( state ) self._pluginPaths = state['pluginPaths'] try: self._libraryPaths = state['libraryPaths'] except KeyError: self._libraryPaths = state['pluginRootPaths'] self._incr = IncrementalValueMonitor() @property def pluginPaths(self): return self._pluginPaths @property def libraryPaths(self): return self._libraryPaths def getSubjectTitle(self): return '[CFG] Paths' def getTitleText(self): return 'Paths Configuration' def getLinkText(self): return 'Paths' def presentPathList(self, pathList): def pathItem(index): def _onDelete(menuItem): del pathList[index] self._incr.onChanged() def buildContextMenu(element, menu): menu.add( MenuItem.menuItemWithLabel( 'Delete', _onDelete ) ) return True return _itemHoverHighlightStyle.applyTo( Label( pathList[index] ) ).withContextMenuInteractor( buildContextMenu ) def _onNew(hyperlink, event): component = hyperlink.getElement().getRootElement().getComponent() openDialog = JFileChooser() openDialog.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY ) response = openDialog.showDialog( component, 'Choose path' ) if response == JFileChooser.APPROVE_OPTION: sf = openDialog.getSelectedFile() if sf is not None: filename = sf.getPath() if filename is not None and os.path.isdir( filename ): pathList.append( filename ) self._incr.onChanged() newLink = Hyperlink( 'NEW', _onNew ) controls = newLink.pad( 10.0, 5.0 ) pathPres = Column( [ pathItem( i ) for i in xrange( len( pathList ) ) ] ) return Column( [ controls, pathPres.padX( 5.0 ) ] ) def pathsSection(self, title, pathList): pathsPres = self.presentPathList( pathList ) return Section( SectionHeading2( title ), pathsPres ) def __present_contents__(self, fragment, inheritedState): self._incr.onAccess() pluginPathsPres = self.pathsSection( 'Plugin paths', self._pluginPaths ) pluginRootPathsPres = self.pathsSection( 'Library paths', self._libraryPaths ) return Body( [ pluginPathsPres, pluginRootPathsPres ] )
class GraphVizConfigurationPage(ConfigurationPage): def __init__(self): super(GraphVizConfigurationPage, self).__init__() self._graphVizDir = None self._config = None self._incr = IncrementalValueMonitor() def initPage(self, config): super(GraphVizConfigurationPage, self).initPage(config) GraphVizConfiguration.setConfigurationPageSubject(self.subject()) def __getstate__(self): state = super(GraphVizConfigurationPage, self).__getstate__() state['graphVizDir'] = self._graphVizDir return state def __setstate__(self, state): super(GraphVizConfigurationPage, self).__setstate__(state) self._graphVizDir = state['graphVizDir'] self._config = None self._incr = IncrementalValueMonitor() self._refreshConfig() def _checkedToolPath(self, name): path = os.path.join(self._graphVizDir, name + _exeExtension) if os.path.exists(path): return path else: return None def _setGraphVizDir(self, dir): self._graphVizDir = dir self._refreshConfig() self._incr.onChanged() def __isConfigured(self): if self._graphVizDir is not None and os.path.isdir(self._graphVizDir): dotPath = self._checkedToolPath('dot') neatoPath = self._checkedToolPath('neato') twopiPath = self._checkedToolPath('twopi') circoPath = self._checkedToolPath('circo') fdpPath = self._checkedToolPath('fdp') sfdpPath = self._checkedToolPath('sfdp') osagePath = self._checkedToolPath('osage') return dotPath is not None and neatoPath is not None and twopiPath is not None and circoPath is not None and fdpPath is not None and sfdpPath is not None and osagePath is not None return False def _refreshConfig(self): if self._graphVizDir is not None and os.path.isdir(self._graphVizDir): dotPath = self._checkedToolPath('dot') neatoPath = self._checkedToolPath('neato') twopiPath = self._checkedToolPath('twopi') circoPath = self._checkedToolPath('circo') fdpPath = self._checkedToolPath('fdp') sfdpPath = self._checkedToolPath('sfdp') osagePath = self._checkedToolPath('osage') self._config = GraphVizConfiguration(dotPath, neatoPath, twopiPath, circoPath, fdpPath, sfdpPath, osagePath) GraphVizConfiguration.setInstance(self._config) else: self._config = None GraphVizConfiguration.setInstance(None) self._incr.onChanged() def getSubjectTitle(self): return '[CFG] GraphViz' def getTitleText(self): return 'GraphViz Configuration' def getLinkText(self): return 'GraphViz' def _presentDir(self): def _onSet(hyperlink, event): component = hyperlink.getElement().getRootElement().getComponent() openDialog = JFileChooser() openDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) response = openDialog.showDialog(component, 'Choose path') if response == JFileChooser.APPROVE_OPTION: sf = openDialog.getSelectedFile() if sf is not None: filename = sf.getPath() if filename is not None and os.path.isdir(filename): self._graphVizDir = filename self._refreshConfig() self._incr.onChanged() dirLabel = Label( self._graphVizDir ) if self._graphVizDir is not None else self._notSetStyle.applyTo( Label('<Not set>')) setLink = Hyperlink('CHANGE', _onSet) return self._dirBorderStyle.applyTo( Border(Row([dirLabel, Spacer(25.0, 0.0), setLink]))) def _toolLabel(self, name): return self._configTableToolNameStyle.applyTo(Label(name)) def _presentConfig(self): if self._config is not None: rows = [] rows.append([SectionHeading3('Tool'), SectionHeading3('Path')]) rows.append( [self._toolLabel('dot'), Label(self._config.getDotPath())]) rows.append( [self._toolLabel('neato'), Label(self._config.getNeatoPath())]) rows.append( [self._toolLabel('twopi'), Label(self._config.getTwopiPath())]) rows.append( [self._toolLabel('circo'), Label(self._config.getCircoPath())]) rows.append( [self._toolLabel('fdp'), Label(self._config.getFdpPath())]) rows.append( [self._toolLabel('sfdp'), Label(self._config.getSfdpPath())]) rows.append( [self._toolLabel('osage'), Label(self._config.getOsagePath())]) return self._configTableStyle.applyTo(Table(rows)).pad(15.0, 5.0) def __present_contents__(self, fragment, inheritedState): self._incr.onAccess() dirPres = self._presentDir() note = NotesText([ 'Note: please choose the location of the GraphViz ', EmphSpan('bin'), ' directory.' ]) columnContents = [note, dirPres] if self._config is not None: columnContents.append(self._presentConfig()) pathContents = Column(columnContents) pathSection = Section(SectionHeading2('GraphViz path'), pathContents) downloadText = '' if self.__isConfigured(): downloadText = 'GraphViz appears to be installed on this machine and configured. If it does not work correctly, you may need to install it. You can download it from the ' else: downloadText = 'If GraphViz is not installed on this machine, please install it. You can download it from the ' downloadLink = Hyperlink('GraphViz homepage', URI('http://www.graphviz.org/')) download = NormalText([downloadText, downloadLink, '.']) downloadSec = Section( SectionHeading2('GraphViz download/installation'), download) return Body([pathSection, downloadSec]) _dirBorderStyle = StyleSheet.style( Primitive.border( SolidBorder(1.0, 3.0, 10.0, 10.0, Color(1.0, 0.85, 0.0), Color(1.0, 1.0, 0.85)))) _notSetStyle = StyleSheet.style(Primitive.fontItalic(True)) _configTableStyle = StyleSheet.style(Primitive.tableColumnSpacing(10.0)) _configTableToolNameStyle = StyleSheet.style( Primitive.foreground(Color(0.25, 0.0, 0.5)))
class ElemAttrs(object): """ XML element attributes Implements the Python dictionary interface Live object; incremental monitor tracks accesses and changes """ def __init__(self, attrs=None): if attrs is None: attrs = {} self.__attrs = attrs self.__incr = IncrementalValueMonitor() def __eq__(self, other): if isinstance(other, ElemAttrs): return self.__attrs == other.__attrs else: return NotImplemented def __ne__(self, other): if isinstance(other, ElemAttrs): return self.__attrs != other.__attrs else: return NotImplemented def attrs_dict(self): x = {} x.update(self.__attrs) return x def __len__(self): self.__incr.onAccess() return len(self.__attrs) def __getitem__(self, key): self.__incr.onAccess() return self.__attrs[key] def __setitem__(self, key, value): self.__incr.onChanged() self.__attrs[key] = value def __delitem__(self, key): self.__incr.onChanged() del self.__attrs[key] def __contains__(self, key): self.__incr.onAccess() return key in self.__attrs def __iter__(self): self.__incr.onAccess() for k in self.__attrs.keys(): self.__incr.onAccess() yield k def clear(self): self.__incr.onChanged() self.__attrs.clear() def copy(self): self.__incr.onAccess() return self.__attrs.copy() def get(self, key, default=None): self.__incr.onAccess() return self.__attrs.get(key, default) def has_key(self, key): self.__incr.onAccess() return self.__attrs.has_key(key) def keys(self): self.__incr.onAccess() return self.__attrs.keys() def update(self, values): self.__incr.onChanged() self.__attrs.update(values) def __pair(self, kv): key, value = kv eq = self._punc_style.applyTo(Label('=')) return Span([ self._name_style(Label(key)), eq, self._value_style(Label(value)) ]) def __present__(self, fragment, inh): space = Label(' ') br = LineBreak() items = self.__attrs.items() contents = [self.__pair(items[0])] for x in items[1:]: contents.extend([space, br, self.__pair(x)]) return Span(contents) _punc_style = StyleSheet.style(Primitive.foreground(Color(0.7, 0.7, 0.7))) _name_style = StyleSheet.style(Primitive.foreground(Color(0.0, 0.7, 0.3))) _value_style = StyleSheet.style(Primitive.foreground(Color(0.7, 0.3, 0.0)))