ImageJ jar file plugin shortcut creation - java

I have been working on a developmental biology project marking various nuclear markers along with a DAPI stain to determine percentage of marker expression. I have found that the ImageJ plugin ITCN (http://rsbweb.nih.gov/ij/plugins/itcn.html) works great for each marker when also using the CLAHE program. My problem is that I have around 6000 images to analyze and I would love to be able to automate the process. I have recorded a macro such as the following (which can itself be looped to individual image files) :
open("image");
run("8-bit");
run("CLAHE");
run("ITCN ");
close();
but the ITCN icon wont start analyzing automatically, nor is there an easily programmed short cut to do the job. I am completely ignorant to any Java programming and I would love to know if there is anyway to get around this likely easy problem.
Thanks in advance
Michael

The ITCN plugin is implemented as a PlugInFrame and its settings are not recordable, as you have discovered. However, looking at the source, it seems that the plugin just uses another class called ITCN_Runner once it has gathered the options, which you should be able to call programmatically.
However, you can't do this from the macro language. Probably the easiest alternative is to use ImageJ's built-in Javascript scripting. For example, start up the Macro Recorder as usual, but select "JavaScript" in the top left. Then the first couple of commands appear for me (with some reformatting for clarity) as:
imp = IJ.openImage("/home/mark/test.tif");
IJ.run(imp, "8-bit", "");
IJ.run(imp,
"Enhance Local Contrast (CLAHE)",
"blocksize=127 histogram=256 maximum=3 mask=*None* fast_(less_accurate)");
Then if you look at the source code of the ITCN plugin you can see how to create the ITCN_Runner class and run it - for example:
runner = new ITCN_Runner( imp,
1, /* width*/
5.0, /* minimum distance */
0, /* threshold */
false, /* detect dark peaks */
null /* mask ImagePlus */ )
runner.run()
That produces output in another window, which has the same name but with "Results " prefixed.

Thanks Marc.
Unfortunately there is an error that results when I run the java scrip.
ReferenceError: "ITCN_Runner" is not defined. (#6) in at line number 6
It says there is an unknown source in the line of the ITCN runner. I can't tell if this is a problem with the code, the fact that I simply copied and pasted yours into the recorder without going into the source code to do so, or the ITCN runner itself.
Thanks again,
Michael

Related

Automatically generate Java code based on existing fields in a class

Scenario
I'm working with a Java model built from scratch in Eclipse. What's important in this model is that we save our output to MATLAB (.mat) files. I constantly add new features, which require new fields that in turn will have to be exported to the .mat file at every iteration. Upon restarting a crashed simulation, I might have to import the .mat file. To export or import my .mat file I use JMatIO.
For example, if I would add a new field rho_m (a simple double) to my class CModel, I have to add to my Save() method:
mlModel.setField("rho_m", new MLDouble(null, new double[] {rho_m}, 1));
And to my Load() method:
rho_m = ((MLDouble)mlModel.getField("rho_m")).getReal(0);
Note that even though rho_m is a double, it needs to be treated as a double[] in JMatIO. This probably has something to do with MATLAB being orientated towards matrices and matrix operations.
Problem
Instead of doing this manually (prone to errors, annoying to maintain) I would like to automate this procedure. Ideally, I would like my IDE to detect all the fields in CModel and write the code based on the field's name and type. Is there any way to do this in Java/Eclipse?
Ideas so far
I have no formal training in low-level programming languages (yes, Java is low-level to me) and am still relatively new to Java. I do have some experience with MATLAB. In MATLAB I think I could use eval() and fieldnames() in a for loop to do what I mentioned. My last resort is to copy-paste the Java code to MATLAB and from there generate the code using a huge, ugly script. Every time I want to make changes to the model I'd rerun the MATLAB script.
Besides that idea I've found terms like UML, but do not have the background knowledge to figure out if this is what I'm looking for or not.
Any help, even if it's just a small push in the right direction, is greatly appreciated. Let me know if I need to further clarify anything.
Looking at your scenario, you are doing model-driven code generation, that is, you have a model and want to get some code generated according to your current model. Therefore, you need a model-driven code generator.
I lead the ABSE/AtomWeaver project, so I'll outline what you can do to get what you want using AtomWeaver (There are however other solutions like MetaEdit+, XText or Eclipse's own GMT/EMF sub-system).
AtomWeaver is an IDE where you can build a model and generate code from that model. You can change your model as many times you want and hit the "Generate" button to get an updated version of your code. ABSE is the name of the modeling method.
We don't need to go into details, but essentially ABSE follows a "building-block" approach. You create a Template that represents a feature or concept of your model. Then, you can associate a mini-code generator just to that concept. You can then "instantiate" and combine those building blocks to quickly build your models. Variables increase the flexibility of your models.
You can also change your models, or add new features ("blocks") and generate again. The generators are built using the Lua programming language, a very simple language with C-Like syntax.
The best way to understand the ABSE development method and the AtomWeaver IDE is to download the IDE and see the samples or try the tutorials. And yes, you can use AtomWeaver for free.

How can I add the functionality of User Input to my eclipse plugin?

I am developing a plugin in eclipse which can generate a text file (based on user input) and can trigger a perl script. I can easily make a simple plugin (like Hello World) and I can add new menus and commands to it. I understand how those things are related to one another, but the place where I am getting stuck is the User Input.
How can I ask the user to enter his choices? I mean what extension point should I use to ask him out? I can't find anything that can ask the user to enter data. Once I can get him to enter the required info, I can easily access that information to proceed further.
PLZ. NOTE: this is my first time in an online community, so I have tried to be as thorough as possible in my description. I am new to eclipse and have a very basic knowledge of Java. I took some Java lessons online by Mark Dexter. I do have a solid understanding and work experience in C++.
Continued from my comment above (sorry, couldn't fit into the 600 character limit for comments, so I'm adding this as a possible answer to your question) -- A quick search led me to this - http://www.eclipse.org/articles/article.php?file=Article-action-contribution/index.html. You can use actions to easily add toolbar buttons, menu items, etc, that are handled by your plugin. In short, this is how you plug functionality into the workbench. I recommend checking the link above to gain a better understanding. As for collecting the input, you can use a JFace dialog (http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjface%2Fdialogs%2FDialog.html). There are many pre-canned dialog that you may find useful, so I recommend doing a little more research to see what will work best for your use case. Good luck!
Starting Eclipse plug-in development might be a bit overwhelming.
The sort answer:
I assume that you have create a new plug-in project with the "hello, world command" template. If not you can easily do it. It will help you to get started. In this sample project, eclipse created a simple menu contribution for you. I'm not going to go over the details, but essentially, you create a command (org.eclipse.ui.commands) and associate it with some location in the workbench like a menu or toolbar icon (org.eclipse.ui.menus). Then you need to create something that will handle this command like when it is executed (by user clicking on the menu). This is done by by handlers (org.eclipse.ui.handlers) and handlers are when you want your code to go into.
Open the "plugin.xml" file in your plug-in and navigate to the "Extension" section
Expand the "org.eclipse.ui.handlers" branch and select the only "(handler)" item.
Click on the "class" link the right part of the editor and that will navigate you to the generated class.
Your code goes to the "execute" method. This is what will be run when user executes the command. In your case if you want to ask for an input you can use an input dialog:
Code:
public Object execute(ExecutionEvent event) throws ExecutionException {
InputDialog dlg = new InputDialog(
HandlerUtil.getActiveShellChecked(event), "Title",
"Enter text", "Initial value", null);
if (dlg.open() == Window.OK) {
// User clicked OK; run perl
String input = dlg.getValue();
// TODO:do something with value
}
return null;
}
No to ask user for an input you will need to show a dialog. I suggest you go over this nice tutorial: http://www.vogella.de/articles/EclipseDialogs/article.html which describes this in a great detail.
The long answer is to look at http://www.vogella.de/articles/EclipsePlugIn/article.html and http://www.vogella.de/articles/EclipseCommands/article.html to see the basics behind Eclipse RPC and commands.
Lastly, you will also need to look in here http://www.vogella.de/articles/EclipseJobs/article.html to understand how to run longer tasks like the perl script you are talking about.
There are no extension points in Eclipse used to input information from the user. For this you typically use a dialog or a view depending on the specific use case.

Create Eclipse shortcut to run particular target of an build file

I have different projects and several build files with different targets in it.
Generally if i want to run a target i use to navigate to 'Ant' view and then select the build file and then selects the target to run.
Instead of doing several steps every time, is there any way to assign a keyboard shortcut for particular target so that i can run that target easily.
The main preference page for keys can be found under Window > Preferences > General > Keys (or faster: Press Ctrl+3, type Keys and press Enter) . See How to manage keyboard shortcuts in Eclipse and why you should article to achieve what you want.
Ok, I've given the "EASE-script + keyboard shortcut" technique a try and that works much better:
I created a "my_build_target.js" javascript file at the base of my workspace/project:
/**
* keyboard: Alt+Shift+2
*/
targetmanager = org.eclipse.cdt.make.core.MakeCorePlugin.getDefault().getTargetManager()
projects = targetmanager.getTargetBuilderProjects()
folder = projects[0].getFolder("Test/Scenarios/Win32")
// targets = targetmanager.getTargets(folder)
target = targetmanager.findTarget(folder, "MyBuildTargetName")
target.build(new org.eclipse.core.runtime.NullProgressMonitor())
Note the use of the "magic keyword" within the header comment which specifies the desired shortcut-key you want for the script.
You then need to specify the locations for your scripts to be loaded from by going to:
"Windows >> Preferences >> Scripting >> Script Locations"
Personally, I clicked the "Add Workspace" button and specified the base of my workspace/project (that's where I housed my script).
I restarted Eclipse and then used my specified "Alt+Shift+2" shortcut key.
Awesome, it works :)
One gotchya is that I can't cancel a build that's in progress with this method. I suspect it's due to me using that NullProgressMonitor class when I call .build(). If I learn of a way to add a proper progress monitor here (that lets you cancel a progressing build), then I will update this answer...
NOTE: This is my initial "Practically Macro + Beanshell script" technique, which I've given up on. I prefer the other technique mentioned in my 2nd answer.
I've been looking for a way to do this for specific make targets too. The only in-built shortcut available is to "Rebuilt Last Target", which isn't all that helpful if you're frequently swapping between targets.
While I don't have a concrete solution yet, I'm working towards one.
I'm assessing the "Practically Macro" plug-in. It has the ability to assign a shortcut key to a macro. It also has the ability to define a macro as a beanshell script.
So all that's left is to figure out what kind of beanshell script would be capable of running a specific make target.
I've tried to explore the Eclipse API via the EASE scripting tool.
I'll share my steps/notes on how I successfully ran a make-target programmatically (via their javascript interface):
targetmanager = org.eclipse.cdt.make.core.MakeCorePlugin.getDefault().getTargetManager()
projects = targetmanager.getTargetBuilderProjects()
folder = projects[0].getFolder("Path/To/My/Build/Targets/")
// targets = targetmanager.getTargets(folder)
target = targetmanager.findTarget(folder, "MyBuildTargetName")
target.build(new org.eclipse.core.runtime.NullProgressMonitor())
So I think all that's left is for me (or someone else that's interested) to:
convert this script from javascript to beanshell and add it as a macro via the "Practically Macro" plugin
Assign a shortcut key to it
...quite an involved way to go about it, so if anyone has any simpler alternatives, I'm open to hear them.
UPDATE:
FWIW, I managed to create a beanshell script for "Practically Macro" in this form:
//Scripts are beanshell format (see http://www.beanshell.org/)
//variable type
//styledText the org.eclipse.swt.custom.StyledText instance for the current editor
//console write output to the macro console via console.write(String), .writeln(String), .write(Exception)
//findTarget the instance of org.eclipse.jface.text.IFindReplaceTarget
import org.eclipse.swt.custom.StyledText;
import org.eclipse.jface.text.IFindReplaceTarget;
c = org.eclipse.core.runtime.Platform.getBundle("org.eclipse.cdt.make.core").loadClass("org.eclipse.cdt.make.core.MakeCorePlugin");
m = c.getMethod("getDefault", null);
dflt = m.invoke(null, null);
targetmanager = dflt.getTargetManager();
projects = targetmanager.getTargetBuilderProjects();
folder = projects[0].getFolder("Path/To/My/Build/Targets/");
target = targetmanager.findTarget(folder, "MyBuildTargetName");
target.build(new org.eclipse.core.runtime.NullProgressMonitor());
And yes, it does kind-of work, but the only gotchya is that the eclipse ide stalls without any refreshing. Only after the build completes does the console pane get updated with the final build output (in one hit) and Eclipse becomes responsive again.
So it's not perfect, but I suppose it's incremental progress in the direction I'm after... As for what causes this freeze/stall during the build, I can't say for sure, but I suspect that the Practically Macro plugin locks Eclipse up until the macro completes.
Next Time:
Perhaps if I had another window of time to look into this again, I'd try to see if I can trigger an EASE-javascript script via a keyboard shortcut. This page seems to hint that it is possible:
https://wiki.eclipse.org/EASE/Scripts

