All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fxmisc.richtext.model.SegmentOps Maven / Gradle / Ivy

The newest version!
package org.fxmisc.richtext.model;

import java.util.Optional;

import org.reactfx.util.Either;

/**
 * Defines the operations which are supported on a specific segment type.
 *
 * @param  The segment type
 * @param  The style type for the segment
 */
public interface SegmentOps {
    public int length(SEG seg);

    public char charAt(SEG seg, int index);

    public String getText(SEG seg);

    public SEG subSequence(SEG seg, int start, int end);

    public SEG subSequence(SEG seg, int start);

    public S getStyle(SEG seg);

    public SEG setStyle(SEG seg, S style);

    public Optional join(SEG currentSeg, SEG nextSeg);

    public SEG createEmpty();

    public default  SegmentOps, S> or(SegmentOps rOps) {
        return either(this, rOps);
    }

    public default  TextOps, S> or_(TextOps rOps) {
        return TextOps.eitherR(this, rOps);
    }

    public static  SegmentOps, S> either(SegmentOps lOps, SegmentOps rOps) {
        return new EitherSegmentOps<>(lOps, rOps);
    }
}

class EitherSegmentOps implements SegmentOps, S> {

    private final SegmentOps lOps;
    private final SegmentOps rOps;

    EitherSegmentOps(SegmentOps lOps, SegmentOps rOps) {
        this.lOps = lOps;
        this.rOps = rOps;
    }


    @Override
    public int length(Either seg) {
        return seg.unify(lOps::length, rOps::length);
    }

    @Override
    public char charAt(Either seg, int index) {
        return seg.unify(l -> lOps.charAt(l, index),
                         r -> rOps.charAt(r, index));
    }

    @Override
    public String getText(Either seg) {
        return seg.unify(lOps::getText, rOps::getText);
    }

    @Override
    public Either subSequence(Either seg, int start, int end) {
        return seg.map(l -> lOps.subSequence(l, start, end),
                       r -> rOps.subSequence(r, start, end));
    }

    @Override
    public Either subSequence(Either seg, int start) {
        return seg.map(l -> lOps.subSequence(l, start),
                       r -> rOps.subSequence(r, start));
    }

    @Override
    public S getStyle(Either seg) {
        return seg.unify(lOps::getStyle,
                         rOps::getStyle);
    }

    @Override
    public Either setStyle(Either seg, S style) {
        return seg.map(l -> lOps.setStyle(l, style),
                       r -> rOps.setStyle(r, style));
    }

    @Override
    public Optional> join(Either left, Either right) {
        return left.unify(ll -> right.unify(rl -> lOps.join(ll, rl).map(Either::left), rr -> Optional.empty()),
                          lr -> right.unify(rl -> Optional.empty(), rr -> rOps.join(lr, rr).map(Either::right)));
    }

    public Either createEmpty() {
        return Either.left(lOps.createEmpty());
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy