Пример #1
0
class XmlElemSpan(abstract_text.MRTAbstractText):
    contents_query = elem_query.children()\
     .map(abstract_text.remove_whitespace, elem.identity)\
     .project_to_objects(mappings.text_mapping)

    def __init__(self, projection_table, elem, contents=None):
        super(XmlElemSpan, self).__init__(projection_table, elem, contents)
        elem_tag_and_attrs = XmlElemTagAndAttrs.from_xml_elem(elem)
        self._elem_tag_and_attrs = elem_tag_and_attrs
        self._editorModel = controller.MallardRichTextController.instance.editorModelSpan(
            [], self._span_attrs(elem_tag_and_attrs))

    def node_init(self):
        self._editorModel.setModelContents(
            controller.MallardRichTextController.instance,
            list(self.contents_query))

    def setElementTagAndAttrs(self, elem_tag_and_attrs):
        self._elem_tag_and_attrs = elem_tag_and_attrs
        self._editorModel.setSpanAttrs(self._span_attrs(elem_tag_and_attrs))
        self._incr.onChanged()

    def getElementTagAndAttrs(self):
        self._incr.onAccess()
        return self._elem_tag_and_attrs

    def __present__(self, fragment, inheritedState):
        self._incr.onAccess()
        open_tag = self._tag_border.surround(
            self._open_tag_style(Label(self._elem_tag_and_attrs.tag)))
        close_tag = self._tag_border.surround(
            self._close_tag_style(Label('/' + self._elem_tag_and_attrs.tag)))
        x = RichSpan([open_tag] + list(self.contents_query) + [close_tag])
        x = controller.MallardRichTextController.instance.editableSpan(self, x)
        return x

    @staticmethod
    def _span_attrs(elem_tag_and_attrs):
        return RichTextAttributes.fromValues(None,
                                             {XML_ELEM: [elem_tag_and_attrs]})

    @staticmethod
    def new_span(mapping, contents, elem_tag_and_attrs):
        return XmlElemSpan(mapping, elem_tag_and_attrs.create_xml_elem(),
                           contents)

    _tag_border = SolidBorder(1.0, 1.0, 4.0, 4.0, Color(0.4, 0.42, 0.45),
                              Color(0.95, 0.975, 1.0))
    _open_tag_style = StyleSheet.style(
        Primitive.fontSize(10), Primitive.foreground(Color(0.0, 0.3, 0.8)),
        Primitive.fontFace('Monospaced'))
    _close_tag_style = StyleSheet.style(
        Primitive.fontSize(10), Primitive.foreground(Color(0.3, 0.35, 0.4)),
        Primitive.fontFace('Monospaced'))
class ExecutionStyle(object):
    pythonExecution = AttributeNamespace('pythonExecution')

    labelStyle = InheritedAttributeNonNull(
        pythonExecution, 'labelStyle', StyleSheet,
        StyleSheet.style(Primitive.fontSize(10)))

    stdOutStyle = InheritedAttributeNonNull(
        pythonExecution, 'stdOutStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 7.0, 7.0, Color(0.5, 1.0, 0.5),
                            Color(0.9, 1.0, 0.9))),
            Primitive.foreground(Color(0.0, 0.5, 0.0))))
    stdErrStyle = InheritedAttributeNonNull(
        pythonExecution, 'stdErrStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 7.0, 7.0, Color(1.0, 0.75, 0.5),
                            Color(1.0, 0.95, 0.9))),
            Primitive.foreground(Color(0.75, 0.375, 0.0))))
    exceptionBorderStyle = InheritedAttributeNonNull(
        pythonExecution, 'exceptionBorderStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 7.0, 7.0, Color(0.8, 0.0, 0.0),
                            Color(1.0, 0.9, 0.9)))))
    resultBorderStyle = InheritedAttributeNonNull(
        pythonExecution, 'resultBorderStyle', StyleSheet,
        StyleSheet.style(
            Primitive.border(
                SolidBorder(1.0, 3.0, 10.0, 10.0, Color(0.0, 0.0, 0.8),
                            Color.WHITE))))

    resultBoxStyle = InheritedAttributeNonNull(
        pythonExecution, 'resultSpacing', StyleSheet,
        StyleSheet.style(Primitive.columnSpacing(5.0)))

    @PyDerivedValueTable(pythonExecution)
    def _resultBoxStyle(style):
        resultSpacing = style.get(ExecutionStyle.resultSpacing)
        return style.withValues(Primitive.columnSpacing(resultSpacing))
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))
Пример #4
0
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)))
Пример #5
0
from BritefuryJ.LSpace.Interactor import PushElementInteractor
from BritefuryJ.LSpace.Input import Modifier

from BritefuryJ.Live import LiveValue, LiveFunction

from Britefury.Config.UserConfig import loadUserConfig, saveUserConfig
from Britefury.Config import Configuration
from Britefury.Config.ConfigurationPage import ConfigurationPage

# Font chooser

_ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
_fontNames = sorted([font.name for font in _ge.allFonts])

_nameStyle = StyleSheet.style(Primitive.fontSize(10),
                              Primitive.foreground(Color(0.45, 0.45, 0.45)))
_hoverStyle = StyleSheet.style(
    Primitive.hoverBackground(
        FilledOutlinePainter(Color(0.95, 0.95, 0.95), Color(0.65, 0.65,
                                                            0.65))))
_headerNameStyle = StyleSheet.style(Primitive.fontItalic(True))


def _fontSample(fontName, sampleFn):
    sample = sampleFn(fontName)
    name = Label(fontName)
    return _hoverStyle(
        Bin(
            Column([
                sample,
                _nameStyle(name).padX(10.0, 0.0),
Пример #6
0
from BritefuryJ.Pres.Primitive import Primitive, Label, Row
from BritefuryJ.Pres.UI import Form

from BritefuryJ.StyleSheet import StyleSheet

from LarchCore.Languages.Python2 import Schema as Py
from LarchCore.Languages.Python2.Embedded import EmbeddedPython2Expr

from LarchTools.PythonTools.GUIEditor.DataModel import ExprField, TypedField
from LarchTools.PythonTools.GUIEditor.LeafComponent import GUILeafComponent
from LarchTools.PythonTools.GUIEditor.ComponentPalette import paletteItem, registerPaletteSubsection

_evalLabelStyle = StyleSheet.style(Primitive.fontItalic(True),
                                   Primitive.fontSize(11),
                                   Primitive.foreground(Color(0.3, 0.4, 0.5)))
_liveEvalLabelStyle = StyleSheet.style(
    Primitive.fontItalic(True), Primitive.fontSize(11),
    Primitive.foreground(Color(0.4, 0.3, 0.5)))

_evalItemStyleF = StyleSheet.style(Primitive.fontItalic(True),
                                   Primitive.foreground(Color(0.2, 0.4, 0.6)))
_evalItemStyleParens = StyleSheet.style(
    Primitive.foreground(Color(0.4, 0.4, 0.4)))


class GUIEval(GUILeafComponent):
    componentName = 'Eval'

    expr = ExprField()
    displayedText = TypedField(str, 'expr')
from BritefuryJ.Live import LiveFunction, LiveValue

from BritefuryJ.Controls import Button, RealSpinEntry

from BritefuryJ.Pres import Pres
from BritefuryJ.Pres.Primitive import Primitive, Label, Bin, Row, Column, Table

from BritefuryJ.StyleSheet import StyleSheet

from LarchCore.Languages.Python2 import Schema as Py

from LarchTools.PythonTools.GUIEditor.DataModel import GUIObject, TypedEvalField



_uniformStyle = StyleSheet.style(Primitive.foreground(Color(0.2, 0.25, 0.3)), Primitive.fontSize(11))
_boxStyle = StyleSheet.style(Primitive.background(FilledOutlinePainter(Color(0.7, 0.75, 0.8), Color(0.6, 0.65, 0.7))), Primitive.fontSize(11), Primitive.foreground(Color(0.0, 0.0, 0.0, 0.5)), Primitive.fontItalic(True))
_tableStyle = StyleSheet.style(Primitive.tableColumnSpacing(2.0), Primitive.tableRowSpacing(2.0))
_liveLabelStyle = StyleSheet.style(Primitive.foreground(Color(0.4, 0.45, 0.5)))



class AbstractPadding (GUIObject):
	def apply(self, p):
		raise NotImplementedError, 'abstract'

	def __apply_py_evalmodel__(self, codeGen, py_p):
		raise NotImplementedError, 'abstract'


Пример #8
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)

from LarchCore.Languages.Python2 import Python2
from LarchCore.Languages.Python2.Execution.ExecutionPresCombinators import execStdout, execStderr, execException, execResult
from LarchCore.Languages.Python2.Execution import Execution




_executeShortcut = Shortcut( KeyEvent.VK_ENTER, Modifier.CTRL )
_executeNoEvalShortcut = Shortcut( KeyEvent.VK_ENTER, Modifier.CTRL | Modifier.SHIFT )
_historyPreviousShortcut = Shortcut( KeyEvent.VK_UP, Modifier.ALT )
_historyNextShortcut = Shortcut( KeyEvent.VK_DOWN, Modifier.ALT )

_bannerTextStyle = StyleSheet.style( Primitive.fontFace( 'Serif' ), Primitive.fontSmallCaps( True ), Primitive.editable( False ) )
_bannerHelpKeyTextStyle = StyleSheet.style( Primitive.fontFace( 'Serif' ), Primitive.fontSmallCaps( True ), Primitive.fontItalic( True ), Primitive.foreground( Color( 0.25, 0.25, 0.25 ) ) )
_bannerHelpTextStyle = StyleSheet.style( Primitive.fontFace( 'Serif' ), Primitive.fontItalic( True ), Primitive.foreground( Color( 0.25, 0.25, 0.25 ) ) )
_bannerBorder = SolidBorder( 2.0, 5.0, 8.0, 8.0, Color( 0.3, 0.5, 0.3 ), Color( 0.875, 0.9, 0.875 ) )


_labelStyle = StyleSheet.style( Primitive.fontSize( 10 ) )

#_blockStyle = StyleSheet.style( Primitive.columnSpacing( 2.0 ), Primitive.border( SolidBorder( 1.0, 5.0, 15.0, 15.0, Color( 0.25, 0.25, 0.25 ), Color( 0.8, 0.8, 0.8 ) ) ) )
_blockStyle = StyleSheet.style( Primitive.columnSpacing( 3.0 ), Primitive.border( SolidBorder( 1.0, 3.0, 13.0, 13.0, Color( 0.6, 0.6, 0.6 ), Color( 0.9, 0.9, 0.9 ) ) ) )
_blockOutputStyle = StyleSheet.style( Primitive.columnSpacing( 2.0 ) )

_pythonModuleBorderStyle = StyleSheet.style( Primitive.border( SolidBorder( 1.5, 5.0, 10.0, 10.0, Color( 0.65, 0.65, 0.65 ), Color.WHITE ) ) )
_dropPromptStyle = StyleSheet.style( Primitive.border( SolidBorder( 1.0, 3.0, 10.0, 10.0, Color( 0.0, 0.8, 0.0 ), None ) ) )

_varAssignVarNameStyle = StyleSheet.style( Primitive.fontItalic( True ), Primitive.foreground( Color( 0.0, 0.0, 0.5 ) ) )
_varAssignTypeNameStyle = StyleSheet.style( Primitive.foreground( Color( 0.3, 0.0, 0.3 ) ) )
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('()'))
    ])
