@org.scijava.plugin.Parameter

Here are the examples of the java api @org.scijava.plugin.Parameter taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

91 Examples 7

19 Source : NotebookOutputConverter.java
with Apache License 2.0
from scijava

/**
 * @author Hadrien Mary
 */
public abstract clreplaced NotebookOutputConverter<I, O extends NotebookOutput> extends AbstractConverter<I, O> {

    @Parameter
    private LogService log;

    @Override
    public <T> T convert(final Object src, final Clreplaced<T> dest) {
        if (src == null) {
            throw new IllegalArgumentException("Null input");
        }
        if (!this.getInputType().isInstance(src)) {
            throw new IllegalArgumentException("Expected input of type " + getInputType().getSimpleName() + ", but got " + src.getClreplaced().getSimpleName());
        }
        return (T) this.convert(src);
    }

    public abstract O convert(Object object);
}

19 Source : NotebookConverters.java
with Apache License 2.0
from scijava

/**
 * Utility clreplaced for converters.
 *
 * @author Alison Walter
 */
public clreplaced NotebookConverters {

    @Parameter
    private static LogService log;

    // TODO: Move this further upstream, possible in SciJava AWT?
    public static String toPNG(BufferedImage bi) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "PNG", os);
        } catch (IOException ex) {
            log.error(ex);
        }
        return Base64.getEncoder().encodeToString(os.toByteArray());
    }
}

19 Source : MapToHTMLTableNotebookConverter.java
with Apache License 2.0
from scijava

/**
 * Converts a {@code Map} to a two column HTML table. The headers for this table
 * are Key and Value.
 *
 * @author Alison Walter
 * @param <K> data type used for the key
 * @param <V> data type used for the values
 */
@Plugin(type = Converter.clreplaced)
public clreplaced MapToHTMLTableNotebookConverter<K, V> extends HTMLNotebookOutputConverter<Map<K, V>, HTMLTableNotebookOutput> {

    @Parameter
    private ConvertService convertService;

    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Clreplaced<Map<K, V>> getInputType() {
        return (Clreplaced) Map.clreplaced;
    }

    @Override
    public Clreplaced<HTMLTableNotebookOutput> getOutputType() {
        return HTMLTableNotebookOutput.clreplaced;
    }

    @Override
    public HTMLTableNotebookOutput convert(final Object object) {
        @SuppressWarnings("unchecked")
        final Map<K, V> table = (Map<K, V>) object;
        // Default headings for a map are Key and Value
        String htmlTable = HTMLTableBuilder.startTable();
        htmlTable += HTMLTableBuilder.appendHeadings("Key", false);
        htmlTable += HTMLTableBuilder.appendHeadings("Value", true);
        // Append the rows
        for (final K key : table.keySet()) {
            final String k = asHTML(key);
            final String v = asHTML(table.get(key));
            htmlTable += HTMLTableBuilder.appendData(k, true, false);
            htmlTable += HTMLTableBuilder.appendData(v, false, true);
        }
        htmlTable += HTMLTableBuilder.endTable();
        return new HTMLTableNotebookOutput(HTMLTableBuilder.getTableStyle(false) + htmlTable);
    }
}

19 Source : HTMLNotebookOutputConverter.java
with Apache License 2.0
from scijava

/**
 * Base clreplaced for converters to {@link HTMLNotebookOutput} and subclreplacedes.
 *
 * @author Curtis Rueden
 */
public abstract clreplaced HTMLNotebookOutputConverter<I, O extends HTMLNotebookOutput> extends NotebookOutputConverter<I, O> {

    @Parameter
    private ConvertService convertService;

    /**
     * Gets an HTML string representing the given object.
     */
    protected String asHTML(final Object o) {
        final HTMLFriendlyNotebookOutput converted = convertService.convert(o, HTMLFriendlyNotebookOutput.clreplaced);
        return converted == null ? "<none>" : converted.toHTML();
    }
}

19 Source : ScijavaKernel.java
with Apache License 2.0
from scijava

/**
 * @author Hadrien Mary
 */
public clreplaced ScijavaKernel extends Kernel {

    // Scijava context
    Context context;

    @Parameter
    private transient LogService log;

    private final ScijavaKernelConfigurationFile config;

    public ScijavaKernel(final Context context, final String id, final ScijavaEvaluator evaluator, ScijavaKernelConfigurationFile config, KernelSocketsFactory kernelSocketsFactory) {
        super(id, evaluator, kernelSocketsFactory);
        this.context = context;
        this.context.inject(this);
        this.config = config;
        // Don't show output when it is null
        Kernel.showNullExecutionResult = false;
        this.setLogLevel(config.getLogLevel());
        log.info("Log level used is : " + this.config.getLogLevel());
        log.info("Scijava Kernel is started and ready to use.");
    }

    @Override
    public CommOpenHandler getCommOpenHandler(Kernel kernel) {
        return new ScijavaCommOpenHandler(kernel);
    }

    @Override
    public KernelHandler<Message> getKernelInfoHandler(Kernel kernel) {
        return new ScijavaKernelInfoHandler(kernel);
    }

    private void setLogLevel(String logLevel) {
        switch(logLevel) {
            case "debug":
                this.log.setLevel(LogLevel.DEBUG);
                break;
            case "error":
                this.log.setLevel(LogLevel.ERROR);
                break;
            case "info":
                this.log.setLevel(LogLevel.INFO);
                break;
            case "none":
                this.log.setLevel(LogLevel.NONE);
                break;
            default:
                this.log.setLevel(LogLevel.INFO);
                break;
        }
    }

    public static void main(String... args) {
        final Context context = new Context();
        // Remove the Display and Results post-processors to prevent output
        // windows from being displayed
        final PluginService pluginService = context.service(PluginService.clreplaced);
        final PluginInfo<SciJavaPlugin> display = pluginService.getPlugin(DisplayPostprocessor.clreplaced);
        final PluginInfo<SciJavaPlugin> results = pluginService.getPlugin(ResultsPostprocessor.clreplaced);
        pluginService.removePlugin(display);
        pluginService.removePlugin(results);
        JupyterService jupyter = context.service(JupyterService.clreplaced);
        jupyter.runKernel(args);
        context.dispose();
    }
}

19 Source : ScijavaEvaluator.java
with Apache License 2.0
from scijava

/**
 * @author Hadrien Mary
 */