Barring copy & paste, is there a way to share Java detail formatters

We have 5-10 developers working on Eclipse with Java here in our shop, and we often are debugging classes that don't have debug-friendly toString().
Along comes Detail Formatters to save the day. Hurray! But only my day. If I want to share the joy with my fellow devs, I THINK I have to do some copying and pasting, as do they.
That sucks. We've got N different version control systems that work in Eclipse... it seems like this would be something that folks would Like To Pass Around.
Nothing in the file->export... dialog. Nothing via searching the online help. Nothing.
I managed to track at least some of the settings to /workspace/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.dbug.ui.prefs, but Have Reason To Believe there's more to it than that. Plus, the thought of putting something burried deep in a hidden folder into source control puts my teeth on edge.
Is there a better way to share detail formatters? Ideally this would be something we could just check into our code repo and disseminate that way.
EDIT: I'm using Helios, Service Release 1, build id 20100917-0705.
In addition to the javaLogicalStructures extension point (for adding logical structure to given classes), there's also one called detailPaneFactories. But this is for creating the pane the text (or whatever, thanks to this extension point) the detail formatter renders to. Neither allows extenders to list existing detail formatters (or logical structures for that matter).
The bottom of the detailPaneFactories extension does have Something Interesting To Say:
Supplied Implementation:
The debug platform contributes a detail pane factory providing a default
text source viewer detail pane. The default detail pane displays textual
details of a selected element based on the corresponding debug model
presentation's implementation of computeDetail(IValue value,
IValueDetailListener listener).
computeDetail sounds promising. I'll keep ya posted (unless someone else beats me to it... hurray bounties).
Hmm... org.eclipse.jdt.debug.ui.JavaDebugUtils.getPreferenceStore() sounds promising, but I'd still rather not write a plugin for this myself.
Ah... well. Here's the code org.eclipse.jdt.internal.debug.ui.JavaDetailFormattersManager uses to load them:
/**
* Populate the detail formatters map with data from preferences.
*/
private void populateDetailFormattersMap() {
String[] detailFormattersList= JavaDebugOptionsManager.parseList(JDIDebugUIPlugin.getDefault().getPreferenceStore().getString(IJDIPreferencesConstants.PREF_DETAIL_FORMATTERS_LIST));
fDetailFormattersMap= new HashMap(detailFormattersList.length / 3);
for (int i= 0, length= detailFormattersList.length; i < length;) {
String typeName= detailFormattersList[i++];
String snippet= detailFormattersList[i++].replace('\u0000', ',');
boolean enabled= ! JavaDetailFormattersPreferencePage.DETAIL_FORMATTER_IS_DISABLED.equals(detailFormattersList[i++]);
fDetailFormattersMap.put(typeName, new DetailFormatter(typeName, snippet, enabled));
}
}
So the string in the preference store is just a bunch of CSVs with type-name,snippet,enabled,type-name... replace \u0000 with , in the snippets, and you're good to go.
That handles the export (hell, you could just dump the preference string whole hog).
Import wouldn't be much harder, though it'd be nice to not overwrite existing types, or given the user the option to do so, perhaps even with a diff of the two snippets in question.
OTOH, I'd really rather not rely on the inner workings of a class in *.internal.*.
From the Eclipse 3.8 and 4.2 M5 - New and Noteworthy:
Detail formatters can now be exported as separate preferences.
Previously the only way to share detail formatters was to export all of your workspace settings.
This closes the bug 224815 mentioned by Brian De Alwis in his answer:
"Make Detail formatters exportable" (with that patch)
Although there is nothing explicit in the preferences export wizard, exporting everything will also write the detail formatters. Just search in the output file for /instance/org.eclipse.jdt.debug.ui/org.eclipse.jdt.debug.ui.detail_formatters and share only those lines.
Update: There seems to be a bug in the importer, you have to remove the /instance/ prefix from each line before importing the file.
Alternatively, as they are stored in a properties file in the workspace metadata, you can share that (although you'll probably overwrite other debug settings if you just copy the file):
${workspace}\.metadata\.plugins\org.eclipse.core.runtime\.settings\org.eclipse.jdt.debug.ui.prefs
Using a "macro" might do the trick here.
You will have to
Install a plugin that lets you
record Macros
Start recording Macro and configure Detail formatters using Eclipse Menus
Save and keep that
macro on some shared directory
Install that plugin and run macro on
PCs used by other developers
One such plugin is : http://sourceforge.net/projects/practicalmacro/reviews/
This issue was filed in the Eclipse Bugzilla as bug 224815. The problem is that the detail formatters were overlooked when configuring the import/export preference transfers. The fix, providing it's accepted, should be in the 3.8/4.2 M6 due out at the end of January.

Word wrap in Eclipse Java? [duplicate]

This question already has answers here:
Does Eclipse have line-wrap
(12 answers)
Closed 7 years ago.
I already have word wrap for Eclipse PHP (How can I get word wrap to work in Eclipse PDT for PHP files?). What about Eclipse Java? Is there a similar tool to wrap Java code lines?
Ctrl+Shift+F will format a file in Eclipse, breaking long lines into multiple lines and nicely word-wrapping comments. You can also highlight just a section of text and format that.
I realize this is not an automatic soft/hard word wrap, but I don't think the question was asking for anything fancy.
Just like to point out that word wrapping is a terrible idea in code. I suppose everyone has their own style, but typically you should refactor or rethink blocks of code that take much more than a single average horizontal screen. (about 1280 pixels)
Of course there are always exceptions... like verbose exceptions for example, but these are not critical for code understanding.
Scanning a line that goes beyond a single horizontal screen, or having to read a thought that stacks on multiple lines will make your code much more difficult to figure out.
Additionally, line counts will be weird, as word wrapping will make a single line seem like it takes up 2, 3, or shudder the thought... 4 lines of code.
As far as comments go, line returns should not be much of a problem for anyone.
Also keep in mind, word wrapping code is not a common practice, and you are essentially saying that everyone reading your code should turn word wrapping on, which is, I'm sorry to say, an unnecessarily painful thing to make others working with your code do....
If nesting is causing you the need for word wrap... well this is also a very bad code smell.
That's my two-cents.
This is for anyone who is having the following problem with the "Ahtik" word-wrap plugin in Texlipse: the plugin installs fine, but selecting the "word-wrap" option using the context menu (or pressing ctrl+alt+w) causes the text to wrap momentarily, and then just flick back to being unwrapped (this probably includes anyone using Windows 7).
Here is a fix...straight from the developer himself! I emailed Ahti Kitsik in a last-ditch attempt to find a way round, and was amazed when he actually found a solution, and sent it to me the next day. He suggested that in return I could just make this information widely available.
So, the way to fix it as follows:
Look up the texlipse plugin location. This will probably be in the Eclipse folder, and the address will probably end: ...\eclipse\plugins\net.sourceforge.texlipse_1.5.0.
Backup the plugin.xml file there just in case, and then edit the original by deleting the following chunks of code:
-Firstly, the "action" (starting at line 843):
action
class="net.sourceforge.texlipse.actions.TexWordWrapAction"
definitionId="net.sourceforge.texlipse.commands.texWordWrap"
icon="icons/wrap.gif"
id="net.sourceforge.texlipse.actions.texWordWrap"
label="W&rap text"
menubarPath="net.sourceforge.texlipse.menus.latex/latexGroup"
style="toggle"
toolbarPath="latexGroup"
tooltip="Use word wrap"
-Secondly, the "command" (starting at line 972):
command
categoryId="net.sourceforge.texlipse.latexEditingCategory"
name="Wrap text"
id="net.sourceforge.texlipse.commands.texWordWrap"
(When you have done this, the file should be 1257 lines long, instead of 1271).
Finally, Ahti says: "Start eclipse with -clean command line argument to force reloading of plugin.xml." (Personally I had no idea how to do this, so I just removed and reinstalled his plugin, then exited Eclipse, and edited the code before I restarted it).
The function should work fine now. Hope this helps someone. And thanks again Ahti!
In the meantime, there has been an fork to Ahtik's word wrap plugin which, I must say, works very nice and fixes jumbled line numbering bug: Eclipse Word-Wrap Plug-In
Open Eclipse -> Help -> Install New Software -> Click "Add.." button and copy this line "http://dev.cdhq.de/eclipse/updatesite/luna/" into field Name and Location -> Click OK
Check -> Line Number Ruler and Word Wrap Feature -> Next -> Next -> Finish -> Restard Eclipse!

Categories

Resources