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 )
Пример #2
0
class StringEditorTextArea(Editor):
    def __init__(self, model=None, value=''):
        super(StringEditorTextArea, self).__init__(model, value)
        self._commitOnChange = LiveValue(True)

    def __getstate__(self):
        state = super(StringEditorTextArea, self).__getstate__()
        state['commitOnChange'] = self._commitOnChange.getValue()
        return state

    def __setstate__(self, state):
        super(StringEditorTextArea, self).__setstate__(state)
        self._commitOnChange = LiveValue(state.get('commitOnChange', True))

    def _newModel(self, value):
        if not isinstance(value, str) and not isinstance(value, unicode):
            value = ''
        return Model(value)

    def _createSettingsPres(self):
        commitOnChange = Checkbox.checkboxWithLabel('Commit on change',
                                                    self._commitOnChange)
        return commitOnChange

    def buildEditorPres(self, fragment, inheritedState):
        if self._commitOnChange.getValue():
            return TextArea.textAreaCommitOnChange(self._model.liveValue)
        else:
            return TextArea(self._model.liveValue)
	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
Пример #4
0
 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 currentComponentEditor(rootElement):
	# Components under pointer
	target = rootElement.getTarget()
	target = target   if target.isValid()  and  isinstance(target, GUIEditorTarget)   else None

	currentComponent = LiveValue()

	# Component UI
	def refreshComponent(component):
		currentComponent.setLiteralValue(component)

	targetListener = GUITargetListener(refreshComponent)

	refreshComponent(target.component   if target is not None   else None)


	@LiveFunction
	def currentComponentUI():
		component = currentComponent.getValue()
		if component is not None:
			editUI = component._editUI()
			return Section(SectionHeading3(component.componentName), editUI)
		else:
			return Blank()


	componentUI = targetListener.tieToLifeTimeOf(currentComponentUI, rootElement)
	return componentUI
Пример #6
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)
Пример #7
0
def _collapsibleFontChooser(title, choiceValue, sampleFn):
    expanded = LiveValue(False)

    @LiveFunction
    def currentChoice():
        return _headerNameStyle(Label(choiceValue.getValue()))

    header = Row([Label(title), Spacer(25.0, 0.0), currentChoice]).alignHPack()

    return DropDownExpander(
        header,
        ScrolledViewport(_fontChooser(choiceValue, sampleFn), 800.0, 400.0,
                         None), expanded).alignHExpand()
    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)
Пример #9
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 )
Пример #10
0
def optionalTypedEditor(live, initialValue, editorFn):
	valueEditor = LiveValue(editorFn(live))

	@LiveFunction
	def editor():
		x = live.getValue()

		if x is None:
			def on_add(button, event):
				live.setLiteralValue(initialValue)
			return Button(_plusStyle(Label('+')), on_add).alignHPack()
		else:
			def on_delete(button, event):
				live.setLiteralValue(None)

			deleteButton = Button(Image.systemIcon('delete'), on_delete)

			return Row([deleteButton.alignHPack(), Spacer(5.0, 0.0).alignHPack(), valueEditor])

	return editor
Пример #11
0
class GUIFlowGrid(GUISequenceComponent):
    componentName = 'Flow grid'

    #targetNumColumns = IntEvalField()

    def __init__(self, targetNumColumns=None):
        super(GUIFlowGrid, self).__init__()
        self._targetNumColumns = LiveValue(targetNumColumns)

    def _presentSequenceContents(self, contents, fragment, inheritedState):
        return FlowGrid(contents)

    def __component_py_evalmodel__(self, codeGen):
        flowGrid = codeGen.embeddedValue(FlowGrid)
        targetNumColumns = self._targetNumColumns.getValue()
        args = []
        if targetNumColumns is not None:
            args.append(Py.IntLiteral(value=repr(targetNumColumns)))
        args.append(self._py_evalmodel_forChildren(codeGen))
        return Py.Call(target=flowGrid, args=args)
Пример #12
0
 def __setstate__(self, state):
     super(FontConfigurationPage, self).__setstate__(state)
     self._config = state.get('config')
     self._userConfig = LiveValue(self._config)
Пример #13
0
 def __init__(self):
     super(FontConfigurationPage, self).__init__()
     self._config = None
     self._userConfig = LiveValue(self._config)
Пример #14
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))
Пример #15
0
 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'))
Пример #16
0
	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()
