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)
                ])
            ])
示例#2
0
    def __present_contents__(self, fragment, inheritedState):
        def _onApply(button, event):
            self._config = self._userConfig.getStaticValue()
            self.apply()

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

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

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

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

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

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

        configMenu = OptionMenu(choices, indexOfChoice, _onChoice)

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

        return self._pageColumnStyle(Column([buttons, chooserHeader, footer]))
    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]))
def charSet(invert, items):
	items = [ Row( [ Segment( item ) ] )   for item in items ]
	if len( items ) == 1:
		itemsCollection = items[0]
	else:
		width = int( math.ceil( math.sqrt( float( len( items ) ) ) ) )
		itemsCollection = FlowGrid( width, items )
	contents = [ _controlCharStyle( Text( '[' ) ) ]
	if invert:
		contents.append( _invertControlCharStyle( Text( '^' ) ) )
	contents.extend( [ itemsCollection,  _controlCharStyle( Text( ']' ) ) ] )
	return _charSetBorder.surround( Row( contents ) )
示例#5
0
	def __present__(self , fragment, inherited_state):
		unload_modules_starting_with(['controls', 'datamodel', 'mallard'])

		from datamodel import xmlmodel
		from mallard import mallard

		title = _info_style(TitleBar(self._filename))

		xml_title = _section_heading_style(SectionHeading1('XML (non-editable)')).alignHExpand()
		rich_text_title = _section_heading_style(SectionHeading1('Rich text (editable)')).alignHExpand()

		if self.__xml_path is not None:
			with open(self.__xml_path, 'r') as f:
				xml_rep = xmlmodel.XmlElem.from_file(f)
		elif self.__xml_bytes is not None:
			xml_rep = xmlmodel.XmlElem.from_string(self.__xml_bytes)
		else:
			raise ValueError, 'Must provide either path or bytes'

		rich_text_rep = mallard.edit(xml_rep)

		scrolled_xml = ScrolledViewport(Pres.coerce(xml_rep).alignVRefY(), 100.0, 400.0, None)
		scrolled_rich_text = ScrolledViewport(_editable_style(rich_text_rep).alignVRefY(), 100.0, 400.0, None)
		xml_contents = Column([xml_title.alignVRefY(), Spacer(0.0, 20.0), scrolled_xml])
		rich_text_contents = Column([rich_text_title.alignVRefY(), Spacer(0.0, 20.0), scrolled_rich_text])

		xml_sec = _section_border.surround(xml_contents).pad(2.0, 2.0)
		rich_text_sec = _section_border.surround(rich_text_contents).pad(2.0, 2.0)

		contents = Row([xml_sec.alignHExpand(), rich_text_sec.alignHExpand()])

		return _info_style(Page([title.alignVRefY(), contents])).alignVExpand()
    def InlinePythonCode(self, fragment, inheritedState, node):
        assert isinstance(node, ViewSchema.InlinePythonCodeView)
        if node.isCodeVisible():
            exprView = Python2.python2EditorPerspective.applyTo(
                Pres.coerce(node.getExpr()))
            if node.isCodeEditable():
                exprView = StyleSheet.style(
                    Primitive.editable(True)).applyTo(exprView)
        else:
            exprView = None

        executionResultView = None
        executionResult = node.getResult()
        if executionResult is not None:
            if node.isResultMinimal():
                executionResultView = executionResult.minimalView()
            else:
                executionResultView = executionResult.view()

        if node.isCodeVisible():
            boxContents = [
                _pythonCodeBorderStyle.applyTo(
                    Border(exprView.alignHExpand()).alignHExpand())
            ]
            if executionResultView is not None:
                boxContents.append(executionResultView.alignHExpand())
            box = StyleSheet.style(Primitive.rowSpacing(5.0)).applyTo(
                Row(boxContents))

            return _pythonCodeEditorBorderStyle.applyTo(
                Border(box.alignHExpand()).alignHExpand())
        else:
            return executionResultView.alignHPack(
            ) if executionResultView is not None else Proxy()
示例#7
0
    def __present__(self, fragment, inheritedState):
        def _onClick(button, event):
            self._stepper._onRun()

        return Button(
            Row([_forwardArrow, Spacer(2.0, 0.0),
                 _forwardArrow]).pad(2.0, 2.0), _onClick).alignVCentre()
