use of ij.io.SaveDialog in project imagej1 by imagej.
the class TextPanel method saveAs.
/**
* Saves all the text in this TextPanel to a file. Set
* 'path' to "" to display a save as dialog. Returns
* 'false' if the user cancels the save as dialog.
*/
public boolean saveAs(String path) {
boolean isResults = IJ.isResultsWindow() && IJ.getTextPanel() == this;
boolean summarized = false;
if (isResults) {
String lastLine = iRowCount >= 2 ? getLine(iRowCount - 2) : null;
summarized = lastLine != null && lastLine.startsWith("Max");
}
String fileName = null;
if (rt != null && rt.getCounter() != 0 && !summarized) {
if (path == null || path.equals("")) {
IJ.wait(10);
String name = isResults ? "Results" : title;
SaveDialog sd = new SaveDialog("Save Results", name, Prefs.defaultResultsExtension());
fileName = sd.getFileName();
if (fileName == null)
return false;
path = sd.getDirectory() + fileName;
}
rt.save(path);
TextWindow tw = getTextWindow();
if (fileName != null && tw != null && !"Results".equals(title)) {
tw.setTitle(fileName);
title = fileName;
}
} else {
if (path.equals("")) {
IJ.wait(10);
boolean hasHeadings = !getColumnHeadings().equals("");
String ext = isResults || hasHeadings ? Prefs.defaultResultsExtension() : ".txt";
SaveDialog sd = new SaveDialog("Save as Text", title, ext);
String file = sd.getFileName();
if (file == null)
return false;
path = sd.getDirectory() + file;
}
PrintWriter pw = null;
try {
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
pw = new PrintWriter(bos);
} catch (IOException e) {
IJ.error("Save As>Text", e.getMessage());
return true;
}
saveAsCSV = path.endsWith(".csv");
save(pw);
saveAsCSV = false;
pw.close();
}
if (isResults) {
Analyzer.setUnsavedMeasurements(false);
if (Recorder.record && !IJ.isMacro())
Recorder.record("saveAs", "Results", path);
} else if (rt != null) {
if (Recorder.record && !IJ.isMacro())
Recorder.record("saveAs", "Results", path);
} else {
if (Recorder.record && !IJ.isMacro())
Recorder.record("saveAs", "Text", path);
}
IJ.showStatus("");
return true;
}
use of ij.io.SaveDialog in project TrakEM2 by trakem2.
the class Compare method compareAllToAll.
/**
* Gets pipes for all open projects, and generates a matrix of dissimilarities, which gets passed on to the Worker thread and also to a file, if desired.
*
* @param to_file Whether to save the results to a file and popup a save dialog for it or not. In any case the results are stored in the worker's load, which you can retrieve like:
* <pre>
* Bureaucrat bu = Compare.compareAllToAll(true, null, null);
* Object result = bu.getWorker().getResult();
* float[][] scores = (float[][])result[0];
* ArrayList<Compare.Chain> chains = (ArrayList<Compare.Chain>)result[1];
* </pre>
*/
public static Bureaucrat compareAllToAll(final boolean to_file, final String regex, final String[] ignore, final Project[] projects, final boolean crop, final boolean from_end, final int max_n_elements, final String outgroup) {
// gather all open projects
final Project[] p = null == projects ? Project.getProjects().toArray(new Project[0]) : projects;
final Worker worker = new Worker("Comparing all to all") {
@Override
public void run() {
startedWorking();
try {
final CATAParameters cp = new CATAParameters();
if (!cp.setup(to_file, regex, false, false)) {
finishedWorking();
return;
}
String filename = null, dir = null;
if (to_file) {
final SaveDialog sd = new SaveDialog("Save matrix", OpenDialog.getDefaultDirectory(), null, ".csv");
filename = sd.getFileName();
if (null == filename) {
finishedWorking();
return;
}
dir = sd.getDirectory().replace('\\', '/');
if (!dir.endsWith("/"))
dir += "/";
}
Object[] ob = gatherChains(p, cp, ignore);
final ArrayList<Chain> chains = (ArrayList<Chain>) ob[0];
// to keep track of each project's chains
final ArrayList[] p_chains = (ArrayList[]) ob[1];
ob = null;
if (null == chains) {
finishedWorking();
return;
}
final int n_chains = chains.size();
// crop chains if desired
if (crop) {
for (final Chain chain : chains) {
if (from_end) {
final int start = chain.vs.length() - max_n_elements;
if (start > 0) {
chain.vs = chain.vs.substring(start, chain.vs.length());
// BEFORE making it relative
chain.vs.resample(cp.delta, cp.with_source);
}
} else {
if (max_n_elements < chain.vs.length()) {
chain.vs = chain.vs.substring(0, max_n_elements);
// BEFORE making it relative
chain.vs.resample(cp.delta, cp.with_source);
}
}
}
}
// compare all to all
final VectorString3D[] vs = new VectorString3D[n_chains];
for (int i = 0; i < n_chains; i++) vs[i] = chains.get(i).vs;
final float[][] scores = Compare.scoreAllToAll(vs, cp.distance_type, cp.delta, cp.skip_ends, cp.max_mut, cp.min_chunk, cp.direct, cp.substring_matching, this);
if (null == scores) {
finishedWorking();
return;
}
// store matrix and chains into the worker
this.result = new Object[] { scores, chains };
// write to file
if (!to_file) {
finishedWorking();
return;
}
final File f = new File(dir + filename);
// encoding in Latin 1 (for macosx not to mess around
final OutputStreamWriter dos = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(f)), "8859_1");
// Normalize matrix to largest value of 1.0
if (cp.normalize) {
float max = 0;
for (int i = 0; i < scores.length; i++) {
// traverse half matrix ony: it's mirrored
for (int j = i; j < scores[0].length; j++) {
if (scores[i][j] > max)
max = scores[i][j];
}
}
for (int i = 0; i < scores.length; i++) {
for (int j = i; j < scores[0].length; j++) {
scores[i][j] = scores[j][i] /= max;
}
}
}
// write chain titles, with project prefix
if (cp.format.equals(cp.formats[0])) {
// as csv:
try {
final StringBuffer[] titles = new StringBuffer[n_chains];
int next = 0;
for (int i = 0; i < p.length; i++) {
final String prefix = Utils.getCharacter(i + 1);
// empty upper left corner
dos.write("\"\"");
for (final Chain chain : (ArrayList<Chain>) p_chains[i]) {
dos.write(",");
titles[next] = new StringBuffer().append('\"').append(prefix).append(' ').append(chain.getCellTitle()).append('\"');
dos.write(titles[next].toString());
next++;
}
}
dos.write("\n");
for (int i = 0; i < n_chains; i++) {
final StringBuffer line = new StringBuffer();
line.append(titles[i]);
for (int j = 0; j < n_chains; j++) line.append(',').append(scores[i][j]);
line.append('\n');
dos.write(line.toString());
}
dos.flush();
} catch (final Exception e) {
e.printStackTrace();
}
} else if (cp.format.equals(cp.formats[1])) {
// as XML:
try {
final StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>\n<!DOCTYPE ggobidata SYSTEM \"ggobi.dtd\">\n");
sb.append("<ggobidata count=\"2\">\n");
sb.append("<data name=\"Pipe Chains\">\n");
sb.append("<description />\n");
// ggobi: what a crappy XML parser it has
sb.append("<variables count=\"0\">\n</variables>\n");
sb.append("<records count=\"").append(chains.size()).append("\" glyph=\"fr 1\" color=\"3\">\n");
int next = 0;
for (int i = 0; i < p.length; i++) {
final String prefix = Utils.getCharacter(i + 1);
final String color = new StringBuffer("color=\"").append(i + 1).append('\"').toString();
for (final Chain chain : (ArrayList<Chain>) p_chains[i]) {
sb.append("<record id=\"").append(next + 1).append("\" label=\"").append(prefix).append(' ').append(chain.getCellTitle()).append("\" ").append(color).append("></record>\n");
next++;
}
}
sb.append("</records>\n</data>\n");
sb.append("<data name=\"distances\">\n");
sb.append("<description />\n");
sb.append("<variables count=\"1\">\n<realvariable name=\"D\" />\n</variables>\n");
sb.append("<records count=\"").append(n_chains * (n_chains - 1)).append("\" glyph=\"fr 1\" color=\"0\">\n");
for (int i = 0; i < n_chains; i++) {
for (int j = 0; j < n_chains; j++) {
if (i == j)
continue;
sb.append("<record source=\"").append(i + 1).append("\" destination=\"").append(j + 1).append("\">").append(scores[i][j]).append("</record>\n");
}
}
sb.append("</records>\n</data>\n");
sb.append("</ggobidata>");
dos.write(sb.toString());
dos.flush();
} catch (final Exception e) {
e.printStackTrace();
}
} else if (cp.format.equals(cp.formats[2])) {
// as Phylip .dis
try {
// collect different projects
final ArrayList<Project> projects = new ArrayList<Project>();
for (final Chain chain : chains) {
final Project p = chain.getRoot().getProject();
if (!projects.contains(p))
projects.add(p);
}
final HashSet names = new HashSet();
final StringBuffer sb = new StringBuffer();
sb.append(scores.length).append('\n');
dos.write(sb.toString());
// unique ids, since phylip cannot handle long names
final AtomicInteger ids = new AtomicInteger(0);
final File ftags = new File(dir + filename + ".tags");
// encoding in Latin 1 (for macosx not to mess around
final OutputStreamWriter dostags = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(ftags)), "8859_1");
for (int i = 0; i < scores.length; i++) {
sb.setLength(0);
// String title = chains.get(i).getShortCellTitle().replace(' ', '_').replace('\t', '_').replace('[', '-').replace(']', '-');
final int id = ids.incrementAndGet();
final String sid = Utils.getCharacter(id);
String name = chains.get(i).getShortCellTitle();
// If sid.length() > 10 chars, trouble!
if (sid.length() > 10) {
Utils.log2("Ignoring " + name + " : id longer than 10 chars: " + id);
continue;
}
final int k = 1;
// Prepend a project char identifier to the name
String project_name = "";
if (projects.size() > 1) {
project_name = Utils.getCharacter(projects.indexOf(chains.get(i).getRoot().getProject()) + 1).toLowerCase();
name = project_name + name;
}
dostags.write(new StringBuilder().append(sid).append('\t').append(name).append('\n').toString());
if (null != outgroup && -1 != name.indexOf(outgroup)) {
Utils.logAll("Outgroup 0-based index is " + id + ", with id " + sid + ", with name " + name);
}
//
final int len = 12;
sb.append(sid);
// pad with spaces up to len
for (int j = len - sid.length(); j > 0; j--) sb.append(' ');
int count = 0;
for (int j = 0; j < scores[0].length; j++) {
sb.append(' ').append(scores[i][j]);
count++;
if (7 == count && j < scores[0].length - 1) {
sb.append('\n');
count = 0;
while (++count < len) sb.append(' ');
sb.append(' ');
count = 0;
}
}
sb.append('\n');
dos.write(sb.toString());
}
dos.flush();
dostags.flush();
dostags.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
dos.close();
} catch (final Exception e) {
e.printStackTrace();
} finally {
finishedWorking();
}
}
};
return Bureaucrat.createAndStart(worker, p);
}
use of ij.io.SaveDialog in project TrakEM2 by trakem2.
the class Render method exportSVG.
// ///////////////////////
// SVG format//
public static void exportSVG(ProjectThing thing, double z_scale) {
StringBuffer data = new StringBuffer();
data.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n").append("<svg\n").append("\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n").append("\txmlns:cc=\"http://web.resource.org/cc/\"\n").append("\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n").append("\txmlns:svg=\"http://www.w3.org/2000/svg\"\n").append("\txmlns=\"http://www.w3.org/2000/svg\"\n").append("\tid=\"").append(thing.getProject().toString()).append("\">\n");
// traverse the tree at node 'thing'
thing.exportSVG(data, z_scale, "\t");
data.append("</svg>");
// save the file
final SaveDialog sd = new SaveDialog("Save .svg", OpenDialog.getDefaultDirectory(), "svg");
String dir = sd.getDirectory();
if (null == dir)
return;
if (IJ.isWindows())
dir = dir.replace('\\', '/');
if (!dir.endsWith("/"))
dir += "/";
String file_name = sd.getFileName();
String file_path = dir + file_name;
File f = new File(file_path);
if (f.exists()) {
YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), "Overwrite?", "File " + file_name + " exists! Overwrite?");
if (!d.yesPressed()) {
return;
}
}
String contents = data.toString();
try {
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f), data.length()));
dos.writeBytes(contents);
dos.flush();
} catch (Exception e) {
IJError.print(e);
Utils.log("ERROR: Most likely did NOT save your file.");
}
}
use of ij.io.SaveDialog in project TrakEM2 by trakem2.
the class Utils method chooseFile.
/**
* Select a file from the file system, for saving purposes. Prompts for overwritting if the file exists, unless the ControlWindow.isGUIEnabled() returns false (i.e. there is no GUI).
*/
public static final File chooseFile(final String default_dir, final String name, final String extension) {
try {
return new TaskOnEDT<File>(new Callable<File>() {
@Override
public File call() {
// using ImageJ's JFileChooser or internal FileDialog, according to user preferences.
String name2 = null;
if (null != name && null != extension)
name2 = name + extension;
else if (null != name)
name2 = name;
else if (null != extension)
name2 = "untitled" + extension;
if (null != default_dir) {
OpenDialog.setDefaultDirectory(default_dir);
}
final SaveDialog sd = new SaveDialog("Save", OpenDialog.getDefaultDirectory(), name2, extension);
final String filename = sd.getFileName();
if (null == filename || filename.toLowerCase().startsWith("null"))
return null;
String dir = sd.getDirectory();
if (IJ.isWindows())
dir = dir.replace('\\', '/');
if (!dir.endsWith("/"))
dir += "/";
final File f = new File(dir + filename);
if (f.exists() && ControlWindow.isGUIEnabled()) {
final YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), "Overwrite?", "File " + filename + " exists! Overwrite?");
if (d.cancelPressed()) {
return null;
} else if (!d.yesPressed()) {
return chooseFile(name, extension);
}
// else if yes pressed, overwrite.
}
return f;
}
}).get();
} catch (final Throwable t) {
IJError.print(t);
return null;
}
}
Aggregations