Пример #11
0
from BritefuryJ.Live import LiveFunction, LiveValue

from BritefuryJ.Controls import Button, RealSpinEntry, ColourPicker

from BritefuryJ.Pres import Pres
from BritefuryJ.Pres.Primitive import Primitive, Label, Bin, Row, Column, Table
from BritefuryJ.Pres.UI import Form

from BritefuryJ.StyleSheet import StyleSheet

from LarchCore.Languages.Python2 import Schema as Py

from LarchTools.PythonTools.GUIEditor.DataModel import GUIObject, TypedEvalField
from LarchTools.PythonTools.GUIEditor.FieldEditor import optionalTypedEditor

_uniformStyle = StyleSheet.style(Primitive.foreground(Color(0.2, 0.25, 0.3)),
                                 Primitive.fontSize(11))
_boxStyle = StyleSheet.style(
    Primitive.background(
        FilledOutlinePainter(Color(0.7, 0.75, 0.8), Color(0.6, 0.65, 0.7))),
    Primitive.fontSize(11), Primitive.foreground(Color(0.0, 0.0, 0.0, 0.5)),
    Primitive.fontItalic(True))
_tableStyle = StyleSheet.style(Primitive.tableColumnSpacing(2.0),
                               Primitive.tableRowSpacing(2.0))
