/** * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from * jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty. */ public static String getClipboardStringContent(Clipboard clipboard) { // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); try { String selection = (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor)); if (selection == null) return null; boolean trailingEOL = (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator"))); // Some Java versions return the clipboard contents using the native line separator, // so have to convert it here , see jEdit's "registers.java" BufferedReader in = new BufferedReader(new StringReader(selection)); StringBuffer buf = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buf.append(line); buf.append('\n'); } // remove trailing \n if (!trailingEOL) buf.setLength(buf.length() - 1); return buf.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY); DataFlavor[] flavors = null; try { Transferable t = dtde.getTransferable(); iterator = null; flavors = t.getTransferDataFlavors(); if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors"); for (int i = 0; i < flavors.length; i++) { if (IJ.debugMode) IJ.log(" flavor[" + i + "]: " + flavors[i].getMimeType()); if (flavors[i].isFlavorJavaFileListType()) { Object data = t.getTransferData(DataFlavor.javaFileListFlavor); iterator = ((List) data).iterator(); break; } else if (flavors[i].isFlavorTextType()) { Object ob = t.getTransferData(flavors[i]); if (!(ob instanceof String)) continue; String s = ob.toString().trim(); if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s); ArrayList list = new ArrayList(); if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) { s = parseHTML(s); if (IJ.debugMode) IJ.log(" url: " + s); list.add(s); this.iterator = list.iterator(); break; } BufferedReader br = new BufferedReader(new StringReader(s)); String tmp; while (null != (tmp = br.readLine())) { tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8"); if (tmp.startsWith("file://")) tmp = tmp.substring(7); if (IJ.debugMode) IJ.log(" content: " + tmp); if (tmp.startsWith("http://")) list.add(s); else list.add(new File(tmp)); } this.iterator = list.iterator(); break; } } if (iterator != null) { Thread thread = new Thread(this, "DrawAndDrop"); thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY)); thread.start(); } } catch (Exception e) { dtde.dropComplete(false); return; } dtde.dropComplete(true); if (flavors == null || flavors.length == 0) { if (IJ.isMacOSX()) IJ.error( "First drag and drop ignored. Please try again. You can avoid this\n" + "problem by dragging to the toolbar instead of the status bar."); else IJ.error("Drag and drop failed"); } }
/** Execute the system command 'cmd' and fill an ArrayList with the results. */ public static ArrayList<String> executeSystemCommand(String cmd) { if (debug) System.out.println("cmd: " + cmd); ArrayList<String> list = new ArrayList<>(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (debug) System.out.println(line); list.add(line); } } catch (IOException e) { e.printStackTrace(); } return list; }
public static String ping(String address) { String reply = "Request timed out"; try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (line.trim().startsWith("Reply ")) { reply = line; break; } } } catch (IOException e) { e.printStackTrace(); } return reply; }
// ========================================================= public String recieve() throws IOException // RECIEVE METHOD { String recievedString; recievedString = buffRdr.readLine(); System.out.println("RECD<<<< " + id + ": " + recievedString); return recievedString; }
public static Properties getEnvironmentVariables() { synchronized (cygstartPath) { if (envVars != null) return envVars; envVars = new Properties(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { // if (debug) System.out.println("getEnvironmentVariables(): line=" + line); int idx = line.indexOf('='); if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1)); } } catch (IOException e) { e.printStackTrace(); } return envVars; } }
public void run(String arg) { GenericDialog gd = new GenericDialog("Options"); double sfreq = 20000.0; gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null); String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"}; gd.addChoice("PSF Type?", psfchoice, psfchoice[0]); String[] filetypechoice = { "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File" }; gd.addChoice("File Type?", filetypechoice, filetypechoice[0]); boolean ch2green = true; gd.addCheckbox("Ch2 is green?", ch2green); gd.showDialog(); if (gd.wasCanceled()) { return; } sfreq = gd.getNextNumber(); int psfflag = gd.getNextChoiceIndex(); int fileflag = gd.getNextChoiceIndex(); ch2green = gd.getNextBoolean(); int nfiles = 0; Object[] histograms = null; int xmax = 0; int ymax = 0; String[] names = null; if (fileflag < 2) { jdataio ioclass = new jdataio(); File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance()); if (filearray.length == 0) { return; } String dir = filearray[0].getAbsolutePath(); int sepindex = dir.lastIndexOf(File.separator); String newdir = dir.substring(0, sepindex + 1); OpenDialog.setDefaultDirectory(newdir); nfiles = filearray.length / 2; if (nfiles > 25) { nfiles = 25; } histograms = new Object[nfiles]; names = organize_c3_files(filearray); for (int i = 0; i < nfiles; i++) { try { int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0); int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0); int length3 = (int) (((double) filearray[2 * i].length()) / 2.0); int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0); InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i])); InputStream instream2 = new BufferedInputStream(new FileInputStream(filearray[2 * i + 1])); if (fileflag == 0) { int[] pmdata = new int[length1]; int[] pmdata2 = new int[length2]; if (!ioclass.skipstreambytes(instream, 128)) { showioerror(); instream.close(); return; } if (!ioclass.skipstreambytes(instream2, 128)) { showioerror(); instream2.close(); return; } if (!ioclass.readintelintfile(instream, length1, pmdata)) { showioerror(); instream.close(); return; } if (!ioclass.readintelintfile(instream2, length2, pmdata2)) { showioerror(); instream2.close(); return; } if (ch2green) { histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000); } else { histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000); } } else { float[] tmdata = new float[length3]; float[] tmdata2 = new float[length4]; if (!ioclass.readintelshortfile(instream, length3, tmdata)) { showioerror(); instream.close(); return; } if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) { showioerror(); instream2.close(); return; } if (ch2green) { histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata); } else { histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2); } } if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } instream.close(); instream2.close(); } catch (IOException e) { showioerror(); return; } } } else { if (fileflag == 2) { ImageWindow iw = WindowManager.getCurrentWindow(); float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues"); float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues"); sfreq = 1.0 / ((double) tempxvals[0][1]); nfiles = trajectories.length / 2; if (nfiles > 25) { nfiles = 25; } names = new String[nfiles + 1]; names[nfiles] = "avg"; histograms = new Object[nfiles]; for (int i = 0; i < nfiles; i++) { names[i] = "trajectory " + (i + 1); if (ch2green) { histograms[i] = (new pmodeconvert()) .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]); } else { histograms[i] = (new pmodeconvert()) .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]); } if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } } } else { // here we read tab delimited lines from files jdataio ioclass = new jdataio(); File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance()); if (filearray.length == 0) { return; } String dir = filearray[0].getAbsolutePath(); int sepindex = dir.lastIndexOf(File.separator); String newdir = dir.substring(0, sepindex + 1); OpenDialog.setDefaultDirectory(newdir); nfiles = filearray.length; if (nfiles > 25) { nfiles = 25; } histograms = new Object[nfiles]; names = new String[nfiles + 1]; names[nfiles] = "avg"; for (int i = 0; i < nfiles; i++) { try { names[i] = filearray[i].getName(); BufferedReader d = new BufferedReader(new FileReader(filearray[i])); String[] lines = new String[256]; int counter = 0; do { lines[counter] = d.readLine(); counter++; } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256); int numcolumns = 0; for (int j = 0; j < counter - 1; j++) { int temp = getncolumns(lines[j]); if (temp > numcolumns) { numcolumns = temp; } } float[][] temphist2 = null; if (ch2green) { temphist2 = new float[numcolumns][counter - 1]; } else { temphist2 = new float[counter - 1][numcolumns]; } for (int k = 0; k < counter - 1; k++) { float[] temp = tab_delim2float(lines[k]); for (int j = 0; j < numcolumns; j++) { if (ch2green) { temphist2[j][k] = temp[j]; } else { temphist2[k][j] = temp[j]; } } } histograms[i] = temphist2; d.close(); } catch (IOException e) { showioerror(); return; } } for (int i = 0; i < nfiles; i++) { if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } } } } // note that here x is green and y is red float[][][] pch = new float[nfiles][xmax][ymax]; for (int i = 0; i < nfiles; i++) { for (int j = 0; j < ((float[][]) histograms[i]).length; j++) { for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) { pch[i][j][k] = ((float[][]) histograms[i])[j][k]; } } } final PCH2DFitWindow cw = new PCH2DFitWindow(); cw.init(names, pch, psfflag); final Frame f = new Frame("PCH 2D Analysis"); f.setLocation(10, 10); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); } }); f.add(cw); f.pack(); f.setResizable(false); Insets ins = f.getInsets(); cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65; cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right; f.setSize(cw.totalSize); f.setVisible(true); cw.requestFocus(); }
/** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard; try { // May throw ugly exception on system without X clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (Exception e) { return false; } if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable.getTransferData(DataFlavor.plainTextFlavor); /* * This fix was suggested in bug #1060649 at * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 * to get around the deprecated DataFlavor.plainTextFlavor, but it * raises a UnsupportedFlavorException on Mac OS X */ if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line = null; for (BufferedReader read = new BufferedReader((Reader) content); (line = read.readLine()) != null; ) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException ufe) { if (debugger != null) debug(ufe + ""); return false; } }
/** * Try to determine whether this application is running under Windows or some other platform by * examining the "os.name" property. */ static { String os = System.getProperty("os.name"); // String version = System.getProperty("os.version"); // for Win7, reports "6.0" on JDK7, should // be "6.1"; for Win8, reports "6.2" as of JDK7u17 if (SystemUtils.startsWithIgnoreCase(os, "windows 7")) isWin7 = true; // reports "Windows Vista" on JDK7 else if (SystemUtils.startsWithIgnoreCase(os, "windows 8")) isWin7 = true; // reports "Windows 8" as of JDK7u17 else if (SystemUtils.startsWithIgnoreCase(os, "windows vista")) isVista = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows xp")) isWinXP = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows 2000")) isWin2k = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows nt")) isWinNT = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows")) isWin9X = true; // win95 or win98 (what about WinME?) else if (SystemUtils.startsWithIgnoreCase(os, "mac")) isMac = true; else if (SystemUtils.startsWithIgnoreCase(os, "so")) isSolaris = true; // sunos or solaris else if (os.equalsIgnoreCase("linux")) isLinux = true; else isUnix = true; // assume UNIX, e.g. AIX, HP-UX, IRIX String osarch = System.getProperty("os.arch"); String arch = (osarch != null && osarch.contains("64")) ? "_x64" /* eg. 'amd64' */ : "_x32"; String syslib = SYSLIB + arch; try { // loading a native lib in a static initializer ensures that it is available before any // method in this class is called: System.loadLibrary(syslib); System.out.println( "Done loading '" + System.mapLibraryName(syslib) + "', PID=" + getProcessID()); } catch (Error e) { System.err.println( "Native library '" + System.mapLibraryName(syslib) + "' not found in 'java.library.path': " + System.getProperty("java.library.path")); throw e; // re-throw } if (isWinPlatform()) { System.setProperty( "line.separator", "\n"); // so we won't have to mess with DOS line endings ever again comSpec = getEnv( "comSpec"); // use native method here since getEnvironmentVariable() needs to know // comSpec comSpec = (comSpec != null) ? comSpec + " /c " : ""; try (BufferedReader br = new BufferedReader( new InputStreamReader( RUNTIME.exec(comSpec + "ver").getInputStream()))) { // fix for Win7,8 for (String line = null; (line = br.readLine()) != null; ) { if (isVista && (line.contains("6.1" /*Win7*/) || line.contains("6.2" /*Win8*/))) { isVista = false; isWin7 = true; } } } catch (IOException e) { e.printStackTrace(); } String cygdir = getEnv("cygdir"); // this is set during CygWin install to "?:/cygwin/bin" isCygWin = (cygdir != null && !cygdir.equals("%cygdir%")); cygstartPath = cygdir + "/cygstart.exe"; // path to CygWin's cygutils' "cygstart" binary if (getDebug() && Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); for (Desktop.Action action : Desktop.Action.values()) System.out.println( "Desktop action " + action + " supported? " + desktop.isSupported(action)); } } }
public void run(String arg) { Frame[] niframes = WindowManager.getNonImageWindows(); String[] titles = new String[niframes.length + 1]; for (int i = 0; i < niframes.length; i++) { titles[i] = niframes[i].getTitle(); } titles[niframes.length] = "Clipboard"; GenericDialog gd = new GenericDialog("Windows"); boolean importfile = false; gd.addCheckbox("Import from file?", importfile); gd.addChoice("Windows", titles, titles[0]); boolean hasxvals = false; gd.addCheckbox("X Vals Column?", hasxvals); boolean multix = false; gd.addCheckbox("Multi_X_Columns?", multix); boolean skipendzeros = false; gd.addCheckbox("Skip_end_zeros?", skipendzeros); String[] delimiters = {"Tab", "Comma", "Space"}; gd.addChoice("Delimiter", delimiters, delimiters[0]); gd.showDialog(); if (gd.wasCanceled()) { return; } importfile = gd.getNextBoolean(); int index = gd.getNextChoiceIndex(); hasxvals = gd.getNextBoolean(); multix = gd.getNextBoolean(); skipendzeros = gd.getNextBoolean(); int delimindex = gd.getNextChoiceIndex(); if (multix) hasxvals = true; String textdata = ""; if (importfile) { OpenDialog od = new OpenDialog("Open File", "", ".txt"); String directory = od.getDirectory(); String name = od.getFileName(); if (name == null) { return; } try { File infile = new File(directory + name); BufferedReader b = new BufferedReader(new FileReader(infile)); textdata = (new jdataio()).readstringfile(b); b.close(); } catch (IOException e) { return; } } else { if (index == niframes.length) { // here we get the data from the clipboard Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { textdata = (String) t.getTransferData(DataFlavor.stringFlavor); } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } if (textdata.equals("")) { IJ.error("Error copying from clipboard."); return; } } else { if (niframes[index] instanceof Editor) { Editor tw = (Editor) niframes[index]; textdata = tw.getText(); } else { if (niframes[index] instanceof TextWindow) { TextWindow tw = (TextWindow) niframes[index]; textdata = tw.getTextPanel().getText(); } else { IJ.showMessage("Not a valid text window"); return; } } } } if (textdata == null) { IJ.showMessage("Error in Obtaining String"); return; } if (textdata.indexOf("\r") >= 0) { textdata = textdata.replace('\r', '\n'); } char[] delims = {'\t', ',', ' '}; delimit_string ds = new delimit_string(delims[delimindex]); String[] rows = ds.getrows(textdata); int lines = rows.length; int columns = ds.getnumcolumns(rows[0]); int ycolumns = columns; if (hasxvals) { if (multix) { ycolumns /= 2; } else { ycolumns--; } } if (multix) { float[][] ydata = new float[ycolumns][lines]; float[][] xdata = new float[ycolumns][lines]; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); for (int j = 0; j < ycolumns; j++) { ydata[j][i] = temp[2 * j + 1]; xdata[j][i] = temp[2 * j]; } } int[] npts = new int[ycolumns]; for (int i = 0; i < ycolumns; i++) { npts[i] = lines; } if (skipendzeros) { for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; while ((xdata[i][counter] == 0.0f || Float.isNaN(xdata[i][counter])) && counter > 0) { xdata[i][counter] = 0.0f; ydata[i][counter] = 0.0f; npts[i]--; counter--; } } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } else { float[][] tempydata = new float[ycolumns][lines]; float[] tempxdata = new float[lines]; float[][] xdata = null; float[][] ydata = null; int startcolumn = 0; if (hasxvals) startcolumn = 1; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); if (hasxvals) { tempxdata[i] = temp[0]; } else { tempxdata[i] = (float) (i + 1); } for (int j = 0; j < ycolumns; j++) { tempydata[j][i] = temp[j + startcolumn]; } } int[] npts = new int[ycolumns]; npts[0] = lines; if (skipendzeros) { int maxpts = 0; for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; npts[i] = lines; while ((tempydata[i][counter] == 0.0f || Float.isNaN(tempydata[i][counter])) && counter > 0) { npts[i]--; counter--; } if (npts[i] > maxpts) maxpts = npts[i]; IJ.log("" + npts[i]); } ydata = new float[ycolumns][maxpts]; xdata = new float[ycolumns][maxpts]; for (int i = 0; i < ycolumns; i++) { // npts[i]=npts[0]; System.arraycopy(tempxdata, 0, xdata[i], 0, npts[i]); System.arraycopy(tempydata[i], 0, ydata[i], 0, npts[i]); } } else { ydata = tempydata; xdata = new float[ycolumns][]; for (int i = 0; i < ycolumns; i++) { npts[i] = npts[0]; xdata[i] = tempxdata.clone(); } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } }