lahodaj commented on code in PR #8019:
URL: https://github.com/apache/netbeans/pull/8019#discussion_r2095126949


##########
java/debugger.jpda.ui/src/org/netbeans/modules/debugger/jpda/ui/models/InlineValueComputerImpl.java:
##########
@@ -0,0 +1,477 @@
+/*
+ * 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.debugger.jpda.ui.models;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.prefs.PreferenceChangeEvent;
+import java.util.prefs.PreferenceChangeListener;
+import java.util.prefs.Preferences;
+import java.util.stream.Collectors;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.Document;
+import org.netbeans.api.debugger.DebuggerManagerAdapter;
+import org.netbeans.api.debugger.LazyDebuggerManagerListener;
+import org.netbeans.api.debugger.Session;
+import org.netbeans.api.debugger.jpda.CallStackFrame;
+import org.netbeans.api.debugger.jpda.InvalidExpressionException;
+import org.netbeans.api.debugger.jpda.JPDAClassType;
+import org.netbeans.api.debugger.jpda.JPDADebugger;
+import org.netbeans.api.debugger.jpda.ObjectVariable;
+import org.netbeans.api.debugger.jpda.Variable;
+import org.netbeans.api.editor.mimelookup.MimeLookup;
+import org.netbeans.api.editor.mimelookup.MimeRegistration;
+import org.netbeans.api.editor.settings.AttributesUtilities;
+import org.netbeans.api.java.source.CancellableTask;
+import org.netbeans.api.java.source.CompilationInfo;
+import org.netbeans.api.java.source.JavaSource.Phase;
+import org.netbeans.api.java.source.JavaSource.Priority;
+import org.netbeans.api.java.source.JavaSourceTaskFactory;
+import org.netbeans.modules.debugger.jpda.JPDADebuggerImpl;
+import org.netbeans.modules.debugger.jpda.expr.formatters.Formatters;
+import 
org.netbeans.modules.debugger.jpda.expr.formatters.FormattersLoopControl;
+import org.netbeans.modules.debugger.jpda.expr.formatters.VariablesFormatter;
+import org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper;
+import 
org.netbeans.modules.debugger.jpda.jdi.InvalidStackFrameExceptionWrapper;
+import org.netbeans.modules.debugger.jpda.jdi.ObjectCollectedExceptionWrapper;
+import org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper;
+import org.netbeans.modules.debugger.jpda.ui.values.ComputeInlineValues;
+import 
org.netbeans.modules.debugger.jpda.ui.values.ComputeInlineValues.InlineVariable;
+import org.netbeans.modules.parsing.spi.TaskIndexingMode;
+import org.netbeans.spi.debugger.ContextProvider;
+import org.netbeans.spi.debugger.DebuggerServiceRegistration;
+import org.netbeans.spi.debugger.ui.Constants;
+import org.netbeans.spi.editor.highlighting.HighlightsLayer;
+import org.netbeans.spi.editor.highlighting.HighlightsLayerFactory;
+import org.netbeans.spi.editor.highlighting.HighlightsSequence;
+import org.netbeans.spi.editor.highlighting.ZOrder;
+import org.netbeans.spi.editor.highlighting.support.OffsetsBag;
+import org.openide.cookies.EditorCookie;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.URLMapper;
+import org.openide.util.Exceptions;
+import org.openide.util.Lookup;
+import org.openide.util.RequestProcessor;
+import org.openide.util.WeakListeners;
+import org.openide.util.lookup.ServiceProvider;
+import org.openide.util.lookup.ServiceProviders;
+
+
+@DebuggerServiceRegistration(path="netbeans-JPDASession/inlineValue", 
types=InlineValueComputer.class)
+public class InlineValueComputerImpl implements InlineValueComputer, 
PreferenceChangeListener, PropertyChangeListener {
+
+    private static final Logger LOG = 
Logger.getLogger(InlineValueComputerImpl.class.getName());
+    private static final RequestProcessor EVALUATOR = new 
RequestProcessor(InlineValueComputerImpl.class.getName(), 1, false, false);
+    private static final String JAVA_STRATUM = "Java"; //XXX: this is probably 
already defined somewhere
+    private final JPDADebuggerImpl debugger;
+    private final Preferences prefs;
+    private TaskDescription currentTask;
+
+    public InlineValueComputerImpl(ContextProvider contextProvider) {
+        debugger = (JPDADebuggerImpl) contextProvider.lookupFirst(null, 
JPDADebugger.class);
+        debugger.addPropertyChangeListener(this);
+        prefs = MimeLookup.getLookup("text/x-java").lookup(Preferences.class);
+        
prefs.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class,
 this, prefs));
+    }
+
+    @Override
+    public void propertyChange(PropertyChangeEvent evt) {
+        if (JPDADebugger.PROP_STATE.equals(evt.getPropertyName()) &&
+            debugger.getState() == JPDADebugger.STATE_DISCONNECTED) {
+            setNewTask(null);
+        }
+
+        if 
(JPDADebugger.PROP_CURRENT_CALL_STACK_FRAME.equals(evt.getPropertyName())) {
+            refreshVariables();
+        }
+    }
+
+    @Override
+    public void preferenceChange(PreferenceChangeEvent evt) {
+        refreshVariables();
+    }
+
+    private void refreshVariables() {
+        CallStackFrame frame = debugger.getCurrentCallStackFrame();
+
+        FileObject frameFile = null;
+        int frameLineNumber = -1;
+        Document frameDocument = null;
+
+        if (prefs.getBoolean(Constants.KEY_INLINE_VALUES, 
Constants.DEF_INLINE_VALUES) &&
+            frame != null && !frame.isObsolete() &&
+            frame.getThread().isSuspended() &&
+            JAVA_STRATUM.equals(frame.getDefaultStratum())) {
+            try {
+                String url = debugger.getEngineContext().getURL(frame, 
JAVA_STRATUM);
+                frameFile = url != null ? 
URLMapper.findFileObject(URI.create(url).toURL()) : null;
+                if (frameFile != null) {
+                    frameLineNumber = frame.getLineNumber(JAVA_STRATUM);
+                    EditorCookie ec = 
frameFile.getLookup().lookup(EditorCookie.class);
+                    frameDocument = ec != null ? ec.getDocument() : null;
+                }
+            } catch (InternalExceptionWrapper | 
InvalidStackFrameExceptionWrapper | ObjectCollectedExceptionWrapper | 
VMDisconnectedExceptionWrapper | MalformedURLException ex) {
+                Exceptions.printStackTrace(ex);
+            }
+        }
+
+        TaskDescription newTask;
+
+        if (frameFile != null && frameDocument != null) {
+            newTask = new TaskDescription(frameFile, frameLineNumber, 
frameDocument);
+        } else {
+            newTask = null;
+        }
+
+        if (setNewTask(newTask)) {
+            return;
+        }
+
+        if (newTask != null) {
+            //TODO: cancel any already running computation if the 
configuration is different:
+            CountDownLatch computationDone = new CountDownLatch(1);
+
+            newTask.addCancelCallback(computationDone::countDown);
+
+            AtomicReference<Collection<InlineVariable>> values = new 
AtomicReference<>();
+
+            EVALUATOR.post(() -> {
+                OffsetsBag runningBag = new OffsetsBag(newTask.frameDocument);
+
+                
Lookup.getDefault().lookup(ComputeInlineVariablesFactory.class).set(newTask.frameFile,
 newTask.frameLineNumber, variables -> {
+                    values.set(variables);
+                    computationDone.countDown();
+                });
+
+                try {
+                    computationDone.await();
+                } catch (InterruptedException ex) {
+                    Exceptions.printStackTrace(ex);
+                }
+
+                if (newTask.isCancelled()) {
+                    return ;
+                }
+
+                Collection<InlineVariable> variables = values.get();
+
+                if (values == null) {
+                    return ;
+                }
+
+                Map<String, Variable> expression2Value = new HashMap<>();
+                Map<Integer, Map<String, String>> line2Values = new 
HashMap<>();
+
+                for (InlineVariable v : variables) {
+                    if (newTask.isCancelled()) {
+                        return ;
+                    }
+
+                    Variable value = 
expression2Value.computeIfAbsent(v.expression, expr -> {
+                        try {
+                            return debugger.evaluate(expr);
+                        } catch (InvalidExpressionException ex) {
+                            //the variable may not exist
+                            LOG.log(Level.FINE, null, ex);
+                            return null;
+                        }
+                    });
+                    if (value != null) {
+                        String valueText;
+                        if (value instanceof ObjectVariable ov) {
+                            valueText = toValue(ov).replace("\n", "\\n");
+                        } else {
+                            valueText = value.getValue();
+                        }
+                        line2Values.computeIfAbsent(v.lineEnd, __ -> new 
LinkedHashMap<>())
+                                   .putIfAbsent(v.expression, v.expression + " 
= " + valueText);
+                        String mergedValues = 
line2Values.get(v.lineEnd).values().stream().collect(Collectors.joining(", ", " 
 ", ""));
+                        AttributeSet attrs = 
AttributesUtilities.createImmutable("virtual-text-prepend", mergedValues);
+
+                        runningBag.addHighlight(v.lineEnd, v.lineEnd + 1, 
attrs);
+
+                        setHighlights(newTask, runningBag);
+                    }
+                }
+            });
+        }
+    }
+
+    private String toValue(ObjectVariable variable) {
+        //mostly copied from the VariablesFormatterFilter.getValueAt:
+        FormattersLoopControl formattersLoop = new FormattersLoopControl();
+        String type = variable.getType ();
+        ObjectVariable ov = (ObjectVariable) variable;
+        JPDAClassType ct = ov.getClassType();
+        if (ct == null) {
+            return ov.getValue();
+        }
+        VariablesFormatter f = Formatters.getFormatterForType(ct, 
formattersLoop.getFormatters());
+        String[] formattersInLoopRef = new String[] { null };
+        if (f != null && formattersLoop.canUse(f, ct.getName(), 
formattersInLoopRef)) {
+            String code = f.getValueFormatCode();
+            if (code != null && code.length() > 0) {
+                try {
+                    java.lang.reflect.Method evaluateMethod = 
ov.getClass().getMethod("evaluate", String.class);
+                    evaluateMethod.setAccessible(true);
+                    Variable ret = (Variable) evaluateMethod.invoke(ov, code);
+                    if (ret == null) {
+                        return null;
+                    }
+                    return ret.getValue();
+                } catch (java.lang.reflect.InvocationTargetException itex) {
+                    Throwable t = itex.getTargetException();
+                    if (t instanceof InvalidExpressionException) {
+                        return ov.getValue();
+                    } else {
+                        Exceptions.printStackTrace(t);
+                    }
+                } catch (NoSuchMethodException ex) {
+                    Exceptions.printStackTrace(ex);
+                } catch (SecurityException ex) {
+                    Exceptions.printStackTrace(ex);
+                } catch (IllegalAccessException ex) {
+                    Exceptions.printStackTrace(ex);
+                } catch (IllegalArgumentException ex) {
+                    Exceptions.printStackTrace(ex);
+                }
+            }
+        } else if (formattersInLoopRef[0] != null) {
+            //ignore loops(?)
+        }
+        if (VariablesFormatterFilter.isToStringValueType(type)) {
+            try {
+                return "\""+ov.getToStringValue ()+"\"";
+            } catch (InvalidExpressionException ex) {
+                // Not a supported operation (e.g. J2ME, see #45543)
+                // Or missing context or any other reason
+                
Logger.getLogger(VariablesFormatterFilter.class.getName()).fine("getToStringValue()
 "+ex.getLocalizedMessage());
+                if ( (ex.getTargetException () != null) &&
+                     (ex.getTargetException () instanceof
+                       UnsupportedOperationException)
+                ) {
+                    // PATCH for J2ME. see 45543
+                    return ov.getValue();
+                }
+                return ex.getLocalizedMessage ();
+            }
+        }
+        return ov.getValue();
+    }
+
+    private synchronized boolean setNewTask(TaskDescription newTask) {
+        if (Objects.equals(currentTask, newTask)) {
+            return true; //nothing changed, nothing to do
+        }
+
+        if (currentTask != null) {
+            currentTask.cancel();
+            getHighlightsBag(currentTask.frameDocument).clear();
+        }
+
+        currentTask = newTask;
+
+        return false;
+    }
+
+    private synchronized void setHighlights(TaskDescription task, OffsetsBag 
highlights) {
+        if (!task.isCancelled()) {
+            
getHighlightsBag(currentTask.frameDocument).setHighlights(highlights);
+        }
+    }
+
+    @DebuggerServiceRegistration(types=LazyDebuggerManagerListener.class)
+    public static final class Init extends DebuggerManagerAdapter {
+        @Override
+        public void sessionAdded(Session session) {
+            for (InlineValueComputer v : session.lookup("inlineValue", 
InlineValueComputer.class)) {
+            }

Review Comment:
   The cancel is happening in `setNewTask`, todo removed.



##########
ide/spi.debugger.ui/apichanges.xml:
##########
@@ -51,6 +51,23 @@
 <!-- ACTUAL CHANGES BEGIN HERE: -->
 
 <changes>
+    <change id="inline-values-setting-keys">
+        <api name="DebuggerCoreSPI"/>
+        <summary><code>Constants</code> class enhanced with constants for 
inline values.</summary>
+        <version major="2" minor="88"/>
+        <date day="8" month="4" year="2025"/>
+        <author login="jlahoda"/>
+        <compatibility binary="compatible" source="compatible" 
modification="yes" semantic="compatible"/>
+        <description>
+            <p>
+                Two new contants are added to <code>Constants</code>:

Review Comment:
   Done.



##########
ide/api.lsp/src/org/netbeans/api/lsp/InlineValue.java:
##########
@@ -0,0 +1,58 @@
+/*
+ * 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.api.lsp;
+
+/**
+ * An expression whose value may be show inline while debugging.

Review Comment:
   Done.



-- 
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: notifications-unsubscr...@netbeans.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscr...@netbeans.apache.org
For additional commands, e-mail: notifications-h...@netbeans.apache.org

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

Reply via email to