_liveLabelStyle = StyleSheet.style(Primitive.foreground(Color(0.4, 0.45, 0.5)))


class AbstractGUIBorder(GUIObject):
    def formSections(self):
        raise NotImplementedError, 'abstract'
from BritefuryJ.ObjectPresentation import PresentationStateListenerList

from BritefuryJ.DefaultPerspective import DefaultPerspective

from LarchCore.PythonConsole import Console

_fragSelectorEntryBorder = SolidBorder(1.0, 3.0, 6.0, 6.0,
                                       Color(0.8, 0.8, 0.8), None,
                                       Color(0.5, 0.5, 0.5),
                                       Color(0.9, 0.9, 0.9))

_fragContentHighlighter = ElementHighlighter(
    FilledOutlinePainter(Color(0.0, 1.0, 0.0, 0.1), Color(0.0, 0.5, 0.0, 0.5)))
_objectKindStyleJava = StyleSheet.style(
    Primitive.fontSize(10), Primitive.foreground(Color(0.0, 0.0, 0.5)))
_objectKindStylePython = StyleSheet.style(
    Primitive.fontSize(10), Primitive.foreground(Color(0.0, 0.5, 0.0)))
_objectKindStyleDocModel = StyleSheet.style(
    Primitive.fontSize(10), Primitive.foreground(Color(0.5, 0.5, 0.5)))
_consoleStyle = StyleSheet.style(Primitive.editable(True),
                                 Primitive.selectable(True))
_inspectorStyle = StyleSheet.style(Primitive.editable(False),
                                   Primitive.selectable(False))

_objectKindJava = _objectKindStyleJava(Label('Java'))
_objectKindPython = _objectKindStylePython(Label('Python'))
_objectKindDocModel = _objectKindStyleDocModel(Label('DocModel'))

