sdedic commented on code in PR #9804:
URL: https://github.com/apache/netbeans/pull/9804#discussion_r4813426355


##########
java/jshell.support/src/org/netbeans/modules/jshell/support/ShellSession.java:
##########
@@ -1196,461 +61,68 @@ public static ShellSession get(Document d) {
     }
 
     public static Collection<ShellSession> allSessions() {
-        Collection<Reference<ShellSession>> ll;
+        Collection<ShellSession> res = new ArrayList<>();
         synchronized (allSessions) {
-            ll = allSessions.values();
-        }
-        Collection<ShellSession> res = new ArrayList<>(ll.size());
-        for (Iterator<Reference<ShellSession>> it = ll.iterator(); 
it.hasNext(); ) {
-            Reference<ShellSession> sr = it.next();
-            ShellSession s = sr.get();
-            if (s != null) {
-                res.add(s);
+            for (Iterator<Reference<ShellSession>> it = 
allSessions.values().iterator(); it.hasNext(); ) {
+                Reference<ShellSession> sr = it.next();
+                ShellSession s = sr.get();
+                if (s != null) {
+                    res.add(s);
+                }
             }
         }
         return res;
     }
-    
-    private void addNewline(int offset) {
-        AtomicLockDocument ald = LineDocumentUtils.asRequired(consoleDocument, 
AtomicLockDocument.class);
-        ald.runAtomic(() -> {
-            try {
-                DocumentUtilities.setTypingModification(consoleDocument, 
false);
-                consoleDocument.insertString(offset, "\n", null);
-            } catch (BadLocationException ex) {
-                
-            }
-        });
-    }
 
-    private void clearAndAddNewline(int offset) {
-        AtomicLockDocument ald = LineDocumentUtils.asRequired(consoleDocument, 
AtomicLockDocument.class);
-        ald.runAtomic(() -> {
-            try {
-                DocumentUtilities.setTypingModification(consoleDocument, 
false);
-                consoleDocument.remove(offset, consoleDocument.getLength() - 
offset);
-                consoleDocument.insertString(offset, "\n", null);
-            } catch (BadLocationException ex) {
-                
-            }
-        });
-    }
+    public abstract List<Snippet> getSnippets(boolean onlyUser, boolean 
onlyValid);
+    public abstract SnippetRegistry getSnippetRegistry();
+    public abstract ConsoleModel getModel();
+    public abstract void reportErrorMessage(Throwable t);
+    public abstract void clearInputAndEvaluateExternal(String command, String 
label) throws IOException;
+    public abstract void stopExecutingCode();
+    public abstract Task closeSession();
+    public abstract JShellTool getJShellTool();
+    public abstract String getExecutionLabel();
 
-    private boolean recordNoSave = false;
-    
-    private String executionLabel;
+    public abstract JShell getShell();

Review Comment:
   `getShell()` / `ensureShell()` should be perhaps unified for clients.



##########
java/jshell.support/src/org/netbeans/modules/jshell/support/ShellSession.java:
##########
@@ -1196,461 +61,68 @@ public static ShellSession get(Document d) {
     }
 
     public static Collection<ShellSession> allSessions() {
-        Collection<Reference<ShellSession>> ll;
+        Collection<ShellSession> res = new ArrayList<>();
         synchronized (allSessions) {
-            ll = allSessions.values();
-        }
-        Collection<ShellSession> res = new ArrayList<>(ll.size());
-        for (Iterator<Reference<ShellSession>> it = ll.iterator(); 
it.hasNext(); ) {
-            Reference<ShellSession> sr = it.next();
-            ShellSession s = sr.get();
-            if (s != null) {
-                res.add(s);
+            for (Iterator<Reference<ShellSession>> it = 
allSessions.values().iterator(); it.hasNext(); ) {
+                Reference<ShellSession> sr = it.next();
+                ShellSession s = sr.get();
+                if (s != null) {
+                    res.add(s);
+                }
             }
         }
         return res;
     }
-    
-    private void addNewline(int offset) {
-        AtomicLockDocument ald = LineDocumentUtils.asRequired(consoleDocument, 
AtomicLockDocument.class);
-        ald.runAtomic(() -> {
-            try {
-                DocumentUtilities.setTypingModification(consoleDocument, 
false);
-                consoleDocument.insertString(offset, "\n", null);
-            } catch (BadLocationException ex) {
-                
-            }
-        });
-    }
 
-    private void clearAndAddNewline(int offset) {
-        AtomicLockDocument ald = LineDocumentUtils.asRequired(consoleDocument, 
AtomicLockDocument.class);
-        ald.runAtomic(() -> {
-            try {
-                DocumentUtilities.setTypingModification(consoleDocument, 
false);
-                consoleDocument.remove(offset, consoleDocument.getLength() - 
offset);
-                consoleDocument.insertString(offset, "\n", null);
-            } catch (BadLocationException ex) {
-                
-            }
-        });
-    }
+    public abstract List<Snippet> getSnippets(boolean onlyUser, boolean 
onlyValid);
+    public abstract SnippetRegistry getSnippetRegistry();
+    public abstract ConsoleModel getModel();
+    public abstract void reportErrorMessage(Throwable t);
+    public abstract void clearInputAndEvaluateExternal(String command, String 
label) throws IOException;
+    public abstract void stopExecutingCode();
+    public abstract Task closeSession();
+    public abstract JShellTool getJShellTool();
+    public abstract String getExecutionLabel();
 
-    private boolean recordNoSave = false;
-    
-    private String executionLabel;
+    public abstract JShell getShell();
+    public abstract JShell ensureShell();
+    public abstract boolean isActive();
+    public abstract boolean isValid();
 
-    public String getExecutionLabel() {
-        return executionLabel;
-    }
-    
-    public void evaluate(String command) throws IOException {
-        evaluate(command, false, null);
-    }
-    
-    public void clearInputAndEvaluateExternal(String command, String label) 
throws IOException {
-        // evaluate even though the connection is not active; perhaps
-        // we get access to the history.
-        post(() -> {
-            ConsoleSection s = model.processInputSection(true);
-            if (s == null) {
-                return;
-            }
-            clearAndAddNewline(s.getPartBegin());
-            boolean saveSave = this.recordNoSave;
-            try {
-                recordNoSave = true;
-                this.executionLabel = label;
-                doExecuteCommands(command);
-            } finally {
-                this.executionLabel = null;
-                this.recordNoSave = saveSave;
-            }
-        });
-    }
-    
-    public void evaluate(String command, boolean excludeFromSave, String 
label) throws IOException {
-        // evaluate even though the connection is not active; perhaps
-        // we get access to the history.
-        post(() -> {
-            ConsoleSection s = model.processInputSection(true);
-            if (s == null) {
-                return;
-            }
-            String c = s.getContents(consoleDocument);
-            if (!c.endsWith("\n")) { // NOI18N
-                addNewline(s.getEnd());
-            }
-            boolean saveSave = this.recordNoSave;
-            try {
-                recordNoSave = excludeFromSave;
-                this.executionLabel = label;
-                doExecuteCommands(command);
-            } finally {
-                this.executionLabel = null;
-                this.recordNoSave = saveSave;
-            }
-        });
-    }
+    public abstract void evaluate(String command) throws IOException;
 
-    /**
-     * Executes commands in input buffer. Executes one by one, since some
-     * snippets may be redundant and will not be reported at all by JShell, so
-     * replacement of individual Snippets will be assisted by setting up a
-     * start position of the to-be-executed snippet in the buffer.
-     * <p/>
-     * Since JShell stops executin after first error, a 'erroneous' flag is 
raised
-     * by {@link #acceptSnippet} when it sees a REJECTED snippet (an error).
-     */
-    @NbBundle.Messages({
-        "MSG_ErrorExecutingCommand=Note: You may need to restart the Java 
Shell to resume proper operation",
-        "MSG_JShellCannotExecute=Java Shell cannot execute commands. Restart 
Java Shell or its host process."
-    })
-    private void doExecuteCommands(final String cmd) {
-        ConsoleSection sec = model.processInputSection(true);
-        if (sec == null) {
-            return;
-        }
-        // rely on JShell's own parsing from the input section
-        // just for case:
-        ModelAccessor.INSTANCE.execute(model, cmd != null, () -> {
-            Executor executor = new Executor(cmd, model.getExecutingSection());
-            executor.execute();
-        }, this::getPromptAfterError);
-    }
-    
-    private class Executor implements Runnable, Consumer<SnippetEvent> {
-        private final String          cmd;
-        private final ConsoleSection  exec;
-        
-        private final List<String>    toExec = new ArrayList<>();
-        private boolean         erroneous;
-        private int             execOffset;
+    public abstract void notifyClosed(JShellEnvironment env, boolean remote);

Review Comment:
   I would recommend to somehow 'hide' this callback to some private protocol 
between `ShellSession` implementor and the `JShellEnvironment`. 
   
   It IMHO should not be exposed for potential JShell clients or drivers.



##########
java/jshell.support/src/org/netbeans/modules/jshell/env/ShellSessionImpl.java:
##########
@@ -0,0 +1,1624 @@
+/*
+ * 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 org.netbeans.modules.jshell.env;
+
+import com.sun.jdi.connect.VMStartException;
+import java.beans.PropertyChangeListener;
+import org.netbeans.modules.jshell.tool.JShellLauncher;
+import org.netbeans.modules.jshell.tool.JShellTool;
+import org.netbeans.modules.jshell.parsing.ModelAccessor;
+import org.netbeans.modules.jshell.parsing.LexerEmbeddingAdapter;
+import org.netbeans.modules.jshell.model.Rng;
+import org.netbeans.modules.jshell.model.ConsoleSection;
+import org.netbeans.modules.jshell.model.ConsoleListener;
+import org.netbeans.modules.jshell.model.ConsoleModel;
+import org.netbeans.modules.jshell.model.ConsoleEvent;
+import java.beans.PropertyChangeSupport;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.Writer;
+import java.lang.ref.Reference;
+import java.lang.ref.WeakReference;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.concurrent.Callable;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.prefs.Preferences;
+import java.util.stream.Collectors;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import javax.swing.text.Position;
+import javax.swing.text.StyledDocument;
+import javax.tools.StandardJavaFileManager;
+import org.netbeans.lib.nbjshell.RemoteJShellService;
+import jdk.jshell.JShell;
+import jdk.jshell.JShell.Subscription;
+import org.netbeans.lib.nbjshell.JShellAccessor;
+import jdk.jshell.Snippet;
+import jdk.jshell.SnippetEvent;
+import jdk.jshell.SourceCodeAnalysis;
+import jdk.jshell.spi.ExecutionControl.ExecutionControlException;
+import jdk.jshell.spi.ExecutionControlProvider;
+import org.netbeans.api.editor.document.AtomicLockDocument;
+import org.netbeans.api.editor.document.LineDocument;
+import org.netbeans.api.editor.document.LineDocumentUtils;
+import org.netbeans.api.editor.guards.GuardedSection;
+import org.netbeans.api.editor.guards.GuardedSectionManager;
+import org.netbeans.api.java.classpath.ClassPath;
+import org.netbeans.api.java.classpath.GlobalPathRegistry;
+import org.netbeans.api.java.platform.JavaPlatform;
+import org.netbeans.api.java.source.ClasspathInfo;
+import org.netbeans.api.java.source.ClasspathInfo.PathKind;
+import org.netbeans.api.project.Project;
+import org.netbeans.api.project.ProjectUtils;
+import org.netbeans.lib.editor.util.swing.DocumentUtilities;
+import org.netbeans.lib.nbjshell.NbExecutionControl;
+import org.netbeans.modules.jshell.model.ConsoleContents;
+import org.netbeans.modules.jshell.model.SnippetHandle;
+import org.netbeans.modules.jshell.parsing.ShellAccessBridge;
+import org.netbeans.modules.jshell.parsing.SnippetRegistry;
+import org.netbeans.modules.jshell.project.ShellProjectUtils;
+import org.netbeans.modules.jshell.support.ShellHistory;
+import org.netbeans.modules.jshell.support.ShellHistory.Item;
+import org.netbeans.modules.jshell.support.ShellSession;
+import org.netbeans.modules.parsing.api.ParserManager;
+import org.netbeans.modules.parsing.api.ResultIterator;
+import org.netbeans.modules.parsing.api.Source;
+import org.netbeans.modules.parsing.api.UserTask;
+import org.netbeans.modules.parsing.api.indexing.IndexingManager;
+import org.netbeans.modules.parsing.spi.ParseException;
+import org.netbeans.spi.editor.guards.GuardedEditorSupport;
+import org.netbeans.spi.editor.guards.support.AbstractGuardedSectionsProvider;
+import org.netbeans.spi.java.classpath.support.ClassPathSupport;
+import org.openide.cookies.EditorCookie;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.FileUtil;
+import org.openide.filesystems.URLMapper;
+import org.openide.modules.InstalledFileLocator;
+import org.openide.modules.SpecificationVersion;
+import org.openide.util.Exceptions;
+import org.openide.util.NbBundle;
+import org.openide.util.NbPreferences;
+import org.openide.util.Pair;
+import org.openide.util.RequestProcessor;
+import org.openide.util.Task;
+
+import static org.netbeans.modules.jshell.tool.JShellLauncher.quote;
+
+/**
+ * The root object for any JShell session. A shell session consists of:
+ * <ul>
+ * <li>a Document, viewed by an editor
+ * <li>an output window, where the JShell prints the results
+ * <li>the JShell instance itself
+ * <li>a process handle to the running target VM
+ * <li>transient FileSystem where the sources for parsing are created
+ * <li>ConsoleModel which divides the Document and maps JShell snippets to
+ * document parts.
+ * </ul>
+ * <p/>
+ * <b>Threading model:</b> The JShell executes single-threaded, so <b>all 
accesses</b>
+ * to JShell must be serialized using {@link #post(java.lang.Runnable)}. The 
getter
+ * for JShell asserts when accessed from outside such Runnable - do not abuse.
+ * <p/>
+ *
+ * @author sdedic
+ */
+final class ShellSessionImpl extends ShellSession {
+    private static final Logger LOG = 
Logger.getLogger(ShellSession.class.getName());
+
+    /**
+     * Work root, contains console file and snippet files
+     */
+    private final FileObject      workRoot;
+
+    /**
+     * The document being operated upon
+     */
+    private final Document  consoleDocument;
+
+    /**
+     * The java platform and projectInfo may possibly change.
+     */
+    private final JavaPlatform    platform;
+
+    /**
+     * ClasspathInfo as set up by the Project
+     */
+    private final ClasspathInfo   projectInfo;
+
+    private ClasspathInfo cpInfo;
+
+    /**
+     * The executing JShell
+     */
+    private JShell shell;
+
+    private ConsoleModel    model;
+
+    /**
+     * The shell output stream, possibly null.
+     * Will be initialized during startup
+     */
+    private PrintStream shellControlOutput;
+
+    private String  displayName;
+
+    /**
+     * True, if the operation of Shell is closed. Closed ShellSession
+     * should not receive anything from the JShell. Detached ShellSession
+     * MAY receive something, but should not reflect it in the document.
+     */
+    private volatile boolean ignoreClose;
+
+    private FileObject consoleFile;
+    private JShellEnvironment env;
+    private final FileSystem  editorSnippetsFileSystem;
+    private final FileObject editorWorkRoot;
+
+    private volatile Set<Snippet>    initialSetupSnippets = 
Collections.emptySet();
+
+    /**
+     * True, if the Session was detached from the document. Another session
+     * now 'owns' the document. The flag cannot be reset back to false.
+     */
+    private volatile boolean detached;
+
+    private static final RequestProcessor FORCE_CLOSE_RP = new 
RequestProcessor("JShell socket closer");
+
+    /**
+     * Mapps snippets to the timestamps of their snippet files. Only valid 
snippets will
+     */
+    private final Map<Snippet, Long>    snippetTimeStamps = new 
WeakHashMap<>();
+
+    private final PropertyChangeSupport propSupport = new 
PropertyChangeSupport(this);
+
+    // @GuardedBy(this)
+    private SnippetRegistry     snippetRegistry;
+
+    private ShellSessionImpl(JShellEnvironment env) {
+        this(env.getDisplayName(),
+             env.getConsoleDocument(),
+             env.getClasspathInfo(),
+             env.getPlatform(),
+             env.getWorkRoot(),
+             env.getConsoleFile());
+        this.env = env;
+    }
+
+    public JShellEnvironment getEnv() {
+        return env;
+    }
+
+    @Override
+    public Project getProject() {
+        return getEnv().getProject();
+    }
+
+    private ShellSessionImpl(String displayName, Document doc, ClasspathInfo 
cpInfo,
+            JavaPlatform platform, FileObject workRoot, FileObject 
consoleFile) {
+        this.consoleDocument = doc;
+        this.projectInfo = cpInfo;
+        this.displayName = displayName;
+        this.platform = platform;
+        this.consoleFile = consoleFile;
+        this.workRoot = workRoot;
+
+        this.editorSnippetsFileSystem = FileUtil.createMemoryFileSystem();
+        this.editorWorkRoot = editorSnippetsFileSystem.getRoot();
+        this.shellControlOutput = new PrintStream(
+            new WriterOutputStream(
+                    // delegate to whatever Writer will be set
+                    new Writer() {
+                        @Override
+                        public void write(char[] cbuf, int off, int len) 
throws IOException {
+                            documentWriter.write(cbuf, off, len);
+                        }
+
+                        @Override
+                        public void flush() throws IOException {
+                            documentWriter.flush();
+                        }
+
+                        @Override
+                        public void close() throws IOException {
+                            documentWriter.close();
+                        }
+
+                    })
+        );
+    }
+
+    static ShellSessionImpl createSession(JShellEnvironment env) {
+        return new ShellSessionImpl(env);
+    }
+
+    public void addPropertyChangeListener(PropertyChangeListener pcl) {
+        propSupport.addPropertyChangeListener(pcl);
+    }
+
+    public void removePropertyChangeListener(PropertyChangeListener pcl) {
+        propSupport.removePropertyChangeListener(pcl);
+    }
+
+    public boolean isActive() {
+        return !detached;
+    }
+
+    private Task detach() {
+        Task t;
+        if (get(consoleDocument) == this) {
+            new ShellSessionImpl(null).associateWith(consoleDocument);

Review Comment:
   IMHO the ShellSessionImpl more or less assumes `env != null` - though most 
of method that use it execute during startup of JShell; some dummy 
`JShellEnvironment` implementation might be safer



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to