public clreplaced ScijavaEvaluator implements Evaluator {

    public static final String DEFAULT_LANGUAGE = "groovy";

    @Parameter
    private LogService log;

    @Parameter
    private transient ScriptService scriptService;

    @Parameter
    private ThreadService threadService;

    @Parameter
    Context context;

    private final Map<String, ScriptEngine> scriptEngines;

    private final Map<String, ScriptLanguage> scriptLanguages;

    private final Map<String, AutoCompleter> completers;

    private String languageName;

    protected String shellId;

    protected String sessionId;

    public ScijavaEvaluator(Context context, String shellId, String sessionId) {
        context.inject(this);
        this.shellId = shellId;
        this.sessionId = sessionId;
        this.scriptEngines = new HashMap<>();
        this.scriptLanguages = new HashMap<>();
        this.completers = new HashMap<>();
        this.languageName = DEFAULT_LANGUAGE;
    }

    @Override
    public void setShellOptions(EvaluatorParameters kp) throws IOException {
        log.debug("Set shell options : " + kp);
    }

    @Override
    public AutocompleteResult autocomplete(String code, int index) {
        // Get only the line corresponding to the index.
        List<String> lines = Arrays.asList(code.substring(0, index).split("\n"));
        String line = lines.get(lines.size() - 1);
        // TODO: we need to find a way the language related to the current cell.
        // For now, we are just using the last used language.
        AutoCompleter completer = this.completers.get(this.languageName);
        ScriptEngine scriptEngine = this.scriptEngines.get(this.languageName);
        List<String> matches;
        int startIndex;
        if (completer != null) {
            AutoCompletionResult result = completer.autocomplete(line, index, scriptEngine);
            matches = result.getMatches();
            startIndex = index;
        } else {
            matches = new ArrayList<>();
            startIndex = 0;
        }
        // Reconstruct each matches with the correct index
        List<String> newMatches = new ArrayList<>();
        String newLine;
        for (String match : matches) {
            lines.set(lines.size() - 1, match);
            newLine = lines.stream().collect(Collectors.joining("\n"));
            newMatches.add(newLine.substring(startIndex, newLine.length()));
        }
        return new AutocompleteResult(newMatches, startIndex);
    }

    @Override
    public void killAllThreads() {
        log.debug("Kill All Threads");
        // Ugly and not working :-(
        System.exit(0);
    }

    @Override
    public void evaluate(SimpleEvaluationObject seo, String code) {
        code = this.setLanguage(code);
        Worker worker = new Worker(this.context, this.scriptEngines, this.scriptLanguages);
        worker.setup(seo, code, this.languageName);
        this.threadService.queue(getClreplaced().getName(), worker);
    }

    @Override
    public void exit() {
        log.debug("Exiting DefaultEvaluator");
        // Ugly and not working :-(
        System.exit(0);
    }

    private void addLanguage(String langName) {
        if (scriptService.getLanguageByName(langName) == null) {
            log.error("Script Language for '" + langName + "' not found.");
            System.exit(1);
        }
        if (!this.scriptLanguages.keySet().contains(langName)) {
            Bindings bindings = null;
            if (!this.scriptEngines.isEmpty()) {
                String firstLanguage = this.scriptEngines.keySet().iterator().next();
                bindings = this.scriptEngines.get(firstLanguage).getBindings(ScriptContext.ENGINE_SCOPE);
            }
            log.info("Script Language for '" + langName + "' found.");
            ScriptLanguage scriptLanguage = scriptService.getLanguageByName(langName);
            this.scriptLanguages.put(langName, scriptLanguage);
            ScriptEngine engine = this.scriptLanguages.get(langName).getScriptEngine();
            this.scriptEngines.put(langName, engine);
            AutoCompleter completer = scriptLanguage.getAutoCompleter();
            this.completers.put(languageName, completer);
            // Not implemented yet
            // engine.setBindings(this.bindings, ScriptContext.ENGINE_SCOPE);
            if (bindings != null) {
                this.initBindings(bindings, engine, scriptLanguage);
            }
        }
        log.debug("Script Language found for '" + langName + "'");
    }

    private String setLanguage(String code) {
        if (code.startsWith("#!")) {
            // If code is composed of multiple lines
            if (code.split("\n").length > 1) {
                this.languageName = code.substring(2, code.indexOf("\n")).trim();
                // Return the code string without the first line
                code = code.substring(code.indexOf("\n") + 1);
            } else // If only one line
            {
                this.languageName = code.substring(2).trim();
                code = "";
            }
        }
        this.addLanguage(this.languageName);
        return code;
    }

    private void initBindings(Bindings bindings, ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {
        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.keySet().forEach((String key) -> {
            currentBindings.put(key, scriptLanguage.decode(bindings.get(key)));
        });
    }

    @Override
    public Clreplacedpath getClreplacedpath() {
        log.debug("addJarToClreplacedpath()");
        return null;
    }

    @Override
    public Imports getImports() {
        log.debug("addJarToClreplacedpath()");
        return null;
    }

    @Override
    public void addImport(ImportPath ip) {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public void resetEnvironment() {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public void removeImport(ImportPath ip) {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public List<Path> addJarsToClreplacedpath(List<PathToJar> list) {
        log.debug("addJarsToClreplacedpath()");
        return null;
    }

    @Override
    public boolean addJarToClreplacedpath(PathToJar ptj) {
        log.debug("addJarToClreplacedpath()");
        return true;
    }

    @Override
    public void cancelExecution() {
        log.debug("cancelExecution()");
    }

    @Override
    public Path getTempFolder() {
        log.debug("getTempFolder()");
        try {
            return FileUtils.createTemporaryDirectory("scijava-jupyter-kernel", null).toPath();
        } catch (final IOException exc) {
            throw new RuntimeException(exc);
        }
    }

    @Override
    public Clreplaced<?> loadClreplaced(String clazzName) throws ClreplacedNotFoundException {
        log.debug("loadClreplaced()");
        final ClreplacedLoader ccl = Thread.currentThread().getContextClreplacedLoader();
        final ClreplacedLoader cl = ccl == null ? ClreplacedLoader.getSystemClreplacedLoader() : ccl;
        return cl.loadClreplaced(clazzName);
    }
}

19 Source : DefaultImageJNotebookService.java
with Apache License 2.0
from scijava

/**
 * AWT-driven implementation of {@link ImageJNotebookService}.
 *
 * @author Curtis Rueden
 */
@Plugin(type = Service.clreplaced)
public clreplaced DefaultImageJNotebookService extends AbstractService implements ImageJNotebookService {

    @Parameter
    private LogService log;

    @Parameter
    private OpService ops;

    @Override
    public <T extends RealType<T>> Object RAIToPNG(// 
    final RandomAccessibleInterval<T> source, // 
    final int xAxis, // 
    final int yAxis, // 
    final int cAxis, final ValueScaling scaling, final long... pos) {
        final IntervalView<T> image = ops.transform().zeroMinView(source);
        final int w = xAxis >= 0 ? (int) image.dimension(xAxis) : 1;
        final int h = yAxis >= 0 ? (int) image.dimension(yAxis) : 1;
        final int c = cAxis >= 0 ? (int) image.dimension(cAxis) : 1;
        final ARGBScreenImage target = new ARGBScreenImage(w, h);
        final ArrayList<Converter<T, ARGBType>> converters = new ArrayList<>(c);
        final double min, max;
        final boolean full = scaling == ValueScaling.FULL || // 
        scaling == ValueScaling.AUTO && isNarrowType(source);
        if (full) {
            // scale the intensities based on the full range of the type
            min = image.firstElement().getMinValue();
            max = image.firstElement().getMaxValue();
        } else {
            // scale the intensities based on the sample values
            final IterableInterval<T> ii = ops.transform().flareplacederableView(source);
            final Pair<T, T> minMax = ops.stats().minMax(ii);
            min = minMax.getA().getRealDouble();
            max = minMax.getB().getRealDouble();
        }
        for (int i = 0; i < c; i++) {
            final ColorTable8 lut = c == 1 ? // 
            ColorTables.GRAYS : ColorTables.getDefaultColorTable(i);
            converters.add(new RealLUTConverter<>(min, max, lut));
        }
        final CompositeXYProjector<T> proj = new CompositeXYProjector<>(image, target, converters, cAxis);
        if (pos != null && pos.length > 0) {
            proj.setPosition(pos);
        }
        proj.setComposite(true);
        proj.map();
        // Convert to PNG
        return NotebookConverters.toPNG(target.image());
    }

    @Override
    public <T extends RealType<T> & NativeType<T>> RandomAccessibleInterval<T> mosaic(final int[] gridLayout, @SuppressWarnings("unchecked") final RandomAccessibleInterval<T>... images) {
        // Count the actual number of image dimensions.
        int numDims = 0;
        for (RandomAccessibleInterval<T> image : images) {
            numDims = Math.max(numDims, image.numDimensions());
        }
        // Pad any missing grid dimensions.
        final int[] grid = new int[numDims];
        for (int d = 0; d < numDims; d++) {
            grid[d] = d < gridLayout.length ? gridLayout[d] : 1;
        }
        // Define a buffer for holding multidimensional position indices.
        final int[] pos = new int[numDims];
        // Compute grid box extents (width, height, etc.).
        final long[][] extents = new long[numDims][];
        for (int d = 0; d < numDims; d++) {
            extents[d] = new long[grid[d]];
        }
        for (int i = 0; i < images.length; i++) {
            IntervalIndexer.indexToPosition(i, grid, pos);
            for (int d = 0; d < numDims; d++) {
                if (pos[d] < grid[d]) {
                    extents[d][pos[d]] = // 
                    Math.max(extents[d][pos[d]], images[i].dimension(d));
                }
            }
        }
        // Compute grid box offsets.
        final long[][] offsets = new long[numDims][];
        for (int d = 0; d < numDims; d++) {
            offsets[d] = new long[grid[d] + 1];
        }
        for (int d = 0; d < numDims; d++) {
            for (int g = 0; g < grid[d]; g++) {
                offsets[d][g + 1] = offsets[d][g] + extents[d][g];
            }
        }
        // Compute total mosaic dimensions.
        final long[] mosaicDims = new long[numDims];
        for (int d = 0; d < numDims; d++) {
            mosaicDims[d] = offsets[d][offsets[d].length - 1];
        }
        final FinalInterval mosaicBox = new FinalInterval(mosaicDims);
        final Img<T> result = // 
        ops.create().img(mosaicBox, Util.getTypeFromInterval(images[0]));
        for (int i = 0; i < images.length; i++) {
            IntervalIndexer.indexToPosition(i, grid, pos);
            // Skip images which will not appear on the grid.
            boolean outOfBounds = false;
            for (int d = 0; d < numDims; d++) {
                if (pos[d] >= grid[d]) {
                    outOfBounds = true;
                    break;
                }
            }
            if (outOfBounds) {
                continue;
            }
            // Translate the origin of each image to match its position in the mosaic.
            final long[] offset = new long[numDims];
            for (int d = 0; d < numDims; d++) {
                offset[d] = offsets[d][pos[d]];
            }
            final // 
            IntervalView<T> translated = ops.transform().translateView(ops.transform().zeroMinView(images[i]), offset);
            // Declare that all values outside the interval proper will be 0.
            // If we do not perform this step, we will get an error when querying
            // out-of-bounds coordinates.
            final RandomAccessible<T> extended = ops.transform().extendZeroView(translated);
            // Define the interval of the image to match the size of the mosaic.
            final RandomAccessibleInterval<T> expanded = // 
            ops.transform().intervalView(extended, mosaicBox);
            // Add the full-size zero-padded translated image into the mosaic.
            Inplaces.binary1(ops, Ops.Math.Add.clreplaced, result, expanded).mutate1(result, expanded);
        }
        // TODO: Some day, use Views.arrange, Views.tile or Views.combine instead.
        return result;
    }

    // -- Helper methods --
    private <T extends RealType<T>> boolean isNarrowType(final RandomAccessibleInterval<T> source) {
        return Util.getTypeFromInterval(source).getBitsPerPixel() <= 8;
    }
}

19 Source : ResultsTableToHTMLTableNotebookConverter.java
with Apache License 2.0
from scijava

/**
 * Converts a {@link ResultsTable} to an HTML table.
 *
 * @author Alison Walter
 */
@Plugin(type = Converter.clreplaced)
public clreplaced ResultsTableToHTMLTableNotebookConverter extends HTMLNotebookOutputConverter<ResultsTable, HTMLTableNotebookOutput> {

    @Parameter
    private ConvertService convertService;

    @Override
    public Clreplaced<HTMLTableNotebookOutput> getOutputType() {
        return HTMLTableNotebookOutput.clreplaced;
    }

    @Override
    public Clreplaced<ResultsTable> getInputType() {
        return ResultsTable.clreplaced;
    }

    @Override
    public HTMLTableNotebookOutput convert(final Object object) {
        GenericTable t = convertService.convert((ResultsTable) object, GenericTable.clreplaced);
        return convertService.convert(t, HTMLTableNotebookOutput.clreplaced);
    }
}

19 Source : ImagePlusToPNGNotebookConverter.java
with Apache License 2.0
from scijava

/**
 * Converts an {@link ImagePlus} to a PNG.
 *
 * @author Alison Walter
 */
@Plugin(type = Converter.clreplaced)
public clreplaced ImagePlusToPNGNotebookConverter extends NotebookOutputConverter<ImagePlus, PNGImageNotebookOutput> {

    @Parameter
    private LogService log;

    @Override
    public Clreplaced<ImagePlus> getInputType() {
        return ImagePlus.clreplaced;
    }

    @Override
    public Clreplaced<PNGImageNotebookOutput> getOutputType() {
        return PNGImageNotebookOutput.clreplaced;
    }

    @Override
    public PNGImageNotebookOutput convert(final Object object) {
        final ImagePlus imgPlus = (ImagePlus) object;
        final String base64Image = NotebookConverters.toPNG(imgPlus.getBufferedImage());
        return new PNGImageNotebookOutput(base64Image);
    }
}

19 Source : SciViewDisplayViewer.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * SciJava DisplayViewer for SciView
 *
 * @author Kyle Harrington
 */
@Plugin(type = DisplayViewer.clreplaced)
public clreplaced SciViewDisplayViewer extends AbstractDisplayViewer<SciView> {

    @Parameter
    private EventService eventService;

    @Override
    public boolean isCompatible(UserInterface ui) {
        return true;
    }

    @Override
    public boolean canView(Display<?> d) {
        return d instanceof SciViewDisplay;
    }

    @Override
    public void view(UserInterface ui, Display<?> d) {
        Object data = d.get(0);
        if (!(data instanceof SciView))
            throw new IllegalArgumentException("Must be SciView");
        final DisplayWindow w = new SciViewDisplayWindow((SciView) data);
        view(w, d);
    }

    @EventHandler
    protected void onEvent(final DisplayDeletedEvent event) {
    // TODO: Dispose of SciView instance.
    }

    /**
     * Synchronizes the user interface appearance with the display model.
     */
    @Override
    public void onDisplayUpdatedEvent(final DisplayUpdatedEvent e) {
    }

    @Override
    public void onDisplayActivatedEvent(final DisplayActivatedEvent e) {
    // do nothing because no panel
    }
}

19 Source : SciViewDisplay.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * SciJava Display for SciView
 *
 * @author Kyle Harrington
 */
@Plugin(type = Display.clreplaced)
public clreplaced SciViewDisplay extends AbstractDisplay<SciView> {

    @Parameter
    private ThreadService threadService;

    @Parameter(required = false)
    private EventService eventService;

    @Parameter
    private LogService logService;

    public SciViewDisplay() {
        super(SciView.clreplaced);
    }

    public SciViewDisplay(Clreplaced<SciView> type) {
        super(type);
    }

    @EventHandler
    protected void onEvent(final DataRestructuredEvent event) {
    }

    // FIXME - displays should not listen for Data events. Views should listen for
    // data events, adjust themselves, and generate view events. The display
    // clreplacedes should listen for view events and refresh themselves as necessary.
    @EventHandler
    protected void onEvent(final DataUpdatedEvent event) {
    // NB: Placeholder in case it's needed in future.
    }

    @EventHandler
    protected void onEvent(final DisplayDeletedEvent event) {
    // NB: Placeholder in case it's needed in future.
    }
}

19 Source : Isosurface.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to create a mesh from the currently open Image
 * @param <T> a RealType
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Process", weight = PROCESS), @Menu(label = "Isosurface", weight = PROCESS_ISOSURFACE) })
public clreplaced Isosurface<T extends RealType> implements Command {

    @Parameter
    private OpService ops;

    @Parameter
    private SciView sciView;

    @Parameter(persist = false)
    private IterableInterval<T> image;

    @Parameter
    private double isoLevel;

    @Parameter
    private UIService uiService;

    @Override
    public void run() {
        T tmp = (T) image.firstElement().createVariable();
        tmp.setReal(isoLevel);
        Img<BitType> bitImg = (Img<BitType>) ops.threshold().apply(image, tmp);
        Mesh m = Meshes.marchingCubes(bitImg);
        Node scMesh = sciView.addMesh(m);
        ((HasGeometry) scMesh).recalculateNormals();
        scMesh.setScale(new Vector3f(0.001f, 0.001f, 0.001f));
    }
}

19 Source : InteractiveConvexMesh.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Interactively place points that are used to seed a convex hull
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Process", weight = PROCESS), @Menu(label = "Interactively Create Convex Mesh", weight = PROCESS_INTERACTIVE_CONVEX_MESH) })
public clreplaced InteractiveConvexMesh extends InteractiveCommand {

    @Parameter
    private OpService opService;

    @Parameter
    private SciView sciView;

    @Parameter(callback = "createMesh")
    private Button createMesh;

    private Node targetPoint;

    private ControlPoints controlPoints;

    protected float controlPointDistance = 10;

    @Override
    public void run() {
        controlPoints = new ControlPoints();
        controlPoints.initializeSciView(sciView, controlPointDistance);
    }

    /* Create a ConvexHulls of controlPoints */
    public void createMesh() {
        Mesh mesh = new NaiveDoubleMesh();
        for (Vector3f v : controlPoints.getVertices()) {
            mesh.vertices().add(v.x(), v.y(), v.z());
        }
        final List<?> result = (List<?>) opService.run(DefaultConvexHull3D.clreplaced, mesh);
        Mesh hull = (Mesh) result.get(0);
        sciView.addMesh(hull);
        controlPoints.cleanup(sciView);
    }

    @Override
    public void cancel() {
        controlPoints.cleanup(sciView);
    }
}

19 Source : ConvexHull.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to create a convex hull of the currently open mesh
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Process", weight = PROCESS), @Menu(label = "Convex Hull", weight = PROCESS_CONVEX_HULL) })
public clreplaced ConvexHull implements Command {

    @Parameter
    private OpService ops;

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Parameter
    private Node node;

    @Override
    public void run() {
        if (node instanceof Mesh) {
            net.imagej.mesh.Mesh ijMesh = MeshConverter.toImageJ((Mesh) node);
            net.imagej.mesh.Mesh smoothMesh = (net.imagej.mesh.Mesh) ops.geom().convexHull(ijMesh).get(0);
            Node convexHull = sciView.addMesh(smoothMesh);
            convexHull.setPosition(node.getPosition());
        }
    }
}

19 Source : Help.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to show input controls
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Help", weight = HELP), @Menu(label = "Controls", weight = HELP_HELP) })
public clreplaced Help implements Command {

    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        // opens own, not modal!, window with the help
        JFrame frame = new JFrame("SciView Input Controls Overview");
        frame.getContentPane().add(new JScrollPane(new JLabel("<html>" + getBasicUsageText(sciView.publicGetInputHandler()) + "<br><br>" + getKeybindingsAsHtmlFrom(sciView.publicGetInputHandler()))));
        frame.pack();
        frame.setVisible(true);
    }

    public static String getBasicUsageText(final InputHandler inputHandler) {
        // find the current key bindings
        final String lookAround = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("view: freely look around"));
        final String walkW = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_forward"));
        final String walkS = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_back"));
        final String walkA = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_left"));
        final String walkD = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_right"));
        final String walkX = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_down"));
        final String walkC = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_up"));
        final String walkMouse = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("move_withMouse_back/forward/left/right"));
        final String nodeSelect = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("node: choose one from the view panel"));
        final String arcBall = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("view: rotate around selected node"));
        final String arcBallScroll = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("view: zoom outward or toward selected node"));
        final String nodeDrag = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("node: move selected one left, right, up, or down"));
        final String nodeScroll = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("node: move selected one closer or further away"));
        final String nodeRotate = InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings("node: rotate selected one"));
        return lookAround + " and move mouse in the 3D view to look around. Walk freely in the scene along the current look with " + walkW + "/" + walkS + " keys,<br>" + "left/right-ward with " + walkA + "/" + walkD + " keys, and down/up-ward with " + walkX + "/" + walkC + " keys. " + walkMouse + " and mouse move walks the scene too.<br>" + "The " + walkW + "," + walkA + "," + walkS + "," + walkD + "," + walkX + "," + walkC + " moves can be accelerated by holding Shift (in the default settings), or even more with Ctrl and Shift.<br><br>" + // 
        "button1 single-click on a node in the Inspector tree selects it, while double-clicking it also centers the 3D view on it.<br>" + nodeSelect + " on a node in the 3D view can select it too, just choose it from the pop-up menu that would appear.<br><br>" + // 
        "Holding " + arcBall + " while dragging mouse centers the 3D view on the selected node first, and then rotates the view<br>" + "around it as the mouse move. Doing " + arcBallScroll + " zooms towards and outwards the selected node.<br><br>" + // 
        "Holding " + nodeDrag + " while dragging mouse moves the node within the scene in the screen plane.<br>" + "Doing " + nodeScroll + " moves the node closer or further within the scene. Finally,<br>" + "holding " + nodeRotate + " while dragging mouse rotates the node within the scene.<br>";
    }

    public static String getKeybindingsAsPlainTxtFrom(final InputHandler inputHandler) {
        // to aid space-padding per item
        int maxLength = 0;
        for (String actionName : inputHandler.getAllBehaviours()) maxLength = Math.max(actionName.length(), maxLength);
        char[] rightSpacePadding = new char[maxLength];
        for (int i = 0; i < maxLength; ++i) rightSpacePadding[i] = ' ';
        final StringBuilder helpString = new StringBuilder("SciView Input Controls Overview:\n\n");
        for (String actionName : inputHandler.getAllBehaviours()) helpString.append(actionName).append(rightSpacePadding, 0, maxLength - actionName.length()).append("\t-\t").append(InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings(actionName))).append("\n");
        return helpString.toString();
    }

    public static String getKeybindingsAsHtmlFrom(final InputHandler inputHandler) {
        final StringBuilder helpString = new StringBuilder("SciView Input Controls Overview:<br>\n");
        helpString.append("<table><tr><th>Action Name</th><th>Binding</th></tr>\n");
        for (String actionName : inputHandler.getAllBehaviours()) helpString.append("<tr><td>").append(actionName).append("</td><td>").append(InputTriggerConfig.prettyPrintInputs(inputHandler.getKeyBindings(actionName))).append("</td></tr>\n");
        helpString.append("</table>\n");
        return helpString.toString();
    }
}

19 Source : About.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to show information about the authors of SciView
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Help", weight = HELP), @Menu(label = "About", weight = HELP_ABOUT) })
public clreplaced About implements Command {

    @Parameter
    private UIService uiService;

    @Parameter
    private LogService log;

    private String ABOUT_TEXT = "SciView was created by Kyle Harrington and Ulrik Günther.<br>" + "Other key contributors include: Curtis Rueden, Aryaman Gupta, Tobias Pietzsch, Robert Haase, Jan Eglinger, and Stephan Saalfeld.<br>" + "Resources files were contributed by: Robert Wiese, and Kyle Harrington.<br>" + "The current citation is: Günther, U. and Harrington, K.I., 2020. Tales from the Trenches: Developing sciview, a new 3D viewer for the ImageJ community. arXiv preprint arXiv:2004.11897.";

    @Override
    public void run() {
        uiService.showDialog("<html>" + ABOUT_TEXT + "</html>", "About SciView");
        log.info(ABOUT_TEXT);
    }
}

19 Source : OpenN5.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to open a file in SciView
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "File", weight = FILE), @Menu(label = "Open N5...", weight = FILE_OPEN) })
public clreplaced OpenN5 implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    // TODO: Find a more extensible way than hard-coding the extensions.
    @Parameter(style = "directory")
    private File file;

    @Override
    public void run() {
        try {
            sciView.open(file.getAbsolutePath());
        } catch (final IOException | IllegalArgumentException exc) {
            log.error(exc);
        }
    }
}