_objectKindMap = {
    TypeUtils.ObjectKind.JAVA: _objectKindJava,
Пример #13
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:
        return self.factory()


class PaletteComponentDrag(Object):
    def __init__(self, factory):
        self.factory = factory

    def getItem(self):
        return self.factory()


#
#
#Control palette:
_paletteItemStyle = StyleSheet.style(
    Primitive.fontSize(11), Primitive.foreground(Color(0.3, 0.3, 0.3)),
    Primitive.background(
        FilledOutlinePainter(Color.white, Color(0.8, 0.8, 0.8))))
_paletteItemBorder = SolidBorder(1.0, 2.0, Color(0.7, 0.7, 0.7),
                                 None).highlight(Color(0.6, 0.6, 0.6),
                                                 Color(0.9, 0.9, 0.9))

_paletteSections = []


def paletteItem(contents, factoryCallable):
    p = _paletteItemStyle(_paletteItemBorder.surround(
        contents)).alignHExpand().alignVRefYExpand()
    p = p.withDragSource(
        PaletteComponentDrag,
        lambda element, aspect: PaletteComponentDrag(factoryCallable))
Пример #15
0
from java.awt import Color

from BritefuryJ.Pres.Primitive import Primitive, Label
from BritefuryJ.StyleSheet import StyleSheet
from BritefuryJ.Graphics import SolidBorder

_error_border = SolidBorder(1.0, 4.0, 5.0, 5.0, Color(1.0, 0.5, 0.5),
                            Color(1.0, 0.95, 0.95))
_error_style = StyleSheet.style(Primitive.foreground(Color(0.3, 0.0, 0.0)))


def error_message(message):
    return _error_border.surround(_error_style(Label(message)))


# Error sentinel value


class ErrorSentinel(object):
    error_message = 'Generic error'

    def __present__(self, fragment, inh):
        return error_message(self.error_message)
Пример #16
0
    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),
    Primitive.foreground(Color(0.25, 0.0, 0.5)))

italic_style_attr = BooleanStyleAttribute('i')


@italic_style_attr.apply_to_pres
def apply_italic_style(p):
    return _italic_style.applyTo(p)
from LarchTools.PythonTools.GUIEditor.DataModel import GUINode, TypedEvalField, TypedField
from LarchTools.PythonTools.GUIEditor.Properties import GUICProp
from LarchTools.PythonTools.GUIEditor.Target import GUITargetInteractor, GUIScrollInteractor
from LarchTools.PythonTools.GUIEditor.ContextMenu import componentContextMenu
from LarchTools.PythonTools.GUIEditor.Padding import AbstractPadding, UniformPadding, NonUniformPadding

componentBorder = SolidBorder(1.0, 2.0, Color(0.8, 0.8, 0.8), None)


def blankCallModel(codeGen):
    blank = codeGen.embeddedValue(Blank)
    return Py.Call(target=blank, args=[])


_noAlignmentStyle = StyleSheet.style(
    Primitive.foreground(Color(0.4, 0.4, 0.4)), Primitive.fontSize(11))


def _hAlignmentEditor(live):
    @LiveFunction
    def displayLive():
        x = live.getValue()
        if x is None:
            return 0
        else:
            return x.ordinal() + 1

    options = [
        _noAlignmentStyle(Label('None')),
        Label('Pack'),
        Label('Left'),
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 ) )
Пример #19
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))
Пример #20
0
            model)
    fragment = element.fragmentContext
    pageSubject = fragment.subject._pageSubject(model)
    return pageSubject


def _dragSourceCreateLink(element, aspect):
    return LinkSubjectDrag(_getSubjectOfPageNameElement(element))


_linkDragSource = ObjectDndHandler.DragSource(LinkSubjectDrag,
                                              _dragSourceCreateLink)

_controlsStyle = StyleSheet.style(Controls.bClosePopupOnActivate(True))
_projectIndexNameStyle = StyleSheet.style(
    Primitive.foreground(Color(0.25, 0.35, 0.5)), Primitive.fontSize(16),
    Primitive.fontFace(Primitive.lightFontName))
_packageNameStyle = StyleSheet.style(
    Primitive.foreground(Color(0.0, 0.0, 0.5)), Primitive.fontSize(14),
    Primitive.fontFace(Primitive.lightFontName))
_itemHoverHighlightStyle = StyleSheet.style(
    Primitive.hoverBackground(
        FilledOutlinePainter(Color(0.8, 0.825, 0.9),
                             Color(0.125, 0.341, 0.574), BasicStroke(1.0))))
_pythonPackageNameStyle = StyleSheet.style(
    Primitive.foreground(Color(0.0, 0.0, 0.5)))
_pythonPackageNameNotSetStyle = StyleSheet.style(
    Primitive.foreground(Color(0.5, 0.0, 0.0)))
