Example usage for com.google.common.collect TreeRangeMap put

List of usage examples for com.google.common.collect TreeRangeMap put

Introduction

In this page you can find the example usage for com.google.common.collect TreeRangeMap put.

Prototype

@Override
    public void put(Range<K> range, V value) 

Source Link

Usage

From source file:eu.trentorise.opendata.semtext.SemText.java

/**
 * Returns the terms enclosed by enclosingSpan as a new TreeRangeMap.
 *//*from w ww  .j  av a 2 s .c  o  m*/
private static TreeRangeMap<Integer, Term> enclosingNewTerms(Span enclosingSpan,
        RangeMap<Integer, Term> termRanges) {
    TreeRangeMap<Integer, Term> ret = TreeRangeMap.create();

    Range enclosingRange = spanToRange(enclosingSpan);

    RangeMap<Integer, Term> subRangeMap = termRanges.subRangeMap(enclosingRange);

    for (Map.Entry<Range<Integer>, Term> termEntry : subRangeMap.asMapOfRanges().entrySet()) {
        if (enclosingRange.encloses(spanToRange(termEntry.getValue()))) {
            ret.put(termEntry.getKey(), termEntry.getValue());
        }
    }

    return ret;
}

From source file:com.google.googlejavaformat.java.ModifierOrderer.java

/**
 * Reorders all modifiers in the given text and within the given character ranges to be in JLS
 * order./*w ww  .j  a  v  a 2  s .  c  o  m*/
 */
static JavaInput reorderModifiers(JavaInput javaInput, Collection<Range<Integer>> characterRanges)
        throws FormatterException {
    if (javaInput.getTokens().isEmpty()) {
        // There weren't any tokens, possible because of a lexing error.
        // Errors about invalid input will be reported later after parsing.
        return javaInput;
    }
    RangeSet<Integer> tokenRanges = javaInput.characterRangesToTokenRanges(characterRanges);
    Iterator<? extends Token> it = javaInput.getTokens().iterator();
    TreeRangeMap<Integer, String> replacements = TreeRangeMap.create();
    while (it.hasNext()) {
        Token token = it.next();
        if (!tokenRanges.contains(token.getTok().getIndex())) {
            continue;
        }
        Modifier mod = asModifier(token);
        if (mod == null) {
            continue;
        }

        List<Token> modifierTokens = new ArrayList<>();
        List<Modifier> mods = new ArrayList<>();

        int begin = token.getTok().getPosition();
        mods.add(mod);
        modifierTokens.add(token);

        int end = -1;
        while (it.hasNext()) {
            token = it.next();
            mod = asModifier(token);
            if (mod == null) {
                break;
            }
            mods.add(mod);
            modifierTokens.add(token);
            end = token.getTok().getPosition() + token.getTok().length();
        }

        if (!Ordering.natural().isOrdered(mods)) {
            Collections.sort(mods);
            StringBuilder replacement = new StringBuilder();
            for (int i = 0; i < mods.size(); i++) {
                if (i > 0) {
                    addTrivia(replacement, modifierTokens.get(i).getToksBefore());
                }
                replacement.append(mods.get(i).toString());
                if (i < (modifierTokens.size() - 1)) {
                    addTrivia(replacement, modifierTokens.get(i).getToksAfter());
                }
            }
            replacements.put(Range.closedOpen(begin, end), replacement.toString());
        }
    }
    return applyReplacements(javaInput, replacements);
}

From source file:org.mskcc.juber.intervals.IntervalNameMap.java

private void add(List<TreeRangeMap<Integer, String>> contigRanges, Range<Integer> range, String name) {
    TreeRangeMap<Integer, String> map = null;

    // find the first tree range map that has no range conflicting
    // with the given range
    // this is because Guava range maps don't accommodate intersecting
    // ranges// w  w w. j a  v a2 s  .  co  m
    int index = 0;
    for (; index < contigRanges.size(); index++) {
        map = contigRanges.get(index);
        if (map.subRangeMap(range).asMapOfRanges().size() == 0) {
            break;
        }
    }

    // did not break, requires adding new map
    if (index == contigRanges.size()) {
        map = TreeRangeMap.create();
        contigRanges.add(map);
    }

    // add the current range to the selected map
    map.put(range, name);
}

From source file:com.google.googlejavaformat.java.StringWrapper.java

/**
 * Reflows string literals in the given Java source code that extend past the given column limit.
 *//*from  w  ww  . j  a va  2s . com*/
