<commit_before>/*
 * Class BreakpointManager
 * @author Jeka
 */
package com.intellij.debugger.ui.breakpoints;

import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
import com.intellij.debugger.impl.*;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.DebuggerExpressionComboBox;
import com.intellij.debugger.ui.DebuggerExpressionTextField;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.*;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.util.Alarm;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.containers.HashMap;
import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointsConfigurationDialogFactory;
import com.sun.jdi.Field;
import com.sun.jdi.InternalException;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.request.*;
import gnu.trove.TIntHashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.*;

public class BreakpointManager implements JDOMExternalizable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.BreakpointManager");

  @NonNls private static final String RULES_GROUP_NAME = "breakpoint_rules";
  private final Project myProject;
  private AnyExceptionBreakpoint myAnyExceptionBreakpoint;
  private List<Breakpoint> myBreakpoints = new ArrayList<Breakpoint>(); // breakpoints storage, access should be synchronized
  private List<EnableBreakpointRule> myBreakpointRules = new ArrayList<EnableBreakpointRule>(); // breakpoint rules
  private List<Breakpoint> myBreakpointsListForIteration = null; // another list for breakpoints iteration, unsynchronized access ok
  private Map<Document, List<BreakpointWithHighlighter>> myDocumentBreakpoints = new HashMap<Document, List<BreakpointWithHighlighter>>();
  private Map<String, String> myUIProperties = new java.util.HashMap<String, String>();
  private Map<Key<? extends Breakpoint>, String> myDefaultSuspendPolicies = new HashMap<Key<? extends Breakpoint>, String>(); 

  private BreakpointsConfigurationDialogFactory myBreakpointsConfigurable;
  private EditorMouseListener myEditorMouseListener;

  private final EventDispatcher<BreakpointManagerListener> myDispatcher = EventDispatcher.create(BreakpointManagerListener.class);

  private StartupManager myStartupManager;

  private final DocumentListener myDocumentListener = new DocumentAdapter() {
    private final Alarm myUpdateAlarm = new Alarm();

    public void documentChanged(final DocumentEvent e) {
      final Document document = e.getDocument();
      synchronized (BreakpointManager.this) {
        List<BreakpointWithHighlighter> breakpoints = myDocumentBreakpoints.get(document);

        if(breakpoints != null) {
          myUpdateAlarm.cancelAllRequests();
          // must create new array in order to avoid "concurrent modification" errors
          final List<BreakpointWithHighlighter> breakpointsToUpdate = new ArrayList<BreakpointWithHighlighter>(breakpoints);
          myUpdateAlarm.addRequest(new Runnable() {
            public void run() {
              if (!myProject.isDisposed()) {
                PsiDocumentManager.getInstance(myProject).commitDocument(document);
                update(breakpointsToUpdate);
              }
            }
          }, 300, ModalityState.NON_MODAL);
        }
      }
    }
  };
  @NonNls private static final String MASTER_BREAKPOINT_TAGNAME = "master_breakpoint";
  @NonNls private static final String SLAVE_BREAKPOINT_TAGNAME = "slave_breakpoint";
  @NonNls private static final String DEFAULT_SUSPEND_POLICY_ATTRIBUTE_NAME = "default_suspend_policy";

  private void update(List<BreakpointWithHighlighter> breakpoints) {
    final TIntHashSet intHash = new TIntHashSet();

    for (BreakpointWithHighlighter breakpoint : breakpoints) {
      SourcePosition sourcePosition = breakpoint.getSourcePosition();
      breakpoint.reload();

      if (breakpoint.isValid()) {
        if (breakpoint.getSourcePosition().getLine() != sourcePosition.getLine()) {
          fireBreakpointChanged(breakpoint);
        }

        if (intHash.contains(breakpoint.getLineIndex())) {
          remove(breakpoint);
        }
        else {
          intHash.add(breakpoint.getLineIndex());
        }
      }
      else {
        remove(breakpoint);
      }
    }
  }

  /*
  // todo: not needed??
  private void setInvalid(final BreakpointWithHighlighter breakpoint) {
    Collection<DebuggerSession> sessions = DebuggerManagerEx.getInstanceEx(myProject).getSessions();

    for (Iterator<DebuggerSession> iterator = sessions.getSectionsIterator(); getSectionsIterator.hasNext();) {
      DebuggerSession session = iterator.next();
      final DebugProcessImpl process = session.getProcess();
      process.getManagerThread().invokeLater(new DebuggerCommandImpl() {
        protected void action() throws Exception {
          process.getRequestsManager().deleteRequest(breakpoint);
          process.getRequestsManager().setInvalid(breakpoint, "Source code changed");
          breakpoint.updateUI();
        }
      });
    }
  }
  */

  private void remove(final BreakpointWithHighlighter breakpoint) {
    DebuggerInvocationUtil.invokeLater(myProject, new Runnable() {
      public void run() {
        removeBreakpoint(breakpoint);
      }
    });
  }

  public BreakpointManager(Project project, StartupManager startupManager, DebuggerManagerImpl debuggerManager) {
    myProject = project;
    myStartupManager = startupManager;
    debuggerManager.getContextManager().addListener(new DebuggerContextListener() {
      private DebuggerSession myPreviousSession;

      public void changeEvent(DebuggerContextImpl newContext, int event) {
        if (newContext.getDebuggerSession() != myPreviousSession || event == DebuggerSession.EVENT_DETACHED) {
          updateBreakpointsUI();
          myPreviousSession = newContext.getDebuggerSession();
        }
      }
    });
  }

  public void init() {
    EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
    myEditorMouseListener = new EditorMouseAdapter() {
      private EditorMouseEvent myMousePressedEvent;

      @Nullable
      private Breakpoint toggleBreakpoint(final boolean mostSuitingBreakpoint, final int line) {
        final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor();
        if (editor == null) {
          return null;
        }
        final Document document = editor.getDocument();
        final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
        if (psiFile == null) {
          return null;
        }
        final FileType fileType = psiFile.getFileType();
        boolean isInsideCompiledClass = StdFileTypes.CLASS.equals(fileType);
        if (!isInsideCompiledClass && !DebuggerUtils.supportsJVMDebugging(fileType)) {
          return null;
        }
        PsiDocumentManager.getInstance(myProject).commitDocument(document);

        int offset = editor.getCaretModel().getOffset();
        int editorLine = editor.getDocument().getLineNumber(offset);
        if(editorLine != line) {
          if (line < 0 || line >= document.getLineCount()) {
            return null;
          }
          offset = editor.getDocument().getLineStartOffset(line);
        }

        Breakpoint breakpoint = findBreakpoint(document, offset, null);
        if (breakpoint == null) {
          if(mostSuitingBreakpoint || isInsideCompiledClass) {<commit_msg>expand folded regions on mouse-driven breakpoint toggle<commit_after>/*
 * Class BreakpointManager
 * @author Jeka
 */
package com.intellij.debugger.ui.breakpoints;

import com.intellij.codeInsight.folding.impl.ExpandRegionHandler;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
import com.intellij.debugger.impl.*;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.DebuggerExpressionComboBox;
import com.intellij.debugger.ui.DebuggerExpressionTextField;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.markup.MarkupEditorFilterFactory;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.*;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.util.Alarm;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.containers.HashMap;
import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointsConfigurationDialogFactory;
import com.sun.jdi.Field;
import com.sun.jdi.InternalException;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.request.*;
import gnu.trove.TIntHashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.*;

public class BreakpointManager implements JDOMExternalizable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.BreakpointManager");

  @NonNls private static final String RULES_GROUP_NAME = "breakpoint_rules";
  private final Project myProject;
  private AnyExceptionBreakpoint myAnyExceptionBreakpoint;
  private List<Breakpoint> myBreakpoints = new ArrayList<Breakpoint>(); // breakpoints storage, access should be synchronized
  private List<EnableBreakpointRule> myBreakpointRules = new ArrayList<EnableBreakpointRule>(); // breakpoint rules
  private List<Breakpoint> myBreakpointsListForIteration = null; // another list for breakpoints iteration, unsynchronized access ok
  private Map<Document, List<BreakpointWithHighlighter>> myDocumentBreakpoints = new HashMap<Document, List<BreakpointWithHighlighter>>();
  private Map<String, String> myUIProperties = new java.util.HashMap<String, String>();
  private Map<Key<? extends Breakpoint>, String> myDefaultSuspendPolicies = new HashMap<Key<? extends Breakpoint>, String>(); 

  private BreakpointsConfigurationDialogFactory myBreakpointsConfigurable;
  private EditorMouseListener myEditorMouseListener;

  private final EventDispatcher<BreakpointManagerListener> myDispatcher = EventDispatcher.create(BreakpointManagerListener.class);

  private StartupManager myStartupManager;

  private final DocumentListener myDocumentListener = new DocumentAdapter() {
    private final Alarm myUpdateAlarm = new Alarm();

    public void documentChanged(final DocumentEvent e) {
      final Document document = e.getDocument();
      synchronized (BreakpointManager.this) {
        List<BreakpointWithHighlighter> breakpoints = myDocumentBreakpoints.get(document);

        if(breakpoints != null) {
          myUpdateAlarm.cancelAllRequests();
          // must create new array in order to avoid "concurrent modification" errors
          final List<BreakpointWithHighlighter> breakpointsToUpdate = new ArrayList<BreakpointWithHighlighter>(breakpoints);
          myUpdateAlarm.addRequest(new Runnable() {
            public void run() {
              if (!myProject.isDisposed()) {
                PsiDocumentManager.getInstance(myProject).commitDocument(document);
                update(breakpointsToUpdate);
              }
            }
          }, 300, ModalityState.NON_MODAL);
        }
      }
    }
  };
  @NonNls private static final String MASTER_BREAKPOINT_TAGNAME = "master_breakpoint";
  @NonNls private static final String SLAVE_BREAKPOINT_TAGNAME = "slave_breakpoint";
  @NonNls private static final String DEFAULT_SUSPEND_POLICY_ATTRIBUTE_NAME = "default_suspend_policy";

  private void update(List<BreakpointWithHighlighter> breakpoints) {
    final TIntHashSet intHash = new TIntHashSet();

    for (BreakpointWithHighlighter breakpoint : breakpoints) {
      SourcePosition sourcePosition = breakpoint.getSourcePosition();
      breakpoint.reload();

      if (breakpoint.isValid()) {
        if (breakpoint.getSourcePosition().getLine() != sourcePosition.getLine()) {
          fireBreakpointChanged(breakpoint);
        }

        if (intHash.contains(breakpoint.getLineIndex())) {
          remove(breakpoint);
        }
        else {
          intHash.add(breakpoint.getLineIndex());
        }
      }
      else {
        remove(breakpoint);
      }
    }
  }

  /*
  // todo: not needed??
  private void setInvalid(final BreakpointWithHighlighter breakpoint) {
    Collection<DebuggerSession> sessions = DebuggerManagerEx.getInstanceEx(myProject).getSessions();

    for (Iterator<DebuggerSession> iterator = sessions.getSectionsIterator(); getSectionsIterator.hasNext();) {
      DebuggerSession session = iterator.next();
      final DebugProcessImpl process = session.getProcess();
      process.getManagerThread().invokeLater(new DebuggerCommandImpl() {
        protected void action() throws Exception {
          process.getRequestsManager().deleteRequest(breakpoint);
          process.getRequestsManager().setInvalid(breakpoint, "Source code changed");
          breakpoint.updateUI();
        }
      });
    }
  }
  */

  private void remove(final BreakpointWithHighlighter breakpoint) {
    DebuggerInvocationUtil.invokeLater(myProject, new Runnable() {
      public void run() {
        removeBreakpoint(breakpoint);
      }
    });
  }

  public BreakpointManager(Project project, StartupManager startupManager, DebuggerManagerImpl debuggerManager) {
    myProject = project;
    myStartupManager = startupManager;
    debuggerManager.getContextManager().addListener(new DebuggerContextListener() {
      private DebuggerSession myPreviousSession;

      public void changeEvent(DebuggerContextImpl newContext, int event) {
        if (newContext.getDebuggerSession() != myPreviousSession || event == DebuggerSession.EVENT_DETACHED) {
          updateBreakpointsUI();
          myPreviousSession = newContext.getDebuggerSession();
        }
      }
    });
  }

  public void init() {
    EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
    myEditorMouseListener = new EditorMouseAdapter() {
      private EditorMouseEvent myMousePressedEvent;

      @Nullable
      private Breakpoint toggleBreakpoint(final boolean mostSuitingBreakpoint, final int line) {
        final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor();
        if (editor == null) {
          return null;
        }
        final Document document = editor.getDocument();
        final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
        if (psiFile == null) {
          return null;
        }
        final FileType fileType = psiFile.getFileType();
        boolean isInsideCompiledClass = StdFileTypes.CLASS.equals(fileType);
        if (!isInsideCompiledClass && !DebuggerUtils.supportsJVMDebugging(fileType)) {
          return null;
        }
        PsiDocumentManager.getInstance(myProject).commitDocument(document);

        int offset = editor.getCaretModel().getOffset();
        int editorLine = editor.getDocument().getLineNumber(offset);
        if(editorLine != line) {
          if (line < 0 || line >= document.getLineCount()) {
            return null;
          }
          offset = editor.getDocument().getLineStartOffset(line);
        }

        ExpandRegionHandler.expandRegionAtCaret(myProject, editor);

        Breakpoint breakpoint = findBreakpoint(document, offset, null);
        if (breakpoint == null) {
          if(mostSuitingBreakpoint || isInsideCompiledClass) {
{'fraction_non_alphanumeric': 0.09244644870349493, 'fraction_numerical': 0.00042948408224620176, 'mean_word_length': 4.320765495572694, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6891182', 'n_tokens_mistral': 5155, 'n_tokens_neox': 5113, 'n_words': 968}