_pythonPackageNameNotSetCommentStyle = StyleSheet.style(
    Primitive.foreground(Color(0.2, 0.2, 0.2)), Primitive.fontItalic(True))
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)))
from BritefuryJ.Editor.List import EditableListController

from Britefury.Util.LiveList import LiveList

from LarchCore.Languages.Python2 import Schema as Py

from LarchTools.PythonTools.GUIEditor.DataModel import ChildField, ChildListField
from LarchTools.PythonTools.GUIEditor.Component import GUIComponent
from LarchTools.PythonTools.GUIEditor.ComponentPalette import PaletteComponentDrag

#
#Sequential components:
_emptyStyle = StyleSheet.style(Primitive.fontItalic(True),
                               Primitive.fontSize(10),
                               Primitive.foreground(Color(0.4, 0.4, 0.4)))
emptyLabel = _emptyStyle(Label('<empty>'))


class GUIBranchComponent(GUIComponent):
    def removeChild(self, child):
        raise NotImplementedError, 'abstract'

    def getNextSiblingOf(self, child):
        raise NotImplementedError, 'abstract'


class GUIUnaryBranchComponent(GUIBranchComponent):
    child = ChildField()

    def removeChild(self, child):
from BritefuryJ.Editor.Table.ObjectList import AttributeColumn, ObjectListTableEditor

from BritefuryJ.StyleSheet import StyleSheet

from Britefury.Util.LiveList import LiveList
from Britefury.Util.UniqueNameTable import UniqueNameTable
from BritefuryJ.Util.Jython import JythonException

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

from LarchTools.PythonTools.InlineTest.InlineTest import AbstractInlineTest, inlineTestCommandSet


_resultFailStyle = StyleSheet.style( Primitive.foreground( Color( 0.5, 0.4, 0.0 ) ) )
_resultPass = StyleSheet.style( Primitive.foreground( Color( 0.0, 0.5, 0.0 ) ) ).applyTo( Label( 'PASS' ) )
_resultNone = StyleSheet.style( Primitive.foreground( Color( 0.4, 0.4, 0.4 ) ) ).applyTo( Label( 'NONE' ) )




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 )
Пример #24
0
from BritefuryJ.DefaultPerspective import DefaultPerspective
from BritefuryJ.Projection import TransientSubject
from Britefury.Kernel.Document import Document

from LarchCore.MainApp.MainAppViewer.View import perspective
from LarchCore.MainApp.MainAppViewer.AboutPage import AboutPage

from Britefury import app_in_jar

from main_app import editor_page



_page_style = StyleSheet.style(Primitive.selectable(False), Primitive.editable(False))
_dir_style = StyleSheet.style(Primitive.foreground(Color(0.0, 0.2, 0.4)))



def _get_examples():
	names_and_bytes = None

	# z is the zip file containing the examples
	z = None
	if app_in_jar.startedFromJar():
		# App started from JAR; attempt to acquire through java.lang.Class.getResourceAsStream()
		stream = Column.getResourceAsStream('/mallard_examples.zip')

		if stream is not None:
			# Convert to cStringIO; FileUtil.wrap does not seem to work well with ZipFile
			fbytes = StringUtil.fromBytes(FileUtil.readBytes(stream))
Пример #25
0
class XmlElem(object):
    """
	A live XML element
	"""
    def __init__(self, tag, **attrs):
        """
		Constructor

		:param tag: the tag of the element
		:param attrs: element attributes in kwarg (dictionary) form
		"""
        self.__tag = tag
        self.__attrs = ElemAttrs(attrs)
        self.__contents = projected_list.LiveProjectedList()

    def __eq__(self, other):
        if isinstance(other, XmlElem):
            return self.__contents == other.__contents and self.__attrs == other.__attrs
        else:
            return NotImplemented

    def __ne__(self, other):
        if isinstance(other, XmlElem):
            return self.__contents != other.__contents or self.__attrs != other.__attrs
        else:
            return NotImplemented

    @property
    def tag(self):
        return self.__tag

    @property
    def attrs(self):
        return self.__attrs

    @property
    def contents(self):
        return self.__contents

    def is_textual(self):
        for x in self.__contents:
            if not isinstance(x, basestring):
                return False
        return True

    @property
    def as_text(self):
        for x in self.__contents:
            if not isinstance(x, basestring):
                raise XmlElemHasNonTextContentError, 'XML node tagged {0} has non-text content'.format(
                    self.__tag)
        return ''.join(self.__contents[:])

    @property
    def as_text_live(self):
        @LiveFunction
        def as_t():
            return self.as_text

        return as_t

    def __iter__(self):
        return iter(self.__contents)

    def append(self, x):
        self.__contents.append(x)
        return self

    def extend(self, xs):
        self.__contents.extend(xs)
        return self

    def children(self, __selector=None, __text=False, **attrs):
        """
		Get the children, optionally filtered

		:param __selector: either 1) a tag name, 2) a list or tuple of tag names, or 3) a callable that is called with the element to test passed as a parameter
		:param __text: if True, the test will only pass if elem is text
		:param attrs: a dictionary mapping attribute names to values; an element will pass the test if its attributes are a superset of those in attrs
		:return: a list of children
		"""
        children = []
        for x in self.__contents:
            if _test(x, __selector, __text, attrs):
                children.append(x)
        return children

    def children_projected(self, __selector=None, __text=False, **attrs):
        """
		Get a live projected list of children, optionally filtered

		:param __selector: either 1) a tag name, 2) a list or tuple of tag names, or 3) a callable that is called with the element to test passed as a parameter
		:param __text: if True, the test will only pass if elem is text
		:param attrs: a dictionary mapping attribute names to values; an element will pass the test if its attributes are a superset of those in attrs
		:return: a live projected list of children
		"""
        return self.__contents.filter(
            lambda x: _test(x, __selector, __text, attrs))

    def child(self, __selector=None, __text=False, **attrs):
        """
		Get a single child that matches the filter conditions.

		:param __selector: either 1) a tag name, 2) a list or tuple of tag names, or 3) a callable that is called with the element to test passed as a parameter
		:param __text: if True, the test will only pass if elem is text
		:param attrs: a dictionary mapping attribute names to values; an element will pass the test if its attributes are a superset of those in attrs
		:return: a list of children

		raises XmlElemMultipleChildrenMatchSelectorError if multiple children match the filter conditions
		raises XmlElemNoChildMatchesSelector if no children match the filter conditions
		"""
        child = None
        for x in self.__contents:
            if _test(x, __selector, __text, attrs):
                if child is not None:
                    raise XmlElemMultipleChildrenMatchSelectorError
                child = x
        if child is None:
            raise XmlElemNoChildMatchesSelector
        return child

    def __present__(self, fragment, inh):
        space = Label(' ')
        open_angle = self._punc_style.applyTo(Label('<'))
        close_angle = self._punc_style.applyTo(Label('>'))
        slash = self._punc_style.applyTo(Label('/'))
        tag = self._tag_style.applyTo(Label(self.__tag))
        br = LineBreak()

        complex = False
        for x in self.__contents:
            if isinstance(x, XmlElem):
                complex = True
                break

        if complex:
            end = Row([open_angle, slash, tag, close_angle])
            content = Column(
                [NormalText([x]) for x in self.__contents if x != ''])
            if len(self.__attrs) == 0:
                start = Row([open_angle, tag, close_angle])
            else:
                start = Paragraph(
                    [open_angle, tag, space, br, self.__attrs, close_angle])
            return Column([start, content.padX(20.0, 0.0), end])
        else:
            if len(self.__contents) == 0:
                if len(self.__attrs) == 0:
                    return Row([open_angle, tag, slash, close_angle])
                else:
                    return Paragraph([
                        open_angle, tag, space, br, self.__attrs, slash,
                        close_angle
                    ])
            else:
                end = Row([open_angle, slash, tag, close_angle])
                content = [RichSpan([x]) for x in self.__contents]
                if len(self.__attrs) == 0:
                    start = Row([open_angle, tag, close_angle])
                else:
                    start = Span([
                        open_angle, tag, space, br, self.__attrs, close_angle
                    ])
                return Paragraph([start] + content + [end])

    def _write_sax(self, sax_handler):
        sax_handler.startElement(self.__tag, self.__attrs.attrs_dict())
        for x in self.__contents:
            if isinstance(x, basestring):
                sax_handler.characters(x)
            elif isinstance(x, XmlElem):
                x._write_sax(sax_handler)
            else:
                raise TypeError, 'Invalid content of type {0}'.format(type(x))
        sax_handler.endElement(self.__tag)

    @staticmethod
    def from_file(f):
        handler = _ReadHandler()
        xml.sax.parse(f, handler)
        return handler._root

    @staticmethod
    def from_string(s):
        handler = _ReadHandler()
        xml.sax.parseString(s, handler)
        return handler._root

    def write(self, f):
        generator = xml.sax.saxutils.XMLGenerator(f)
        generator.startDocument()
        self._write_sax(generator)
        generator.endDocument()

    def write_as_string(self):
        out = StringIO.StringIO()
        generator = xml.sax.saxutils.XMLGenerator(out)
        generator.startDocument()
        self._write_sax(generator)
        generator.endDocument()
        return out.getvalue()

    _punc_style = StyleSheet.style(Primitive.foreground(Color(0.7, 0.7, 0.7)))
    _tag_style = StyleSheet.style(Primitive.foreground(Color(0.0, 0.3, 0.7)))
