Пример #1
0
class StepperBreakpoint(object):
    def __init__(self):
        self.__change_history__ = None
        self._isCurrent = LiveValue(False)

    def __getstate__(self):
        return {None: None}

    def __setstate__(self, state):
        self.__change_history__ = None
        self._isCurrent = LiveValue(False)

    def __get_trackable_contents__(self):
        return []

    def __py_exec__(self, globals, locals, codeGen):
        co = Coroutine.getCurrent()
        stepper = _getStepperForCoroutine(co)
        if stepper is not None:
            stateView = self._createStateView()
            sourceStepper = stepper._co.yieldToParent((self, stateView))

    def _setAsNotCurrent(self):
        self._isCurrent.setLiteralValue(False)

    def _setAsCurrent(self):
        self._isCurrent.setLiteralValue(True)

    def _createStateView(self):
        print 'StepperBreakpoint._createStateView: not implemented'
        return None

    def __present__(self, fragment, inheritedState):
        current = self._isCurrent.getValue()
        label = _breakPointStyle(Label('BREAKPOINT'))
        if current:
            return _breakPointCurrentBorder.surround(
                Row([_breakPointArrow,
                     Spacer(
                         3.0,
                         0.0,
                     ), label]).alignVCentre())
        else:
            return _breakPointBorder.surround(label)
Пример #2
0
class Model (object):
	def __init__(self, value=None):
		self._live = LiveValue( value )


	def __getValue(self):
		return self._live.getValue()

	def __setValue(self, value):
		self._live.setLiteralValue(value)

	value = property(__getValue, __setValue)


	@property
	def liveValue(self):
		return self._live



	def __getstate__(self):
		return { 'value' : self._live.getValue() }


	def __setstate__(self, state):
		value = state['value']
		self._live = LiveValue( value )



	def _addListener(self, listener):
		self._live.addListener( listener )

	def _removeListener(self, listener):
		self._live.removeListener( listener )



	def __present__(self, fragment, inheritedState):
		return ObjectBox( 'LarchTools.EmbeddedData.Model', self._live )
