You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2019/09/26 00:26:32 UTC
[groovy] 13/23: GROOVY-9254: Split package renaming second stage
(remove violating packages)
This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 88034ff1d52642ff871b1344df78804f5f76541c
Author: Paul King <pa...@asert.com.au>
AuthorDate: Wed Sep 18 19:53:42 2019 +1000
GROOVY-9254: Split package renaming second stage (remove violating packages)
---
.../src/main/groovy/groovy/inspect/TextNode.groovy | 55 -
.../groovy/groovy/inspect/TextTreeNodeMaker.groovy | 37 -
.../groovy/inspect/swingui/AstBrowser.groovy | 690 --------
.../inspect/swingui/AstNodeToScriptAdapter.groovy | 1185 --------------
.../inspect/swingui/ButtonOrDefaultRenderer.groovy | 42 -
.../inspect/swingui/ButtonOrTextEditor.groovy | 61 -
.../groovy/inspect/swingui/ObjectBrowser.groovy | 168 --
.../inspect/swingui/ScriptToTreeNodeAdapter.groovy | 823 ----------
.../groovy/groovy/inspect/swingui/package.html | 28 -
.../src/main/groovy/groovy/ui/Console.groovy | 1718 --------------------
.../main/groovy/groovy/ui/ConsoleActions.groovy | 428 -----
.../src/main/groovy/groovy/ui/ConsoleApplet.groovy | 42 -
.../main/groovy/groovy/ui/ConsoleIvyPlugin.groovy | 65 -
.../groovy/groovy/ui/ConsolePreferences.groovy | 168 --
.../src/main/groovy/groovy/ui/ConsoleSupport.java | 91 --
.../main/groovy/groovy/ui/ConsoleTextEditor.java | 356 ----
.../src/main/groovy/groovy/ui/ConsoleView.groovy | 181 ---
.../src/main/groovy/groovy/ui/HistoryRecord.groovy | 48 -
.../main/groovy/groovy/ui/OutputTransforms.groovy | 110 --
.../groovy/groovy/ui/SystemOutputInterceptor.java | 135 --
.../src/main/groovy/groovy/ui/package.html | 28 -
.../groovy/groovy/ui/text/AutoIndentAction.groovy | 55 -
.../groovy/groovy/ui/text/FindReplaceUtility.java | 544 -------
.../main/groovy/groovy/ui/text/GroovyFilter.java | 271 ---
.../groovy/groovy/ui/text/MatchingHighlighter.java | 222 ---
.../groovy/groovy/ui/text/SmartDocumentFilter.java | 361 ----
.../ui/text/StructuredSyntaxDocumentFilter.java | 574 -------
.../groovy/ui/text/StructuredSyntaxHandler.java | 107 --
.../groovy/ui/text/StructuredSyntaxResources.java | 81 -
.../src/main/groovy/groovy/ui/text/TextEditor.java | 500 ------
.../groovy/groovy/ui/text/TextUndoManager.java | 201 ---
.../src/main/groovy/groovy/ui/text/package.html | 28 -
.../groovy/groovy/ui/view/BasicContentPane.groovy | 158 --
.../main/groovy/groovy/ui/view/BasicMenuBar.groovy | 102 --
.../groovy/groovy/ui/view/BasicStatusBar.groovy | 34 -
.../main/groovy/groovy/ui/view/BasicToolBar.groovy | 46 -
.../src/main/groovy/groovy/ui/view/Defaults.groovy | 88 -
.../main/groovy/groovy/ui/view/GTKDefaults.groovy | 58 -
.../groovy/groovy/ui/view/MacOSXDefaults.groovy | 88 -
.../groovy/groovy/ui/view/MacOSXMenuBar.groovy | 149 --
.../groovy/groovy/ui/view/WindowsDefaults.groovy | 35 -
.../inspect/swingui/AstBrowserProperties.groovy | 67 -
.../main/resources/groovy/ui/Console.properties | 47 -
.../src/main/resources/groovy/ui/ConsoleIcon.png | Bin 3739 -> 0 bytes
.../groovy/ui/InteractiveShell.properties | 66 -
.../main/resources/groovy/ui/icons/arrow_redo.png | Bin 625 -> 0 bytes
.../main/resources/groovy/ui/icons/arrow_undo.png | Bin 631 -> 0 bytes
.../main/resources/groovy/ui/icons/book_next.png | Bin 702 -> 0 bytes
.../resources/groovy/ui/icons/book_previous.png | Bin 680 -> 0 bytes
.../resources/groovy/ui/icons/bullet_green.png | Bin 295 -> 0 bytes
.../src/main/resources/groovy/ui/icons/clear.png | Bin 524 -> 0 bytes
.../src/main/resources/groovy/ui/icons/credits.txt | 24 -
.../src/main/resources/groovy/ui/icons/cross.png | Bin 655 -> 0 bytes
.../src/main/resources/groovy/ui/icons/cut.png | Bin 648 -> 0 bytes
.../src/main/resources/groovy/ui/icons/cut_red.png | Bin 650 -> 0 bytes
.../src/main/resources/groovy/ui/icons/disk.png | Bin 620 -> 0 bytes
.../src/main/resources/groovy/ui/icons/find.png | Bin 659 -> 0 bytes
.../main/resources/groovy/ui/icons/folder_page.png | Bin 688 -> 0 bytes
.../src/main/resources/groovy/ui/icons/page.png | Bin 635 -> 0 bytes
.../main/resources/groovy/ui/icons/page_copy.png | Bin 663 -> 0 bytes
.../main/resources/groovy/ui/icons/page_paste.png | Bin 703 -> 0 bytes
.../main/resources/groovy/ui/icons/script_go.png | Bin 839 -> 0 bytes
.../resources/groovy/ui/icons/text_replace.png | Bin 691 -> 0 bytes
63 files changed, 10365 deletions(-)
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextNode.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextNode.groovy
deleted file mode 100644
index d76748c..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextNode.groovy
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * Represents a plain text node for use in the AST tree made by ASTBrowser
- */
-package groovy.inspect
-
-import groovy.transform.CompileStatic
-
-@CompileStatic
-@Deprecated
-class TextNode {
- Object userObject
- List<List<String>> properties
- TextNode parent
- List children
-
- TextNode(Object userObject) {
- this.userObject = userObject
- children = new ArrayList<TextNode>()
- }
-
- TextNode(Object userObject, List<List<String>> properties) {
- this(userObject)
- this.properties = properties
- }
-
- void add(TextNode child) {
- children << child
- }
-
- void setParent(TextNode newParent) {
- parent = newParent
- }
-
- String toString() {
- userObject ? userObject.toString() : 'null'
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextTreeNodeMaker.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextTreeNodeMaker.groovy
deleted file mode 100644
index fa24403..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/TextTreeNodeMaker.groovy
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-/**
- * A factory class for plain text nodes for use in the AST tree made by ASTBrowser
- */
-package groovy.inspect
-
-import groovy.inspect.swingui.AstBrowserNodeMaker
-import groovy.transform.CompileStatic
-
-@CompileStatic
-@Deprecated
-class TextTreeNodeMaker implements AstBrowserNodeMaker<TextNode> {
- TextNode makeNode(Object userObject) {
- new TextNode(userObject)
- }
-
- TextNode makeNodeWithProperties(Object userObject, List<List<String>> properties) {
- new TextNode(userObject, properties)
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstBrowser.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstBrowser.groovy
deleted file mode 100644
index 9882fc3..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstBrowser.groovy
+++ /dev/null
@@ -1,690 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.lang.GroovyClassLoader.ClassCollector
-import groovy.swing.SwingBuilder
-import groovy.transform.CompileStatic
-import org.apache.groovy.io.StringBuilderWriter
-import org.codehaus.groovy.ast.ClassNode
-import org.codehaus.groovy.control.CompilationUnit
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.Phases
-import org.codehaus.groovy.control.SourceUnit
-import org.objectweb.asm.ClassReader
-import org.objectweb.asm.util.ASMifier
-import org.objectweb.asm.util.TraceClassVisitor
-
-import javax.swing.*
-import javax.swing.event.TreeSelectionEvent
-import javax.swing.event.TreeSelectionListener
-import javax.swing.tree.DefaultMutableTreeNode
-import javax.swing.tree.DefaultTreeModel
-import javax.swing.tree.TreeNode
-import javax.swing.tree.TreeSelectionModel
-import java.awt.*
-import java.awt.event.KeyEvent
-import java.util.List
-import java.util.prefs.Preferences
-import java.util.regex.Pattern
-
-import static java.awt.GridBagConstraints.BOTH
-import static java.awt.GridBagConstraints.HORIZONTAL
-import static java.awt.GridBagConstraints.NONE
-import static java.awt.GridBagConstraints.NORTHEAST
-import static java.awt.GridBagConstraints.NORTHWEST
-import static java.awt.GridBagConstraints.WEST
-
-/**
- * This object is a GUI for looking at the AST that Groovy generates.
- *
- * Usage: java groovy.inspect.swingui.AstBrowser [filename]
- * where [filename] is an existing Groovy script.
- */
-@Deprecated
-class AstBrowser {
-
- private static final String BYTECODE_MSG_SELECT_NODE = '// Please select a class node in the tree view.'
- private static final String NO_BYTECODE_AVAILABLE_AT_THIS_PHASE = '// No bytecode available at this phase'
-
- private inputArea, rootElement, decompiledSource, jTree, propertyTable, splitterPane, mainSplitter, bytecodeView, asmifierView
- boolean showScriptFreeForm, showScriptClass, showClosureClasses, showTreeView, showIndyBytecode
- GeneratedBytecodeAwareGroovyClassLoader classLoader
- def prefs = new AstBrowserUiPreferences()
- Action refreshAction
- private CompilerConfiguration config
-
- AstBrowser(inputArea, rootElement, classLoader, config = null) {
- this.inputArea = inputArea
- this.rootElement = rootElement
- this.classLoader = new GeneratedBytecodeAwareGroovyClassLoader(classLoader)
- this.config = config
- }
-
- SwingBuilder swing
- def frame
-
- static void main(args) {
-
- if (!args) {
- println 'Usage: java groovy.inspect.swingui.AstBrowser [filename]\nwhere [filename] is a Groovy script'
- } else {
- def file = new File((String) args[0])
- if (!file.exists()) {
- println "File $args[0] cannot be found."
- } else {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
- new AstBrowser(null, null, new GroovyClassLoader()).run({file.text}, file.path)
- }
- }
- }
-
- void initAuxViews() {
- bytecodeView.textEditor.text = BYTECODE_MSG_SELECT_NODE
- asmifierView.textEditor.text = BYTECODE_MSG_SELECT_NODE
- }
-
- void run(Closure script) {
- run(script, null)
- }
-
- void run(Closure script, String name) {
-
- swing = new SwingBuilder()
- def phasePicker
-
- showScriptFreeForm = prefs.showScriptFreeForm
- showScriptClass = prefs.showScriptClass
- showClosureClasses = prefs.showClosureClasses
- showTreeView = prefs.showTreeView
- showIndyBytecode = prefs.showIndyBytecode
-
- frame = swing.frame(title: 'Groovy AST Browser' + (name ? " - $name" : ''),
- location: prefs.frameLocation,
- size: prefs.frameSize,
- iconImage: swing.imageIcon(groovy.ui.Console.ICON_PATH).image,
- defaultCloseOperation: WindowConstants.DISPOSE_ON_CLOSE,
- windowClosing: { event -> prefs.save(frame, splitterPane, mainSplitter, showScriptFreeForm, showScriptClass, showClosureClasses, phasePicker.selectedItem, showTreeView, showIndyBytecode) }) {
-
- menuBar {
- menu(text: 'Show Script', mnemonic: 'S') {
- checkBoxMenuItem(selected: showScriptFreeForm) {
- action(name: 'Free Form', closure: this.&showScriptFreeForm,
- mnemonic: 'F',)
- }
- checkBoxMenuItem(selected: showScriptClass) {
- action(name: 'Class Form', closure: this.&showScriptClass,
- mnemonic: 'C')
- }
- checkBoxMenuItem(selected: showClosureClasses) {
- action(name: 'Generated Closure/Lambda Classes', closure: this.&showClosureClasses,
- mnemonic: 'G')
- }
- checkBoxMenuItem(selected: showTreeView) {
- action(name: 'Tree View', closure: this.&showTreeView,
- mnemonic: 'T')
- }
- checkBoxMenuItem(selected: showIndyBytecode) {
- action(name: 'Generate Indy Bytecode', closure: this.&showIndyBytecode,
- mnemonic: 'I')
- }
- }
- menu(text: 'View', mnemonic: 'V') {
- menuItem {action(name: 'Larger Font', closure: this.&largerFont, mnemonic: 'L', accelerator: shortcut('shift L'))}
- menuItem {action(name: 'Smaller Font', closure: this.&smallerFont, mnemonic: 'S', accelerator: shortcut('shift S'))}
- menuItem {
- refreshAction = action(name: 'Refresh', closure: {
- decompile(phasePicker.selectedItem.phaseId, script())
- compile(jTree, script(), phasePicker.selectedItem.phaseId)
- initAuxViews()
- }, mnemonic: 'R', accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0))
- }
- }
- menu(text: 'Help', mnemonic: 'H') {
- menuItem {action(name: 'About', closure: this.&showAbout, mnemonic: 'A')}
- }
- }
- panel {
- gridBagLayout()
- label(text: 'At end of Phase: ',
- constraints: gbc(gridx: 0, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 0, weighty: 0, anchor: WEST, fill: HORIZONTAL, insets: [2, 2, 2, 2]))
- phasePicker = comboBox(items: CompilePhaseAdapter.values(),
- selectedItem: prefs.selectedPhase,
- actionPerformed: {
- // reset text to the default as the phase change removes the focus from the class node
- initAuxViews()
-
- decompile(phasePicker.selectedItem.phaseId, script())
- compile(jTree, script(), phasePicker.selectedItem.phaseId)
- },
- constraints: gbc(gridx: 1, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 1.0, weighty: 0, anchor: NORTHWEST, fill: NONE, insets: [2, 2, 2, 2]))
- button(text: 'Refresh',
- actionPerformed: {
- decompile(phasePicker.selectedItem.phaseId, script())
- compile(jTree, script(), phasePicker.selectedItem.phaseId)
- initAuxViews()
- },
- constraints: gbc(gridx: 2, gridy: 0, gridwidth: 1, gridheight: 1, weightx: 0, weighty: 0, anchor: NORTHEAST, fill: NONE, insets: [2, 2, 2, 3]))
- splitterPane = splitPane(
- visible: showTreeView,
- leftComponent: scrollPane {
- jTree = tree(
- name: 'AstTreeView', rowHeight: 0, /* force recalc */
- model: new DefaultTreeModel(new DefaultMutableTreeNode('Loading...'))) {}
- },
- rightComponent: scrollPane {
- propertyTable = table {
- tableModel(list: [[:]]) {
- propertyColumn(header: 'Name', propertyName: 'name')
- propertyColumn(header: 'Value', propertyName: 'value')
- propertyColumn(header: 'Type', propertyName: 'type')
- }
- }
- }
- ) { }
- mainSplitter = splitPane(
- orientation: JSplitPane.VERTICAL_SPLIT,
- topComponent: splitterPane,
- bottomComponent: tabbedPane {
- widget(decompiledSource = new groovy.ui.ConsoleTextEditor(editable: false, showLineNumbers: false), title:'Source')
- widget(bytecodeView = new groovy.ui.ConsoleTextEditor(editable: false, showLineNumbers: false), title:getByteCodeTitle())
- widget(asmifierView = new groovy.ui.ConsoleTextEditor(editable: false, showLineNumbers: false), title:getASMifierTitle())
- },
- constraints: gbc(gridx: 0, gridy: 2, gridwidth: 3, gridheight: 1, weightx: 1.0, weighty: 1.0, anchor: NORTHWEST, fill: BOTH, insets: [2, 2, 2, 2])) { }
-
- }
- }
-
- initAuxViews()
-
- propertyTable.model.rows.clear() //for some reason this suppress an empty row
-
- jTree.cellRenderer.setLeafIcon(swing.imageIcon(groovy.ui.Console.NODE_ICON_PATH))
- jTree.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
- jTree.addTreeSelectionListener({ TreeSelectionEvent e ->
-
- propertyTable.model.rows.clear()
- propertyTable.columnModel.getColumn(1).cellRenderer = new ButtonOrDefaultRenderer()
- propertyTable.columnModel.getColumn(1).cellEditor = new ButtonOrTextEditor()
- TreeNode node = jTree.lastSelectedPathComponent
- if (node instanceof TreeNodeWithProperties) {
- def titleSuffix = node.properties.find{ it[0] == 'text' }?.get(1)
- for (it in node.properties) {
- def propList = it
- if (propList[2] == "ListHashMap" && propList[1] != 'null' && propList[1] != '[:]') {
- //If the class is a ListHashMap, make it accessible in a new frame through a button
- def kvPairs = propList[1].substring(1, propList[1].length() - 1).tokenize(',')
- def kvFirst = kvPairs.get(0)
- def btnPanel = swing.button(
- text: "Key/value pairs: [" + kvFirst.substring(0, Math.min(25, kvFirst.size())) + "...]",
- actionPerformed: {
- def mapTable
- String title = titleSuffix ? propList[0] + " (" + titleSuffix + ")" : propList[0]
- def props = swing.frame(title: title, defaultCloseOperation: JFrame.DISPOSE_ON_CLOSE,
- show: true, locationRelativeTo: null) {
- lookAndFeel("system")
- panel {
- scrollPane() {
- mapTable = swing.table() {
- tableModel(list: [[:]]) {
- propertyColumn(header: 'Name', propertyName: 'name')
- propertyColumn(header: 'Value', propertyName: 'value')
- }
- }
- }
- }
- }
- mapTable.model.rows.clear()
- kvPairs.each {
- def kv = it.tokenize(':')
- if (kv)
- mapTable.model.rows << ["name": kv[0], "value": kv[1]]
- }
- props.pack()
- })
- propertyTable.model.rows << ["name": propList[0], "value": btnPanel, "type": propList[2]]
- btnPanel.updateUI()
- } else {
- propertyTable.model.rows << ["name": it[0], "value": it[1], "type": it[2]]
- }
- }
-
- if (inputArea && rootElement) {
- // get the line / column information to select the text represented by the current selected node
- def lineInfo = node.properties.findAll { it[0] in ['lineNumber', 'columnNumber', 'lastLineNumber', 'lastColumnNumber'] }
- def lineInfoMap = lineInfo.inject([:]) { map, info -> map[(info[0])] = Integer.valueOf(info[1]); return map }
-
- // when there are valid line / column information (ie. != -1), create a selection in the input area
- if (!lineInfoMap.every { k, v -> v == -1 }) {
- def startOffset = rootElement.getElement(lineInfoMap.lineNumber - 1).startOffset
- inputArea.setCaretPosition(startOffset + lineInfoMap.columnNumber - 1)
-
- def endOffset = rootElement.getElement(lineInfoMap.lastLineNumber - 1).startOffset
- inputArea.moveCaretPosition(endOffset + lineInfoMap.lastColumnNumber - 1)
- } else {
- // if no line number is provided, unselect the current selection
- // but keep the caret at the same position
- inputArea.moveCaretPosition(inputArea.getCaretPosition())
- }
- }
-
- if (node.classNode || node.methodNode) {
- bytecodeView.textEditor.text = '// Loading bytecode ...'
- asmifierView.textEditor.text = '// Loading ASMifier\'s output ...'
- boolean showOnlyMethodCode = node.methodNode
-
- swing.doOutside {
- def className = showOnlyMethodCode ? node.getPropertyValue('declaringClass') : node.getPropertyValue('name')
- def bytecode = classLoader.getBytecode(className)
- if (bytecode) {
- def methodName = node.getPropertyValue('name')
- def methodDescriptor = node.getPropertyValue('descriptor')
- boolean isMethodNameAndMethodDescriptorAvailable = methodName && methodDescriptor
-
- String bytecodeSource = generateSource(bytecode, {writer -> new TraceClassVisitor(new PrintWriter(writer))})
- showSource(bytecodeView, bytecodeSource, showOnlyMethodCode, isMethodNameAndMethodDescriptorAvailable, {"^.*\\n.*${Pattern.quote(methodName + methodDescriptor)}[\\s\\S]*?\\n[}|\\n]"})
-
- String asmifierSource = generateSource(bytecode, {writer -> new TraceClassVisitor(null, new ASMifier(), new PrintWriter(writer))})
- showSource(asmifierView, asmifierSource, showOnlyMethodCode, isMethodNameAndMethodDescriptorAvailable, {"^.*\\n.*${Pattern.quote(methodName)}.*?${Pattern.quote(methodDescriptor)}[\\s\\S]*?\\n[}|\\n]"})
- } else {
- swing.doLater {
- bytecodeView.textEditor.text = NO_BYTECODE_AVAILABLE_AT_THIS_PHASE
- asmifierView.textEditor.text = NO_BYTECODE_AVAILABLE_AT_THIS_PHASE
- }
- }
- }
-
- } else {
- bytecodeView.textEditor.text = ''
- asmifierView.textEditor.text = ''
- }
- }
- propertyTable.model.fireTableDataChanged()
- } as TreeSelectionListener)
-
- updateFontSize(prefs.decompiledSourceFontSize)
-
- frame.pack()
- frame.location = prefs.frameLocation
- frame.size = prefs.frameSize
- splitterPane.dividerLocation = prefs.verticalDividerLocation
- mainSplitter.dividerLocation = prefs.horizontalDividerLocation
- frame.visible = true
-
- String source = script()
- decompile(phasePicker.selectedItem.phaseId, source)
- compile(jTree, source, phasePicker.selectedItem.phaseId)
- jTree.rootVisible = false
- jTree.showsRootHandles = true // some OS's require this as a step to show nodes
-
- }
-
- private static final int INITIAL_CAPACITY = 64 * 1024 // 64K
- private String generateSource(byte[] bytecode, getVisitor) {
- def sw = new StringBuilderWriter(INITIAL_CAPACITY) // the generated code of `println 123` occupies about 618 bytes, so we should increase the initial capacity to 64K
- new ClassReader(bytecode).accept(getVisitor(sw), 0)
- return sw.toString()
- }
-
- private void showSource(view, String source, boolean showOnlyMethodCode, boolean isMethodNameAndMethodDescriptorAvailable, getPatternStr) {
- swing.doLater {
- view.textEditor.text = source
- if (showOnlyMethodCode && isMethodNameAndMethodDescriptorAvailable) {
- def pattern = Pattern.compile(getPatternStr(), Pattern.MULTILINE)
- def matcher = pattern.matcher(source)
- if (matcher.find()) {
- view.textEditor.text = source.substring(matcher.start(0), matcher.end(0))
- }
- }
-
- view.textEditor.caretPosition = 0
- }
- }
-
- void largerFont(EventObject evt = null) {
- updateFontSize(decompiledSource.textEditor.font.size + 2)
- }
-
- void smallerFont(EventObject evt = null) {
- updateFontSize(decompiledSource.textEditor.font.size - 2)
- }
-
- private final updateFontSize = { newFontSize ->
- if (newFontSize > 40) {
- newFontSize = 40
- } else if (newFontSize < 4) {
- newFontSize = 4
- }
-
- prefs.decompiledSourceFontSize = newFontSize
-
- def newDecompilerFont = new Font(decompiledSource.textEditor.font.name, decompiledSource.textEditor.font.style, newFontSize)
- decompiledSource.textEditor.font = newDecompilerFont
-
- def newFont = new Font(jTree.cellRenderer.font.name, jTree.cellRenderer.font.style, newFontSize)
- jTree.cellRenderer.font = newFont
- jTree.model.reload(jTree.model.root)
- propertyTable.tableHeader.font = newFont
- propertyTable.font = newFont
- propertyTable.rowHeight = newFontSize + 2
- }
-
- void showAbout(EventObject evt) {
- def pane = swing.optionPane()
- def version = GroovySystem.getVersion()
- pane.setMessage('An interactive GUI to explore AST capabilities\nVersion ' + version)
- def dialog = pane.createDialog(frame, 'About Groovy AST Browser')
- dialog.pack()
- dialog.visible = true
- }
-
- void showScriptFreeForm(EventObject evt) {
- showScriptFreeForm = evt.source.selected
- }
-
- void showScriptClass(EventObject evt) {
- showScriptClass = evt.source.selected
- }
-
- void showClosureClasses(EventObject evt) {
- showClosureClasses = evt.source.selected
- }
-
- void showTreeView(EventObject evt = null) {
- showTreeView = !showTreeView
- splitterPane.visible = showTreeView
- if (showTreeView) {
- mainSplitter.dividerLocation = 100
- } else {
- mainSplitter.dividerLocation = 0
- }
- }
-
- void showIndyBytecode(EventObject evt = null) {
- showIndyBytecode = evt.source.selected
- initAuxViews()
- refreshAction.actionPerformed(null)
- updateTabTitles()
- }
-
- private void updateTabTitles() {
- def tabPane = mainSplitter.bottomComponent
- int tabCount = tabPane.getTabCount()
- for (int i = 0; i < tabCount; i++) {
- def component = tabPane.getComponentAt(i);
- if (bytecodeView.is(component)) {
- tabPane.setTitleAt(i, getByteCodeTitle())
- } else if (asmifierView.is(component)) {
- tabPane.setTitleAt(i, getASMifierTitle())
- }
- }
- }
-
- private String getByteCodeTitle() {
- 'Bytecode' + (showIndyBytecode ? ' (Indy)' : '')
- }
-
- private String getASMifierTitle() {
- 'ASMifier' + (showIndyBytecode ? ' (Indy)' : '')
- }
-
- void decompile(phaseId, source) {
-
- decompiledSource.textEditor.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))
- decompiledSource.textEditor.text = 'Loading...'
-
- swing.doOutside {
- try {
-
- String result = new AstNodeToScriptAdapter().compileToScript(source, phaseId, classLoader, showScriptFreeForm, showScriptClass, config)
- swing.doLater {
- decompiledSource.textEditor.text = result
- decompiledSource.textEditor.setCaretPosition(0)
- decompiledSource.textEditor.setCursor(Cursor.defaultCursor)
- }
- } catch (Throwable t) {
- swing.doLater {
- decompiledSource.textEditor.text = t.getMessage()
- decompiledSource.textEditor.setCaretPosition(0)
- decompiledSource.textEditor.setCursor(Cursor.defaultCursor)
- }
- throw t
- }
- }
- }
-
- void compile(jTree, String script, int compilePhase) {
- jTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))
- def model = jTree.model
- swing.edt {
- def root = model.getRoot()
- root.removeAllChildren()
- root.add(new DefaultMutableTreeNode(new DefaultMutableTreeNode('Loading...')))
- model.reload(root)
- }
- swing.doOutside {
- try {
- def nodeMaker = new SwingTreeNodeMaker()
- def adapter = new ScriptToTreeNodeAdapter(classLoader, showScriptFreeForm, showScriptClass, showClosureClasses, nodeMaker, config)
- classLoader.clearBytecodeTable()
- def result = adapter.compile(script, compilePhase, showIndyBytecode)
- swing.doLater {
- model.setRoot(result)
- model.reload()
- jTree.setCursor(Cursor.defaultCursor)
- }
- } catch (Throwable t) {
- swing.doLater {
- jTree.setCursor(Cursor.defaultCursor)
- }
- throw t
- }
- }
- }
-}
-
-/**
- * This class sets and restores control positions in the browser.
- */
-@Deprecated
-class AstBrowserUiPreferences {
-
- final frameLocation
- final frameSize
- final verticalDividerLocation
- final horizontalDividerLocation
- final boolean showScriptFreeForm
- final boolean showTreeView
- final boolean showScriptClass
- final boolean showClosureClasses
- final boolean showIndyBytecode
- int decompiledSourceFontSize
- final CompilePhaseAdapter selectedPhase
-
- AstBrowserUiPreferences() {
- Preferences prefs = Preferences.userNodeForPackage(AstBrowserUiPreferences)
- frameLocation = [
- prefs.getInt('frameX', 200),
- prefs.getInt('frameY', 200)]
- frameSize = [
- prefs.getInt('frameWidth', 800),
- prefs.getInt('frameHeight', 600)]
-
- decompiledSourceFontSize = prefs.getInt('decompiledFontSize', 12)
- verticalDividerLocation = Math.max(prefs.getInt('verticalSplitterLocation', 100), 100)
- horizontalDividerLocation = Math.max(prefs.getInt('horizontalSplitterLocation', 100), 100)
- showScriptFreeForm = prefs.getBoolean('showScriptFreeForm', false)
- showScriptClass = prefs.getBoolean('showScriptClass', true)
- showClosureClasses = prefs.getBoolean('showClosureClasses', false)
- showTreeView = prefs.getBoolean('showTreeView', true)
- showIndyBytecode = prefs.getBoolean('showIndyBytecode', false)
- int phase = prefs.getInt('compilerPhase', Phases.SEMANTIC_ANALYSIS)
- selectedPhase = CompilePhaseAdapter.values().find {
- it.phaseId == phase
- }
- }
-
- def save(frame, vSplitter, hSplitter, scriptFreeFormPref, scriptClassPref, closureClassesPref, CompilePhaseAdapter phase, showTreeView, showIndyBytecode=false) {
- Preferences prefs = Preferences.userNodeForPackage(AstBrowserUiPreferences)
- prefs.putInt('decompiledFontSize', decompiledSourceFontSize as int)
- prefs.putInt('frameX', frame.location.x as int)
- prefs.putInt('frameY', frame.location.y as int)
- prefs.putInt('frameWidth', frame.size.width as int)
- prefs.putInt('frameHeight', frame.size.height as int)
- prefs.putInt('verticalSplitterLocation', vSplitter.dividerLocation)
- prefs.putInt('horizontalSplitterLocation', hSplitter.dividerLocation)
- prefs.putBoolean('showScriptFreeForm', scriptFreeFormPref)
- prefs.putBoolean('showScriptClass', scriptClassPref)
- prefs.putBoolean('showClosureClasses', closureClassesPref)
- prefs.putBoolean('showTreeView', showTreeView)
- prefs.putBoolean('showIndyBytecode', showIndyBytecode)
- prefs.putInt('compilerPhase', phase.phaseId)
- }
-}
-
-/**
- * An adapter for the CompilePhase enum that can be entered into a Swing combobox.
- */
-@CompileStatic
-@Deprecated
-enum CompilePhaseAdapter {
- INITIALIZATION(Phases.INITIALIZATION, 'Initialization'),
- PARSING(Phases.PARSING, 'Parsing'),
- CONVERSION(Phases.CONVERSION, 'Conversion'),
- SEMANTIC_ANALYSIS(Phases.SEMANTIC_ANALYSIS, 'Semantic Analysis'),
- CANONICALIZATION(Phases.CANONICALIZATION, 'Canonicalization'),
- INSTRUCTION_SELECTION(Phases.INSTRUCTION_SELECTION, 'Instruction Selection'),
- CLASS_GENERATION(Phases.CLASS_GENERATION, 'Class Generation'),
- OUTPUT(Phases.OUTPUT, 'Output'),
- FINALIZATION(Phases.FINALIZATION, 'Finalization')
-
- final int phaseId
- final String string
-
- CompilePhaseAdapter(int phaseId, String string) {
- this.phaseId = phaseId
- this.string = string
- }
-
- String toString() {
- return string
- }
-}
-
-/**
- * This class is a TreeNode and you can store additional properties on it.
- */
-@CompileStatic
-@Deprecated
-class TreeNodeWithProperties extends DefaultMutableTreeNode {
-
- List<List<String>> properties
-
- /**
- * Creates a tree node and attaches properties to it.
- * @param userObject same as a DefaultMutableTreeNode requires
- * @param properties a list of String lists
- */
- TreeNodeWithProperties(userObject, List<List<String>> properties) {
- super(userObject)
- this.properties = properties
- }
-
- String getPropertyValue(String name) {
- def match = properties.find { n, v, t -> name == n }
- return match != null ? match[1] : null
- }
-
- boolean isClassNode() {
- getPropertyValue('class') in ['class org.codehaus.groovy.ast.ClassNode', 'class org.codehaus.groovy.ast.InnerClassNode']
- }
-
- boolean isMethodNode() {
- getPropertyValue('class') in ['class org.codehaus.groovy.ast.MethodNode', 'class org.codehaus.groovy.ast.ConstructorNode']
- }
-}
-
-/**
- * This interface is used to create tree nodes of various types
- */
-@CompileStatic
-@Deprecated
-interface AstBrowserNodeMaker<T> {
- T makeNode(Object userObject)
-
- T makeNodeWithProperties(Object userObject, List<List<String>> properties)
-}
-
-/**
- * Creates tree nodes for swing UI
- */
-@CompileStatic
-@Deprecated
-class SwingTreeNodeMaker implements AstBrowserNodeMaker<DefaultMutableTreeNode> {
- DefaultMutableTreeNode makeNode(Object userObject) {
- new DefaultMutableTreeNode(userObject)
- }
-
- DefaultMutableTreeNode makeNodeWithProperties(Object userObject, List<List<String>> properties) {
- new TreeNodeWithProperties(userObject, properties)
- }
-}
-
-@Deprecated
-class BytecodeCollector extends ClassCollector {
-
- Map<String, byte[]> bytecode
-
- BytecodeCollector(ClassCollector delegate, Map<String,byte[]> bytecode) {
- super(delegate.cl, delegate.unit, delegate.su)
- this.bytecode = bytecode
- }
-
- @Override
- protected Class createClass(byte[] code, ClassNode classNode) {
- bytecode[classNode.name] = code
- return super.createClass(code, classNode)
- }
-
-}
-
-@CompileStatic
-@Deprecated
-class GeneratedBytecodeAwareGroovyClassLoader extends GroovyClassLoader {
-
- private final Map<String, byte[]> bytecode = new HashMap<String, byte[]>()
-
- GeneratedBytecodeAwareGroovyClassLoader(final GroovyClassLoader parent) {
- super(parent)
- }
-
- @Override
- protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) {
- def collector = super.createCollector(unit, su)
- new BytecodeCollector(collector, bytecode)
- }
-
- void clearBytecodeTable() {
- bytecode.clear()
- }
-
- byte[] getBytecode(final String className) {
- bytecode[className]
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy
deleted file mode 100644
index 9f75dcd..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy
+++ /dev/null
@@ -1,1185 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.transform.CompileStatic
-import org.apache.groovy.io.StringBuilderWriter
-import org.codehaus.groovy.ast.ASTNode
-import org.codehaus.groovy.ast.AnnotationNode
-import org.codehaus.groovy.ast.ClassHelper
-import org.codehaus.groovy.ast.ClassNode
-import org.codehaus.groovy.ast.ConstructorNode
-import org.codehaus.groovy.ast.FieldNode
-import org.codehaus.groovy.ast.GenericsType
-import org.codehaus.groovy.ast.GroovyClassVisitor
-import org.codehaus.groovy.ast.GroovyCodeVisitor
-import org.codehaus.groovy.ast.ImportNode
-import org.codehaus.groovy.ast.MethodNode
-import org.codehaus.groovy.ast.PackageNode
-import org.codehaus.groovy.ast.Parameter
-import org.codehaus.groovy.ast.PropertyNode
-import org.codehaus.groovy.ast.expr.ArgumentListExpression
-import org.codehaus.groovy.ast.expr.ArrayExpression
-import org.codehaus.groovy.ast.expr.AttributeExpression
-import org.codehaus.groovy.ast.expr.BinaryExpression
-import org.codehaus.groovy.ast.expr.BitwiseNegationExpression
-import org.codehaus.groovy.ast.expr.BooleanExpression
-import org.codehaus.groovy.ast.expr.CastExpression
-import org.codehaus.groovy.ast.expr.ClassExpression
-import org.codehaus.groovy.ast.expr.ClosureExpression
-import org.codehaus.groovy.ast.expr.ClosureListExpression
-import org.codehaus.groovy.ast.expr.ConstantExpression
-import org.codehaus.groovy.ast.expr.ConstructorCallExpression
-import org.codehaus.groovy.ast.expr.DeclarationExpression
-import org.codehaus.groovy.ast.expr.ElvisOperatorExpression
-import org.codehaus.groovy.ast.expr.EmptyExpression
-import org.codehaus.groovy.ast.expr.Expression
-import org.codehaus.groovy.ast.expr.FieldExpression
-import org.codehaus.groovy.ast.expr.GStringExpression
-import org.codehaus.groovy.ast.expr.LambdaExpression
-import org.codehaus.groovy.ast.expr.ListExpression
-import org.codehaus.groovy.ast.expr.MapEntryExpression
-import org.codehaus.groovy.ast.expr.MapExpression
-import org.codehaus.groovy.ast.expr.MethodCallExpression
-import org.codehaus.groovy.ast.expr.MethodPointerExpression
-import org.codehaus.groovy.ast.expr.MethodReferenceExpression
-import org.codehaus.groovy.ast.expr.NotExpression
-import org.codehaus.groovy.ast.expr.PostfixExpression
-import org.codehaus.groovy.ast.expr.PrefixExpression
-import org.codehaus.groovy.ast.expr.PropertyExpression
-import org.codehaus.groovy.ast.expr.RangeExpression
-import org.codehaus.groovy.ast.expr.SpreadExpression
-import org.codehaus.groovy.ast.expr.SpreadMapExpression
-import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
-import org.codehaus.groovy.ast.expr.TernaryExpression
-import org.codehaus.groovy.ast.expr.TupleExpression
-import org.codehaus.groovy.ast.expr.UnaryMinusExpression
-import org.codehaus.groovy.ast.expr.UnaryPlusExpression
-import org.codehaus.groovy.ast.expr.VariableExpression
-import org.codehaus.groovy.ast.stmt.AssertStatement
-import org.codehaus.groovy.ast.stmt.BlockStatement
-import org.codehaus.groovy.ast.stmt.BreakStatement
-import org.codehaus.groovy.ast.stmt.CaseStatement
-import org.codehaus.groovy.ast.stmt.CatchStatement
-import org.codehaus.groovy.ast.stmt.ContinueStatement
-import org.codehaus.groovy.ast.stmt.DoWhileStatement
-import org.codehaus.groovy.ast.stmt.EmptyStatement
-import org.codehaus.groovy.ast.stmt.ExpressionStatement
-import org.codehaus.groovy.ast.stmt.ForStatement
-import org.codehaus.groovy.ast.stmt.IfStatement
-import org.codehaus.groovy.ast.stmt.ReturnStatement
-import org.codehaus.groovy.ast.stmt.Statement
-import org.codehaus.groovy.ast.stmt.SwitchStatement
-import org.codehaus.groovy.ast.stmt.SynchronizedStatement
-import org.codehaus.groovy.ast.stmt.ThrowStatement
-import org.codehaus.groovy.ast.stmt.TryCatchStatement
-import org.codehaus.groovy.ast.stmt.WhileStatement
-import org.codehaus.groovy.classgen.BytecodeExpression
-import org.codehaus.groovy.classgen.GeneratorContext
-import org.codehaus.groovy.classgen.Verifier
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.CompilationUnit
-import org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation
-import org.codehaus.groovy.control.CompilePhase
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.SourceUnit
-import org.codehaus.groovy.syntax.Types
-
-import java.lang.reflect.Modifier
-import java.security.CodeSource
-
-/**
- * This class takes Groovy source code, compiles it to a specific compile phase, and then decompiles it
- * back to the groovy source. It is used by GroovyConsole's AST Browser, but can also be invoked from
- * the command line.
- */
-@CompileStatic
-@Deprecated
-class AstNodeToScriptAdapter {
-
- /**
- * Run this class as a script to compile a groovy file and print out the resulting source.
- * @param args
- * a filename to compile and a CompilePhase to run to
- */
- static void main(String[] args) {
-
- if (!args || args.length < 2) {
- println '''
-Usage: java groovy.inspect.swingui.AstNodeToScriptAdapter [filename] [compilephase]
-where [filename] is a Groovy script
-and [compilephase] is a valid Integer based org.codehaus.groovy.control.CompilePhase'''
- } else {
- def file = new File((String) args[0])
- def phase = CompilePhase.fromPhaseNumber(args[1] as int)
- if (!file.exists()) {
- println "File ${args[0]} cannot be found."
- } else if (phase == null) {
- println "Compile phase ${args[1]} cannot be mapped to a org.codehaus.groovy.control.CompilePhase."
- } else {
- println new AstNodeToScriptAdapter().compileToScript(file.text, phase.getPhaseNumber())
- }
- }
- }
-
- /**
- * This method takes source code, compiles it, then reverses it back to source.
- *
- * @param script
- * the source code to be compiled. If invalid, a compile error occurs
- * @param compilePhase
- * the CompilePhase. Must be an int mapped in {@link CompilePhase}
- * @param classLoader
- * (optional) the classloader to use. If missing/null then the current is used.
- * This parameter enables things like ASTBrowser to invoke this with the correct classpath
- * @param showScriptFreeForm
- * Whether or not to show the script portion of the source code
- * @param showScriptClass
- * Whether or not to show the Script class from the source code
- * @param config
- * optional compiler configuration
- * @returns the source code from the AST state
- */
-
- String compileToScript(String script, int compilePhase, ClassLoader classLoader = null, boolean showScriptFreeForm = true, boolean showScriptClass = true, CompilerConfiguration config = null) {
-
- def writer = new StringBuilderWriter()
-
- classLoader = classLoader ?: new GroovyClassLoader(getClass().classLoader)
-
- def scriptName = 'script' + System.currentTimeMillis() + '.groovy'
- GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptName, '/groovy/script')
- CompilationUnit cu = new CompilationUnit((CompilerConfiguration) (config ?: CompilerConfiguration.DEFAULT), (CodeSource) codeSource.codeSource, (GroovyClassLoader) classLoader)
- cu.addPhaseOperation(new AstNodeToScriptVisitor(writer, showScriptFreeForm, showScriptClass), compilePhase)
- cu.addSource(codeSource.getName(), script)
- try {
- cu.compile(compilePhase)
- } catch (CompilationFailedException cfe) {
-
- writer.println 'Unable to produce AST for this phase due to earlier compilation error:'
- cfe.message.eachLine {
- writer.println it
- }
- writer.println 'Fix the above error(s) and then press Refresh'
- } catch (Throwable t) {
- writer.println 'Unable to produce AST for this phase due to an error:'
- writer.println t.getMessage()
- writer.println 'Fix the above error(s) and then press Refresh'
- }
- return writer.toString()
- }
-}
-
-/**
- * An adapter from ASTNode tree to source code.
- */
-@CompileStatic
-@Deprecated
-class AstNodeToScriptVisitor extends PrimaryClassNodeOperation implements GroovyCodeVisitor, GroovyClassVisitor {
-
- private final Writer _out
- Stack<String> classNameStack = new Stack<String>()
- String _indent = ''
- boolean readyToIndent = true
- boolean showScriptFreeForm
- boolean showScriptClass
- boolean scriptHasBeenVisited
-
- def AstNodeToScriptVisitor(Writer writer, boolean showScriptFreeForm = true, boolean showScriptClass = true) {
- this._out = writer
- this.showScriptFreeForm = showScriptFreeForm
- this.showScriptClass = showScriptClass
- this.scriptHasBeenVisited = false
- }
-
- void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
-
- visitPackage(source?.getAST()?.getPackage())
-
- visitAllImports(source)
-
- if (showScriptFreeForm && !scriptHasBeenVisited) {
- scriptHasBeenVisited = true
- source?.getAST()?.getStatementBlock()?.visit(this)
- }
- if (showScriptClass || !classNode.isScript()) {
- visitClass classNode
- }
- }
-
- private def visitAllImports(SourceUnit source) {
- boolean staticImportsPresent = false
- boolean importsPresent = false
-
- source?.getAST()?.getStaticImports()?.values()?.each {
- visitImport(it)
- staticImportsPresent = true
- }
- source?.getAST()?.getStaticStarImports()?.values()?.each {
- visitImport(it)
- staticImportsPresent = true
- }
-
- if (staticImportsPresent) {
- printDoubleBreak()
- }
-
- source?.getAST()?.getImports()?.each {
- visitImport(it)
- importsPresent = true
- }
- source?.getAST()?.getStarImports()?.each {
- visitImport(it)
- importsPresent = true
- }
- if (importsPresent) {
- printDoubleBreak()
- }
- }
-
-
- void print(parameter) {
- def output = parameter.toString()
-
- if (readyToIndent) {
- _out.print _indent
- readyToIndent = false
- while (output.startsWith(' ')) {
- output = output[1..-1] // trim left
- }
- }
- if (_out.toString().endsWith(' ')) {
- if (output.startsWith(' ')) {
- output = output[1..-1]
- }
- }
- _out.print output
- }
-
- def println(parameter) {
- throw new UnsupportedOperationException('Wrong API')
- }
-
- def indented(Closure block) {
- String startingIndent = _indent
- _indent = _indent + ' '
- block()
- _indent = startingIndent
- }
-
- def printLineBreak() {
- if (!_out.toString().endsWith('\n')) {
- _out.print '\n'
- }
- readyToIndent = true
- }
-
- def printDoubleBreak() {
- if (_out.toString().endsWith('\n\n')) {
- // do nothing
- } else if (_out.toString().endsWith('\n')) {
- _out.print '\n'
- } else {
- _out.print '\n'
- _out.print '\n'
- }
- readyToIndent = true
- }
-
- void visitPackage(PackageNode packageNode) {
-
- if (packageNode) {
-
- packageNode.annotations?.each {
- visitAnnotationNode(it)
- printLineBreak()
- }
-
- if (packageNode.text.endsWith('.')) {
- print packageNode.text[0..-2]
- } else {
- print packageNode.text
- }
- printDoubleBreak()
- }
- }
-
- void visitImport(ImportNode node) {
- if (node) {
- node.annotations?.each {
- visitAnnotationNode(it)
- printLineBreak()
- }
- print node.text
- printLineBreak()
- }
- }
-
- @Override
- void visitClass(ClassNode node) {
-
- classNameStack.push(node.name)
-
- node?.annotations?.each {
- visitAnnotationNode(it)
- printLineBreak()
- }
-
- visitModifiers(node.modifiers)
- if (node.isInterface()) print node.name
- else print "class $node.name"
- visitGenerics node?.genericsTypes
- print ' extends '
- visitType node.unresolvedSuperClass
- boolean first = true
- node.unresolvedInterfaces?.each {
- if (!first) {
- print ', '
- } else {
- print ' implements '
- }
- first = false
- visitType it
- }
- print ' { '
- printDoubleBreak()
-
- indented {
- node?.properties?.each { visitProperty(it) }
- printLineBreak()
- node?.fields?.each { visitField(it) }
- printDoubleBreak()
- node?.declaredConstructors?.each { visitConstructor(it) }
- printLineBreak()
- visitObjectInitializerBlocks(node)
- printLineBreak()
- node?.methods?.each { visitMethod(it) }
- }
- print '}'
- printLineBreak()
- classNameStack.pop()
- }
-
- private void visitObjectInitializerBlocks(ClassNode node) {
- for (Statement stmt : node.getObjectInitializerStatements()) {
- print '{'
- printLineBreak()
- indented {
- stmt.visit(this)
- }
- printLineBreak()
- print '}'
- printDoubleBreak()
- }
- }
-
- private void visitGenerics(GenericsType[] generics) {
-
- if (generics) {
- print '<'
- boolean first = true
- generics.each { GenericsType it ->
- if (!first) {
- print ', '
- }
- first = false
- print it.name
- if (it.upperBounds) {
- print ' extends '
- boolean innerFirst = true
- it.upperBounds.each { ClassNode upperBound ->
- if (!innerFirst) {
- print ' & '
- }
- innerFirst = false
- visitType upperBound
- }
- }
- if (it.lowerBound) {
- print ' super '
- visitType it.lowerBound
- }
- }
- print '>'
- }
- }
-
- @Override
- void visitConstructor(ConstructorNode node) {
- visitMethod(node)
- }
-
- private String visitParameters(parameters) {
- boolean first = true
-
- parameters.each { Parameter it ->
- if (!first) {
- print ', '
- }
- first = false
-
- it.annotations?.each {
- visitAnnotationNode(it)
- print(' ')
- }
-
- visitModifiers(it.modifiers)
- visitType it.type
- print ' ' + it.name
- if (it.initialExpression && !(it.initialExpression instanceof EmptyExpression)) {
- print ' = '
- it.initialExpression.visit this
- }
- }
- }
-
- @Override
- void visitMethod(MethodNode node) {
- node?.annotations?.each {
- visitAnnotationNode(it)
- printLineBreak()
- }
-
- visitModifiers(node.modifiers)
- if (node.name == '<init>') {
- print "${classNameStack.peek()}("
- visitParameters(node.parameters)
- print ') {'
- printLineBreak()
- } else if (node.name == '<clinit>') {
- print '{ ' // will already have 'static' from modifiers
- printLineBreak()
- } else {
- visitType node.returnType
- print " $node.name("
- visitParameters(node.parameters)
- print ')'
- if (node.exceptions) {
- boolean first = true
- print ' throws '
- node.exceptions.each {
- if (!first) {
- print ', '
- }
- first = false
- visitType it
- }
- }
- print ' {'
- printLineBreak()
- }
-
- indented {
- node?.code?.visit(this)
- }
- printLineBreak()
- print '}'
- printDoubleBreak()
- }
-
- private void visitModifiers(int modifiers) {
- String mods = Modifier.toString(modifiers)
- mods = mods ? mods + ' ' : mods
- print mods
- }
-
- @Override
- void visitField(FieldNode node) {
- node?.annotations?.each {
- visitAnnotationNode(it)
- printLineBreak()
- }
- visitModifiers(node.modifiers)
- visitType node.type
- print " $node.name "
- // do not print initial expression, as this is executed as part of the constructor, unless on static constant
- Expression exp = node.initialValueExpression
- if (exp instanceof ConstantExpression) exp = Verifier.transformToPrimitiveConstantIfPossible(exp)
- ClassNode type = exp?.type
- if (Modifier.isStatic(node.modifiers) && Modifier.isFinal(node.getModifiers())
- && exp instanceof ConstantExpression
- && type == node.type
- && ClassHelper.isStaticConstantInitializerType(type)) {
- // GROOVY-5150: final constants may be initialized directly
- print ' = '
- if (ClassHelper.STRING_TYPE == type) {
- print "'" + node.initialValueExpression.text.replaceAll("'", "\\\\'") + "'"
- } else if (ClassHelper.char_TYPE == type) {
- print "'${node.initialValueExpression.text}'"
- } else {
- print node.initialValueExpression.text
- }
- }
- printLineBreak()
- }
-
- void visitAnnotationNode(AnnotationNode node) {
- print '@' + node?.classNode?.name
- if (node?.members) {
- print '('
- boolean first = true
- node.members.each { String name, Expression value ->
- if (first) {
- first = false
- } else {
- print ', '
- }
- print name + ' = '
- value.visit(this)
- }
- print ')'
- }
-
- }
-
- @Override
- void visitProperty(PropertyNode node) {
- // is a FieldNode, avoid double dispatch
- }
-
- @Override
- void visitBlockStatement(BlockStatement block) {
- if (printStatementLabels(block)) {
- print '{'
- printLineBreak()
- indented {
- block?.statements?.each {
- it.visit(this)
- printLineBreak()
- }
- }
- print '}'
- printLineBreak()
- } else {
- block?.statements?.each {
- it.visit(this)
- printLineBreak()
- }
- }
- if (!_out.toString().endsWith('\n')) {
- printLineBreak()
- }
- }
-
- @Override
- void visitForLoop(ForStatement statement) {
- printStatementLabels(statement)
- print 'for ('
- if (statement?.variable != ForStatement.FOR_LOOP_DUMMY) {
- visitParameters([statement.variable])
- print ' : '
- }
-
- if (statement?.collectionExpression instanceof ListExpression) {
- statement?.collectionExpression?.visit this
- } else {
- statement?.collectionExpression?.visit this
- }
- print ') {'
- printLineBreak()
- indented {
- statement?.loopBlock?.visit this
- }
- print '}'
- printLineBreak()
- }
-
- @Override
- void visitIfElse(IfStatement ifElse) {
- printStatementLabels(ifElse)
- print 'if ('
- ifElse?.booleanExpression?.visit this
- print ') {'
- printLineBreak()
- indented {
- ifElse?.ifBlock?.visit this
- }
- printLineBreak()
- if (ifElse?.elseBlock && !(ifElse.elseBlock instanceof EmptyStatement)) {
- print '} else {'
- printLineBreak()
- indented {
- ifElse?.elseBlock?.visit this
- }
- printLineBreak()
- }
- print '}'
- printLineBreak()
- }
-
- @Override
- void visitExpressionStatement(ExpressionStatement statement) {
- statement.expression.visit this
- }
-
- @Override
- void visitReturnStatement(ReturnStatement statement) {
- printLineBreak()
- print 'return '
- statement.getExpression().visit(this)
- printLineBreak()
- }
-
- @Override
- void visitSwitch(SwitchStatement statement) {
- printStatementLabels(statement)
- print 'switch ('
- statement?.expression?.visit this
- print ') {'
- printLineBreak()
- indented {
- statement?.caseStatements?.each {
- visitCaseStatement it
- }
- if (statement?.defaultStatement) {
- print 'default: '
- printLineBreak()
- statement?.defaultStatement?.visit this
- }
- }
- print '}'
- printLineBreak()
- }
-
- @Override
- void visitCaseStatement(CaseStatement statement) {
- print 'case '
- statement?.expression?.visit this
- print ':'
- printLineBreak()
- indented {
- statement?.code?.visit this
- }
- }
-
- @Override
- void visitBreakStatement(BreakStatement statement) {
- print 'break'
- if (statement?.label) {
- print ' ' + statement.label
- }
- printLineBreak()
- }
-
- @Override
- void visitContinueStatement(ContinueStatement statement) {
- print 'continue'
- if (statement?.label) {
- print ' ' + statement.label
- }
- printLineBreak()
- }
-
- @Override
- void visitMethodCallExpression(MethodCallExpression expression) {
-
- Expression objectExp = expression.getObjectExpression()
- if (objectExp instanceof VariableExpression) {
- visitVariableExpression(objectExp, false)
- } else {
- objectExp.visit(this)
- }
- if (expression.spreadSafe) {
- print '*'
- }
- if (expression.safe) {
- print '?'
- }
- print '.'
- Expression method = expression.getMethod()
- if (method instanceof ConstantExpression) {
- visitConstantExpression(method, true)
- } else {
- method.visit(this)
- }
- expression.getArguments().visit(this)
- }
-
- @Override
- void visitStaticMethodCallExpression(StaticMethodCallExpression expression) {
- print expression?.ownerType?.name + '.' + expression?.method
- if (expression?.arguments instanceof VariableExpression || expression?.arguments instanceof MethodCallExpression) {
- print '('
- expression?.arguments?.visit this
- print ')'
- } else {
- expression?.arguments?.visit this
- }
- }
-
- @Override
- void visitConstructorCallExpression(ConstructorCallExpression expression) {
- if (expression?.isSuperCall()) {
- print 'super'
- } else if (expression?.isThisCall()) {
- print 'this '
- } else {
- print 'new '
- visitType expression?.type
- }
- expression?.arguments?.visit this
- }
-
- @Override
- void visitBinaryExpression(BinaryExpression expression) {
- expression?.leftExpression?.visit this
- if (!(expression.rightExpression instanceof EmptyExpression) || expression.operation.type != Types.ASSIGN) {
- print " $expression.operation.text "
- expression.rightExpression.visit this
-
- if (expression?.operation?.text == '[') {
- print ']'
- }
- }
- }
-
- @Override
- void visitPostfixExpression(PostfixExpression expression) {
- print '('
- expression?.expression?.visit this
- print ')'
- print expression?.operation?.text
- }
-
- @Override
- void visitPrefixExpression(PrefixExpression expression) {
- print expression?.operation?.text
- print '('
- expression?.expression?.visit this
- print ')'
- }
-
-
- @Override
- void visitClosureExpression(ClosureExpression expression) {
- print '{ '
- if (expression?.parameters) {
- visitParameters(expression?.parameters)
- print ' ->'
- }
- printLineBreak()
- indented {
- expression?.code?.visit this
- }
- print '}'
- }
-
- @Override
- void visitLambdaExpression(LambdaExpression expression) {
- print '( '
- if (expression?.parameters) {
- visitParameters(expression?.parameters)
- }
- print ') -> {'
- printLineBreak()
- indented {
- expression?.code?.visit this
- }
- print '}'
- }
-
- @Override
- void visitTupleExpression(TupleExpression expression) {
- print '('
- visitExpressionsAndCommaSeparate(expression?.expressions)
- print ')'
- }
-
- @Override
- void visitRangeExpression(RangeExpression expression) {
- print '('
- expression?.from?.visit this
- print '..'
- expression?.to?.visit this
- print ')'
- }
-
- @Override
- void visitPropertyExpression(PropertyExpression expression) {
- expression?.objectExpression?.visit this
- if (expression?.spreadSafe) {
- print '*'
- } else if (expression?.isSafe()) {
- print '?'
- }
- print '.'
- if (expression?.property instanceof ConstantExpression) {
- visitConstantExpression((ConstantExpression) expression?.property, true)
- } else {
- expression?.property?.visit this
- }
- }
-
- @Override
- void visitAttributeExpression(AttributeExpression attributeExpression) {
- visitPropertyExpression attributeExpression
- }
-
- @Override
- void visitFieldExpression(FieldExpression expression) {
- print expression?.field?.name
- }
-
- void visitConstantExpression(ConstantExpression expression, boolean unwrapQuotes = false) {
- if (expression.value instanceof String && !unwrapQuotes) {
- // string reverse escaping is very naive
- def escaped = ((String) expression.value).replaceAll('\n', '\\\\n').replaceAll("'", "\\\\'")
- print "'$escaped'"
- } else {
- print expression.value
- }
- }
-
- @Override
- void visitClassExpression(ClassExpression expression) {
- print expression.text
- }
-
- void visitVariableExpression(VariableExpression expression, boolean spacePad = true) {
-
- if (spacePad) {
- print ' ' + expression.name + ' '
- } else {
- print expression.name
- }
- }
-
- @Override
- void visitDeclarationExpression(DeclarationExpression expression) {
- // handle multiple assignment expressions
- if (expression?.leftExpression instanceof ArgumentListExpression) {
- print 'def '
- visitArgumentlistExpression((ArgumentListExpression) expression?.leftExpression, true)
- print " $expression.operation.text "
- expression.rightExpression.visit this
-
- if (expression?.operation?.text == '[') {
- print ']'
- }
- } else {
- visitType expression?.leftExpression?.type
- visitBinaryExpression expression // is a BinaryExpression
- }
- }
-
- @Override
- void visitGStringExpression(GStringExpression expression) {
- print '"' + expression.text + '"'
- }
-
- @Override
- void visitSpreadExpression(SpreadExpression expression) {
- print '*'
- expression?.expression?.visit this
- }
-
- @Override
- void visitNotExpression(NotExpression expression) {
- print '!('
- expression?.expression?.visit this
- print ')'
- }
-
- @Override
- void visitUnaryMinusExpression(UnaryMinusExpression expression) {
- print '-('
- expression?.expression?.visit this
- print ')'
- }
-
- @Override
- void visitUnaryPlusExpression(UnaryPlusExpression expression) {
- print '+('
- expression?.expression?.visit this
- print ')'
- }
-
- @Override
- void visitCastExpression(CastExpression expression) {
- print '(('
- expression?.expression?.visit this
- print ') as '
- visitType(expression?.type)
- print ')'
-
- }
-
- /**
- * Prints out the type, safely handling arrays.
- * @param classNode
- */
- void visitType(ClassNode classNode) {
- def name = classNode.name
- if (name =~ /^\[+L/ && name.endsWith(';')) {
- int numDimensions = name.indexOf('L')
- print "${classNode.name[(numDimensions + 1)..-2]}" + ('[]' * numDimensions)
- } else {
- print name
- }
- visitGenerics classNode?.genericsTypes
- }
-
- void visitArgumentlistExpression(ArgumentListExpression expression, boolean showTypes = false) {
- print '('
- int count = expression?.expressions?.size()
- expression.expressions.each {
- if (showTypes) {
- visitType it.type
- print ' '
- }
- if (it instanceof VariableExpression) {
- visitVariableExpression it, false
- } else if (it instanceof ConstantExpression) {
- visitConstantExpression it, false
- } else {
- it.visit this
- }
- count--
- if (count) print ', '
- }
- print ')'
- }
-
- @Override
- void visitBytecodeExpression(BytecodeExpression expression) {
- print '/*BytecodeExpression*/'
- printLineBreak()
- }
-
-
- @Override
- void visitMapExpression(MapExpression expression) {
- print '['
- if (expression?.mapEntryExpressions?.size() == 0) {
- print ':'
- } else {
- visitExpressionsAndCommaSeparate((List) expression?.mapEntryExpressions)
- }
- print ']'
- }
-
- @Override
- void visitMapEntryExpression(MapEntryExpression expression) {
- if (expression?.keyExpression instanceof SpreadMapExpression) {
- print '*' // is this correct?
- } else {
- expression?.keyExpression?.visit this
- }
- print ': '
- expression?.valueExpression?.visit this
- }
-
- @Override
- void visitListExpression(ListExpression expression) {
- print '['
- visitExpressionsAndCommaSeparate(expression?.expressions)
- print ']'
- }
-
- @Override
- void visitTryCatchFinally(TryCatchStatement statement) {
- printStatementLabels(statement)
- print 'try {'
- printLineBreak()
- indented {
- statement?.tryStatement?.visit this
- }
- printLineBreak()
- print '} '
- printLineBreak()
- statement?.catchStatements?.each { CatchStatement catchStatement ->
- visitCatchStatement(catchStatement)
- }
- print 'finally { '
- printLineBreak()
- indented {
- statement?.finallyStatement?.visit this
- }
- print '} '
- printLineBreak()
- }
-
- @Override
- void visitThrowStatement(ThrowStatement statement) {
- print 'throw '
- statement?.expression?.visit this
- printLineBreak()
- }
-
- @Override
- void visitSynchronizedStatement(SynchronizedStatement statement) {
- printStatementLabels(statement)
- print 'synchronized ('
- statement?.expression?.visit this
- print ') {'
- printLineBreak()
- indented {
- statement?.code?.visit this
- }
- print '}'
- }
-
- @Override
- void visitTernaryExpression(TernaryExpression expression) {
- expression?.booleanExpression?.visit this
- print ' ? '
- expression?.trueExpression?.visit this
- print ' : '
- expression?.falseExpression?.visit this
- }
-
- @Override
- void visitShortTernaryExpression(ElvisOperatorExpression expression) {
- visitTernaryExpression(expression)
- }
-
- @Override
- void visitBooleanExpression(BooleanExpression expression) {
- expression?.expression?.visit this
- }
-
- @Override
- void visitWhileLoop(WhileStatement statement) {
- printStatementLabels(statement)
- print 'while ('
- statement?.booleanExpression?.visit this
- print ') {'
- printLineBreak()
- indented {
- statement?.loopBlock?.visit this
- }
- printLineBreak()
- print '}'
- printLineBreak()
- }
-
- @Override
- void visitDoWhileLoop(DoWhileStatement statement) {
- printStatementLabels(statement)
- print 'do {'
- printLineBreak()
- indented {
- statement?.loopBlock?.visit this
- }
- print '} while ('
- statement?.booleanExpression?.visit this
- print ')'
- printLineBreak()
- }
-
- @Override
- void visitCatchStatement(CatchStatement statement) {
- print 'catch ('
- visitParameters([statement.variable])
- print ') {'
- printLineBreak()
- indented {
- statement.code?.visit this
- }
- print '} '
- printLineBreak()
- }
-
- @Override
- void visitBitwiseNegationExpression(BitwiseNegationExpression expression) {
- print '~('
- expression?.expression?.visit this
- print ') '
- }
-
- @Override
- void visitAssertStatement(AssertStatement statement) {
- print 'assert '
- statement?.booleanExpression?.visit this
- print ' : '
- statement?.messageExpression?.visit this
- }
-
- @Override
- void visitClosureListExpression(ClosureListExpression expression) {
- boolean first = true
- expression?.expressions?.each {
- if (!first) {
- print ';'
- }
- first = false
- it.visit this
- }
- }
-
- @Override
- void visitMethodPointerExpression(MethodPointerExpression expression) {
- expression?.expression?.visit this
- print '.&'
- expression?.methodName?.visit this
- }
-
- @Override
- void visitMethodReferenceExpression(MethodReferenceExpression expression) {
- expression?.expression?.visit this
- print '::'
- expression?.methodName?.visit this
- }
-
- @Override
- void visitArrayExpression(ArrayExpression expression) {
- print 'new '
- visitType expression?.elementType
- print '['
- visitExpressionsAndCommaSeparate(expression?.sizeExpression)
- print ']'
- }
-
- private void visitExpressionsAndCommaSeparate(List<? super Expression> expressions) {
- boolean first = true
- expressions?.each {
- if (!first) {
- print ', '
- }
- first = false
- ((ASTNode) it).visit this
- }
- }
-
- @Override
- void visitSpreadMapExpression(SpreadMapExpression expression) {
- print '*:'
- expression?.expression?.visit this
- }
-
- /**
- * Prints all labels for the given statement. The labels will be printed on a single
- * line and line break will be added.
- *
- * @param statement for which to print labels
- * @return {@code true} if the statement had labels to print, else {@code false}
- */
- private boolean printStatementLabels(Statement statement) {
- List<String> labels = statement?.statementLabels
- if (labels == null || labels.isEmpty()) {
- return false
- }
- for (String label : labels) {
- print label + ':'
- printLineBreak()
- }
- return true
- }
-
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrDefaultRenderer.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrDefaultRenderer.groovy
deleted file mode 100644
index 2e7a880..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrDefaultRenderer.groovy
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.transform.CompileStatic
-
-import javax.swing.*
-import javax.swing.table.DefaultTableCellRenderer
-import java.awt.*
-
-/**
- * A table cell renderer that will return a component instead of drawing it,
- * or call the default in the case of a non component object.
- * This hack allows to render a button shape in a table cell.
- */
-@CompileStatic
-@Deprecated
-class ButtonOrDefaultRenderer extends DefaultTableCellRenderer {
- Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
- if (value instanceof JComponent) {
- value.setSize(Math.round(value.getSize().getWidth())?.toInteger(), table.getRowHeight(row))
- return value
- }
- return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column)
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrTextEditor.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrTextEditor.groovy
deleted file mode 100644
index 9bc9b3b..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ButtonOrTextEditor.groovy
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.transform.CompileStatic
-
-import javax.swing.*
-import javax.swing.table.TableCellEditor
-import java.awt.*
-import java.awt.event.ActionListener
-import java.awt.event.FocusListener
-
-/**
- * A table cell editor that will return a button automatically if it is the cell value,
- * a text field if the value exists, or null otherwise (non editable cell).
- * This hack allows to interact with buttons in a cell.
- */
-@CompileStatic
-@Deprecated
-class ButtonOrTextEditor extends AbstractCellEditor implements TableCellEditor {
- /** The Swing component being edited. */
- protected JComponent editorComponent
-
- @Override
- Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
- if (value instanceof JButton) {
- editorComponent = value
- ((JButton) editorComponent).addActionListener({ fireEditingStopped() } as ActionListener)
- } else if (value instanceof JTextArea) {
- editorComponent = value
- } else if (value) {
- editorComponent = new JTextArea(value.toString())
- editorComponent.addFocusListener({ fireEditingCanceled() } as FocusListener)
- } else {
- editorComponent = null
- }
- editorComponent
- }
-
- @Override
- Object getCellEditorValue() {
- editorComponent
- }
-}
-
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ObjectBrowser.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ObjectBrowser.groovy
deleted file mode 100644
index 92f44aa..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ObjectBrowser.groovy
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.inspect.Inspector
-import groovy.swing.SwingBuilder
-
-import javax.swing.*
-import java.awt.*
-
-import static groovy.inspect.Inspector.MEMBER_DECLARER_IDX
-import static groovy.inspect.Inspector.MEMBER_EXCEPTIONS_IDX
-import static groovy.inspect.Inspector.MEMBER_MODIFIER_IDX
-import static groovy.inspect.Inspector.MEMBER_NAME_IDX
-import static groovy.inspect.Inspector.MEMBER_ORIGIN_IDX
-import static groovy.inspect.Inspector.MEMBER_PARAMS_IDX
-import static groovy.inspect.Inspector.MEMBER_TYPE_IDX
-import static groovy.inspect.Inspector.MEMBER_VALUE_IDX
-
-/**
- * A little GUI to show some of the Inspector capabilities.
- * Starting this script opens the ObjectBrowser on "some String".
- * Use it in groovysh or groovyConsole to inspect your object of interest with:
- * <code>
- * ObjectBrowser.inspect(myObject)
- * </code>.
- */
-@Deprecated
-class ObjectBrowser {
-
- def inspector
- def swing, frame, fieldTable, methodTable, itemTable, mapTable
-
- static void main(args) {
- inspect('some String')
- }
-
- static void inspect(objectUnderInspection) {
- def browser = new ObjectBrowser()
- browser.inspector = new Inspector(objectUnderInspection)
- browser.run()
- }
-
- void run() {
- swing = new SwingBuilder()
-
- frame = swing.frame(title: 'Groovy Object Browser', location: [200, 200],
- size: [800, 600], pack: true, show: true,
- iconImage: swing.imageIcon(groovy.ui.Console.ICON_PATH).image,
- defaultCloseOperation: WindowConstants.DISPOSE_ON_CLOSE) {
-
- menuBar {
- menu(text: 'Help') {
- menuItem { action(name: 'About', closure: this.&showAbout) }
- }
- }
- panel {
- borderLayout()
- panel(name: 'Class Info',
- border: emptyBorder([5, 10, 5, 10]),
- constraints: NORTH) {
- flowLayout(alignment: FlowLayout.LEFT)
- def props = inspector.classProps
- def classLabel = '<html>' + props.join('<br>')
- label(classLabel)
- }
- tabbedPane(constraints: CENTER) {
- if (inspector.object instanceof Collection) {
- scrollPane(name: ' Collection data ') {
- itemTable = table {
- int i = 0
- def data = inspector.object.collect { val -> [i++, val] }
- tableModel(list: data) {
- closureColumn(header: 'Index', read: { it[0] })
- closureColumn(header: 'Value', read: { it[1] })
- }
- }
- }
- }
- if (inspector.object instanceof Map) {
- scrollPane(name: ' Map data ') {
- itemTable = table {
- int i = 0
- def data = inspector.object.collect { key, val -> [i++, key, val] }
- tableModel(list: data) {
- closureColumn(header: 'Index', read: { it[0] })
- closureColumn(header: 'Key', read: { it[1] })
- closureColumn(header: 'Value', read: { it[2] })
- }
- }
- }
- }
- scrollPane(name: ' Public Fields and Properties ') {
- fieldTable = table {
- def data = Inspector.sort(inspector.publicFields.toList())
- data.addAll(Inspector.sort(inspector.propertyInfo.toList()))
- tableModel(list: data) {
- closureColumn(header: 'Name', read: { it[MEMBER_NAME_IDX] })
- closureColumn(header: 'Value', read: { it[MEMBER_VALUE_IDX] })
- closureColumn(header: 'Type', read: { it[MEMBER_TYPE_IDX] })
- closureColumn(header: 'Origin', read: { it[MEMBER_ORIGIN_IDX] })
- closureColumn(header: 'Modifier', read: { it[MEMBER_MODIFIER_IDX] })
- closureColumn(header: 'Declarer', read: { it[MEMBER_DECLARER_IDX] })
- }
- }
- }
- scrollPane(name: ' (Meta) Methods ') {
- methodTable = table {
- def data = Inspector.sort(inspector.methods.toList())
- data.addAll(Inspector.sort(inspector.metaMethods.toList()))
-
- tableModel(list: data) {
- closureColumn(header: 'Name', read: { it[MEMBER_NAME_IDX] })
- closureColumn(header: 'Params', read: { it[MEMBER_PARAMS_IDX] })
- closureColumn(header: 'Type', read: { it[MEMBER_TYPE_IDX] })
- closureColumn(header: 'Origin', read: { it[MEMBER_ORIGIN_IDX] })
- closureColumn(header: 'Modifier', read: { it[MEMBER_MODIFIER_IDX] })
- closureColumn(header: 'Declarer', read: { it[MEMBER_DECLARER_IDX] })
- closureColumn(header: 'Exceptions', read: { it[MEMBER_EXCEPTIONS_IDX] })
- }
- }
- }
- }
- }
- }
-
- // Add a bit of formatting
- addSorter(itemTable)
- addSorter(mapTable)
- addSorter(fieldTable)
- addSorter(methodTable)
-
- frame.toFront()
- }
-
- void addSorter(table) {
- if (table != null) {
- def sorter = new TableSorter(table.model)
- table.model = sorter
- sorter.addMouseListenerToHeaderInTable(table)
- }
- }
-
- void showAbout(EventObject evt) {
- def pane = swing.optionPane()
- // work around GROOVY-1048
- def version = GroovySystem.version
- pane.setMessage('An interactive GUI to explore object capabilities.\nVersion ' + version)
- def dialog = pane.createDialog(frame, 'About Groovy Object Browser')
- dialog.show()
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ScriptToTreeNodeAdapter.groovy b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ScriptToTreeNodeAdapter.groovy
deleted file mode 100644
index 7290d98..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/ScriptToTreeNodeAdapter.groovy
+++ /dev/null
@@ -1,823 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.inspect.swingui
-
-import groovy.text.GStringTemplateEngine
-import groovy.text.Template
-import groovy.transform.CompileStatic
-import groovy.transform.PackageScope
-import org.apache.groovy.io.StringBuilderWriter
-import org.codehaus.groovy.GroovyBugError
-import org.codehaus.groovy.ast.AnnotationNode
-import org.codehaus.groovy.ast.ClassHelper
-import org.codehaus.groovy.ast.ClassNode
-import org.codehaus.groovy.ast.CodeVisitorSupport
-import org.codehaus.groovy.ast.ConstructorNode
-import org.codehaus.groovy.ast.DynamicVariable
-import org.codehaus.groovy.ast.FieldNode
-import org.codehaus.groovy.ast.InnerClassNode
-import org.codehaus.groovy.ast.MethodNode
-import org.codehaus.groovy.ast.ModuleNode
-import org.codehaus.groovy.ast.Parameter
-import org.codehaus.groovy.ast.PropertyNode
-import org.codehaus.groovy.ast.expr.ArgumentListExpression
-import org.codehaus.groovy.ast.expr.ArrayExpression
-import org.codehaus.groovy.ast.expr.AttributeExpression
-import org.codehaus.groovy.ast.expr.BinaryExpression
-import org.codehaus.groovy.ast.expr.BitwiseNegationExpression
-import org.codehaus.groovy.ast.expr.BooleanExpression
-import org.codehaus.groovy.ast.expr.CastExpression
-import org.codehaus.groovy.ast.expr.ClassExpression
-import org.codehaus.groovy.ast.expr.ClosureExpression
-import org.codehaus.groovy.ast.expr.ClosureListExpression
-import org.codehaus.groovy.ast.expr.ConstantExpression
-import org.codehaus.groovy.ast.expr.ConstructorCallExpression
-import org.codehaus.groovy.ast.expr.DeclarationExpression
-import org.codehaus.groovy.ast.expr.ElvisOperatorExpression
-import org.codehaus.groovy.ast.expr.Expression
-import org.codehaus.groovy.ast.expr.FieldExpression
-import org.codehaus.groovy.ast.expr.GStringExpression
-import org.codehaus.groovy.ast.expr.LambdaExpression
-import org.codehaus.groovy.ast.expr.ListExpression
-import org.codehaus.groovy.ast.expr.MapEntryExpression
-import org.codehaus.groovy.ast.expr.MapExpression
-import org.codehaus.groovy.ast.expr.MethodCallExpression
-import org.codehaus.groovy.ast.expr.MethodPointerExpression
-import org.codehaus.groovy.ast.expr.MethodReferenceExpression
-import org.codehaus.groovy.ast.expr.NamedArgumentListExpression
-import org.codehaus.groovy.ast.expr.NotExpression
-import org.codehaus.groovy.ast.expr.PostfixExpression
-import org.codehaus.groovy.ast.expr.PrefixExpression
-import org.codehaus.groovy.ast.expr.PropertyExpression
-import org.codehaus.groovy.ast.expr.RangeExpression
-import org.codehaus.groovy.ast.expr.SpreadExpression
-import org.codehaus.groovy.ast.expr.SpreadMapExpression
-import org.codehaus.groovy.ast.expr.StaticMethodCallExpression
-import org.codehaus.groovy.ast.expr.TernaryExpression
-import org.codehaus.groovy.ast.expr.TupleExpression
-import org.codehaus.groovy.ast.expr.UnaryMinusExpression
-import org.codehaus.groovy.ast.expr.UnaryPlusExpression
-import org.codehaus.groovy.ast.expr.VariableExpression
-import org.codehaus.groovy.ast.stmt.AssertStatement
-import org.codehaus.groovy.ast.stmt.BlockStatement
-import org.codehaus.groovy.ast.stmt.BreakStatement
-import org.codehaus.groovy.ast.stmt.CaseStatement
-import org.codehaus.groovy.ast.stmt.CatchStatement
-import org.codehaus.groovy.ast.stmt.ContinueStatement
-import org.codehaus.groovy.ast.stmt.DoWhileStatement
-import org.codehaus.groovy.ast.stmt.EmptyStatement
-import org.codehaus.groovy.ast.stmt.ExpressionStatement
-import org.codehaus.groovy.ast.stmt.ForStatement
-import org.codehaus.groovy.ast.stmt.IfStatement
-import org.codehaus.groovy.ast.stmt.ReturnStatement
-import org.codehaus.groovy.ast.stmt.Statement
-import org.codehaus.groovy.ast.stmt.SwitchStatement
-import org.codehaus.groovy.ast.stmt.SynchronizedStatement
-import org.codehaus.groovy.ast.stmt.ThrowStatement
-import org.codehaus.groovy.ast.stmt.TryCatchStatement
-import org.codehaus.groovy.ast.stmt.WhileStatement
-import org.codehaus.groovy.classgen.BytecodeExpression
-import org.codehaus.groovy.classgen.GeneratorContext
-import org.codehaus.groovy.classgen.asm.BytecodeHelper
-import org.codehaus.groovy.control.CompilationFailedException
-import org.codehaus.groovy.control.CompilationUnit
-import org.codehaus.groovy.control.CompilationUnit.PrimaryClassNodeOperation
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.SourceUnit
-
-import java.util.concurrent.atomic.AtomicBoolean
-
-/**
- * This class controls the conversion from a Groovy script as a String into
- * a tree representation of the AST of that script. The script itself
- * will be a tree node, and each class in the script will be a tree node. The
- * conversion creates tree nodes for any concrete class found within an AST
- * visitor. So, if a tree node should be shown once for each ASTNode and the parent
- * types will not appear as nodes. Custom subclasses of expression types will
- * not appear in the tree.
- *
- * The String label of a tree node is defined by classname in AstBrowserProperties.properties.
- */
-@Deprecated
-class ScriptToTreeNodeAdapter {
-
- static Properties classNameToStringForm
- boolean showScriptFreeForm, showScriptClass, showClosureClasses
- final GroovyClassLoader classLoader
- final AstBrowserNodeMaker nodeMaker
- private final CompilerConfiguration config
-
- static {
- try {
- URL url = ClassLoader.getSystemResource('groovy/inspect/swingui/AstBrowserProperties.groovy')
- if (!url) {
- url = ScriptToTreeNodeAdapter.class.classLoader.getResource('groovy/inspect/swingui/AstBrowserProperties.groovy')
- }
-
- def config = new ConfigSlurper().parse(url)
- classNameToStringForm = config.toProperties()
-
- String home = System.getProperty('user.home')
- if (home) {
- File userFile = new File(home + File.separator + '.groovy/AstBrowserProperties.groovy')
- if (userFile.exists()) {
- def customConfig = new ConfigSlurper().parse(userFile.toURL())
- // layer custom string forms onto defaults with putAll, do not replace them
- classNameToStringForm.putAll(customConfig.toProperties())
- }
- }
- } catch(ex) {
- // on restricted environments like, such calls may fail, but that should not prevent the class
- // from being loaded. Tree nodes can still get rendered with their simple names.
- classNameToStringForm = new Properties()
- }
- }
-
- ScriptToTreeNodeAdapter(classLoader, showScriptFreeForm, showScriptClass, showClosureClasses, nodeMaker, config = null) {
- this.classLoader = classLoader ?: new GroovyClassLoader(getClass().classLoader)
- this.showScriptFreeForm = showScriptFreeForm
- this.showScriptClass = showScriptClass
- this.showClosureClasses = showClosureClasses
- this.nodeMaker = nodeMaker
- this.config = config
- }
-
- /**
- * Performs the conversion from script to TreeNode.
- *
- * @param script
- * a Groovy script in String form
- * @param compilePhase
- * the int based CompilePhase to compile it to.
- * @param indy
- * if {@code true} InvokeDynamic (Indy) bytecode is generated
- */
- def compile(String script, int compilePhase, boolean indy=false) {
- def scriptName = 'script' + System.currentTimeMillis() + '.groovy'
- GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptName, '/groovy/script')
- CompilerConfiguration cc = new CompilerConfiguration(config ?: CompilerConfiguration.DEFAULT)
- if (config) {
- cc.addCompilationCustomizers(*config.compilationCustomizers)
- }
- if (indy) {
- cc.optimizationOptions.put(CompilerConfiguration.INVOKEDYNAMIC, true)
- }
- CompilationUnit cu = new CompilationUnit(cc, codeSource.codeSource, classLoader)
- cu.setClassgenCallback(classLoader.createCollector(cu, null))
-
- TreeNodeBuildingNodeOperation operation = new TreeNodeBuildingNodeOperation(this, showScriptFreeForm, showScriptClass, showClosureClasses)
- cu.addPhaseOperation(operation, compilePhase)
- cu.addSource(codeSource.getName(), script)
- try {
- cu.compile(compilePhase)
- } catch (CompilationFailedException cfe) {
- operation.root.add(nodeMaker.makeNode('Unable to produce AST for this phase due to earlier compilation error:'))
- cfe.message.eachLine {
- operation.root.add(nodeMaker.makeNode(it))
- }
- operation.root.add(nodeMaker.makeNode('Fix the above error(s) and then press Refresh'))
- } catch (Throwable t) {
- operation.root.add(nodeMaker.makeNode('Unable to produce AST for this phase due to an error:'))
- operation.root.add(nodeMaker.makeNode(t))
- operation.root.add(nodeMaker.makeNode('Fix the above error(s) and then press Refresh'))
- }
- return operation.root
- }
-
- def make(node) {
- nodeMaker.makeNodeWithProperties(getStringForm(node), getPropertyTable(node))
- }
-
- def make(MethodNode node) {
- def table = getPropertyTable(node)
- extendMethodNodePropertyTable(table, node)
-
- nodeMaker.makeNodeWithProperties(getStringForm(node), table)
- }
-
- /**
- * Extends the method node property table by adding custom properties.
- */
- void extendMethodNodePropertyTable(List<List<String>> table, MethodNode node) {
- table << ['descriptor', BytecodeHelper.getMethodDescriptor(node), 'String']
- }
-
- /**
- * Creates the property table for the node so that the properties view can display nicely.
- */
- private List<List<String>> getPropertyTable(node) {
- node.metaClass.properties?.
- findAll { it.getter }?.
- collect {
- def name = it.name.toString()
- def value
- try {
- // multiple assignment statements cannot be cast to VariableExpression so
- // instead reference the value through the leftExpression property, which is the same
- if (node instanceof DeclarationExpression &&
- (name == 'variableExpression' || name == 'tupleExpression')) {
- value = toString(node.leftExpression)
- } else {
- value = toString(it.getProperty(node))
- }
- } catch (GroovyBugError reflectionArtefact) {
- // compiler throws error if it thinks a field is being accessed
- // before it is set under certain conditions. It wasn't designed
- // to be walked reflectively like this.
- value = null
- }
- def type = it.type.simpleName.toString()
- [name, value, type]
- }?.
- sort { it[0] }
- }
-
- // GROOVY-8339: to avoid illegal access to a non-visible implementation class - can be removed if a more general solution is found
- @CompileStatic
- String toString(Object o) {
- o.toString()
- }
-
- /**
- * Handles the property file templating for node types.
- */
- private String getStringForm(node) {
- String templateTextForNode = classNameToStringForm[node.class.name]
- if (templateTextForNode) {
- GStringTemplateEngine engine = new GStringTemplateEngine()
- Template template = engine.createTemplate(templateTextForNode)
- Writable writable = template.make([expression: node])
- Writer result = new StringBuilderWriter()
- writable.writeTo(result)
- result.toString()
- } else {
- node.class.simpleName
- }
- }
-}
-
-/**
- * This Node Operation builds up a root tree node for the viewer.
- */
-@Deprecated
-class TreeNodeBuildingNodeOperation extends PrimaryClassNodeOperation {
-
- final root
- final sourceCollected = new AtomicBoolean(false)
- final ScriptToTreeNodeAdapter adapter
-
- final showScriptFreeForm
- final showScriptClass
- final showClosureClasses
-
- final nodeMaker
-
- TreeNodeBuildingNodeOperation(ScriptToTreeNodeAdapter adapter, showScriptFreeForm, showScriptClass) {
- this(adapter, showScriptFreeForm, showScriptClass, false)
- }
-
- TreeNodeBuildingNodeOperation(ScriptToTreeNodeAdapter adapter, showScriptFreeForm, showScriptClass, showClosureClasses) {
- if (!adapter) throw new IllegalArgumentException('Null: adapter')
- this.adapter = adapter
- this.showScriptFreeForm = showScriptFreeForm
- this.showScriptClass = showScriptClass
- this.showClosureClasses = showClosureClasses
- nodeMaker = adapter.nodeMaker
- root = nodeMaker.makeNode('root')
- }
-
- @Override
- void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
- // module node
- if (!sourceCollected.getAndSet(true) && showScriptFreeForm) {
- // display the source unit AST
- ModuleNode ast = source.getAST()
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- ast.getStatementBlock().visit(visitor)
- if (visitor.currentNode) root.add(visitor.currentNode)
- collectModuleNodeMethodData('Methods', ast.getMethods())
- }
-
- if(classNode.isScript() && !showScriptClass) return
-
- def child = adapter.make(classNode)
- root.add(child)
-
- collectConstructorData(child, 'Constructors', classNode)
- collectObjectInitializers(child, 'Object Initializers', classNode)
- collectMethodData(child, 'Methods', classNode)
- collectFieldData(child, 'Fields', classNode)
- collectPropertyData(child, 'Properties', classNode)
- collectAnnotationData(child, 'Annotations', classNode)
-
- if (showClosureClasses) {
- makeClosureClassTreeNodes(classNode)
- }
- }
-
- protected void makeClosureClassTreeNodes(ClassNode classNode) {
- def compileUnit = classNode.compileUnit
- if (!compileUnit.generatedInnerClasses) return
-
- def innerClassNodes = compileUnit.generatedInnerClasses.values().sort { it.name }
- innerClassNodes.each { InnerClassNode innerClassNode ->
- if (!innerClassNode.implementsInterface(ClassHelper.GENERATED_CLOSURE_Type) && !innerClassNode.implementsInterface(ClassHelper.GENERATED_LAMBDA_TYPE)) return
- if (innerClassNode.outerMostClass != classNode) return
-
- def child = adapter.make(innerClassNode)
- root.add(child)
-
- collectConstructorData(child, 'Constructors', innerClassNode)
- collectObjectInitializers(child, 'Object Initializers', innerClassNode)
- collectMethodData(child, 'Methods', innerClassNode)
- collectFieldData(child, 'Fields', innerClassNode)
- collectPropertyData(child, 'Properties', innerClassNode)
- collectAnnotationData(child, 'Annotations', innerClassNode)
- }
- }
-
- private void collectAnnotationData(parent, String name, ClassNode classNode) {
- def allAnnotations = nodeMaker.makeNode(name)
- if (classNode.annotations) parent.add(allAnnotations)
- classNode.annotations?.each {AnnotationNode annotationNode ->
- def ggrandchild = adapter.make(annotationNode)
- allAnnotations.add(ggrandchild)
- }
- }
-
- private void collectPropertyData(parent, String name, ClassNode classNode) {
- def allProperties = nodeMaker.makeNode(name)
- if (classNode.properties) parent.add(allProperties)
- classNode.properties?.each {PropertyNode propertyNode ->
- def ggrandchild = adapter.make(propertyNode)
- allProperties.add(ggrandchild)
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- if (propertyNode.field?.initialValueExpression) {
- propertyNode.field.initialValueExpression.visit(visitor)
- ggrandchild.add(visitor.currentNode)
- }
- }
- }
-
- private void collectFieldData(parent, String name, ClassNode classNode) {
- def allFields = nodeMaker.makeNode(name)
- if (classNode.fields) parent.add(allFields)
- classNode.fields?.each {FieldNode fieldNode ->
- def ggrandchild = adapter.make(fieldNode)
- allFields.add(ggrandchild)
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- if (fieldNode.initialValueExpression) {
- fieldNode.initialValueExpression.visit(visitor)
- if (visitor.currentNode) ggrandchild.add(visitor.currentNode)
- }
- }
- }
-
- private void collectMethodData(parent, String name, ClassNode classNode) {
- def allMethods = nodeMaker.makeNode(name)
- if (classNode.methods) parent.add(allMethods)
-
- doCollectMethodData(allMethods, classNode.methods)
- }
-
- private void collectModuleNodeMethodData(String name, List methods) {
- if(!methods) return
- def allMethods = nodeMaker.makeNode(name)
- root.add(allMethods)
-
- doCollectMethodData(allMethods, methods)
- }
-
- private void doCollectMethodData(allMethods, List methods) {
- methods?.each {MethodNode methodNode ->
- def ggrandchild = adapter.make(methodNode)
- allMethods.add(ggrandchild)
-
- // print out parameters of method
- methodNode.parameters?.each {Parameter parameter ->
- def gggrandchild = adapter.make(parameter)
- ggrandchild.add(gggrandchild)
- if (parameter.initialExpression) {
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- parameter.initialExpression.visit(visitor)
- if (visitor.currentNode) gggrandchild.add(visitor.currentNode)
- }
- }
-
- // print out code of method
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- if (methodNode.code) {
- methodNode.code.visit(visitor)
- if (visitor.currentNode) ggrandchild.add(visitor.currentNode)
- }
- }
- }
-
- private void collectConstructorData(parent, String name, ClassNode classNode) {
- def allCtors = nodeMaker.makeNode(name)
- if (classNode.declaredConstructors) parent.add(allCtors)
- classNode.declaredConstructors?.each {ConstructorNode ctorNode ->
-
- def ggrandchild = adapter.make(ctorNode)
- allCtors.add(ggrandchild)
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- if (ctorNode.code) {
- ctorNode.code.visit(visitor)
- if (visitor.currentNode) ggrandchild.add(visitor.currentNode)
- }
- }
-
- }
-
- private void collectObjectInitializers(parent, String name, ClassNode node) {
- List<Statement> initStatements = node.getObjectInitializerStatements()
- if (!initStatements) {
- return
- }
- def allInitializers = nodeMaker.makeNode(name)
- parent.add(allInitializers)
- for (Statement stmt : initStatements) {
- TreeNodeBuildingVisitor visitor = new TreeNodeBuildingVisitor(adapter)
- stmt.visit(visitor)
- if (visitor.currentNode) {
- allInitializers.add(visitor.currentNode)
- }
- }
- }
-
-}
-
-/**
-* This AST visitor builds up a TreeNode.
-*/
-@PackageScope
-@Deprecated
-class TreeNodeBuildingVisitor extends CodeVisitorSupport {
-
- def currentNode
- private final adapter
-
- /**
- * Creates the visitor. A file named AstBrowserProperties.groovy is located which is
- * a property files the describes how to represent ASTNode types as Strings.
- */
- TreeNodeBuildingVisitor(adapter) {
- if (!adapter) throw new IllegalArgumentException('Null: adapter')
- this.adapter = adapter
- }
-
- /**
- * This method looks at the AST node and decides how to represent it in a TreeNode, then it
- * continues walking the tree. If the node and the expectedSubclass are not exactly the same
- * Class object then the node is not added to the tree. This is to eliminate seeing duplicate
- * nodes, for instance seeing an ArgumentListExpression and a TupleExpression in the tree, when
- * an ArgumentList is-a Tuple.
- */
- private void addNode(node, Class expectedSubclass, Closure superMethod) {
-
- if (expectedSubclass.getName() == node.getClass().getName()) {
- if (currentNode == null) {
- currentNode = adapter.make(node)
- superMethod.call(node)
- } else {
- // visitor works off void methods... so we have to
- // perform a swap to get accumulation like behavior.
- def temp = currentNode
- currentNode = adapter.make(node)
-
- temp.add(currentNode)
- currentNode.parent = temp
- superMethod.call(node)
- currentNode = temp
- }
- } else {
- superMethod.call(node)
- }
- }
-
- @Override
- void visitBlockStatement(BlockStatement node) {
- addNode(node, BlockStatement, { super.visitBlockStatement(it) })
- }
-
- @Override
- void visitForLoop(ForStatement node) {
- addNode(node, ForStatement, { super.visitForLoop(it) })
- }
-
- @Override
- void visitWhileLoop(WhileStatement node) {
- addNode(node, WhileStatement, { super.visitWhileLoop(it) })
- }
-
- @Override
- void visitDoWhileLoop(DoWhileStatement node) {
- addNode(node, DoWhileStatement, { super.visitDoWhileLoop(it) })
- }
-
- @Override
- void visitIfElse(IfStatement node) {
- addNode(node, IfStatement, { super.visitIfElse(it) })
- }
-
- @Override
- void visitExpressionStatement(ExpressionStatement node) {
- addNode(node, ExpressionStatement, { super.visitExpressionStatement(it) })
- }
-
- @Override
- void visitReturnStatement(ReturnStatement node) {
- addNode(node, ReturnStatement, { super.visitReturnStatement(it) })
- }
-
- @Override
- void visitAssertStatement(AssertStatement node) {
- addNode(node, AssertStatement, { super.visitAssertStatement(it) })
- }
-
- @Override
- void visitTryCatchFinally(TryCatchStatement node) {
- addNode(node, TryCatchStatement, { super.visitTryCatchFinally(it) })
- }
-
- @Override
- protected void visitEmptyStatement(EmptyStatement node) {
- addNode(node, EmptyStatement, { super.visitEmptyStatement(it) })
- }
-
- @Override
- void visitSwitch(SwitchStatement node) {
- addNode(node, SwitchStatement, { super.visitSwitch(it) })
- }
-
- @Override
- void visitCaseStatement(CaseStatement node) {
- addNode(node, CaseStatement, { super.visitCaseStatement(it) })
- }
-
- @Override
- void visitBreakStatement(BreakStatement node) {
- addNode(node, BreakStatement, { super.visitBreakStatement(it) })
- }
-
- @Override
- void visitContinueStatement(ContinueStatement node) {
- addNode(node, ContinueStatement, { super.visitContinueStatement(it) })
- }
-
- @Override
- void visitSynchronizedStatement(SynchronizedStatement node) {
- addNode(node, SynchronizedStatement, { super.visitSynchronizedStatement(it) })
- }
-
- @Override
- void visitThrowStatement(ThrowStatement node) {
- addNode(node, ThrowStatement, { super.visitThrowStatement(it) })
- }
-
- @Override
- void visitMethodCallExpression(MethodCallExpression node) {
- addNode(node, MethodCallExpression, { super.visitMethodCallExpression(it) })
- }
-
- @Override
- void visitStaticMethodCallExpression(StaticMethodCallExpression node) {
- addNode(node, StaticMethodCallExpression, { super.visitStaticMethodCallExpression(it) })
- }
-
- @Override
- void visitConstructorCallExpression(ConstructorCallExpression node) {
- addNode(node, ConstructorCallExpression, { super.visitConstructorCallExpression(it) })
- }
-
- @Override
- void visitBinaryExpression(BinaryExpression node) {
- addNode(node, BinaryExpression, { super.visitBinaryExpression(it) })
- }
-
- @Override
- void visitTernaryExpression(TernaryExpression node) {
- addNode(node, TernaryExpression, { super.visitTernaryExpression(it) })
- }
-
- @Override
- void visitShortTernaryExpression(ElvisOperatorExpression node) {
- addNode(node, ElvisOperatorExpression, { super.visitShortTernaryExpression(it) })
- }
-
- @Override
- void visitPostfixExpression(PostfixExpression node) {
- addNode(node, PostfixExpression, { super.visitPostfixExpression(it) })
- }
-
- @Override
- void visitPrefixExpression(PrefixExpression node) {
- addNode(node, PrefixExpression, { super.visitPrefixExpression(it) })
- }
-
- @Override
- void visitBooleanExpression(BooleanExpression node) {
- addNode(node, BooleanExpression, { super.visitBooleanExpression(it) })
- }
-
- @Override
- void visitNotExpression(NotExpression node) {
- addNode(node, NotExpression, { super.visitNotExpression(it) })
- }
-
- @Override
- void visitClosureExpression(ClosureExpression node) {
- addNode(node, ClosureExpression, {
- it.parameters?.each { parameter -> visitParameter(parameter) }
- super.visitClosureExpression(it)
- })
- }
-
- @Override
- void visitLambdaExpression(LambdaExpression node) {
- addNode(node, LambdaExpression, {
- // params will be catered for by super call
- //it.parameters?.each { parameter -> visitParameter(parameter) }
- super.visitLambdaExpression(it)
- })
- }
-
- /**
- * Makes walking parameters look like others in the visitor.
- */
- void visitParameter(Parameter node) {
- addNode(node, Parameter, {
- if (node.initialExpression) {
- node.initialExpression?.visit(this)
- }
- })
- }
-
- @Override
- void visitTupleExpression(TupleExpression node) {
- addNode(node, TupleExpression, { super.visitTupleExpression(it) })
- }
-
- @Override
- void visitListExpression(ListExpression node) {
- addNode(node, ListExpression, { super.visitListExpression(it) })
- }
-
- @Override
- void visitArrayExpression(ArrayExpression node) {
- addNode(node, ArrayExpression, { super.visitArrayExpression(it) })
- }
-
- @Override
- void visitMapExpression(MapExpression node) {
- addNode(node, MapExpression, { super.visitMapExpression(it) })
- }
-
- @Override
- void visitMapEntryExpression(MapEntryExpression node) {
- addNode(node, MapEntryExpression, { super.visitMapEntryExpression(it) })
- }
-
- @Override
- void visitRangeExpression(RangeExpression node) {
- addNode(node, RangeExpression, { super.visitRangeExpression(it) })
- }
-
- @Override
- void visitSpreadExpression(SpreadExpression node) {
- addNode(node, SpreadExpression, { super.visitSpreadExpression(it) })
- }
-
- @Override
- void visitSpreadMapExpression(SpreadMapExpression node) {
- addNode(node, SpreadMapExpression, { super.visitSpreadMapExpression(it) })
- }
-
- @Override
- void visitMethodPointerExpression(MethodPointerExpression node) {
- addNode(node, MethodPointerExpression, { super.visitMethodPointerExpression(it) })
- }
-
- @Override
- void visitMethodReferenceExpression(MethodReferenceExpression node) {
- addNode(node, MethodReferenceExpression, { super.visitMethodReferenceExpression(it) })
- }
-
- @Override
- void visitUnaryMinusExpression(UnaryMinusExpression node) {
- addNode(node, UnaryMinusExpression, { super.visitUnaryMinusExpression(it) })
- }
-
- @Override
- void visitUnaryPlusExpression(UnaryPlusExpression node) {
- addNode(node, UnaryPlusExpression, { super.visitUnaryPlusExpression(it) })
- }
-
- @Override
- void visitBitwiseNegationExpression(BitwiseNegationExpression node) {
- addNode(node, BitwiseNegationExpression, { super.visitBitwiseNegationExpression(it) })
- }
-
- @Override
- void visitCastExpression(CastExpression node) {
- addNode(node, CastExpression, { super.visitCastExpression(it) })
- }
-
- @Override
- void visitConstantExpression(ConstantExpression node) {
- addNode(node, ConstantExpression, { super.visitConstantExpression(it) })
- }
-
- @Override
- void visitClassExpression(ClassExpression node) {
- addNode(node, ClassExpression, { super.visitClassExpression(it) })
- }
-
- @Override
- void visitVariableExpression(VariableExpression node) {
- addNode(node, VariableExpression, { VariableExpression it ->
- if (it.accessedVariable) {
- if (it.accessedVariable instanceof Parameter) {
- visitParameter((Parameter)it.accessedVariable)
- } else if (it.accessedVariable instanceof DynamicVariable) {
- addNode(it.accessedVariable, DynamicVariable,{ it.initialExpression?.visit(this)})
- }
- }
- })
- }
-
- @Override
- void visitDeclarationExpression(DeclarationExpression node) {
- addNode(node, DeclarationExpression, { super.visitDeclarationExpression(it) })
- }
-
- @Override
- void visitPropertyExpression(PropertyExpression node) {
- addNode(node, PropertyExpression, { super.visitPropertyExpression(it) })
- }
-
- @Override
- void visitAttributeExpression(AttributeExpression node) {
- addNode(node, AttributeExpression, { super.visitAttributeExpression(it) })
- }
-
- @Override
- void visitFieldExpression(FieldExpression node) {
- addNode(node, FieldExpression, { super.visitFieldExpression(it) })
- }
-
- @Override
- void visitGStringExpression(GStringExpression node) {
- addNode(node, GStringExpression, { super.visitGStringExpression(it) })
- }
-
- @Override
- void visitCatchStatement(CatchStatement node) {
- addNode(node, CatchStatement, {
- if (it.variable) visitParameter(it.variable)
- super.visitCatchStatement(it)
- })
- }
-
- @Override
- void visitArgumentlistExpression(ArgumentListExpression node) {
- addNode(node, ArgumentListExpression, { super.visitArgumentlistExpression(it) })
- }
-
- @Override
- void visitClosureListExpression(ClosureListExpression node) {
- addNode(node, ClosureListExpression, { super.visitClosureListExpression(it) })
- }
-
- @Override
- void visitBytecodeExpression(BytecodeExpression node) {
- addNode(node, BytecodeExpression, { super.visitBytecodeExpression(it) })
- }
-
- @Override
- void visitListOfExpressions(List<? extends Expression> list) {
- list.each { Expression node ->
- if (node instanceof NamedArgumentListExpression ) {
- addNode(node, NamedArgumentListExpression, { it.visit(this) })
- } else {
- node.visit(this)
- }
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/package.html b/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/package.html
deleted file mode 100644
index 7b601f9..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/inspect/swingui/package.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<html>
- <head>
- <title>package groovy.inspect.swingui.*</title>
- </head>
- <body>
- <p>Classes associated with the Swing GUI for inspecting objects.</p>
- </body>
-</html>
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/Console.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/Console.groovy
deleted file mode 100644
index e7db397..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/Console.groovy
+++ /dev/null
@@ -1,1718 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.cli.internal.CliBuilderInternal
-import groovy.cli.internal.OptionAccessor
-import groovy.inspect.swingui.AstBrowser
-import groovy.inspect.swingui.ObjectBrowser
-import groovy.swing.SwingBuilder
-import groovy.transform.CompileStatic
-import groovy.transform.ThreadInterrupt
-import groovy.ui.text.FindReplaceUtility
-import groovy.ui.text.GroovyFilter
-import groovy.ui.text.SmartDocumentFilter
-import org.apache.groovy.io.StringBuilderWriter
-import org.apache.groovy.parser.antlr4.GroovyLangLexer
-import org.apache.groovy.util.SystemUtil
-import org.codehaus.groovy.antlr.LexerFrame
-import org.codehaus.groovy.control.CompilerConfiguration
-import org.codehaus.groovy.control.ErrorCollector
-import org.codehaus.groovy.control.MultipleCompilationErrorsException
-import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
-import org.codehaus.groovy.control.messages.ExceptionMessage
-import org.codehaus.groovy.control.messages.SimpleMessage
-import org.codehaus.groovy.control.messages.SyntaxErrorMessage
-import org.codehaus.groovy.runtime.StackTraceUtils
-import org.codehaus.groovy.runtime.StringGroovyMethods
-import org.codehaus.groovy.syntax.SyntaxException
-import org.codehaus.groovy.tools.shell.util.MessageSource
-import org.codehaus.groovy.transform.ThreadInterruptibleASTTransformation
-
-import javax.swing.Action
-import javax.swing.Icon
-import javax.swing.JApplet
-import javax.swing.JFileChooser
-import javax.swing.JFrame
-import javax.swing.JLabel
-import javax.swing.JOptionPane
-import javax.swing.JScrollPane
-import javax.swing.JSplitPane
-import javax.swing.JTextPane
-import javax.swing.RootPaneContainer
-import javax.swing.SwingUtilities
-import javax.swing.UIManager
-import javax.swing.event.CaretEvent
-import javax.swing.event.CaretListener
-import javax.swing.event.DocumentListener
-import javax.swing.event.HyperlinkEvent
-import javax.swing.event.HyperlinkListener
-import javax.swing.filechooser.FileFilter
-import javax.swing.text.AttributeSet
-import javax.swing.text.Document
-import javax.swing.text.Element
-import javax.swing.text.SimpleAttributeSet
-import javax.swing.text.Style
-import javax.swing.text.StyleConstants
-import javax.swing.text.html.HTML
-
-import java.awt.BorderLayout
-import java.awt.Component
-import java.awt.Dimension
-import java.awt.EventQueue
-import java.awt.Font
-import java.awt.Toolkit
-import java.awt.Window
-import java.awt.event.ActionEvent
-import java.awt.event.ComponentEvent
-import java.awt.event.ComponentListener
-import java.awt.event.FocusEvent
-import java.awt.event.FocusListener
-import java.util.prefs.Preferences
-
-/**
- * Groovy Swing console.
- *
- * Allows user to interactively enter and execute Groovy.
- */
-@Deprecated
-class Console implements CaretListener, HyperlinkListener, ComponentListener, FocusListener {
-
- static final String DEFAULT_SCRIPT_NAME_START = 'ConsoleScript'
-
- static private prefs = Preferences.userNodeForPackage(Console)
-
- // Whether or not std output should be captured to the console
- static boolean captureStdOut = prefs.getBoolean('captureStdOut', true)
- static boolean captureStdErr = prefs.getBoolean('captureStdErr', true)
- static consoleControllers = []
-
- static boolean smartHighlighter = prefs.getBoolean('smartHighlighter',
- Boolean.valueOf(SystemUtil.getSystemPropertySafe('groovy.console.enable.smart.highlighter', 'true')))
-
- boolean fullStackTraces = prefs.getBoolean('fullStackTraces',
- Boolean.valueOf(System.getProperty('groovy.full.stacktrace', 'false')))
- Action fullStackTracesAction
-
- boolean showScriptInOutput = prefs.getBoolean('showScriptInOutput', true)
- Action showScriptInOutputAction
-
- boolean visualizeScriptResults = prefs.getBoolean('visualizeScriptResults', false)
- Action visualizeScriptResultsAction
-
- boolean showToolbar = prefs.getBoolean('showToolbar', true)
- Component toolbar
- Action showToolbarAction
-
- boolean detachedOutput = prefs.getBoolean('detachedOutput', false)
- Action detachedOutputAction
-
- boolean orientationVertical = prefs.getBoolean('orientationVertical', true)
- Action orientationVerticalAction
- Action showOutputWindowAction
- Action hideOutputWindowAction1
- Action hideOutputWindowAction2
- Action hideOutputWindowAction3
- Action hideOutputWindowAction4
- int origDividerSize
- Component outputWindow
- Component copyFromComponent
- Component blank
- Component scrollArea
-
- boolean autoClearOutput = prefs.getBoolean('autoClearOutput', false)
- Action autoClearOutputAction
-
- // Safer thread interruption
- boolean threadInterrupt = prefs.getBoolean('threadInterrupt', false)
- Action threadInterruptAction
-
- boolean saveOnRun = prefs.getBoolean('saveOnRun', false)
- Action saveOnRunAction
-
- boolean indy = prefs.getBoolean('indy', false)
- Action indyAction
-
- //to allow loading classes dynamically when using @Grab (GROOVY-4877, GROOVY-5871)
- boolean useScriptClassLoaderForScriptExecution = false
-
- // Maximum size of history
- int maxHistory = 10
-
- // Maximum number of characters to show on console at any time
- int maxOutputChars = System.getProperty('groovy.console.output.limit','20000') as int
-
- // File to output stdout & stderr, in addition to console
- PrintWriter outputPrintWriter = null
-
- // UI
- SwingBuilder swing
- RootPaneContainer frame
- ConsoleTextEditor inputEditor
- JSplitPane splitPane
- JTextPane inputArea
- JTextPane outputArea
- JLabel statusLabel
- JLabel rowNumAndColNum
-
- // row info
- Element rootElement
- int cursorPos
- int rowNum
- int colNum
-
- // Styles for output area
- Style promptStyle
- Style commandStyle
- Style outputStyle
- Style stacktraceStyle
- Style hyperlinkStyle
- Style resultStyle
-
- // Internal history
- List history = []
- int historyIndex = 1 // valid values are 0..history.length()
- HistoryRecord pendingRecord = new HistoryRecord( allText: '', selectionStart: 0, selectionEnd: 0)
- Action prevHistoryAction
- Action nextHistoryAction
-
- // Current editor state
- boolean dirty
- Action saveAction
- int textSelectionStart // keep track of selections in inputArea
- int textSelectionEnd
- def scriptFile
- File currentFileChooserDir = new File(Preferences.userNodeForPackage(Console).get('currentFileChooserDir', '.'))
- File currentClasspathJarDir = new File(Preferences.userNodeForPackage(Console).get('currentClasspathJarDir', '.'))
- File currentClasspathDir = new File(Preferences.userNodeForPackage(Console).get('currentClasspathDir', '.'))
-
- // Running scripts
- CompilerConfiguration baseConfig
- CompilerConfiguration config
- GroovyShell shell
- int scriptNameCounter = 0
- SystemOutputInterceptor systemOutInterceptor
- SystemOutputInterceptor systemErrorInterceptor
- Thread runThread = null
- Closure beforeExecution
- Closure afterExecution
-
- public static URL ICON_PATH = Console.class.classLoader.getResource('groovy/ui/ConsoleIcon.png') // used by ObjectBrowser and AST Viewer
- public static URL NODE_ICON_PATH = Console.class.classLoader.getResource('groovy/ui/icons/bullet_green.png') // used by AST Viewer
-
- static groovyFileFilter = new GroovyFileFilter()
- boolean scriptRunning = false
- boolean stackOverFlowError = false
- Action interruptAction
-
- Action selectWordAction
- Action selectPreviousWordAction
-
- ConsolePreferences consolePreferences
-
- static void main(args) {
- MessageSource messages = new MessageSource(Console)
- def cli = new CliBuilderInternal(usage: 'groovyConsole [options] [filename]', stopAtNonOption: false,
- header: messages['cli.option.header'])
- cli.with {
- _(names: ['-cp', '-classpath', '--classpath'], messages['cli.option.classpath.description'])
- h(longOpt: 'help', messages['cli.option.help.description'])
- V(longOpt: 'version', messages['cli.option.version.description'])
- pa(longOpt: 'parameters', messages['cli.option.parameters.description'])
- i(longOpt: 'indy', messages['cli.option.indy.description'])
- D(longOpt: 'define', type: Map, argName: 'name=value', messages['cli.option.define.description'])
- _(longOpt: 'configscript', args: 1, messages['cli.option.configscript.description'])
- }
- OptionAccessor options = cli.parse(args)
-
- if (options == null) {
- // CliBuilder prints error, but does not exit
- System.exit(22) // Invalid Args
- }
-
- if (options.h) {
- cli.usage()
- System.exit(0)
- }
-
- if (options.V) {
- System.out.println(messages.format('cli.info.version', GroovySystem.version))
- System.exit(0)
- }
-
- if (options.hasOption('D')) {
- options.Ds.each { k, v -> System.setProperty(k, v) }
- }
-
- // full stack trace should not be logged to the output window - GROOVY-4663
- java.util.logging.Logger.getLogger(StackTraceUtils.STACK_LOG_NAME).useParentHandlers = false
-
- //when starting via main set the look and feel to system
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
-
- def baseConfig = new CompilerConfiguration(System.getProperties())
- String starterConfigScripts = System.getProperty("groovy.starter.configscripts", null)
- if (options.configscript || (starterConfigScripts != null && !starterConfigScripts.isEmpty())) {
- List<String> configScripts = new ArrayList<String>()
- if (options.configscript) {
- configScripts.add(options.configscript)
- }
- if (starterConfigScripts != null) {
- configScripts.addAll(StringGroovyMethods.tokenize((CharSequence) starterConfigScripts, ','))
- }
- GroovyMain.processConfigScripts(configScripts, baseConfig)
- }
-
- baseConfig.setParameters(options.hasOption("pa"))
-
- if (options.i) {
- enableIndy(baseConfig)
- }
-
- def console = new Console(Thread.currentThread().contextClassLoader, new Binding(), baseConfig)
- console.useScriptClassLoaderForScriptExecution = true
- console.run()
- def remaining = options.arguments()
- if (remaining && !remaining[-1].startsWith("-")) {
- console.loadScriptFile(remaining[-1] as File)
- }
- }
-
- int loadMaxOutputChars() {
- // For backwards compatibility 'maxOutputChars' remains defined in the Console class
- // and the System Property takes precedence as the default value.
- int max = prefs.getInt('maxOutputChars', ConsolePreferences.DEFAULT_MAX_OUTPUT_CHARS)
- return System.getProperty('groovy.console.output.limit', "${max}") as int
- }
-
- void preferences(EventObject evt = null) {
- if (!consolePreferences) {
- consolePreferences = new ConsolePreferences(this)
- }
- consolePreferences.show()
- }
-
- void setOutputPreferences(boolean useOutputFile, File outputFile) {
- prefs.remove('outputLogFileName')
- if (!useOutputFile) {
- closeOutputPrintWriter(outputFile)
- } else {
- if (outputFile != null) {
- closeOutputPrintWriter()
- createOutputPrintWriter(outputFile)
- prefs.put('outputLogFileName', outputFile.getAbsolutePath())
- }
- }
- }
-
- void createOutputPrintWriter(File outputFile) {
- outputPrintWriter = new PrintWriter(new FileOutputStream(
- outputFile,
- true))
- }
-
- void closeOutputPrintWriter() {
- if (outputPrintWriter != null) {
- outputPrintWriter.close()
- outputPrintWriter = null
- }
- }
-
- Console(Binding binding = new Binding()) {
- this(null, binding)
- }
-
- Console(ClassLoader parent, Binding binding = new Binding(), CompilerConfiguration baseConfig = new CompilerConfiguration(System.getProperties())) {
- this.baseConfig = baseConfig
- this.maxOutputChars = loadMaxOutputChars()
- indy = indy || isIndyEnabled(baseConfig)
- if (indy) {
- enableIndy(baseConfig)
- }
-
- // Set up output file for stdout/stderr, if any
- def outputLogFileName = prefs.get('outputLogFileName', null)
- if (outputLogFileName) {
- createOutputPrintWriter(new File(outputLogFileName))
- }
-
- newScript(parent, binding)
- try {
- System.setProperty('groovy.full.stacktrace', System.getProperty('groovy.full.stacktrace',
- Boolean.toString(prefs.getBoolean('fullStackTraces', false))))
-
- } catch (SecurityException se) {
- fullStackTracesAction.enabled = false
- }
- consoleControllers += this
-
- // listen for Ivy events if Ivy is on the Classpath
- try {
- if (Class.forName('org.apache.ivy.core.event.IvyListener')) {
- def ivyPluginClass = Class.forName('groovy.ui.ConsoleIvyPlugin')
- ivyPluginClass.newInstance().addListener(this)
- }
- } catch(ClassNotFoundException ignore) { }
-
- binding.variables._outputTransforms = OutputTransforms.loadOutputTransforms()
- }
-
- void newScript(ClassLoader parent, Binding binding) {
- config = new CompilerConfiguration(baseConfig)
- config.addCompilationCustomizers(*baseConfig.compilationCustomizers)
- if (threadInterrupt) {
- config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt))
- }
- shell = new GroovyShell(parent, binding, config)
- }
-
- static frameConsoleDelegates = [
- rootContainerDelegate:{
- frame(
- title: 'GroovyConsole',
- //location: [100,100], // in groovy 2.0 use platform default location
- iconImage: imageIcon('/groovy/ui/ConsoleIcon.png').image,
- defaultCloseOperation: JFrame.DO_NOTHING_ON_CLOSE,
- ) {
- try {
- current.locationByPlatform = true
- } catch (Exception e) {
- current.location = [100, 100] // for 1.4 compatibility
- }
- containingWindows += current
- }
- },
- menuBarDelegate: {arg->
- current.JMenuBar = build(arg)}
- ]
-
- void run() {
- run(frameConsoleDelegates)
- }
-
- void run(JApplet applet) {
- run([
- rootContainerDelegate:{
- containingWindows += SwingUtilities.getRoot(applet.getParent())
- applet
- },
- menuBarDelegate: {arg->
- current.JMenuBar = build(arg)}
- ])
- }
-
- void run(Map defaults) {
-
- swing = new SwingBuilder()
- defaults.each{k, v -> swing[k] = v}
-
- // tweak what the stack traces filter out to be fairly broad
- System.setProperty('groovy.sanitized.stacktraces', '''org.codehaus.groovy.runtime.
- org.codehaus.groovy.
- groovy.lang.
- gjdk.groovy.lang.
- sun.
- java.lang.reflect.
- java.lang.Thread
- groovy.ui.Console''')
-
-
- // add controller to the swingBuilder bindings
- swing.controller = this
-
- // create the actions
- swing.build(ConsoleActions)
-
- // create the view
- swing.build(ConsoleView)
-
- bindResults()
-
- // stitch some actions together
- swing.bind(source:swing.inputEditor.undoAction, sourceProperty:'enabled', target:swing.undoAction, targetProperty:'enabled')
- swing.bind(source:swing.inputEditor.redoAction, sourceProperty:'enabled', target:swing.redoAction, targetProperty:'enabled')
-
- if (swing.consoleFrame instanceof Window) {
- nativeFullScreenForMac(swing.consoleFrame)
- swing.consoleFrame.pack()
- swing.consoleFrame.show()
- }
- installInterceptor()
- updateTitle() // Title changes based on indy setting
- swing.doLater inputArea.&requestFocus
- }
-
- /**
- * Make the console frames capable of native fullscreen
- * for Mac OS X Lion and beyond.
- *
- * @param frame the application window
- */
- private void nativeFullScreenForMac(Window frame) {
- if (System.getProperty('os.name').contains('Mac OS X')) {
- new GroovyShell(new Binding([frame: frame])).evaluate('''
- try {
- com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(frame, true)
- } catch (Throwable t) {
- // simply ignore as full screen capability is not available
- }
- ''')
- }
- }
-
- void installInterceptor() {
- systemOutInterceptor = new SystemOutputInterceptor(this.¬ifySystemOut, true)
- systemOutInterceptor.start()
- systemErrorInterceptor = new SystemOutputInterceptor(this.¬ifySystemErr, false)
- systemErrorInterceptor.start()
- }
-
- void addToHistory(record) {
- history.add(record)
- // history.size here just retrieves method closure
- if (history.size() > maxHistory) {
- history.remove(0)
- }
- // history.size doesn't work here either
- historyIndex = history.size()
- updateHistoryActions()
- }
-
- // Ensure we don't have too much in console (takes too much memory)
- private ensureNoDocLengthOverflow(doc) {
- // if it is a case of stackOverFlowError, show the exception details from the front
- // as there is no point in showing the repeating details at the back
- int offset = stackOverFlowError ? maxOutputChars : 0
- if (doc.length > maxOutputChars) {
- doc.remove(offset, doc.length - maxOutputChars)
- }
- }
-
- // Append a string to the output area
- void appendOutput(String text, AttributeSet style){
- def doc = outputArea.styledDocument
- insertString(doc, doc.length, text, style)
- ensureNoDocLengthOverflow(doc)
- }
-
- void appendOutput(Window window, AttributeSet style) {
- appendOutput(window.toString(), style)
- }
-
- void appendOutput(Object object, AttributeSet style) {
- appendOutput(object.toString(), style)
- }
-
- void appendOutput(Component component, AttributeSet style) {
- SimpleAttributeSet sas = new SimpleAttributeSet()
- sas.addAttribute(StyleConstants.NameAttribute, 'component')
- StyleConstants.setComponent(sas, component)
- appendOutput(component.toString(), sas)
- }
-
- void appendOutput(Icon icon, AttributeSet style) {
- SimpleAttributeSet sas = new SimpleAttributeSet()
- sas.addAttribute(StyleConstants.NameAttribute, 'icon')
- StyleConstants.setIcon(sas, icon)
- appendOutput(icon.toString(), sas)
- }
-
- void appendStacktrace(text) {
- def doc = outputArea.styledDocument
-
- // split lines by new line separator
- def lines = text.split(/(\n|\r|\r\n|\u0085|\u2028|\u2029)/)
-
- // Java Identifier regex
- def ji = /([\p{Alnum}_\$][\p{Alnum}_\$]*)/
-
- // stacktrace line regex
- def stacktracePattern = /\tat $ji(\.$ji)+\((($ji(\.(java|groovy))?):(\d+))\)/
-
- lines.each { line ->
- int initialLength = doc.length
-
- def matcher = line =~ stacktracePattern
- def fileName = matcher.matches() ? matcher[0][-5] : ''
-
- if (fileName == scriptFile?.name || fileName.startsWith(DEFAULT_SCRIPT_NAME_START)) {
- def fileNameAndLineNumber = matcher[0][-6]
- def length = fileNameAndLineNumber.length()
- def index = line.indexOf(fileNameAndLineNumber)
-
- def style = hyperlinkStyle
- def hrefAttr = new SimpleAttributeSet()
- // don't pass a GString as it won't be coerced to String as addAttribute takes an Object
- hrefAttr.addAttribute(HTML.Attribute.HREF, 'file://' + fileNameAndLineNumber)
- style.addAttribute(HTML.Tag.A, hrefAttr)
-
- insertString(doc, initialLength, line[0..<index], stacktraceStyle)
- insertString(doc, initialLength + index, line[index..<(index + length)], style)
- insertString(doc, initialLength + index + length, line[(index + length)..-1] + '\n', stacktraceStyle)
- } else {
- insertString(doc, initialLength, line + '\n', stacktraceStyle)
- }
- }
-
- ensureNoDocLengthOverflow(doc)
- }
-
- void insertString(Document doc, int offset, String text, AttributeSet attributeSet, boolean outputToFile = true) {
- doc.insertString(offset, text, attributeSet)
-
- // Output to file if activated
- if (outputToFile && outputPrintWriter != null) {
- outputPrintWriter.append(text)
- outputPrintWriter.flush()
- }
- }
-
- // Append a string to the output area on a new line
- void appendOutputNl(text, style) {
- def doc = outputArea.styledDocument
- def len = doc.length
- def alreadyNewLine = (len == 0 || doc.getText(len - 1, 1) == '\n')
- insertString(doc, doc.length, ' \n', style)
- if (alreadyNewLine) {
- doc.remove(len, 2) // windows hack to fix (improve?) line spacing
- }
- appendOutput(text, style)
- }
-
- void appendOutputLines(text, style) {
- appendOutput(text, style)
- def doc = outputArea.styledDocument
- def len = doc.length
-
- // Disable output to log file in this case ('\n' is removed from outputArea next line)
- insertString(doc, len, ' \n', style, false)
- doc.remove(len, 2) // windows hack to fix (improve?) line spacing
- }
-
- // Return false if use elected to cancel
- boolean askToSaveFile() {
- if (!dirty) {
- return true
- }
- switch (JOptionPane.showConfirmDialog(frame,
- 'Save changes' + (scriptFile != null ? " to ${scriptFile.name}" : '') + '?',
- 'GroovyConsole', JOptionPane.YES_NO_CANCEL_OPTION))
- {
- case JOptionPane.YES_OPTION:
- return fileSave()
- case JOptionPane.NO_OPTION:
- return true
- default:
- return false
- }
- }
-
- void beep() {
- Toolkit.defaultToolkit.beep()
- }
-
- // Binds the '_' and '__' variables in the shell
- void bindResults() {
- shell.setVariable('_', getLastResult()) // lastResult doesn't seem to work
- shell.setVariable('__', history.collect {it.result})
- }
-
- // Handles menu event
- static void captureStdOut(EventObject evt) {
- captureStdOut = evt.source.selected
- prefs.putBoolean('captureStdOut', captureStdOut)
- }
-
- static void captureStdErr(EventObject evt) {
- captureStdErr = evt.source.selected
- prefs.putBoolean('captureStdErr', captureStdErr)
- }
-
- void fullStackTraces(EventObject evt) {
- fullStackTraces = evt.source.selected
- System.setProperty('groovy.full.stacktrace',
- Boolean.toString(fullStackTraces))
- prefs.putBoolean('fullStackTraces', fullStackTraces)
- }
-
- void showScriptInOutput(EventObject evt) {
- showScriptInOutput = evt.source.selected
- prefs.putBoolean('showScriptInOutput', showScriptInOutput)
- }
-
- void visualizeScriptResults(EventObject evt) {
- visualizeScriptResults = evt.source.selected
- prefs.putBoolean('visualizeScriptResults', visualizeScriptResults)
- }
-
- void showToolbar(EventObject evt) {
- showToolbar = evt.source.selected
- prefs.putBoolean('showToolbar', showToolbar)
- toolbar.visible = showToolbar
- }
-
- void orientationVertical(EventObject evt) {
- def oldValue = orientationVertical
- orientationVertical = evt.source.selected
- prefs.putBoolean('orientationVertical', orientationVertical)
- if (oldValue != orientationVertical) {
- if (orientationVertical) {
- splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT)
- } else {
- splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT)
- }
- splitPane.resizeWeight = detachedOutput ? 1.0 : 0.5
- splitPane.resetToPreferredSizes()
- }
- }
-
- void detachedOutput(EventObject evt) {
- def oldDetachedOutput = detachedOutput
- detachedOutput = evt.source.selected
- prefs.putBoolean('detachedOutput', detachedOutput)
- if (oldDetachedOutput != detachedOutput) {
- if (detachedOutput) {
- splitPane.add(blank, JSplitPane.BOTTOM)
- origDividerSize = splitPane.dividerSize
- splitPane.dividerSize = 0
- splitPane.resizeWeight = 1.0
- outputWindow.add(scrollArea, BorderLayout.CENTER)
- prepareOutputWindow()
- } else {
- splitPane.add(scrollArea, JSplitPane.BOTTOM)
- splitPane.dividerSize = origDividerSize
- outputWindow.add(blank, BorderLayout.CENTER)
- outputWindow.visible = false
- splitPane.resizeWeight = 0.5
- }
- }
- }
-
- void autoClearOutput(EventObject evt) {
- autoClearOutput = evt.source.selected
- prefs.putBoolean('autoClearOutput', autoClearOutput)
- }
-
- void threadInterruption(EventObject evt) {
- threadInterrupt = evt.source.selected
- prefs.putBoolean('threadInterrupt', threadInterrupt)
- def customizers = config.compilationCustomizers.iterator()
- while (customizers.hasNext()) {
- def next = customizers.next()
- if (next instanceof ASTTransformationCustomizer) {
- ASTTransformationCustomizer astCustomizer = next
- if (astCustomizer.transformation instanceof ThreadInterruptibleASTTransformation) {
- customizers.remove()
- }
- }
- }
- if (threadInterrupt) {
- config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt))
- }
- }
-
- void caretUpdate(CaretEvent e){
- textSelectionStart = Math.min(dot(e), mark(e))
- textSelectionEnd = Math.max(dot(e), mark(e))
- setRowNumAndColNum()
- }
-
- // GROOVY-8339: to avoid illegal access to a non-visible implementation class - can be removed if a more general solution is found
- @CompileStatic
- int dot(CaretEvent e) {
- e.dot
- }
-
- // GROOVY-8339: to avoid illegal access to a non-visible implementation class - can be removed if a more general solution is found
- @CompileStatic
- int mark(CaretEvent e) {
- e.mark
- }
-
- void clearOutput(EventObject evt = null) {
- outputArea.text = ''
- }
-
- // If at exit time, a script is running, the user is given an option to interrupt it first
- def askToInterruptScript() {
- if(!scriptRunning) return true
- def rc = JOptionPane.showConfirmDialog(frame, "Script executing. Press 'OK' to attempt to interrupt it before exiting.",
- 'GroovyConsole', JOptionPane.OK_CANCEL_OPTION)
- if (rc == JOptionPane.OK_OPTION) {
- doInterrupt()
- return true
- } else {
- return false
- }
- }
-
- void doInterrupt(EventObject evt = null) {
- runThread?.interrupt()
- }
-
- void exitDesktop(EventObject evt = null, quitResponse = null) {
- exit(evt)
- quitResponse.performQuit()
- }
-
- void exit(EventObject evt = null) {
- if (askToInterruptScript()) {
- if (askToSaveFile()) {
- if (frame instanceof Window) {
- frame.hide()
- frame.dispose()
- outputWindow?.dispose()
- }
- FindReplaceUtility.dispose()
- consoleControllers.remove(this)
- if (!consoleControllers) {
- systemOutInterceptor.stop()
- systemErrorInterceptor.stop()
- }
- }
- }
- }
-
- void fileNewFile(EventObject evt = null) {
- if (askToSaveFile()) {
- scriptFile = null
- setDirty(false)
- inputArea.text = ''
- }
- }
-
- // Start a new window with a copy of current variables
- void fileNewWindow(EventObject evt = null) {
- Console consoleController = new Console(
- new Binding(
- new HashMap(shell.getContext().variables)))
- consoleController.systemOutInterceptor = systemOutInterceptor
- consoleController.systemErrorInterceptor = systemErrorInterceptor
- SwingBuilder swing = new SwingBuilder()
- consoleController.swing = swing
- frameConsoleDelegates.each {k, v -> swing[k] = v}
- swing.controller = consoleController
- swing.build(ConsoleActions)
- swing.build(ConsoleView)
- installInterceptor()
- nativeFullScreenForMac(swing.consoleFrame)
- swing.consoleFrame.pack()
- swing.consoleFrame.show()
- swing.doLater swing.inputArea.&requestFocus
- }
-
- void fileOpen(EventObject evt = null) {
- if (askToSaveFile()) {
- def scriptName = selectFilename()
- if (scriptName != null) {
- loadScriptFile(scriptName)
- }
- }
- }
-
- void loadScriptFile(File file) {
- swing.edt {
- inputArea.editable = false
- }
- swing.doOutside {
- try {
- consoleText = file.readLines().join('\n')
- scriptFile = file
- swing.edt {
- def listeners = inputArea.document.getListeners(DocumentListener)
- listeners.each { inputArea.document.removeDocumentListener(it) }
- updateTitle()
- inputArea.document.remove 0, inputArea.document.length
- inputArea.document.insertString 0, consoleText, null
- listeners.each { inputArea.document.addDocumentListener(it) }
- setDirty(false)
- inputArea.caretPosition = 0
- }
- } finally {
- swing.edt { inputArea.editable = true }
- // GROOVY-3684: focus away and then back to inputArea ensures caret blinks
- swing.doLater outputArea.&requestFocusInWindow
- swing.doLater inputArea.&requestFocusInWindow
- }
- }
- }
-
- // Save file - return false if user cancelled save
- boolean fileSave(EventObject evt = null) {
- if (scriptFile == null) {
- return fileSaveAs(evt)
- }
-
- scriptFile.write(inputArea.text)
- setDirty(false)
- return true
- }
-
- // Save file - return false if user cancelled save
- boolean fileSaveAs(EventObject evt = null) {
- scriptFile = selectFilename('Save')
- if (scriptFile != null) {
- scriptFile.write(inputArea.text)
- setDirty(false)
- return true
- } else {
- return false
- }
- }
-
- def finishException(Throwable t, boolean executing) {
- if(executing) {
- statusLabel.text = 'Execution terminated with exception.'
- history[-1].exception = t
- } else {
- statusLabel.text = 'Compilation failed.'
- }
-
- if (t instanceof MultipleCompilationErrorsException) {
- MultipleCompilationErrorsException mcee = t
- ErrorCollector collector = mcee.errorCollector
- int count = collector.errorCount
- appendOutputNl("${count} compilation error${count > 1 ? 's' : ''}:\n\n", commandStyle)
-
- collector.errors.each { error ->
- if (error instanceof SyntaxErrorMessage) {
- SyntaxException se = error.cause
- int errorLine = se.line
- String message = se.originalMessage
-
- String scriptFileName = scriptFile?.name ?: DEFAULT_SCRIPT_NAME_START
-
- def doc = outputArea.styledDocument
-
- def style = hyperlinkStyle
- def hrefAttr = new SimpleAttributeSet()
- // don't pass a GString as it won't be coerced to String as addAttribute takes an Object
- hrefAttr.addAttribute(HTML.Attribute.HREF, 'file://' + scriptFileName + ':' + errorLine)
- style.addAttribute(HTML.Tag.A, hrefAttr)
-
- insertString(doc, doc.length, message + ' at ', stacktraceStyle)
- insertString(doc, doc.length, "line: ${se.line}, column: ${se.startColumn}\n\n", style)
- } else if (error instanceof Throwable) {
- reportException(error)
- } else if (error instanceof ExceptionMessage) {
- reportException(error.cause)
- } else if (error instanceof SimpleMessage) {
- def doc = outputArea.styledDocument
- insertString(doc, doc.length, "${error.message}\n", new SimpleAttributeSet())
- }
- }
- } else {
- reportException(t)
- }
-
- if(!executing) {
- bindResults()
- }
-
- // GROOVY-4496: set the output window position to the top-left so the exception details are visible from the start
- outputArea.caretPosition = 0
-
- if (detachedOutput) {
- prepareOutputWindow()
- showOutputWindow()
- }
- }
-
- private calcPreferredSize(a, b, c) {
- [c, [a, b].min()].max()
- }
-
- private reportException(Throwable t) {
- appendOutputNl('Exception thrown\n', commandStyle)
-
- Writer sw = new StringBuilderWriter()
- new PrintWriter(sw).withWriter {pw -> StackTraceUtils.deepSanitize(t).printStackTrace(pw) }
- appendStacktrace("\n${sw.builder}\n")
- }
-
- def finishNormal(Object result) {
- // Take down the wait/cancel dialog
- history[-1].result = result
- if (result != null) {
- statusLabel.text = 'Execution complete.'
- appendOutputNl('Result: ', promptStyle)
- def obj = (visualizeScriptResults
- ? OutputTransforms.transformResult(result, shell.getContext()._outputTransforms)
- : result.toString())
-
- // multi-methods are magical!
- appendOutput(obj, resultStyle)
- } else {
- statusLabel.text = 'Execution complete. Result was null.'
- }
- bindResults()
- if (detachedOutput) {
- prepareOutputWindow()
- showOutputWindow()
- }
- }
-
- def compileFinishNormal() {
- statusLabel.text = 'Compilation complete.'
- }
-
- private def prepareOutputWindow() {
- outputArea.setPreferredSize(null)
- outputWindow.pack()
- outputArea.setPreferredSize([calcPreferredSize(outputWindow.getWidth(), inputEditor.getWidth(), 120),
- calcPreferredSize(outputWindow.getHeight(), inputEditor.getHeight(), 60)] as Dimension)
- outputWindow.pack()
- }
-
- // Gets the last, non-null result
- def getLastResult() {
- // runtime bugs in here history.reverse produces odd lookup
- // return history.reverse.find {it != null}
- if (!history) {
- return
- }
- for (i in (history.size() - 1)..0) {
- if (history[i].result != null) {
- return history[i].result
- }
- }
- return null
- }
-
- void historyNext(EventObject evt = null) {
- if (historyIndex < history.size()) {
- setInputTextFromHistory(historyIndex + 1)
- } else {
- statusLabel.text = "Can't go past end of history (time travel not allowed)"
- beep()
- }
- }
-
- void historyPrev(EventObject evt = null) {
- if (historyIndex > 0) {
- setInputTextFromHistory(historyIndex - 1)
- } else {
- statusLabel.text = "Can't go past start of history"
- beep()
- }
- }
-
- void inspectLast(EventObject evt = null){
- if (null == lastResult) {
- JOptionPane.showMessageDialog(frame, 'The last result is null.',
- 'Cannot Inspect', JOptionPane.INFORMATION_MESSAGE)
- return
- }
- ObjectBrowser.inspect(lastResult)
- }
-
- void inspectVariables(EventObject evt = null) {
- ObjectBrowser.inspect(shell.getContext().variables)
- }
-
- void inspectAst(EventObject evt = null) {
- new AstBrowser(inputArea, rootElement, shell.getClassLoader(), config).run({ inputArea.getText() } )
- }
-
- void inspectTokens(EventObject evt = null) {
- def content = inputArea.getText()
- def lf = (CompilerConfiguration.DEFAULT.pluginFactory instanceof org.codehaus.groovy.antlr.AntlrParserPluginFactory
- ? LexerFrame.groovyScriptFactory(content) : new LexerFrame(GroovyLangLexer, org.apache.groovy.parser.antlr4.GroovyLexer, new StringReader(content)))
-
- lf.visible = true
- }
-
- void largerFont(EventObject evt = null) {
- updateFontSize(inputArea.font.size + 2)
- }
-
- static boolean notifySystemOut(int consoleId, String str) {
- if (!captureStdOut) {
- // Output as normal
- return true
- }
-
- Closure doAppend = {
- Console console = findConsoleById(consoleId)
- if (console) {
- console.appendOutputLines(str, console.outputStyle)
- } else {
- consoleControllers.each {it.appendOutputLines(str, it.outputStyle)}
- }
- }
-
- // Put onto GUI
- if (EventQueue.isDispatchThread()) {
- doAppend.call()
- }
- else {
- SwingUtilities.invokeLater doAppend
- }
- return false
- }
-
- static boolean notifySystemErr(int consoleId, String str) {
- if (!captureStdErr) {
- // Output as normal
- return true
- }
-
- Closure doAppend = {
- Console console = findConsoleById(consoleId)
- if (console) {
- console.appendStacktrace(str)
- } else {
- consoleControllers.each {it.appendStacktrace(str)}
- }
- }
-
- // Put onto GUI
- if (EventQueue.isDispatchThread()) {
- doAppend.call()
- }
- else {
- SwingUtilities.invokeLater doAppend
- }
- return false
- }
-
- int getConsoleId() {
- return System.identityHashCode(this)
- }
-
- private static Console findConsoleById(int consoleId) {
- return consoleControllers.find { it.consoleId == consoleId }
- }
-
- // actually run the script
-
- void runScript(EventObject evt = null) {
- if (saveOnRun && scriptFile != null) {
- if (fileSave(evt)) runScriptImpl(false)
- } else {
- runScriptImpl(false)
- }
- }
-
- void saveOnRun(EventObject evt = null) {
- saveOnRun = evt.source.selected
- prefs.putBoolean('saveOnRun', saveOnRun)
- }
-
- void indy(EventObject evt = null) {
- indy = evt.source.selected
- prefs.putBoolean('indy', indy)
- if (indy) {
- enableIndy(baseConfig)
- } else {
- disableIndy(baseConfig)
- }
- updateTitle()
- newScript(shell.classLoader, shell.context)
- }
-
- private static void enableIndy(CompilerConfiguration cc) {
- cc.getOptimizationOptions().put(CompilerConfiguration.INVOKEDYNAMIC, true)
- }
-
- private static void disableIndy(CompilerConfiguration cc) {
- cc.getOptimizationOptions().remove(CompilerConfiguration.INVOKEDYNAMIC)
- }
-
- private static boolean isIndyEnabled(CompilerConfiguration cc) {
- cc.getOptimizationOptions().get(CompilerConfiguration.INVOKEDYNAMIC)
- }
-
- void runSelectedScript(EventObject evt = null) {
- runScriptImpl(true)
- }
-
- void addClasspathJar(EventObject evt = null) {
- def fc = new JFileChooser(currentClasspathJarDir)
- fc.fileSelectionMode = JFileChooser.FILES_ONLY
- fc.multiSelectionEnabled = true
- fc.acceptAllFileFilterUsed = true
- if (fc.showDialog(frame, 'Add') == JFileChooser.APPROVE_OPTION) {
- currentClasspathJarDir = fc.currentDirectory
- Preferences.userNodeForPackage(Console).put('currentClasspathJarDir', currentClasspathJarDir.path)
- fc.selectedFiles?.each { file ->
- shell.getClassLoader().addURL(file.toURL())
- }
- }
- }
-
- void addClasspathDir(EventObject evt = null) {
- def fc = new JFileChooser(currentClasspathDir)
- fc.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
- fc.acceptAllFileFilterUsed = true
- if (fc.showDialog(frame, 'Add') == JFileChooser.APPROVE_OPTION) {
- currentClasspathDir = fc.currentDirectory
- Preferences.userNodeForPackage(Console).put('currentClasspathDir', currentClasspathDir.path)
- shell.getClassLoader().addURL(fc.selectedFile.toURL())
- }
- }
-
- void listClasspath(EventObject evt = null) {
- List<URL> urls = []
-
- ClassLoader cl = shell.classLoader
- while(cl instanceof URLClassLoader) {
- cl.getURLs().each { url -> urls << url }
- cl = cl.parent
- }
-
- boolean isWin = isWindows()
- List data = urls.unique().collect { url -> [name: new File(url.toURI()).name, path: isWin ? url.path.substring(1).replace('/', '\\') : url.path] }
- data.sort { it.name.toLowerCase() }
-
- JScrollPane scrollPane = swing.scrollPane{
- table {
- tableModel(list : data) {
- propertyColumn(header: 'Name', propertyName: 'name', editable: false)
- propertyColumn(header:' Path', propertyName: 'path', editable: false)
- }
- }
- }
-
- def pane = swing.optionPane()
- pane.message = scrollPane
- def dialog = pane.createDialog(frame, 'Classpath')
- dialog.setSize(800, 600)
- dialog.resizable = true
- dialog.visible = true
- }
-
- void clearContext(EventObject evt = null) {
- def binding = new Binding()
- newScript(null, binding)
- // reload output transforms
- binding.variables._outputTransforms = OutputTransforms.loadOutputTransforms()
- }
-
- private void runScriptImpl(boolean selected) {
- if(scriptRunning) {
- statusLabel.text = 'Cannot run script now as a script is already running. Please wait or use "Interrupt Script" option.'
- return
- }
- scriptRunning = true
- interruptAction.enabled = true
- stackOverFlowError = false // reset this flag before running a script
- def endLine = System.getProperty('line.separator')
- def record = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'),
- selectionStart: textSelectionStart, selectionEnd: textSelectionEnd)
- addToHistory(record)
- pendingRecord = new HistoryRecord(allText:'', selectionStart:0, selectionEnd:0)
-
- if (prefs.getBoolean('autoClearOutput', false)) clearOutput()
-
- // Print the input text
- if (showScriptInOutput) {
- for (line in record.getTextToRun(selected).tokenize('\n')) {
- appendOutputNl('groovy> ', promptStyle)
- appendOutput(line, commandStyle)
- }
- appendOutputNl(' \n', promptStyle)
- }
-
- // Kick off a new thread to do the evaluation
- // Run in a thread outside of EDT, this method is usually called inside the EDT
- runThread = Thread.start {
- try {
- systemOutInterceptor.setConsoleId(this.getConsoleId())
- SwingUtilities.invokeLater { showExecutingMessage() }
- String name = scriptFile?.name ?: (DEFAULT_SCRIPT_NAME_START + scriptNameCounter++)
- if(beforeExecution) {
- beforeExecution()
- }
- def result
- if(useScriptClassLoaderForScriptExecution) {
- ClassLoader savedThreadContextClassLoader = Thread.currentThread().contextClassLoader
- try {
- Thread.currentThread().contextClassLoader = shell.classLoader
- result = shell.run(record.getTextToRun(selected), name, [])
- }
- finally {
- Thread.currentThread().contextClassLoader = savedThreadContextClassLoader
- }
- }
- else {
- result = shell.run(record.getTextToRun(selected), name, [])
- }
- if(afterExecution) {
- afterExecution()
- }
- SwingUtilities.invokeLater { finishNormal(result) }
- } catch (Throwable t) {
- if(t instanceof StackOverflowError) {
- // set the flag that will be used in printing exception details in output pane
- stackOverFlowError = true
- clearOutput()
- }
- SwingUtilities.invokeLater { finishException(t, true) }
- } finally {
- runThread = null
- scriptRunning = false
- interruptAction.enabled = false
- systemOutInterceptor.removeConsoleId()
- }
- }
- }
-
- void compileScript(EventObject evt = null) {
- if(scriptRunning) {
- statusLabel.text = 'Cannot compile script now as a script is already running. Please wait or use "Interrupt Script" option.'
- return
- }
- stackOverFlowError = false // reset this flag before running a script
- def endLine = System.getProperty('line.separator')
- def record = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'),
- selectionStart: textSelectionStart, selectionEnd: textSelectionEnd)
-
- if (prefs.getBoolean('autoClearOutput', false)) clearOutput()
-
- // Print the input text
- if (showScriptInOutput) {
- for (line in record.allText.tokenize('\n')) {
- appendOutputNl('groovy> ', promptStyle)
- appendOutput(line, commandStyle)
- }
- appendOutputNl(' \n', promptStyle)
- }
-
- // Kick off a new thread to do the compilation
- // Run in a thread outside of EDT, this method is usually called inside the EDT
- runThread = Thread.start {
- try {
- SwingUtilities.invokeLater { showCompilingMessage() }
- shell.getClassLoader().parseClass(record.allText)
- SwingUtilities.invokeLater { compileFinishNormal() }
- } catch (Throwable t) {
- SwingUtilities.invokeLater { finishException(t, false) }
- } finally {
- runThread = null
- }
- }
- }
-
- def selectFilename(name = 'Open') {
- def fc = new JFileChooser(currentFileChooserDir)
- fc.fileSelectionMode = JFileChooser.FILES_ONLY
- fc.acceptAllFileFilterUsed = true
- fc.fileFilter = groovyFileFilter
- if(name == 'Save') {
- fc.selectedFile = new File('*.groovy')
- }
- if (fc.showDialog(frame, name) == JFileChooser.APPROVE_OPTION) {
- currentFileChooserDir = fc.currentDirectory
- Preferences.userNodeForPackage(Console).put('currentFileChooserDir', currentFileChooserDir.path)
- return fc.selectedFile
- } else {
- return null
- }
- }
-
- void setDirty(boolean newDirty) {
- //TODO when @BoundProperty is live, this should be handled via listeners
- dirty = newDirty
- saveAction.enabled = newDirty
- updateTitle()
- }
-
- private void setInputTextFromHistory(newIndex) {
- def endLine = System.getProperty('line.separator')
- if (historyIndex >= history.size()) {
- pendingRecord = new HistoryRecord( allText: inputArea.getText().replaceAll(endLine, '\n'),
- selectionStart: textSelectionStart, selectionEnd: textSelectionEnd)
- }
- historyIndex = newIndex
- def record
- if (historyIndex < history.size()) {
- record = history[historyIndex]
- statusLabel.text = "command history ${history.size() - historyIndex}"
- } else {
- record = pendingRecord
- statusLabel.text = 'at end of history'
- }
- inputArea.text = record.allText
- inputArea.selectionStart = record.selectionStart
- inputArea.selectionEnd = record.selectionEnd
- setDirty(true) // Should calculate dirty flag properly (hash last saved/read text in each file)
- updateHistoryActions()
- }
-
- private void updateHistoryActions() {
- nextHistoryAction.enabled = historyIndex < history.size()
- prevHistoryAction.enabled = historyIndex > 0
- }
-
- // Adds a variable to the binding
- // Useful for adding variables before opening the console
- void setVariable(String name, Object value) {
- shell.getContext().setVariable(name, value)
- }
-
- void showAbout(EventObject evt = null) {
- def version = GroovySystem.getVersion()
- def pane = swing.optionPane()
- // work around GROOVY-1048
- pane.setMessage('Welcome to the Groovy Console for evaluating Groovy scripts\nVersion ' + version)
- def dialog = pane.createDialog(frame, 'About GroovyConsole')
- dialog.show()
- }
-
- void find(EventObject evt = null) {
- FindReplaceUtility.showDialog()
- }
-
- void findNext(EventObject evt = null) {
- FindReplaceUtility.FIND_ACTION.actionPerformed(evt)
- }
-
- void findPrevious(EventObject evt = null) {
- def reverseEvt = new ActionEvent(
- evt.getSource(), evt.getID(),
- evt.getActionCommand(), evt.getWhen(),
- ActionEvent.SHIFT_MASK) //reverse
- FindReplaceUtility.FIND_ACTION.actionPerformed(reverseEvt)
- }
-
- void replace(EventObject evt = null) {
- FindReplaceUtility.showDialog(true)
- }
-
- void comment(EventObject evt = null) {
- def rootElement = inputArea.document.defaultRootElement
- def cursorPos = inputArea.getCaretPosition()
- int startRow = rootElement.getElementIndex(cursorPos)
- int endRow = startRow
-
- if (inputArea.getSelectedText()) {
- def selectionStart = inputArea.getSelectionStart()
- startRow = rootElement.getElementIndex(selectionStart)
- def selectionEnd = inputArea.getSelectionEnd()
- endRow = rootElement.getElementIndex(selectionEnd)
- }
-
- // If multiple commented lines intermix with uncommented lines, consider them uncommented
- def allCommented = true
- startRow.upto(endRow) { rowIndex ->
- def rowElement = rootElement.getElement(rowIndex)
- int startOffset = rowElement.getStartOffset()
- int endOffset = rowElement.getEndOffset()
- String rowText = inputArea.document.getText(startOffset, endOffset - startOffset)
- if (rowText.trim().length() < 2 || !rowText.trim().substring(0, 2).equals("//")) {
- allCommented = false
- }
- }
-
- startRow.upto(endRow) { rowIndex ->
- def rowElement = rootElement.getElement(rowIndex)
- int startOffset = rowElement.getStartOffset()
- int endOffset = rowElement.getEndOffset()
- String rowText = inputArea.document.getText(startOffset, endOffset - startOffset)
- if (allCommented) {
- // Uncomment this line if it is already commented
- int slashOffset = rowText.indexOf("//")
- inputArea.document.remove(slashOffset + startOffset, 2)
- } else {
- // Add comment string in front of this line
- inputArea.document.insertString(startOffset, "//", new SimpleAttributeSet())
- }
- }
- }
-
- void selectBlock(EventObject evt = null) {
- final int startPos = inputArea.getSelectionStart()
- final int endPos = inputArea.getSelectionEnd()
- final int startRow = rootElement.getElementIndex(startPos)
- final int endRow = rootElement.getElementIndex(endPos)
- final Element rowElement = rootElement.getElement(startRow)
- final int startRowOffset = rowElement.getStartOffset()
- final int endRowOffset = rowElement.getEndOffset()
-
- // Empty line, nothing to do
- if (startRowOffset == endRowOffset - 1) {
- return
- }
-
- // Nothing is currently selected so select next chunk unless we are at the end of
- // the line then we select the previous
- if (startPos == endPos && selectWordAction != null && selectPreviousWordAction != null) {
- if (endPos == endRowOffset - 1) {
- selectPreviousWordAction.actionPerformed(evt)
- } else {
- selectWordAction.actionPerformed(evt)
- }
- return
- }
-
- // Partial selection on a single line but not the entire line or word
- // selection actions are not available so select the entire line
- if (startRow == endRow && (startPos != startRowOffset || (endPos != endRowOffset - 1))) {
- inputArea.setSelectionStart(startRowOffset)
- inputArea.setSelectionEnd(endRowOffset - 1)
- return
- }
-
- // At this point an entire line or multiple lines are selected so
- // look for a block/paragraph to select
- String rowText = inputArea.document.getText(startRowOffset, endRowOffset - startRowOffset)
- if (!rowText?.trim()) {
- // Selection is empty or all spaces so not part of any block
- return
- }
-
- // Look up for first empty row
- int startBlockPos = startRowOffset
- for (int i = startRow - 1; i >= 0; i--) {
- Element re = rootElement.getElement(i)
- rowText = inputArea.document.getText(re.getStartOffset(), re.getEndOffset() - re.getStartOffset())
- if (!rowText?.trim()) {
- break
- }
- startBlockPos = re.getStartOffset()
- }
-
- // Look down for first empty row
- int endBlockPos = endRowOffset
- int totalRows = rootElement.getElementCount()
- for (int i = startRow + 1; i < totalRows; i++) {
- Element re = rootElement.getElement(i)
- rowText = inputArea.document.getText(re.getStartOffset(), re.getEndOffset() - re.getStartOffset())
- if (!rowText?.trim()) {
- break
- }
- endBlockPos = re.getEndOffset()
- }
-
- inputArea.setSelectionStart(startBlockPos)
- inputArea.setSelectionEnd(endBlockPos)
- }
-
- void showMessage(String message) {
- statusLabel.text = message
- }
-
- void showExecutingMessage() {
- statusLabel.text = 'Script executing now. Please wait or use "Interrupt Script" option.'
- }
-
- void showCompilingMessage() {
- statusLabel.text = 'Script compiling now. Please wait.'
- }
-
- // Shows the detached 'outputArea' dialog
- void showOutputWindow(EventObject evt = null) {
- if (detachedOutput) {
- outputWindow.setLocationRelativeTo(frame)
- outputWindow.show()
- }
- }
-
- void hideOutputWindow(EventObject evt = null) {
- if (detachedOutput) {
- outputWindow.visible = false
- }
- }
-
- void hideAndClearOutputWindow(EventObject evt = null) {
- clearOutput()
- hideOutputWindow()
- }
-
- void smallerFont(EventObject evt = null){
- updateFontSize(inputArea.font.size - 2)
- }
-
- void smartHighlighter(EventObject evt = null) {
- inputEditor.enableHighLighter(evt.source.selected ? SmartDocumentFilter : GroovyFilter)
- inputEditor.textEditor.setText(inputEditor.textEditor.getText()) // enable the highlighter immediately
- prefs.putBoolean('smartHighlighter', evt.source.selected)
- }
-
- void updateTitle() {
- if (frame.title) {
- String title = 'GroovyConsole'
- if (indy) {
- title += ' (Indy)'
- }
- if (scriptFile != null) {
- frame.title = scriptFile.name + (dirty?' * ':'') + ' - ' + title
- } else {
- frame.title = title
- }
- }
- }
-
- private updateFontSize(newFontSize) {
- if (newFontSize > 40) {
- newFontSize = 40
- } else if (newFontSize < 4) {
- newFontSize = 4
- }
-
- prefs.putInt('fontSize', newFontSize)
-
- // don't worry, the fonts won't be changed to this family, the styles will only derive from this
- def newFont = new Font(inputEditor.defaultFamily, Font.PLAIN, newFontSize)
- inputArea.font = newFont
- outputArea.font = newFont
- }
-
- void invokeTextAction(evt, closure, area = inputArea) {
- def source = evt.getSource()
- if (source != null) {
- closure(area)
- }
- }
-
- void cut(EventObject evt = null) {
- invokeTextAction(evt, { source -> source.cut() })
- }
-
- void copy(EventObject evt = null) {
- invokeTextAction(evt, { source -> source.copy() }, copyFromComponent ?: inputArea)
- }
-
- void paste(EventObject evt = null) {
- invokeTextAction(evt, { source -> source.paste() })
- }
-
- void selectAll(EventObject evt = null) {
- invokeTextAction(evt, { source -> source.selectAll() }, copyFromComponent ?: inputArea)
- }
-
- void setRowNumAndColNum() {
- cursorPos = inputArea.getCaretPosition()
- rowNum = rootElement.getElementIndex(cursorPos) + 1
-
- def rowElement = rootElement.getElement(rowNum - 1)
- colNum = cursorPos - rowElement.getStartOffset() + 1
-
- rowNumAndColNum.setText("$rowNum:$colNum")
- }
-
- void print(EventObject evt = null) {
- inputEditor.printAction.actionPerformed(evt)
- }
-
- void undo(EventObject evt = null) {
- inputEditor.undoAction.actionPerformed(evt)
- }
-
- void redo(EventObject evt = null) {
- inputEditor.redoAction.actionPerformed(evt)
- }
-
- void hyperlinkUpdate(HyperlinkEvent e) {
- if (e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
- // URL of the form: file://myscript.groovy:32
- String url = e.getURL()
- int lineNumber = url[(url.lastIndexOf(':') + 1)..-1].toInteger()
-
- def editor = inputEditor.textEditor
- def text = editor.text
-
- int newlineBefore = 0
- int newlineAfter = 0
- int currentLineNumber = 1
-
- // let's find the previous and next newline surrounding the offending line
- int i = 0
- for (ch in text) {
- if (ch == '\n') {
- currentLineNumber++
- }
- if (currentLineNumber == lineNumber) {
- newlineBefore = i
- def nextNewline = text.indexOf('\n', i + 1)
- newlineAfter = nextNewline > -1 ? nextNewline : text.length()
- break
- }
- i++
- }
-
- // highlight / select the whole line
- editor.setCaretPosition(newlineBefore)
- editor.moveCaretPosition(newlineAfter)
- }
- }
-
- void componentHidden(ComponentEvent e) { }
-
- void componentMoved(ComponentEvent e) { }
-
- void componentResized(ComponentEvent e) {
- def component = e.getComponent()
- if (component == outputArea || component == inputArea) {
- def rect = component.getVisibleRect()
- prefs.putInt("${component.name}Width", rect.getWidth().intValue())
- prefs.putInt("${component.name}Height", rect.getHeight().intValue())
- } else {
- prefs.putInt("${component.name}Width", component.width)
- prefs.putInt("${component.name}Height", component.height)
- }
- }
-
- void componentShown(ComponentEvent e) { }
-
- void focusGained(FocusEvent e) {
- // remember component with focus for text-copy functionality
- if (e.component == outputArea || e.component == inputArea) {
- copyFromComponent = e.component
- }
- }
-
- void focusLost(FocusEvent e) { }
-
- private static boolean isWindows() {
- return getOsName().startsWith("windows")
- }
- private static String getOsName() {
- return System.getProperty("os.name").toLowerCase()
- }
-}
-
-@CompileStatic
-@Deprecated
-class GroovyFileFilter extends FileFilter {
- private static final List GROOVY_SOURCE_EXTENSIONS = ['*.groovy', '*.gvy', '*.gy', '*.gsh', '*.story', '*.gpp', '*.grunit']
- private static final GROOVY_SOURCE_EXT_DESC = GROOVY_SOURCE_EXTENSIONS.join(',')
-
- boolean accept(File f) {
- if (f.isDirectory()) {
- return true
- }
- GROOVY_SOURCE_EXTENSIONS.find {it == getExtension(f)} ? true : false
- }
-
- String getDescription() {
- "Groovy Source Files ($GROOVY_SOURCE_EXT_DESC)"
- }
-
- static String getExtension(File f) {
- def ext = null
- def s = f.getName()
- def i = s.lastIndexOf('.')
- if (i > 0 && i < s.length() - 1) {
- ext = s.substring(i).toLowerCase()
- }
- "*$ext"
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleActions.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleActions.groovy
deleted file mode 100644
index 50b536e..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleActions.groovy
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import javax.swing.*
-import java.awt.*
-import java.awt.event.InputEvent
-import java.awt.event.KeyEvent
-
-newFileAction = action(
- name: 'New File',
- closure: controller.&fileNewFile,
- mnemonic: 'N',
- accelerator: shortcut('N'),
- smallIcon: imageIcon(resource:'icons/page.png', class:this),
- shortDescription: 'New Groovy Script'
-)
-
-newWindowAction = action(
- name: 'New Window',
- closure: controller.&fileNewWindow,
- mnemonic: 'W',
- accelerator: shortcut('shift N')
-)
-
-openAction = action(
- name: 'Open',
- closure: controller.&fileOpen,
- mnemonic: 'O',
- accelerator: shortcut('O'),
- smallIcon: imageIcon(resource:'icons/folder_page.png', class:this),
- shortDescription: 'Open Groovy Script'
-)
-
-saveAction = action(
- name: 'Save',
- closure: controller.&fileSave,
- mnemonic: 'S',
- accelerator: shortcut('S'),
- smallIcon: imageIcon(resource:'icons/disk.png', class:this),
- shortDescription: 'Save Groovy Script',
- enabled: false // controller will enable as needed
-)
-
-saveAsAction = action(
- name: 'Save As...',
- closure: controller.&fileSaveAs,
- mnemonic: 'A',
-)
-
-printAction = action(
- name: 'Print...',
- closure: controller.&print,
- mnemonic: 'P',
- accelerator: shortcut('P')
-)
-
-exitAction = action(
- name: 'Exit',
- closure: controller.&exit,
- mnemonic: 'X'
-// whether or not application exit should have an
-// accelerator is debatable in usability circles
-// at the very least a confirm dialog should dhow up
-//accelerator: shortcut('Q')
-)
-
-undoAction = action(
- name: 'Undo',
- closure: controller.&undo,
- mnemonic: 'U',
- accelerator: shortcut('Z'),
- smallIcon: imageIcon(resource:'icons/arrow_undo.png', class:this),
- shortDescription: 'Undo'
-)
-
-redoAction = action(
- name: 'Redo',
- closure: controller.&redo,
- mnemonic: 'R',
- accelerator: shortcut('shift Z'), // is control-shift-Z or control-Y more common?
- smallIcon: imageIcon(resource:'icons/arrow_redo.png', class:this),
- shortDescription: 'Redo'
-)
-
-findAction = action(
- name: 'Find...',
- closure: controller.&find,
- mnemonic: 'F',
- accelerator: shortcut('F'),
- smallIcon: imageIcon(resource:'icons/find.png', class:this),
- shortDescription: 'Find'
-)
-
-findNextAction = action(
- name: 'Find Next',
- closure: controller.&findNext,
- mnemonic: 'N',
- accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)
-)
-
-findPreviousAction = action(
- name: 'Find Previous',
- closure: controller.&findPrevious,
- mnemonic: 'V',
- accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK)
-)
-
-replaceAction = action(
- name: 'Replace...',
- closure: controller.&replace,
- mnemonic: 'E',
- accelerator: shortcut('H'),
- smallIcon: imageIcon(resource:'icons/text_replace.png', class:this),
- shortDescription: 'Replace'
-)
-
-cutAction = action(
- name: 'Cut',
- closure: controller.&cut,
- mnemonic: 'T',
- accelerator: shortcut('X'),
- smallIcon: imageIcon(resource:'icons/cut.png', class:this),
- shortDescription: 'Cut'
-)
-
-copyAction = action(
- name: 'Copy',
- closure: controller.©,
- mnemonic: 'C',
- accelerator: shortcut('C'),
- smallIcon: imageIcon(resource:'icons/page_copy.png', class:this),
- shortDescription: 'Copy'
-)
-
-pasteAction = action(
- name: 'Paste',
- closure: controller.&paste,
- mnemonic: 'P',
- accelerator: shortcut('V'),
- smallIcon: imageIcon(resource:'icons/page_paste.png', class:this),
- shortDescription: 'Paste'
-)
-
-selectAllAction = action(
- name: 'Select All',
- closure: controller.&selectAll,
- mnemonic: 'A',
- accelerator: shortcut('A')
-)
-
-historyPrevAction = action(
- name: 'Previous',
- closure: controller.&historyPrev,
- mnemonic: 'P',
- accelerator: shortcut(KeyEvent.VK_COMMA),
- smallIcon: imageIcon(resource:'icons/book_previous.png', class:this),
- shortDescription: 'Previous Groovy Script',
- enabled: false // controller will enable as needed
-)
-
-historyNextAction = action(
- name: 'Next',
- closure: controller.&historyNext,
- mnemonic: 'N',
- accelerator: shortcut(KeyEvent.VK_PERIOD),
- smallIcon: imageIcon(resource:'icons/book_next.png', class:this),
- shortDescription: 'Next Groovy Script',
- enabled: false // controller will enable as needed
-)
-
-clearOutputAction = action(
- name: 'Clear Output',
- closure: controller.&clearOutput,
- mnemonic: 'C',
- accelerator: shortcut('W'),
- smallIcon: imageIcon(resource:'icons/clear.png', class:this),
- shortDescription: 'Clear Output Area'
-)
-
-runAction = action(
- name: 'Run',
- closure: controller.&runScript,
- mnemonic: 'R',
- keyStroke: shortcut('ENTER'),
- accelerator: shortcut('R'),
- smallIcon: imageIcon(resource:'icons/script_go.png', class:this),
- shortDescription: 'Execute Groovy Script'
-)
-
-runSelectionAction = action(
- name: 'Run Selection',
- closure: controller.&runSelectedScript,
- mnemonic: 'E',
- keyStroke: shortcut('shift ENTER'),
- accelerator: shortcut('shift R')
-)
-
-addClasspathJar = action(
- name: 'Add Jar(s) to ClassPath',
- closure: controller.&addClasspathJar,
- mnemonic: 'J',
-)
-
-addClasspathDir = action(
- name: 'Add Directory to ClassPath',
- closure: controller.&addClasspathDir,
- mnemonic: 'D',
-)
-
-listClasspath = action(
- name: 'List Classpath',
- closure: controller.&listClasspath
-)
-
-clearClassloader = action(
- name: 'Clear Script Context',
- closure: controller.&clearContext,
- mnemonic: 'C',
-)
-
-inspectLastAction = action(
- name: 'Inspect Last',
- closure: controller.&inspectLast,
- mnemonic: 'I',
- accelerator: shortcut('I')
-)
-
-inspectVariablesAction = action(
- name: 'Inspect Variables',
- closure: controller.&inspectVariables,
- mnemonic: 'V',
- accelerator: shortcut('J')
-)
-
-inspectAstAction = action(
- name: 'Inspect Ast',
- closure: controller.&inspectAst,
- mnemonic: 'A',
- accelerator: shortcut('T'),
-)
-
-inspectTokensAction = action(
- name: 'Inspect Tokens',
- closure: controller.&inspectTokens,
- mnemonic: 'T',
- accelerator: shortcut('K'),
-)
-
-captureStdOutAction = action(
- name: 'Capture Standard Output',
- closure: controller.&captureStdOut,
- mnemonic: 'O'
-)
-
-captureStdErrAction = action(
- name: 'Capture Standard Error Output',
- closure: controller.&captureStdErr,
- mnemonic: 'E'
-)
-
-fullStackTracesAction = action(
- name: 'Show Full Stack Traces',
- closure: controller.&fullStackTraces,
- mnemonic: 'F'
-)
-
-showScriptInOutputAction = action(
- name: 'Show Script in Output',
- closure: controller.&showScriptInOutput,
- mnemonic: 'R'
-)
-
-visualizeScriptResultsAction = action(
- name: 'Visualize Script Results',
- closure: controller.&visualizeScriptResults,
- mnemonic: 'V'
-)
-
-showToolbarAction = action(
- name: 'Show Toolbar',
- closure: controller.&showToolbar,
- mnemonic: 'T'
-)
-
-detachedOutputAction = action(
- name: 'Detached Output',
- closure: controller.&detachedOutput,
- mnemonic: 'D'
-)
-
-orientationVerticalAction = action(
- name: 'Vertical Orientation',
- closure: controller.&orientationVertical,
- mnemonic: 'n'
-)
-
-showOutputWindowAction = action(
- closure: controller.&showOutputWindow,
- keyStroke: shortcut('shift O'),
-)
-
-hideOutputWindowAction1 = action(
- closure: controller.&hideOutputWindow,
- keyStroke: 'SPACE',
-)
-
-hideOutputWindowAction2 = action(
- closure: controller.&hideOutputWindow,
- keyStroke: 'ENTER',
-)
-
-hideOutputWindowAction3 = action(
- closure: controller.&hideOutputWindow,
- keyStroke: 'ESCAPE',
-)
-
-hideOutputWindowAction4 = action(
- closure: controller.&hideAndClearOutputWindow,
- keyStroke: shortcut('W'),
-)
-
-autoClearOutputAction = action(
- name: 'Auto Clear Output On Run',
- closure: controller.&autoClearOutput,
- mnemonic: 'A'
-)
-
-saveOnRunAction = action(
- name: 'Auto Save on Runs',
- closure: controller.&saveOnRun,
- mnemonic: 'A'
-)
-
-largerFontAction = action(
- name: 'Larger Font',
- closure: controller.&largerFont,
- mnemonic: 'L',
- accelerator: shortcut('shift L')
-)
-
-smallerFontAction = action(
- name: 'Smaller Font',
- closure: controller.&smallerFont,
- mnemonic: 'S',
- accelerator: shortcut('shift S')
-)
-
-smartHighlighterAction = action(
- name: 'Enable Smart Highlighter',
- closure: controller.&smartHighlighter
-)
-
-aboutAction = action(
- name: 'About',
- closure: controller.&showAbout,
- mnemonic: 'A'
-)
-
-threadInterruptAction = action(
- name: 'Allow Interruption',
- closure: controller.&threadInterruption,
- mnemonic: 'O'
-)
-
-interruptAction = action(
- name: 'Interrupt',
- closure: controller.&doInterrupt,
- mnemonic: 'T',
- smallIcon: imageIcon(resource:'icons/cross.png', class:this),
- shortDescription: 'Interrupt Running Script',
- enabled: false // controller will enable as needed
-)
-
-compileAction = action(
- name: 'Compile',
- closure: controller.&compileScript,
- mnemonic: 'L',
- accelerator: shortcut('L'),
- shortDescription: 'Compile Groovy Script'
-)
-
-commentAction = action(
- name: 'Comment',
- closure: controller.&comment,
- mnemonic: 'C',
- // Ctrl or Command + /
- accelerator: KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
- shortDescription: 'Comment/Uncomment Selected Script'
-)
-
-selectBlockAction = action(
- name: 'Select Block',
- closure: controller.&selectBlock,
- mnemonic: 'B',
- accelerator: shortcut('B'),
- shortDescription: 'Selects current Word, Line or Block in Script'
-)
-
-indyAction = action(
- name: 'Enable Indy Compilation',
- closure: controller.&indy,
- mnemonic: 'I',
- shortDescription: 'Enable InvokeDynamic (Indy) compilation for scripts'
-)
-
-preferencesAction = action(
- name: 'Preferences',
- closure: controller.&preferences,
- mnemonic: 'S',
- shortDescription: 'Preference Settings'
-)
\ No newline at end of file
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleApplet.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleApplet.groovy
deleted file mode 100644
index 5147d2e..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleApplet.groovy
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.transform.CompileStatic
-
-import javax.swing.JApplet
-
-/**
- * ConsoleApplet
- */
-@CompileStatic
-@Deprecated
-class ConsoleApplet extends JApplet {
-
- Console console
-
- void start() {
- console = new Console()
- console.run this
- }
-
- void stop() {
- console.exit()
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleIvyPlugin.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleIvyPlugin.groovy
deleted file mode 100644
index 787da0e..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleIvyPlugin.groovy
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.grape.Grape
-import groovy.grape.GrapeIvy
-import org.apache.ivy.core.event.IvyListener
-import org.apache.ivy.core.event.download.PrepareDownloadEvent
-import org.apache.ivy.core.event.resolve.StartResolveEvent
-
-/**
- * Groovy Swing console.
- *
- * Adds Groovy Grape feedback (via an Ivy listener).
- */
-@Deprecated
-class ConsoleIvyPlugin {
- Console savedConsole
- Set<String> resolvedDependencies = []
- Set<String> downloadedArtifacts = []
-
- def addListener(Console console) {
- savedConsole = console
-
- ((GrapeIvy) Grape.instance).ivyInstance.eventManager.addIvyListener([progress: { ivyEvent ->
- switch (ivyEvent) {
- case StartResolveEvent:
- ivyEvent.moduleDescriptor.dependencies.each { it ->
- def name = it.toString()
- if (!resolvedDependencies.contains(name)) {
- resolvedDependencies << name
- savedConsole.showMessage "Resolving ${name} ..."
- }
- }
- break
- case PrepareDownloadEvent:
- ivyEvent.artifacts.each { it ->
- def name = it.toString()
- if (!downloadedArtifacts.contains(name)) {
- downloadedArtifacts << name
- savedConsole.showMessage "Downloading artifact ${name} ..."
- }
- }
- break
- }
- }] as IvyListener)
-
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsolePreferences.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsolePreferences.groovy
deleted file mode 100644
index 577f20a..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsolePreferences.groovy
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.beans.Bindable
-import groovy.swing.SwingBuilder
-import org.codehaus.groovy.tools.shell.util.MessageSource
-
-import javax.swing.*
-import java.awt.*
-
-@Deprecated
-class ConsolePreferences {
-
- // Default maximum number of characters to show on console at any time
- static int DEFAULT_MAX_OUTPUT_CHARS = 20000
-
- @Bindable int maxOutputChars
-
- private final console
- private final MessageSource T
-
- private JDialog dialog
- File outputFile
-
- ConsolePreferences(console) {
- this.console = console
- T = new MessageSource(Console)
-
- maxOutputChars = console.loadMaxOutputChars()
- console.maxOutputChars = maxOutputChars
- }
-
- void show() {
- console.swing.edt {
- if (!dialog) {
- buildDialog()
- }
- dialog.setLocationRelativeTo(console.frame)
- dialog.pack()
- dialog.getRootPane().setDefaultButton(console.swing.closePrefsButton)
- console.swing.doLater console.swing.closePrefsButton.&requestFocusInWindow
- dialog.setVisible(true)
- }
- }
-
- private void buildDialog() {
- dialog = console.swing.dialog(
- title: T['prefs.dialog.title'], owner: console.frame, modal: true
- ) {
- vbox {
- vbox(border: titledBorder(T['prefs.output.settings.title'])) {
- hbox {
- label "${T['prefs.max.characters.output']}:"
-
- formattedTextField value: maxOutputChars, id: 'txtMaxOutputChars',
- text:
- bind(target: this, targetProperty: 'maxOutputChars',
- validator: this.&isInteger, converter: Integer.&parseInt),
- columns: 6
- }
-
- hbox {
- checkBox T['prefs.output.file'], id: 'outputFileCheckBox', selected: false
- hglue()
- label T['prefs.output.file.name'], id: 'outputFileName',
- enabled: bind(source: outputFileCheckBox, sourceProperty: 'selected')
- button T['prefs.output.file.select'], id: 'outputFileNameButton',
- enabled: bind(source: outputFileCheckBox, sourceProperty: 'selected'),
- actionPerformed: this.&onChooseFile
- }
- }
-
- vglue()
-
- hbox {
- button T['prefs.reset.defaults'], id: 'resetPrefsButton', actionPerformed: this.&onReset
- hglue()
- button T['prefs.close'], id: 'closePrefsButton', actionPerformed: this.&onClose
- }
-
- }
- }
-
- console.swing.txtMaxOutputChars.maximumSize = new Dimension(Integer.MAX_VALUE, (int) console.swing.txtMaxOutputChars.preferredSize.height)
-
- def outputLogFileName = console.prefs.get('outputLogFileName', null)
- if (outputLogFileName != null) {
- console.swing.outputFileCheckBox.selected = true
- console.swing.outputFileName.text = outputLogFileName
- }
- }
-
- private boolean isInteger(value) {
- try {
- Integer.parseInt(value)
- return true
- } catch (NumberFormatException ignore) {
- return false
- }
- }
-
- private void onReset(EventObject event) {
- console.swing.txtMaxOutputChars.text = DEFAULT_MAX_OUTPUT_CHARS
- }
-
- private void onClose(EventObject event) {
- console.prefs.putInt('maxOutputChars', maxOutputChars)
- // For backwards compatibility 'maxOutputChars' remains defined in the Console class
- // and so we update the value to keep it in sync.
- if (maxOutputChars != console.maxOutputChars) {
- console.maxOutputChars = maxOutputChars
- }
-
- console.setOutputPreferences(console.swing.outputFileCheckBox.enabled, outputFile)
-
- dialog.dispose()
- }
-
- private void onChooseFile(EventObject event) {
- JFileChooser fileChooser = console.swing.fileChooser()
-
- if (console.prefs.get('outputLogFileName', null) != null) {
- fileChooser.setSelectedFile(new File(console.prefs.get('outputLogFileName', null)))
- }
-
- if (fileChooser.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) {
- outputFile = fileChooser.selectedFile
- }
- console.swing.outputFileName.text = outputFile.path
- }
-
- // Useful for testing gui
- static void main(args) {
- javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName())
- def c = new Expando().with {
- swing = new SwingBuilder()
- frame = swing.frame(title: 'foo', size:[800, 800])
- DEFAULT_MAX_OUTPUT_CHARS = 25000
- maxOutputChars = 25000
- loadMaxOutputChars = { 20000 }
- prefs = [putInt: { s, t -> }, getInt: { s, t -> t }]
- it
- }
- ConsolePreferences cp = new ConsolePreferences(c)
- cp.show()
- c.frame.dispose()
- println "maxOutputChars==${cp.maxOutputChars}"
- println "console.maxOutputChars==${c.maxOutputChars}"
- println 'done'
- }
-}
\ No newline at end of file
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleSupport.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleSupport.java
deleted file mode 100644
index 3086c46..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleSupport.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui;
-
-import groovy.lang.GroovyShell;
-
-import javax.swing.*;
-import javax.swing.text.Style;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.StyleContext;
-import javax.swing.text.StyledDocument;
-import java.awt.*;
-
-/**
- * Base class for console
- */
-@Deprecated
-public abstract class ConsoleSupport {
-
- Style promptStyle;
- Style commandStyle;
- Style outputStyle;
- private GroovyShell shell;
- int counter;
-
- protected void addStylesToDocument(JTextPane outputArea) {
- StyledDocument doc = outputArea.getStyledDocument();
-
- Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
-
- Style regular = doc.addStyle("regular", def);
- StyleConstants.setFontFamily(def, "Monospaced");
-
- promptStyle = doc.addStyle("prompt", regular);
- StyleConstants.setForeground(promptStyle, Color.BLUE);
-
- commandStyle = doc.addStyle("command", regular);
- StyleConstants.setForeground(commandStyle, Color.MAGENTA);
-
- outputStyle = doc.addStyle("output", regular);
- StyleConstants.setBold(outputStyle, true);
- }
-
- public Style getCommandStyle() {
- return commandStyle;
- }
-
- public Style getOutputStyle() {
- return outputStyle;
- }
-
- public Style getPromptStyle() {
- return promptStyle;
- }
-
- public GroovyShell getShell() {
- if (shell == null) {
- shell = new GroovyShell();
- }
- return shell;
- }
-
- protected Object evaluate(String text) {
- String name = "Script" + counter++;
- try {
- return getShell().evaluate(text, name);
- }
- catch (Exception e) {
- handleException(text, e);
- return null;
- }
- }
-
- protected abstract void handleException(String text, Exception e);
-}
\ No newline at end of file
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleTextEditor.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleTextEditor.java
deleted file mode 100644
index 6356aa1..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleTextEditor.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui;
-
-import groovy.ui.text.GroovyFilter;
-import groovy.ui.text.MatchingHighlighter;
-import groovy.ui.text.SmartDocumentFilter;
-import groovy.ui.text.StructuredSyntaxResources;
-import groovy.ui.text.TextEditor;
-import groovy.ui.text.TextUndoManager;
-import org.codehaus.groovy.runtime.StringGroovyMethods;
-
-import javax.swing.AbstractAction;
-import javax.swing.Action;
-import javax.swing.ActionMap;
-import javax.swing.InputMap;
-import javax.swing.JComponent;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.KeyStroke;
-import javax.swing.event.CaretListener;
-import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.Document;
-import javax.swing.text.DocumentFilter;
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.Font;
-import java.awt.Graphics;
-import java.awt.Point;
-import java.awt.datatransfer.DataFlavor;
-import java.awt.datatransfer.Transferable;
-import java.awt.event.ActionEvent;
-import java.awt.event.InputEvent;
-import java.awt.event.KeyEvent;
-import java.awt.print.PrinterJob;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.util.prefs.Preferences;
-
-/**
- * Component which provides a styled editor for the console.
- */
-@Deprecated
-public class ConsoleTextEditor extends JScrollPane {
- public String getDefaultFamily() {
- return defaultFamily;
- }
-
- public void setDefaultFamily(String defaultFamily) {
- this.defaultFamily = defaultFamily;
- }
-
- private class LineNumbersPanel extends JPanel {
-
- public LineNumbersPanel() {
- int initialSize = 3 * Preferences.userNodeForPackage(Console.class).getInt("fontSize", 12);
- setMinimumSize(new Dimension(initialSize, initialSize));
- setPreferredSize(new Dimension(initialSize, initialSize));
- }
-
- @Override
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- // starting position in document
- int start = textEditor.viewToModel(getViewport().getViewPosition());
- // end position in document
- int end = textEditor.viewToModel(new Point(10,
- getViewport().getViewPosition().y +
- (int) textEditor.getVisibleRect().getHeight())
- );
-
- // translate offsets to lines
- Document doc = textEditor.getDocument();
- int startline = doc.getDefaultRootElement().getElementIndex(start) + 1;
- int endline = doc.getDefaultRootElement().getElementIndex(end) + 1;
- Font f = textEditor.getFont();
- int fontHeight = g.getFontMetrics(f).getHeight();
- int fontDesc = g.getFontMetrics(f).getDescent();
- int startingY = -1;
-
- try {
- startingY = textEditor.modelToView(start).y + fontHeight - fontDesc;
- } catch (BadLocationException e1) {
- System.err.println(e1.getMessage());
- }
- g.setFont(f);
- for (int line = startline, y = startingY; line <= endline; y += fontHeight, line++) {
- String lineNumber = StringGroovyMethods.padLeft((CharSequence)Integer.toString(line), 4, " ");
- g.drawString(lineNumber, 0, y);
- }
- }
- }
-
- private String defaultFamily = "Monospaced";
-
- private static final PrinterJob PRINTER_JOB = PrinterJob.getPrinterJob();
-
- private LineNumbersPanel numbersPanel = new LineNumbersPanel();
-
- private boolean documentChangedSinceLastRepaint = false;
-
- private TextEditor textEditor = new TextEditor(true, true, true) {
-
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
-
- // only repaint the line numbers in the gutter when the document has changed
- // in case lines (hence line numbers) have been added or removed from the document
- if (documentChangedSinceLastRepaint) {
- numbersPanel.repaint();
- documentChangedSinceLastRepaint = false;
- }
- }
- };
-
- private UndoAction undoAction = new UndoAction();
- private RedoAction redoAction = new RedoAction();
- private PrintAction printAction = new PrintAction();
-
- private boolean editable = true;
-
- private TextUndoManager undoManager;
-
- /**
- * Creates a new instance of ConsoleTextEditor
- */
- public ConsoleTextEditor() {
- textEditor.setFont(new Font(defaultFamily, Font.PLAIN,
- Preferences.userNodeForPackage(Console.class).getInt("fontSize", 12)));
-
- setViewportView(new JPanel(new BorderLayout()) {{
- add(numbersPanel, BorderLayout.WEST);
- add(textEditor, BorderLayout.CENTER);
- }});
-
- textEditor.setDragEnabled(editable);
-
- getVerticalScrollBar().setUnitIncrement(10);
-
- initActions();
-
- DefaultStyledDocument doc = new DefaultStyledDocument();
- doc.setDocumentFilter(new GroovyFilter(doc));
- textEditor.setDocument(doc);
-
- // add a document listener, to hint whether the line number gutter has to be repainted
- // when the number of lines changes
- doc.addDocumentListener(new DocumentListener() {
- public void insertUpdate(DocumentEvent documentEvent) {
- documentChangedSinceLastRepaint = true;
- }
-
- public void removeUpdate(DocumentEvent documentEvent) {
- documentChangedSinceLastRepaint = true;
- }
-
- public void changedUpdate(DocumentEvent documentEvent) {
- documentChangedSinceLastRepaint = true;
- int width = 3 * Preferences.userNodeForPackage(Console.class).getInt("fontSize", 12);
- numbersPanel.setPreferredSize(new Dimension(width, width));
- }
- });
-
- // create and add the undo/redo manager
- this.undoManager = new TextUndoManager();
- doc.addUndoableEditListener(undoManager);
-
- // add the undo actions
- undoManager.addPropertyChangeListener(undoAction);
- undoManager.addPropertyChangeListener(redoAction);
-
- doc.addDocumentListener(undoAction);
- doc.addDocumentListener(redoAction);
-
- InputMap im = textEditor.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
- KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK, false);
- im.put(ks, StructuredSyntaxResources.UNDO);
- ActionMap am = textEditor.getActionMap();
- am.put(StructuredSyntaxResources.UNDO, undoAction);
-
- ks = KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK, false);
- im.put(ks, StructuredSyntaxResources.REDO);
- am.put(StructuredSyntaxResources.REDO, redoAction);
-
- ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK, false);
- im.put(ks, StructuredSyntaxResources.PRINT);
- am.put(StructuredSyntaxResources.PRINT, printAction);
- }
-
- public void setShowLineNumbers(boolean showLineNumbers) {
- if (showLineNumbers) {
- setViewportView(new JPanel(new BorderLayout()) {{
- add(numbersPanel, BorderLayout.WEST);
- add(textEditor, BorderLayout.CENTER);
- }});
- } else {
- setViewportView(textEditor);
- }
- }
-
- public void setEditable(boolean editable) {
- textEditor.setEditable(editable);
- }
-
- public boolean clipBoardAvailable() {
- Transferable t = StructuredSyntaxResources.SYSTEM_CLIPBOARD.getContents(this);
- return t.isDataFlavorSupported(DataFlavor.stringFlavor);
- }
-
- public TextEditor getTextEditor() {
- return textEditor;
- }
-
- protected void initActions() {
- ActionMap map = getActionMap();
-
- PrintAction printAction = new PrintAction();
- map.put(StructuredSyntaxResources.PRINT, printAction);
- }
-
- private class PrintAction extends AbstractAction {
-
- public PrintAction() {
- setEnabled(true);
- }
-
- public void actionPerformed(ActionEvent ae) {
- PRINTER_JOB.setPageable(textEditor);
-
- try {
- if (PRINTER_JOB.printDialog()) {
- PRINTER_JOB.print();
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- } // end ConsoleTextEditor.PrintAction
-
- private class RedoAction extends UpdateCaretListener implements PropertyChangeListener {
-
- public RedoAction() {
- setEnabled(false);
- }
-
- public void actionPerformed(ActionEvent ae) {
- undoManager.redo();
- setEnabled(undoManager.canRedo());
- undoAction.setEnabled(undoManager.canUndo());
- super.actionPerformed(ae);
- }
-
- public void propertyChange(PropertyChangeEvent pce) {
- setEnabled(undoManager.canRedo());
- }
- } // end ConsoleTextEditor.RedoAction
-
- private abstract class UpdateCaretListener extends AbstractAction implements DocumentListener {
-
- protected int lastUpdate;
-
- public void changedUpdate(DocumentEvent de) {
- }
-
- public void insertUpdate(DocumentEvent de) {
- lastUpdate = de.getOffset() + de.getLength();
- }
-
- public void removeUpdate(DocumentEvent de) {
- lastUpdate = de.getOffset();
- }
-
- public void actionPerformed(ActionEvent ae) {
- textEditor.setCaretPosition(lastUpdate);
- }
- }
-
- private class UndoAction extends UpdateCaretListener implements PropertyChangeListener {
-
- public UndoAction() {
- setEnabled(false);
- }
-
- public void actionPerformed(ActionEvent ae) {
- undoManager.undo();
- setEnabled(undoManager.canUndo());
- redoAction.setEnabled(undoManager.canRedo());
- super.actionPerformed(ae);
- }
-
- public void propertyChange(PropertyChangeEvent pce) {
- setEnabled(undoManager.canUndo());
- }
- }
-
- public Action getUndoAction() {
- return undoAction;
- }
-
- public Action getRedoAction() {
- return redoAction;
- }
-
- public Action getPrintAction() {
- return printAction;
- }
-
- public void enableHighLighter(Class clazz) {
- DefaultStyledDocument doc = (DefaultStyledDocument) textEditor.getDocument();
-
- try {
- DocumentFilter documentFilter = (DocumentFilter) clazz.getConstructor(doc.getClass()).newInstance(doc);
- doc.setDocumentFilter(documentFilter);
-
- disableMatchingHighlighter();
- if (documentFilter instanceof SmartDocumentFilter) {
- final SmartDocumentFilter smartDocumentFilter = (SmartDocumentFilter) documentFilter;
- enableMatchingHighlighter(smartDocumentFilter);
- }
- } catch (ReflectiveOperationException e) {
- e.printStackTrace();
- }
- }
-
- private void enableMatchingHighlighter(SmartDocumentFilter smartDocumentFilter) {
- textEditor.addCaretListener(new MatchingHighlighter(smartDocumentFilter, textEditor));
- }
-
- private void disableMatchingHighlighter() {
- for (CaretListener cl : textEditor.getCaretListeners()) {
- if (cl instanceof MatchingHighlighter) {
- textEditor.removeCaretListener(cl);
- }
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleView.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleView.groovy
deleted file mode 100644
index b70cf00..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/ConsoleView.groovy
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.ui.view.Defaults
-import groovy.ui.view.GTKDefaults
-import groovy.ui.view.MacOSXDefaults
-import groovy.ui.view.WindowsDefaults
-
-import javax.swing.*
-import javax.swing.event.DocumentListener
-import javax.swing.text.DefaultEditorKit
-import java.awt.datatransfer.DataFlavor
-import java.awt.dnd.DnDConstants
-import java.awt.dnd.DropTarget
-import java.awt.dnd.DropTargetDragEvent
-import java.awt.dnd.DropTargetDropEvent
-import java.awt.dnd.DropTargetEvent
-import java.awt.dnd.DropTargetListener
-
-switch (UIManager.getSystemLookAndFeelClassName()) {
- case 'com.sun.java.swing.plaf.windows.WindowsLookAndFeel':
- case 'com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel':
- build(WindowsDefaults)
- break
-
- case 'apple.laf.AquaLookAndFeel':
- case 'com.apple.laf.AquaLookAndFeel':
- build(MacOSXDefaults)
- break
-
- case 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel':
- build(GTKDefaults)
- break
-
- default:
- build(Defaults)
- break
-}
-
-binding.rootContainerDelegate.delegate = this
-
-consoleFrame = binding['rootContainerDelegate']()
-container(consoleFrame) {
-
- binding.menuBarDelegate.delegate = delegate
- binding['menuBarDelegate'](menuBarClass)
-
- build(contentPaneClass)
-
- build(toolBarClass)
-
- build(statusBarClass)
-}
-
-inputEditor.textEditor.componentPopupMenu = popupMenu {
- menuItem(cutAction)
- menuItem(copyAction)
- menuItem(pasteAction)
- menuItem(selectAllAction)
- separator()
- menuItem(undoAction)
- menuItem(redoAction)
- separator()
- menuItem(runAction)
- menuItem(runSelectionAction)
-}
-
-outputArea.componentPopupMenu = popupMenu {
- menuItem(copyAction)
- menuItem(selectAllAction)
- menuItem(clearOutputAction)
-}
-
-controller.promptStyle = promptStyle
-controller.commandStyle = commandStyle
-controller.outputStyle = outputStyle
-controller.stacktraceStyle = stacktraceStyle
-controller.hyperlinkStyle = hyperlinkStyle
-controller.resultStyle = resultStyle
-
-// add the window close handler
-if (consoleFrame instanceof java.awt.Window) {
- consoleFrame.windowClosing = controller.&exit
-}
-
-// link in references to the controller
-controller.inputEditor = inputEditor
-controller.inputArea = inputEditor.textEditor
-controller.outputArea = outputArea
-controller.outputWindow = outputWindow
-controller.statusLabel = status
-controller.frame = consoleFrame
-controller.rowNumAndColNum = rowNumAndColNum
-controller.toolbar = toolbar
-
-// link actions
-controller.saveAction = saveAction
-controller.prevHistoryAction = historyPrevAction
-controller.nextHistoryAction = historyNextAction
-controller.fullStackTracesAction = fullStackTracesAction
-controller.showToolbarAction = showToolbarAction
-controller.detachedOutputAction = detachedOutputAction
-controller.autoClearOutputAction = autoClearOutputAction
-controller.saveOnRunAction = saveOnRunAction
-controller.threadInterruptAction = threadInterruptAction
-controller.showOutputWindowAction = showOutputWindowAction
-controller.hideOutputWindowAction1 = hideOutputWindowAction1
-controller.hideOutputWindowAction2 = hideOutputWindowAction2
-controller.hideOutputWindowAction3 = hideOutputWindowAction3
-controller.hideOutputWindowAction4 = hideOutputWindowAction4
-controller.interruptAction = interruptAction
-controller.origDividerSize = origDividerSize
-controller.splitPane = splitPane
-controller.blank = blank
-controller.scrollArea = scrollArea
-controller.selectWordAction = inputArea.getActions().find {
- DefaultEditorKit.selectWordAction.equals(it.getValue(Action.NAME))
-}
-controller.selectPreviousWordAction = inputArea.getActions().find {
- DefaultEditorKit.selectionPreviousWordAction.equals(it.getValue(Action.NAME))
-}
-
-// some more UI linkage
-controller.outputArea.addComponentListener(controller)
-controller.inputArea.addComponentListener(controller)
-controller.outputArea.addHyperlinkListener(controller)
-controller.outputArea.addHyperlinkListener(controller)
-controller.outputArea.addFocusListener(controller)
-controller.inputArea.addCaretListener(controller)
-controller.inputArea.document.addDocumentListener({ controller.setDirty(true) } as DocumentListener)
-controller.rootElement = inputArea.document.defaultRootElement
-
-
-def dtListener = [
- dragEnter:{DropTargetDragEvent evt ->
- if (evt.dropTargetContext.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
- evt.acceptDrag(DnDConstants.ACTION_COPY)
- } else {
- evt.rejectDrag()
- }
- },
- dragOver:{DropTargetDragEvent evt ->
- //dragEnter(evt)
- },
- dropActionChanged:{DropTargetDragEvent evt ->
- //dragEnter(evt)
- },
- dragExit:{DropTargetEvent evt ->
- },
- drop:{DropTargetDropEvent evt ->
- evt.acceptDrop DnDConstants.ACTION_COPY
- //println "Dropping! ${evt.transferable.getTransferData(DataFlavor.javaFileListFlavor)}"
- if (controller.askToSaveFile()) {
- controller.loadScriptFile(evt.transferable.getTransferData(DataFlavor.javaFileListFlavor)[0])
- }
- },
-] as DropTargetListener
-
-[consoleFrame, inputArea, outputArea].each {
- new DropTarget(it, DnDConstants.ACTION_COPY, dtListener)
-}
-
-// don't send any return value from the view, all items should be referenced via the bindings
-return null
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/HistoryRecord.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/HistoryRecord.groovy
deleted file mode 100644
index 8035ddc..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/HistoryRecord.groovy
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.transform.CompileStatic
-
-@CompileStatic
-@Deprecated
-class HistoryRecord {
- String allText
- int selectionStart
- int selectionEnd
- String scriptName
- Object result
- Throwable exception
-
- public String getTextToRun(boolean useSelection) {
- if (useSelection && selectionStart != selectionEnd) {
- // Retrieve all the imports included in the script before the current selection
- def before = allText[0 ..< selectionStart].split("\n")
- def importLines = before.findAll { it.trim().startsWith("import") }
- def imports = importLines.join("\n")
- def code = imports + "\n" + allText[selectionStart ..< selectionEnd]
- return code
- }
- return allText
- }
-
- public Object getValue() {
- return exception ? exception : result
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/OutputTransforms.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/OutputTransforms.groovy
deleted file mode 100644
index 19609c7..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/OutputTransforms.groovy
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui
-
-import groovy.transform.CompileStatic
-import org.codehaus.groovy.runtime.InvokerHelper
-
-import javax.swing.Icon
-import javax.swing.ImageIcon
-import javax.swing.JComponent
-import java.awt.Component
-import java.awt.Dimension
-import java.awt.Graphics2D
-import java.awt.GraphicsConfiguration
-import java.awt.GraphicsDevice
-import java.awt.GraphicsEnvironment
-import java.awt.Image
-import java.awt.Transparency
-import java.awt.Window
-import java.awt.image.BufferedImage
-
-@CompileStatic
-@Deprecated
-class OutputTransforms {
-
- @Lazy static List<Closure> localTransforms = loadOutputTransforms()
-
- static List<Closure> loadOutputTransforms() {
- def transforms = []
-
- //
- // load user local transforms
- //
- def userHome = new File(System.getProperty('user.home'))
- def groovyDir = new File(userHome, '.groovy')
- def userTransforms = new File(groovyDir, "OutputTransforms.groovy")
- if (userTransforms.exists()) {
- GroovyShell shell = new GroovyShell()
- shell.setVariable('transforms', transforms)
- shell.evaluate(userTransforms)
- }
-
- //
- // built-in transforms
- //
-
- // any non-window GUI components, such as a heavyweight button or a
- // Swing component, gets passed if it has no parent set (the parent
- // clause is to keep buttons from disappearing from user shown forms)
- transforms << { it -> if ((it instanceof Component) && !(it instanceof Window) && (it.parent == null)) it }
-
- // remaining components get printed to an image
- transforms << { it ->
- if (it instanceof JComponent) {
- Dimension d = it.size
- if (d.width == 0) {
- d = it.preferredSize
- it.size = d
- }
-
- GraphicsEnvironment ge = GraphicsEnvironment.localGraphicsEnvironment
- GraphicsDevice gs = ge.defaultScreenDevice
- GraphicsConfiguration gc = gs.defaultConfiguration
-
- BufferedImage image = gc.createCompatibleImage(d.width as int, d.height as int, Transparency.TRANSLUCENT)
- Graphics2D g2 = image.createGraphics()
- it.print(g2)
- g2.dispose()
- new ImageIcon(image)
- }
- }
-
- // icons get passed, they can be rendered multiple times so no parent check
- transforms << { it -> if (it instanceof Icon) it }
-
- // Images become ImageIcons
- transforms << { it -> if (it instanceof Image) new ImageIcon(it)}
-
- // final case, non-nulls just get inspected as strings
- transforms << { it -> if (it != null) "${InvokerHelper.inspect(it)}" }
-
- return (List<Closure>) transforms
- }
-
- static transformResult(base, List<Closure> transforms = localTransforms) {
- for (Closure c : transforms) {
- def result = c(base as Object)
- if (result != null) {
- return result
- }
- }
- return base
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/SystemOutputInterceptor.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/SystemOutputInterceptor.java
deleted file mode 100644
index 1ff8efb..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/SystemOutputInterceptor.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui;
-
-import groovy.lang.Closure;
-
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-
-/**
- * Intercepts System.out/System.err. Implementation helper for Console.groovy.
- */
-@Deprecated
-public class SystemOutputInterceptor extends FilterOutputStream {
-
- private Closure callback;
- private boolean output;
-
- private static final ThreadLocal<Integer> consoleId = new InheritableThreadLocal<Integer>() {
- @Override
- protected Integer initialValue() {
- return 0;
- }
- };
-
- /**
- * Constructor
- *
- * @param callback accepts the id of the target Console instance and a
- * string to be sent to std out and returns a Boolean.
- * If the return value is true, output will be sent to
- * System.out, otherwise it will not.
- */
- public SystemOutputInterceptor(final Closure callback) {
- this(callback, true);
- }
-
- /**
- * Constructor
- *
- * @param callback accepts the id of the target Console instance and a
- * string to be sent to std out and returns a Boolean.
- * If the return value is true, output will be sent to
- * System.out/System.err, otherwise it will not.
- * @param output flag that tells whether System.out needs capturing ot System.err
- */
- public SystemOutputInterceptor(final Closure callback, boolean output) {
- super(output ? System.out : System.err);
-
- assert callback != null;
-
- this.callback = callback;
- this.output = output;
- }
-
- /**
- * Starts intercepting System.out/System.err
- */
- public void start() {
- if (output) {
- System.setOut(new PrintStream(this));
- } else {
- System.setErr(new PrintStream(this));
- }
- }
-
- /**
- * Stops intercepting System.out/System.err, sending output to wherever it was
- * going when this interceptor was created.
- */
- public void stop() {
- if (output) {
- System.setOut((PrintStream) out);
- } else {
- System.setErr((PrintStream) out);
- }
- }
-
- /**
- * Intercepts output - more common case of byte[]
- */
- public void write(byte[] b, int off, int len) throws IOException {
- Boolean result = (Boolean) callback.call(consoleId.get(), new String(b, off, len));
- if (result) {
- out.write(b, off, len);
- }
- }
-
- /**
- * Intercepts output - single characters
- */
- public void write(int b) throws IOException {
- Boolean result = (Boolean) callback.call(consoleId.get(), String.valueOf((char) b));
- if (result) {
- out.write(b);
- }
- }
-
- /**
- * Threads executing a script should call this method at the start of execution
- * in order to set the id of the console that is hosting the thread of execution. This
- * should be called prior to any output that is generated. The consoleId will
- * be passed to the callback.
- *
- * @param consoleId id of the Console instance executing the script
- */
- public void setConsoleId(int consoleId) {
- this.consoleId.set(consoleId);
- }
-
- /**
- * Threads executing a script should call this method after
- * execution completes in order to unregister the consoleId.
- */
- public void removeConsoleId() {
- this.consoleId.remove();
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/package.html b/subprojects/groovy-console/src/main/groovy/groovy/ui/package.html
deleted file mode 100644
index ce90d36..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/package.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<html>
- <head>
- <title>package groovy.ui.*</title>
- </head>
- <body>
- <p>An interactive command line terminal along with a Swing console for evaluating Groovy scripts.</p>
- </body>
-</html>
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/AutoIndentAction.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/AutoIndentAction.groovy
deleted file mode 100644
index d2be1ea..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/AutoIndentAction.groovy
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text
-
-import groovy.transform.CompileStatic
-
-import javax.swing.*
-import javax.swing.text.AttributeSet
-import javax.swing.text.SimpleAttributeSet
-import java.awt.event.ActionEvent
-
-@CompileStatic
-@Deprecated
-class AutoIndentAction extends AbstractAction {
- AttributeSet simpleAttributeSet = new SimpleAttributeSet()
-
- void actionPerformed(ActionEvent evt) {
- JTextPane inputArea = (JTextPane) evt.source
- def rootElement = inputArea.document.defaultRootElement
- def cursorPos = inputArea.getCaretPosition()
- int rowNum = rootElement.getElementIndex(cursorPos)
- def rowElement = rootElement.getElement(rowNum)
- int startOffset = rowElement.getStartOffset()
- int endOffset = rowElement.getEndOffset()
- String rowContent = inputArea.document.getText(startOffset, endOffset - startOffset);
- String contentBeforeCursor = inputArea.document.getText(startOffset, cursorPos - startOffset);
- String whitespaceStr = ''
- def matcher = (rowContent =~ /(?m)^(\s*).*\n$/)
- matcher.each { all, ws ->
- whitespaceStr = ws
- }
-
- if (contentBeforeCursor ==~ /(\s)*/) {
- whitespaceStr = contentBeforeCursor
- }
-
- inputArea.document.insertString(cursorPos, '\n' + whitespaceStr, simpleAttributeSet)
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/FindReplaceUtility.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/FindReplaceUtility.java
deleted file mode 100644
index 574934d..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/FindReplaceUtility.java
+++ /dev/null
@@ -1,544 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import javax.swing.*;
-import javax.swing.event.EventListenerList;
-import javax.swing.text.AttributeSet;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.Document;
-import javax.swing.text.JTextComponent;
-import javax.swing.text.Segment;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.FocusAdapter;
-import java.awt.event.FocusEvent;
-import java.awt.event.KeyAdapter;
-import java.awt.event.KeyEvent;
-import java.awt.event.TextEvent;
-import java.awt.event.TextListener;
-import java.util.EventListener;
-
-@Deprecated
-public final class FindReplaceUtility {
-
- public static final String FIND_ACTION_COMMAND = "Find";
-
- public static final String REPLACE_ACTION_COMMAND = "Replace";
-
- public static final String REPLACE_ALL_ACTION_COMMAND = "Replace All";
-
- public static final String CLOSE_ACTION_COMMAND = "Close";
-
- public static final Action FIND_ACTION = new FindAction();
-
- private static final JDialog FIND_REPLACE_DIALOG = new JDialog();
-
- private static final JPanel TEXT_FIELD_PANEL = new JPanel(new GridLayout(2, 1));
-
- private static final JPanel ENTRY_PANEL = new JPanel();
-
- private static final JPanel FIND_PANEL = new JPanel();
- private static final JLabel FIND_LABEL = new JLabel("Find What: ");
- private static final JComboBox FIND_FIELD = new JComboBox();
-
- private static final JPanel REPLACE_PANEL = new JPanel();
- private static final JLabel REPLACE_LABEL = new JLabel("Replace With:");
- private static final JComboBox REPLACE_FIELD = new JComboBox();
-
- private static final JPanel BUTTON_PANEL = new JPanel();
- private static final JButton FIND_BUTTON = new JButton();
- private static final JButton REPLACE_BUTTON = new JButton();
- private static final JButton REPLACE_ALL_BUTTON = new JButton();
- private static final JButton CLOSE_BUTTON = new JButton();
-
- private static final Action CLOSE_ACTION = new CloseAction();
- private static final Action REPLACE_ACTION = new ReplaceAction();
-
- private static final JPanel CHECK_BOX_PANEL = new JPanel(new GridLayout(3, 1));
- private static final JCheckBox MATCH_CASE_CHECKBOX = new JCheckBox("Match Case ");
- private static final JCheckBox IS_BACKWARDS_CHECKBOX = new JCheckBox("Search Backwards");
- private static final JCheckBox WRAP_SEARCH_CHECKBOX = new JCheckBox("Wrap Search ");
-
- private static JTextComponent textComponent;
- private static AttributeSet attributeSet;
-
- private static int findReplaceCount;
- private static String lastAction;
-
- private static final EventListenerList EVENT_LISTENER_LIST = new EventListenerList();
-
- // the document segment
- private static final Segment SEGMENT = new Segment();
-
- private static final FocusAdapter TEXT_FOCUS_LISTENER = new FocusAdapter() {
- public void focusGained(FocusEvent fe) {
- textComponent = (JTextComponent) fe.getSource();
- attributeSet =
- textComponent.getDocument().getDefaultRootElement().getAttributes();
- }
- };
-
- static {
- FIND_REPLACE_DIALOG.setResizable(false);
- FIND_REPLACE_DIALOG.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
- // is next line needed at all?
- /* KeyStroke keyStroke = */
- KeyStroke.getKeyStroke("enter");
- KeyAdapter keyAdapter = new KeyAdapter() {
- public void keyTyped(KeyEvent ke) {
- if (ke.getKeyChar() == KeyEvent.VK_ENTER) {
- FIND_BUTTON.doClick();
- }
- }
- };
- FIND_PANEL.setLayout(new FlowLayout(FlowLayout.RIGHT));
- FIND_PANEL.add(FIND_LABEL);
- FIND_PANEL.add(FIND_FIELD);
- FIND_FIELD.addItem("");
- FIND_FIELD.setEditable(true);
- FIND_FIELD.getEditor().getEditorComponent().addKeyListener(keyAdapter);
- Dimension d = FIND_FIELD.getPreferredSize();
- d.width = 225;
- FIND_FIELD.setPreferredSize(d);
-
- REPLACE_PANEL.add(REPLACE_LABEL);
- REPLACE_PANEL.add(REPLACE_FIELD);
- REPLACE_FIELD.setEditable(true);
- REPLACE_FIELD.getEditor().getEditorComponent().addKeyListener(keyAdapter);
- REPLACE_FIELD.setPreferredSize(d);
-
- TEXT_FIELD_PANEL.setLayout(new BoxLayout(TEXT_FIELD_PANEL, BoxLayout.Y_AXIS));
- TEXT_FIELD_PANEL.add(FIND_PANEL);
- TEXT_FIELD_PANEL.add(REPLACE_PANEL);
-
- ENTRY_PANEL.add(TEXT_FIELD_PANEL);
- FIND_REPLACE_DIALOG.getContentPane().add(ENTRY_PANEL, BorderLayout.WEST);
-
- CHECK_BOX_PANEL.add(MATCH_CASE_CHECKBOX);
-
- CHECK_BOX_PANEL.add(IS_BACKWARDS_CHECKBOX);
-
- CHECK_BOX_PANEL.add(WRAP_SEARCH_CHECKBOX);
-
- ENTRY_PANEL.add(CHECK_BOX_PANEL);
- ENTRY_PANEL.setLayout(new BoxLayout(ENTRY_PANEL, BoxLayout.Y_AXIS));
-
- REPLACE_ALL_BUTTON.setAction(new ReplaceAllAction());
- REPLACE_ALL_BUTTON.setHorizontalAlignment(JButton.CENTER);
- d = REPLACE_ALL_BUTTON.getPreferredSize();
-
- BUTTON_PANEL.setLayout(new BoxLayout(BUTTON_PANEL, BoxLayout.Y_AXIS));
- FIND_BUTTON.setAction(FIND_ACTION);
- FIND_BUTTON.setPreferredSize(d);
- FIND_BUTTON.setHorizontalAlignment(JButton.CENTER);
- JPanel panel = new JPanel();
- panel.add(FIND_BUTTON);
- BUTTON_PANEL.add(panel);
- FIND_REPLACE_DIALOG.getRootPane().setDefaultButton(FIND_BUTTON);
-
- REPLACE_BUTTON.setAction(REPLACE_ACTION);
- REPLACE_BUTTON.setPreferredSize(d);
- REPLACE_BUTTON.setHorizontalAlignment(JButton.CENTER);
- panel = new JPanel();
- panel.add(REPLACE_BUTTON);
- BUTTON_PANEL.add(panel);
-
- panel = new JPanel();
- panel.add(REPLACE_ALL_BUTTON);
- BUTTON_PANEL.add(panel);
-
- CLOSE_BUTTON.setAction(CLOSE_ACTION);
- CLOSE_BUTTON.setPreferredSize(d);
- CLOSE_BUTTON.setHorizontalAlignment(JButton.CENTER);
- panel = new JPanel();
- panel.add(CLOSE_BUTTON);
- BUTTON_PANEL.add(panel);
- FIND_REPLACE_DIALOG.getContentPane().add(BUTTON_PANEL);
-
- KeyStroke stroke = (KeyStroke) CLOSE_ACTION.getValue(Action.ACCELERATOR_KEY);
- JRootPane rPane = FIND_REPLACE_DIALOG.getRootPane();
- rPane.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW).put(stroke, "exit");
- rPane.getActionMap().put("exit", CLOSE_ACTION);
- }
-
- // Singleton
-
- private FindReplaceUtility() {
- }
-
- public static void addTextListener(TextListener tl) {
- EVENT_LISTENER_LIST.add(TextListener.class, tl);
- }
-
- private static void fireTextEvent() {
- EventListener[] lstrs =
- EVENT_LISTENER_LIST.getListeners(TextListener.class);
- if (lstrs != null && lstrs.length > 0) {
- TextEvent te =
- new TextEvent(FIND_REPLACE_DIALOG, TextEvent.TEXT_VALUE_CHANGED);
- for (int i = 0; i < lstrs.length; i++) {
- ((TextListener) lstrs[i]).textValueChanged(te);
- }
- }
- }
-
- /**
- * @return the last action
- */
- public static String getLastAction() {
- return lastAction;
- }
-
- /**
- * @return the replacement count
- */
- public static int getReplacementCount() {
- return findReplaceCount;
- }
-
- /**
- * @return the search text
- */
- public static String getSearchText() {
- return (String) FIND_FIELD.getSelectedItem();
- }
-
- /**
- * @param textComponent the text component to listen to
- */
- public static void registerTextComponent(JTextComponent textComponent) {
- textComponent.addFocusListener(TEXT_FOCUS_LISTENER);
- }
-
- public static void removeTextListener(TextListener tl) {
- EVENT_LISTENER_LIST.remove(TextListener.class, tl);
- }
-
- /**
- * Find and select the next searchable matching text.
- *
- * @param reverse look forwards or backwards
- * @param pos the starting index to start finding from
- * @return the location of the next selected, or -1 if not found
- */
- private static int findNext(boolean reverse, int pos) {
- boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();
- backwards = backwards ? !reverse : reverse;
-
- String pattern = (String) FIND_FIELD.getSelectedItem();
- if (pattern != null && pattern.length() > 0) {
- try {
- Document doc = textComponent.getDocument();
- doc.getText(0, doc.getLength(), SEGMENT);
- }
- catch (Exception e) {
- // should NEVER reach here
- e.printStackTrace();
- }
-
- pos += textComponent.getSelectedText() == null ?
- (backwards ? -1 : 1) : 0;
-
- char first = backwards ?
- pattern.charAt(pattern.length() - 1) : pattern.charAt(0);
- char oppFirst = Character.isUpperCase(first) ?
- Character.toLowerCase(first) : Character.toUpperCase(first);
- int start = pos;
- boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();
- int end = backwards ? 0 : SEGMENT.getEndIndex();
- pos += backwards ? -1 : 1;
-
- int length = textComponent.getDocument().getLength();
- if (pos > length) {
- pos = wrapped ? 0 : length;
- }
-
- boolean found = false;
- while (!found && (backwards ? pos > end : pos < end)) {
- found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;
- found = found ? found : SEGMENT.array[pos] == first;
-
- if (found) {
- pos += backwards ? -(pattern.length() - 1) : 0;
- for (int i = 0; found && i < pattern.length(); i++) {
- char c = pattern.charAt(i);
- found = SEGMENT.array[pos + i] == c;
- if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {
- c = Character.isUpperCase(c) ?
- Character.toLowerCase(c) :
- Character.toUpperCase(c);
- found = SEGMENT.array[pos + i] == c;
- }
- }
- }
-
- if (!found) {
- pos += backwards ? -1 : 1;
-
- if (pos == end && wrapped) {
- pos = backwards ? SEGMENT.getEndIndex() : 0;
- end = start;
- wrapped = false;
- }
- }
- }
- pos = found ? pos : -1;
- }
-
- return pos;
- }
-
- private static void setListStrings() {
- Object findObject = FIND_FIELD.getSelectedItem();
- Object replaceObject = REPLACE_FIELD.isShowing() ?
- (String) REPLACE_FIELD.getSelectedItem() : "";
-
- if (findObject != null && replaceObject != null) {
- boolean found = false;
- for (int i = 0; !found && i < FIND_FIELD.getItemCount(); i++) {
- found = FIND_FIELD.getItemAt(i).equals(findObject);
- }
- if (!found) {
- FIND_FIELD.insertItemAt(findObject, 0);
- if (FIND_FIELD.getItemCount() > 7) {
- FIND_FIELD.removeItemAt(7);
- }
- }
-
- if (REPLACE_FIELD.isShowing()) {
- found = false;
- for (int i = 0; !found && i < REPLACE_FIELD.getItemCount(); i++) {
- found = REPLACE_FIELD.getItemAt(i).equals(findObject);
- }
- if (!found) {
- REPLACE_FIELD.insertItemAt(replaceObject, 0);
- if (REPLACE_FIELD.getItemCount() > 7) {
- REPLACE_FIELD.removeItemAt(7);
- }
- }
- }
- }
-
- }
-
- public static void showDialog() {
- showDialog(false);
- }
-
- /**
- * @param isReplace show a replace dialog rather than a find dialog if true
- */
- public static void showDialog(boolean isReplace) {
- String title = isReplace ? REPLACE_ACTION_COMMAND : FIND_ACTION_COMMAND;
- FIND_REPLACE_DIALOG.setTitle(title);
-
- String text = textComponent.getSelectedText();
- if (text == null) {
- text = "";
- }
- FIND_FIELD.getEditor().setItem(text);
- FIND_FIELD.getEditor().selectAll();
-
- REPLACE_PANEL.setVisible(isReplace);
- REPLACE_ALL_BUTTON.setVisible(isReplace);
- CLOSE_BUTTON.setVisible(isReplace);
-
- Action action = isReplace ?
- REPLACE_ACTION : CLOSE_ACTION;
- REPLACE_BUTTON.setAction(action);
-
- REPLACE_BUTTON.setPreferredSize(null);
- Dimension d = isReplace ?
- REPLACE_ALL_BUTTON.getPreferredSize() :
- REPLACE_BUTTON.getPreferredSize();
- FIND_BUTTON.setPreferredSize(d);
- REPLACE_BUTTON.setPreferredSize(d);
- CLOSE_BUTTON.setPreferredSize(d);
-
- FIND_REPLACE_DIALOG.invalidate();
- FIND_REPLACE_DIALOG.repaint();
- FIND_REPLACE_DIALOG.pack();
-
- java.awt.Frame[] frames = java.awt.Frame.getFrames();
- for (int i = 0; i < frames.length; i++) {
- if (frames[i].isFocused()) {
- FIND_REPLACE_DIALOG.setLocationRelativeTo(frames[i]);
- }
- }
-
- FIND_REPLACE_DIALOG.setVisible(true);
- FIND_FIELD.requestFocusInWindow();
- }
-
- /**
- * @param textComponent the text component to stop listening to
- */
- public static void unregisterTextComponent(JTextComponent textComponent) {
- textComponent.removeFocusListener(TEXT_FOCUS_LISTENER);
- }
-
- private static class FindAction extends AbstractAction {
-
- public FindAction() {
- putValue(Action.NAME, FIND_ACTION_COMMAND);
- putValue(Action.ACTION_COMMAND_KEY, FIND_ACTION_COMMAND);
- putValue(Action.MNEMONIC_KEY, KeyEvent.VK_F);
- }
-
- public void actionPerformed(ActionEvent ae) {
- lastAction = FIND_ACTION_COMMAND;
- findReplaceCount = 0;
-
- if (FIND_REPLACE_DIALOG.isVisible() &&
- FIND_REPLACE_DIALOG.getTitle().equals(FIND_ACTION_COMMAND)) {
- }
-
- int pos = textComponent.getSelectedText() == null ?
- textComponent.getCaretPosition() :
- textComponent.getSelectionStart();
-
- boolean reverse = (ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
- pos = findNext(reverse, pos);
-
- if (pos > -1) {
- String pattern = (String) FIND_FIELD.getSelectedItem();
- textComponent.select(pos, pos + pattern.length());
- findReplaceCount = 1;
- }
-
- setListStrings();
-
- fireTextEvent();
- }
- }
-
- private static class ReplaceAction extends AbstractAction {
-
- public ReplaceAction() {
- putValue(Action.NAME, REPLACE_ACTION_COMMAND);
- putValue(Action.ACTION_COMMAND_KEY, REPLACE_ACTION_COMMAND);
- putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R);
- }
-
- public void actionPerformed(ActionEvent ae) {
- lastAction = ae.getActionCommand();
- findReplaceCount = 0;
-
- int pos = textComponent.getSelectedText() == null ?
- textComponent.getCaretPosition() :
- textComponent.getSelectionStart();
-
- pos = findNext(false, pos - 1);
-
- if (pos > -1) {
- String find = (String) FIND_FIELD.getSelectedItem();
- String replace = (String) REPLACE_FIELD.getSelectedItem();
- replace = replace == null ? "" : replace;
- Document doc = textComponent.getDocument();
- try {
- doc.remove(pos, find.length());
- doc.insertString(pos, replace, attributeSet);
-
- int last = pos;
- pos = findNext(false, pos);
- if (pos > -1) {
- textComponent.select(pos, pos + find.length());
- } else {
- textComponent.setCaretPosition(last + replace.length());
- }
- }
- catch (BadLocationException ble) {
- ble.printStackTrace();
- }
-
- findReplaceCount = 1;
- }
- setListStrings();
-
- fireTextEvent();
- }
- }
-
- private static class ReplaceAllAction extends AbstractAction {
-
- public ReplaceAllAction() {
- putValue(Action.NAME, REPLACE_ALL_ACTION_COMMAND);
- putValue(Action.ACTION_COMMAND_KEY, REPLACE_ALL_ACTION_COMMAND);
- putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
- }
-
- public void actionPerformed(ActionEvent ae) {
- lastAction = ae.getActionCommand();
- findReplaceCount = 0;
-
- int last = textComponent.getSelectedText() == null ?
- textComponent.getCaretPosition() :
- textComponent.getSelectionStart();
-
- int pos = findNext(false, last - 1);
-
- String find = (String) FIND_FIELD.getSelectedItem();
- String replace = (String) REPLACE_FIELD.getSelectedItem();
- replace = replace == null ? "" : replace;
- while (pos > -1) {
- Document doc = textComponent.getDocument();
- try {
- doc.remove(pos, find.length());
- doc.insertString(pos, replace, attributeSet);
-
- last = pos;
- pos = findNext(false, pos);
- }
- catch (BadLocationException ble) {
- ble.printStackTrace();
- }
-
- findReplaceCount++;
- }
-
- if (pos > -1) {
- textComponent.select(pos, pos + find.length());
- } else {
- textComponent.setCaretPosition(last + replace.length());
- }
- setListStrings();
-
- fireTextEvent();
- }
- }
-
- private static class CloseAction extends AbstractAction {
-
- public CloseAction() {
- putValue(Action.NAME, CLOSE_ACTION_COMMAND);
- putValue(Action.ACTION_COMMAND_KEY, CLOSE_ACTION_COMMAND);
- putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
- putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ESCAPE"));
- }
-
- public void actionPerformed(ActionEvent ae) {
- FIND_REPLACE_DIALOG.dispose();
- }
- }
-
- public static void dispose() {
- FIND_REPLACE_DIALOG.dispose();
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/GroovyFilter.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/GroovyFilter.java
deleted file mode 100644
index 85a1e69..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/GroovyFilter.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import javax.swing.*;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.Element;
-import javax.swing.text.JTextComponent;
-import javax.swing.text.Segment;
-import javax.swing.text.Style;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.StyleContext;
-import javax.swing.text.StyledDocument;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.KeyEvent;
-
-@Deprecated
-public class GroovyFilter extends StructuredSyntaxDocumentFilter {
-
- // java tab policy action
- private static final Action AUTO_TAB_ACTION = new AutoTabAction();
-
- // Style names
- public static final String COMMENT = "comment";
- public static final String SLASH_STAR_COMMENT = "/\\*(?s:.)*?(?:\\*/|\\z)";
- public static final String SLASH_SLASH_COMMENT = "//.*";
-
- public static final String QUOTES =
- "(?ms:\"{3}.*?(?:\"{3}|\\z))|(?:\"{1}.*?(?:\"|\\Z))";
-
- public static final String SINGLE_QUOTES =
- "(?ms:'{3}(?!'{1,3}).*?(?:'{3}|\\z))|(?:'{1}.*?(?:'|\\z))";
-
- public static final String SLASHY_QUOTES = "(?:/[^/*].*?(?<!\\\\)/|(?ms:\\$/.*?(?:/\\$|\\z)))";
-
- public static final String DIGIT = "DIGIT";
- public static final String DECIMAL_INTEGER_LITERAL = "(?:0|[1-9](?:[_0-9]*[0-9])?)[lL]?";
- public static final String HEX_INTEGER_LITERAL = "0[xX][0-9a-fA-F](?:[0-9a-fA-F_]*[0-9a-fA-F])?";
- public static final String OCTAL_INTEGER_LITERAL = "0[0-7](?:[_0-7]*[0-7])?";
- public static final String BINARY_INTEGER_LITERAL = "0[bB][01](?:[_01]*[01])?";
- public static final String DECIMAL_FLOATING_POINT_LITERAL = "(?:0|[1-9](?:[_0-9]*[0-9])?)?\\.?[0-9](?:[_0-9]*[0-9])?(?:[eE][+-]?[0-9]+(?:[_0-9]*[0-9])?)?[fFdD]?";
- public static final String HEXADECIMAL_FLOATING_POINT_LITERAL = "0[xX](?:[0-9a-fA-F](?:[0-9a-fA-F_]*[0-9a-fA-F])?)?\\.?(?:[0-9a-fA-F_]*[0-9a-fA-F])?(?:[pP][+-]?[0-9]+(?:[_0-9]*[0-9])?)?[fFdD]?";
-
- public static final String IDENT = "[\\w\\$&&[\\D]][\\w\\$]*";
- public static final String OPERATION = "[\\w\\$&&[\\D]][\\w\\$]* *\\(";
- public static final String LEFT_PARENS = "\\(";
-
- private static final Color COMMENT_COLOR =
- Color.LIGHT_GRAY.darker().darker();
-
-
- public static final String RESERVED_WORD = "reserved";
- public static final String[] RESERVED_WORDS = {"\\babstract\\b",
- "\\bassert\\b",
- "\\bdefault\\b",
- "\\bif\\b",
- "\\bprivate\\b",
- "\\bthis\\b",
- "\\bboolean\\b",
- "\\bdo\\b",
- "\\bimplements\\b",
- "\\bprotected\\b",
- "\\bthrow\\b",
- "\\bbreak\\b",
- "\\bdouble\\b",
- "\\bimport\\b",
- "\\bpublic\\b",
- "\\bthrows\\b",
- "\\bbyte\\b",
- "\\belse\\b",
- "\\binstanceof\\b",
- "\\breturn\\b",
- "\\btransient\\b",
- "\\bcase\\b",
- "\\bextends\\b",
- "\\bint\\b",
- "\\bshort\\b",
- "\\btry\\b",
- "\\bcatch\\b",
- "\\bfinal\\b",
- "\\binterface\\b",
- "\\benum\\b",
- "\\bstatic\\b",
- "\\bvoid\\b",
- "\\bchar\\b",
- "\\bfinally\\b",
- "\\blong\\b",
- "\\bstrictfp\\b",
- "\\bvolatile\\b",
- "\\bclass\\b",
- "\\bfloat\\b",
- "\\bnative\\b",
- "\\bsuper\\b",
- "\\bwhile\\b",
- "\\bconst\\b",
- "\\bfor\\b",
- "\\bnew\\b",
- "\\bswitch\\b",
- "\\bcontinue\\b",
- "\\bgoto\\b",
- "\\bpackage\\b",
- "\\bdef\\b",
- "\\bvar\\b",
- "\\bas\\b",
- "\\bin\\b",
- "\\bsynchronized\\b",
- "\\bnull\\b",
- "\\btrait\\b"
- };
-
- /**
- * Creates a new instance of GroovyFilter
- */
- public GroovyFilter(DefaultStyledDocument doc) {
- super(doc);
- init();
- }
-
- private void init() {
- StyleContext styleContext = StyleContext.getDefaultStyleContext();
- Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
-
- Style comment = styleContext.addStyle(COMMENT, defaultStyle);
- StyleConstants.setForeground(comment, COMMENT_COLOR);
- StyleConstants.setItalic(comment, true);
-
- Style quotes = styleContext.addStyle(QUOTES, defaultStyle);
- StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker());
-
- Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle);
- StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker());
-
- Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle);
- StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker());
-
- Style digit = styleContext.addStyle(DIGIT, defaultStyle);
- StyleConstants.setForeground(digit, Color.RED.darker());
-
- Style operation = styleContext.addStyle(OPERATION, defaultStyle);
- StyleConstants.setBold(operation, true);
-
- Style ident = styleContext.addStyle(IDENT, defaultStyle);
-
- Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle);
- StyleConstants.setBold(reservedWords, true);
- StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker());
-
- Style leftParens = styleContext.addStyle(IDENT, defaultStyle);
-
- getRootNode().putStyle(SLASH_STAR_COMMENT, comment);
- getRootNode().putStyle(SLASH_SLASH_COMMENT, comment);
- getRootNode().putStyle(QUOTES, quotes);
- getRootNode().putStyle(SINGLE_QUOTES, charQuotes);
- getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes);
-
- getRootNode().putStyle(new String[] {
- HEX_INTEGER_LITERAL,
- OCTAL_INTEGER_LITERAL,
- BINARY_INTEGER_LITERAL,
- DECIMAL_FLOATING_POINT_LITERAL,
- HEXADECIMAL_FLOATING_POINT_LITERAL,
- DECIMAL_INTEGER_LITERAL,
- }, digit);
-
- getRootNode().putStyle(OPERATION, operation);
- StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode();
- node.putStyle(RESERVED_WORDS, reservedWords);
- node.putStyle(LEFT_PARENS, leftParens);
- getRootNode().putChild(OPERATION, node);
-
- getRootNode().putStyle(IDENT, ident);
- node = createLexerNode();
- node.putStyle(RESERVED_WORDS, reservedWords);
- getRootNode().putChild(IDENT, node);
- }
-
- public static void installAutoTabAction(JTextComponent tComp) {
- tComp.getActionMap().put("GroovyFilter-autoTab", AUTO_TAB_ACTION);
- KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
- tComp.getInputMap().put(keyStroke, "GroovyFilter-autoTab");
- }
-
- private static class AutoTabAction extends AbstractAction {
-
- private StyledDocument doc;
- private final Segment segment = new Segment();
- private final StringBuilder buffer = new StringBuilder();
-
- public void actionPerformed(ActionEvent ae) {
- JTextComponent tComp = (JTextComponent) ae.getSource();
- if (tComp.getDocument() instanceof StyledDocument) {
- doc = (StyledDocument) tComp.getDocument();
- try {
- doc.getText(0, doc.getLength(), segment);
- }
- catch (Exception e) {
- // should NEVER reach here
- e.printStackTrace();
- }
- int offset = tComp.getCaretPosition();
- int index = findTabLocation(offset);
- buffer.delete(0, buffer.length());
- buffer.append('\n');
- if (index > -1) {
- for (int i = 0; i < index + 4; i++) {
- buffer.append(' ');
- }
- }
- try {
- doc.insertString(offset, buffer.toString(),
- doc.getDefaultRootElement().getAttributes());
- }
- catch (BadLocationException ble) {
- ble.printStackTrace();
- }
- }
- }
-
- public int findTabLocation(int offset) {
-
- // find first {
- boolean cont = true;
- while (offset > -1 && cont) {
- Element el = doc.getCharacterElement(offset);
- Object color =
- el.getAttributes().getAttribute(StyleConstants.Foreground);
- if (!COMMENT_COLOR.equals(color)) {
- cont = segment.array[offset] != '{' &&
- segment.array[offset] != '}';
- }
- offset -= cont ? 1 : 0;
- }
-
- if (offset > -1 && segment.array[offset] == '{') {
- while (offset > -1 &&
- !Character.isWhitespace(segment.array[offset--])) {
- }
- }
-
- int index = offset < 0 || segment.array[offset] == '}' ? -4 : 0;
- if (offset > -1) {
- Element top = doc.getDefaultRootElement();
- offset = top.getElement(top.getElementIndex(offset)).getStartOffset();
-
- while (Character.isWhitespace(segment.array[offset++])) {
- index++;
- }
- }
-
- return index;
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/MatchingHighlighter.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/MatchingHighlighter.java
deleted file mode 100644
index 12e4a0c..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/MatchingHighlighter.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import groovy.lang.Tuple2;
-import groovy.lang.Tuple3;
-import org.antlr.v4.runtime.Token;
-import org.apache.groovy.util.Maps;
-
-import javax.swing.JTextPane;
-import javax.swing.SwingUtilities;
-import javax.swing.event.CaretEvent;
-import javax.swing.event.CaretListener;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.Position;
-import javax.swing.text.Style;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.StyleContext;
-import java.awt.Color;
-import java.util.ArrayDeque;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-import static groovy.lang.Tuple.tuple;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LBRACE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LBRACK;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.LPAREN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RBRACE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RBRACK;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RPAREN;
-
-/**
- * Represents highlighter to highlight matched parentheses, brackets and curly braces when caret touching them
- *
- * @since 3.0.0
- */
-@Deprecated
-public class MatchingHighlighter implements CaretListener {
- private final SmartDocumentFilter smartDocumentFilter;
- private final JTextPane textEditor;
- private final DefaultStyledDocument doc;
- private static final Map<String, Tuple3<Integer, Integer, Boolean>> PAREN_MAP = Maps.of(
- "(", tuple(LPAREN, RPAREN, true),
- ")", tuple(RPAREN, LPAREN, false),
- "[", tuple(LBRACK, RBRACK, true),
- "]", tuple(RBRACK, LBRACK, false),
- "{", tuple(LBRACE, RBRACE, true),
- "}", tuple(RBRACE, LBRACE, false)
- );
- private volatile List<Tuple2<Integer, Position>> highlightedTokenInfoList = Collections.emptyList();
-
- public MatchingHighlighter(SmartDocumentFilter smartDocumentFilter, JTextPane textEditor) {
- this.smartDocumentFilter = smartDocumentFilter;
- this.textEditor = textEditor;
- this.doc = (DefaultStyledDocument) textEditor.getStyledDocument();
-
- initStyles();
- }
-
- @Override
- public void caretUpdate(CaretEvent e) {
- highlight();
- }
-
- public void highlight() {
- // `SwingUtilities.invokeLater` is used to avoid "java.lang.IllegalStateException: Attempt to mutate in notification"
- SwingUtilities.invokeLater(this::doHighlight);
- }
-
- private void doHighlight() {
- clearHighlighted();
-
- if (!smartDocumentFilter.isLatest()) {
- return;
- }
-
- int caretPosition = textEditor.getCaretPosition();
- int f = -1;
- String c = null;
- try {
- f = caretPosition - 1;
- c = doc.getText(f, 1);
- } catch (BadLocationException e1) {
- // ignore
- }
-
- if (!PAREN_MAP.containsKey(c)) {
- try {
- f = caretPosition;
- c = doc.getText(f, 1);
- } catch (BadLocationException e1) {
- // ignore
- }
- }
-
- if (!PAREN_MAP.containsKey(c)) {
- return;
- }
-
- final int offset = f;
- final String p = c;
-
- highlightMatched(offset, p);
- }
-
- private void highlightMatched(int offset, String p) {
- List<Token> latestTokenList = smartDocumentFilter.getLatestTokenList();
- Tuple3<Integer, Integer, Boolean> tokenTypeTuple = PAREN_MAP.get(p);
- int triggerTokenType = tokenTypeTuple.getV1();
- int matchedTokenType = tokenTypeTuple.getV2();
- boolean normalOrder = tokenTypeTuple.getV3();
- Deque<Tuple2<Token, Boolean>> stack = new ArrayDeque<>();
-
- Token triggerToken = null;
- Token matchedToken = null;
-
- for (ListIterator<Token> iterator = latestTokenList.listIterator(normalOrder ? 0 : latestTokenList.size());
- normalOrder ? iterator.hasNext() : iterator.hasPrevious(); ) {
- Token token = normalOrder ? iterator.next() : iterator.previous();
-
- int tokenType = token.getType();
- if (tokenType == triggerTokenType) {
- Boolean triggerFlag = offset == token.getStartIndex();
-
- stack.push(tuple(token, triggerFlag));
- } else if (tokenType == matchedTokenType) {
- Tuple2<Token, Boolean> tokenAndTriggerFlagTuple = stack.pop();
- if (tokenAndTriggerFlagTuple.getV2()) {
- triggerToken = tokenAndTriggerFlagTuple.getV1();
- matchedToken = token;
- break;
- }
- }
- }
-
- if (null != triggerToken && null != matchedToken) {
- highlightToken(p, triggerToken);
- highlightToken(p, matchedToken);
- try {
- highlightedTokenInfoList = Arrays.asList(
- tuple(triggerToken.getType(), doc.createPosition(triggerToken.getStartIndex())),
- tuple(matchedToken.getType(), doc.createPosition(matchedToken.getStartIndex()))
- );
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void initStyles() {
- PAREN_MAP.keySet().forEach(e -> createHighlightedStyleByParen(e));
- }
-
- private final StyleContext styleContext = StyleContext.getDefaultStyleContext();
- private final Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
-
- private void createHighlightedStyleByParen(String p) {
- Style style = StyleContext.getDefaultStyleContext().addStyle(highlightedStyleName(p), findStyleByTokenType(PAREN_MAP.get(p).getV1()));
- StyleConstants.setForeground(style, Color.YELLOW.darker());
- StyleConstants.setBold(style, true);
- }
-
- private static String highlightedStyleName(String p) {
- return "highlighted" + p;
- }
-
- private Style findHighlightedStyleByParen(String p) {
- Style style = styleContext.getStyle(highlightedStyleName(p));
-
- return null == style ? defaultStyle : style;
- }
-
- private Style findStyleByTokenType(int tokenType) {
- Style style = styleContext.getStyle(String.valueOf(tokenType));
-
- return null == style ? defaultStyle : style;
- }
-
- private void highlightToken(String p, final Token tokenToHighlight) {
- Style style = findHighlightedStyleByParen(p);
- doc.setCharacterAttributes(tokenToHighlight.getStartIndex(),
- 1,
- style,
- true);
- }
-
- private void clearHighlighted() {
- if (!highlightedTokenInfoList.isEmpty()) {
- for (Tuple2<Integer, Position> highlightedTokenInfo : highlightedTokenInfoList) {
- doc.setCharacterAttributes(
- highlightedTokenInfo.getV2().getOffset(),
- 1,
- findStyleByTokenType(highlightedTokenInfo.getV1()),
- true
- );
- }
-
- highlightedTokenInfoList = Collections.emptyList();
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/SmartDocumentFilter.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/SmartDocumentFilter.java
deleted file mode 100644
index 7802c3d..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/SmartDocumentFilter.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import org.antlr.v4.runtime.CharStream;
-import org.antlr.v4.runtime.CharStreams;
-import org.antlr.v4.runtime.CommonTokenStream;
-import org.antlr.v4.runtime.ConsoleErrorListener;
-import org.antlr.v4.runtime.LexerNoViableAltException;
-import org.antlr.v4.runtime.Token;
-import org.apache.groovy.parser.antlr4.GroovyLangLexer;
-import org.apache.groovy.parser.antlr4.GroovySyntaxError;
-
-import javax.swing.text.AttributeSet;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.DocumentFilter;
-import javax.swing.text.Style;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.StyleContext;
-import java.awt.Color;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ABSTRACT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.AS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ASSERT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BREAK;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BooleanLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.BuiltInPrimitiveType;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CASE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CATCH;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CLASS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.COMMA;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CONST;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.CONTINUE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DEFAULT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.DO;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ELSE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.ENUM;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EOF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.EXTENDS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FINAL;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FINALLY;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FOR;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.FloatingPointLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GOTO;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringBegin;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringEnd;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.GStringPart;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IMPLEMENTS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IMPORT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INSTANCEOF;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.INTERFACE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.IntegerLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NATIVE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NEW;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NL;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.NullLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PACKAGE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PRIVATE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PROTECTED;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.PUBLIC;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.RETURN;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SEMI;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.STATIC;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.STRICTFP;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SUPER;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SWITCH;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.SYNCHRONIZED;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.StringLiteral;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THIS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THREADSAFE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THROW;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.THROWS;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRAIT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRANSIENT;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.TRY;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.UNEXPECTED_CHAR;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VAR;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOID;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.VOLATILE;
-import static org.apache.groovy.parser.antlr4.GroovyLexer.WHILE;
-
-
-/**
- * The document filter based on Parrot's lexer is for highlighting the content of text editor
- *
- * @since 3.0.0
- */
-@Deprecated
-public class SmartDocumentFilter extends DocumentFilter {
- private static final String MONOSPACED = "Monospaced";
- private final DefaultStyledDocument styledDocument;
- private final StyleContext styleContext;
- private final Style defaultStyle;
-
- public SmartDocumentFilter(DefaultStyledDocument styledDocument) {
- this.styledDocument = styledDocument;
-
- this.styleContext = StyleContext.getDefaultStyleContext();
- this.defaultStyle = this.styleContext.getStyle(StyleContext.DEFAULT_STYLE);
- StyleConstants.setFontFamily(this.defaultStyle, MONOSPACED);
-
- initStyles();
- }
-
- @Override
- public void insertString(DocumentFilter.FilterBypass fb, int offset,
- String text, AttributeSet attrs) throws BadLocationException {
- // remove problem meta characters returns
- text = replaceMetaCharacters(text);
-
- fb.insertString(offset, text, attrs);
- parseDocument();
- }
-
- @Override
- public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
- throws BadLocationException {
-
- fb.remove(offset, length);
- parseDocument();
- }
-
- @Override
- public void replace(DocumentFilter.FilterBypass fb, int offset,
- int length, String text, AttributeSet attrs)
- throws BadLocationException {
-
- // text might be null and indicates no replacement text
- if (text == null) text = "";
-
- // remove problem meta characters returns
- text = replaceMetaCharacters(text);
-
- fb.replace(offset, length, text, attrs);
-
- parseDocument();
- }
-
- private String replaceMetaCharacters(String string) {
- // just in case remove carriage returns
- string = string.replaceAll("\\t", TAB_REPLACEMENT);
- return string;
- }
-
- private void parseDocument() throws BadLocationException {
- GroovyLangLexer lexer;
- try {
- lexer = createLexer(styledDocument.getText(0, styledDocument.getLength()));
- } catch (IOException e) {
- e.printStackTrace();
- this.latest = false;
- return;
- }
-
- CommonTokenStream tokenStream = new CommonTokenStream(lexer);
-
- try {
- tokenStream.fill();
- } catch (LexerNoViableAltException | GroovySyntaxError e) {
- // ignore
- this.latest = false;
- return;
- } catch (Exception e) {
- e.printStackTrace();
- this.latest = false;
- return;
- }
-
- List<Token> tokenList = tokenStream.getTokens();
- List<Token> tokenListToRender = findTokensToRender(tokenList);
-
- for (Token token : tokenListToRender) {
- int tokenType = token.getType();
-
-// if (token instanceof CommonToken) {
-// System.out.println(((CommonToken) token).toString(lexer));
-// }
-
- if (EOF == tokenType) {
- continue;
- }
-
- int tokenStartIndex = token.getStartIndex();
- int tokenStopIndex = token.getStopIndex();
- int tokenLength = tokenStopIndex - tokenStartIndex + 1;
-
- styledDocument.setCharacterAttributes(tokenStartIndex,
- tokenLength,
- findStyleByTokenType(tokenType),
- true);
-
- if (GStringBegin == tokenType || GStringPart == tokenType) {
- styledDocument.setCharacterAttributes(
- tokenStartIndex + tokenLength - 1,
- 1,
- defaultStyle,
- true);
- }
- }
-
- this.latestTokenList = tokenList;
- this.latest = true;
- }
-
- private List<Token> findTokensToRender(List<Token> tokenList) {
- int tokenListSize = tokenList.size();
- int latestTokenListSize = latestTokenList.size();
-
- if (0 == tokenListSize || 0 == latestTokenListSize) {
- return tokenList;
- }
-
- int startTokenIndex = 0;
- int minSize = Math.min(tokenListSize, latestTokenListSize);
- for (int i = 0; i < minSize; i++) {
- Token token = tokenList.get(i);
- Token latestToken = latestTokenList.get(i);
-
- if (token.getType() == latestToken.getType()
- && token.getStartIndex() == latestToken.getStartIndex()
- && token.getStopIndex() == latestToken.getStopIndex()) {
- continue;
- }
-
- startTokenIndex = i;
- break;
- }
-
- List<Token> newTokenList = new ArrayList<>(tokenList);
- List<Token> newLatestTokenList = new ArrayList<>(latestTokenList);
-
- Collections.reverse(newTokenList);
- Collections.reverse(newLatestTokenList);
-
- int stopTokenIndex = tokenListSize;
-
- Token lastToken = newTokenList.get(0);
- Token lastLatestToken = newLatestTokenList.get(0);
-
- for (int i = 0; i < minSize; i++) {
- Token token = newTokenList.get(i);
- Token latestToken = newLatestTokenList.get(i);
-
- if ((token.getType() == latestToken.getType())
- && (token.getStartIndex() - lastToken.getStartIndex()) == (latestToken.getStartIndex() - lastLatestToken.getStartIndex())
- && ((token.getStopIndex() - lastToken.getStopIndex()) == (latestToken.getStopIndex() - lastLatestToken.getStopIndex()))) {
- continue;
- }
-
- stopTokenIndex = tokenListSize - i;
- break;
- }
-
- if (startTokenIndex <= stopTokenIndex) {
- return tokenList.subList(startTokenIndex, stopTokenIndex);
- }
-
- return Collections.emptyList();
- }
-
- private Style findStyleByTokenType(int tokenType) {
- Style style = styleContext.getStyle(String.valueOf(tokenType));
-
- return null == style ? defaultStyle : style;
- }
-
- private Style createDefaultStyleByTokenType(int tokenType) {
- return styleContext.addStyle(String.valueOf(tokenType), defaultStyle);
- }
-
- private GroovyLangLexer createLexer(String text) throws IOException {
- CharStream charStream = CharStreams.fromReader(new StringReader(text));
- GroovyLangLexer lexer = new GroovyLangLexer(charStream);
-
- lexer.removeErrorListener(ConsoleErrorListener.INSTANCE);
-
- return lexer;
- }
-
- private void initStyles() {
- Style comment = createDefaultStyleByTokenType(NL);
- StyleConstants.setForeground(comment, Color.LIGHT_GRAY.darker().darker());
- StyleConstants.setItalic(comment, true);
-
- // gstrings, e.g. "${xxx}", /xxx/
- for (int t : Arrays.asList(GStringBegin, GStringPart, GStringEnd)) {
- Style style = createDefaultStyleByTokenType(t);
- StyleConstants.setForeground(style, Color.MAGENTA.darker().darker());
- }
-
- // strings, e.g. 'xxx'
- Style stringLiteral = createDefaultStyleByTokenType(StringLiteral);
- StyleConstants.setForeground(stringLiteral, Color.GREEN.darker().darker());
-
- // numbers, e.g. 123, 1.23
- for (int t : Arrays.asList(IntegerLiteral, FloatingPointLiteral)) {
- Style style = createDefaultStyleByTokenType(t);
- StyleConstants.setForeground(style, Color.RED.darker());
- }
-
- // reserved keywords, null literals, boolean literals
- for (int t : Arrays.asList(AS, DEF, IN, TRAIT, THREADSAFE,
- VAR, BuiltInPrimitiveType, ABSTRACT, ASSERT, BREAK, CASE, CATCH, CLASS, CONST, CONTINUE, DEFAULT, DO,
- ELSE, ENUM, EXTENDS, FINAL, FINALLY, FOR, IF, GOTO, IMPLEMENTS, IMPORT, INSTANCEOF, INTERFACE,
- NATIVE, NEW, PACKAGE, PRIVATE, PROTECTED, PUBLIC, RETURN, STATIC, STRICTFP, SUPER, SWITCH, SYNCHRONIZED,
- THIS, THROW, THROWS, TRANSIENT, TRY, VOID, VOLATILE, WHILE, NullLiteral, BooleanLiteral)) {
- Style style = createDefaultStyleByTokenType(t);
- StyleConstants.setBold(style, true);
- StyleConstants.setForeground(style, Color.BLUE.darker().darker());
- }
-
- // commas, semicolons
- for (int t : Arrays.asList(COMMA, SEMI)) {
- Style style = createDefaultStyleByTokenType(t);
- StyleConstants.setForeground(style, Color.BLUE.darker());
- }
-
- // unexpected char, e.g. `
- Style unexpectedChar = createDefaultStyleByTokenType(UNEXPECTED_CHAR);
- StyleConstants.setForeground(unexpectedChar, Color.CYAN.darker());
- }
-
- private volatile boolean latest = false;
- private volatile List<Token> latestTokenList = Collections.emptyList();
- private static final String TAB_REPLACEMENT = " ";
-
- public boolean isLatest() {
- return latest;
- }
-
- public List<Token> getLatestTokenList() {
- return latestTokenList;
- }
-
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxDocumentFilter.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxDocumentFilter.java
deleted file mode 100644
index 848965e..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxDocumentFilter.java
+++ /dev/null
@@ -1,574 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import javax.swing.text.AttributeSet;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.DefaultStyledDocument;
-import javax.swing.text.DocumentFilter;
-import javax.swing.text.Position;
-import javax.swing.text.Segment;
-import javax.swing.text.Style;
-import javax.swing.text.StyleContext;
-import java.io.Serializable;
-import java.nio.CharBuffer;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-@Deprecated
-public class StructuredSyntaxDocumentFilter extends DocumentFilter {
-
- public static final String TAB_REPLACEMENT = " ";
-
- private static final MLComparator ML_COMPARATOR = new MLComparator();
-
- /**
- * The root of the lexical parsing tree.
- */
- protected LexerNode lexer = new LexerNode(true);
-
- // The styled document the filter parses
- protected DefaultStyledDocument styledDocument;
-
- // the document buffer and segment
- private Segment segment = new Segment();
- private CharBuffer buffer;
-
- /**
- * The position tree of multi-line comments.
- */
- protected SortedSet mlTextRunSet = new TreeSet(ML_COMPARATOR);
-
- // Ensures not adding any regexp with capturing groups
- private static void checkRegexp(String regexp) {
- String checking = regexp.replaceAll("\\\\\\(", "X").replaceAll("\\(\\?", "X");
- int checked = checking.indexOf('(');
- if (checked > -1) {
- StringBuilder msg = new StringBuilder("Only non-capturing groups allowed:\r\n" +
- regexp + "\r\n");
- for (int i = 0; i < checked; i++) {
- msg.append(" ");
- }
- msg.append("^");
- throw new IllegalArgumentException(msg.toString());
- }
- }
-
- /**
- * Creates a new instance of StructuredSyntaxDocumentFilter
- * @param document the styled document to parse
- */
- public StructuredSyntaxDocumentFilter(DefaultStyledDocument document) {
- this.styledDocument = document;
- }
-
- private int calcBeginParse(int offset) {
- MultiLineRun mlr = getMultiLineRun(offset);
- if (mlr != null) {
- // means we're in middle of mlr, so start at beginning of mlr
- offset = mlr.start();
- }
- else {
- // otherwise, earliest position in line not part of mlr
- offset = styledDocument.getParagraphElement(offset).getStartOffset();
- mlr = getMultiLineRun(offset);
- offset = mlr == null ? offset : mlr.end() + 1;
- }
-
- return offset;
- }
-
- private int calcEndParse(int offset) {
- MultiLineRun mlr = getMultiLineRun(offset);
- if (mlr != null) {
- // means we're in middle of mlr, so end is at end of mlr
- offset = mlr.end();
- }
- else {
- // otherwise, latest position in line not part of mlr
- offset = styledDocument.getParagraphElement(offset).getEndOffset();
- mlr = getMultiLineRun(offset);
- offset = mlr == null ? offset : mlr.end();
- }
-
- return offset;
- }
-
- /**
- * Create a new LexerNode for adding to root.
- *
- * @return a new LexerNode
- */
- public LexerNode createLexerNode() {
- return new LexerNode(false);
- }
-
- // given an offset, return the mlr it resides in
- private MultiLineRun getMultiLineRun(int offset) {
- MultiLineRun ml = null;
- if (offset > 0) {
- Integer os = offset;
-
- SortedSet set = mlTextRunSet.headSet(os);
- if (!set.isEmpty()) {
- ml = (MultiLineRun)set.last();
- ml = ml.end() >= offset ? ml : null;
- }
- }
-
- return ml;
- }
-
- /**
- * Get the root node for lexing the document. Children can be added such
- * that matching patterns can be further parsed if required.
- *
- * @return the root lexing node.
- */
- public LexerNode getRootNode() {
- return lexer;
- }
-
- /**
- * Insert a string into the document, and then parse it if the parser has been
- * set.
- *
- * @param fb
- * @param offset
- * @param text
- * @param attrs
- * @throws BadLocationException
- */
- public void insertString(DocumentFilter.FilterBypass fb, int offset,
- String text, AttributeSet attrs)
- throws BadLocationException {
- // remove problem meta characters returns
- text = replaceMetaCharacters(text);
-
- fb.insertString(offset, text, attrs);
-
- // start on the string that was inserted
- parseDocument(offset, text.length());
- }
-
- /**
- * Parse the Document to update the character styles given an initial start
- * position. Called by the filter after it has updated the text.
- *
- * @param offset
- * @param length
- * @throws BadLocationException
- */
- protected void parseDocument(int offset, int length) throws BadLocationException {
- // initialize the segment with the complete document so the segment doesn't
- // have an underlying gap in the buffer
- styledDocument.getText(0, styledDocument.getLength(), segment);
-
- buffer = CharBuffer.wrap(segment.array).asReadOnlyBuffer();
-
- // initialize the lexer if necessary
- if (!lexer.isInitialized()) {
- // prime the parser and reparse whole document
- lexer.initialize();
- offset = 0;
- length = styledDocument.getLength();
- }
- else {
- int end = offset + length;
- offset = calcBeginParse(offset);
- length = calcEndParse(end) - offset;
-
- // clean the tree by ensuring multi line styles are reset in area
- // of parsing
- SortedSet set = mlTextRunSet.subSet(offset,
- offset + length);
- if (set != null) {
- set.clear();
- }
- }
-
- // parse the document
- lexer.parse(buffer, offset, length);
- }
-
- /**
- * Remove a string from the document, and then parse it if the parser has been
- * set.
- *
- * @param fb
- * @param offset
- * @param length
- * @throws BadLocationException
- */
- public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
- throws BadLocationException {
- // FRICKIN' HACK!!!!! For some reason, deleting a string at offset 0
- // does not get done properly, so first replace and remove after parsing
- if (offset == 0 && length != fb.getDocument().getLength()) {
- fb.replace(0, length, "\n", lexer.defaultStyle);
-
- // start on either side of the removed text
- parseDocument(offset, 2);
- fb.remove(offset, 1);
- }
- else {
- fb.remove(offset, length);
-
- // start on either side of the removed text
- if (offset + 1 < fb.getDocument().getLength()) {
- parseDocument(offset, 1);
- }
- else if (offset - 1 > 0) {
- parseDocument(offset - 1, 1);
- }
- else {
- // empty text
- mlTextRunSet.clear();
- }
- }
-
- }
-
- /**
- * Replace a string in the document, and then parse it if the parser has been
- * set.
- *
- * @param fb
- * @param offset
- * @param length
- * @param text
- * @param attrs
- * @throws BadLocationException
- */
- public void replace(DocumentFilter.FilterBypass fb, int offset,
- int length, String text, AttributeSet attrs)
- throws BadLocationException
- {
- // text might be null and indicates no replacement text
- if (text == null) text = "";
-
- // remove problem meta characters returns
- text = replaceMetaCharacters(text);
-
- fb.replace(offset, length, text, attrs);
-
- // start on the text that was replaced
- parseDocument(offset, text.length());
- }
-
- // tabs with spaces (I hate tabs)
- private String replaceMetaCharacters(String string) {
- // just in case remove carriage returns
- string = string.replaceAll("\\t", TAB_REPLACEMENT);
- return string;
- }
-
- public final class LexerNode {
-
- private Style defaultStyle;
-
- private Map styleMap = new LinkedHashMap();
- private Map children = new HashMap();
-
- private Matcher matcher;
- private List groupList = new ArrayList();
-
- private boolean initialized;
-
- private CharBuffer lastBuffer;
-
- /*
- * Creates a new instance of LexerNode
- */
- LexerNode(boolean isParent) {
- StyleContext sc = StyleContext.getDefaultStyleContext();
- defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
- }
-
- private String buildRegexp(String[] regexps) {
- StringBuilder regexp = new StringBuilder();
-
- for (int i = 0; i < regexps.length; i++) {
- regexp.append("|").append(regexps[i]);
- }
-
- // ensure leading '|' is removed
- return regexp.substring(1);
- }
-
- public Style getDefaultStyle() {
- return defaultStyle;
- }
-
- private void initialize() {
- matcher = null;
- groupList.clear();
- groupList.add(null);
-
- Iterator iter = styleMap.keySet().iterator();
- StringBuilder regexp = new StringBuilder();
- while (iter.hasNext()) {
- String nextRegexp = (String)iter.next();
- regexp.append("|(").append(nextRegexp).append(")");
- // have to compile regexp first so that it will match
- groupList.add(Pattern.compile(nextRegexp).pattern());
- }
- if (!regexp.toString().equals("")) {
- matcher = Pattern.compile(regexp.substring(1)).matcher("");
-
- iter = children.values().iterator();
- while (iter.hasNext()) {
- ((LexerNode)iter.next()).initialize();
- }
- }
- initialized = true;
- }
-
- /**
- * @return true if initialised
- */
- public boolean isInitialized() {
- return initialized;
- }
-
- /**
- * @param buffer
- * @param offset
- * @param length
- * @throws BadLocationException
- */
- public void parse(CharBuffer buffer, int offset, int length)
- throws BadLocationException {
- // get the index of where we can start to look for an exit:
- // i.e. after the end of the length of the segment, when we find
- // that text in question already is set properly, we can stop
- // parsing
- int checkPoint = offset + length;
-
- // reset the matcher and start parsing string
- if (lastBuffer != buffer) {
- matcher.reset(buffer);
- lastBuffer = buffer;
- }
-
- // the start and end indices of a match in the Matcher looking
- int matchEnd = offset;
- Style style = null;
- while (matchEnd < checkPoint && matcher.find(offset)) {
- // when we get something other than -1, we know which regexp
- // matched; the 0 group is the complete expression of the
- // matcher, which would always return a hit based on the above
- // while condition
- int groupNum = 0;
- while ((offset = matcher.start(++groupNum)) == -1){
- }
-
- // if the matching offset is not the same as the end of the
- // previous match, we have extra text not matched, so set to
- // the default style of this lexer node
- if (offset != matchEnd) {
- offset = offset > checkPoint ? checkPoint : offset;
- styledDocument.setCharacterAttributes(matchEnd,
- offset - matchEnd,
- defaultStyle,
- true);
- if (offset >= checkPoint) {
- return;
- }
- }
-
- // track the end of the matching string
- matchEnd = matcher.end(groupNum);
-
- // retrieve the proper style from groupNum of the groupList and
- // styleMap, then set the attributes of the matching string
- style = (Style)styleMap.get((String)groupList.get(groupNum));
- styledDocument.setCharacterAttributes(offset,
- matchEnd - offset,
- style, true);
-
- // if the match was multiline, which we'll know if they span
- // multiple paragraph elements, the mark it (this list was cleaned
- // above in parseDocument())
- if (styledDocument.getParagraphElement(offset).getStartOffset() !=
- styledDocument.getParagraphElement(matchEnd).getStartOffset()) {
- // mark a ml run
- MultiLineRun mlr = new MultiLineRun(offset, matchEnd);
- mlTextRunSet.add(mlr);
- }
-
- // parse the child regexps, if any, within a matched block
- LexerNode node = (LexerNode)children.get(groupList.get(groupNum));
- if (node != null) {
- node.parse(buffer, offset, matchEnd - offset);
- }
-
- // set the offset to start where we left off
- offset = matchEnd;
- }
- if (matchEnd < checkPoint) {
- // if we finished before hitting the end of the checkpoint from
- // no mroe matches, then set ensure the text is reset to the
- // defaultStyle
- styledDocument.setCharacterAttributes(matchEnd,
- checkPoint - matchEnd,
- defaultStyle,
- true);
- }
- }
-
- /**
- *
- * @param regexp
- * @param node
- */
- public void putChild(String regexp, LexerNode node) {
- node.defaultStyle = (Style)styleMap.get(regexp);
-
- // have to compile regexp first so that it will match
- children.put(Pattern.compile(regexp).pattern(), node);
- initialized = false;
- }
-
- /**
- * @param regexps
- * @param node
- */
- public void putChild(String[] regexps, LexerNode node) {
- putChild(buildRegexp(regexps), node);
- }
-
- /**
- * @param regexp
- * @param style
- */
- public void putStyle(String regexp, Style style) {
- checkRegexp(regexp);
- styleMap.put(regexp, style);
- initialized = false;
- }
-
- /**
- * @param regexps
- * @param style
- */
- public void putStyle(String regexps[], Style style) {
- putStyle(buildRegexp(regexps), style);
- }
-
- /**
- * @param regexp
- */
- public void removeChild(String regexp) {
- children.remove(regexp);
- }
-
- /**
- * @param regexp
- */
- public void removeStyle(String regexp) {
- styleMap.remove(regexp);
- children.remove(regexp);
- }
-
- /**
- * @param regexps
- */
- public void removeStyle(String regexps[]) {
- removeStyle(buildRegexp(regexps));
- }
-
- public void setDefaultStyle(Style style) {
- defaultStyle = style;
- }
- }
-
- protected class MultiLineRun {
-
- private Position start;
- private Position end;
- private int delimeterSize;
-
- public MultiLineRun(int start, int end) throws BadLocationException {
- this(start, end, 2);
- }
-
- public MultiLineRun(int start, int end, int delimeterSize) throws BadLocationException {
- if (start > end) {
- String msg = "Start offset is after end: ";
- throw new BadLocationException(msg, start);
- }
- if (delimeterSize < 1) {
- String msg = "Delimiters be at least size 1: " +
- delimeterSize;
- throw new IllegalArgumentException(msg);
- }
- this.start = styledDocument.createPosition(start);
- this.end = styledDocument.createPosition(end);
- this.delimeterSize = delimeterSize;
- }
-
- public int getDelimeterSize() {
- return delimeterSize;
- }
-
- public int end() {
- return end.getOffset();
- }
-
- public int length() {
- return end.getOffset() - start.getOffset();
- }
-
- public int start() {
- return start.getOffset();
- }
-
- public String toString() {
- return start.toString() + " " + end.toString();
- }
-
- }
-
- private static class MLComparator implements Comparator, Serializable {
-
- private static final long serialVersionUID = -4210196728719411217L;
-
- public int compare(Object obj, Object obj1) {
- return valueOf(obj) - valueOf(obj1);
- }
-
- private int valueOf(Object obj) {
- return obj instanceof Integer ?
- (Integer) obj :
- (obj instanceof MultiLineRun) ?
- ((MultiLineRun)obj).start() :
- ((Position)obj).getOffset();
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxHandler.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxHandler.java
deleted file mode 100644
index 00f7e90..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxHandler.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.DefaultHandler;
-
-@Deprecated
-public class StructuredSyntaxHandler extends DefaultHandler {
-
- //StyleConstants.
- public static final String REGEXP = "regexp";
- public static final String STYLE = "style";
-
- public static final String ALIGN_CENTER = "ALIGN_CENTER";
- public static final String ALIGN_JUSTIFIED = "ALIGN_JUSTIFIED";
- public static final String ALIGN_LEFT = "ALIGN_LEFT";
- public static final String ALIGN_RIGHT = "ALIGN_RIGHT";
-
- public static final String ALIGNMENT = "alignment";
- public static final String BACKGROUND = "background";
- public static final String BIDI_LEVEL = "bidiLevel";
- public static final String BOLD = "bold";
- public static final String COMPONENT_ATTRIBUTE = "componentAttribute";
- public static final String COMPONENT_ELEMENT_NAME = "componentElementName";
- public static final String COMPOSED_TEXT_ATTRIBUTE = "composedTextAttribute";
- public static final String FIRST_LINE_INDENT = "firstLineIndent";
- public static final String FONT_FAMILY = "fontFamily";
- public static final String FONT_SIZE = "fontSize";
- public static final String FOREGROUND = "foreground";
- public static final String ICON_ATTRIBUTE = "iconAttribute";
- public static final String ICON_ELEMENT_NAME = "iconElementName";
- public static final String ITALIC = "italic";
- public static final String LEFT_INDENT = "leftIndent";
- public static final String LINE_SPACING = "lineSpacing";
- public static final String MODEL_ATTRIBUTE = "modelAttribute";
- public static final String NAME_ATTRIBUTE = "nameAttribute";
- public static final String ORIENTATION = "orientation";
- public static final String RESOLVE_ATTRIBUTE = "resolveAttribute";
- public static final String RIGHT_INDENT = "rightIndent";
- public static final String SPACE_ABOVE = "spaceAbove";
- public static final String SPACE_BELOW = "spaceBelow";
- public static final String STRIKE_THROUGH = "strikeThrough";
- public static final String SUBSCRIPT = "subscript";
- public static final String SUPERSCRIPT = "superscript";
- public static final String TAB_SET = "tabSet";
- public static final String UNDERLINE = "underline";
-
- private StructuredSyntaxDocumentFilter.LexerNode currentNode;
-
- private final StructuredSyntaxDocumentFilter filter;
-
- /**
- * Creates a new instance of MasterFrameHandler
- *
- * @param filter
- */
- public StructuredSyntaxHandler(StructuredSyntaxDocumentFilter filter) {
- this.filter = filter;
- }
-
- public void characters(char[] ch, int start, int length) {
- }
-
- public void endDocument() throws SAXException {
- super.endDocument();
- }
-
- public void endElement(String uri,
- String localName,
- String qName) throws SAXException {
- }
-
- public void error(SAXParseException e) throws SAXException {
- throw new SAXException("Line: " + e.getLineNumber() + " message: " + e.getMessage());
- }
-
- public void startDocument() throws SAXException {
- super.startDocument();
- currentNode = filter.getRootNode();
- }
-
- public void startElement(String uri,
- String localName,
- String qName,
- Attributes attributes) throws SAXException {
- super.startElement(uri, localName, qName, attributes);
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxResources.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxResources.java
deleted file mode 100644
index 2c060c1..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/StructuredSyntaxResources.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import java.awt.*;
-import java.awt.datatransfer.Clipboard;
-
-/**
- * Contains all the basic resources and values used by the utility frame work
- * framework.
- */
-@Deprecated
-public final class StructuredSyntaxResources {
-
- // ==================================================
- // ClipBoard
- // ==================================================
-
- public static final Clipboard SYSTEM_CLIPBOARD;
- static {
- Clipboard systemClipboard = null;
- try {
- // if we don't have access to the system clipboard, will throw
- // a security exception
- SecurityManager mgr = System.getSecurityManager();
- if (mgr != null) {
- mgr.checkPermission(new AWTPermission("accessClipboard"));
- }
- systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
- }
- catch (SecurityException e) {
- // means we can't get to system clipboard, so create app level one
- systemClipboard = new Clipboard("UIResourceMgr");
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- SYSTEM_CLIPBOARD = systemClipboard;
- }
-
- // =====================================================
- // STANDARD FONTS
- // =====================================================
-
- public static final Font LARGE_FONT = Font.decode("Arial-24");
- public static final Font MEDIUM_FONT = Font.decode("Arial-18");
- public static final Font SMALL_FONT = Font.decode("Arial-12");
-
- public static final Font EDITOR_FONT = Font.decode("Monospaced-12");
-
- // =====================================================
- // UNDO/REDO NAMES
- // =====================================================
-
- public static final String UNDO = "Undo";
- public static final String REDO = "Redo";
- public static final String PRINT = "Print";
- public static final String FIND = "Find";
- public static final String FIND_NEXT = "Find Next";
- public static final String REPLACE = "Replace";
-
- // singleton
- private StructuredSyntaxResources() {
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextEditor.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextEditor.java
deleted file mode 100644
index 371096b..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextEditor.java
+++ /dev/null
@@ -1,500 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import javax.swing.*;
-import javax.swing.plaf.ComponentUI;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.Caret;
-import javax.swing.text.DefaultCaret;
-import javax.swing.text.DefaultEditorKit;
-import javax.swing.text.Document;
-import javax.swing.text.Element;
-import javax.swing.text.JTextComponent;
-import javax.swing.text.Utilities;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.print.PageFormat;
-import java.awt.print.Pageable;
-import java.awt.print.Paper;
-import java.awt.print.Printable;
-import java.awt.print.PrinterException;
-import java.awt.print.PrinterJob;
-import java.util.Calendar;
-import java.util.regex.Pattern;
-
-/**
- * A simple text pane that is printable and wrapping is optional.
- */
-@Deprecated
-public class TextEditor extends JTextPane implements Pageable, Printable {
-
- public static final String FIND = "Find...";
- public static final String FIND_NEXT = "Find Next";
- public static final String FIND_PREVIOUS = "Find Previous";
- public static final String REPLACE = "Replace...";
- public static final String AUTO_INDENT = "AutoIndent";
-
- private static final String TABBED_SPACES = " ";
- private static final Pattern TAB_BACK_PATTERN =
- Pattern.compile("^(([\t])|( )|( )|( )|( ))", Pattern.MULTILINE);
- private static final Pattern LINE_START =
- Pattern.compile("^", Pattern.MULTILINE);
-
- private static final JTextPane PRINT_PANE = new JTextPane();
- private static final Dimension PRINT_SIZE = new Dimension();
- private static boolean isOvertypeMode;
-
- private Caret defaultCaret;
- private Caret overtypeCaret;
-
- private static final PageFormat PAGE_FORMAT;
-
- static {
- PrinterJob job = PrinterJob.getPrinterJob();
- PAGE_FORMAT = job.defaultPage();
- }
-
- private int numPages;
-
- private MouseAdapter mouseAdapter =
- new MouseAdapter() {
- Cursor cursor;
-
- public void mouseEntered(MouseEvent me) {
- if (contains(me.getPoint())) {
- cursor = getCursor();
- Cursor curs = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);
- getRootPane().getLayeredPane().setCursor(curs);
- } else {
- getRootPane().getLayeredPane().setCursor(cursor);
- }
- }
-
- public void mouseExited(MouseEvent me) {
- getRootPane().getLayeredPane().setCursor(null);
- }
- };
-
- private boolean unwrapped;
- private boolean tabsAsSpaces;
- private boolean multiLineTab;
-
- /**
- * Creates a new instance of TextEditor
- */
- public TextEditor() {
- this(false);
- }
-
- /**
- * Creates a new instance of TextEditor
- */
- public TextEditor(boolean tabsAsSpaces) {
- this(tabsAsSpaces, false);
- }
-
- /**
- * Creates a new instance of TextEditor
- */
- public TextEditor(boolean tabsAsSpaces, boolean multiLineTab) {
- this(multiLineTab, tabsAsSpaces, false);
- }
-
- /**
- * Creates a new instance of TextEditor
- */
- public TextEditor(boolean tabsAsSpaces, boolean multiLineTab, boolean unwrapped) {
- this.tabsAsSpaces = tabsAsSpaces;
- this.multiLineTab = multiLineTab;
- this.unwrapped = unwrapped;
-
- // remove and replace the delete action to another spot so ctrl H later
- // on is strictly for showing the find & replace dialog
- ActionMap aMap = getActionMap();
- Action action = null;
- do {
- action = action == null ? aMap.get(DefaultEditorKit.deletePrevCharAction) : null;
- aMap.remove(DefaultEditorKit.deletePrevCharAction);
- aMap = aMap.getParent();
- } while (aMap != null);
- aMap = getActionMap();
- InputMap iMap = getInputMap();
- KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0, false);
- iMap.put(keyStroke, "delete");
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, KeyEvent.SHIFT_MASK, false);
- iMap.put(keyStroke, "delete");
- aMap.put("delete", action);
-
- // set all the actions
- action = new FindAction();
- aMap.put(FIND, action);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK, false);
- iMap.put(keyStroke, FIND);
-
- aMap.put(FIND_NEXT, FindReplaceUtility.FIND_ACTION);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, false);
- iMap.put(keyStroke, FIND_NEXT);
-
- aMap.put(FIND_PREVIOUS, FindReplaceUtility.FIND_ACTION);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_MASK, false);
- iMap.put(keyStroke, FIND_PREVIOUS);
-
- action = new TabAction();
- aMap.put("TextEditor-tabAction", action);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false);
- iMap.put(keyStroke, "TextEditor-tabAction");
-
- action = new ShiftTabAction();
- aMap.put("TextEditor-shiftTabAction", action);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK, false);
- iMap.put(keyStroke, "TextEditor-shiftTabAction");
-
- action = new ReplaceAction();
- getActionMap().put(REPLACE, action);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK, false);
- do {
- iMap.remove(keyStroke);
- iMap = iMap.getParent();
- } while (iMap != null);
- getInputMap().put(keyStroke, REPLACE);
-
- action = new AutoIndentAction();
- getActionMap().put(AUTO_INDENT, action);
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
- getInputMap().put(keyStroke, AUTO_INDENT);
-
- setAutoscrolls(true);
-
- defaultCaret = getCaret();
- overtypeCaret = new OvertypeCaret();
- overtypeCaret.setBlinkRate(defaultCaret.getBlinkRate());
- }
-
- public void addNotify() {
- super.addNotify();
- addMouseListener(mouseAdapter);
- FindReplaceUtility.registerTextComponent(this);
- }
-
- public int getNumberOfPages() {
- Paper paper = PAGE_FORMAT.getPaper();
- numPages = (int) Math.ceil(getSize().getHeight() / paper.getImageableHeight());
- return numPages;
- }
-
- public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
- return PAGE_FORMAT;
- }
-
- public Printable getPrintable(int param) throws IndexOutOfBoundsException {
- return this;
- }
-
- public int print(Graphics graphics, PageFormat pageFormat, int page)
- throws PrinterException {
- if (page < numPages) {
- Paper paper = pageFormat.getPaper();
-
- // initialize the PRINT_PANE (need this so that wrapping
- // can take place)
- PRINT_PANE.setDocument(getDocument());
-
- PRINT_PANE.setFont(getFont());
- PRINT_SIZE.setSize(paper.getImageableWidth(),
- getSize().getHeight());
- PRINT_PANE.setSize(PRINT_SIZE);
-
- // translate the graphics origin upwards so the area of the page we
- // want to print is in the origin; the clipping region auto set
- // will take care of the rest
- double y = -(page * paper.getImageableHeight()) + paper.getImageableY();
-
- ((Graphics2D) graphics).translate(paper.getImageableX(), y);
-
- // print the text with its own routines
- PRINT_PANE.print(graphics);
-
- // translate the graphics object back to reality in the y dimension
- // so we can print a page number
- ((Graphics2D) graphics).translate(0, -y);
- Rectangle rect = graphics.getClipBounds();
- graphics.setClip(rect.x, 0, rect.width, (int) paper.getHeight() + 100);
-
- // get the name of the pane (or user name) and the time for the header
- Calendar cal = Calendar.getInstance();
- String header = cal.getTime().toString().trim();
- String name = getName() == null ?
- System.getProperty("user.name").trim() : getName().trim();
- String pageStr = String.valueOf(page + 1);
-
- Font font = Font.decode("Monospaced 8");
- graphics.setFont(font);
- FontMetrics fm = graphics.getFontMetrics(font);
- int width = SwingUtilities.computeStringWidth(fm, header);
- ((Graphics2D) graphics).drawString(header,
- (float) (paper.getImageableWidth() / 2 - width / 2),
- (float) paper.getImageableY() / 2 + fm.getHeight());
-
- ((Graphics2D) graphics).translate(0, paper.getImageableY() - fm.getHeight());
- double height = paper.getImageableHeight() + paper.getImageableY() / 2;
- width = SwingUtilities.computeStringWidth(fm, name);
- ((Graphics2D) graphics).drawString(name,
- (float) (paper.getImageableWidth() / 2 - width / 2),
- (float) height - fm.getHeight() / 2);
-
- ((Graphics2D) graphics).translate(0, fm.getHeight());
- width = SwingUtilities.computeStringWidth(fm, pageStr);
- ((Graphics2D) graphics).drawString(pageStr,
- (float) (paper.getImageableWidth() / 2 - width / 2),
- (float) height - fm.getHeight() / 2);
-
- return Printable.PAGE_EXISTS;
- }
- return Printable.NO_SUCH_PAGE;
- }
-
- public boolean getScrollableTracksViewportWidth() {
- boolean bool = super.getScrollableTracksViewportWidth();
- if (unwrapped) {
- Component parent = this.getParent();
- ComponentUI ui = this.getUI();
- int uiWidth = ui.getPreferredSize(this).width;
- bool = (parent == null) || (uiWidth < parent.getSize().width);
- }
- return bool;
- }
-
- /**
- * Whether using the tab key indents the selected lines of code
- *
- * @return true if multiline tabbing is active
- */
- public boolean isMultiLineTabbed() {
- return multiLineTab;
- }
-
- /**
- * @return true if overtype mode is active, false for insert mode
- */
- public static boolean isOvertypeMode() {
- return isOvertypeMode;
- }
-
- /**
- * @return true if tabs are converted to spaces upon typing
- */
- public boolean isTabsAsSpaces() {
- return tabsAsSpaces;
- }
-
- /**
- * @return true if text wrapping is disabled
- */
- public boolean isUnwrapped() {
- return unwrapped;
- }
-
- protected void processKeyEvent(KeyEvent e) {
- super.processKeyEvent(e);
-
- // Handle release of Insert key to toggle overtype/insert mode
- // unless a modifier is active (eg Shift+Insert for paste or
- // Ctrl+Insert for Copy)
- if (e.getID() == KeyEvent.KEY_RELEASED &&
- e.getKeyCode() == KeyEvent.VK_INSERT &&
- e.getModifiersEx() == 0) {
- setOvertypeMode(!isOvertypeMode());
- }
- }
-
- public void removeNotify() {
- super.removeNotify();
- removeMouseListener(mouseAdapter);
- FindReplaceUtility.unregisterTextComponent(this);
- }
-
- public void replaceSelection(String text) {
- // Implement overtype mode by selecting the character at the current
- // caret position
- if (isOvertypeMode()) {
- int pos = getCaretPosition();
- if (getSelectedText() == null && pos < getDocument().getLength()) {
- moveCaretPosition(pos + 1);
- }
- }
- super.replaceSelection(text);
- }
-
- public void setBounds(int x, int y, int width, int height) {
- if (unwrapped) {
- Dimension size = this.getPreferredSize();
- super.setBounds(x, y,
- Math.max(size.width, width),
- Math.max(size.height, height));
- } else {
- super.setBounds(x, y, width, height);
- }
- }
-
- /**
- * @param multiLineTab the new multiLine tab value
- */
- public void isMultiLineTabbed(boolean multiLineTab) {
- this.multiLineTab = multiLineTab;
- }
-
- /**
- * @param tabsAsSpaces whether tabs are converted to spaces
- */
- public void isTabsAsSpaces(boolean tabsAsSpaces) {
- this.tabsAsSpaces = tabsAsSpaces;
- }
-
- /**
- * Set the caret to use depending on overtype/insert mode
- *
- * @param isOvertypeMode the new mode; true = overtype
- */
- public void setOvertypeMode(boolean isOvertypeMode) {
- TextEditor.isOvertypeMode = isOvertypeMode;
- int pos = getCaretPosition();
- setCaret(isOvertypeMode() ? overtypeCaret : defaultCaret);
- setCaretPosition(pos);
- }
-
- /**
- * @param unwrapped the new unwrapped value
- */
- public void setUnwrapped(boolean unwrapped) {
- this.unwrapped = unwrapped;
- }
-
- private static class FindAction extends AbstractAction {
- public void actionPerformed(ActionEvent ae) {
- FindReplaceUtility.showDialog();
- }
- }
-
- private static class ReplaceAction extends AbstractAction {
- public void actionPerformed(ActionEvent ae) {
- FindReplaceUtility.showDialog(true);
- }
- }
-
- private class ShiftTabAction extends AbstractAction {
- public void actionPerformed(ActionEvent ae) {
- try {
- if (multiLineTab && TextEditor.this.getSelectedText() != null) {
- int end = Utilities.getRowEnd(TextEditor.this, getSelectionEnd());
- TextEditor.this.setSelectionEnd(end);
-
- Element el = Utilities.getParagraphElement(TextEditor.this, getSelectionStart());
- int start = el.getStartOffset();
- TextEditor.this.setSelectionStart(start);
-
- // remove text and reselect the text
- String text = tabsAsSpaces ?
- TAB_BACK_PATTERN.matcher(getSelectedText()).replaceAll("") :
- getSelectedText().replaceAll("^\t", "");
-
- TextEditor.this.replaceSelection(text);
-
- TextEditor.this.select(start, start + text.length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- private class TabAction extends AbstractAction {
- public void actionPerformed(ActionEvent ae) {
- try {
- Document doc = TextEditor.this.getDocument();
- String text = tabsAsSpaces ? TABBED_SPACES : "\t";
- if (multiLineTab && getSelectedText() != null) {
- int end = Utilities.getRowEnd(TextEditor.this, getSelectionEnd());
- TextEditor.this.setSelectionEnd(end);
-
- Element el = Utilities.getParagraphElement(TextEditor.this, getSelectionStart());
- int start = el.getStartOffset();
- TextEditor.this.setSelectionStart(start);
-
- String toReplace = TextEditor.this.getSelectedText();
- toReplace = LINE_START.matcher(toReplace).replaceAll(text);
- TextEditor.this.replaceSelection(toReplace);
- TextEditor.this.select(start, start + toReplace.length());
- } else {
- int pos = TextEditor.this.getCaretPosition();
- doc.insertString(pos, text, null);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Paint a horizontal line the width of a column and 1 pixel high
- */
- private static class OvertypeCaret extends DefaultCaret {
- //The overtype caret will simply be a horizontal line one pixel high
- // (once we determine where to paint it)
- public void paint(Graphics g) {
- if (isVisible()) {
- try {
- JTextComponent component = getComponent();
- Rectangle r = component.getUI().modelToView(component, getDot());
- Color c = g.getColor();
- g.setColor(component.getBackground());
- g.setXORMode(component.getCaretColor());
- r.setBounds(r.x, r.y,
- g.getFontMetrics().charWidth('w'),
- g.getFontMetrics().getHeight());
- g.fillRect(r.x, r.y, r.width, r.height);
- g.setPaintMode();
- g.setColor(c);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
-
- /*
- * Damage must be overridden whenever the paint method is overridden
- * (The damaged area is the area the caret is painted in. We must
- * consider the area for the default caret and this caret)
- */
- protected synchronized void damage(Rectangle r) {
- if (r != null) {
- JTextComponent component = getComponent();
- x = r.x;
- y = r.y;
- Font font = component.getFont();
- width = component.getFontMetrics(font).charWidth('w');
- height = r.height;
- repaint();
- }
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextUndoManager.java b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextUndoManager.java
deleted file mode 100644
index 4a32300..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/TextUndoManager.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.text;
-
-import javax.swing.event.SwingPropertyChangeSupport;
-import javax.swing.event.UndoableEditEvent;
-import javax.swing.undo.CompoundEdit;
-import javax.swing.undo.UndoManager;
-import javax.swing.undo.UndoableEdit;
-import java.beans.PropertyChangeListener;
-
-/**
- * To use this, simply drop this as an UndoableEditListener into your document,
- * and then create actions to call undo/redo as needed (checking can undo/redo
- * first, of course).
- */
-@Deprecated
-public class TextUndoManager extends UndoManager {
-
- private SwingPropertyChangeSupport propChangeSupport =
- new SwingPropertyChangeSupport(this);
-
- private StructuredEdit compoundEdit = new StructuredEdit();
-
- private long firstModified;
-
- private UndoableEdit modificationMarker = editToBeUndone();
-
- /**
- * Creates a new instance of TextUndoManager.
- */
- public TextUndoManager() {
- }
-
- public void addPropertyChangeListener(PropertyChangeListener pcl) {
- propChangeSupport.addPropertyChangeListener(pcl);
- }
-
- public void die() {
- boolean undoable = canUndo();
- super.die();
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
- }
-
- public void discardAllEdits() {
- boolean undoable = canUndo();
- boolean redoable = canRedo();
-
- boolean changed = hasChanged();
- super.discardAllEdits();
- modificationMarker = editToBeUndone();
-
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
- firePropertyChangeEvent(UndoManager.UndoName, redoable, canRedo());
- }
-
- protected void firePropertyChangeEvent(String name,
- boolean oldValue,
- boolean newValue) {
- propChangeSupport.firePropertyChange(name, oldValue, newValue);
- }
-
- public boolean hasChanged() {
- return modificationMarker != editToBeUndone();
- }
-
- public void redo() throws javax.swing.undo.CannotRedoException {
- compoundEdit.end();
-
- if (firstModified == 0) {
- firstModified = ((StructuredEdit) editToBeRedone()).editedTime();
- }
-
- boolean undoable = canUndo();
-
- boolean changed = hasChanged();
- super.redo();
-
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
- }
-
- protected void redoTo(UndoableEdit edit) {
- compoundEdit.end();
-
- if (firstModified == 0) {
- firstModified = ((StructuredEdit) editToBeRedone()).editedTime();
- }
-
- boolean undoable = canUndo();
-
- boolean changed = hasChanged();
- super.redoTo(edit);
-
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
-
- }
-
- public void removePropertyChangeListener(PropertyChangeListener pcl) {
- propChangeSupport.removePropertyChangeListener(pcl);
- }
-
- public void reset() {
- boolean changed = modificationMarker != editToBeUndone();
- if (changed) {
- modificationMarker = editToBeUndone();
- }
- }
-
- protected void trimEdits(int from, int to) {
- boolean undoable = canUndo();
- boolean redoable = canRedo();
-
- boolean changed = hasChanged();
- super.trimEdits(from, to);
-
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
- firePropertyChangeEvent(UndoManager.RedoName, redoable, canRedo());
- }
-
- public void undo() throws javax.swing.undo.CannotUndoException {
- compoundEdit.end();
-
- UndoableEdit edit = editToBeUndone();
- if (((StructuredEdit) editToBeUndone()).editedTime() ==
- firstModified) {
- firstModified = 0;
- } else if (firstModified == 0) {
- firstModified = ((StructuredEdit) editToBeUndone()).editedTime();
- }
-
- boolean redoable = canRedo();
- boolean changed = hasChanged();
- super.undo();
- firePropertyChangeEvent(UndoManager.RedoName, redoable, canRedo());
- }
-
- public void undoableEditHappened(UndoableEditEvent uee) {
- UndoableEdit edit = uee.getEdit();
- boolean undoable = canUndo();
-
- long editTime = System.currentTimeMillis();
-
- if (firstModified == 0 ||
- editTime - compoundEdit.editedTime() > 700) {
- compoundEdit.end();
- compoundEdit = new StructuredEdit();
- }
- compoundEdit.addEdit(edit);
-
- firstModified = firstModified == 0 ?
- compoundEdit.editedTime() : firstModified;
-
- if (lastEdit() != compoundEdit) {
- boolean changed = hasChanged();
- addEdit(compoundEdit);
- firePropertyChangeEvent(UndoManager.UndoName, undoable, canUndo());
- }
-
- }
-
- private static class StructuredEdit extends CompoundEdit {
-
- private long editedTime;
-
- public boolean addEdit(UndoableEdit edit) {
- boolean result = super.addEdit(edit);
- if (result && editedTime == 0) {
- editedTime = System.currentTimeMillis();
- }
- return result;
- }
-
- public boolean canUndo() {
- return !edits.isEmpty();
- }
-
- protected long editedTime() {
- return editedTime;
- }
-
- public boolean isInProgress() {
- return false;
- }
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/package.html b/subprojects/groovy-console/src/main/groovy/groovy/ui/text/package.html
deleted file mode 100644
index 390544d..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/text/package.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-<html>
- <head>
- <title>package groovy.ui.text.*</title>
- </head>
- <body>
- <p>Text processing helpers for the interactive command line terminal.</p>
- </body>
-</html>
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicContentPane.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicContentPane.groovy
deleted file mode 100644
index d7794b8..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicContentPane.groovy
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.view
-
-import groovy.ui.Console
-import groovy.ui.ConsoleTextEditor
-import groovy.ui.text.SmartDocumentFilter
-
-import javax.swing.JSplitPane
-import javax.swing.WindowConstants
-import javax.swing.text.Style
-import javax.swing.text.StyleConstants
-import javax.swing.text.StyleContext
-import javax.swing.text.StyledDocument
-import java.awt.BorderLayout
-import java.awt.Color
-import java.awt.Dimension
-import java.awt.Font
-import java.awt.FontMetrics
-import java.awt.Graphics
-import java.awt.GraphicsEnvironment
-import java.awt.image.BufferedImage
-import java.util.prefs.Preferences
-
-import static javax.swing.JSplitPane.HORIZONTAL_SPLIT
-import static javax.swing.JSplitPane.VERTICAL_SPLIT
-
-Preferences prefs = Preferences.userNodeForPackage(Console)
-def detachedOutputFlag = prefs.getBoolean('detachedOutput', false)
-outputWindow = frame(visible:false, defaultCloseOperation: WindowConstants.HIDE_ON_CLOSE) {
- blank = glue()
- blank.preferredSize = [0, 0] as Dimension
-}
-splitPane = splitPane(resizeWeight: 0.5, orientation:
- prefs.getBoolean('orientationVertical', true) ? VERTICAL_SPLIT : HORIZONTAL_SPLIT) {
- def editor = new ConsoleTextEditor()
- boolean smartHighlighterEnabled = Console.smartHighlighter
- if (smartHighlighterEnabled) {
- editor.enableHighLighter(SmartDocumentFilter)
- }
- inputEditor = widget(editor, border:emptyBorder(0))
- buildOutputArea(prefs)
-}
-
-private def buildOutputArea(prefs) {
- scrollArea = scrollPane(border: emptyBorder(0)) {
- outputArea = textPane(
- editable: false,
- name: 'outputArea',
- contentType: 'text/html',
- background: new Color(255, 255, 218),
- font: new Font('Monospaced', Font.PLAIN, prefs.getInt('fontSize', 12)),
- border: emptyBorder(4)
- )
- }
-}
-
-
-inputArea = inputEditor.textEditor
-// attach ctrl-enter to input area
-// need to wrap in actions to keep it from being added as a component
-actions {
- container(inputArea, name: 'inputArea', font:new Font('Monospaced', Font.PLAIN, prefs.getInt('fontSize', 12)), border:emptyBorder(4)) {
- action(runAction)
- action(runSelectionAction)
- action(showOutputWindowAction)
- }
- container(outputArea, name: 'outputArea') {
- action(hideOutputWindowAction1)
- action(hideOutputWindowAction2)
- action(hideOutputWindowAction3)
- action(hideOutputWindowAction4)
- }
-}
-
-// add styles to the output area, should this be moved into SwingBuilder somehow?
-outputArea.font = new Font('Monospaced', outputArea.font.style, outputArea.font.size)
-StyledDocument doc = outputArea.styledDocument
-
-Style defStyle = StyleContext.defaultStyleContext.getStyle(StyleContext.DEFAULT_STYLE)
-
-def applyStyle = {Style style, values -> values.each{k, v -> style.addAttribute(k, v)}}
-
-Style regular = doc.addStyle('regular', defStyle)
-applyStyle(regular, styles.regular)
-
-promptStyle = doc.addStyle('prompt', regular)
-applyStyle(promptStyle, styles.prompt)
-
-commandStyle = doc.addStyle('command', regular)
-applyStyle(commandStyle, styles.command)
-
-outputStyle = doc.addStyle('output', regular)
-applyStyle(outputStyle, styles.output)
-
-resultStyle = doc.addStyle('result', regular)
-applyStyle(resultStyle, styles.result)
-
-stacktraceStyle = doc.addStyle('stacktrace', regular)
-applyStyle(stacktraceStyle, styles.stacktrace)
-
-hyperlinkStyle = doc.addStyle('hyperlink', regular)
-applyStyle(hyperlinkStyle, styles.hyperlink)
-
-// redo styles for editor
-doc = inputArea.styledDocument
-StyleContext styleContext = StyleContext.defaultStyleContext
-styles.each {styleName, defs ->
- Style style = styleContext.getStyle(styleName)
- if (style) {
- applyStyle(style, defs)
- String family = defs[StyleConstants.FontFamily]
- if (style.name == 'default' && family) {
- inputEditor.defaultFamily = family
- inputArea.font = new Font(family, Font.PLAIN, inputArea.font.size)
- }
- }
-}
-
-// set the preferred size of the input and output areas
-// this is a good enough solution, there are margins and scrollbars and such to worry about for 80x12x2
-Graphics g = GraphicsEnvironment.localGraphicsEnvironment.createGraphics (new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB))
-FontMetrics fm = g.getFontMetrics(outputArea.font)
-
-outputArea.preferredSize = [
- prefs.getInt('outputAreaWidth', fm.charWidth(0x77) * 81),
- prefs.getInt('outputAreaHeight', (fm.getHeight() + fm.getLeading()) * 12)
-] as Dimension
-
-inputEditor.preferredSize = [
- prefs.getInt('inputAreaWidth', fm.charWidth(0x77) * 81),
- prefs.getInt('inputAreaHeight', (fm.getHeight() + fm.getLeading()) * 12)
-] as Dimension
-
-origDividerSize = -1
-if (detachedOutputFlag) {
- splitPane.add(blank, JSplitPane.BOTTOM)
- origDividerSize = splitPane.dividerSize
- splitPane.dividerSize = 0
- splitPane.resizeWeight = 1.0
- outputWindow.add(scrollArea, BorderLayout.CENTER)
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicMenuBar.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicMenuBar.groovy
deleted file mode 100644
index 737c4a1..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicMenuBar.groovy
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.view
-
-menuBar {
- menu(text: 'File', mnemonic: 'F') {
- menuItem(newFileAction)
- menuItem(newWindowAction)
- menuItem(openAction)
- separator()
- menuItem(saveAction)
- menuItem(saveAsAction)
- separator()
- menuItem(printAction)
- separator()
- menuItem(exitAction)
- }
-
- menu(text: 'Edit', mnemonic: 'E') {
- menuItem(undoAction)
- menuItem(redoAction)
- separator()
- menuItem(cutAction)
- menuItem(copyAction)
- menuItem(pasteAction)
- separator()
- menuItem(findAction)
- menuItem(findNextAction)
- menuItem(findPreviousAction)
- menuItem(replaceAction)
- separator()
- menuItem(selectAllAction)
- separator()
- menuItem(commentAction)
- menuItem(selectBlockAction)
- separator()
- menuItem(preferencesAction)
- }
-
- menu(text: 'View', mnemonic: 'V') {
- menuItem(clearOutputAction)
- separator()
- menuItem(largerFontAction)
- menuItem(smallerFontAction)
- checkBoxMenuItem(smartHighlighterAction, selected: controller.smartHighlighter)
- separator()
- checkBoxMenuItem(captureStdOutAction, selected: controller.captureStdOut)
- checkBoxMenuItem(captureStdErrAction, selected: controller.captureStdErr)
- checkBoxMenuItem(fullStackTracesAction, selected: controller.fullStackTraces)
- checkBoxMenuItem(showScriptInOutputAction, selected: controller.showScriptInOutput)
- checkBoxMenuItem(visualizeScriptResultsAction, selected: controller.visualizeScriptResults)
- checkBoxMenuItem(showToolbarAction, selected: controller.showToolbar)
- checkBoxMenuItem(detachedOutputAction, selected: controller.detachedOutput)
- checkBoxMenuItem(autoClearOutputAction, selected: controller.autoClearOutput)
- checkBoxMenuItem(orientationVerticalAction, selected: controller.orientationVertical)
- }
-
- menu(text: 'History', mnemonic: 'I') {
- menuItem(historyPrevAction)
- menuItem(historyNextAction)
- }
-
- menu(text: 'Script', mnemonic: 'S') {
- menuItem(runAction)
- checkBoxMenuItem(saveOnRunAction, selected: controller.saveOnRun)
- menuItem(runSelectionAction)
- checkBoxMenuItem(threadInterruptAction, selected: controller.threadInterrupt)
- menuItem(interruptAction)
- menuItem(compileAction)
- checkBoxMenuItem(indyAction, selected: controller.indy)
- separator()
- menuItem(addClasspathJar)
- menuItem(addClasspathDir)
- menuItem(listClasspath)
- menuItem(clearClassloader)
- separator()
- menuItem(inspectLastAction)
- menuItem(inspectVariablesAction)
- menuItem(inspectAstAction)
- menuItem(inspectTokensAction)
- }
-
- menu(text: 'Help', mnemonic: 'H') {
- menuItem(aboutAction)
- }
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicStatusBar.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicStatusBar.groovy
deleted file mode 100644
index 02048f1..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicStatusBar.groovy
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package groovy.ui.view
-
-import javax.swing.*
-import java.awt.*
-
-statusPanel = panel(constraints: BorderLayout.SOUTH) {
- gridBagLayout()
- separator(gridwidth:GridBagConstraints.REMAINDER, fill:GridBagConstraints.HORIZONTAL)
- status = label("Welcome to Groovy ${GroovySystem.version}.",
- weightx:1.0,
- anchor:GridBagConstraints.WEST,
- fill:GridBagConstraints.HORIZONTAL,
- insets: [1,3,1,3])
- separator(orientation:SwingConstants.VERTICAL, fill:GridBagConstraints.VERTICAL)
- rowNumAndColNum = label('1:1', insets: [1,3,1,3])
-}
diff --git a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicToolBar.groovy b/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicToolBar.groovy
deleted file mode 100644
index 849ca16..0000000
--- a/subprojects/groovy-console/src/main/groovy/groovy/ui/view/BasicToolBar.groovy
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
... 784 lines suppressed ...