Skip to content

Improves IJ1 Macro Recording by using objectService.getName method instead of toString #243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/main/java/net/imagej/legacy/IJ1Helper.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.module.ModuleInfo;
import org.scijava.object.ObjectService;
import org.scijava.platform.event.AppAboutEvent;
import org.scijava.platform.event.AppOpenFilesEvent;
import org.scijava.platform.event.AppPreferencesEvent;
Expand Down Expand Up @@ -124,6 +125,10 @@ public class IJ1Helper extends AbstractContextual {
@Parameter
private LogService log;

/** A reference to ObjectService in order to get the name of Object in the ObjectService */
@Parameter
private ObjectService objectService;

/** Search bar in the main window. */
private Object searchBar;

Expand Down Expand Up @@ -649,6 +654,12 @@ public boolean isImagePlus(final Class<?> c) {
return ImagePlus.class.isAssignableFrom(c);
}

/** Returns the name of the object in the object service
* - return non null even if the object is not in the object service */
public String getObjectName(final Object o) {
return objectService.getName(o);
}

/**
* Gets the ID of the given {@link ImagePlus} object. If the given object is
* not an {@link ImagePlus}, throws {@link IllegalArgumentException}.
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/net/imagej/legacy/plugin/IJ1MacroEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ else if (v instanceof Number || v instanceof Boolean) {
return v.toString();
}
else {
return "\"" + quote(v.toString()) + "\"";
return "\"" + quote(ij1Helper.getObjectName(v)) + "\"";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.scijava.module.ModuleItem;
import org.scijava.module.process.AbstractPostprocessorPlugin;
import org.scijava.module.process.PostprocessorPlugin;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.widget.TextWidget;
Expand All @@ -56,6 +57,9 @@ public class MacroRecorderPostprocessor extends AbstractPostprocessorPlugin {
@Parameter(required = false)
private LegacyService legacyService;

@Parameter(required = false)
private ObjectService objectService;

// -- ModuleProcessor methods --

@Override
Expand Down Expand Up @@ -104,7 +108,7 @@ private String toString(final Object value) {
final String title = IJ1Helper.getTitle(value);
if (title != null) return title;

return value.toString();
return objectService.getName(value);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2020 ImageJ developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/

package net.imagej.legacy.plugin;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.object.ObjectService;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptModule;
import org.scijava.script.ScriptService;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.concurrent.ExecutionException;

import static org.junit.Assert.*;

/**
* Tests whether {@link IJ1MacroLanguage} works conveniently with named Objects present in the {@link ObjectService}
*
* This test works in combination with {@link MacroRecorderPostprocessorNamedObjectTest}
*
* Extra : groovy : should return the Object while in IJ1
*
* TODO : how to deal with duplicate names ? In terms of testing ?
*
* @author Nicolas Chiaruttini
*/

public class IJ1MacroLanguageNamedObjectTest {

private Context context;
private ScriptService scriptService;
private ObjectService objectService;

@Before
public void setUp() {
context = new Context();
scriptService = context.service(ScriptService.class);
objectService = context.service(ObjectService.class);
}

@After
public void tearDown() {
context.dispose();
}

@Test
public void testIJ1MacroLanguageNamedObject() throws InterruptedException,
ExecutionException
{
// Puts a named Pet object into the ObjectService
Pet pet = new Pet("Felix", "Cat");
objectService.addObject(pet,pet.getName());

// Makes Pet class easily discoverable be the script service
scriptService.addAlias(Pet.class);

// Execute a script.
final String script = "" + //
"#@ Pet animal\n" + //
"#@output String greeting\n" + //
"greeting = 'Oh, '+animal+' is so cute!'\n" + //
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the benefit of having the object name available in the macro language? Apart from printing log messages, I don't see much value in this, as there's no way to actually do anything with the input object. IMHO it would only make sense if you use the API of the object, i.e. for other scripting languages than IJ1 macros.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imagine you have an IJ1 script that manipulate a BdvHandle, and a library with a String to BdvHandle converter. The user makes a screenshot and close the window.
The recorder then outputs:

run("BdvScreenShot", "bdvh=BDV_01");
run("BdvClose", "bdvh=BDV_01");

Now the user wants to make a small script that does both actions. And he likes the macro language.
He will just have to do a script like that:

#@BdvHandle bdvh;
run("BdvScreenShot", "bdvh="+bdvh);
run("BdvClose", "bdvh="+bdvh);

Does that make sense ? I wanted to try it but I cannot use the new legacy I built because of the error I mentioned on gitter, but I have no time to investigate it now. Will later later or next week.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried and it works.

"";

final ScriptModule m = scriptService.run("greet.ijm", script, true, //
"animal", pet).get();

final Object returnValue = m.getReturnValue();

// Verify that the input has been found - felix the cat
// Correct class
assertSame(m.getInput("animal").getClass(), Pet.class);
// Correct instance
assertSame(m.getInput("animal"), pet);

// Verify that the script executed correctly - with the correct object NAME being
// given to the script (IJ1 Macro Language behaviour)
assertEquals("Oh, Felix is so cute!", //
m.getOutput("greeting"));

}

/*
Simple "custom" object
*/
static class Pet {

private String name;

Pet(String name, String species) {
this.name = name;
}

// Unfortunately not a toString overriden method
public String getName() {
return name;
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2018 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/

package net.imagej.legacy.plugin;

import net.imagej.legacy.IJ1Helper;
import net.imagej.legacy.LegacyService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.module.Module;
import org.scijava.module.process.AbstractPreprocessorPlugin;
import org.scijava.module.process.PreprocessorPlugin;
import org.scijava.object.ObjectService;
import org.scijava.plugin.PluginInfo;
import org.scijava.plugin.PluginService;
import org.scijava.script.ScriptModule;
import org.scijava.script.ScriptService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static org.junit.Assert.assertEquals;

/**
* Tests whether {@link MacroRecorderPostprocessor} uses the name of {@link org.scijava.object.NamedObjectIndex}
* in the MacroRecorder. This allows to conveniently use IJ1 MacroRecorder for objects present in the
* {@link ObjectService}, which do not have a proper overriden toString() method.
*
* This class tests whether a Command being recorded outputs the correct name of an object, it works
* in combination with the test {@link IJ1MacroLanguageNamedObjectTest}.
*
* @author Nicolas Chiaruttini
*/
public class MacroRecorderPostprocessorNamedObjectTest {

private Context context;
private ScriptService scriptService;
private LegacyService legacyService;
private ObjectService objectService;

@Before
public void setUp() {
context = new Context();
scriptService = context.service(ScriptService.class);
legacyService = context.service(LegacyService.class);
objectService = context.service(ObjectService.class);
}

@After
public void tearDown() {
context.dispose();
}

@Test
public void testParametersRecorded() throws InterruptedException,
ExecutionException
{
// NB: Register a preprocessor that injects input values and resolves them.
// We need this, rather than passing the key/value pairs directly to the
// run method, because when you pass parameters directly to the module
// execution, they are immediately marked as resolved. But for the purposes
// of macro recording, we need the parameters to be _unresolved_ initially,
// and only later resolved around the time that input harvesting occurs.
context.service(PluginService.class).addPlugin(new PluginInfo<>(
MockInputHarvester.class, PreprocessorPlugin.class));

// NB: Override the IJ1Helper to remember which parameters get recorded.
final EideticIJ1Helper ij1Helper = new EideticIJ1Helper();
legacyService.setIJ1Helper(ij1Helper);

// Puts a named Pet object into the ObjectService
Pet pet = new Pet("Felix", "Cat");
objectService.addObject(pet,pet.getName());

// Makes Pet class easily discoverable be the script service
scriptService.addAlias(Pet.class);

// Execute a script.
final String script = "" + //
"#@ Pet animal\n" + //
"#@ ObjectService objectService\n" + //
"#@output String greeting\n" + //
"greeting = 'Oh, '+objectService.getName(animal)+' is so cute!'\n" + //
"";

final ScriptModule m = //
scriptService.run("greet.groovy", script, true).get();

// Verify that Felix name is correctly registered in the ObjectService.
// TODO : is this necessary ? That's probably tested elsewhere
assertEquals("Felix", //
objectService.getName(pet));

// Verify that the script executed correctly.
assertEquals("Oh, Felix is so cute!", //
m.getOutput("greeting"));

// Verify that the animal was recorded ...
assertEquals(1, ij1Helper.recordedArgs.size());

// ... with the recorder properly outputing the named defined when added in the objectService
assertEquals("animal=Felix", ij1Helper.recordedArgs.get(0));
}

// -- Helper classes --

/**
* Extended version of {@link IJ1Helper} that remembers recorded parameters.
*/
private class EideticIJ1Helper extends IJ1Helper {

public EideticIJ1Helper() {
super(legacyService);
}

private final List<String> recordedArgs = new ArrayList<>();
private boolean finished;

@Override
public void recordOption(final String key, final String value) {
if (finished) {
recordedArgs.clear();
finished = false;
}
recordedArgs.add(key + "=" + value);
super.recordOption(key, value);
}

@Override
public void finishRecording() {
super.finishRecording();
finished = true;
}
}

public static class MockInputHarvester extends AbstractPreprocessorPlugin {

@Override
public void process(final Module module) {
// Gets the first animal put in the objectService
Pet pet = this.context().getService(ObjectService.class).getObjects(Pet.class).get(0);
module.setInput("animal", pet);
module.resolveInput("animal");
}
}

/*
Simple "custom" object
*/
static class Pet {

private String name;

Pet(String name, String species) {
this.name = name;
}

// Unfortunately not a toString overriden method
public String getName() {
return name;
}

}
}