Пример #3
0
class FontConfiguration(object):
    def __init__(self,
                 generic=Primitive.genericFontName,
                 normal=Primitive.normalTextFontName,
                 heading=Primitive.headingFontName,
                 title=Primitive.titleFontName,
                 uiHeading=Primitive.lightFontName):
        self._generic = LiveValue(generic)
        self._normal = LiveValue(normal)
        self._heading = LiveValue(heading)
        self._title = LiveValue(title)
        self._uiHeading = LiveValue(uiHeading)

    def __getstate__(self):
        state = {}
        state['generic'] = self._generic.getStaticValue()
        state['normal'] = self._normal.getStaticValue()
        state['heading'] = self._heading.getStaticValue()
        state['title'] = self._title.getStaticValue()
        state['uiHeading'] = self._uiHeading.getStaticValue()
        return state

    def __setstate__(self, state):
        self._generic = LiveValue(state.get('generic', 'SansSerif'))
        self._normal = LiveValue(state.get('normal', 'SansSerif'))
        self._heading = LiveValue(state.get('heading', 'Serif'))
        self._title = LiveValue(state.get('title', 'Serif'))
        self._uiHeading = LiveValue(state.get('uiHeading', 'SansSerif'))

    def copyFrom(self, config):
        self._generic.setLiteralValue(config._generic.getStaticValue())
        self._normal.setLiteralValue(config._normal.getStaticValue())
        self._heading.setLiteralValue(config._heading.getStaticValue())
        self._title.setLiteralValue(config._title.getStaticValue())
        self._uiHeading.setLiteralValue(config._uiHeading.getStaticValue())

    def _createStyleSheet(self):
        def suffix(fontName, defaultFont):
            if defaultFont in [f.strip() for f in fontName.split(';')]:
                return fontName
            elif fontName.strip() == '':
                return defaultFont
            else:
                return fontName + '; ' + defaultFont

        style = StyleSheet.style(
            Primitive.fontFace(suffix(self._generic.getValue(), 'SansSerif')),
            RichText.titleTextAttrs(
                RichText.titleTextAttrs.defaultValue.withValues(
                    Primitive.fontFace(suffix(self._title.getValue(),
                                              'Serif')))),
            RichText.headingTextAttrs(
                RichText.headingTextAttrs.defaultValue.withValues(
                    Primitive.fontFace(
                        suffix(self._heading.getValue(), 'Serif')))),
            RichText.normalTextAttrs(
                RichText.normalTextAttrs.defaultValue.withValues(
                    Primitive.fontFace(
                        suffix(self._normal.getValue(), 'SansSerif')))),
            UI.uiTextAttrs(
                UI.uiTextAttrs.defaultValue.withValues(
                    Primitive.fontFace(
                        suffix(self._uiHeading.getValue(), 'SansSerif')))))
        return style

    def apply(self):
        StyleValues.setRootStyleSheet(self._createStyleSheet())

    def __present__(self, fragment, inheritedState):
        helpText = NormalText(
            'Click to open the font choosers. Click on a font sample to choose it. Ctrl-click to select additional fonts.'
        )

        def titleSample(fontName, text='The quick brown fox'):
            style = StyleSheet.style(
                RichText.titleTextAttrs(
                    RichText.titleTextAttrs.defaultValue.withValues(
                        Primitive.fontFace(fontName))))
            return style(TitleBar(text))

        titleChooser = _collapsibleFontChooser('Titles', self._title,
                                               titleSample)

        def headingSample(fontName,
                          text='The quick brown fox jumps over the lazy dog'):
            style = StyleSheet.style(
                RichText.headingTextAttrs(
                    RichText.headingTextAttrs.defaultValue.withValues(
                        Primitive.fontFace(fontName))))
            return style(Heading1(text))

        headingChooser = _collapsibleFontChooser('Headings', self._heading,
                                                 headingSample)

        def normalSample(fontName,
                         text='The quick brown fox jumps over the lazy dog'):
            style = StyleSheet.style(
                RichText.normalTextAttrs(
                    RichText.normalTextAttrs.defaultValue.withValues(
                        Primitive.fontFace(fontName))))
            return style(NormalText(text))

        normalChooser = _collapsibleFontChooser('Normal text', self._normal,
                                                normalSample)

        def uiHeadingSample(fontName,
                            text='The quick brown fox jumps over the lazy dog'
                            ):
            style = StyleSheet.style(
                UI.uiTextAttrs(
                    UI.uiTextAttrs.defaultValue.withValues(
                        Primitive.fontFace(fontName))))
            return style(SectionHeading1(text))

        uiHeadingChooser = _collapsibleFontChooser('UI Headings',
                                                   self._uiHeading,
                                                   uiHeadingSample)

        def genericSample(fontName,
                          text='The quick brown fox jumps over the lazy dog'):
            style = StyleSheet.style(Primitive.fontFace(fontName))
            return style(Label(text))

        genericChooser = _collapsibleFontChooser('Generic text', self._generic,
                                                 genericSample)

        chooserColumn = self._chooserColumnStyle(
            Column([
                titleChooser, headingChooser, normalChooser, uiHeadingChooser,
                genericChooser
            ]))

        # Sample page
        @LiveFunction
        def samplePage():
            label = Label('Sample page:')

            title = titleSample(self._title.getValue(), 'Example Page Title')
            heading = headingSample(self._heading.getValue(), 'Main heading')
            normal1 = normalSample(self._normal.getValue(),
                                   'Normal text will appear like this.')
            normal2 = normalSample(
                self._normal.getValue(),
                'Paragraphs of normal text are used for standard content.')
            ui1 = uiHeadingSample(self._uiHeading.getValue(), 'UI heading')
            genericLabel = Label(
                'Generic text (within controls, code, etc) will appear like this.'
            )
            buttons = self._buttonRowStyle(
                Row([
                    Button.buttonWithLabel('Button %d' % (i, ), None)
                    for i in xrange(0, 5)
                ]))
            ui = Section(ui1, Column([genericLabel,
                                      Spacer(0.0, 7.0), buttons]))
            page = Page([title, Body([heading, normal1, normal2, ui])])

            return Column([label, Spacer(0.0, 15.0), page])

        return self._mainColumnStyle(
            Column([helpText, chooserColumn, samplePage]))

    _mainColumnStyle = StyleSheet.style(Primitive.columnSpacing(30.0))
    _chooserColumnStyle = StyleSheet.style(Primitive.columnSpacing(5.0))
    _buttonRowStyle = StyleSheet.style(Primitive.rowSpacing(10.0))
