def executionResultBox(streams, exception, resultInTuple,
                       bUseDefaultPerspecitveForException,
                       bUseDefaultPerspectiveForResult):
    boxContents = []
    for stream in streams:
        if stream.name == 'out':
            boxContents.append(
                execStdout(stream.richString, bUseDefaultPerspectiveForResult))
        elif stream.name == 'err':
            boxContents.append(
                execStderr(stream.richString, bUseDefaultPerspectiveForResult))
        else:
            raise ValueError, 'Unreckognised stream \'{0}\''.format(
                stream.name)
    if exception is not None:
        exceptionView = Pres.coerce(exception).alignHPack()
        if bUseDefaultPerspecitveForException:
            exceptionView = ApplyPerspective.defaultPerspective(exceptionView)
        boxContents.append(execException(exceptionView))
    if resultInTuple is not None:
        resultView = Pres.coercePresentingNull(resultInTuple[0]).alignHPack()
        if bUseDefaultPerspectiveForResult:
            resultView = ApplyPerspective.defaultPerspective(resultView)
        boxContents.append(execResult(resultView))

    if len(boxContents) > 0:
        return ApplyStyleSheetFromAttribute(ExecutionStyle.resultBoxStyle,
                                            Column(boxContents).alignHExpand())
    else:
        return None
Exemple #2
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)
	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()
	def _testValue(self, kind, data, excType=None):
		self._actual.setLiteralValue( ( kind, data ) )
		expected = self._expected.getStaticValue()
		if expected is not None:
			expectedKind, expectedData = expected
			if kind == expectedKind:
				if expectedKind == 'exception':
					if excType == expectedData:
						self.__result.setLiteralValue( _resultPass )
					else:
						title = _resultFailStyle( Label( 'FAIL' ) )
						heading = Label( 'Expected exception of type %s, got:' % expectedData.__name__ )
						res = Column( [ title, heading, data ] )
						self.__result.setLiteralValue( res )
				elif expectedKind == 'value':
					if data == expectedData:
						self.__result.setLiteralValue( _resultPass )
					else:
						title = _resultFailStyle( Label( 'FAIL' ) )
						heading1 = Label( 'Expected:' )
						heading2 = Label( 'Got:' )
						res = Column( [ title, heading1, expectedData, heading2, data ] )
						self.__result.setLiteralValue( res )
				else:
					raise TypeError, 'unknown expected result kind %s' % expectedKind
			else:
				resContents = [ _resultFailStyle( Label( 'FAIL' ) ) ]

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

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

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

			fixButton = Button.buttonWithLabel( 'Set expected result', _onFix )
			title = Label( 'No expected result, received:' )
			self.__result.setLiteralValue( Column( [ title, Pres.coerce( data ).pad( 5.0, 0.0, 5.0, 5.0 ), fixButton ] ).alignHPack().alignVTop() )
def _richStringItem(item, textStyleAttribute, bUseDefaultPerspectiveForResult):
    if item.isStructural():
        resultView = Pres.coercePresentingNull(item.getValue())
        if bUseDefaultPerspectiveForResult:
            resultView = ApplyPerspective.defaultPerspective(resultView)
        return resultView
    else:
        return _textLines(item.getValue(), textStyleAttribute)
    def _presentChild(self):
        def _onDropFromPalette(element, targetPos, data, action):
            assert isinstance(data, PaletteComponentDrag)
            self.child.node = data.getItem()
            return True

        child = self.child.node
        if child is None:
            p = self._emptyPres
            return p.withDropDest(PaletteComponentDrag, _onDropFromPalette)
        else:
            return Pres.coerce(child)
Exemple #8
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 ) )
    def PythonCode(self, fragment, inheritedState, node):
        if node.isVisible():
            if node.isCodeVisible():
                codeView = Python2.python2EditorPerspective.applyTo(
                    Pres.coerce(node.getCode()))
                if node.isCodeEditable():
                    codeView = StyleSheet.style(
                        Primitive.editable(True)).applyTo(codeView)
            else:
                codeView = None

            executionResultView = None
            executionResult = node.getResult()
            if executionResult is not None:
                if not node.isResultVisible():
                    executionResult = executionResult.suppressStdOut(
                    ).suppressResult()
                if node.isMinimal():
                    executionResultView = executionResult.minimalView()
                else:
                    executionResultView = executionResult.view()

            if node.isMinimal():
                return executionResultView.alignHExpand(
                ) if executionResultView is not None else Blank()
            else:
                boxContents = []
                if node.isCodeVisible():
                    boxContents.append(
                        _pythonCodeBorderStyle.applyTo(
                            Border(codeView.alignHExpand()).alignHExpand()))
                if node.isResultVisible() and executionResultView is not None:
                    boxContents.append(executionResultView.alignHExpand())
                box = StyleSheet.style(Primitive.columnSpacing(5.0)).applyTo(
                    Column(boxContents))

                return _pythonCodeEditorBorderStyle.applyTo(
                    Border(box.alignHExpand()).alignHExpand())
        else:
            return Blank()
    def Worksheet(self, fragment, inheritedState, node):
        bodyView = Pres.coerce(node.getBody())

        try:
            editSubject = fragment.subject.editSubject
        except AttributeError:
            pageContents = []
        else:
            editLink = Hyperlink('Switch to developer mode', editSubject)
            linkHeader = LinkHeaderBar([editLink])
            pageContents = [linkHeader]

        tip = TipBox([
            NormalText([
                'To edit this worksheet or add content, click ',
                EmphSpan('Switch to developer mode'), ' at the top right'
            ])
        ], 'larchcore.worksheet.view.toedit')

        w = Page(pageContents + [bodyView, tip])
        w = w.withContextMenuInteractor(_worksheetContextMenuFactory)
        return StyleSheet.style(Primitive.editable(False)).applyTo(w)
 def _explorerPres():
     return Pres.coerce(self._explorer)
 def _log():
     l = self._fragment.view.log
     l.startRecording()
     return Pres.coerce(LogView(l))
Exemple #13
0
    def AppState(self, fragment, state, node):
        def _onNewDoc(link, event):
            def handleNewDocumentFn(document, firstPageSubjectFn):
                name = _newDocumentName(openDocuments)
                document.setDocumentName(name)

                node.registerOpenDocument(document)

                subject = document.newSubject(fragment.subject, None,
                                              document.getDocumentName())
                subject = firstPageSubjectFn(subject)

                pageController = link.element.rootElement.pageController
                pageController.openSubject(
                    subject, PageController.OpenOperation.OPEN_IN_CURRENT_TAB)

            element = link.getElement()
            openDocuments = node.getOpenDocuments()
            DocumentManagement.promptNewDocument(fragment.subject.world,
                                                 element, handleNewDocumentFn)

            return True

        def _onOpenDoc(link, event):
            def handleOpenedDocumentFn(fullPath, document):
                appDoc = node.registerOpenDocument(document)

            element = link.getElement()
            DocumentManagement.promptOpenDocument(
                fragment.subject.world,
                element.getRootElement().getComponent(),
                handleOpenedDocumentFn)

            return True

        def _onFileListDrop(element, targetPosition, data, action):
            world = fragment.subject.world
            for filename in data:
                filename = str(filename)

                document = Document.readFile(world, filename)
                node.registerOpenDocument(document)
            return True

        def _onNewConsole(link, event):
            consoles = node.getConsoles()
            index = _newConsoleIndex(consoles)
            appConsole = Application.AppConsole(index)
            node.addConsole(appConsole)

            subject = appConsole.subject(fragment.subject)

            pageController = link.element.rootElement.pageController
            pageController.openSubject(
                subject, PageController.OpenOperation.OPEN_IN_CURRENT_TAB)

            return True

        openDocViews = Pres.mapCoerce(node.getOpenDocuments())
        consoles = Pres.mapCoerce(node.getConsoles())

        systemLink = Hyperlink('TEST PAGES', TestsRootPage.instanceSubject)
        configurationLink = Hyperlink(
            'CONFIGURATION PAGE',
            fragment.subject.world.configuration.subject())
        aboutLink = Hyperlink('ABOUT', fragment.subject.aboutPageSubject)
        linkHeader = SplitLinkHeaderBar([aboutLink],
                                        [configurationLink, systemLink])

        title = TitleBar('The Larch Environment')

        newLink = Hyperlink('NEW', _onNewDoc)
        openLink = Hyperlink('OPEN', _onOpenDoc)
        openDocumentsBox = _contentsList([newLink, openLink], openDocViews,
                                         'Documents')
        openDocumentsBox = openDocumentsBox.withNonLocalDropDest(
            DataFlavor.javaFileListFlavor, _onFileListDrop)
        openDocumentsBox = AttachTooltip(
            openDocumentsBox,
            'Click NEW to create a new document. To open from a file, click OPEN, or drag files from a file explorer application.',
            False)

        newConsoleLink = Hyperlink('NEW', _onNewConsole)
        consolesBox = _contentsList([newConsoleLink], consoles,
                                    'Python consoles')


        tip = TipBox( [ NormalText( [ StrongSpan( 'Getting started: ' ), 'To get programming quickly, create a new Python console by pressing ', EmphSpan( 'new' ), ', beneath', EmphSpan( ' Python consoles' ), '.' ] ),
          NormalText( [ 'For something more easily modifiable and something you can save, press ', EmphSpan( 'new' ), ' beneath ', EmphSpan( 'Documents' ), ' and choose the ', EmphSpan( 'Quickstart: worksheet' ), ' option.' ] ),
          NormalText( [ StrongSpan( 'Tips: ' ), 'You can highlight items that have help tips by pressing F2. Hover the pointer over them to display the tips. ' + \
                   'Some items do not display their tips unless highlighting is enabled, in order to reduce clutter.' ] ),
          NormalText( [ StrongSpan( 'Command bar: ' ), 'The command bar can be invoked by pressing the ', EmphSpan( 'escape' ), ' key. From there you can type abbreviated commands to invoke them. '
            'Alternatively, type in part of the full name of a command and autocomplete will show a list of commands that match. '
            'Press ', EmphSpan( 'tab' ), ' to switch between the entries in the autocomplete list and press ', EmphSpan( 'enter' ), ' to execute the highlighted command. '
            'Bold letters shown within command names indicate abbreviations, e.g. ', EmphSpan( 's' ), ' for ', EmphSpan( 'save' ), ' and ', EmphSpan( 'sa' ), ' for ', EmphSpan( 'save as' ), '. '
            'You can type these to execute them quickly.' ] )],
               'larchcore.mainapp.tooltiphighlights' )

        head = Head([linkHeader, title])
        body = Body([
            openDocumentsBox.pad(0.0, 10.0).alignHLeft(),
            consolesBox.pad(0.0, 10.0).alignHLeft(), tip
        ])
        return StyleSheet.style(Primitive.editable(False)).applyTo(
            Page([head, body]))
	def apply(self, p):
		x = self.x.getValueForEditor()
		y = self.y.getValueForEditor()
		return Pres.coerce(p).pad(x, y)
	def apply(self, p):
		left = self.left.getValueForEditor()
		right = self.right.getValueForEditor()
		top = self.top.getValueForEditor()
		bottom = self.bottom.getValueForEditor()
		return Pres.coerce(p).pad(left, right, top, bottom)
	def _presentFrameSubtree(self, valuesLive):
		frameBox = _FrameBox( self, valuesLive )
		tab = Pres.coerce( frameBox ).pad( 2.0, 2.0 ).alignVExpand()
		return Row( [ tab, Column( [ x._presentFrameSubtree( valuesLive )   for x in self.childFrames ] ) ] )
	def _presentContents(self, fragment, inheritedState):
		d = Pres.coerce(self._contents.value).withContextMenuInteractor(_documentContextMenuFactory)
		d = d.withDropDest(PaletteComponentDrag, None, _dndHighlight, _onDropFromPalette)
		d = GUIRichTextController.instance.region(d)
		return d