Пример #26
0
from BritefuryJ.Editor.SyntaxRecognizing.SyntaxRecognizingController import EditMode



from LarchTools.PythonTools.VisualRegex import Schema
from LarchTools.PythonTools.VisualRegex.Parser import VisualRegexGrammar
from LarchTools.PythonTools.VisualRegex.SRController import VisualRegexSyntaxRecognizingController


PRECEDENCE_NONE = -1




_unparsedTextStyle = StyleSheet.style( Primitive.textSquiggleUnderlinePaint( Color.RED ) )
_controlCharStyle = StyleSheet.style( Primitive.foreground( Color( 0.0, 0.0, 0.0, 0.5 ) ) )
_invertControlCharStyle = StyleSheet.style( Primitive.foreground( Color( 1.0, 0.0, 0.0, 0.5 ) ) )

_specialCharStyle = StyleSheet.style( Primitive.foreground( Color( 0.25, 0.25, 0.35 ) ), Primitive.fontSize( 10 ) )
_specialBorder = SolidBorder( 1.0, 1.0, 4.0, 4.0, Color( 0.6, 0.6, 0.7 ), Color( 0.75, 0.75, 0.85 ) )

_charClassStyle = StyleSheet.style( Primitive.foreground( Color( 0.2, 0.3, 0.4 ) ), Primitive.fontSize( 10 ) )
_charClassBorder = SolidBorder( 1.0, 1.0, 4.0, 4.0, Color( 0.6, 0.65, 0.7 ), Color( 0.8, 0.85, 0.9 ) )


#_charClassStyle = StyleSheet.style( Primitive.foreground( Color( 0.0, 0.25, 0.5 ) ) )
#_charClassEscapeStyle = StyleSheet.style( Primitive.foreground( Color( 0.0, 0.25, 0.5, 0.5 ) ) )
#_charClassBorder = SolidBorder( 1.0, 2.0, 4.0, 4.0, Color( 0.0, 0.25, 0.5 ), Color( 0.8, 0.9, 1.0 ) )

_groupNameStyle = StyleSheet.style( Primitive.foreground( Color( 0.0, 0.65, 0.0 ) ) )
_groupNumberStyle = StyleSheet.style( Primitive.foreground( Color( 0.1, 0.45, 0.1 ) ) )
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))