Пример #17
0
    def Page(self, fragment, inheritedState, page):
        root = page.rootNode
        if root is None:
            raise RuntimeError, 'No root node'
        isFrontPage = root.frontPage is page
        isStartupPage = root.startupPage is page

        class _RenameListener(TextEntry.TextEntryListener):
            def onAccept(self, textEntry, text):
                page.name = text

            def onCancel(self, textEntry, originalText):
                nameLive.setLiteralValue(nameBox)

        def _onRename(menuItem):
            textEntry = TextEntry(page.name, _RenameListener()).regexValidated(
                _nameRegex, 'Please enter a valid identifier')
            textEntry.grabCaretOnRealise()
            nameLive.setLiteralValue(textEntry)

        def _onDelete(menuItem):
            if page.parent is not None:
                page.parent.remove(page)

        def _onClearFrontPage(menuItem):
            root.frontPage = None

        def _onSetAsFrontPage(menuItem):
            root.frontPage = page

        def _onClearStartupPage(menuItem):
            root.startupPage = None

        def _onSetAsStartupPage(menuItem):
            root.startupPage = page

        def _pageContextMenuFactory(element, menu):
            menu.add(MenuItem.menuItemWithLabel('Rename', _onRename))
            menu.add(HSeparator())
            menu.add(MenuItem.menuItemWithLabel('Delete', _onDelete))
            menu.add(HSeparator())

            if isFrontPage:
                menu.add(
                    MenuItem.menuItemWithLabel('Clear front page',
                                               _onClearFrontPage))
            else:
                menu.add(
                    MenuItem.menuItemWithLabel('Set as front page',
                                               _onSetAsFrontPage))

            if isStartupPage:
                menu.add(
                    MenuItem.menuItemWithLabel('Clear startup page',
                                               _onClearStartupPage))
            else:
                menu.add(
                    MenuItem.menuItemWithLabel('Set as startup page',
                                               _onSetAsStartupPage))

            return True

        pageSubject = fragment.subject._pageSubject(page)

        link = Hyperlink(page.name, pageSubject)
        link = link.withContextMenuInteractor(_pageContextMenuFactory)
        nameBox = _itemHoverHighlightStyle.applyTo(Row([link]))
        nameBox = _ProjectTreeController.instance.item(page, nameBox)
        nameBox = nameBox.withDragSource(_linkDragSource)
        nameBox = AttachTooltip(
            nameBox,
            'Click to enter page.\nRight click to access context menu.', False)

        nameLive = LiveValue(nameBox)

        if isFrontPage or isStartupPage:
            notes = []
            if isFrontPage:
                notes.append(
                    _frontPageNoteBorder.surround(
                        _frontPageNoteStyle.applyTo(Label('Front page'))))
            if isStartupPage:
                notes.append(
                    _startupPageNoteBorder.surround(
                        _startupPageNoteStyle.applyTo(Label('Startup page'))))
            notesPres = _notesRowStyle.applyTo(Row(notes))
            pagePres = Row([nameLive, notesPres.padX(_notesGap, 0.0)])
        else:
            pagePres = nameLive

        return pagePres
Пример #18
0
 def __init__(self):
     self.__change_history__ = None
     self._isCurrent = LiveValue(False)
	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 ] )
Пример #20
0
	def __setstate__(self, state):
		value = state['value']
		self._live = LiveValue( value )
Пример #21
0
	def __init__(self, value=None):
		self._live = LiveValue( value )
Пример #22
0
 def __init__(self, model=None, value=''):
     super(StringEditorTextArea, self).__init__(model, value)
     self._commitOnChange = LiveValue(True)
Пример #23
0
 def __setstate__(self, state):
     super(StringEditorTextArea, self).__setstate__(state)
     self._commitOnChange = LiveValue(state.get('commitOnChange', True))
Пример #24
0
 def __setstate__(self, state):
     self.__change_history__ = None
     self._isCurrent = LiveValue(False)
Пример #25
0
 def __init__(self, targetNumColumns=None):
     super(GUIFlowGrid, self).__init__()
     self._targetNumColumns = LiveValue(targetNumColumns)
Пример #26
0
    def Package(self, fragment, inheritedState, package):
        def _addPackage(menuItem):
            package.append(ProjectPackage('NewPackage'))

        class _RenameListener(TextEntry.TextEntryListener):
            def onAccept(self, textEntry, text):
                package.name = text

            def onCancel(self, textEntry, originalText):
                nameLive.setLiteralValue(nameBox)

        def _onRename(menuItem):
            textEntry = TextEntry(package.name,
                                  _RenameListener()).regexValidated(
                                      _nameRegex,
                                      'Please enter a valid identifier')
            textEntry.grabCaretOnRealise()
            nameLive.setLiteralValue(textEntry)

        def _onDelete(menuItem):
            if package.parent is not None:
                package.parent.remove(package)

        def _addPage(page):
            package.append(page)

        def _packageContextMenuFactory(element, menu):
            menu.add(MenuItem.menuItemWithLabel('New package', _addPackage))
            newPageMenu = PageData.newPageMenu(_addPage)
            importPageMenu = PageData.importPageMenu(
                element.getRootElement().getComponent(), _addPage)
            menu.add(
                MenuItem.menuItemWithLabel(
                    'New page', newPageMenu,
                    MenuItem.SubmenuPopupDirection.RIGHT))
            menu.add(
                MenuItem.menuItemWithLabel(
                    'Import page', importPageMenu,
                    MenuItem.SubmenuPopupDirection.RIGHT))
            menu.add(HSeparator())
            menu.add(MenuItem.menuItemWithLabel('Rename', _onRename))
            menu.add(HSeparator())
            menu.add(MenuItem.menuItemWithLabel('Delete', _onDelete))
            return True

        nameElement = _packageNameStyle.applyTo(StaticText(package.name))
        nameBox = _itemHoverHighlightStyle.applyTo(
            Row([
                _packageIcon.padX(5.0).alignHPack().alignVCentre(),
                nameElement.alignVCentre()
            ]))

        # Set drop destination and place in box that is h-packed, otherwise attempting to drop items as children could require the user to
        # drop somewhere off to the right of the package, since the h-expand applied further up the presentation tree will expand it beyond
        # its visible bounds
        nameBox = Bin(nameBox).alignHPack()

        nameBox = nameBox.withContextMenuInteractor(_packageContextMenuFactory)
        nameBox = _ProjectTreeController.instance.nestedListItem(
            package, package, nameBox)
        nameBox = AttachTooltip(nameBox, 'Right click to access context menu.',
                                False)

        nameLive = LiveValue(nameBox)
        itemsBox = Column(package[:])
        itemsBox = _ProjectTreeController.instance.editableList(
            package, itemsBox)

        return Column([
            nameLive,
            itemsBox.padX(_packageContentsIndentation, 0.0).alignHExpand()
        ])
Пример #27
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))
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 )