static String wrap(final int columnLimit, final String input) throws FormatterException {
    if (!longLines(columnLimit, input)) {
        // fast path
        return input;
    }

    JCTree.JCCompilationUnit unit = parse(input, /* allowStringFolding= */ false);
    String separator = Newlines.guessLineSeparator(input);

    // Paths to string literals that extend past the column limit.
    List<TreePath> toFix = new ArrayList<>();
    final Position.LineMap lineMap = unit.getLineMap();
    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitLiteral(LiteralTree literalTree, Void aVoid) {
            if (literalTree.getKind() != Kind.STRING_LITERAL) {
                return null;
            }
            Tree parent = getCurrentPath().getParentPath().getLeaf();
            if (parent instanceof MemberSelectTree
                    && ((MemberSelectTree) parent).getExpression().equals(literalTree)) {
                return null;
            }
            int endPosition = getEndPosition(unit, literalTree);
            int lineEnd = endPosition;
            while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
                lineEnd++;
            }
            if (lineMap.getColumnNumber(lineEnd) - 1 <= columnLimit) {
                return null;
            }
            toFix.add(getCurrentPath());
            return null;
        }
    }.scan(new TreePath(unit), null);

    TreeRangeMap<Integer, String> replacements = TreeRangeMap.create();
    for (TreePath path : toFix) {
        // Find the outermost contiguous enclosing concatenation expression
        TreePath enclosing = path;
        while (enclosing.getParentPath().getLeaf().getKind() == Tree.Kind.PLUS) {
            enclosing = enclosing.getParentPath();
        }
        // Is the literal being wrapped the first in a chain of concatenation expressions?
        // i.e. `ONE + TWO + THREE`
        // We need this information to handle continuation indents.
        AtomicBoolean first = new AtomicBoolean(false);
        // Finds the set of string literals in the concat expression that includes the one that needs
        // to be wrapped.
        List<Tree> flat = flatten(input, unit, path, enclosing, first);
        // Zero-indexed start column
        int startColumn = lineMap.getColumnNumber(getStartPosition(flat.get(0))) - 1;

        // Handling leaving trailing non-string tokens at the end of the literal,
        // e.g. the trailing `);` in `foo("...");`.
        int end = getEndPosition(unit, getLast(flat));
        int lineEnd = end;
        while (Newlines.hasNewlineAt(input, lineEnd) == -1) {
            lineEnd++;
        }
        int trailing = lineEnd - end;

        // Get the original source text of the string literals, excluding `"` and `+`.
        ImmutableList<String> components = stringComponents(input, unit, flat);
        replacements.put(Range.closedOpen(getStartPosition(flat.get(0)), getEndPosition(unit, getLast(flat))),
                reflow(separator, columnLimit, startColumn, trailing, components, first.get()));
    }
    String result = applyReplacements(input, replacements);

    {
        // We really don't want bugs in this pass to change the behaviour of programs we're
        // formatting, so check that the pretty-printed AST is the same before and after reformatting.
        String expected = parse(input, /* allowStringFolding= */ true).toString();
        String actual = parse(result, /* allowStringFolding= */ true).toString();
        if (!expected.equals(actual)) {
            throw new FormatterException(String.format("Something has gone terribly wrong. Please file a bug: "
                    + "https://github.com/google/google-java-format/issues/new"
                    + "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n", actual, expected));
        }
    }

    return result;
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.DetailsChartLane.java

/**
 * Given information about the current layout pass so far and about a
 * particular node, compute the y position of that node.
 *
 *
 * @param yMin    the smallest (towards the top of the screen) y position to
 *                consider/*from   w w w . j  a  v a2s.com*/
 * @param h       the height of the node we are trying to position
 * @param maxXatY a map from y ranges to the max x within that range. NOTE:
 *                This map will be updated to include the node in question.
 * @param xLeft   the left x-cord of the node to position
 * @param xRight  the left x-cord of the node to position
 *
 * @return the y position for the node in question.
 *
 *
 */
