Ejemplo n.º 1
0
	def __present__(self, fragment, inheritedState):
		pythonModule = self.getPythonModule()

		executionResult = self.getExecResult()

		caughtException = executionResult.getCaughtException()
		result = executionResult.getResult()
		streams = executionResult.getStreams()

		moduleView = StyleSheet.style( Primitive.editable( False ) ).applyTo( Python2.python2EditorPerspective.applyTo( pythonModule ) )
		caughtExceptionView = ApplyPerspective.defaultPerspective( caughtException )   if caughtException is not None   else None
		resultView = ApplyPerspective.defaultPerspective( result[0] )   if result is not None   else None

		code = _pythonModuleBorderStyle.applyTo( Border( moduleView.alignHExpand() ).alignHExpand() )
		outputContents = []
		for stream in streams:
			if stream.name == 'out':
				outputContents.append( execStdout( stream.richString, True ) )
			elif stream.name == 'err':
				outputContents.append( execStderr( stream.richString, True ) )
			else:
				raise ValueError, 'Unreckognised stream \'{0}\''.format( stream.name )
		if caughtExceptionView is not None:
			outputContents.append( execException( caughtExceptionView ) )
		if resultView is not None:
			outputContents.append( execResult( resultView ) )
		outputColumn = _blockOutputStyle.applyTo( Column( outputContents ).alignHExpand() )
		return _blockStyle.applyTo( Border( Column( [ code, outputColumn ] ) ) ).alignHExpand()
Ejemplo n.º 2
0
    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 __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]))
Ejemplo n.º 4
0
    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()
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
def embeddedObjectMacro(ctx, style, valueView, modelView):
    modelView = StyleSheet.style(Primitive.editable(False)).applyTo(modelView)

    embeddedObjectBorderStyle = style.get(
        PythonEditorStyle.embeddedObjectBorderStyle)
    embeddedObjectLineStyle = style.get(
        PythonEditorStyle.embeddedObjectLineStyle)
    embeddedObjectExpansionLabelStyle = style.get(
        PythonEditorStyle.embeddedObjectExpansionLabelStyle)

    hLine = embeddedObjectLineStyle.applyTo(Box(1, 1).alignHExpand()).pad(
        8.0, 2.0).alignHExpand()

    expansionLabel = embeddedObjectExpansionLabelStyle.applyTo(
        Label('Expansion'))

    expander = DropDownExpander(expansionLabel, modelView)

    view = embeddedObjectBorderStyle.applyTo(
        Border(Column([valueView, expander])))

    segment = Segment(view)
    return segment.present(ctx, style)
class ConfigurationPage (object):
	class _ConfigPageSubject (TransientSubject):
		def __init__(self, enclosingSubject, page):
			super( ConfigurationPage._ConfigPageSubject, self ).__init__( enclosingSubject )
			self._page = page
		
		def getFocus(self):
			return self._page
		
		def getTitle(self):
			return self._page.getSubjectTitle()
		
	
	def __init__(self):
		self.__config = None

		
	def __getstate__(self):
		return {}
	
	def __setstate__(self, state):
		pass

		
		
	def initPage(self, config):
		self.__config = config


	def subject(self, enclosingSubject=None):
		if enclosingSubject is None:
			enclosingSubject = self.__config.subject()
		return self._ConfigPageSubject( enclosingSubject, self )

		
	@abstractmethod
	def getSubjectTitle(self):
		pass
	
	@abstractmethod
	def getTitleText(self):
		pass
	
	@abstractmethod
	def getLinkText(self):
		pass
	
	
	@abstractmethod
	def __present_contents__(self, fragment, inheritedState):
		pass	


	def __present__(self, fragment, inheritedState):
		homeLink = Hyperlink( 'HOME PAGE', fragment.subject.rootSubject )
		configLink = Hyperlink( 'CONFIGURATION PAGE', fragment.subject.configSubject )
		linkHeader = SplitLinkHeaderBar( [ homeLink ], [ configLink ] )
		
		title = TitleBar( self.getTitleText() )

		head = _staticStyle.applyTo( Head( [ linkHeader, title ] ) )
		
		contents = self.__present_contents__( fragment, inheritedState )
		
		return self._configPageStyle.applyTo( Page( [ head, contents ] ) )
	
	
	_configPageStyle = StyleSheet.style( Primitive.editable( False ) )
