def presentPathList(self, pathList): def pathItem(index): def _onDelete(menuItem): del pathList[index] self._incr.onChanged() def buildContextMenu(element, menu): menu.add( MenuItem.menuItemWithLabel( 'Delete', _onDelete ) ) return True return _itemHoverHighlightStyle.applyTo( Label( pathList[index] ) ).withContextMenuInteractor( buildContextMenu ) def _onNew(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 ): pathList.append( filename ) self._incr.onChanged() newLink = Hyperlink( 'NEW', _onNew ) controls = newLink.pad( 10.0, 5.0 ) pathPres = Column( [ pathItem( i ) for i in xrange( len( pathList ) ) ] ) return Column( [ controls, pathPres.padX( 5.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])
def Package(self, fragment, inheritedState, package): def _addPackage(menuItem): package.append(ProjectPackage('NewPackage')) class _RenameListener(TextEntry.TextEntryListener): def onAccept(self, textEntry, text): package.name = text def onCancel(self, textEntry, originalText): nameLive.setLiteralValue(nameBox) def _onRename(menuItem): textEntry = TextEntry(package.name, _RenameListener()).regexValidated( _nameRegex, 'Please enter a valid identifier') textEntry.grabCaretOnRealise() nameLive.setLiteralValue(textEntry) def _onDelete(menuItem): if package.parent is not None: package.parent.remove(package) def _addPage(page): package.append(page) def _packageContextMenuFactory(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)) menu.add(HSeparator()) menu.add(MenuItem.menuItemWithLabel('Rename', _onRename)) menu.add(HSeparator()) menu.add(MenuItem.menuItemWithLabel('Delete', _onDelete)) return True nameElement = _packageNameStyle.applyTo(StaticText(package.name)) nameBox = _itemHoverHighlightStyle.applyTo( Row([ _packageIcon.padX(5.0).alignHPack().alignVCentre(), nameElement.alignVCentre() ])) # Set drop destination and place in box that is h-packed, otherwise attempting to drop items as children could require the user to # drop somewhere off to the right of the package, since the h-expand applied further up the presentation tree will expand it beyond # its visible bounds nameBox = Bin(nameBox).alignHPack() nameBox = nameBox.withContextMenuInteractor(_packageContextMenuFactory) nameBox = _ProjectTreeController.instance.nestedListItem( package, package, nameBox) nameBox = AttachTooltip(nameBox, 'Right click to access context menu.', False) nameLive = LiveValue(nameBox) itemsBox = Column(package[:]) itemsBox = _ProjectTreeController.instance.editableList( package, itemsBox) return Column([ nameLive, itemsBox.padX(_packageContentsIndentation, 0.0).alignHExpand() ])
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]))