Exemple #18
0
 def __present__(self, fragment, inheritedState):
     return Pres.coerce(self._model)
Exemple #19
0
	def __present__(self, fragment, inheritedState):
		d = Pres.coerce(self.block_query).withContextMenuInteractor(_documentContextMenuFactory)
		d = d.withNonLocalDropDest(DataFlavor.javaFileListFlavor, _dndHighlight, _onDropImage)
		d = _controller.region(d)
		return d
	def __debugWrap(self, p):
		d = self._debug()
		if d is not None:
			return Column( [ p, Pres.coerce( d ).alignHPack() ] ).alignVTop()
		else:
			return p
	def __present__(self, fragment, inheritedState):
		x = Pres.coerce(self._value.value).withContextMenuInteractor(_inlineEmbedContextMenuFactory)
		x = GUIRichTextController.instance.editableInlineEmbed(self, x)
		return x
 def Body(self, fragment, inheritedState, node):
     contentViews = Pres.mapCoerce(
         [c for c in node.getContents() if c.isVisible()])
     return Body(contentViews).padX(_worksheetMargin)
	def tieToLifeTimeOf(self, p, rootElement):
		return Pres.coerce( p ).withElementInteractor( _TargetListenerLifeTime( self, rootElement ) )
 def __present__(self, fragment, inheritedState):
     p = Pres.coerce(self.__root)
     p = _guiEditorBorder.surround(p)
     p = p.withContextMenuInteractor(guiEditorContextMenu)
     p = p.withProperty(GUIEdProp.instance, self)
     return p