##-* licensed under the MIT license, a copy of which can be found in
##-* the file 'COPYING'.
##-*************************
from BritefuryJ.Controls import Hyperlink

from BritefuryJ.Pres.Primitive import Primitive
from BritefuryJ.Pres.RichText import SplitLinkHeaderBar, TitleBar, Page, Head, Body
from BritefuryJ.StyleSheet import StyleSheet

from BritefuryJ.Projection import TransientSubject

from Britefury.Util.Abstract import abstractmethod



_staticStyle = StyleSheet.style( Primitive.editable( False ) )


class ConfigurationPage (object):
	class _ConfigPageSubject (TransientSubject):
		def __init__(self, enclosingSubject, page):
			super( ConfigurationPage._ConfigPageSubject, self ).__init__( enclosingSubject )
			self._page = page
		
		def getFocus(self):
			return self._page
		
		def getTitle(self):
			return self._page.getSubjectTitle()
		
	
Ejemplo n.º 9
0
from BritefuryJ.StyleSheet import StyleSheet

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
Ejemplo n.º 10
0
    def ProjectRoot(self, fragment, inheritedState, project):
        # Save and Save As
        def _onSave(control, buttonEvent):
            if document.hasFilename():
                document.save()
            else:

                def handleSaveDocumentAsFn(filename):
                    document.saveAs(filename)

                DocumentManagement.promptSaveDocumentAs(
                    world,
                    control.getElement().getRootElement().getComponent(),
                    handleSaveDocumentAsFn)

        def _onSaveAs(control, buttonEvent):
            def handleSaveDocumentAsFn(filename):
                document.saveAs(filename)

            DocumentManagement.promptSaveDocumentAs(
                world,
                control.getElement().getRootElement().getComponent(),
                handleSaveDocumentAsFn, document.getFilename())

        def _onReload(control, buttonEvent):
            if document.hasFilename():
                document.save()
                document.reload()
                project.reset()
            else:

                def handleSaveDocumentAsFn(filename):
                    document.saveAs(filename)
                    document.reload()
                    project.reset()

                DocumentManagement.promptSaveDocumentAs(
                    world,
                    control.getElement().getRootElement().getComponent(),
                    handleSaveDocumentAsFn)

        def _onExport(control, event):
            component = control.getElement().getRootElement().getComponent()
            openDialog = JFileChooser()
            openDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            response = openDialog.showDialog(component, 'Export')
            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):
                        response = JOptionPane.showOptionDialog(
                            component,
                            'Existing content will be overwritten. Proceed?',
                            'Overwrite existing content',
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE, None,
                            ['Overwrite', 'Cancel'], 'Cancel')
                        if response == JFileChooser.APPROVE_OPTION:
                            exc = None
                            try:
                                project.export(filename)
                            except:
                                exc = JythonException.getCurrentException()
                            if exc is not None:
                                BubblePopup.popupInBubbleAdjacentTo(
                                    DefaultPerspective.instance(exc),
                                    control.getElement(), Anchor.BOTTOM, True,
                                    True)

        # Python package name
        class _PythonPackageNameListener(EditableLabel.EditableLabelListener):
            def onTextChanged(self, editableLabel, text):
                if text != '':
                    project.pythonPackageName = text
                else:
                    project.pythonPackageName = None

        # Project index
        def _addPackage(menuItem):
            project.append(ProjectPackage('NewPackage'))

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

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

        # Get some initial variables
        document = fragment.subject.document
        world = fragment.subject.world

        # Title
        title = TitleBar(document.getDocumentName())

        # Controls for 'save' and 'save as'
        saveExportHeader = SectionHeading1('Save/export')
        saveButton = Button.buttonWithLabel('Save', _onSave)
        saveAsButton = Button.buttonWithLabel('Save as', _onSaveAs)
        reloadButton = Button.buttonWithLabel('Save and reload', _onReload)
        reloadButton = AttachTooltip(
            reloadButton,
            'Saves and reloads the project from scratch\nCauses all embedded objects to be re-created.'
        )
        exportButton = Button.buttonWithLabel('Export', _onExport)
        exportButton = AttachTooltip(
            exportButton,
            'Exports project contents to text files where possible.')
        saveBox = Row([
            saveButton.padX(10.0),
            Spacer(30.0, 0.0),
            saveAsButton.padX(10.0),
            Spacer(30.0, 0.0),
            reloadButton.padX(10.0),
            Spacer(50.0, 0.0),
            exportButton.padX(10.0)
        ]).alignHLeft()
        saveExportSection = Section(saveExportHeader, saveBox)

        #
        # Project Section
        #

        # Python package name
        notSet = _pythonPackageNameNotSetStyle.applyTo(Label('<not set>'))
        pythonPackageNameLabel = EditableLabel(
            project.pythonPackageName, notSet,
            _PythonPackageNameListener()).regexValidated(
                _pythonPackageNameRegex,
                'Please enter a valid dotted identifier')
        pythonPackageNameLabel = AttachTooltip( pythonPackageNameLabel, 'The root python package name is the name under which the contents of the project can be imported using import statements within the project.\n' + \
         'If this is not set, pages from this project cannot be imported.', False )
        pythonPackageNameRow = Form.Section(
            'Root Python package name',
            'Pages will not be importable unless this is set',
            pythonPackageNameLabel)

        # Clear imported modules
        def _onReset(button, event):
            project.reset()
            modules = document.unloadAllImportedModules()
            heading = SectionHeading2('Unloaded modules:')
            modules = Column([Label(module) for module in modules])
            report = Section(heading, modules)
            BubblePopup.popupInBubbleAdjacentTo(report, button.getElement(),
                                                Anchor.BOTTOM, True, True)

        resetButton = Button.buttonWithLabel('Reset', _onReset)
        resetButton = AttachTooltip(
            resetButton,
            'Unloads all modules that were imported from this project from the Python module cache. This way they can be re-imported, allowing modifications to take effect.'
        )
        resetRow = Form.Section('Reset', 'Unload project modules', resetButton)

        projectSection = Form('Project', [pythonPackageNameRow, resetRow])

        # Project index
        indexHeader = SectionHeading1('Index')

        nameElement = _projectIndexNameStyle.applyTo(Label('Project root'))
        nameBox = _itemHoverHighlightStyle.applyTo(nameElement.alignVCentre())
        nameBox = nameBox.withContextMenuInteractor(
            _projectIndexContextMenuFactory)
        nameBox = _ProjectTreeController.instance.item(project, nameBox)
        nameBox = AttachTooltip( nameBox, 'Right click to access context menu, from which new pages and packages can be created.\n' + \
         'A page called index at the root will appear instead of the project page. A page called __startup__ will be executed at start time.', False )

        itemsBox = Column(project[:]).alignHExpand()
        itemsBox = _ProjectTreeController.instance.editableList(
            project, itemsBox)

        contentsView = Column([
            nameBox.alignHExpand(),
            itemsBox.padX(_packageContentsIndentation, 0.0).alignHExpand()
        ])

        indexSection = Section(indexHeader, contentsView)

        def _onBuildJar(button, event):
            _buildProjectJar(button.element, document)

        buildJarButton = Button.buttonWithLabel('Build JAR', _onBuildJar)
        jarRow = Form.Section('Build executable app',
                              'Export the project as an executable JAR',
                              buildJarButton)

        packagingSection = Form('Packaging', [jarRow])

        indexTip = TipBox([
            NormalText([
                StrongSpan('Index: '),
                'Larch projects act like Python programs. Packages act as directories/packages and pages act as Python source files. Pages can import code from one another as if they are modules.'
            ]),
            NormalText([
                'New pages and packages can be created by right clicking on the entries in the index or on ',
                EmphSpan('Project root'),
                ' (they will highlight as you hover over them).'
            ]),
            NormalText([
                StrongSpan('Front and startup pages: '),
                'If a page is set as the front page it will appear instead of the project page. In these cases, the project page can still be reached using the links in the location bar at the top of the window.'
            ]),
            'If a page is set as the startup page, code within it will be executed before all other pages. This can be used for registering editor extensions.',
            'To set a page as the front page or the startup page, right-click on it to show its context menu and choose the appropriate option.'
        ], 'larchcore.worksheet.worksheeteditor')

        # The page
        head = Head([title])
        body = Body([
            saveExportSection, projectSection, indexSection, packagingSection,
            indexTip
        ]).alignHPack()

        return StyleSheet.style(Primitive.editable(False)).applyTo(
            Page([head, body]))
