2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Toolkit;
24 import java.awt.event.MouseEvent;
25 import java.io.BufferedReader;
27 import java.io.FileOutputStream;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.Reader;
34 import java.util.Properties;
36 import javax.swing.SwingUtilities;
38 import org.json.simple.parser.JSONParser;
39 import org.json.simple.parser.ParseException;
41 import jalview.bin.argparser.ArgParser;
42 import jalview.javascript.json.JSON;
45 * System platform information used by Applet and Application
52 private static boolean isJS = /** @j2sNative true || */
55 private static Boolean isNoJSMac = null, isNoJSWin = null, isMac = null,
56 isWin = null, isLinux = null;
58 private static Boolean isHeadless = null;
60 // If launched from CLI with launcher script then -DCOLUMNWIDTH is set
61 private static final int CONSOLEWIDTH;
63 private static final String CONSOLEWIDTHPROPERTY = "CONSOLEWIDTH";
68 if (System.getProperty(CONSOLEWIDTHPROPERTY) != null
69 && System.getProperty(CONSOLEWIDTHPROPERTY).length() > 0)
73 cw = Integer.parseInt(System.getProperty(CONSOLEWIDTHPROPERTY));
74 } catch (NumberFormatException e)
82 * added to group mouse events into Windows and nonWindows (mac, unix, linux)
86 public static boolean isMac()
89 ? (isMac = (System.getProperty("os.name").indexOf("Mac") >= 0))
94 * added to group mouse events into Windows and nonWindows (mac, unix, linux)
98 public static boolean isWin()
100 return (isWin == null
101 ? (isWin = (System.getProperty("os.name").indexOf("Win") >= 0))
106 * added to check LaF for Linux
110 public static boolean isLinux()
112 return (isLinux == null
113 ? (isLinux = (System.getProperty("os.name")
114 .indexOf("Linux") >= 0))
120 * @return true if HTML5 JavaScript
122 public static boolean isJS()
128 * sorry folks - Macs really are different
130 * BH: disabled for SwingJS -- will need to check key-press issues
132 * @return true if we do things in a special way.
134 public static boolean isAMacAndNotJS()
136 return (isNoJSMac == null ? (isNoJSMac = !isJS && isMac()) : isNoJSMac);
140 * Check if we are on a Microsoft plaform...
142 * @return true if we have to cope with another platform variation
144 public static boolean isWindowsAndNotJS()
146 return (isNoJSWin == null ? (isNoJSWin = !isJS && isWin()) : isNoJSWin);
151 * @return true if we are running in non-interactive no UI mode
153 public static boolean isHeadless()
155 if (isHeadless == null)
157 isHeadless = "true".equals(System.getProperty("java.awt.headless"));
164 * @return nominal maximum command line length for this platform
166 public static int getMaxCommandLineLength()
168 // TODO: determine nominal limits for most platforms.
169 return 2046; // this is the max length for a windows NT system.
173 * Answers the input with every backslash replaced with a double backslash (an
174 * 'escaped' single backslash)
179 public static String escapeBackslashes(String s)
181 return s == null ? null : s.replace("\\", "\\\\");
185 * Answers true if the mouse event has Meta-down (Command key on Mac) or
186 * Ctrl-down (on other o/s). Note this answers _false_ if the Ctrl key is
187 * pressed instead of the Meta/Cmd key on Mac. To test for Ctrl-pressed on
188 * Mac, you can use e.isPopupTrigger().
193 public static boolean isControlDown(MouseEvent e)
195 return isControlDown(e, isMac());
199 * Overloaded version of method (to allow unit testing)
205 protected static boolean isControlDown(MouseEvent e, boolean aMac)
209 return e.isControlDown();
211 // Jalview 2.11 code below: above is as amended for JalviewJS
213 // * answer false for right mouse button
215 // if (e.isPopupTrigger())
220 // (jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx() //
221 // .getMenuShortcutKeyMaskEx()
222 // & jalview.util.ShortcutKeyMaskExWrapper
223 // .getModifiersEx(e)) != 0; // getModifiers()) != 0;
225 // answer false for right mouse button
226 // shortcut key will be META for a Mac
227 return !e.isPopupTrigger()
228 && (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
229 & e.getModifiers()) != 0;
230 // could we use e.isMetaDown() here?
233 // BH: I don't know about that previous method. Here is what SwingJS uses.
234 // Notice the distinction in mouse events. (BUTTON3_MASK == META)
236 // private static boolean isPopupTrigger(int id, int mods, boolean isWin) {
237 // boolean rt = ((mods & InputEvent.BUTTON3_MASK) != 0);
239 // if (id != MouseEvent.MOUSE_RELEASED)
242 //// // Oddly, Windows returns InputEvent.META_DOWN_MASK on release, though
243 //// // BUTTON3_DOWN_MASK for pressed. So here we just accept both.
245 //// actually, we can use XXX_MASK, not XXX_DOWN_MASK and avoid this issue,
247 //// J2S adds the appropriate extended (0x3FC0) and simple (0x3F) modifiers.
251 // // mac, linux, unix
252 // if (id != MouseEvent.MOUSE_PRESSED)
254 // boolean lt = ((mods & InputEvent.BUTTON1_MASK) != 0);
255 // boolean ctrl = ((mods & InputEvent.CTRL_MASK) != 0);
256 // return rt || (ctrl && lt);
262 * Windows (not Mac, Linux, or Unix) and right button to test for the
263 * right-mouse pressed event in Windows that would have opened a menu or a
269 public static boolean isWinRightButton(MouseEvent e)
271 // was !isAMac(), but that is true also for Linux and Unix and JS,
273 return isWin() && SwingUtilities.isRightMouseButton(e);
277 * Windows (not Mac, Linux, or Unix) and middle button -- for mouse wheeling
278 * without pressing the button.
283 public static boolean isWinMiddleButton(MouseEvent e)
285 // was !isAMac(), but that is true also for Linux and Unix and JS
286 return isWin() && SwingUtilities.isMiddleMouseButton(e);
289 public static boolean allowMnemonics()
294 public final static int TIME_RESET = 0;
296 public final static int TIME_MARK = 1;
298 public static final int TIME_SET = 2;
300 public static final int TIME_GET = 3;
302 public static long time, mark, set, duration;
304 public static void timeCheck(String msg, int mode)
306 long t = System.currentTimeMillis();
313 jalview.bin.Console.errPrintln("Platform: timer reset\t\t\t" + msg);
319 duration += (t - set);
329 jalview.bin.Console.errPrintln(
330 "Platform: timer mark\t" + ((t - time) / 1000f) + "\t"
331 + ((t - mark) / 1000f) + "\t" + msg);
343 .errPrintln("Platform: timer dur\t" + ((t - time) / 1000f)
344 + "\t" + ((duration) / 1000f) + "\t" + msg);
351 public static void cacheFileData(String path, Object data)
353 if (!isJS() || data == null)
360 * swingjs.JSUtil.cacheFileData$S$O(path, data);
365 public static void cacheFileData(File file)
368 if (!isJS() || (data = Platform.getFileBytes(file)) == null)
372 cacheFileData(file.toString(), data);
375 public static byte[] getFileBytes(File f)
377 return /** @j2sNative f && swingjs.JSUtil.getFileAsBytes$O(f) || */
381 public static byte[] getFileAsBytes(String fileStr)
384 // BH 2018 hack for no support for access-origin
386 * @j2sNative bytes = swingjs.JSUtil.getFileAsBytes$O(fileStr)
388 cacheFileData(fileStr, bytes);
392 @SuppressWarnings("unused")
393 public static String getFileAsString(String url)
399 * ret = swingjs.JSUtil.getFileAsString$S(url);
403 cacheFileData(url, ret);
407 public static boolean setFileBytes(File f, String urlstring)
413 @SuppressWarnings("unused")
414 byte[] bytes = getFileAsBytes(urlstring);
415 // TODO temporary doubling of 秘bytes and _bytes;
416 // just remove _bytes when new transpiler has been installed
418 * @j2sNative f.\u79d8bytes = f._bytes = bytes;
423 public static void addJ2SBinaryType(String ext)
428 * J2S._binaryTypes.push("." + ext + "?");
434 * Encode the URI using JavaScript encodeURIComponent
437 * @return encoded value
439 public static String encodeURI(String value)
442 * @j2sNative value = encodeURIComponent(value);
448 * Open the URL using a simple window call if this is JavaScript
451 * @return true if window has been opened
453 public static boolean openURL(String url)
468 public static String getUniqueAppletID()
471 * @j2sNative return swingjs.JSUtil.getApplet$()._uniqueId;
479 * Read the Info block for this applet.
484 * @return unique id for this applet
486 public static void readInfoProperties(String prefix, Properties p)
492 String id = getUniqueAppletID();
493 String key = "", value = "";
495 * @j2sNative var info = swingjs.JSUtil.getApplet$().__Info || {}; for (var
496 * key in info) { if (key.indexOf(prefix) == 0) { value = "" +
500 jalview.bin.Console.outPrintln(
501 "Platform id=" + id + " reading Info." + key + " = " + value);
502 p.put(id + "_" + key, value);
512 public static void setAjaxJSON(URL url)
520 public static Object parseJSON(InputStream response)
521 throws IOException, ParseException
525 return JSON.parse(response);
528 BufferedReader br = null;
531 br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
532 return new JSONParser().parse(br);
540 } catch (IOException e)
548 public static Object parseJSON(String json) throws ParseException
550 return (isJS() ? JSON.parse(json) : new JSONParser().parse(json));
553 public static Object parseJSON(Reader r)
554 throws IOException, ParseException
563 return new JSONParser().parse(r);
565 // Using a file reader is not currently supported in SwingJS JavaScript
567 if (r instanceof FileReader)
569 throw new IOException(
570 "StringJS does not support FileReader parsing for JSON -- but it could...");
572 return JSON.parse(r);
577 * Dump the input stream to an output file.
581 * @throws IOException
582 * if the file cannot be created or there is a problem reading the
585 public static void streamToFile(InputStream is, File outFile)
589 * @j2sNative outFile.setBytes$O && outFile.setBytes$O(is) &&
595 FileOutputStream fio = new FileOutputStream(outFile);
598 byte[] bb = new byte[32 * 1024];
600 while ((l = is.read(bb)) > 0)
611 * Add a known domain that implements access-control-allow-origin:*
613 * These should be reviewed periodically.
616 * for a service that is not allowing ajax
618 * @author hansonr@stolaf.edu
621 public static void addJ2SDirectDatabaseCall(String domain)
626 jalview.bin.Console.outPrintln(
627 "Platform adding known access-control-allow-origin * for domain "
632 * J2S.addDirectDatabaseCall(domain);
638 public static void getURLCommandArguments()
641 // setting ArgParser.ignoreNonStringValues allows non-string args to be
642 // set with, e.g., --wrap=hello
643 // which might be necessary for a querystring, plus we don't have access
644 // to Arg.hasOption(Opt.STRING)
647 ArgParser.setIgnoreNonStringValues(true);
651 // extra spaces between lines of javascript to avoid eclipse comment
652 // munging into one line
655 * Retrieve the first query field as command arguments to Jalview. Include
656 * only if prior to "?j2s" or "&j2s" or "#". Assign the applet's
657 * __Info.args element to this value.
659 * if a querystringnamespace has been given in Info={...}. Use this
660 * namespace to find arguments and values in the querystring parameters.
661 * Arguments that do not take a value do not need to have a value in the
662 * querystring. If they do they will be ignored. Note, this means you
663 * cannot do 'debug=false' instead of 'nodebug'. If querystringnamepsace
664 * is an empty string ("") then no colon (":") will be expected.
666 * if querystringnamespace is not defined then use the old style single
667 * first parameter for arguments
669 * @j2sNative var querystringnamespace =
670 * J2S.thisApplet.__Info.querystringnamespace;
672 * if (querystringnamespace === undefined)
676 * System.out.println("No querystringnamespace given");
679 * decodeURI((document.location.href.replace("&","?").split("?j2s")[0]
680 * + "?").split("?")[1].split("#")[0]);
682 * a && (System.out.println("URL arguments detected were "+a))
683 * && (J2S.thisApplet.__Info.urlargs = a.split(" "));
685 * (!J2S.thisApplet.__Info.args || J2S.thisApplet.__Info.args
686 * == "" || J2S.thisApplet.__Info.args == "??") &&
687 * (J2S.thisApplet.__Info.args = a) && (System.out.println("URL
688 * arguments were passed to J2S main."));
692 * else // querystringnamespace is defined
698 * if (J2S.thisApplet.__Info.querystringnamespace) {
700 * qsnsc = J2S.thisApplet.__Info.querystringnamespace + ":";
704 * System.out.println("querystringnamespace is '"+qsnsc+"'");
706 * var qsParams = new URLSearchParams(window.location.search);
710 * for (var param of qsParams) {
712 * var key = param[0];
714 * var val = param[1];
716 * if (key.startsWith(qsnsc)) {
718 * var arg = key.substring(qsnsc.length);
720 * qsargs.push("--" + arg + "=" + val);
722 * System.out.println("Setting arg '"+arg+"' to '"+val+"'");
728 * qsargs && (System.out.println("URL parameters detected were
729 * "+qsargs.join(" "))) && (J2S.thisApplet.__Info.urlargs =
732 * (!J2S.thisApplet.__Info.args || J2S.thisApplet.__Info.args
733 * == "" || J2S.thisApplet.__Info.args == "??") &&
734 * (J2S.thisApplet.__Info.args = qsargs.join(" ")) &&
735 * (System.out.println("URL parameters were passed to J2S
740 } catch (Throwable t)
743 * @j2sNative console.log("Problem looking for arguments");
750 * A (case sensitive) file path comparator that ignores the difference between
757 public static boolean pathEquals(String path1, String path2)
761 return path2 == null;
767 String p1 = path1.replace('\\', '/');
768 String p2 = path2.replace('\\', '/');
769 return p1.equals(p2);
773 * If started on command line using launch script, return the console width
775 public static int consoleWidth()