e53d2a945cc5d544528ce0cc5e4b8a860886eaa0
[jalview.git] / src / jalview / util / Platform.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.util;
22
23 import jalview.javascript.json.JSON;
24
25 import java.awt.Color;
26 import java.awt.Toolkit;
27 import java.awt.event.MouseEvent;
28 import java.io.BufferedReader;
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.io.Reader;
36 import java.net.MalformedURLException;
37 import java.net.URL;
38 import java.util.Properties;
39 import java.util.logging.ConsoleHandler;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42
43 import javax.swing.SwingUtilities;
44
45 import org.json.simple.parser.JSONParser;
46 import org.json.simple.parser.ParseException;
47
48 import com.stevesoft.pat.Regex;
49
50 /**
51  * System platform information used by Applet and Application
52  * 
53  * @author Jim Procter
54  */
55 public class Platform
56 {
57
58   private static boolean isJS = /** @j2sNative true || */
59           false;
60
61   private static Boolean isNoJSMac = null, isNoJSWin = null, isMac = null,
62           isWin = null;
63
64   // private static Boolean isHeadless = null;
65
66   /**
67    * added to group mouse events into Windows and nonWindows (mac, unix, linux)
68    * 
69    * @return
70    */
71   public static boolean isMac()
72   {
73     return (isMac == null
74             ? (isMac = (System.getProperty("os.name").indexOf("Mac") >= 0))
75             : isMac);
76   }
77
78   /**
79    * added to group mouse events into Windows and nonWindows (mac, unix, linux)
80    * 
81    * @return
82    */
83   public static boolean isWin()
84   {
85     return (isWin == null
86             ? (isWin = (System.getProperty("os.name").indexOf("Win") >= 0))
87             : isWin);
88   }
89
90   /**
91    * 
92    * @return true if HTML5 JavaScript
93    */
94   public static boolean isJS()
95   {
96     return isJS;
97   }
98
99   /**
100    * sorry folks - Macs really are different
101    * 
102    * BH: disabled for SwingJS -- will need to check key-press issues
103    * 
104    * @return true if we do things in a special way.
105    */
106   public static boolean isAMacAndNotJS()
107   {
108     return (isNoJSMac == null ? (isNoJSMac = !isJS && isMac()) : isNoJSMac);
109   }
110
111   /**
112    * Check if we are on a Microsoft plaform...
113    * 
114    * @return true if we have to cope with another platform variation
115    */
116   public static boolean isWindowsAndNotJS()
117   {
118     return (isNoJSWin == null ? (isNoJSWin = !isJS && isWin()) : isNoJSWin);
119   }
120
121   // /**
122   // *
123   // * @return true if we are running in non-interactive no UI mode
124   // */
125   // public static boolean isHeadless()
126   // {
127   // if (isHeadless == null)
128   // {
129   // isHeadless = "true".equals(System.getProperty("java.awt.headless"));
130   // }
131   // return isHeadless;
132   // }
133
134   /**
135    * 
136    * @return nominal maximum command line length for this platform
137    */
138   public static int getMaxCommandLineLength()
139   {
140     // TODO: determine nominal limits for most platforms.
141     return 2046; // this is the max length for a windows NT system.
142   }
143
144   /**
145    * escape a string according to the local platform's escape character
146    * 
147    * @param file
148    * @return escaped file
149    */
150   public static String escapeString(String file)
151   {
152     StringBuffer f = new StringBuffer();
153     int p = 0, lastp = 0;
154     while ((p = file.indexOf('\\', lastp)) > -1)
155     {
156       f.append(file.subSequence(lastp, p));
157       f.append("\\\\");
158       lastp = p + 1;
159     }
160     f.append(file.substring(lastp));
161     return f.toString();
162   }
163
164   /**
165    * Answers true if the mouse event has Meta-down (Command key on Mac) or
166    * Ctrl-down (on other o/s). Note this answers _false_ if the Ctrl key is
167    * pressed instead of the Meta/Cmd key on Mac. To test for Ctrl-pressed on
168    * Mac, you can use e.isPopupTrigger().
169    * 
170    * @param e
171    * @return
172    */
173   public static boolean isControlDown(MouseEvent e)
174   {
175     return isControlDown(e, isMac());
176   }
177
178   /**
179    * Overloaded version of method (to allow unit testing)
180    * 
181    * @param e
182    * @param aMac
183    * @return
184    */
185   protected static boolean isControlDown(MouseEvent e, boolean aMac)
186   {
187     if (!aMac)
188     {
189       return e.isControlDown();
190     }
191     // answer false for right mouse button
192     // shortcut key will be META for a Mac
193     return !e.isPopupTrigger()
194             && (Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
195                     & e.getModifiers()) != 0;
196     // could we use e.isMetaDown() here?
197   }
198
199   // BH: I don't know about that previous method. Here is what SwingJS uses.
200   // Notice the distinction in mouse events. (BUTTON3_MASK == META)
201   //
202   // private static boolean isPopupTrigger(int id, int mods, boolean isWin) {
203   // boolean rt = ((mods & InputEvent.BUTTON3_MASK) != 0);
204   // if (isWin) {
205   // if (id != MouseEvent.MOUSE_RELEASED)
206   // return false;
207   ////
208   //// // Oddly, Windows returns InputEvent.META_DOWN_MASK on release, though
209   //// // BUTTON3_DOWN_MASK for pressed. So here we just accept both.
210   ////
211   //// actually, we can use XXX_MASK, not XXX_DOWN_MASK and avoid this issue,
212   // because
213   //// J2S adds the appropriate extended (0x3FC0) and simple (0x3F) modifiers.
214   ////
215   // return rt;
216   // } else {
217   // // mac, linux, unix
218   // if (id != MouseEvent.MOUSE_PRESSED)
219   // return false;
220   // boolean lt = ((mods & InputEvent.BUTTON1_MASK) != 0);
221   // boolean ctrl = ((mods & InputEvent.CTRL_MASK) != 0);
222   // return rt || (ctrl && lt);
223   // }
224   // }
225   //
226
227   /**
228    * Windows (not Mac, Linux, or Unix) and right button to test for the
229    * right-mouse pressed event in Windows that would have opened a menu or a
230    * Mac.
231    * 
232    * @param e
233    * @return
234    */
235   public static boolean isWinRightButton(MouseEvent e)
236   {
237     // was !isAMac(), but that is true also for Linux and Unix and JS,
238
239     return isWin() && SwingUtilities.isRightMouseButton(e);
240   }
241
242   /**
243    * Windows (not Mac, Linux, or Unix) and middle button -- for mouse wheeling
244    * without pressing the button.
245    * 
246    * @param e
247    * @return
248    */
249   public static boolean isWinMiddleButton(MouseEvent e)
250   {
251     // was !isAMac(), but that is true also for Linux and Unix and JS
252     return isWin() && SwingUtilities.isMiddleMouseButton(e);
253   }
254
255   public static boolean allowMnemonics()
256   {
257     return !isMac();
258   }
259
260   public final static int TIME_RESET = 0;
261
262   public final static int TIME_MARK = 1;
263
264   public static final int TIME_SET = 2;
265
266   public static final int TIME_GET = 3;
267
268   public static long time, mark, set, duration;
269
270   /**
271    * typical usage:
272    * 
273    * Platform.timeCheck(null, Platform.TIME_MARK);
274    * 
275    * ...
276    * 
277    * Platform.timeCheck("some message", Platform.TIME_MARK);
278    * 
279    * @param msg
280    * @param mode
281    */
282   public static void timeCheck(String msg, int mode)
283   {
284     long t = System.currentTimeMillis();
285     switch (mode)
286     {
287     case TIME_RESET:
288       time = mark = t;
289       if (msg != null)
290       {
291         System.err.println("Platform: timer reset\t\t\t" + msg);
292       }
293       break;
294     case TIME_MARK:
295       if (set > 0)
296       {
297         duration += (t - set);
298       }
299       else
300       {
301         if (time == 0)
302         {
303           time = mark = t;
304         }
305         if (msg != null)
306         {
307           System.err.println("Platform: timer mark\t" + ((t - time) / 1000f)
308                   + "\t" + ((t - mark) / 1000f) + "\t" + msg);
309         }
310         mark = t;
311       }
312       break;
313     case TIME_SET:
314       set = t;
315       break;
316     case TIME_GET:
317       if (msg != null)
318       {
319         System.err.println("Platform: timer dur\t" + ((t - time) / 1000f)
320                 + "\t" + ((duration) / 1000f) + "\t" + msg);
321       }
322       set = 0;
323       break;
324     }
325   }
326
327   public static void cacheFileData(String path, Object data)
328   {
329     if (!isJS() || data == null)
330     {
331       return;
332     }
333     /**
334      * @j2sNative
335      * 
336      *            swingjs.JSUtil.cacheFileData$S$O(path, data);
337      * 
338      */
339   }
340
341   public static void cacheFileData(File file)
342   {
343     byte[] data;
344     if (!isJS() || (data = Platform.getFileBytes(file)) == null)
345     {
346       return;
347     }
348     cacheFileData(file.toString(), data);
349   }
350
351   public static byte[] getFileBytes(File f)
352   {
353     // TODO temporary doubling of 秘bytes and _bytes;
354     // just remove _bytes when new transpiler has been installed
355     return /** @j2sNative f && (f.秘bytes || f._bytes) || */
356     null;
357   }
358
359   public static byte[] getFileAsBytes(String fileStr)
360   {
361     byte[] bytes = null;
362     // BH 2018 hack for no support for access-origin
363     /**
364      * @j2sNative bytes = swingjs.JSUtil.getFileAsBytes$O(fileStr)
365      */
366     cacheFileData(fileStr, bytes);
367     return bytes;
368   }
369
370   @SuppressWarnings("unused")
371   public static String getFileAsString(String url)
372   {
373     String ret = null;
374     /**
375      * @j2sNative
376      * 
377      *            ret = swingjs.JSUtil.getFileAsString$S(url);
378      * 
379      * 
380      */
381     cacheFileData(url, ret);
382     return ret;
383   }
384
385   public static boolean setFileBytes(File f, String urlstring)
386   {
387     if (!isJS())
388     {
389       return false;
390     }
391     @SuppressWarnings("unused")
392     byte[] bytes = getFileAsBytes(urlstring);
393     // TODO temporary doubling of 秘bytes and _bytes;
394     // just remove _bytes when new transpiler has been installed
395     /**
396      * @j2sNative f.秘bytes = f._bytes = bytes;
397      */
398     return true;
399   }
400
401   public static void addJ2SBinaryType(String ext)
402   {
403     /**
404      * @j2sNative
405      * 
406      *            J2S._binaryTypes.push("." + ext + "?");
407      * 
408      */
409   }
410
411   /**
412    * Encode the URI using JavaScript encodeURIComponent
413    * 
414    * @param value
415    * @return encoded value
416    */
417   public static String encodeURI(String value)
418   {
419     /**
420      * @j2sNative value = encodeURIComponent(value);
421      */
422     return value;
423   }
424
425   /**
426    * Open the URL using a simple window call if this is JavaScript
427    * 
428    * @param url
429    * @return true if window has been opened
430    */
431   public static boolean openURL(String url) throws IOException
432   {
433     if (!isJS())
434     {
435       BrowserLauncher.openURL(url);
436       return false;
437     }
438     /**
439      * @j2sNative
440      * 
441      * 
442      *            window.open(url);
443      */
444     return true;
445   }
446
447   public static String getUniqueAppletID()
448   {
449     @SuppressWarnings("unused")
450     ThreadGroup g = Thread.currentThread().getThreadGroup();
451     /**
452      * @j2sNative return g.秘html5Applet._uniqueId;
453      *
454      */
455     return null;
456
457   }
458
459   /**
460    * Read the Info block for this applet.
461    * 
462    * @param prefix
463    *          "jalview_"
464    * @param p
465    * @return unique id for this applet
466    */
467   public static void readInfoProperties(String prefix, Properties p)
468   {
469     if (!isJS())
470     {
471       return;
472     }
473     @SuppressWarnings("unused")
474     ThreadGroup g = Thread.currentThread().getThreadGroup();
475     String id = getUniqueAppletID();
476     String key = "", value = "";
477     /**
478      * @j2sNative var info = g.秘html5Applet.__Info || {}; for (var key in info)
479      *            { if (key.indexOf(prefix) == 0) { value = "" + info[key];
480      */
481
482     System.out.println(
483             "Platform id=" + id + " reading Info." + key + " = " + value);
484     p.put(key, value);
485
486     /**
487      * @j2sNative
488      * 
489      * 
490      *            } }
491      */
492   }
493
494   public static void setAjaxJSON(URL url)
495   {
496     if (isJS())
497     {
498       JSON.setAjax(url);
499     }
500   }
501
502   public static Object parseJSON(InputStream response)
503           throws IOException, ParseException
504   {
505     if (isJS())
506     {
507       return JSON.parse(response);
508     }
509
510     BufferedReader br = null;
511     try
512     {
513       br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
514       return new JSONParser().parse(br);
515     } finally
516     {
517       if (br != null)
518       {
519         try
520         {
521           br.close();
522         } catch (IOException e)
523         {
524           // ignore
525         }
526       }
527     }
528   }
529
530   public static Object parseJSON(String json) throws ParseException
531   {
532     return (isJS() ? JSON.parse(json)
533             : new JSONParser().parse(json));
534   }
535
536   public static Object parseJSON(Reader r)
537           throws IOException, ParseException
538   {
539     if (r == null)
540     {
541       return null;
542     }
543
544     if (!isJS())
545     {
546       return new JSONParser().parse(r);
547     }
548     // Using a file reader is not currently supported in SwingJS JavaScript
549
550     if (r instanceof FileReader)
551     {
552       throw new IOException(
553               "StringJS does not support FileReader parsing for JSON -- but it could...");
554     }
555     return JSON.parse(r);
556
557   }
558
559   /**
560    * Dump the input stream to an output file.
561    * 
562    * @param is
563    * @param outFile
564    * @throws IOException
565    *           if the file cannot be created or there is a problem reading the
566    *           input stream.
567    */
568   public static void streamToFile(InputStream is, File outFile)
569           throws IOException
570   {
571     FileOutputStream fio = new FileOutputStream(outFile);
572     try
573     {
574       if (isJS()
575               && /**
576                   * @j2sNative outFile.setBytes$O && outFile.setBytes$O(is) &&
577                   */
578               true)
579       {
580         return;
581       }
582       byte[] bb = new byte[32 * 1024];
583       int l;
584       while ((l = is.read(bb)) > 0)
585       {
586         fio.write(bb, 0, l);
587       }
588     } finally
589     {
590       fio.close();
591     }
592   }
593
594   /**
595    * Add a known domain that implements access-control-allow-origin:*
596    * 
597    * These should be reviewed periodically.
598    * 
599    * @param domain
600    *          for a service that is not allowing ajax
601    * 
602    * @author hansonr@stolaf.edu
603    * 
604    */
605   public static void addJ2SDirectDatabaseCall(String domain)
606   {
607
608     if (isJS())
609     {
610       System.out.println(
611             "Platform adding known access-control-allow-origin * for domain "
612                     + domain);
613       /**
614        * @j2sNative
615        * 
616        *            J2S.addDirectDatabaseCall(domain);
617        */
618     }
619
620   }
621
622   public static void getURLCommandArguments()
623   {
624
625     /**
626      * Retrieve the first query field as command arguments to Jalview. Include
627      * only if prior to "?j2s" or "&j2s" or "#". Assign the applet's __Info.args
628      * element to this value.
629      * 
630      * @j2sNative var a =
631      *            decodeURI((document.location.href.replace("&","?").split("?j2s")[0]
632      *            + "?").split("?")[1].split("#")[0]); a &&
633      *            (J2S.thisApplet.__Info.args = a.split(" "));
634      */
635
636   }
637
638   public static URL getDocumentBase()
639   {
640     try
641     {
642       if (isJS())
643       {
644         @SuppressWarnings("unused")
645         Object g = Thread.currentThread().getThreadGroup();
646         return new URL(/**
647                         * @j2sNative g.秘html5Applet._appletPanel.appletDocumentBase
648                         *            ||
649                         */
650                 "");
651       }
652     } catch (MalformedURLException e)
653     {
654     }
655     return null;
656   }
657
658   public static URL getCodeBase()
659   {
660     try
661     {
662       if (isJS())
663       {
664         @SuppressWarnings("unused")
665         Object g = Thread.currentThread().getThreadGroup();
666         return new URL(/**
667                         * @j2sNative g.秘html5Applet._appletPanel.appletCodeBase
668                         *            ||
669                         */
670                 "");
671       }
672     } catch (MalformedURLException e)
673     {
674     }
675     return null;
676   }
677
678   /**
679    * load a resource -- probably a core file -- if and only if a particular
680    * class has not been instantialized. We use a String here because if we used
681    * a .class object, that reference itself would simply load the class, and we
682    * want the core package to include that as well.
683    * 
684    * @param resourcePath
685    * @param className
686    */
687   public static void loadStaticResource(Object resourcePath,
688           String className)
689   {
690     /**
691      * 
692      * @j2sNative if (!swingjs.JSUtil.isClassLoaded$S(className))
693      *            swingjs.JSUtil.loadStaticResource$S(resourcePath);
694      */
695   }
696
697   public static void ensureRegex()
698   {
699     loadStaticResource("core/core_stevesoft.z.js",
700             "com.stevesoft.pat.Regex");
701   }
702
703   public static Regex newRegex(String searchString, String replaceString)
704   {
705     ensureRegex();
706     return (replaceString == null ? new Regex(searchString)
707             : new Regex(searchString, replaceString));
708   }
709
710   public static Regex newRegexPerl(String code)
711   {
712     ensureRegex();
713     return Regex.perlCode(code);
714   }
715
716   /**
717    * @param c
718    */
719   public static Color getColorFromName(String name)
720   {
721     if (name == null)
722     {
723       return null;
724     }
725     /**
726      * @j2sNative
727      * 
728      *            return swingjs.JSUtil.getColorFromName$S(name);
729      */
730     {
731       // or make a static map; or use reflection on the field name
732       switch (name.toLowerCase())
733       {
734       case "black":
735         return Color.black;
736       case "blue":
737         return Color.blue;
738       case "cyan":
739         return Color.cyan;
740       case "darkgray":
741         return Color.darkGray;
742       case "gray":
743         return Color.gray;
744       case "green":
745         return Color.green;
746       case "lightgray":
747         return Color.lightGray;
748       case "magenta":
749         return Color.magenta;
750       case "orange":
751         return Color.orange;
752       case "pink":
753         return Color.pink;
754       case "red":
755         return Color.red;
756       case "white":
757         return Color.white;
758       case "yellow":
759         return Color.yellow;
760       default:
761         return null;
762       }
763
764     }
765   }
766
767   /**
768    * Initialize Java debug logging. A representative sample -- adapt as desired.
769    */
770   public static void startJavaLogging()
771   {
772     /**
773      * @j2sIgnore
774      */
775     {
776       logClass("java.awt.EventDispatchThread", "java.awt.EventQueue",
777               "java.awt.Component", "java.awt.focus.Component",
778               "java.awt.event.Component",
779               "java.awt.focus.DefaultKeyboardFocusManager");
780     }
781   }
782
783   /**
784    * Initiate Java logging for a given class. Only for Java, not JavaScript;
785    * Allows debugging of complex event processing.
786    * 
787    * @param className
788    */
789   public static void logClass(String... classNames)
790   {
791     /**
792      * @j2sIgnore
793      * 
794      * 
795      */
796     {
797       Logger rootLogger = Logger.getLogger("");
798       rootLogger.setLevel(Level.ALL);
799       ConsoleHandler consoleHandler = new ConsoleHandler();
800       consoleHandler.setLevel(Level.ALL);
801       for (int i = classNames.length; --i >= 0;)
802       {
803         Logger logger = Logger.getLogger(classNames[i]);
804         logger.setLevel(Level.ALL);
805         logger.addHandler(consoleHandler);
806       }
807     }
808   }
809
810   /**
811    * Set the "app" property of the HTML5 applet object, for example,
812    * "testApplet.app", to point to the Jalview instance. This will be the object
813    * that page developers use that is similar to the original Java applet object
814    * that was accessed via LiveConnect.
815    * 
816    * @param j
817    */
818   public static void setAppClass(Object j)
819   {
820     if (!isJS())
821     {
822       return;
823     }
824     @SuppressWarnings("unused")
825     Thread t = Thread.currentThread();
826     /**
827      * Set up "testApplet.app" to be this instance
828      * 
829      * @j2sNative
830      * 
831      *            try {self[t.name].app = j}catch(e){}
832      */
833   }
834
835 }