def choice(subexps):
	rows = []
	for subexp in subexps[:-1]:
		rows.append( Row( [ subexp.alignHPack(), _controlCharStyle( Text( '|' ).alignHRight() ) ] ).alignHExpand() )
		rows.append( _choiceRuleStyle.applyTo( Box( 1.0, 1.0 ).pad( 5.0, 3.0 ).alignHExpand() ) )
	rows.append( subexps[-1].alignHPack() )
	return _choiceBorder.surround( Column( rows ) )
示例#9
0
def externalExpr(ctx, style, exprView, title, deleteButton):
    externalExprBorderStyle = style.get(
        PythonEditorStyle.externalExprBorderStyle)
    externalExprTitleStyle = style.get(
        PythonEditorStyle.externalExprTitleStyle)

    titleLabel = externalExprTitleStyle.applyTo(Label(title))

    header = Row(
        [titleLabel.alignHLeft(),
         deleteButton.alignHRight().alignVCentre()])
    box = externalExprBorderStyle.applyTo(
        Border(Column([header.alignHExpand(),
                       exprView.pad(3.0, 3.0)]))).pad(1.0, 1.0)

    segment = Segment(box)
    return segment.present(ctx, style)
示例#10
0
def badIndentedBlock(ctx, style, indentElement, lines, dedentElement):
    rectStyle = PythonEditorStyle._badIndentationRectangleStyle.get(style)
    blockIndentation = style.get(PythonEditorStyle.blockIndentation)

    block = Column([indentElement] + lines + [dedentElement])

    return Row(
        [rectStyle.applyTo(Box(blockIndentation, 0.0).alignVExpand()),
         block]).alignHPack().present(ctx, style)
    def __present__(self, fragment, inheritedState):
        configurationLink = Hyperlink(
            'CONFIGURATION PAGE',
            fragment.subject.world.configuration.subject())
        linkHeader = LinkHeaderBar([configurationLink])

        title = TitleBar('About')

        splash = Image.systemImage('SplashScreen.png')

        desc = NormalText(
            'The Larch Environment was designed and written by Geoffrey French'
        )

        jythonLink = Hyperlink('Jython', URI('http://www.jython.org/'))
        jerichoLink = Hyperlink('Jericho HTML parser',
                                URI('http://jericho.htmlparser.net'))
        salamanderLink = Hyperlink('SVG Salamander',
                                   URI('http://svgsalamander.java.net/'))
        googleFontsLink = Hyperlink('Google Fonts',
                                    URI('http://www.google.com/fonts'))

        jythonAcks = NormalText([
            'The Larch Environment incorporates the ', jythonLink,
            ' interpreter.'
        ])
        libraryAcks = NormalText([
            'Larch incorporates the ', jerichoLink, ', and ', salamanderLink,
            ' libraries.'
        ])
        fontAcks = NormalText([
            'Larch incorporates the following fonts (found at ',
            googleFontsLink, '): ',
            'Arimo (by Steve Matteson), Lora (by Cyreal), Nobile (by Vernon Adams), Noto Sans (by Google), ',
            'Open Sans (by Steve Matteson), PT Serif (by ParaType), and Source Sans Pro (by Paul D. Hunt)'
        ])

        copyright = NormalText('(C) copyright Geoffrey French 2008-2013')

        homePage = Hyperlink('The Larch Environment website',
                             URI('http://www.larchenvironment.com'))

        head = Head([linkHeader, title])
        body = Body([
            splash.padY(20.0).alignHCentre(),
            desc.padY(10.0).alignHCentre(),
            Spacer(0.0, 10.0),
            jythonAcks.pad(25.0, 5.0).alignHLeft(),
            libraryAcks.pad(25.0, 5.0).alignHLeft(),
            fontAcks.pad(25.0, 5.0).alignHLeft(),
            Spacer(0.0, 10.0),
            Row([copyright.alignHLeft(),
                 homePage.alignHRight()]).pad(10.0, 10.0).alignHExpand()
        ])
        return StyleSheet.style(Primitive.editable(False)).applyTo(
            Page([head, body]))
示例#12
0
    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])