19 Source : ExportXYZ.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to export a XYZ file for the currently active Mesh
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "File", weight = FILE), // 
@Menu(label = "Export", weight = FILE_EXPORT), @Menu(label = "XYZ...", weight = FILE_EXPORT_XYZ) })
public clreplaced ExportXYZ implements Command {

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Parameter(style = FileWidget.SAVE_STYLE)
    private File xyzFile = new File("");

    @Override
    public void run() {
        if (sciView.getActiveNode() instanceof Mesh) {
            Mesh mesh = (Mesh) sciView.getActiveNode();
            if (mesh != null) {
                try {
                    Utils.writeXYZ(xyzFile, mesh);
                } catch (final Exception e) {
                    logService.trace(e);
                }
            }
        }
    }
}

19 Source : ExportSTL.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to export a STL of the currently active Node
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "File", weight = FILE), // 
@Menu(label = "Export", weight = FILE_EXPORT), @Menu(label = "STL...", weight = FILE_EXPORT_STL) })
public clreplaced ExportSTL implements Command {

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Parameter(style = FileWidget.SAVE_STYLE)
    private File stlFile = new File("");

    @Override
    public void run() {
        if (sciView.getActiveNode() instanceof Mesh) {
            Mesh mesh = (Mesh) sciView.getActiveNode();
            if (mesh != null) {
                try {
                    Utils.writeSCMesh(stlFile.getAbsolutePath(), mesh);
                } catch (final Exception e) {
                    logService.trace(e);
                }
            }
        }
    }
}

19 Source : ExportN5.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to export the currently active Node to N5
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "File", weight = FILE), // 
@Menu(label = "Export", weight = FILE_EXPORT), @Menu(label = "N5...", weight = FILE_EXPORT_N5) })
public clreplaced ExportN5 implements Command {

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Parameter(style = FileWidget.SAVE_STYLE)
    private File n5File = new File("");

    @Parameter(label = "Dataset")
    private String dataset = "/myDataset";

    @Override
    public void run() {
        if (sciView.getActiveNode() instanceof Mesh) {
            Mesh mesh = (Mesh) sciView.getActiveNode();
            if (mesh != null) {
                try {
                    if (!n5File.exists())
                        throw new IOException("N5 path does not exist");
                    N5Writer n5 = new N5FSWriter(n5File.getAbsolutePath());
                    N5.save(MeshConverter.toImageJ(mesh), n5, dataset);
                } catch (final Exception e) {
                    logService.trace(e);
                }
            }
        } else {
            logService.warn("Node is " + sciView.getActiveNode().getNodeType() + " cannot export to N5.");
        }
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(MeshDemo.clreplaced, true, argmap);
        argmap.put("n5File", "/tmp/sciview/test.n5");
        argmap.put("dataset", "/testMesh");
        Thread.sleep(1000);
        command.run(ExportN5.clreplaced, true, argmap);
    }
}

19 Source : ToggleFloor.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to toggle the visibility of the floor
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), @Menu(label = "Toggle Floor", weight = EDIT_TOGGLE_FLOOR) })
public clreplaced ToggleFloor implements Command {

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        sciView.getFloor().setVisible(!sciView.getFloor().getVisible());
    }
}

19 Source : SciViewSettings.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to adjust SciView settings
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Settings", weight = EDIT_SETTINGS), @Menu(label = "SciView", weight = EDIT_SETTINGS_SCIVIEW) })
public clreplaced SciViewSettings implements Command {

    @Parameter
    private LogService logService;

    @Parameter
    private SciView sciView;

    @Parameter
    private boolean inspectorVisible;

    @Parameter
    private boolean interpreterVisible;

    @Override
    public void run() {
        sciView.setInspectorWindowVisibility(inspectorVisible);
        sciView.setInterpreterWindowVisibility(interpreterVisible);
    }
}

19 Source : DeleteObject.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to delete the currently active Node from the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), @Menu(label = "Delete Object", weight = EDIT_DELETE_OBJECT) })
public clreplaced DeleteObject implements Command {

    @Parameter
    private SciView sciView;

    // TODO it would be good if this could continue to use active node but also use an @Parameter by using a callback or sth
    // @Parameter
    // private Node node;
    @Override
    public void run() {
        if (sciView.getActiveNode() != null) {
            sciView.deleteActiveNode();
        }
    }
}

19 Source : AddSphere.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to add a sphere in the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Sphere...", weight = EDIT_ADD_SPHERE) })
public clreplaced AddSphere implements Command {

    @Parameter
    private SciView sciView;

    // @Parameter
    // private String position = "0; 0; 0";
    @Parameter
    private float radius = 1.0f;

    @Parameter
    private ColorRGB color = SciView.DEFAULT_COLOR;

    @Override
    public void run() {
        // final Vector3 pos = ClearGLVector3.parse( position );
        final Vector3f pos = new Vector3f(0, 0, 0);
        sciView.addSphere(pos, radius, color);
    }
}

19 Source : AddPointLight.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to add a point light to the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Point Light", weight = EDIT_ADD_POINTLIGHT) })
public clreplaced AddPointLight implements Command {

    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        sciView.addPointLight();
    }
}

19 Source : AddOrientationCompass.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to orientation compreplaced (R,G,B cylinders oriented along X,Y,Z axes, respectively) to the scene
 *
 * @author Vladimir Ulman
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Compreplaced", weight = EDIT_ADD_COMPreplaced) })
public clreplaced AddOrientationCompreplaced implements Command {

    @Parameter
    private SciView sciView;

    @Parameter
    private float axisLength = 0.1f;

    @Parameter
    private float AXESBARRADIUS = 0.001f;

    @Parameter
    private Vector3f xColor = new Vector3f(1f, 0f, 0f);

    @Parameter
    private Vector3f yColor = new Vector3f(0f, 1f, 0f);

    @Parameter
    private Vector3f zColor = new Vector3f(0f, 0f, 1f);

    private Node makeAxis(float axisLength, float angleX, float angleY, float angleZ, Vector3f color) {
        Cylinder axisNode = new Cylinder(AXESBARRADIUS, axisLength, 4);
        axisNode.setName("compreplaced axis: X");
        axisNode.setRotation(new Quaternionf().rotateXYZ(angleX, angleY, angleZ));
        axisNode.getMaterial().getDiffuse().set(color);
        axisNode.getMaterial().setDepthTest(Material.DepthTest.Always);
        axisNode.getMaterial().getBlending().setTransparent(true);
        Icosphere axisCap = new Icosphere(AXESBARRADIUS, 2);
        axisCap.setPosition(new Vector3f(0, axisLength, 0));
        axisCap.getMaterial().getDiffuse().set(color);
        axisCap.getMaterial().setDepthTest(Material.DepthTest.Always);
        axisCap.getMaterial().getBlending().setTransparent(true);
        axisNode.addChild(axisCap);
        return axisNode;
    }

    @Override
    public void run() {
        final Node root = new Node("Scene orientation compreplaced");
        // NB: RGB colors ~ XYZ axes
        // x axis:
        Node axisNode = makeAxis(axisLength, 0, 0, (float) (-0.5 * Math.PI), xColor);
        axisNode.setName("compreplaced axis: X");
        root.addChild(axisNode);
        // y axis:
        axisNode = makeAxis(axisLength, 0, 0, 0, yColor);
        axisNode.setName("compreplaced axis: Y");
        root.addChild(axisNode);
        // z axis:
        axisNode = makeAxis(axisLength, (float) (0.5 * Math.PI), 0, 0, zColor);
        axisNode.setName("compreplaced axis: Z");
        root.addChild(axisNode);
        sciView.addNode(root);
        sciView.getCamera().addChild(root);
        root.getUpdate().add(() -> {
            final Camera cam = sciView.getCamera();
            root.setPosition(cam.viewportToView(new Vector2f(-0.9f, 0.7f)));
            root.setRotation(new Quaternionf(sciView.getCamera().getRotation()).conjugate().normalize());
            return null;
        });
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(AddOrientationCompreplaced.clreplaced, true, argmap);
    }
}

19 Source : AddLine.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to add a line in the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Line...", weight = EDIT_ADD_LINE) })
public clreplaced AddLine implements Command {

    @Parameter
    private SciView sciView;

    // FIXME
    // @Parameter(label = "First endpoint")
    // private String start = "0; 0; 0";
    // 
    // @Parameter(label = "Second endpoint")
    // private String stop = "1; 1; 1";
    @Parameter
    private ColorRGB color = SciView.DEFAULT_COLOR;

    @Parameter(label = "Edge width", min = "0")
    private double edgeWidth = 1;

    @Override
    public void run() {
        // Vector3[] endpoints = { JOMLVector3.parse( start ), JOMLVector3.parse( stop ) };
        Vector3f[] endpoints = { new Vector3f(0, 0, 0), new Vector3f(1, 1, 1) };
        sciView.addLine(endpoints, color, edgeWidth);
    }
}

19 Source : AddLabelImage.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Adds a label image to the scene.
 *
 * @author Robert Haase, Scientific Computing Facility, MPI-CBG Dresden
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Label Image", weight = EDIT_ADD_LABELIMAGE) })
public clreplaced AddLabelImage<T extends RealType<T>> implements Command {

    @Parameter
    private OpService ops;

    @Parameter
    private SciView sciView;

    @Parameter
    private Dataset currentImage;

    @Override
    public void run() {
        // interpret the current image as a label image and convert it to ImgLabeling
        @SuppressWarnings("unchecked")
        Img<T> labelMap = (Img<T>) currentImage.getImgPlus();
        final Dimensions dims = labelMap;
        final IntType t = new IntType();
        final RandomAccessibleInterval<IntType> img = Util.getArrayOrCellImgFactory(dims, t).create(dims, t);
        ImgLabeling<Integer, IntType> labeling = new ImgLabeling<>(img);
        final Cursor<LabelingType<Integer>> labelCursor = Views.flareplacederable(labeling).cursor();
        for (final T input : Views.flareplacederable(labelMap)) {
            final LabelingType<Integer> element = labelCursor.next();
            if (input.getRealFloat() != 0) {
                element.add((int) input.getRealFloat());
            }
        }
        // take the regions, process them to meshes and put it in the viewer
        LabelRegions<Integer> labelRegions = new LabelRegions<>(labeling);
        Object[] regionsArr = labelRegions.getExistingLabels().toArray();
        for (int i = 0; i < labelRegions.getExistingLabels().size(); i++) {
            LabelRegion<Integer> lr = labelRegions.getLabelRegion((Integer) regionsArr[i]);
            Mesh mesh = ops.geom().marchingCubes(lr);
            sciView.addMesh(mesh);
        }
    }
}