Ejemplo n.º 11
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]))
Ejemplo n.º 12
0
from BritefuryJ.Pres.Primitive import Primitive, Blank, Border, Column, Row, Proxy
from BritefuryJ.Pres.RichText import TitleBar, Heading1, Heading2, Heading3, Heading4, Heading4, Heading5, Heading6, NormalText, RichSpan, Page, Body, LinkHeaderBar, EmphSpan
from BritefuryJ.Pres.ObjectPres import ObjectBorder
from BritefuryJ.Pres.UI import Section, SectionHeading2, ControlsRow
from BritefuryJ.Pres.Help import TipBox

from BritefuryJ.Projection import Perspective, Subject, SubjectPathEntry

from LarchCore.Languages.Python2 import Python2
from LarchCore.Languages.Python2.CodeGenerator import compileForModuleExecution

from LarchCore.Worksheet import Schema
from LarchCore.Worksheet.WorksheetViewer import ViewSchema
from LarchCore.Worksheet.WorksheetEditor.View import WorksheetEditorSubject

_editableStyle = StyleSheet.style(Primitive.editable(True))

_worksheetMargin = 10.0

_pythonCodeBorderStyle = StyleSheet.style(
    Primitive.border(
        SolidBorder(1.0, 5.0, 10.0, 10.0, Color(0.2, 0.4, 0.8), None)))
_pythonCodeEditorBorderStyle = StyleSheet.style(
    Primitive.border(
        SolidBorder(1.5, 4.0, 10.0, 10.0, Color(0.4, 0.4, 0.5), None)))


def _worksheetContextMenuFactory(element, menu):
    def _onRefresh(button, event):
        model.refreshResults()
Ejemplo n.º 13
0
from BritefuryJ.Pres.UI import SectionHeading1
from BritefuryJ.Controls import ScrolledViewport

from BritefuryJ.Graphics import SolidBorder, FillPainter

from BritefuryJ.StyleSheet import StyleSheet

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


_info_style = StyleSheet.style(Primitive.selectable(False), Primitive.editable(False))
_editable_style = StyleSheet.style(Primitive.selectable(True), Primitive.editable(True))

_section_heading_style = StyleSheet.style(Primitive.background(FillPainter(Color(0.925, 0.925, 0.925))))

_section_border = SolidBorder(1.0, 3.0, 4.0, 4.0, Color(0.4, 0.4, 0.4), None)


def unload_modules_starting_with(prefixes):
	to_remove = []
	for m in sys.modules:
		for prefix in prefixes:
			if m.startswith(prefix):
				to_remove.append(m)
	for m in to_remove:
		del sys.modules[m]
Ejemplo n.º 14
0
from BritefuryJ.Util import TypeUtils


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 ) ) )
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,
    TypeUtils.ObjectKind.PYTHON: _objectKindPython,
    TypeUtils.ObjectKind.DOCMODEL: _objectKindDocModel,
}