Search in sources :

Example 1 with Xterm256

use of coloring.Xterm256 in project ASCIIGenome by dariober.

the class TrackSet method setFeatureColorForRegex.

public void setFeatureColorForRegex(List<String> cmdTokens) throws InvalidCommandLineException, InvalidColourException {
    List<String> argList = new ArrayList<String>(cmdTokens);
    // Remove cmd name
    argList.remove(0);
    // Collect all regex/color pairs from input. We move left to right along the command
    // arguments and collect -r/-R and set the regex inversion accordingly.
    List<Argument> colorForRegex = new ArrayList<Argument>();
    new Xterm256();
    while (argList.contains("-r") || argList.contains("-R")) {
        int r = argList.indexOf("-r") >= 0 ? argList.indexOf("-r") : Integer.MAX_VALUE;
        int R = argList.indexOf("-R") >= 0 ? argList.indexOf("-R") : Integer.MAX_VALUE;
        List<String> pair;
        boolean invert = false;
        if (r < R) {
            pair = Utils.getNArgsForParam(argList, "-r", 2);
        } else {
            pair = Utils.getNArgsForParam(argList, "-R", 2);
            invert = true;
        }
        String pattern = pair.get(0);
        try {
            // Check valid regex
            Pattern.compile(pattern);
        } catch (PatternSyntaxException e) {
            System.err.println("Invalid regex: " + pattern);
            throw new InvalidCommandLineException();
        }
        Argument xcolor = new Argument(pair.get(0), pair.get(1), invert);
        // Check this is a valid colour
        Xterm256.colorNameToXterm256(xcolor.getArg());
        colorForRegex.add(xcolor);
    }
    if (colorForRegex.size() == 0) {
        colorForRegex = null;
    }
    boolean invertSelection = Utils.argListContainsFlag(argList, "-v");
    // Regex to capture tracks: All positional args left
    List<String> trackNameRegex = new ArrayList<String>();
    if (argList.size() > 0) {
        trackNameRegex = argList;
    } else {
        // Default: Capture everything
        trackNameRegex.add(".*");
    }
    // Set as appropriate
    List<Track> tracksToReset = this.matchTracks(trackNameRegex, true, invertSelection);
    for (Track tr : tracksToReset) {
        tr.setColorForRegex(colorForRegex);
    }
}
Also used : Xterm256(coloring.Xterm256) ArrayList(java.util.ArrayList) InvalidCommandLineException(exceptions.InvalidCommandLineException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 2 with Xterm256

use of coloring.Xterm256 in project ASCIIGenome by dariober.

the class Main method main.

public static void main(String[] args) throws IOException, InvalidGenomicCoordsException, InvalidCommandLineException, InvalidRecordException, BamIndexNotFoundException, ClassNotFoundException, SQLException, DocumentException, UnindexableFastaFileException, InvalidColourException, InvalidConfigException {
    /* Start parsing arguments * 
		 * *** If you change something here change also in console input ***/
    Namespace opts = ArgParse.argParse(args);
    List<String> initFileList = opts.getList("input");
    String region = opts.getString("region");
    final String fasta = opts.getString("fasta");
    String exec = opts.getString("exec");
    String config = opts.getString("config");
    exec = parseExec(exec);
    int debug = opts.getInt("debug");
    // Get configuration. Note that we don't need to assign this to a variable.
    new Config(config);
    new Xterm256();
    ASCIIGenomeHistory asciiGenomeHistory = new ASCIIGenomeHistory();
    // Init console right at start so if something goes wrong the user's terminal is reset to
    // initial defaults with the shutdown hook. This could be achieved in cleaner way probably.
    ConsoleReader console = initConsole();
    messageVersion(opts.getBoolean("noFormat"));
    /* Set up console */
    Utils.checkFasta(fasta, debug);
    /* Test input files exist */
    List<String> inputFileList = new ArrayList<String>();
    Utils.addSourceName(inputFileList, initFileList, debug);
    if (region == null || region.isEmpty()) {
        region = initRegion(inputFileList, fasta, null, debug);
    }
    int terminalWidth = Utils.getTerminalWidth();
    GenomicCoords initGc = new GenomicCoords(region, terminalWidth, null, null);
    List<String> initGenomeList = new ArrayList<String>();
    for (String x : inputFileList) {
        initGenomeList.add(x);
    }
    initGenomeList.add(fasta);
    initGc.setGenome(initGenomeList, false);
    // ----------------------------
    // Genomic positions start here:
    final GenomicCoordsHistory gch = new GenomicCoordsHistory();
    GenomicCoords start = new GenomicCoords(initGc.toStringRegion(), terminalWidth, initGc.getSamSeqDict(), initGc.getFastaFile());
    gch.readHistory(asciiGenomeHistory.getFileName(), start);
    gch.add(start);
    final TrackSet trackSet = new TrackSet(inputFileList, gch.current());
    trackSet.addHistoryFiles(asciiGenomeHistory.getFiles());
    setDefaultTrackHeights(console.getTerminal().getHeight(), trackSet.getTrackList());
    final TrackProcessor proc = new TrackProcessor(trackSet, gch);
    proc.setShowMem(opts.getBoolean("showMem"));
    proc.setShowTime(opts.getBoolean("showTime"));
    proc.setNoFormat(opts.getBoolean("noFormat"));
    // Put here the previous command so that it is re-issued if no input is given
    // You have to initialize this var outside the while loop that processes input files.
    String currentCmdConcatInput = "";
    if (!proc.isNoFormat()) {
        String str = String.format("\033[48;5;%sm", Config.get256Color(ConfigKey.background));
        System.out.print(str);
    }
    // Batch processing file of regions
    final String batchFile = opts.getString("batchFile");
    if (batchFile != null && !batchFile.isEmpty()) {
        console.clearScreen();
        console.flush();
        BufferedReader br = batchFileReader(batchFile);
        String line = null;
        while ((line = br.readLine()) != null) {
            // Start processing intervals one by one
            IntervalFeature target = new IntervalFeature(line, TrackFormat.BED, null);
            String reg = target.getChrom() + ":" + target.getFrom() + "-" + target.getTo();
            String gotoAndExec = ("goto " + reg + " && " + exec).trim().replaceAll("&&$", "");
            InteractiveInput itr = new InteractiveInput(console);
            itr.processInput(gotoAndExec, proc, debug);
            if (itr.getInteractiveInputExitCode().equals(ExitCode.ERROR)) {
                System.err.println("Error processing '" + gotoAndExec + "' at line '" + line + "'");
                System.exit(1);
            }
        }
        br.close();
        return;
    }
    // See if we need to process the exec arg before going to interactive mode.
    // Also if we are in non-interactive mode, we process the track set now and later exit
    console.clearScreen();
    console.flush();
    proc.iterateTracks();
    if (!exec.isEmpty() || opts.getBoolean("nonInteractive")) {
        InteractiveInput itr = new InteractiveInput(console);
        itr.processInput(exec, proc, debug);
        if (opts.getBoolean("nonInteractive")) {
            System.out.print("\033[0m");
            return;
        }
    }
    /* Set up done, start processing */
    /* ============================= */
    console.setHistory(asciiGenomeHistory.getCommandHistory());
    writeYamlHistory(asciiGenomeHistory, console.getHistory(), trackSet, gch);
    while (true) {
        // keep going until quit or if no interactive input set
        // *** START processing interactive input
        // String like "zi && -F 16 && mapq 10"
        String cmdConcatInput = "";
        InteractiveInput interactiveInput = new InteractiveInput(console);
        ExitCode currentExitCode = ExitCode.NULL;
        interactiveInput.setInteractiveInputExitCode(currentExitCode);
        while (!interactiveInput.getInteractiveInputExitCode().equals(ExitCode.ERROR) || interactiveInput.getInteractiveInputExitCode().equals(ExitCode.NULL)) {
            console.setPrompt(StringUtils.repeat(' ', proc.getWindowSize()) + '\r' + "[h] for help: ");
            cmdConcatInput = console.readLine().trim();
            if (cmdConcatInput.isEmpty()) {
                // Empty input: User only issued <ENTER>
                if (interactiveInput.getInteractiveInputExitCode().equals(ExitCode.CLEAN)) {
                    // User only issued <ENTER>: Repeat previous command if the exit code was not an error.
                    cmdConcatInput = currentCmdConcatInput;
                } else {
                    // Refresh screen if the exit code was not CLEAN.
                    cmdConcatInput = "+0";
                }
            }
            interactiveInput.processInput(cmdConcatInput, proc, debug);
            currentCmdConcatInput = cmdConcatInput;
        }
    // *** END processing interactive input
    }
}
Also used : Xterm256(coloring.Xterm256) TrackSet(tracks.TrackSet) ConsoleReader(jline.console.ConsoleReader) Config(coloring.Config) ArrayList(java.util.ArrayList) Namespace(net.sourceforge.argparse4j.inf.Namespace) BufferedReader(java.io.BufferedReader) IntervalFeature(tracks.IntervalFeature)

Aggregations

Xterm256 (coloring.Xterm256)2 ArrayList (java.util.ArrayList)2 Config (coloring.Config)1 InvalidCommandLineException (exceptions.InvalidCommandLineException)1 BufferedReader (java.io.BufferedReader)1 PatternSyntaxException (java.util.regex.PatternSyntaxException)1 ConsoleReader (jline.console.ConsoleReader)1 Namespace (net.sourceforge.argparse4j.inf.Namespace)1 IntervalFeature (tracks.IntervalFeature)1 TrackSet (tracks.TrackSet)1