19 Source : AddBox.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to add a box to the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Box...", weight = EDIT_ADD_BOX) })
public clreplaced AddBox implements Command {

    @Parameter
    private DisplayService displayService;

    @Parameter
    private SciView sciView;

    // FIXME
    // @Parameter
    // private String position = "0; 0; 0";
    @Parameter
    private float size = 1.0f;

    @Parameter
    private ColorRGB color = SciView.DEFAULT_COLOR;

    @Parameter
    private boolean inside;

    @Override
    public void run() {
        // final Vector3 pos = ClearGLVector3.parse( position );
        final Vector3f pos = new Vector3f(0f, 0f, 0f);
        final Vector3f vSize = new Vector3f(size, size, size);
        sciView.addBox(pos, vSize, color, inside);
    }
}

19 Source : LineDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of lines.
 *
 * @author Kyle Harrington
 * @author Curtis Rueden
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Lines Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Lines", weight = DEMO_BASIC_LINES) })
public clreplaced LineDemo implements Command {

    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        int numPoints = 25;
        Vector3f[] points = new Vector3f[numPoints];
        for (int k = 0; k < numPoints; k++) {
            points[k] = new // 
            Vector3f(// 
            (float) (10.0f * Math.random() - 5.0f), // 
            (float) (10.0f * Math.random() - 5.0f), (float) (10.0f * Math.random() - 5.0f));
        }
        double edgeWidth = 0.1;
        sciView.addLine(points, Colors.LIGHTSALMON, edgeWidth).setName("Lines Demo");
        sciView.centerOnNode(sciView.getActiveNode());
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(LineDemo.clreplaced, true, argmap);
    }
}