Пример #4
0
class FontConfigurationPage(ConfigurationPage):
    def __init__(self):
        super(FontConfigurationPage, self).__init__()
        self._config = None
        self._userConfig = LiveValue(self._config)

    def __getstate__(self):
        state = super(FontConfigurationPage, self).__getstate__()
        state['config'] = self._config
        return state

    def __setstate__(self, state):
        super(FontConfigurationPage, self).__setstate__(state)
        self._config = state.get('config')
        self._userConfig = LiveValue(self._config)

    def getSubjectTitle(self):
        return '[CFG] Fonts'

    def getTitleText(self):
        return 'Font Configuration'

    def getLinkText(self):
        return 'Fonts'

    def apply(self):
        config = _fontConfigForName(self._config)
        config.apply()

    def __present_contents__(self, fragment, inheritedState):
        def _onApply(button, event):
            self._config = self._userConfig.getStaticValue()
            self.apply()

        def _onRevert(button, event):
            self._userConfig.setLiteralValue(self._config)

        choices = [Label(c[1]) for c in _fontConfigChoices]
        choices.append(Label('Custom'))

        @LiveFunction
        def indexOfChoice():
            config = self._userConfig.getValue()
            if isinstance(config, FontConfiguration):
                return len(choices) - 1
            else:
                try:
                    return [c[0] for c in _fontConfigChoices
                            ].index(self._userConfig.getValue())
                except ValueError:
                    return 0

        @LiveFunction
        def footer():
            config = self._userConfig.getValue()
            if isinstance(config, FontConfiguration):
                return config
            else:
                return Blank()

        def _onChoice(menu, prevChoice, choice):
            if choice == len(choices) - 1:
                # Custom
                if prevChoice != choice:
                    prevConfig = _fontConfigChoices[prevChoice][0]
                    prevConfig = _fontConfigForName(prevConfig)
                    config = FontConfiguration()
                    config.copyFrom(prevConfig)
                    self._userConfig.setLiteralValue(config)
            else:
                self._userConfig.setLiteralValue(_fontConfigChoices[choice][0])

        applyButton = Button.buttonWithLabel('Apply', _onApply)
        revertButton = Button.buttonWithLabel('Revert', _onRevert)
        buttons = Row([applyButton,
                       Spacer(15.0, 0.0), revertButton]).alignHPack()

        configMenu = OptionMenu(choices, indexOfChoice, _onChoice)

        chooserHeader = Row([
            Label('Choose a font configuration:'),
            Spacer(25.0, 0.0), configMenu
        ]).alignHPack()

        return self._pageColumnStyle(Column([buttons, chooserHeader, footer]))

    _pageColumnStyle = StyleSheet.style(Primitive.columnSpacing(25.0))