示例#13
0
def intLiteral(format, value):
    valuePres = ApplyStyleSheetFromAttribute(PythonEditorStyle.numLiteralStyle,
                                             Text(value))
    boxContents = [valuePres]
    if format is not None:
        boxContents.append(
            ApplyStyleSheetFromAttribute(PythonEditorStyle.literalFormatStyle,
                                         Text(format)))

    return Row(boxContents)
示例#14
0
 def __present__(self, fragment, inheritedState):
     title = Label('Code stepper')
     header = _headerStyle(
         Row([
             title.alignVCentre().alignHPack(),
             Pres.coerce(self._stepButton).alignHPack(),
             Pres.coerce(self._runButton).alignHPack()
         ])).alignHExpand()
     main = Column([header, Pres.coerce(self._code).alignHExpand()])
     return _stepperBorder.surround(main).withCommands(_stepperCommands)
示例#15
0
 def __present__(self, fragment, inheritedState):
     current = self._isCurrent.getValue()
     label = _breakPointStyle(Label('BREAKPOINT'))
     if current:
         return _breakPointCurrentBorder.surround(
             Row([_breakPointArrow,
                  Spacer(
                      3.0,
                      0.0,
                  ), label]).alignVCentre())
     else:
         return _breakPointBorder.surround(label)
示例#16
0
	def __present__(self, fragment, inheritedState):
		self._incr.onAccess()

		title = SectionHeading2( 'Unit tests' )

		nameEntry = _nameBorder.surround( EditableLabel( self._name, _notSet ).regexValidated( Tokens.identifierPattern, 'Please enter a valid identifier' ) )

		header = Row( [ title, Spacer( 25.0, 0.0 ), nameEntry ] )

		contents = [ header.padY( 0.0, 5.0 ), _standardCodeBorder.surround( self._suite ).padY( 3.0 ).alignHExpand() ]

		if self.__passes is not None  and  self.__failures is not None:
			resultsTitle = SectionHeading3( 'Test results:' )
			passes = _standardPassStyle( Label( '%d / %d test(s) passed' % ( self.__passes, self.__passes + len( self.__failures ) ) ) )
			failuresLabel = _standardFailStyle( Label( '%d test(s) failed:' % len( self.__failures ) ) )
			failures = [ Column( [ _standardFailedTestStyle( Label( name ) ), Pres.coerce( exception ).padX( 5.0, 0.0 ) ] ).padX( 5.0, 0.0 )   for name, exception in self.__failures ]
			results = _standardResultsBorder.surround( Column( [ resultsTitle, passes, failuresLabel ] + failures ) ).pad( 3.0, 3.0 )
			contents.append( results )


		return _standardInlineTestBorder.surround( Column( contents ) )
示例#17
0
def _collapsibleFontChooser(title, choiceValue, sampleFn):
    expanded = LiveValue(False)

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

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

    return DropDownExpander(
        header,
        ScrolledViewport(_fontChooser(choiceValue, sampleFn), 800.0, 400.0,
                         None), expanded).alignHExpand()
	def __present__(self, fragment, inheritedState):
		title = SectionHeading2( 'Unit tests' )

		nameEntry = _nameBorder.surround( EditableLabel( self._name, _notSet ).regexValidated( Tokens.identifierPattern, 'Please enter a valid identifier' ) )

		header = Row( [ title, Spacer( 25.0, 0.0 ), nameEntry ] )

		if self._tableEditor is NotImplemented:
			raise NotImplementedError, 'Table editor is abstract'

		table = self._tableEditor.editTable( self._tests )

		return _inlineTestTableBorder.surround( Column( [ header, Spacer( 0.0, 5.0 ), table ] ) )
示例#19
0
	def editor():
		x = live.getValue()

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

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

			return Row([deleteButton.alignHPack(), Spacer(5.0, 0.0).alignHPack(), valueEditor])
	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 )
示例#21
0
def embeddedObjectLiteral(ctx, style, valueView, hideFrame):
    embeddedObjectLiteralBorder = style.get(
        PythonEditorStyle.embeddedObjectLiteralBorder)
    embeddedObjectTagLabelStyle = style.get(
        PythonEditorStyle.embeddedObjectTagLabelStyle)
    embeddedObjectTagBorder = style.get(
        PythonEditorStyle.embeddedObjectTagBorder)

    tagLabel = embeddedObjectTagBorder.surround(
        embeddedObjectTagLabelStyle(Label('l')))
    contents = Row([tagLabel.alignVCentre(), valueView.pad(2.0, 2.0)])
    box = embeddedObjectLiteralBorder.surround(contents).padX(1.0, 1.0)

    segment = Segment(box)
    return segment.present(ctx, style)