19 Source : Line3DDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of edges.
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Line3D Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Line3D", weight = DEMO_BASIC_LINE3D) })
public clreplaced Line3DDemo implements Command {

    @Parameter
    private SciView sciView;

    @Override
    public void run() {
        int numPoints = 25;
        List<Vector3f> points = new ArrayList<>();
        List<ColorRGB> colors = new ArrayList<>();
        for (int k = 0; k < numPoints; k++) {
            points.add(new // 
            Vector3f(// 
            (float) (10.0f * Math.random() - 5.0f), // 
            (float) (10.0f * Math.random() - 5.0f), (float) (10.0f * Math.random() - 5.0f)));
            colors.add(new ColorRGB((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
        }
        double edgeWidth = 0.1;
        Line3D line = new Line3D(points, colors, edgeWidth);
        line.setName("Line3D Demo");
        sciView.addNode(line, true);
        sciView.getFloor().setVisible(false);
        sciView.centerOnNode(line);
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(Line3DDemo.clreplaced, true, argmap);
    }
}

19 Source : ImagePlaneDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of inserting a 2D image as a plane into a scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Image Plane Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Image Plane", weight = DEMO_BASIC_IMAGEPLANE) })
public clreplaced ImagePlaneDemo implements Command {

    @Parameter
    private SciView sciView;

    @Parameter
    private IOService ioService;

    @Parameter
    private UIService uiService;

    @Override
    public void run() {
        // Load the 2D image
        Img<UnsignedByteType> img = sciView.getScreenshot();
        // Add noise
        Random rng = new Random(17);
        img.forEach(t -> t.add(new UnsignedByteType(rng.nextInt(25))));
        ByteBuffer bb = imgToByteBuffer(img);
        Box imgPlane = new Box(new Vector3f(10f, 10f, 0.01f));
        imgPlane.setPosition(new Vector3f(0, 10, 0));
        FloatBuffer tc = BufferUtils.allocateFloatAndPut(new float[] { // front
        // --+
        0.0f, // --+
        0.0f, // +-+
        1.0f, // +-+
        0.0f, // +++
        1.0f, // +++
        1.0f, // -++
        0.0f, // -++
        1.0f, // right
        0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, // back
        // ---
        0.0f, // ---
        0.0f, // -+-
        0.0f, // -+-
        1.0f, // ++-
        1.0f, // ++-
        1.0f, // +--
        1.0f, // +--
        0.0f, // left
        0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, // bottom
        0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, // up
        0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f });
        imgPlane.setTexcoords(tc);
        Material mat = new Material();
        mat.setSpecular(new Vector3f(1, 1, 1));
        mat.setDiffuse(new Vector3f(1, 1, 1));
        mat.setAmbient(new Vector3f(1, 1, 1));
        Texture tex = new Texture(new Vector3i((int) img.dimension(0), (int) img.dimension(1), 1), 4, bb);
        mat.getTextures().put("diffuse", tex);
        imgPlane.setMaterial(mat);
        imgPlane.setNeedsUpdate(true);
        sciView.addNode(imgPlane);
        sciView.centerOnNode(imgPlane);
        uiService.show(img);
    }

    // This should interleave channels, but the coloring doesnt seem to happen
    private static ByteBuffer imgToByteBuffer(Img<UnsignedByteType> img) {
        int numBytes = (int) (img.dimension(0) * img.dimension(1) * img.dimension(2));
        ByteBuffer bb = BufferUtils.allocateByte(numBytes);
        byte[] pixel = new byte[(int) img.dimension(2)];
        RandomAccess<UnsignedByteType> ra = img.randomAccess();
        long[] pos = new long[(int) img.dimension(2)];
        for (int y = 0; y < img.dimension(1); y++) {
            for (int x = 0; x < img.dimension(0); x++) {
                for (int c = 0; c < img.dimension(2); c++) {
                    pos[0] = x;
                    pos[1] = img.dimension(1) - y - 1;
                    pos[2] = c;
                    ra.setPosition(pos);
                    pixel[c] = ra.get().getByte();
                }
                bb.put(pixel);
            }
        }
        bb.flip();
        return bb;
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(ImagePlaneDemo.clreplaced, true, argmap);
    }
}

19 Source : SwingSourceAndConverterListWidget.java
with BSD 2-Clause "Simplified" License
from bigdataviewer

/**
 * Swing implementation of {@link SourceAndConverterListWidget}.
 *
 * Note the rather complex {@link SwingSourceAndConverterListWidget#set} method to avoid memory leak
 *
 * @author Nicolas Chiaruttini
 */
@Plugin(type = InputWidget.clreplaced)
public clreplaced SwingSourceAndConverterListWidget extends SwingInputWidget<SourceAndConverter[]> implements SourceAndConverterListWidget<JPanel> {

    @Override
    protected void doRefresh() {
    }

    @Override
    public boolean supports(final WidgetModel model) {
        return super.supports(model) && model.isType(SourceAndConverter[].clreplaced);
    }

    @Override
    public SourceAndConverter[] getValue() {
        return getSelectedSourceAndConverters();
    }

    @Parameter
    SourceAndConverterService bss;

    public SourceAndConverter[] getSelectedSourceAndConverters() {
        // A set avoids duplicate SourceAndConverter
        Set<SourceAndConverter> sacList = new HashSet<>();
        for (TreePath tp : tree.getSelectionModel().getSelectionPaths()) {
            if (((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject() instanceof RenamableSourceAndConverter) {
                Object userObj = ((RenamableSourceAndConverter) ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject()).sac;
                sacList.add((SourceAndConverter) userObj);
            } else {
                sacList.addAll(getSourceAndConvertersFromChildrenOf((DefaultMutableTreeNode) tp.getLastPathComponent()));
            }
        }
        return sacList.toArray(new SourceAndConverter[0]);
    }

    private Set<SourceAndConverter> getSourceAndConvertersFromChildrenOf(DefaultMutableTreeNode node) {
        Set<SourceAndConverter> sacs = new HashSet<>();
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
            if (child.getUserObject() instanceof RenamableSourceAndConverter) {
                Object userObj = ((RenamableSourceAndConverter) (child.getUserObject())).sac;
                sacs.add((SourceAndConverter) userObj);
            } else {
                sacs.addAll(getSourceAndConvertersFromChildrenOf(child));
            }
        }
        return sacs;
    }

    JTree tree;

    @Override
    public void set(final WidgetModel model) {
        super.set(model);
        tree = new JTree(bss.getUI().getTreeModel());
        tree.setCellRenderer(new SourceAndConverterTreeCellRenderer());
        JScrollPane scrollPane = new JScrollPane(tree);
        scrollPane.setPreferredSize(new Dimension(350, 200));
        getComponent().add(scrollPane);
        refreshWidget();
        model.setValue(null);
        TreeSelectionListener tsl = (e) -> model.setValue(getValue());
        // Memory leak... How ot solve this ?
        tree.addTreeSelectionListener(tsl);
        // -------------------------------- Memory leak! Cut heads of the Hydra of Lerna
        // The part below helps solve the memory leak:
        // with JTree not released the lastly selected path
        // with Listeners holding references with objects of potentially big memory footprint (SourceAndConverters)
        // Maybe related:
        // https://bugs.openjdk.java.net/browse/JDK-6472844
        // https://stackoverflow.com/questions/4517931/java-swing-jtree-is-not-garbage-collected
        // this one more particularly :
        tree.addAncestorListener(new AncestorListener() {

            @Override
            public void ancestorAdded(AncestorEvent event) {
            }

            @Override
            public void ancestorRemoved(AncestorEvent event) {
                tree.removeTreeSelectionListener(tsl);
                tree.clearSelection();
                tree.cancelEditing();
                // tree.clearToggledPaths();
                tree.resetKeyboardActions();
                tree.updateUI();
                scrollPane.remove(tree);
                getComponent().remove(scrollPane);
                tree.setModel(null);
                tree.removeAncestorListener(this);
                tree = null;
            }

            @Override
            public void ancestorMoved(AncestorEvent event) {
            }
        });
    // -------------------------------- All heads cut (hopefully)
    }
}

19 Source : StringToSourceAndConverterArray.java
with BSD 2-Clause "Simplified" License
from bigdataviewer

/**
 * TODO : allows multiple Paths splitted by a character ? Not sure it's fool proof
 * @param <I>
 */
@Plugin(type = org.scijava.convert.Converter.clreplaced)
public clreplaced StringToSourceAndConverterArray<I extends String> extends AbstractConverter<I, SourceAndConverter[]> {

    @Parameter
    SourceAndConverterService sacsService;

    @Override
    public <T> T convert(Object src, Clreplaced<T> dest) {
        String str = (String) src;
        TreePath tp = sacsService.getUI().getTreePathFromString(str);
        if (tp != null) {
            // sacsService.getUI().getSourceAndConvertersFromTreePath(tp).toArray(new SourceAndConverter[0]);
            return (T) sacsService.getUI().getSourceAndConvertersFromTreePath(tp).toArray(new SourceAndConverter[0]);
        } else {
            return null;
        }
    }

    @Override
    public Clreplaced getOutputType() {
        return SourceAndConverter[].clreplaced;
    }

    @Override
    public Clreplaced<I> getInputType() {
        return (Clreplaced<I>) String.clreplaced;
    }
}

19 Source : StringToBdvHandle.java
with BSD 2-Clause "Simplified" License
from bigdataviewer

@Plugin(type = org.scijava.convert.Converter.clreplaced)
public clreplaced StringToBdvHandle<I extends String, O extends BdvHandle> extends AbstractConverter<I, O> {

    @Parameter
    ObjectService os;

    @Override
    public <T> T convert(Object src, Clreplaced<T> dest) {
        Optional<BdvHandle> ans = os.getObjects(BdvHandle.clreplaced).stream().filter(bdvh -> (bdvh.toString().equals(src)) || (BdvHandleHelper.getWindowreplacedle(bdvh).equals(src))).findFirst();
        return (T) ans.orElse(null);
    }

    @Override
    public Clreplaced<O> getOutputType() {
        return (Clreplaced<O>) BdvHandle.clreplaced;
    }

    @Override
    public Clreplaced<I> getInputType() {
        return (Clreplaced<I>) String.clreplaced;
    }
}

19 Source : ViewTransformLoggerCommand.java
with BSD 2-Clause "Simplified" License
from bigdataviewer

/**
 * ViewTransformLoggerCommand
 * <p>
 * <p>
 * <p>
 * Author: @haesleinhuepf
 * 12 2019
 */
@Plugin(type = BdvPlaygroundActionCommand.clreplaced, menuPath = ScijavaBdvDefaults.RootMenu + "BDV>BDV - Log view transform", description = "Outputs the current view transfrom of a BDV window into the standard IJ logger")
public clreplaced ViewTransformLoggerCommand implements BdvPlaygroundActionCommand {

    @Parameter
    BdvHandle bdvh;

    @Parameter
    LogService ls;

    @Override
    public void run() {
        new ViewerTransformLogger(bdvh, new Logger() {

            @Override
            public void out(String msg) {
                ls.info(msg);
            }

            @Override
            public void err(String msg) {
                ls.error(msg);
            }
        }).run();
    }
}

18 Source : DefaultNotebookService.java
with Apache License 2.0
from scijava

/**
 * AWT-driven implementation of {@link NotebookService}.
 *
 * @author Curtis Rueden
 * @author Hadrien Mary
 */
@Plugin(type = Service.clreplaced)
public clreplaced DefaultNotebookService extends AbstractService implements NotebookService {

    @Parameter
    private LogService log;

    @Parameter
    private ConvertService convertService;

    @Parameter
    private ImageJNotebookService ijNotebookService;

    @Override
    public Object display(final Object object, final Clreplaced<? extends NotebookOutput> outputType) {
        if (convertService.supports(object, outputType)) {
            return convertService.convert(object, outputType);
        }
        return object;
    }

    @Override
    public Object displayMimetype(String mimetype, String content) {
        return new MIMEContainer(mimetype, content);
    }

    @Override
    public Object displayMimetype(String mimetype, Object content) {
        return new MIMEContainer(mimetype, content);
    }

    // TODO : those methods are using the net.imagej namespace.
    // Also would it be possible to create a converter for this ?
    // With RandomAccessibleInterval[] or List<RandomAccessibleInterval> as a type ?
    public Object tiles(final int[] gridLayout, final RandomAccessibleInterval... images) {
        RandomAccessibleInterval rai = ijNotebookService.mosaic(gridLayout, images);
        return convertService.convert(rai, NotebookOutput.clreplaced);
    }
}

18 Source : DefaultJupyterService.java
with Apache License 2.0
from scijava

/**
 * @author Hadrien Mary
 */
@Plugin(type = Service.clreplaced)
public clreplaced DefaultJupyterService extends AbstractService implements JupyterService {

    @Parameter
    private transient LogService log;

    @Parameter
    private transient Context context;

    @Parameter
    private transient CommandService command;

    /* Install kernel */
    @Override
    public void installKernel(String... args) {
        Map<String, Object> parameters = parseArgumentsInstall(args);
        // TODO : Ensure parameters contains the appropriate keys.
        installKernel((String) parameters.get("logLevel"), (String) parameters.get("pythonBinaryPath"), (String) parameters.get("clreplacedpath"), (String) parameters.get("javaBinaryPath"));
    }

    @Override
    public void installKernel(String logLevel, String pythonBinaryPath) {
        installKernel(logLevel, Paths.get(pythonBinaryPath));
    }

    @Override
    public void installKernel(String logLevel, Path pythonBinaryPath) {
        installKernel(logLevel, pythonBinaryPath.toFile());
    }

    @Override
    public void installKernel(String logLevel, File pythonBinaryPath) {
        installKernel(logLevel, pythonBinaryPath, null, null);
    }

    @Override
    public void installKernel(String logLevel, String pythonBinaryPath, String clreplacedpath, String javaBinaryPath) {
        installKernel(logLevel, new File(pythonBinaryPath), clreplacedpath, javaBinaryPath);
    }

    @Override
    public void installKernel(String logLevel, File pythonBinaryPath, String clreplacedpath, String javaBinaryPath) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("logLevel", logLevel);
        parameters.put("pythonBinaryPath", pythonBinaryPath);
        parameters.put("clreplacedpath", clreplacedpath);
        parameters.put("javaBinaryPath", new File(javaBinaryPath));
        command.run(InstallScijavaKernel.clreplaced, true, parameters);
    }

    /* Run kernel */
    @Override
    public void runKernel(String... args) {
        Map<String, Object> parameters = parseArgumentsRun(args);
        // TODO : Ensure parameters contains the appropriate keys.
        runKernel((String) parameters.get("logLevel"), (String) parameters.get("connectionFile"));
    }

    @Override
    public void runKernel(String logLevel, String connectionFile) {
        runKernel(logLevel, Paths.get(connectionFile));
    }

    @Override
    public void runKernel(String logLevel, File connectionFile) {
        runKernel(logLevel, connectionFile.toPath());
    }

    @Override
    public void runKernel(String logLevel, Path connectionFile) {
        KernelRunner.run(() -> {
            String id = uuid();
            // Setup configuration
            ScijavaKernelConfigurationFile config = new ScijavaKernelConfigurationFile(this.context, logLevel, connectionFile);
            // Setup the socket
            KernelSocketsFactoryImpl kernelSocketsFactory = new KernelSocketsFactoryImpl(config);
            // Setup the evaluator
            ScijavaEvaluator evaluator = new ScijavaEvaluator(context, id, id);
            // Launch the kernel
            return new ScijavaKernel(context, id, evaluator, config, kernelSocketsFactory);
        });
    }

    /* Helpers private method */
    private Map<String, Object> parseArgumentsRun(final String... args) {
        if (args.length > 0) {
            try {
                Options options = new Options();
                options.addOption("connectionFile", true, "Connection File Path");
                options.addOption("verbose", true, "Verbose Mode");
                CommandLineParser parser = new DefaultParser();
                CommandLine cmd = parser.parse(options, args);
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("connectionFile", cmd.getOptionValue("connectionFile"));
                parameters.put("logLevel", cmd.getOptionValue("verbose"));
                return parameters;
            } catch (ParseException ex) {
                log.error("Error parsing arguments : " + ex.toString());
            }
        } else {
            log.error("No parameters preplaceded to the Scijava kernel.");
        }
        return null;
    }

    private Map<String, Object> parseArgumentsInstall(final String... args) {
        if (args.length > 0) {
            try {
                Options options = new Options();
                options.addOption("pythonBinaryPath", true, "Python Binary Path");
                options.addOption("verbose", true, "Verbose Mode");
                options.addOption("clreplacedpath", true, "Additional JAVA clreplacedpath ?");
                options.addOption("javaBinaryPath", true, "Java Binary Path");
                CommandLineParser parser = new DefaultParser();
                CommandLine cmd = parser.parse(options, args);
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("pythonBinaryPath", cmd.getOptionValue("pythonBinaryPath"));
                parameters.put("logLevel", cmd.getOptionValue("verbose"));
                if (cmd.getOptionValue("clreplacedpath") != null) {
                    parameters.put("clreplacedpath", cmd.getOptionValue("clreplacedpath"));
                } else {
                    parameters.put("clreplacedpath", null);
                }
                if (cmd.getOptionValue("javaBinaryPath") != null) {
                    parameters.put("javaBinaryPath", cmd.getOptionValue("javaBinaryPath"));
                } else {
                    parameters.put("javaBinaryPath", null);
                }
                return parameters;
            } catch (ParseException ex) {
                log.error("Error parsing arguments : " + ex.toString());
            }
        } else {
            log.error("No parameters preplaceded to the Scijava kernel.");
        }
        return null;
    }
}

18 Source : Worker.java
with Apache License 2.0
from scijava

public clreplaced Worker implements Runnable {

    @Parameter
    private LogService log;

    @Parameter
    private Context context;

    @Parameter
    private PluginService pluginService;

    @Parameter
    private ConvertService convertService;

    private final Map<String, ScriptEngine> scriptEngines;

    private final Map<String, ScriptLanguage> scriptLanguages;

    private String languageName;

    SimpleEvaluationObject seo = null;

    String code = null;

    Worker(Context context, Map<String, ScriptEngine> scriptEngines, Map<String, ScriptLanguage> scriptLanguages) {
        context.inject(this);
        this.scriptEngines = scriptEngines;
        this.scriptLanguages = scriptLanguages;
    }

    public void setup(SimpleEvaluationObject seo, String code, String languageName) {
        this.seo = seo;
        this.code = code;
        this.languageName = languageName;
    }

    @Override
    public void run() {
        ScriptLanguage scriptLanguage = this.scriptLanguages.get(this.languageName);
        ScriptEngine scriptEngine = this.scriptEngines.get(this.languageName);
        final Reader input = new StringReader(this.code);
        final ScriptInfo info = new ScriptInfo(context, "dummy.py", input);
        info.setLanguage(scriptLanguage);
        this.seo.setOutputHandler();
        try {
            // create the ScriptModule instance
            final ScriptModule module = info.createModule();
            context.inject(module);
            // HACK: Inject our cached script engine instance, rather
            // than letting the ScriptModule instance create its own.
            final Field f = ClreplacedUtils.getField(ScriptModule.clreplaced, "scriptEngine");
            ClreplacedUtils.setValue(f, module, scriptEngine);
            // execute the code
            final List<PreprocessorPlugin> pre = pluginService.createInstancesOfType(PreprocessorPlugin.clreplaced);
            final List<PostprocessorPlugin> post = pluginService.createInstancesOfType(PostprocessorPlugin.clreplaced);
            final ModuleRunner runner = new ModuleRunner(context, module, pre, post);
            runner.run();
            // acreplacedulate the outputs into an ordered map
            final Map<String, Object> outputTable = new LinkedHashMap<>();
            info.outputs().forEach(output -> {
                final String name = output.getName();
                final Object value = output.getValue(module);
                if (value != null) {
                    outputTable.put(name, value);
                }
            });
            // convert result into a notebook-friendly form
            Object output = null;
            try {
                if (outputTable.size() == 0) {
                    output = null;
                } else if (outputTable.size() == 1) {
                    output = outputTable.values().toArray()[0];
                    if (!(output instanceof MIMEContainer)) {
                        output = convertService.convert(output, NotebookOutput.clreplaced);
                        if (output == null) {
                            log.warn("[WARNING] No suitable converter found");
                            output = outputTable.values().toArray()[0];
                        }
                    }
                } else {
                    output = convertService.convert(outputTable, NotebookOutput.clreplaced);
                    if (output == null) {
                        log.warn("[WARNING] No suitable converter found");
                        output = outputTable;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                output = "[ERROR]";
            } finally {
                this.seo.finished(output);
            }
            this.syncBindings(scriptEngine, scriptLanguage);
        } catch (final ThreadDeath ex) {
            seo.error("Execution canceled");
            log.error(ex);
        } catch (final ModuleException t) {
            seo.error(t.getMessage());
            log.error(t);
        }
        this.seo.clrOutputHandler();
        this.seo.executeCodeCallback();
    }

    private void syncBindings(ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {
        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        this.scriptEngines.forEach((String name, ScriptEngine engine) -> {
            Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
            currentBindings.keySet().forEach((String key) -> {
                bindings.put(key, scriptLanguage.decode(currentBindings.get(key)));
            });
        });
    }
}

18 Source : ScijavaKernelConfigurationFile.java
with Apache License 2.0
from scijava

/**
 * @author Hadrien Mary
 */
public clreplaced ScijavaKernelConfigurationFile implements ConfigurationFile {

    @Parameter
    private transient LogService log;

    private final File configFile;

    private Config configuration;

    private final String logLevel;

    public ScijavaKernelConfigurationFile(Context context, String logLevel, Path connectionFile) {
        context.inject(this);
        this.configFile = connectionFile.toFile();
        this.logLevel = logLevel;
    }

    @Override
    public Config getConfig() {
        if (configuration == null) {
            try {
                configuration = MessageSerializer.parse(new String(Files.readAllBytes(this.configFile.toPath())), Config.clreplaced);
            } catch (IOException ex) {
                log.error("Issue loading connection file : " + ex);
            }
        }
        return configuration;
    }

    public String getLogLevel() {
        return this.logLevel;
    }
}

18 Source : InstallScijavaKernel.java
with Apache License 2.0
from scijava

@Plugin(type = Command.clreplaced, menu = { @Menu(label = "replacedyze"), @Menu(label = "Jupyter Kernel"), @Menu(label = "Install Scijava Kernel (only for debugging)") })
public clreplaced InstallScijavaKernel implements Command {

    @Parameter
    private LogService log;

    @Parameter
    private transient ScriptService scriptService;

    @Parameter(required = true, label = "Python binary")
    private File pythonBinaryPath;

    @Parameter(required = true, label = "Log Level", choices = { "debug", "error", "info", "none" })
    private String logLevel = "info";

    @Parameter(required = false, label = "Additional JAVA clreplacedpath")
    private String clreplacedpath = "";

    @Parameter(required = false, label = "Java Binary Path")
    private File javaBinaryPath = null;

    @Override
    public void run() {
        if (!this.pythonBinaryPath.isFile()) {
            log.error(this.pythonBinaryPath + " does not exist.");
        }
        log.info("Installing 'scijava' kernel.");
        String[] cmd = null;
        String sourceCode = null;
        Map<String, String> results = null;
        // Check binary is a valid Python executable
        cmd = new String[] { pythonBinaryPath.toString(), "--version" };
        results = ProcessUtil.executeProcess(cmd, log);
        if (!results.get("output").contains("Python") && !results.get("error").contains("Python")) {
            log.error(this.pythonBinaryPath + " does not seem to be a valid Python executable.");
            log.error("Output : " + results.get("output"));
            log.error("Error : " + results.get("error"));
            return;
        }
        log.debug("Python found.");
        // Check Jupyter is installed
        sourceCode = "import jupyter";
        results = ProcessUtil.executePythonCode(this.pythonBinaryPath, sourceCode, log);
        if (results.get("error").contains("ModuleNotFoundError")) {
            log.error("Jupyter does not seems to be installed.");
            log.error("Output : " + results.get("output"));
            log.error("Error : " + results.get("error"));
            return;
        }
        log.debug("Jupyter found.");
        // Create the new kernel
        Path kernelDir = Paths.get(System.getProperty("java.io.tmpdir"), "scijava");
        SystemUtil.deleteFolderRecursively(kernelDir, log);
        kernelDir.toFile().mkdir();
        try {
            // Copy the logo
            Files.copy(this.getClreplaced().getResourcereplacedtream("/logo-64x64.png"), Paths.get(kernelDir.toString(), "logo-64x64.png"));
            Files.copy(this.getClreplaced().getResourcereplacedtream("/logo-32x32.png"), Paths.get(kernelDir.toString(), "logo-32x32.png"));
        } catch (IOException ex) {
            log.error(ex);
            return;
        }
        // Generate the kernel.json file
        String JSONString;
        if (this.javaBinaryPath == null) {
            JSONString = JupyterUtil.createKernelJSON(this.clreplacedpath, this.logLevel, null);
        } else {
            JSONString = JupyterUtil.createKernelJSON(this.clreplacedpath, this.logLevel, this.javaBinaryPath.toString());
        }
        Path kernelJSONPath = Paths.get(kernelDir.toString(), "kernel.json");
        try (FileWriter file = new FileWriter(kernelJSONPath.toFile())) {
            file.write(JSONString);
            log.debug("kernel.json file : \n" + JSONString);
        } catch (IOException ex) {
            log.error(ex);
            return;
        }
        log.debug("Kernel generated.");
        // Install the new kernel
        sourceCode = "from jupyter_client.kernelspec import KernelSpecManager\n";
        sourceCode += "KernelSpecManager().install_kernel_spec(\"" + kernelDir.toAbsolutePath().toString().replace("\\", "\\\\") + "\", user=True, replace=True)\n";
        results = ProcessUtil.executePythonCode(this.pythonBinaryPath, sourceCode, log);
        if (results.get("output").toLowerCase().contains("error") || results.get("error").toLowerCase().contains("error")) {
            log.error("New kernel installation failed.");
            log.error("Output : " + results.get("output"));
            log.error("Error : " + results.get("error"));
            return;
        }
        log.debug("Kernel installed.");
        // Clean temp dir
        log.debug("Clean temporary files.");
        SystemUtil.deleteFolderRecursively(kernelDir, log);
        log.info("The kernel 'scijava' has been correctly installed.");
    }

    public static void main(String... args) {
        Context context = new Context();
        LogService log = context.service(LogService.clreplaced);
        log.setLevel(LogLevel.INFO);
        JupyterService jupyter = context.service(JupyterService.clreplaced);
        jupyter.installKernel(args);
        context.dispose();
    }
}

18 Source : RAIToPNGNotebookConverter.java
with Apache License 2.0
from scijava

@Plugin(type = Converter.clreplaced)
public clreplaced RAIToPNGNotebookConverter<T extends RealType<T>> extends NotebookOutputConverter<RandomAccessibleInterval<T>, PNGImageNotebookOutput> {

    @Parameter
    private ImageJNotebookService ijnb;

    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Clreplaced<RandomAccessibleInterval<T>> getInputType() {
        return (Clreplaced) RandomAccessibleInterval.clreplaced;
    }

    @Override
    public Clreplaced<PNGImageNotebookOutput> getOutputType() {
        return PNGImageNotebookOutput.clreplaced;
    }

    @Override
    public PNGImageNotebookOutput convert(Object object) {
        RandomAccessibleInterval<T> source = (RandomAccessibleInterval<T>) object;
        // NB: replacedume <=3 samples in the 3rd dimension means channels. Of course,
        // we have no metadata with a vanilla RAI, but this is a best guess;
        // 3rd dimensions with >3 samples are probably something like Z or time.
        final int cAxis = source.numDimensions() > 2 && source.dimension(2) <= 3 ? 2 : -1;
        String base64Image = (String) ijnb.RAIToPNG(source, 0, 1, cAxis, ValueScaling.AUTO);
        return new PNGImageNotebookOutput(base64Image);
    }
}

18 Source : DatasetToPNGNotebookConverter.java
with Apache License 2.0
from scijava

@Plugin(type = Converter.clreplaced)
public clreplaced DatasetToPNGNotebookConverter extends NotebookOutputConverter<Dataset, PNGImageNotebookOutput> {

    @Parameter
    private ImageJNotebookService ijnb;

    @Override
    public Clreplaced<Dataset> getInputType() {
        return Dataset.clreplaced;
    }

    @Override
    public Clreplaced<PNGImageNotebookOutput> getOutputType() {
        return PNGImageNotebookOutput.clreplaced;
    }

    @Override
    public PNGImageNotebookOutput convert(Object object) {
        Dataset source = (Dataset) object;
        String base64Image = (String) // 
        ijnb.RAIToPNG(// 
        (Img) source, source.dimensionIndex(Axes.X), source.dimensionIndex(Axes.Y), source.dimensionIndex(Axes.CHANNEL), ImageJNotebookService.ValueScaling.AUTO);
        return new PNGImageNotebookOutput(base64Image);
    }
}

18 Source : REPLEditor.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * REPL editor
 *
 * @author Ulrik Günther
 */
public clreplaced REPLEditor extends EditorPane {

    protected ScriptREPL repl;

    @Parameter
    Context context;

    @Parameter
    private ScriptService scriptService;

    @Parameter
    private LogService logService;

    protected OutputPane outputPane;

    protected VarsPane varsPane;

    protected boolean executing = false;

    public REPLEditor(ScriptREPL repl, VarsPane vars, OutputPane output) {
        super();
        this.repl = repl;
        this.outputPane = output;
        this.varsPane = vars;
    }

    @Override
    protected void processKeyEvent(KeyEvent e) {
        if (executing) {
            e.consume();
            return;
        }
        if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_UP && e.getID() == KeyEvent.KEY_RELEASED) {
            walk(false);
            e.consume();
            return;
        }
        if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_DOWN && e.getID() == KeyEvent.KEY_RELEASED) {
            walk(true);
            e.consume();
            return;
        }
        if (!e.isShiftDown() && e.getKeyCode() == KeyEvent.VK_ENTER && e.getID() == KeyEvent.KEY_RELEASED) {
            String text = getText();
            if (text.length() == 0) {
                e.consume();
                return;
            }
            if (text.endsWith("\n")) {
                System.out.println("Truncating whitespace");
                text = text.substring(0, text.length() - 1);
            }
            outputPane.append(">> " + text + "\n");
            executing = true;
            String finalText = text;
            threadService().run(() -> {
                final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
                ctx.setErrorWriter(outputPane.getOutputWriter());
                ctx.setWriter(outputPane.getOutputWriter());
                final boolean result = repl.evaluate(finalText);
                threadService().queue(() -> {
                    executing = false;
                    if (!result) {
                        outputPane.append("REPL error occured\n");
                        logService.warn("REPL error occured");
                    }
                // varsPane.update();
                });
            });
            setText("");
            e.consume();
        } else {
            super.processKeyEvent(e);
            e.consume();
        }
    }

    private void walk(boolean forward) {
        setText(repl.getInterpreter().walkHistory(getText(), forward));
    }

    private ThreadService threadService() {
        // HACK: Get the SciJava context from the REPL.
        // This can be fixed if/when the REPL offers a getter for it.
        final Context ctx = (Context) // 
        ClreplacedUtils.getValue(Types.field(repl.getClreplaced(), "context"), repl);
        return ctx.service(ThreadService.clreplaced);
    }

    void setREPLLanguage(String language) {
        System.out.println("Resetting language to " + language);
        if (!repl.getInterpreter().getLanguage().getNames().contains(language)) {
            repl.lang(language);
        }
        ScriptLanguage l = scriptService.getLanguageByName(language);
        setLanguage(scriptService.getLanguageByName(language));
        final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
        ctx.setErrorWriter(outputPane.getOutputWriter());
        ctx.setWriter(outputPane.getOutputWriter());
    }
}

18 Source : Open.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to open a file in SciView
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "File", weight = FILE), @Menu(label = "Open...", weight = FILE_OPEN) })
public clreplaced Open implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    // TODO: Find a more extensible way than hard-coding the extensions.
    @Parameter(style = "open,extensions:obj/ply/stl/xyz/csv")
    private File file;

    @Override
    public void run() {
        try {
            sciView.open(file.getAbsolutePath());
        } catch (final IOException | IllegalArgumentException exc) {
            log.error(exc);
        }
    }
}

