Search in sources :

Example 1 with DebuggerSession

use of com.intellij.debugger.impl.DebuggerSession in project intellij-community by JetBrains.

the class ValueHint method getSelectedExpression.

private static Trinity<PsiElement, TextRange, Value> getSelectedExpression(final Project project, final Editor editor, final Point point, final ValueHintType type) {
    final Ref<PsiElement> selectedExpression = Ref.create(null);
    final Ref<TextRange> currentRange = Ref.create(null);
    final Ref<Value> preCalculatedValue = Ref.create(null);
    PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> {
        // Point -> offset
        final int offset = calculateOffset(editor, point);
        PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (psiFile == null || !psiFile.isValid()) {
            return;
        }
        int selectionStart = editor.getSelectionModel().getSelectionStart();
        int selectionEnd = editor.getSelectionModel().getSelectionEnd();
        if ((type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT) && (selectionStart <= offset && offset <= selectionEnd)) {
            PsiElement ctx = (selectionStart > 0) ? psiFile.findElementAt(selectionStart - 1) : psiFile.findElementAt(selectionStart);
            try {
                String text = editor.getSelectionModel().getSelectedText();
                if (text != null && ctx != null) {
                    final JVMElementFactory factory = JVMElementFactories.getFactory(ctx.getLanguage(), project);
                    if (factory == null) {
                        return;
                    }
                    selectedExpression.set(factory.createExpressionFromText(text, ctx));
                    currentRange.set(new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd()));
                }
            } catch (IncorrectOperationException ignored) {
            }
        }
        if (currentRange.get() == null) {
            PsiElement elementAtCursor = psiFile.findElementAt(offset);
            if (elementAtCursor == null) {
                return;
            }
            Pair<PsiElement, TextRange> pair = findExpression(elementAtCursor, type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT);
            if (pair == null) {
                if (type == ValueHintType.MOUSE_OVER_HINT) {
                    final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(project).getContext().getDebuggerSession();
                    if (debuggerSession != null && debuggerSession.isPaused()) {
                        final Pair<Method, Value> lastExecuted = debuggerSession.getProcess().getLastExecutedMethod();
                        if (lastExecuted != null) {
                            final Method method = lastExecuted.getFirst();
                            if (method != null) {
                                final Pair<PsiElement, TextRange> expressionPair = findExpression(elementAtCursor, true);
                                if (expressionPair != null && expressionPair.getFirst() instanceof PsiMethodCallExpression) {
                                    final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expressionPair.getFirst();
                                    final PsiMethod psiMethod = methodCallExpression.resolveMethod();
                                    if (psiMethod != null) {
                                        final JVMName jvmSignature = JVMNameUtil.getJVMSignature(psiMethod);
                                        try {
                                            if (method.name().equals(psiMethod.getName()) && method.signature().equals(jvmSignature.getName(debuggerSession.getProcess()))) {
                                                pair = expressionPair;
                                                preCalculatedValue.set(lastExecuted.getSecond());
                                            }
                                        } catch (EvaluateException ignored) {
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (pair == null) {
                return;
            }
            selectedExpression.set(pair.getFirst());
            currentRange.set(pair.getSecond());
        }
    });
    return Trinity.create(selectedExpression.get(), currentRange.get(), preCalculatedValue.get());
}
Also used : JVMName(com.intellij.debugger.engine.JVMName) Method(com.sun.jdi.Method) AbstractValueHint(com.intellij.xdebugger.impl.evaluate.quick.common.AbstractValueHint) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) PrimitiveValue(com.sun.jdi.PrimitiveValue) Value(com.sun.jdi.Value) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 2 with DebuggerSession

use of com.intellij.debugger.impl.DebuggerSession in project intellij-community by JetBrains.

the class DebuggerPanelsManager method attachVirtualMachine.

@Nullable
public RunContentDescriptor attachVirtualMachine(DebugUIEnvironment environment) throws ExecutionException {
    final DebugEnvironment modelEnvironment = environment.getEnvironment();
    final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(myProject).attachVirtualMachine(modelEnvironment);
    if (debuggerSession == null) {
        return null;
    }
    XDebugSession debugSession = XDebuggerManager.getInstance(myProject).startSessionAndShowTab(modelEnvironment.getSessionName(), environment.getReuseContent(), new XDebugProcessStarter() {

        @Override
        @NotNull
        public XDebugProcess start(@NotNull XDebugSession session) {
            return JavaDebugProcess.create(session, debuggerSession);
        }
    });
    return debugSession.getRunContentDescriptor();
}
Also used : XDebugSession(com.intellij.xdebugger.XDebugSession) XDebugProcess(com.intellij.xdebugger.XDebugProcess) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) XDebugProcessStarter(com.intellij.xdebugger.XDebugProcessStarter) DebugEnvironment(com.intellij.debugger.DebugEnvironment) NotNull(org.jetbrains.annotations.NotNull) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with DebuggerSession

use of com.intellij.debugger.impl.DebuggerSession in project intellij-community by JetBrains.

the class DefaultSourcePositionProvider method getSourcePositionForField.

@Nullable
private static SourcePosition getSourcePositionForField(@NotNull FieldDescriptor descriptor, @NotNull Project project, @NotNull DebuggerContextImpl context, boolean nearest) {
    final ReferenceType type = descriptor.getField().declaringType();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final String fieldName = descriptor.getField().name();
    if (fieldName.startsWith(FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) {
        // this field actually mirrors a local variable in the outer class
        String varName = fieldName.substring(fieldName.lastIndexOf('$') + 1);
        PsiElement element = PositionUtil.getContextElement(context);
        if (element == null) {
            return null;
        }
        PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class, false);
        if (aClass == null) {
            return null;
        }
        PsiElement navigationElement = aClass.getNavigationElement();
        if (!(navigationElement instanceof PsiClass)) {
            return null;
        }
        aClass = (PsiClass) navigationElement;
        PsiVariable psiVariable = facade.getResolveHelper().resolveReferencedVariable(varName, aClass);
        if (psiVariable == null) {
            return null;
        }
        if (nearest) {
            return DebuggerContextUtil.findNearest(context, psiVariable, aClass.getContainingFile());
        }
        return SourcePosition.createFromElement(psiVariable);
    } else {
        final DebuggerSession session = context.getDebuggerSession();
        final GlobalSearchScope scope = session != null ? session.getSearchScope() : GlobalSearchScope.allScope(project);
        PsiClass aClass = facade.findClass(type.name().replace('$', '.'), scope);
        if (aClass == null) {
            // trying to search, assuming declaring class is an anonymous class
            final DebugProcessImpl debugProcess = context.getDebugProcess();
            if (debugProcess != null) {
                try {
                    final List<Location> locations = type.allLineLocations();
                    if (!locations.isEmpty()) {
                        // important: use the last location to be sure the position will be within the anonymous class
                        final Location lastLocation = locations.get(locations.size() - 1);
                        final SourcePosition position = debugProcess.getPositionManager().getSourcePosition(lastLocation);
                        aClass = JVMNameUtil.getClassAt(position);
                    }
                } catch (AbsentInformationException | ClassNotPreparedException ignored) {
                }
            }
        }
        if (aClass != null) {
            PsiField field = aClass.findFieldByName(fieldName, false);
            if (field == null)
                return null;
            if (nearest) {
                return DebuggerContextUtil.findNearest(context, field.getNavigationElement(), aClass.getContainingFile());
            }
            return SourcePosition.createFromElement(field);
        }
        return null;
    }
}
Also used : AbsentInformationException(com.sun.jdi.AbsentInformationException) ClassNotPreparedException(com.sun.jdi.ClassNotPreparedException) ReferenceType(com.sun.jdi.ReferenceType) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SourcePosition(com.intellij.debugger.SourcePosition) Location(com.sun.jdi.Location) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with DebuggerSession

use of com.intellij.debugger.impl.DebuggerSession in project intellij-community by JetBrains.

the class DefaultCodeFragmentFactory method createCodeFragment.

public JavaCodeFragment createCodeFragment(TextWithImports item, PsiElement context, final Project project) {
    final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(project);
    final String text = item.getText();
    final JavaCodeFragment fragment;
    if (CodeFragmentKind.EXPRESSION == item.getKind()) {
        final String expressionText = StringUtil.endsWithChar(text, ';') ? text.substring(0, text.length() - 1) : text;
        fragment = factory.createExpressionCodeFragment(expressionText, context, null, true);
    } else /*if (CodeFragmentKind.CODE_BLOCK == item.getKind())*/
    {
        fragment = factory.createCodeBlockCodeFragment(text, context, true);
    }
    if (item.getImports().length() > 0) {
        fragment.addImportsFromString(item.getImports());
    }
    fragment.setVisibilityChecker(JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE);
    //noinspection HardCodedStringLiteral
    fragment.putUserData(KEY, "DebuggerComboBoxEditor.IS_DEBUGGER_EDITOR");
    fragment.putCopyableUserData(JavaCompletionUtil.DYNAMIC_TYPE_EVALUATOR, (expression, parameters) -> {
        if (!RuntimeTypeEvaluator.isSubtypeable(expression)) {
            return null;
        }
        if (parameters.getInvocationCount() <= 1 && JavaCompletionUtil.mayHaveSideEffects(expression)) {
            final CompletionService service = CompletionService.getCompletionService();
            if (parameters.getInvocationCount() < 2) {
                service.setAdvertisementText("Invoke completion once more to see runtime type variants");
            }
            return null;
        }
        final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(project).getContext();
        DebuggerSession debuggerSession = debuggerContext.getDebuggerSession();
        if (debuggerSession != null && debuggerContext.getSuspendContext() != null) {
            final Semaphore semaphore = new Semaphore();
            semaphore.down();
            final AtomicReference<PsiType> nameRef = new AtomicReference<>();
            final RuntimeTypeEvaluator worker = new RuntimeTypeEvaluator(null, expression, debuggerContext, ProgressManager.getInstance().getProgressIndicator()) {

                @Override
                protected void typeCalculationFinished(@Nullable PsiType type) {
                    nameRef.set(type);
                    semaphore.up();
                }
            };
            debuggerSession.getProcess().getManagerThread().invoke(worker);
            for (int i = 0; i < 50; i++) {
                ProgressManager.checkCanceled();
                if (semaphore.waitFor(20))
                    break;
            }
            return nameRef.get();
        }
        return null;
    });
    return fragment;
}
Also used : RuntimeTypeEvaluator(com.intellij.debugger.codeinsight.RuntimeTypeEvaluator) AtomicReference(java.util.concurrent.atomic.AtomicReference) Semaphore(com.intellij.util.concurrency.Semaphore) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) CompletionService(com.intellij.codeInsight.completion.CompletionService) DebuggerContextImpl(com.intellij.debugger.impl.DebuggerContextImpl) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with DebuggerSession

use of com.intellij.debugger.impl.DebuggerSession in project intellij-community by JetBrains.

the class JavaMarkObjectActionHandler method perform.

@Override
public void perform(@NotNull Project project, AnActionEvent event) {
    final DebuggerTreeNodeImpl node = DebuggerAction.getSelectedNode(event.getDataContext());
    if (node == null) {
        return;
    }
    final NodeDescriptorImpl descriptor = node.getDescriptor();
    if (!(descriptor instanceof ValueDescriptorImpl)) {
        return;
    }
    final DebuggerTree tree = node.getTree();
    tree.saveState(node);
    final Component parent = event.getData(CONTEXT_COMPONENT);
    final ValueDescriptorImpl valueDescriptor = ((ValueDescriptorImpl) descriptor);
    final DebuggerContextImpl debuggerContext = tree.getDebuggerContext();
    final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
    final ValueMarkup markup = valueDescriptor.getMarkup(debugProcess);
    debugProcess.getManagerThread().invoke(new DebuggerContextCommandImpl(debuggerContext) {

        public Priority getPriority() {
            return Priority.HIGH;
        }

        public void threadAction() {
            boolean sessionRefreshNeeded = true;
            try {
                if (markup != null) {
                    valueDescriptor.setMarkup(debugProcess, null);
                } else {
                    final String defaultText = valueDescriptor.getName();
                    final Ref<Pair<ValueMarkup, Boolean>> result = new Ref<>(null);
                    try {
                        final boolean suggestAdditionalMarkup = canSuggestAdditionalMarkup(debugProcess, valueDescriptor.getValue());
                        SwingUtilities.invokeAndWait(() -> {
                            ObjectMarkupPropertiesDialog dialog = new ObjectMarkupPropertiesDialog(parent, defaultText, suggestAdditionalMarkup);
                            if (dialog.showAndGet()) {
                                result.set(Pair.create(dialog.getConfiguredMarkup(), dialog.isMarkAdditionalFields()));
                            }
                        });
                    } catch (InterruptedException ignored) {
                    } catch (InvocationTargetException e) {
                        LOG.error(e);
                    }
                    final Pair<ValueMarkup, Boolean> pair = result.get();
                    if (pair != null) {
                        valueDescriptor.setMarkup(debugProcess, pair.first);
                        if (pair.second) {
                            final Value value = valueDescriptor.getValue();
                            final Map<ObjectReference, ValueMarkup> additionalMarkup = suggestMarkup((ObjectReference) value);
                            if (!additionalMarkup.isEmpty()) {
                                final Map<ObjectReference, ValueMarkup> map = NodeDescriptorImpl.getMarkupMap(debugProcess);
                                if (map != null) {
                                    for (Map.Entry<ObjectReference, ValueMarkup> entry : additionalMarkup.entrySet()) {
                                        final ObjectReference key = entry.getKey();
                                        if (!map.containsKey(key)) {
                                            map.put(key, entry.getValue());
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        sessionRefreshNeeded = false;
                    }
                }
            } finally {
                final boolean _sessionRefreshNeeded = sessionRefreshNeeded;
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        tree.restoreState(node);
                        final TreeBuilder model = tree.getMutableModel();
                        refreshLabelsRecursively(model.getRoot(), model, valueDescriptor.getValue());
                        if (_sessionRefreshNeeded) {
                            final DebuggerSession session = debuggerContext.getDebuggerSession();
                            if (session != null) {
                                session.refresh(true);
                            }
                        }
                    }

                    private void refreshLabelsRecursively(Object node, TreeBuilder model, Value value) {
                        if (node instanceof DebuggerTreeNodeImpl) {
                            final DebuggerTreeNodeImpl _node = (DebuggerTreeNodeImpl) node;
                            final NodeDescriptorImpl descriptor = _node.getDescriptor();
                            if (descriptor instanceof ValueDescriptor && Comparing.equal(value, ((ValueDescriptor) descriptor).getValue())) {
                                _node.labelChanged();
                            }
                        }
                        final int childCount = model.getChildCount(node);
                        for (int idx = 0; idx < childCount; idx++) {
                            refreshLabelsRecursively(model.getChild(node, idx), model, value);
                        }
                    }
                });
            }
        }
    });
}
Also used : DebuggerTreeNodeImpl(com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl) ValueDescriptor(com.intellij.debugger.ui.tree.ValueDescriptor) ValueDescriptorImpl(com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) NodeDescriptorImpl(com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl) Pair(com.intellij.openapi.util.Pair) DebuggerTree(com.intellij.debugger.ui.impl.watch.DebuggerTree) ValueMarkup(com.intellij.xdebugger.impl.ui.tree.ValueMarkup) InvocationTargetException(java.lang.reflect.InvocationTargetException) TreeBuilder(com.intellij.debugger.ui.impl.tree.TreeBuilder) Ref(com.intellij.openapi.util.Ref) DebugProcessImpl(com.intellij.debugger.engine.DebugProcessImpl) DebuggerContextImpl(com.intellij.debugger.impl.DebuggerContextImpl) HashMap(com.intellij.util.containers.HashMap) Map(java.util.Map) DebuggerContextCommandImpl(com.intellij.debugger.engine.events.DebuggerContextCommandImpl)

Aggregations

DebuggerSession (com.intellij.debugger.impl.DebuggerSession)28 DebuggerContextImpl (com.intellij.debugger.impl.DebuggerContextImpl)11 Project (com.intellij.openapi.project.Project)9 XDebugSession (com.intellij.xdebugger.XDebugSession)7 DebuggerManagerEx (com.intellij.debugger.DebuggerManagerEx)5 DebugProcessImpl (com.intellij.debugger.engine.DebugProcessImpl)5 Nullable (org.jetbrains.annotations.Nullable)5 DebugEnvironment (com.intellij.debugger.DebugEnvironment)3 SourcePosition (com.intellij.debugger.SourcePosition)3 DebuggerCommandImpl (com.intellij.debugger.engine.events.DebuggerCommandImpl)3 DebuggerContextCommandImpl (com.intellij.debugger.engine.events.DebuggerContextCommandImpl)3 SuspendContextImpl (com.intellij.debugger.engine.SuspendContextImpl)2 DebuggerTree (com.intellij.debugger.ui.impl.watch.DebuggerTree)2 DebuggerTreeNodeImpl (com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl)2 NodeDescriptorImpl (com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl)2 WatchItemDescriptor (com.intellij.debugger.ui.impl.watch.WatchItemDescriptor)2 RunnerAndConfigurationSettings (com.intellij.execution.RunnerAndConfigurationSettings)2 ConfigurationFactory (com.intellij.execution.configurations.ConfigurationFactory)2 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)2 Presentation (com.intellij.openapi.actionSystem.Presentation)2