class AbstractInlineTestTableRow (object):
	def __init__(self):
		self.__testTable = None
		self.__result = LiveValue( _resultNone )
		self.__testMethodName = None
		# Form: either ( 'value', value )  or  ( 'exception', exceptionType )  or  None
		self._expected = TrackedLiveValue( None )
		self._actual = TrackedLiveValue( None )

		self.__change_history__ = None



	def __getstate__(self):
		return { 'expected' : self._expected.getStaticValue() }

	def __setstate__(self, state):
		self.__change_history__ = None
		self.__testTable = None
		self.__result = LiveValue( _resultNone )
		self.__testMethodName = None
		self._expected = TrackedLiveValue( state['expected'] )
		self._actual = TrackedLiveValue( None )


	def __get_trackable_contents__(self):
		return [ self._expected ]



	def reset(self):
		self.__result.setLiteralValue( _resultNone )
		self.__testMethodName = None
		self._actual.setLiteralValue( None )


	def _regsiterTestTable(self, testTable):
		self.__testTable = testTable


	def runOnInstance(self, instance):
		getattr( instance, self._methodName )()


	@property
	def _desiredMethodName(self):
		raise NotImplementedError, 'abstract'


	@property
	def _methodName(self):
		if self.__testMethodName is None:
			self.__testMethodName = self.__testTable._uniqueMethodName( self._desiredMethodName )
		return self.__testMethodName


	def _createValueStmtsAndResultVarName(self, codeGen):
		raise NotImplementedError, 'abstract'


	@property
	def _scope(self):
		return self.__testTable._scope   if self.__testTable is not None   else ( None, None, None )


	def _debug(self):
		return None


	def __debugWrap(self, p):
		d = self._debug()
		if d is not None:
			return Column( [ p, Pres.coerce( d ).alignHPack() ] ).alignVTop()
		else:
			return p


	def _createMethodAST(self, codeGen):
		valueStmts, resultVarName = self._createValueStmtsAndResultVarName( codeGen )

		JythonExceptionAST = codeGen.embeddedValue( JythonException )
		sysAST = codeGen.embeddedValue( sys )
		getCurrentExceptionCallAST = Schema.Call( target=Schema.AttributeRef( target=JythonExceptionAST, name='getCurrentException' ), args=[] )
		getExcInfoTypeAST = Schema.Subscript( target=Schema.Call( target=Schema.AttributeRef( target=sysAST, name='exc_info' ), args=[] ),
						      index=Schema.IntLiteral( format='decimal', numType='int', value='0' ) )
		selfAST = codeGen.embeddedValue( self )
		testValueAST = Schema.AttributeRef( target=selfAST, name='_testValue' )
		kindExceptionAST = Schema.StringLiteral( format='ascii', quotation='single', value='exception' )
		kindValueAST = Schema.StringLiteral( format='ascii', quotation='single', value='value' )

		exceptStmts = [ Schema.ExprStmt( expr=Schema.Call( target=testValueAST, args=[ kindExceptionAST, getCurrentExceptionCallAST, getExcInfoTypeAST ] ) ) ]
		elseStmts = [ Schema.ExprStmt( expr=Schema.Call( target=testValueAST, args=[ kindValueAST, Schema.Load( name=resultVarName ) ] ) ) ]
		methodBody = [ Schema.TryStmt( suite=valueStmts, exceptBlocks=[ Schema.ExceptBlock( suite=exceptStmts ) ], elseSuite=elseStmts ) ]

		methodAST = Schema.DefStmt( name=self._methodName, decorators=[], params=[ Schema.SimpleParam( name='self' ) ], suite=methodBody )
		return methodAST



	@staticmethod
	def _statementsForExecutionAndEvaluationIntoValue(stmts, varName):
		for i in xrange( len( stmts ) - 1, -1, -1 ):
			stmt = stmts[i]
			if stmt.isInstanceOf( Schema.ExprStmt ):
				return stmts[:i] + [ Schema.AssignStmt( targets=[ Schema.SingleTarget( name=varName ) ], value=stmt['expr'] ) ] + stmts[i+1:]
			elif stmt.isInstanceOf( Schema.BlankLine )  or  stmt.isInstanceOf( Schema.CommentStmt ):
				pass
			else:
				break
		return deepcopy( stmts ) + [ Schema.AssignStmt( targets=[ Schema.SingleTarget( name=varName ) ], value=Schema.Load( name='None' ) ) ]




	def _testValue(self, kind, data, excType=None):
		self._actual.setLiteralValue( ( kind, data ) )
		expected = self._expected.getStaticValue()
		if expected is not None:
			expectedKind, expectedData = expected
			if kind == expectedKind:
				if expectedKind == 'exception':
					if excType == expectedData:
						self.__result.setLiteralValue( _resultPass )
					else:
						title = _resultFailStyle( Label( 'FAIL' ) )
						heading = Label( 'Expected exception of type %s, got:' % expectedData.__name__ )
						res = Column( [ title, heading, data ] )
						self.__result.setLiteralValue( res )
				elif expectedKind == 'value':
					if data == expectedData:
						self.__result.setLiteralValue( _resultPass )
					else:
						title = _resultFailStyle( Label( 'FAIL' ) )
						heading1 = Label( 'Expected:' )
						heading2 = Label( 'Got:' )
						res = Column( [ title, heading1, expectedData, heading2, data ] )
						self.__result.setLiteralValue( res )
				else:
					raise TypeError, 'unknown expected result kind %s' % expectedKind
			else:
				resContents = [ _resultFailStyle( Label( 'FAIL' ) ) ]

				if expectedKind == 'exception':
					resContents.append( Label( 'Expected exception of type %s:' % expectedData.__name__ ) )
				elif expectedKind == 'value':
					resContents.append( Label( 'Expected:' ) )
					resContents.append( expectedData )
				else:
					raise TypeError, 'unknown expected result kind %s' % expectedKind

				if kind == 'exception':
					resContents.append( Label( 'Got exception:' ) )
					resContents.append( data )
				elif kind == 'value':
					resContents.append( Label( 'Expected:' ) )
					resContents.append( data )
				else:
					raise TypeError, 'unknown result kind %s' % kind

				self.__result.setLiteralValue( Column( resContents ) )
		else:
			def _onFix(button, event):
				if kind == 'exception':
					self._expected.setLiteralValue( ( kind, excType ) )
				elif kind == 'value':
					self._expected.setLiteralValue( ( kind, data ) )
				else:
					raise TypeError, 'unknown result kind %s' % kind
				self.__result.setLiteralValue( _resultNone )

			fixButton = Button.buttonWithLabel( 'Set expected result', _onFix )
			title = Label( 'No expected result, received:' )
			self.__result.setLiteralValue( Column( [ title, Pres.coerce( data ).pad( 5.0, 0.0, 5.0, 5.0 ), fixButton ] ).alignHPack().alignVTop() )







	@property
	def result(self):
		return self.__debugWrap( self.__result )


	@property
	def expected(self):
		expected = self._expected.getValue()
		if expected is not None:
			expectedKind, expectedData = expected
			if expectedKind == 'exception':
				return Label( 'Exception of type %s' % expectedData.__name__ )
			elif expectedKind == 'value':
				return expectedData
			else:
				raise TypeError, 'unknown expected result kind %s' % expectedKind
		else:
			return Blank()


	@expected.setter
	def expected(self, x):
		if x is None:
			self._expected.setLiteralValue( None )