示例#22
0
def _contentsList(controls, contentsLists, title):
    controlsBox = _appDocumentControlsStyle.applyTo(
        Row([c.padX(_controlsPadding) for c in controls]))
    controlsBorder = _appDocumentControlsBorder.surround(controlsBox)

    openDocumentsSeparator = HSeparator()

    docListBox = _documentListTableStyle.applyTo(RGrid(contentsLists))

    contentsBox = Column([
        controlsBorder.pad(2.0, 2.0), openDocumentsSeparator,
        docListBox.pad(12.0, 2.0)
    ])

    heading = SectionHeading1(title)

    return Section(heading, contentsBox)
    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)
示例#24
0
    def buildEditorPres(self, fragment, inheritedState):
        def _onOpen(button, event):
            component = button.getElement().getRootElement().getComponent()
            fileChooser = JFileChooser()
            self._initFileChooser(fileChooser)
            response = fileChooser.showDialog(component, 'Open')
            if response == JFileChooser.APPROVE_OPTION:
                sf = fileChooser.getSelectedFile()
                if sf is not None:
                    filename = sf.getPath()
                    if filename is not None:
                        self._model.liveValue.setLiteralValue(filename)

        openButton = Button.buttonWithLabel('...', _onOpen)
        return Row([
            openButton,
            Spacer(3.0, 0.0),
            EditableLabel(self._model.liveValue,
                          _notSetStyle(Label('<none>'))).regexValidated(
                              _filenamePattern,
                              'Please enter a valid filename')
        ])
示例#25
0
def stringLiteral(format, quotation, value, isUnicode, raw):
    boxContents = []

    if format is not None and format != '':
        boxContents.append(
            ApplyStyleSheetFromAttribute(PythonEditorStyle.literalFormatStyle,
                                         Text(format)))

    # Split the value into pieces of escaped and non-escaped content
    if raw:
        valuePres = ApplyStyleSheetFromAttribute(
            PythonEditorStyle.stringLiteralStyle, Text(value))
    else:
        segments = _non_escaped_string_re.split(value)
        if len(segments) == 1:
            valuePres = ApplyStyleSheetFromAttribute(
                PythonEditorStyle.stringLiteralStyle, Text(value))
        else:
            escape = False
            segsAsPres = []
            for seg in segments:
                if seg is not None and len(seg) > 0:
                    if escape:
                        segsAsPres.append(
                            ApplyStyleSheetFromAttribute(
                                PythonEditorStyle.stringLiteralEscapeStyle,
                                Border(Text(seg))))
                    else:
                        segsAsPres.append(Text(seg))
                escape = not escape
            valuePres = ApplyStyleSheetFromAttribute(
                PythonEditorStyle.stringLiteralStyle, Span(segsAsPres))

    quotationPres = ApplyStyleSheetFromAttribute(
        PythonEditorStyle.quotationStyle, Text(quotation))
    boxContents.extend([quotationPres, valuePres, quotationPres])

    return Row(boxContents)
    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])))
示例#27
0
        def samplePage():
            label = Label('Sample page:')

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

            return Column([label, Spacer(0.0, 15.0), page])
示例#28
0
def repeatRange(subexp, min, max, greedy):
	greedyness = []   if greedy   else [ _controlCharStyle( Text( '?' ) ) ]
	return _repetition( subexp, Row( [ _controlCharStyle( Text( '{' ) ), Text( min ),  _controlCharStyle( Text( ',' ) ), Text( max ), _controlCharStyle( Text( '}' ) ) ]  +  greedyness ) )
示例#29
0
def repeat(subexp, repetitions):
	return _repetition( subexp, Row( [ _controlCharStyle( Text( '{' ) ), Text( repetitions ), _controlCharStyle( Text( '}' ) ) ] ) )
示例#30
0
def _repetition(subexp, repetitions):
	return Script.scriptRSuper( Row( [ subexp ] ), _repeatBorder.surround( repetitions ) )