18 Source : AddCamera.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * Command to add a camera to the scene
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Edit", weight = EDIT), // 
@Menu(label = "Add", weight = EDIT_ADD), @Menu(label = "Camera...", weight = EDIT_ADD_CAMERA) })
public clreplaced AddCamera implements Command {

    @Parameter
    private DisplayService displayService;

    @Parameter
    private SciView sciView;

    // FIXME
    // @Parameter
    // private String position = "0; 0; 0";
    @Parameter(label = "Field of View")
    private float fov = 50.0f;

    @Parameter(label = "Near plane")
    private float nearPlane = 0.1f;

    @Parameter(label = "farPlane")
    private float farPlane = 500.0f;

    @Override
    public void run() {
        // final Vector3 pos = ClearGLVector3.parse( position );
        final Vector3f pos = new Vector3f(0, 0, 0);
        final DetachedHeadCamera cam = new DetachedHeadCamera();
        cam.perspectiveCamera(fov, sciView.getWindowWidth(), sciView.getWindowHeight(), Math.min(nearPlane, farPlane), Math.max(nearPlane, farPlane));
        cam.setPosition(pos);
        sciView.addNode(cam);
    }
}

18 Source : TextDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of text annotations
 *
 * @author Kyle Harrington
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Mesh Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Text Demo", weight = DEMO_BASIC_TEXT) })
public clreplaced TextDemo implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    @Parameter
    private CommandService commandService;

    @Override
    public void run() {
        final Mesh m;
        String filePath = "/WieseRobert_simplified_Cip1.stl";
        try {
            File meshFile = ResourceLoader.createFile(getClreplaced(), filePath);
            m = (Mesh) io.open(meshFile.getAbsolutePath());
        } catch (IOException exc) {
            log.error(exc);
            return;
        }
        Node msh = sciView.addMesh(m);
        msh.setName(filePath);
        // msh.fitInto( 15.0f, true );
        Material mat = new Material();
        mat.setAmbient(new Vector3f(1.0f, 0.0f, 0.0f));
        mat.setDiffuse(new Vector3f(0.8f, 0.5f, 0.4f));
        mat.setSpecular(new Vector3f(1.0f, 1.0f, 1.0f));
        // mat.setDoubleSided( true );
        msh.setMaterial(mat);
        msh.setNeedsUpdate(true);
        msh.setDirty(true);
        TextBoard board = new TextBoard();
        board.setText("This mesh was contributed by Robert Wiese!");
        board.setName("TextBoard");
        board.setTransparent(0);
        board.setFontColor(new Vector4f(0, 0, 0, 0));
        board.setBackgroundColor(new Vector4f(100, 100, 0, 0));
        board.setPosition(msh.getPosition().add(new Vector3f(0, 10, 0)));
        board.setScale(new Vector3f(10.0f, 10.0f, 10.0f));
        sciView.addNode(board, false);
        sciView.centerOnNode(msh);
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(TextDemo.clreplaced, true, argmap);
    }
}