double computeYTop(double yMin, double h, TreeRangeMap<Double, Double> maxXatY, double xLeft, double xRight) {
    double yTop = yMin;
    double yBottom = yTop + h;
    //until the node is not overlapping any others try moving it down.
    boolean overlapping = true;
    while (overlapping) {
        overlapping = false;
        //check each pixel from bottom to top.
        for (double y = yBottom; y >= yTop; y -= MINIMUM_ROW_HEIGHT) {
            final Double maxX = maxXatY.get(y);
            if (maxX != null && maxX >= xLeft - MINIMUM_EVENT_NODE_GAP) {
                //if that pixel is already used
                //jump top to this y value and repeat until free slot is found.
                overlapping = true;
                yTop = y + MINIMUM_EVENT_NODE_GAP;
                yBottom = yTop + h;
                break;
            }
        }
    }
    maxXatY.put(Range.closed(yTop, yBottom), xRight);
    return yTop;
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.EventDetailsChart.java

/**
 * layout the nodes in the given list, starting form the given minimum y
 * coordinate./*from ww w  .  j av a  2s . com*/
 *
 * Layout the nodes representing events via the following algorithm.
 *
 * we start with a list of nodes (each representing an event) - sort the
 * list of nodes by span start time of the underlying event - initialize
 * empty map (maxXatY) from y-position to max used x-value - for each node:
 *
 * -- size the node based on its children (recursively)
 *
 * -- get the event's start position from the dateaxis
 *
 * -- to position node (1)check if maxXatY is to the left of the left x
 * coord: if maxXatY is less than the left x coord, good, put the current
 * node here, mark right x coord as maxXatY, go to next node ; if maxXatY
 * greater than start position, increment y position, do check(1) again
 * until maxXatY less than start position
 *
 * @param nodes collection of nodes to layout
 * @param minY  the minimum y coordinate to position the nodes at.
 */
double layoutEventBundleNodes(final Collection<? extends EventBundleNodeBase<?, ?, ?>> nodes,
        final double minY) {

    TreeRangeMap<Double, Double> treeRangeMap = TreeRangeMap.create();
    // maximum y values occupied by any of the given nodes,  updated as nodes are layed out.
    double localMax = minY;

    Set<String> activeQuickHidefilters = getController().getQuickHideFilters().stream()
            .filter(AbstractFilter::isActive).map(DescriptionFilter::getDescription)
            .collect(Collectors.toSet());
    //for each node do a recursive layout to size it and then position it in first available slot
    for (EventBundleNodeBase<?, ?, ?> bundleNode : nodes) {
        //is the node hiden by a quick hide filter?
        boolean quickHide = activeQuickHidefilters.contains(bundleNode.getDescription());
        if (quickHide) {
            //hide it and skip layout
            bundleNode.setVisible(false);
            bundleNode.setManaged(false);
        } else {
            bundleLayoutHelper(bundleNode);
            //get computed height and width
            double h = bundleNode.getBoundsInLocal().getHeight();
            double w = bundleNode.getBoundsInLocal().getWidth();
            //get left and right x coords from axis plus computed width
            double xLeft = getXForEpochMillis(bundleNode.getStartMillis())
                    - bundleNode.getLayoutXCompensation();
            double xRight = xLeft + w + MINIMUM_EVENT_NODE_GAP;

            //initial test position
            double yTop = minY;

            if (oneEventPerRow.get()) {
                // if onePerRow, just put it at end
                yTop = (localMax + MINIMUM_EVENT_NODE_GAP);
            } else {
                double yBottom = yTop + h;

                //until the node is not overlapping any others try moving it down.
                boolean overlapping = true;
                while (overlapping) {
                    overlapping = false;
                    //check each pixel from bottom to top.
                    for (double y = yBottom; y >= yTop; y--) {
                        final Double maxX = treeRangeMap.get(y);
                        if (maxX != null && maxX >= xLeft - MINIMUM_EVENT_NODE_GAP) {
                            //if that pixel is already used
                            //jump top to this y value and repeat until free slot is found.
                            overlapping = true;
                            yTop = y + MINIMUM_EVENT_NODE_GAP;
                            yBottom = yTop + h;
                            break;
                        }
                    }
                }
                treeRangeMap.put(Range.closed(yTop, yBottom), xRight);
            }

            localMax = Math.max(yTop + h, localMax);

            if ((xLeft != bundleNode.getLayoutX()) || (yTop != bundleNode.getLayoutY())) {

                //animate node to new position
                Timeline timeline = new Timeline(
                        new KeyFrame(Duration.millis(100), new KeyValue(bundleNode.layoutXProperty(), xLeft),
                                new KeyValue(bundleNode.layoutYProperty(), yTop)));
                timeline.setOnFinished((ActionEvent event) -> {
                    requestChartLayout();
                });
                timeline.play();
            }
        }
    }
    return localMax; //return new max
}