<commit_before>/*
 * Copyright 2011 <NAME> (Sylvanaar)
 *
 *   Licensed 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 com.sylvanaar.idea.Lua.debugger;

import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.XSuspendContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: <NAME>
 * Date: 3/22/11
 * Time: 6:31 PM
 */
public class LuaDebuggerController {
    private static final Logger log = Logger.getInstance("Lua.LuaDebuggerController");
    ServerSocket serverSocket;
    Socket clientSocket;
    int serverPort = 8171;

    SocketReader reader = null;
    OutputStream outputStream = null;

    static final String RUN = "RUN\n";
    static final String STEP = "STEP\n";
    static final String STEP_OVER = "OVER\n";

    private boolean readerCanRun = true;

    Pattern AT_BREAKPOINT;
    private XDebugSession session;
    private ConsoleView console;
    private boolean ready;

    public XDebugSession getSession() { return session; }

    Map<XBreakpoint, LuaPosition> myBreakpoints2Pos = new HashMap<XBreakpoint, LuaPosition>();
    Map<LuaPosition, XBreakpoint> myPos2Breakpoints = new HashMap<LuaPosition, XBreakpoint>();

    Project myProject = null;

    LuaDebuggerController(XDebugSession session) {
        myProject = session.getProject();
        this.session = session;
        this.session.setPauseActionSupported(false);
        AT_BREAKPOINT = Pattern.compile("^202 Paused\\s+(\\S+)\\s+(\\d+)", Pattern.MULTILINE);

        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
            @Override
            public void run() {
                log.debug("Starting Debug Controller");
                try {
                    serverSocket = new ServerSocket(serverPort);
                    log.debug("Accepting Connections");
                    clientSocket = serverSocket.accept();
                    log.debug("Client Connected " + clientSocket.getInetAddress());
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    public void printToConsole(String text, ConsoleViewContentType contentType)
    {
        assert console != null;
        
        console.print(text + '\n', contentType);
    }
    
    public void waitForConnect() throws IOException {

        int count = 0;
        while (clientSocket == null) {
            try {
                Thread.sleep(200);
                if (++count > 20)
                    throw new RuntimeException("timeout");
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        printToConsole("Debugger connected at " + clientSocket.getInetAddress(), ConsoleViewContentType.SYSTEM_OUTPUT);

        reader = new SocketReader();
        reader.start();

        outputStream = clientSocket.getOutputStream();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        ready = true;
    }

    public void terminate() {
        log.debug("terminate");
        readerCanRun = false;

        try {
            serverSocket.close();
            if (clientSocket != null)
                clientSocket.close();
            ready = false;
        } catch (IOException e) {
            e.printStackTrace();  
        }
    }

    public void stepInto() {
        try {
            log.debug("stepInto");

            outputStream.write(STEP.getBytes("UTF8"));
            ready = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stepOver() {
        try {
            log.debug("stepOver");

            outputStream.write(STEP_OVER.getBytes("UTF8"));
            ready = false;<commit_msg>IDLua-113 fix an NPE during debugger process shutdown<commit_after>/*
 * Copyright 2011 <NAME> (Sylvanaar)
 *
 *   Licensed 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 com.sylvanaar.idea.Lua.debugger;

import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.XSuspendContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: <NAME>
 * Date: 3/22/11
 * Time: 6:31 PM
 */
public class LuaDebuggerController {
    private static final Logger log = Logger.getInstance("Lua.LuaDebuggerController");
    ServerSocket serverSocket;
    Socket clientSocket;
    int serverPort = 8171;

    SocketReader reader = null;
    OutputStream outputStream = null;

    static final String RUN = "RUN\n";
    static final String STEP = "STEP\n";
    static final String STEP_OVER = "OVER\n";

    private boolean readerCanRun = true;

    Pattern AT_BREAKPOINT;
    private XDebugSession session;
    private ConsoleView console;
    private boolean ready;

    public XDebugSession getSession() { return session; }

    Map<XBreakpoint, LuaPosition> myBreakpoints2Pos = new HashMap<XBreakpoint, LuaPosition>();
    Map<LuaPosition, XBreakpoint> myPos2Breakpoints = new HashMap<LuaPosition, XBreakpoint>();

    Project myProject = null;

    LuaDebuggerController(XDebugSession session) {
        myProject = session.getProject();
        this.session = session;
        this.session.setPauseActionSupported(false);
        AT_BREAKPOINT = Pattern.compile("^202 Paused\\s+(\\S+)\\s+(\\d+)", Pattern.MULTILINE);

        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
            @Override
            public void run() {
                log.debug("Starting Debug Controller");
                try {
                    serverSocket = new ServerSocket(serverPort);
                    log.debug("Accepting Connections");
                    clientSocket = serverSocket.accept();
                    log.debug("Client Connected " + clientSocket.getInetAddress());
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    public void printToConsole(String text, ConsoleViewContentType contentType)
    {
        assert console != null;
        
        console.print(text + '\n', contentType);
    }
    
    public void waitForConnect() throws IOException {

        int count = 0;
        while (clientSocket == null) {
            try {
                Thread.sleep(200);
                if (++count > 20)
                    throw new RuntimeException("timeout");
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        printToConsole("Debugger connected at " + clientSocket.getInetAddress(), ConsoleViewContentType.SYSTEM_OUTPUT);

        reader = new SocketReader();
        reader.start();

        outputStream = clientSocket.getOutputStream();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        ready = true;
    }

    public void terminate() {
        log.debug("terminate");
        readerCanRun = false;

        try {
            if (serverSocket!=null)
                serverSocket.close();
            if (clientSocket != null)
                clientSocket.close();
            ready = false;
        } catch (IOException e) {
            e.printStackTrace();  
        }
    }

    public void stepInto() {
        try {
            log.debug("stepInto");

            outputStream.write(STEP.getBytes("UTF8"));
            ready = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stepOver() {
        try {
            log.debug("stepOver");

            outputStream.write(STEP_OVER.getBytes("UTF8"));
            ready = false;
{'fraction_non_alphanumeric': 0.09770547301109649, 'fraction_numerical': 0.007240925333834869, 'mean_word_length': 2.4811783960720133, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '3616597', 'n_tokens_mistral': 2955, 'n_tokens_neox': 2825, 'n_words': 748}