18 Source : PointCloudDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of meshes.
 *
 * @author Kyle Harrington
 * @author Curtis Rueden
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Mesh Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Point Cloud", weight = DEMO_BASIC_POINTCLOUD) })
public clreplaced PointCloudDemo implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    @Parameter
    private CommandService commandService;

    @Override
    public void run() {
        int numPoints = 100;
        double w = 1;
        double h = w;
        double d = w;
        List<RealLocalizable> spots = new ArrayList<RealLocalizable>();
        Random rng = new Random();
        for (int k = 0; k < numPoints; k++) {
            double x = rng.nextDouble() * w - w / 2;
            double y = rng.nextDouble() * h - h / 2;
            double z = rng.nextDouble() * d - d / 2;
            spots.add(new RealPoint(x, y, z));
        }
        sciView.addPointCloud(spots, "Point Cloud Demo", 50.0f);
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(PointCloudDemo.clreplaced, true, argmap);
    }
}

18 Source : MultiMeshDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of meshes.
 *
 * @author Kyle Harrington
 * @author Curtis Rueden
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Multi Mesh Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "MultiMesh", weight = DEMO_BASIC_MULTIMESH) })
public clreplaced MultiMeshDemo implements Command {

    @Parameter
    private int numMeshes;

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    @Parameter
    private CommandService commandService;

    @Override
    public void run() {
        final Mesh m;
        try {
            File meshFile = ResourceLoader.createFile(getClreplaced(), "/WieseRobert_simplified_Cip1.stl");
            m = (Mesh) io.open(meshFile.getAbsolutePath());
        } catch (IOException exc) {
            log.error(exc);
            return;
        }
        Material mat = new Material();
        mat.setAmbient(new Vector3f(1.0f, 0.0f, 0.0f));
        mat.setDiffuse(new Vector3f(0.8f, 0.5f, 0.4f));
        mat.setSpecular(new Vector3f(1.0f, 1.0f, 1.0f));
        // mat.setDoubleSided( true );
        Random RNG = new Random();
        float shellR = 100;
        ArrayList<Node> meshes = new ArrayList<>();
        for (int k = 0; k < numMeshes; k++) {
            Node msh = sciView.addMesh(m);
            msh.setName("Mesh_" + k);
            msh.setPosition(new Vector3f((RNG.nextFloat() * shellR - shellR), (RNG.nextFloat() * shellR - shellR), (RNG.nextFloat() * shellR - shellR)));
            // msh.fitInto( 15.0f, true );
            msh.setMaterial(mat);
            msh.setNeedsUpdate(true);
            msh.setDirty(true);
            meshes.add(msh);
        }
        // Wait for everything to settle before framing the view
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sciView.getFloor().setVisible(false);
        sciView.surroundLighting();
        sciView.centerOnScene();
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(MultiMeshDemo.clreplaced, true, argmap);
    }
}

18 Source : MeshDemo.java
with BSD 2-Clause "Simplified" License
from scenerygraphics

/**
 * A demo of meshes.
 *
 * @author Kyle Harrington
 * @author Curtis Rueden
 */
@// 
Plugin(// 
type = Command.clreplaced, // 
label = "Mesh Demo", // 
menuRoot = "SciView", menu = { // 
@Menu(label = "Demo", weight = DEMO), // 
@Menu(label = "Basic", weight = DEMO_BASIC), @Menu(label = "Mesh", weight = DEMO_BASIC_MESH) })
public clreplaced MeshDemo implements Command {

    @Parameter
    private IOService io;

    @Parameter
    private LogService log;

    @Parameter
    private SciView sciView;

    @Parameter
    private CommandService commandService;

    @Override
    public void run() {
        final Mesh m;
        try {
            File meshFile = ResourceLoader.createFile(getClreplaced(), "/WieseRobert_simplified_Cip1.stl");
            m = (Mesh) io.open(meshFile.getAbsolutePath());
        } catch (IOException exc) {
            log.error(exc);
            return;
        }
        Node msh = sciView.addMesh(m);
        msh.setName("Mesh Demo");
        // msh.fitInto( 15.0f, true );
        Material mat = new Material();
        mat.setAmbient(new Vector3f(1.0f, 0.0f, 0.0f));
        mat.setDiffuse(new Vector3f(0.8f, 0.5f, 0.4f));
        mat.setSpecular(new Vector3f(1.0f, 1.0f, 1.0f));
        // mat.setDoubleSided( true );
        msh.setMaterial(mat);
        msh.setNeedsUpdate(true);
        msh.setDirty(true);
        sciView.getFloor().setPosition(new Vector3f(0, -25, 0));
        sciView.setActiveNode(msh);
        sciView.centerOnNode(sciView.getActiveNode());
    }

    public static void main(String... args) throws Exception {
        SciView sv = SciView.create();
        CommandService command = sv.getScijavaContext().getService(CommandService.clreplaced);
        HashMap<String, Object> argmap = new HashMap<>();
        command.run(MeshDemo.clreplaced, true, argmap);
    }
}

See More Examples