示例#1
0
class TextSpanAbstractView(_TextAbstractView):
    def __init__(self, worksheet, model):
        super(TextSpanAbstractView, self).__init__(worksheet, model)
        self._styleMapLive = LiveFunction(self.__compute_style_map)

    def getStyleAttrs(self):
        return self._styleMapLive.getValue()[0]

    def getStyleSheet(self):
        return self._styleMapLive.getValue()[1]

    _styleMap = {}
    _styleMap['italic'] = lambda value: Primitive.fontItalic(bool(value))
    _styleMap['bold'] = lambda value: Primitive.fontBold(bool(value))
    _styleMap['underline'] = lambda value: Primitive.fontUnderline(bool(value))
    _styleMap['strikethrough'] = lambda value: Primitive.fontStrikethrough(
        bool(value))

    def __compute_style_map(self):
        attrs = self._model['styleAttrs']

        m = {}
        styles = []

        for a in attrs:
            key = a['name']
            value = a['value']

            m[key] = value
            styles.append(self._styleMap[key](value))

        return m, StyleSheet.style(*styles)
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))
示例#3
0
def enumSwitchButtonEditorWithLabels(live, enumType, labelTexts):
	return enumSwitchButtonEditor(live, enumType, [Label(t)   for t in labelTexts])
	@LiveFunction
	def displayLive():
		return live.getValue().ordinal()

	def _onChoice(control, prevChoice, choice):
		live.setLiteralValue(enumType.values()[choice])

	options = [Label(t)   for t in ['Larger', 'Smaller', 'Fixed', 'None']]

	return SwitchButton(options, options, SwitchButton.Orientation.HORIZONTAL, displayLive, _onChoice)



_plusStyle = StyleSheet.style(Primitive.fontBold(True), Primitive.foreground(Color(0.0, 0.6, 0.0)), Primitive.fontSize(12))

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)
示例#4
0
    def make_xml_element(self, rich_text_attributes, child):
        value = rich_text_attributes.getValue(self.tag_name, 0)
        if value:
            e = xmlmodel.XmlElem(self.tag_name)
            if child is not None:
                e.append(child)
            return e
        else:
            return child

    def store_value_from_element(self, rich_text_attributes, element):
        rich_text_attributes.putOverride(self.tag_name, True)


_italic_style = StyleSheet.instance.withValues(Primitive.fontItalic(True))
_bold_style = StyleSheet.instance.withValues(Primitive.fontBold(True))
_code_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
    Primitive.background(
        FilledOutlinePainter(Color(0.9, 0.9, 0.9), Color(0.75, 0.75, 0.75))))
_cmd_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
    Primitive.background(
        FilledOutlinePainter(Color(0.9, 0.9, 0.9), Color(0.75, 0.75, 0.75))),
    Primitive.foreground(Color(0.0, 0.5, 0.0)))
_cmd_prompt_style = StyleSheet.instance.withValues(
    Primitive.foreground(Color(0.0, 0.6, 0.5)))
_app_style = StyleSheet.instance.withValues(
    Primitive.fontItalic(True), Primitive.foreground(Color(0.5, 0.0, 0.0)))
_sys_style = StyleSheet.instance.withValues(
    Primitive.fontFace(Primitive.monospacedFontName),
示例#5
0
from BritefuryJ.Controls import Button

from BritefuryJ.Pres import Pres
from BritefuryJ.Pres.Primitive import Primitive, Label, Arrow, Spacer, Box, Row, Column
from BritefuryJ.StyleSheet import StyleSheet

from BritefuryJ.Util.Coroutine import Coroutine

from BritefuryJ.Live import LiveValue

from LarchCore.Languages.Python2.PythonCommands import pythonCommandSet, WrapSelectedStatementRangeInEmbeddedObjectAction, EmbeddedStatementAtCaretAction, chainActions
from LarchCore.Languages.Python2.Embedded import EmbeddedPython2Suite

_headerStyle = StyleSheet.style(
    Primitive.fontBold(True),
    Primitive.background(FillPainter(Color(1.0, 0.95, 0.8))),
    Primitive.rowSpacing(5.0))
_forwardArrow = Arrow(Arrow.Direction.RIGHT, 12.0)
_codeBorder = SolidBorder(1.0, 2.0, 8.0, 8.0, Color(0.75, 0.737, 0.675), None)
_stepperBorder = SolidBorder(2.0, 2.0, 8.0, 8.0, Color(0.55, 0.52, 0.4), None)
_breakPointBorder = SolidBorder(1.0, 1.0, 5.0, 5.0, Color(0.3, 0.3, 0.3),
                                Color(0.85, 0.85, 0.85))
_breakPointCurrentBorder = SolidBorder(1.0, 1.0, 5.0, 5.0,
                                       Color(0.0, 0.4, 0.0),
                                       Color(0.85, 1.0, 0.85))
_breakPointStyle = StyleSheet.style(Primitive.fontSize(10))
_breakPointArrow = Arrow(Arrow.Direction.RIGHT, 8.0)


class StepperCode(object):
示例#6
0
class PythonEditorStyle(object):
    pythonEditor = AttributeNamespace('pythonEditor')

    _pythonCodeFont = 'Noto Sans; SansSerif'

    #keywordStyle = InheritedAttributeNonNull( pythonEditor, 'keywordStyle', StyleSheet,
    #StyleSheet.style( Primitive.fontFace( _pythonCodeFont ), Primitive.fontSize( 14 ), Primitive.fontBold( True ),
    #Primitive.foreground( Color( 0.25, 0.0, 0.5 ) ), Primitive.fontSmallCaps( True ) )

    keywordStyle = InheritedAttributeNonNull(
        pythonEditor, 'keywordStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14), Primitive.fontBold(True),
                         Primitive.foreground(Color(0.25, 0.0, 0.5))))
    literalFormatStyle = InheritedAttributeNonNull(
        pythonEditor, 'literalFormatStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.25, 0.25))))
    quotationStyle = InheritedAttributeNonNull(
        pythonEditor, 'quotationStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.0, 0.5))))
    stringLiteralStyle = InheritedAttributeNonNull(
        pythonEditor, 'stringLiteralStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.25, 0.0, 0.5))))
    stringLiteralEscapeStyle = InheritedAttributeNonNull(
        pythonEditor, 'stringLiteralEscapeStyle', StyleSheet,
        StyleSheet.style(
            Primitive.fontFace(_pythonCodeFont), Primitive.fontSize(14),
            Primitive.foreground(Color(0.25, 0.2, 0.15)),
            Primitive.border(
                SolidBorder(1.0, 1.0, 4.0, 4.0, Color(0.75, 0.6, 0.5),
                            Color(1.0, 0.85, 0.75)))))
    numLiteralStyle = InheritedAttributeNonNull(
        pythonEditor, 'numLiteralStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.5, 0.5))))
    punctuationStyle = InheritedAttributeNonNull(
        pythonEditor, 'punctuationStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.0, 1.0))))
    delimStyle = InheritedAttributeNonNull(
        pythonEditor, 'delimStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.0, 1.0))))
    targetStyle = InheritedAttributeNonNull(
        pythonEditor, 'targetStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    varStyle = InheritedAttributeNonNull(
        pythonEditor, 'varStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    attributeStyle = InheritedAttributeNonNull(
        pythonEditor, 'attributeStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    kwNameStyle = InheritedAttributeNonNull(
        pythonEditor, 'kwNameStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    operatorStyle = InheritedAttributeNonNull(
        pythonEditor, 'operatorStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontBold(True), Primitive.fontSize(14),
                         Primitive.foreground(Color(0.0, 0.5, 0.0))))
    paramStyle = InheritedAttributeNonNull(
        pythonEditor, 'paramStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    importStyle = InheritedAttributeNonNull(
        pythonEditor, 'importStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black)))
    commentStyle = InheritedAttributeNonNull(
        pythonEditor, 'commentStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color(0.4, 0.4, 0.4))))
    unparseableStyle = InheritedAttributeNonNull(
        pythonEditor, 'unparseableStyle', StyleSheet,
        StyleSheet.style(Primitive.fontFace(_pythonCodeFont),
                         Primitive.fontSize(14),
                         Primitive.foreground(Color.black),
                         Primitive.textSquiggleUnderlinePaint(Color.red)))

    sequenceStyle = InheritedAttributeNonNull(
        pythonEditor, 'sequenceStyle', StyleSheet,
        StyleSheet.style(Sequence.addLineBreaks(True),
                         Sequence.matchOuterIndentation(True),
                         Sequence.addLineBreakCost(True)))

    quoteBorderStyle = InheritedAttributeNonNull(
        pythonEditor, 'quoteBorderStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 5.0, 5.0, Color(0.5, 0.3, 0.7), None))))
    quoteTitleStyle = InheritedAttributeNonNull(
        pythonEditor, 'quoteTitleStyle', StyleSheet,
        StyleSheet.style(Primitive.foreground(Color(0.3, 0.1, 0.5)),
                         Primitive.fontSize(10)))

    unquoteBorderStyle = InheritedAttributeNonNull(
        pythonEditor, 'unquoteBorderStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 5.0, 5.0, Color(1.0, 0.5, 0.3), None))))
    unquoteTitleStyle = InheritedAttributeNonNull(
        pythonEditor, 'unquoteTitleStyle', StyleSheet,
        StyleSheet.style(Primitive.foreground(Color(0.7, 0.35, 0.0)),
                         Primitive.fontSize(10)))

    externalExprBorderStyle = InheritedAttributeNonNull(
        pythonEditor, 'externalExprBorderStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 5.0, 5.0, Color(0.3, 0.7, 1.0), None))))
    externalExprTitleStyle = InheritedAttributeNonNull(
        pythonEditor, 'externalExprTitleStyle', StyleSheet,
        StyleSheet.style(Primitive.foreground(Color(0.0, 0.5, 1.0)),
                         Primitive.fontSize(10)))

    embeddedObjectBorder = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectBorder', AbstractBorder,
        SolidBorder(1.5, 1.5, 4.0, 4.0, Color(0.6, 0.65, 0.8), None))
    embeddedObjectLiteralBorder = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectLiteralBorder', AbstractBorder,
        SolidBorder(1.5, 1.5, 4.0, 4.0, Color(0.4, 0.433, 0.533), None))
    embeddedObjectTagLabelStyle = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectTagLabelStyle', StyleSheet,
        StyleSheet.style(Primitive.foreground(Color(0.0, 0.0, 0.0, 0.6)),
                         Primitive.fontSize(9)))
    embeddedObjectTagBorder = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectTagBorder', AbstractBorder,
        SolidBorder(1.0, 1.0, 3.0, 3.0, Color(0.45, 0.4, 0.533),
                    Color(0.925, 0.9, 0.95)))
    embeddedObjectLineStyle = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectLineStyle', StyleSheet,
        StyleSheet.style(
            Primitive.shapePainter(FillPainter(Color(0.1, 0.2, 0.3)))))
    embeddedObjectExpansionLabelStyle = InheritedAttributeNonNull(
        pythonEditor, 'embeddedObjectExpansionLabelStyle', StyleSheet,
        StyleSheet.style(Primitive.fontSize(10)))

    paragraphIndentationStyle = InheritedAttributeNonNull(
        pythonEditor, 'paragraphIndentationStyle', StyleSheet,
        StyleSheet.style(Primitive.paragraphIndentation(40.0)))

    solidHighlightRounding = InheritedAttributeNonNull(
        pythonEditor, 'solidHighlightRounding', float, 3.0)
    outlineHighlightThickness = InheritedAttributeNonNull(
        pythonEditor, 'outlineHighlightThickness', float, 1.5)
    outlineHighlightInset = InheritedAttributeNonNull(pythonEditor,
                                                      'outlineHighlightInset',
                                                      float, 2.0)
    outlineHighlightRounding = InheritedAttributeNonNull(
        pythonEditor, 'outlineHighlightRounding', float, 5.0)

    defStmtHighlightColour = InheritedAttributeNonNull(
        pythonEditor, 'defStmtHighlightColour', Color,
        Color(0.420, 0.620, 0.522))
    classStmtHighlightColour = InheritedAttributeNonNull(
        pythonEditor, 'classStmtHighlightColour', Color,
        Color(0.522, 0.420, 0.620))
    badIndentationRectanglePainter = InheritedAttributeNonNull(
        pythonEditor, 'badIndentationRectanglePainter', Painter,
        FilledOutlinePainter(lerpColour(Color.RED, Color.WHITE, 0.75),
                             lerpColour(Color.RED, Color.WHITE, 0.5)))

    comprehensionSpacing = InheritedAttributeNonNull(pythonEditor,
                                                     'comprehensionSpacing',
                                                     float, 15.0)
    conditionalSpacing = InheritedAttributeNonNull(pythonEditor,
                                                   'conditionalSpacing', float,
                                                   15.0)
    blockIndentation = InheritedAttributeNonNull(pythonEditor,
                                                 'blockIndentation', float,
                                                 30.0)

    @PyDerivedValueTable(pythonEditor)
    def _defStmtHeaderHighlightStyle(style):
        border = _solidHighlightBorder(
            style, style.get(PythonEditorStyle.defStmtHighlightColour))
        return style.withValues(Primitive.border(border))

    @PyDerivedValueTable(pythonEditor)
    def _defStmtHighlightStyle(style):
        border = _outlineHighlightBorder(
            style, style.get(PythonEditorStyle.defStmtHighlightColour))
        return style.withValues(Primitive.border(border))

    @PyDerivedValueTable(pythonEditor)
    def _classStmtHeaderHighlightStyle(style):
        border = _solidHighlightBorder(
            style, style.get(PythonEditorStyle.classStmtHighlightColour))
        return style.withValues(Primitive.border(border))

    @PyDerivedValueTable(pythonEditor)
    def _classStmtHighlightStyle(style):
        border = _outlineHighlightBorder(
            style, style.get(PythonEditorStyle.classStmtHighlightColour))
        return style.withValues(Primitive.border(border))

    @PyDerivedValueTable(pythonEditor)
    def _badIndentationRectangleStyle(style):
        painter = style.get(PythonEditorStyle.badIndentationRectanglePainter)
        return style.withValues(Primitive.shapePainter(painter))
示例#7
0
def _documentContextMenuFactory(element, menu):
	region = element.getRegion()
	rootElement = element.getRootElement()
	
	def makeParagraphStyleFn(style):
		def setStyle(model):
			model.setStyle(style)
		
		def _onLink(link, event):
			caret = rootElement.getCaret()
			if caret is not None and caret.isValid():
				caretElement = caret.getElement()
				if caretElement.getRegion() is region:
					_controller.modifyParagraphAtMarker(caret.getMarker(), setStyle)
		return _onLink
	
	def insertEmbedPara(link, event):
		def _newEmbedPara():
			img = _imageFileChooser(link.element, lambda f: _ParaImage(f))
			return embed.ParaEmbed(img)   if img is not None   else None
		
		caret = rootElement.getCaret()
		if caret is not None and caret.isValid():
			caretElement = caret.getElement()
			if caretElement.getRegion() is region:
				_controller.insertParagraphAtCaret(caret, _newEmbedPara)
	
	normalStyle = Hyperlink('Normal', makeParagraphStyleFn('normal'))
	h1Style = Hyperlink('H1', makeParagraphStyleFn('h1'))
	h2Style = Hyperlink('H2', makeParagraphStyleFn('h2'))
	h3Style = Hyperlink('H3', makeParagraphStyleFn('h3'))
	h4Style = Hyperlink('H4', makeParagraphStyleFn('h4'))
	h5Style = Hyperlink('H5', makeParagraphStyleFn('h5'))
	h6Style = Hyperlink('H6', makeParagraphStyleFn('h6'))
	titleStyle = Hyperlink('Title', makeParagraphStyleFn('title'))
	paraStyles = ControlsRow([normalStyle, h1Style, h2Style, h3Style, h4Style, h5Style, h6Style, titleStyle])
	embedPara = Hyperlink('Embed para', insertEmbedPara)
	paraEmbeds = ControlsRow([embedPara])
	menu.add(Section(SectionHeading2('Paragraph styles'), paraStyles))
	menu.add(Section(SectionHeading2('Paragraph embeds'), paraEmbeds))
	
	
	def makeStyleFn(attrName):
		def computeStyleValues(listOfSpanAttrs):
			value = listOfSpanAttrs[0].getValue(attrName, 0)
			value = not value
			attrs = RichTextAttributes()
			attrs.putOverride(attrName, value)
			return attrs
		
		def onButton(button, event):
			selection = rootElement.getSelection()
			if isinstance(selection, TextSelection):
				if selection.getRegion() == region:
					_controller.applyStyleToSelection(selection, computeStyleValues)
		return onButton
	
	def _onInsertInlineEmbed(button, event):
		def _newInlineEmbedValue():
			return _imageFileChooser(button.element, lambda f: _InlineImage(f))
		
		caret = rootElement.getCaret()
		if caret is not None and caret.isValid():
			caretElement = caret.getElement()
			if caretElement.getRegion() is region:
				_controller.insertInlineEmbedAtMarker(caret.getMarker(), _newInlineEmbedValue)
	
	def style_button(text, on_click, *style_values):
		sty = StyleSheet.instance.withValues(Primitive.fontFace(Primitive.monospacedFontName),
						     *style_values)
		return Button(sty.applyTo(Label(text)), on_click)

	italicStyle = style_button('I', makeStyleFn('i'), Primitive.fontItalic(True))
	boldStyle = style_button('B', makeStyleFn('b'), Primitive.fontBold(True))
	codeStyle = style_button('code', makeStyleFn('code'))
	cmdStyle = style_button('> cmd', makeStyleFn('cmd'))
	appStyle = style_button('app', makeStyleFn('app'))
	sysStyle = style_button('sys', makeStyleFn('sys'))
	styles = ControlsRow([italicStyle, boldStyle, codeStyle, cmdStyle, appStyle, sysStyle]).alignHLeft()
	insertInlineEmbed = Button.buttonWithLabel('Embed', _onInsertInlineEmbed)
	inlineEmbeds = ControlsRow([insertInlineEmbed]).alignHLeft()
	
	menu.add(Section(SectionHeading2('Selection styles'), styles))
	menu.add(Section(SectionHeading2('Inline embeds'), inlineEmbeds))
	
	
	return 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('()'))
    ])
示例#9
0
from LarchCore.Languages.Python2.PythonCommands import pythonCommandSet, EmbeddedStatementAtCaretAction, WrapSelectedStatementRangeInEmbeddedObjectAction, chainActions
from LarchCore.Languages.Python2.Embedded import EmbeddedPython2Suite
from LarchCore.Languages.Python2 import Schema


_nameBorder = SolidBorder( 1.0, 2.0, 5.0, 5.0, Color( 0.6, 0.6, 0.6 ), Color( 0.95, 0.95, 0.95 ) )

_notSet = StyleSheet.style( Primitive.fontItalic( True ) )( Label( 'not set' ) )




_testValueBorder = SolidBorder( 1.5, 2.5, 4.0, 4.0, Color( 0.75, 0.0, 0.0 ), None )


_comparisonStyle = StyleSheet.style( Primitive.fontBold( True ), Primitive.foreground( Color( 0.75, 0.0, 0.0 ) ) )


class TestCase (object):
	def assertEqual(self, first, second):
		if not ( first == second ):
			raise AssertionError, Row( [ _testValueBorder.surround( first ), _comparisonStyle( Label( 'not ==' ) ), _testValueBorder.surround( second ) ] )


	def assertNotEqual(self, first, second):
		if not ( first != second ):
			raise AssertionError, Row( [ _testValueBorder.surround( first ), _comparisonStyle( Label( 'not !=' ) ), _testValueBorder.surround( second ) ] )


	def assertTrue(self, first):
		if not first:
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))