Java2Script 3.2.2 upgrade
[jalview.git] / src / jalview / gui / Desktop.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.gui;
22
23 import static jalview.util.UrlConstants.SEQUENCE_ID;
24
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.gui.ImageExporter.ImageWriterI;
30 import jalview.io.DataSourceType;
31 import jalview.io.FileFormat;
32 import jalview.io.FileFormatException;
33 import jalview.io.FileFormatI;
34 import jalview.io.FileFormats;
35 import jalview.io.FileLoader;
36 import jalview.io.FormatAdapter;
37 import jalview.io.IdentifyFile;
38 import jalview.io.JalviewFileChooser;
39 import jalview.io.JalviewFileView;
40 import jalview.jbgui.GSplitFrame;
41 import jalview.jbgui.GStructureViewer;
42 import jalview.structure.StructureSelectionManager;
43 import jalview.urls.IdOrgSettings;
44 import jalview.util.BrowserLauncher;
45 import jalview.util.ImageMaker.TYPE;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
48 import jalview.util.UrlConstants;
49 import jalview.util.dialogrunner.RunResponse;
50 import jalview.viewmodel.AlignmentViewport;
51 import jalview.ws.params.ParamManager;
52 import jalview.ws.utils.UrlDownloadClient;
53
54 import java.awt.BorderLayout;
55 import java.awt.Color;
56 import java.awt.Dimension;
57 import java.awt.FontMetrics;
58 import java.awt.Graphics;
59 import java.awt.GridLayout;
60 import java.awt.Point;
61 import java.awt.Rectangle;
62 import java.awt.Toolkit;
63 import java.awt.Window;
64 import java.awt.datatransfer.Clipboard;
65 import java.awt.datatransfer.ClipboardOwner;
66 import java.awt.datatransfer.DataFlavor;
67 import java.awt.datatransfer.Transferable;
68 import java.awt.dnd.DnDConstants;
69 import java.awt.dnd.DropTargetDragEvent;
70 import java.awt.dnd.DropTargetDropEvent;
71 import java.awt.dnd.DropTargetEvent;
72 import java.awt.dnd.DropTargetListener;
73 import java.awt.event.ActionEvent;
74 import java.awt.event.ActionListener;
75 import java.awt.event.InputEvent;
76 import java.awt.event.KeyEvent;
77 import java.awt.event.MouseAdapter;
78 import java.awt.event.MouseEvent;
79 import java.awt.event.WindowAdapter;
80 import java.awt.event.WindowEvent;
81 import java.beans.PropertyChangeEvent;
82 import java.beans.PropertyChangeListener;
83 import java.io.BufferedInputStream;
84 import java.io.File;
85 import java.io.FileOutputStream;
86 import java.io.IOException;
87 import java.net.URL;
88 import java.util.ArrayList;
89 import java.util.Hashtable;
90 import java.util.List;
91 import java.util.ListIterator;
92 import java.util.StringTokenizer;
93 import java.util.Vector;
94 import java.util.concurrent.ExecutorService;
95 import java.util.concurrent.Executors;
96 import java.util.concurrent.Semaphore;
97
98 import javax.swing.AbstractAction;
99 import javax.swing.Action;
100 import javax.swing.ActionMap;
101 import javax.swing.Box;
102 import javax.swing.BoxLayout;
103 import javax.swing.DefaultDesktopManager;
104 import javax.swing.DesktopManager;
105 import javax.swing.InputMap;
106 import javax.swing.JButton;
107 import javax.swing.JCheckBox;
108 import javax.swing.JComboBox;
109 import javax.swing.JComponent;
110 import javax.swing.JDesktopPane;
111 import javax.swing.JFrame;
112 import javax.swing.JInternalFrame;
113 import javax.swing.JLabel;
114 import javax.swing.JMenuItem;
115 import javax.swing.JPanel;
116 import javax.swing.JPopupMenu;
117 import javax.swing.JProgressBar;
118 import javax.swing.KeyStroke;
119 import javax.swing.SwingUtilities;
120 import javax.swing.event.HyperlinkEvent;
121 import javax.swing.event.HyperlinkEvent.EventType;
122 import javax.swing.event.InternalFrameAdapter;
123 import javax.swing.event.InternalFrameEvent;
124 import javax.swing.event.MenuEvent;
125 import javax.swing.event.MenuListener;
126
127 import org.stackoverflowusers.file.WindowsShortcut;
128
129 /**
130  * Jalview Desktop
131  * 
132  * 
133  * @author $author$
134  * @version $Revision: 1.155 $
135  */
136 public class Desktop extends jalview.jbgui.GDesktop
137         implements DropTargetListener, ClipboardOwner, IProgressIndicator,
138         jalview.api.StructureSelectionManagerProvider
139 {
140   private static int DEFAULT_MIN_WIDTH = 300;
141
142   private static int DEFAULT_MIN_HEIGHT = 250;
143
144   private static int ALIGN_FRAME_DEFAULT_MIN_WIDTH = 600;
145
146   private static int ALIGN_FRAME_DEFAULT_MIN_HEIGHT = 70;
147
148   private static final String EXPERIMENTAL_FEATURES = "EXPERIMENTAL_FEATURES";
149
150   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
151
152   /**
153    * news reader - null if it was never started.
154    */
155   private BlogReader jvnews = null;
156
157   private File projectFile;
158
159   /**
160    * @param listener
161    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
162    */
163   public void addJalviewPropertyChangeListener(
164           PropertyChangeListener listener)
165   {
166     changeSupport.addJalviewPropertyChangeListener(listener);
167   }
168
169   /**
170    * @param propertyName
171    * @param listener
172    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
173    *      java.beans.PropertyChangeListener)
174    */
175   public void addJalviewPropertyChangeListener(String propertyName,
176           PropertyChangeListener listener)
177   {
178     changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
179   }
180
181   /**
182    * @param propertyName
183    * @param listener
184    * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
185    *      java.beans.PropertyChangeListener)
186    */
187   public void removeJalviewPropertyChangeListener(String propertyName,
188           PropertyChangeListener listener)
189   {
190     changeSupport.removeJalviewPropertyChangeListener(propertyName,
191             listener);
192   }
193
194   /** Singleton Desktop instance */
195   public static Desktop instance;
196
197   public static MyDesktopPane desktop;
198
199   public static MyDesktopPane getDesktop()
200   {
201     // BH 2018 could use currentThread() here as a reference to a
202     // Hashtable<Thread, MyDesktopPane> in JavaScript
203     return desktop;
204   }
205
206   static int openFrameCount = 0;
207
208   static final int xOffset = 30;
209
210   static final int yOffset = 30;
211
212   public static jalview.ws.jws1.Discoverer discoverer;
213
214   public static Object[] jalviewClipboard;
215
216   public static boolean internalCopy = false;
217
218   static int fileLoadingCount = 0;
219
220   class MyDesktopManager implements DesktopManager
221   {
222
223     private DesktopManager delegate;
224
225     public MyDesktopManager(DesktopManager delegate)
226     {
227       this.delegate = delegate;
228     }
229
230     @Override
231     public void activateFrame(JInternalFrame f)
232     {
233       try
234       {
235         delegate.activateFrame(f);
236       } catch (NullPointerException npe)
237       {
238         Point p = getMousePosition();
239         instance.showPasteMenu(p.x, p.y);
240       }
241     }
242
243     @Override
244     public void beginDraggingFrame(JComponent f)
245     {
246       delegate.beginDraggingFrame(f);
247     }
248
249     @Override
250     public void beginResizingFrame(JComponent f, int direction)
251     {
252       delegate.beginResizingFrame(f, direction);
253     }
254
255     @Override
256     public void closeFrame(JInternalFrame f)
257     {
258       delegate.closeFrame(f);
259     }
260
261     @Override
262     public void deactivateFrame(JInternalFrame f)
263     {
264       delegate.deactivateFrame(f);
265     }
266
267     @Override
268     public void deiconifyFrame(JInternalFrame f)
269     {
270       delegate.deiconifyFrame(f);
271     }
272
273     @Override
274     public void dragFrame(JComponent f, int newX, int newY)
275     {
276       if (newY < 0)
277       {
278         newY = 0;
279       }
280       delegate.dragFrame(f, newX, newY);
281     }
282
283     @Override
284     public void endDraggingFrame(JComponent f)
285     {
286       delegate.endDraggingFrame(f);
287       desktop.repaint();
288     }
289
290     @Override
291     public void endResizingFrame(JComponent f)
292     {
293       delegate.endResizingFrame(f);
294       desktop.repaint();
295     }
296
297     @Override
298     public void iconifyFrame(JInternalFrame f)
299     {
300       delegate.iconifyFrame(f);
301     }
302
303     @Override
304     public void maximizeFrame(JInternalFrame f)
305     {
306       delegate.maximizeFrame(f);
307     }
308
309     @Override
310     public void minimizeFrame(JInternalFrame f)
311     {
312       delegate.minimizeFrame(f);
313     }
314
315     @Override
316     public void openFrame(JInternalFrame f)
317     {
318       delegate.openFrame(f);
319     }
320
321     @Override
322     public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
323             int newHeight)
324     {
325       if (newY < 0)
326       {
327         newY = 0;
328       }
329       delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
330     }
331
332     @Override
333     public void setBoundsForFrame(JComponent f, int newX, int newY,
334             int newWidth, int newHeight)
335     {
336       delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
337     }
338
339     // All other methods, simply delegate
340
341   }
342
343   /**
344    * Creates a new Desktop object.
345    */
346   public Desktop()
347   {
348     /**
349      * A note to implementors. It is ESSENTIAL that any activities that might block
350      * are spawned off as threads rather than waited for during this constructor.
351      */
352     instance = this;
353     if (!Jalview.isJS())
354     {
355       doVamsasClientCheck();
356     }
357
358     doConfigureStructurePrefs();
359     setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
360     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
361     boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
362             false);
363     boolean showjconsole = jalview.bin.Cache.getDefault("SHOW_JAVA_CONSOLE",
364             false);
365     desktop = new MyDesktopPane(selmemusage);
366     showMemusage.setSelected(selmemusage);
367     desktop.setBackground(Color.white);
368     getContentPane().setLayout(new BorderLayout());
369     // alternate config - have scrollbars - see notes in JAL-153
370     // JScrollPane sp = new JScrollPane();
371     // sp.getViewport().setView(desktop);
372     // getContentPane().add(sp, BorderLayout.CENTER);
373     getContentPane().add(desktop, BorderLayout.CENTER);
374     desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
375
376     // This line prevents Windows Look&Feel resizing all new windows to maximum
377     // if previous window was maximised
378     desktop.setDesktopManager(new MyDesktopManager(
379             (Platform.isWindows() ? new DefaultDesktopManager()
380                     : Platform.isAMac()
381                             ? new AquaInternalFrameManager(
382                                     desktop.getDesktopManager())
383                             : desktop.getDesktopManager())));
384
385     Rectangle dims = getLastKnownDimensions("");
386     if (dims != null)
387     {
388       setBounds(dims);
389     }
390     else
391     {
392       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
393       int xPos = Math.max(5, (screenSize.width - 900) / 2);
394       int yPos = Math.max(5, (screenSize.height - 650) / 2);
395       setBounds(xPos, yPos, 900, 650);
396     }
397     
398     boolean doFullLoad = /** @j2sNative ! */true;
399     
400     if (doFullLoad) {
401       
402       jconsole = new Console(this, showjconsole);
403       // add essential build information
404       jconsole.setHeader("Jalview Version: "
405               + jalview.bin.Cache.getProperty("VERSION") + "\n"
406               + "Jalview Installation: "
407               + jalview.bin.Cache.getDefault("INSTALLATION", "unknown")
408               + "\n" + "Build Date: "
409               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
410               + "Java version: " + System.getProperty("java.version") + "\n"
411               + System.getProperty("os.arch") + " "
412               + System.getProperty("os.name") + " "
413               + System.getProperty("os.version"));
414
415       showConsole(showjconsole);
416
417       showNews.setVisible(false);
418
419       experimentalFeatures.setSelected(showExperimental());
420
421       getIdentifiersOrgData();
422
423       checkURLLinks();
424
425       // Spawn a thread that shows the splashscreen
426
427       SwingUtilities.invokeLater(new Runnable()
428       {
429         @Override
430         public void run()
431         {
432           new SplashScreen();
433         }
434       });
435
436       // Thread off a new instance of the file chooser - this reduces the time it
437       // takes to open it later on.
438       new Thread(new Runnable()
439       {
440         @Override
441         public void run()
442         {
443           Cache.log.debug("Filechooser init thread started.");
444           String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
445           JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
446                   fileFormat);
447           Cache.log.debug("Filechooser init thread finished.");
448         }
449       }).start();
450       // Add the service change listener
451       changeSupport.addJalviewPropertyChangeListener("services",
452               new PropertyChangeListener()
453               {
454
455                 @Override
456                 public void propertyChange(PropertyChangeEvent evt)
457                 {
458                   Cache.log.debug("Firing service changed event for "
459                           + evt.getNewValue());
460                   JalviewServicesChanged(evt);
461                 }
462
463               });
464
465     } 
466
467     this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
468
469     this.addWindowListener(new WindowAdapter()
470     {
471       @Override
472       public void windowClosing(WindowEvent evt)
473       {
474         quit();
475       }
476     });
477
478     MouseAdapter ma;
479     this.addMouseListener(ma = new MouseAdapter()
480     {
481       @Override
482       public void mousePressed(MouseEvent evt)
483       {
484         if (evt.isPopupTrigger()) // Mac
485         {
486           showPasteMenu(evt.getX(), evt.getY());
487         }
488       }
489
490       @Override
491       public void mouseReleased(MouseEvent evt)
492       {
493         if (evt.isPopupTrigger()) // Windows
494         {
495           showPasteMenu(evt.getX(), evt.getY());
496         }
497       }
498     });
499     desktop.addMouseListener(ma);
500
501   }
502
503   /**
504    * Answers true if user preferences to enable experimental features is True
505    * (on), else false
506    * 
507    * @return
508    */
509   public boolean showExperimental()
510   {
511     String experimental = Cache.getDefault(EXPERIMENTAL_FEATURES,
512             Boolean.FALSE.toString());
513     return Boolean.valueOf(experimental).booleanValue();
514   }
515
516   public void doConfigureStructurePrefs()
517   {
518     // configure services
519     StructureSelectionManager ssm = StructureSelectionManager
520             .getStructureSelectionManager(this);
521     if (jalview.bin.Cache.getDefault(Preferences.ADD_SS_ANN, true))
522     {
523       ssm.setAddTempFacAnnot(jalview.bin.Cache
524               .getDefault(Preferences.ADD_TEMPFACT_ANN, true));
525       ssm.setProcessSecondaryStructure(jalview.bin.Cache
526               .getDefault(Preferences.STRUCT_FROM_PDB, true));
527       ssm.setSecStructServices(
528               jalview.bin.Cache.getDefault(Preferences.USE_RNAVIEW, true));
529     }
530     else
531     {
532       ssm.setAddTempFacAnnot(false);
533       ssm.setProcessSecondaryStructure(false);
534       ssm.setSecStructServices(false);
535     }
536   }
537
538   public void checkForNews()
539   {
540     final Desktop me = this;
541     // Thread off the news reader, in case there are connection problems.
542     addDialogThread(new Runnable()
543     {
544       @Override
545       public void run()
546       {
547         Cache.log.debug("Starting news thread.");
548         jvnews = new BlogReader(me);
549         showNews.setVisible(true);
550         Cache.log.debug("Completed news thread.");
551       }
552     });
553   }
554
555   public void getIdentifiersOrgData()
556   {
557     // Thread off the identifiers fetcher
558     addDialogThread(new Runnable()
559     {
560       @Override
561       public void run()
562       {
563         Cache.log.debug("Downloading data from identifiers.org");
564         UrlDownloadClient client = new UrlDownloadClient();
565         try
566         {
567           client.download(IdOrgSettings.getUrl(),
568                   IdOrgSettings.getDownloadLocation());
569         } catch (IOException e)
570         {
571           Cache.log.debug("Exception downloading identifiers.org data"
572                   + e.getMessage());
573         }
574       }
575     });
576   }
577
578   @Override
579   protected void showNews_actionPerformed(ActionEvent e)
580   {
581     showNews(showNews.isSelected());
582   }
583
584   void showNews(boolean visible)
585   {
586     Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
587     showNews.setSelected(visible);
588     if (visible && !jvnews.isVisible())
589     {
590       new Thread(new Runnable()
591       {
592         @Override
593         public void run()
594         {
595           long now = System.currentTimeMillis();
596           Desktop.instance.setProgressBar(
597                   MessageManager.getString("status.refreshing_news"), now);
598           jvnews.refreshNews();
599           Desktop.instance.setProgressBar(null, now);
600           jvnews.showNews();
601         }
602       }).start();
603     }
604   }
605
606   /**
607    * recover the last known dimensions for a jalview window
608    * 
609    * @param windowName
610    *          - empty string is desktop, all other windows have unique prefix
611    * @return null or last known dimensions scaled to current geometry (if last
612    *         window geom was known)
613    */
614   Rectangle getLastKnownDimensions(String windowName)
615   {
616     // TODO: lock aspect ratio for scaling desktop Bug #0058199
617     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
618     String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
619     String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
620     String width = jalview.bin.Cache
621             .getProperty(windowName + "SCREEN_WIDTH");
622     String height = jalview.bin.Cache
623             .getProperty(windowName + "SCREEN_HEIGHT");
624     if ((x != null) && (y != null) && (width != null) && (height != null))
625     {
626       int ix = Integer.parseInt(x), iy = Integer.parseInt(y),
627               iw = Integer.parseInt(width), ih = Integer.parseInt(height);
628       if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
629       {
630         // attempt #1 - try to cope with change in screen geometry - this
631         // version doesn't preserve original jv aspect ratio.
632         // take ratio of current screen size vs original screen size.
633         double sw = ((1f * screenSize.width) / (1f * Integer.parseInt(
634                 jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
635         double sh = ((1f * screenSize.height) / (1f * Integer.parseInt(
636                 jalview.bin.Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
637         // rescale the bounds depending upon the current screen geometry.
638         ix = (int) (ix * sw);
639         iw = (int) (iw * sw);
640         iy = (int) (iy * sh);
641         ih = (int) (ih * sh);
642         while (ix >= screenSize.width)
643         {
644           jalview.bin.Cache.log.debug(
645                   "Window geometry location recall error: shifting horizontal to within screenbounds.");
646           ix -= screenSize.width;
647         }
648         while (iy >= screenSize.height)
649         {
650           jalview.bin.Cache.log.debug(
651                   "Window geometry location recall error: shifting vertical to within screenbounds.");
652           iy -= screenSize.height;
653         }
654         jalview.bin.Cache.log.debug(
655                 "Got last known dimensions for " + windowName + ": x:" + ix
656                         + " y:" + iy + " width:" + iw + " height:" + ih);
657       }
658       // return dimensions for new instance
659       return new Rectangle(ix, iy, iw, ih);
660     }
661     return null;
662   }
663
664   private void doVamsasClientCheck()
665   {
666     if (Cache.vamsasJarsPresent())
667     {
668       setupVamsasDisconnectedGui();
669       VamsasMenu.setVisible(true);
670       final Desktop us = this;
671       VamsasMenu.addMenuListener(new MenuListener()
672       {
673         // this listener remembers when the menu was first selected, and
674         // doesn't rebuild the session list until it has been cleared and
675         // reselected again.
676         boolean refresh = true;
677
678         @Override
679         public void menuCanceled(MenuEvent e)
680         {
681           refresh = true;
682         }
683
684         @Override
685         public void menuDeselected(MenuEvent e)
686         {
687           refresh = true;
688         }
689
690         @Override
691         public void menuSelected(MenuEvent e)
692         {
693           if (refresh)
694           {
695             us.buildVamsasStMenu();
696             refresh = false;
697           }
698         }
699       });
700       vamsasStart.setVisible(true);
701     }
702   }
703
704   void showPasteMenu(int x, int y)
705   {
706     JPopupMenu popup = new JPopupMenu();
707     JMenuItem item = new JMenuItem(
708             MessageManager.getString("label.paste_new_window"));
709     item.addActionListener(new ActionListener()
710     {
711       @Override
712       public void actionPerformed(ActionEvent evt)
713       {
714         paste();
715       }
716     });
717
718     popup.add(item);
719     popup.show(this, x, y);
720   }
721
722   public void paste()
723   {
724     try
725     {
726       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
727       Transferable contents = c.getContents(this);
728
729       if (contents != null)
730       {
731         String file = (String) contents
732                 .getTransferData(DataFlavor.stringFlavor);
733
734         FileFormatI format = new IdentifyFile().identify(file,
735                 DataSourceType.PASTE);
736
737         new FileLoader().LoadFile(file, DataSourceType.PASTE, format);
738
739       }
740     } catch (Exception ex)
741     {
742       System.out.println(
743               "Unable to paste alignment from system clipboard:\n" + ex);
744     }
745   }
746
747   /**
748    * Adds and opens the given frame to the desktop
749    * 
750    * @param frame
751    *          Frame to show
752    * @param title
753    *          Visible Title
754    * @param w
755    *          width
756    * @param h
757    *          height
758    */
759   public static synchronized void addInternalFrame(
760           final JInternalFrame frame, String title, int w, int h)
761   {
762     addInternalFrame(frame, title, true, w, h, true, false);
763   }
764
765   /**
766    * Add an internal frame to the Jalview desktop
767    * 
768    * @param frame
769    *          Frame to show
770    * @param title
771    *          Visible Title
772    * @param makeVisible
773    *          When true, display frame immediately, otherwise, caller must call
774    *          setVisible themselves.
775    * @param w
776    *          width
777    * @param h
778    *          height
779    */
780   public static synchronized void addInternalFrame(
781           final JInternalFrame frame, String title, boolean makeVisible,
782           int w, int h)
783   {
784     addInternalFrame(frame, title, makeVisible, w, h, true, false);
785   }
786
787   /**
788    * Add an internal frame to the Jalview desktop and make it visible
789    * 
790    * @param frame
791    *          Frame to show
792    * @param title
793    *          Visible Title
794    * @param w
795    *          width
796    * @param h
797    *          height
798    * @param resizable
799    *          Allow resize
800    */
801   public static synchronized void addInternalFrame(
802           final JInternalFrame frame, String title, int w, int h,
803           boolean resizable)
804   {
805     addInternalFrame(frame, title, true, w, h, resizable, false);
806   }
807
808   /**
809    * Add an internal frame to the Jalview desktop
810    * 
811    * @param frame
812    *          Frame to show
813    * @param title
814    *          Visible Title
815    * @param makeVisible
816    *          When true, display frame immediately, otherwise, caller must call
817    *          setVisible themselves.
818    * @param w
819    *          width
820    * @param h
821    *          height
822    * @param resizable
823    *          Allow resize
824    * @param ignoreMinSize
825    *          Do not set the default minimum size for frame
826    */
827   public static synchronized void addInternalFrame(
828           final JInternalFrame frame, String title, boolean makeVisible,
829           int w, int h, boolean resizable, boolean ignoreMinSize)
830   {
831
832     // TODO: allow callers to determine X and Y position of frame (eg. via
833     // bounds object).
834     // TODO: consider fixing method to update entries in the window submenu with
835     // the current window title
836
837     frame.setTitle(title);
838     if (frame.getWidth() < 1 || frame.getHeight() < 1)
839     {
840       frame.setSize(w, h);
841     }
842     // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
843     // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
844     // IF JALVIEW IS RUNNING HEADLESS
845     // ///////////////////////////////////////////////
846     if (instance == null || (System.getProperty("java.awt.headless") != null
847             && System.getProperty("java.awt.headless").equals("true")))
848     {
849       return;
850     }
851
852     openFrameCount++;
853
854     if (!ignoreMinSize)
855     {
856       frame.setMinimumSize(
857               new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
858
859       // Set default dimension for Alignment Frame window.
860       // The Alignment Frame window could be added from a number of places,
861       // hence,
862       // I did this here in order not to miss out on any Alignment frame.
863       if (frame instanceof AlignFrame)
864       {
865         frame.setMinimumSize(new Dimension(ALIGN_FRAME_DEFAULT_MIN_WIDTH,
866                 ALIGN_FRAME_DEFAULT_MIN_HEIGHT));
867       }
868     }
869
870     frame.setVisible(makeVisible);
871     frame.setClosable(true);
872     frame.setResizable(resizable);
873     frame.setMaximizable(resizable);
874     frame.setIconifiable(resizable);
875     frame.setOpaque(/** @j2sNative true || */
876             false);
877
878     if (frame.getX() < 1 && frame.getY() < 1)
879     {
880       frame.setLocation(xOffset * openFrameCount,
881               yOffset * ((openFrameCount - 1) % 10) + yOffset);
882     }
883
884     /*
885      * add an entry for the new frame in the Window menu 
886      * (and remove it when the frame is closed)
887      */
888     final JMenuItem menuItem = new JMenuItem(title);
889     frame.addInternalFrameListener(new InternalFrameAdapter()
890     {
891       @Override
892       public void internalFrameActivated(InternalFrameEvent evt)
893       {
894         JInternalFrame itf = desktop.getSelectedFrame();
895         if (itf != null)
896         {
897           if (itf instanceof AlignFrame)
898           {
899             Jalview.setCurrentAlignFrame((AlignFrame) itf);
900           }
901           itf.requestFocus();
902         }
903       }
904
905       @Override
906       public void internalFrameClosed(InternalFrameEvent evt)
907       {
908         PaintRefresher.RemoveComponent(frame);
909
910         /*
911          * defensive check to prevent frames being
912          * added half off the window
913          */
914         if (openFrameCount > 0)
915         {
916           openFrameCount--;
917         }
918
919         /*
920          * ensure no reference to alignFrame retained by menu item listener
921          */
922         if (menuItem.getActionListeners().length > 0)
923         {
924           menuItem.removeActionListener(menuItem.getActionListeners()[0]);
925         }
926         windowMenu.remove(menuItem);
927       };
928     });
929
930     menuItem.addActionListener(new ActionListener()
931     {
932       @Override
933       public void actionPerformed(ActionEvent e)
934       {
935         try
936         {
937           frame.setSelected(true);
938           frame.setIcon(false);
939         } catch (java.beans.PropertyVetoException ex)
940         {
941           // System.err.println(ex.toString());
942         }
943       }
944     });
945
946     setKeyBindings(frame);
947
948     desktop.add(frame);
949
950     windowMenu.add(menuItem);
951
952     frame.toFront();
953     try
954     {
955       frame.setSelected(true);
956       frame.requestFocus();
957     } catch (java.beans.PropertyVetoException ve)
958     {
959     } catch (java.lang.ClassCastException cex)
960     {
961       Cache.log.warn(
962               "Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
963               cex);
964     }
965   }
966
967   /**
968    * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close the
969    * window
970    * 
971    * @param frame
972    */
973   private static void setKeyBindings(JInternalFrame frame)
974   {
975     @SuppressWarnings("serial")
976     final Action closeAction = new AbstractAction()
977     {
978       @Override
979       public void actionPerformed(ActionEvent e)
980       {
981         frame.dispose();
982       }
983     };
984
985     /*
986      * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
987      */
988     KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
989             InputEvent.CTRL_DOWN_MASK);
990     KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
991             Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
992
993     InputMap inputMap = frame
994             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
995     String ctrlW = ctrlWKey.toString();
996     inputMap.put(ctrlWKey, ctrlW);
997     inputMap.put(cmdWKey, ctrlW);
998
999     ActionMap actionMap = frame.getActionMap();
1000     actionMap.put(ctrlW, closeAction);
1001   }
1002
1003   @Override
1004   public void lostOwnership(Clipboard clipboard, Transferable contents)
1005   {
1006     if (!internalCopy)
1007     {
1008       Desktop.jalviewClipboard = null;
1009     }
1010
1011     internalCopy = false;
1012   }
1013
1014   @Override
1015   public void dragEnter(DropTargetDragEvent evt)
1016   {
1017   }
1018
1019   @Override
1020   public void dragExit(DropTargetEvent evt)
1021   {
1022   }
1023
1024   @Override
1025   public void dragOver(DropTargetDragEvent evt)
1026   {
1027   }
1028
1029   @Override
1030   public void dropActionChanged(DropTargetDragEvent evt)
1031   {
1032   }
1033
1034   /**
1035    * DOCUMENT ME!
1036    * 
1037    * @param evt
1038    *          DOCUMENT ME!
1039    */
1040   @Override
1041   public void drop(DropTargetDropEvent evt)
1042   {
1043     boolean success = true;
1044     // JAL-1552 - acceptDrop required before getTransferable call for
1045     // Java's Transferable for native dnd
1046     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
1047     Transferable t = evt.getTransferable();
1048     List<Object> files = new ArrayList<>();
1049     List<DataSourceType> protocols = new ArrayList<>();
1050
1051     try
1052     {
1053       Desktop.transferFromDropTarget(files, protocols, evt, t);
1054     } catch (Exception e)
1055     {
1056       e.printStackTrace();
1057       success = false;
1058     }
1059
1060     if (files != null)
1061     {
1062       try
1063       {
1064         for (int i = 0; i < files.size(); i++)
1065         {
1066           // BH 2018 File or String
1067           Object file = files.get(i);
1068           String fileName = file.toString();
1069           DataSourceType protocol = (protocols == null)
1070                   ? DataSourceType.FILE
1071                   : protocols.get(i);
1072           FileFormatI format = null;
1073
1074           if (fileName.endsWith(".jar"))
1075           {
1076             format = FileFormat.Jalview;
1077
1078           }
1079           else
1080           {
1081             format = new IdentifyFile().identify(file, protocol);
1082           }
1083
1084           new FileLoader().LoadFile(null, file, protocol, format);
1085
1086         }
1087       } catch (Exception ex)
1088       {
1089         success = false;
1090       }
1091     }
1092     evt.dropComplete(success); // need this to ensure input focus is properly
1093                                // transfered to any new windows created
1094   }
1095
1096   /**
1097    * DOCUMENT ME!
1098    * 
1099    * @param e
1100    *          DOCUMENT ME!
1101    */
1102   @Override
1103   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
1104   {
1105     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
1106     JalviewFileChooser chooser = JalviewFileChooser
1107             .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
1108
1109     chooser.setFileView(new JalviewFileView());
1110     chooser.setDialogTitle(
1111             MessageManager.getString("label.open_local_file"));
1112     chooser.setToolTipText(MessageManager.getString("action.open"));
1113
1114     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1115     {
1116
1117       @Override
1118       public void run()
1119       {
1120         File selectedFile = chooser.getSelectedFile();
1121         Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
1122
1123         FileFormatI format = chooser.getSelectedFormat();
1124
1125         /*
1126          * Call IdentifyFile to verify the file contains what its extension implies.
1127          * Skip this step for dynamically added file formats, because
1128          * IdentifyFile does not know how to recognise them.
1129          */
1130         if (FileFormats.getInstance().isIdentifiable(format))
1131         {
1132           try
1133           {
1134             format = new IdentifyFile().identify(selectedFile,
1135                     DataSourceType.FILE);
1136           } catch (FileFormatException e)
1137           {
1138             // format = null; //??
1139           }
1140         }
1141
1142         new FileLoader().LoadFile(viewport, selectedFile,
1143                 DataSourceType.FILE, format);
1144       }
1145     }).openDialog(this);
1146   }
1147
1148   /**
1149    * DOCUMENT ME!
1150    * 
1151    * @param e
1152    *          DOCUMENT ME!
1153    */
1154   @Override
1155   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
1156   {
1157     // This construct allows us to have a wider textfield
1158     // for viewing
1159     JLabel label = new JLabel(
1160             MessageManager.getString("label.input_file_url"));
1161
1162     JComboBox history = new JComboBox();
1163     JPanel panel = new JPanel(new GridLayout(2, 1));
1164     panel.add(label);
1165     panel.add(history);
1166     history.setPreferredSize(new Dimension(400, 20));
1167     history.setEditable(true);
1168     history.addItem("http://www.");
1169
1170     String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
1171
1172     StringTokenizer st;
1173
1174     if (historyItems != null)
1175     {
1176       st = new StringTokenizer(historyItems, "\t");
1177
1178       while (st.hasMoreTokens())
1179       {
1180         history.addItem(st.nextElement());
1181       }
1182     }
1183
1184     // BH 2018 -- providing a callback for SwingJS
1185     // dialogOption is just a simple way to provide
1186     // context for the modal-like response.
1187     // The only requirement is that desktop implement
1188     // PropertyChangeListener, which is used already in Java
1189     // for changes in input value and such within the dialogs.
1190
1191     String dialogOption = "label.input_alignment_from_url";
1192     desktop.dialogData = new Object[] { dialogOption, viewport, history };
1193     desktop.onDialogReturn(JvOptionPane.showInternalConfirmDialog(desktop,
1194             panel, MessageManager.getString(dialogOption),
1195             JvOptionPane.OK_CANCEL_OPTION));
1196
1197     // no code may follow this, as SwingJS will not block
1198     // callback in JavaScript comes via a property change event,
1199     // thus going into desktop.onDialogReturn(int) just the same as
1200     // in Java.
1201
1202   }
1203
1204   /**
1205    * Opens the CutAndPaste window for the user to paste an alignment in to
1206    * 
1207    * @param viewPanel
1208    *          - if not null, the pasted alignment is added to the current
1209    *          alignment; if null, to a new alignment window
1210    */
1211   @Override
1212   public void inputTextboxMenuItem_actionPerformed(
1213           AlignmentViewPanel viewPanel)
1214   {
1215     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1216     cap.setForInput(viewPanel);
1217     Desktop.addInternalFrame(cap,
1218             MessageManager.getString("label.cut_paste_alignmen_file"), true,
1219             600, 500);
1220   }
1221
1222   /*
1223    * Exit the program
1224    */
1225   @Override
1226   public void quit()
1227   {
1228     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1229     jalview.bin.Cache.setProperty("SCREENGEOMETRY_WIDTH",
1230             screen.width + "");
1231     jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT",
1232             screen.height + "");
1233     storeLastKnownDimensions("", new Rectangle(getBounds().x, getBounds().y,
1234             getWidth(), getHeight()));
1235
1236     if (jconsole != null)
1237     {
1238       storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1239       jconsole.stopConsole();
1240     }
1241     if (jvnews != null)
1242     {
1243       storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1244
1245     }
1246     if (dialogExecutor != null)
1247     {
1248       dialogExecutor.shutdownNow();
1249     }
1250     closeAll_actionPerformed(null);
1251
1252     if (groovyConsole != null)
1253     {
1254       // suppress a possible repeat prompt to save script
1255       groovyConsole.setDirty(false);
1256       groovyConsole.exit();
1257     }
1258     System.exit(0);
1259   }
1260
1261   private void storeLastKnownDimensions(String string, Rectangle jc)
1262   {
1263     jalview.bin.Cache.log.debug("Storing last known dimensions for "
1264             + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1265             + " height:" + jc.height);
1266
1267     jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
1268     jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1269     jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1270     jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1271   }
1272
1273   /**
1274    * DOCUMENT ME!
1275    * 
1276    * @param e
1277    *          DOCUMENT ME!
1278    */
1279   @Override
1280   public void aboutMenuItem_actionPerformed(ActionEvent e)
1281   {
1282     // StringBuffer message = getAboutMessage(false);
1283     // JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1284     //
1285     // message.toString(), "About Jalview", JvOptionPane.INFORMATION_MESSAGE);
1286     new Thread(new Runnable()
1287     {
1288       @Override
1289       public void run()
1290       {
1291         new SplashScreen(true);
1292       }
1293     }).start();
1294   }
1295
1296   public StringBuffer getAboutMessage(boolean shortv)
1297   {
1298     StringBuffer message = new StringBuffer();
1299     message.append("<html>");
1300     if (shortv)
1301     {
1302       message.append("<h1><strong>Version: "
1303               + jalview.bin.Cache.getProperty("VERSION")
1304               + "</strong></h1>");
1305       message.append("<strong>Last Updated: <em>"
1306               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
1307               + "</em></strong>");
1308
1309     }
1310     else
1311     {
1312
1313       message.append("<strong>Version "
1314               + jalview.bin.Cache.getProperty("VERSION")
1315               + "; last updated: "
1316               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1317     }
1318
1319     if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1320             .equals("Checking"))
1321     {
1322       message.append("<br>...Checking latest version...</br>");
1323     }
1324     else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1325             .equals(jalview.bin.Cache.getProperty("VERSION")))
1326     {
1327       boolean red = false;
1328       if (jalview.bin.Cache.getProperty("VERSION").toLowerCase()
1329               .indexOf("automated build") == -1)
1330       {
1331         red = true;
1332         // Displayed when code version and jnlp version do not match and code
1333         // version is not a development build
1334         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1335       }
1336
1337       message.append("<br>!! Version "
1338               + jalview.bin.Cache.getDefault("LATEST_VERSION",
1339                       "..Checking..")
1340               + " is available for download from "
1341               + jalview.bin.Cache.getDefault("www.jalview.org",
1342                       "http://www.jalview.org")
1343               + " !!");
1344       if (red)
1345       {
1346         message.append("</div>");
1347       }
1348     }
1349     message.append("<br>Authors:  " + jalview.bin.Cache.getDefault(
1350             "AUTHORFNAMES",
1351             "The Jalview Authors (See AUTHORS file for current list)")
1352             + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
1353             + "<br><br>For help, see the FAQ at <a href=\"http://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list"
1354             + "<br><br>If  you use Jalview, please cite:"
1355             + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1356             + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1357             + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033"
1358             + "</html>");
1359     return message;
1360   }
1361
1362   /**
1363    * Action on requesting Help documentation
1364    */
1365   @Override
1366   public void documentationMenuItem_actionPerformed()
1367   {
1368     try
1369     {
1370       if (Jalview.isJS())
1371       {
1372         BrowserLauncher.openURL("http://www.jalview.org/help.html");
1373       }
1374       else
1375       {
1376         Help.showHelpWindow();
1377       }
1378     } catch (Exception ex)
1379     {
1380       System.err.println("Error opening help: " + ex.getMessage());
1381     }
1382   }
1383
1384   @Override
1385   public void closeAll_actionPerformed(ActionEvent e)
1386   {
1387     // TODO show a progress bar while closing?
1388     JInternalFrame[] frames = desktop.getAllFrames();
1389     for (int i = 0; i < frames.length; i++)
1390     {
1391       try
1392       {
1393         frames[i].setClosed(true);
1394       } catch (java.beans.PropertyVetoException ex)
1395       {
1396       }
1397     }
1398     Jalview.setCurrentAlignFrame(null);
1399     System.out.println("ALL CLOSED");
1400     if (v_client != null)
1401     {
1402       // TODO clear binding to vamsas document objects on close_all
1403     }
1404
1405     /*
1406      * reset state of singleton objects as appropriate (clear down session state
1407      * when all windows are closed)
1408      */
1409     StructureSelectionManager ssm = StructureSelectionManager
1410             .getStructureSelectionManager(this);
1411     if (ssm != null)
1412     {
1413       ssm.resetAll();
1414     }
1415   }
1416
1417   @Override
1418   public void raiseRelated_actionPerformed(ActionEvent e)
1419   {
1420     reorderAssociatedWindows(false, false);
1421   }
1422
1423   @Override
1424   public void minimizeAssociated_actionPerformed(ActionEvent e)
1425   {
1426     reorderAssociatedWindows(true, false);
1427   }
1428
1429   void closeAssociatedWindows()
1430   {
1431     reorderAssociatedWindows(false, true);
1432   }
1433
1434   /*
1435    * (non-Javadoc)
1436    * 
1437    * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1438    * ActionEvent)
1439    */
1440   @Override
1441   protected void garbageCollect_actionPerformed(ActionEvent e)
1442   {
1443     // We simply collect the garbage
1444     jalview.bin.Cache.log.debug("Collecting garbage...");
1445     System.gc();
1446     jalview.bin.Cache.log.debug("Finished garbage collection.");
1447   }
1448
1449   /*
1450    * (non-Javadoc)
1451    * 
1452    * @see
1453    * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1454    * )
1455    */
1456   @Override
1457   protected void showMemusage_actionPerformed(ActionEvent e)
1458   {
1459     desktop.showMemoryUsage(showMemusage.isSelected());
1460   }
1461
1462   /*
1463    * (non-Javadoc)
1464    * 
1465    * @see
1466    * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1467    * )
1468    */
1469   @Override
1470   protected void showConsole_actionPerformed(ActionEvent e)
1471   {
1472     showConsole(showConsole.isSelected());
1473   }
1474
1475   Console jconsole = null;
1476
1477   /**
1478    * control whether the java console is visible or not
1479    * 
1480    * @param selected
1481    */
1482   void showConsole(boolean selected)
1483   {
1484     // TODO: decide if we should update properties file
1485     if (jconsole != null) // BH 2018
1486     {
1487       showConsole.setSelected(selected);
1488       Cache.setProperty("SHOW_JAVA_CONSOLE",
1489               Boolean.valueOf(selected).toString());
1490       jconsole.setVisible(selected);
1491     }
1492   }
1493
1494   void reorderAssociatedWindows(boolean minimize, boolean close)
1495   {
1496     JInternalFrame[] frames = desktop.getAllFrames();
1497     if (frames == null || frames.length < 1)
1498     {
1499       return;
1500     }
1501
1502     AlignmentViewport source = null, target = null;
1503     if (frames[0] instanceof AlignFrame)
1504     {
1505       source = ((AlignFrame) frames[0]).getCurrentView();
1506     }
1507     else if (frames[0] instanceof TreePanel)
1508     {
1509       source = ((TreePanel) frames[0]).getViewPort();
1510     }
1511     else if (frames[0] instanceof PCAPanel)
1512     {
1513       source = ((PCAPanel) frames[0]).av;
1514     }
1515     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1516     {
1517       source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1518     }
1519
1520     if (source != null)
1521     {
1522       for (int i = 0; i < frames.length; i++)
1523       {
1524         target = null;
1525         if (frames[i] == null)
1526         {
1527           continue;
1528         }
1529         if (frames[i] instanceof AlignFrame)
1530         {
1531           target = ((AlignFrame) frames[i]).getCurrentView();
1532         }
1533         else if (frames[i] instanceof TreePanel)
1534         {
1535           target = ((TreePanel) frames[i]).getViewPort();
1536         }
1537         else if (frames[i] instanceof PCAPanel)
1538         {
1539           target = ((PCAPanel) frames[i]).av;
1540         }
1541         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1542         {
1543           target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1544         }
1545
1546         if (source == target)
1547         {
1548           try
1549           {
1550             if (close)
1551             {
1552               frames[i].setClosed(true);
1553             }
1554             else
1555             {
1556               frames[i].setIcon(minimize);
1557               if (!minimize)
1558               {
1559                 frames[i].toFront();
1560               }
1561             }
1562
1563           } catch (java.beans.PropertyVetoException ex)
1564           {
1565           }
1566         }
1567       }
1568     }
1569   }
1570
1571   /**
1572    * DOCUMENT ME!
1573    * 
1574    * @param e
1575    *          DOCUMENT ME!
1576    */
1577   @Override
1578   protected void preferences_actionPerformed(ActionEvent e)
1579   {
1580     new Preferences();
1581   }
1582
1583   /**
1584    * Prompts the user to choose a file and then saves the Jalview state as a
1585    * Jalview project file
1586    */
1587   @Override
1588   public void saveState_actionPerformed()
1589   {
1590     JalviewFileChooser chooser = new JalviewFileChooser("jvp",
1591             "Jalview Project");
1592
1593     chooser.setFileView(new JalviewFileView());
1594     chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1595
1596     int value = chooser.showSaveDialog(this);
1597
1598     if (value == JalviewFileChooser.APPROVE_OPTION)
1599     {
1600       final Desktop me = this;
1601       final java.io.File choice = chooser.getSelectedFile();
1602       setProjectFile(choice);
1603
1604       new Thread(new Runnable()
1605       {
1606         @Override
1607         public void run()
1608         {
1609           // TODO: refactor to Jalview desktop session controller action.
1610           setProgressBar(MessageManager.formatMessage(
1611                   "label.saving_jalview_project", new Object[]
1612                   { choice.getName() }), choice.hashCode());
1613           jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1614                   choice.getParent());
1615           // TODO catch and handle errors for savestate
1616           // TODO prevent user from messing with the Desktop whilst we're saving
1617           try
1618           {
1619             new Jalview2XML().saveState(choice);
1620           } catch (OutOfMemoryError oom)
1621           {
1622             new OOMWarning(
1623                     "Whilst saving current state to " + choice.getName(),
1624                     oom);
1625           } catch (Exception ex)
1626           {
1627             Cache.log.error(
1628                     "Problems whilst trying to save to " + choice.getName(),
1629                     ex);
1630             JvOptionPane.showMessageDialog(me,
1631                     MessageManager.formatMessage(
1632                             "label.error_whilst_saving_current_state_to",
1633                             new Object[]
1634                             { choice.getName() }),
1635                     MessageManager.getString("label.couldnt_save_project"),
1636                     JvOptionPane.WARNING_MESSAGE);
1637           }
1638           setProgressBar(null, choice.hashCode());
1639         }
1640       }).start();
1641     }
1642   }
1643
1644   private void setProjectFile(File choice)
1645   {
1646     this.projectFile = choice;
1647   }
1648
1649   public File getProjectFile()
1650   {
1651     return this.projectFile;
1652   }
1653
1654   /**
1655    * Prompts the user to choose a file and loads in as a Jalview project file
1656    */
1657   @Override
1658   public void loadState_actionPerformed()
1659   {
1660     JalviewFileChooser chooser = new JalviewFileChooser(
1661             Cache.getProperty("LAST_DIRECTORY"), new String[]
1662             { "jvp", "jar" },
1663             new String[]
1664             { "Jalview Project", "Jalview Project (old)" },
1665             "Jalview Project");
1666     chooser.setFileView(new JalviewFileView());
1667     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
1668
1669     int value = chooser.showOpenDialog(this);
1670
1671     if (value == JalviewFileChooser.APPROVE_OPTION)
1672     {
1673       final File selectedFile = chooser.getSelectedFile();
1674       setProjectFile(selectedFile);
1675       final String choice = selectedFile.getAbsolutePath();
1676       Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
1677       new Thread(new Runnable()
1678       {
1679         @Override
1680         public void run()
1681         {
1682           setProgressBar(MessageManager.formatMessage(
1683                   "label.loading_jalview_project", new Object[]
1684                   { choice }), choice.hashCode());
1685           try
1686           {
1687             new Jalview2XML().loadJalviewAlign(choice);
1688           } catch (OutOfMemoryError oom)
1689           {
1690             new OOMWarning("Whilst loading project from " + choice, oom);
1691           } catch (Exception ex)
1692           {
1693             Cache.log.error(
1694                     "Problems whilst loading project from " + choice, ex);
1695             JvOptionPane.showMessageDialog(Desktop.desktop,
1696                     MessageManager.formatMessage(
1697                             "label.error_whilst_loading_project_from",
1698                             new Object[]
1699                             { choice }),
1700                     MessageManager.getString("label.couldnt_load_project"),
1701                     JvOptionPane.WARNING_MESSAGE);
1702           }
1703           setProgressBar(null, choice.hashCode());
1704         }
1705       }).start();
1706     }
1707   }
1708
1709   @Override
1710   public void inputSequence_actionPerformed(ActionEvent e)
1711   {
1712     new SequenceFetcher(this);
1713   }
1714
1715   JPanel progressPanel;
1716
1717   ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
1718
1719   public void startLoading(final Object fileName)
1720   {
1721     if (fileLoadingCount == 0)
1722     {
1723       fileLoadingPanels.add(addProgressPanel(MessageManager
1724               .formatMessage("label.loading_file", new Object[]
1725               { fileName })));
1726     }
1727     fileLoadingCount++;
1728   }
1729
1730   private JPanel addProgressPanel(String string)
1731   {
1732     if (progressPanel == null)
1733     {
1734       progressPanel = new JPanel(new GridLayout(1, 1));
1735       totalProgressCount = 0;
1736       instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1737     }
1738     JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
1739     JProgressBar progressBar = new JProgressBar();
1740     progressBar.setIndeterminate(true);
1741
1742     thisprogress.add(new JLabel(string), BorderLayout.WEST);
1743
1744     thisprogress.add(progressBar, BorderLayout.CENTER);
1745     progressPanel.add(thisprogress);
1746     ((GridLayout) progressPanel.getLayout()).setRows(
1747             ((GridLayout) progressPanel.getLayout()).getRows() + 1);
1748     ++totalProgressCount;
1749     instance.validate();
1750     return thisprogress;
1751   }
1752
1753   int totalProgressCount = 0;
1754
1755   private void removeProgressPanel(JPanel progbar)
1756   {
1757     if (progressPanel != null)
1758     {
1759       synchronized (progressPanel)
1760       {
1761         progressPanel.remove(progbar);
1762         GridLayout gl = (GridLayout) progressPanel.getLayout();
1763         gl.setRows(gl.getRows() - 1);
1764         if (--totalProgressCount < 1)
1765         {
1766           this.getContentPane().remove(progressPanel);
1767           progressPanel = null;
1768         }
1769       }
1770     }
1771     validate();
1772   }
1773
1774   public void stopLoading()
1775   {
1776     fileLoadingCount--;
1777     if (fileLoadingCount < 1)
1778     {
1779       while (fileLoadingPanels.size() > 0)
1780       {
1781         removeProgressPanel(fileLoadingPanels.remove(0));
1782       }
1783       fileLoadingPanels.clear();
1784       fileLoadingCount = 0;
1785     }
1786     validate();
1787   }
1788
1789   public static int getViewCount(String alignmentId)
1790   {
1791     AlignmentViewport[] aps = getViewports(alignmentId);
1792     return (aps == null) ? 0 : aps.length;
1793   }
1794
1795   /**
1796    * 
1797    * @param alignmentId
1798    *          - if null, all sets are returned
1799    * @return all AlignmentPanels concerning the alignmentId sequence set
1800    */
1801   public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1802   {
1803     if (Desktop.desktop == null)
1804     {
1805       // no frames created and in headless mode
1806       // TODO: verify that frames are recoverable when in headless mode
1807       return null;
1808     }
1809     List<AlignmentPanel> aps = new ArrayList<>();
1810     AlignFrame[] frames = getAlignFrames();
1811     if (frames == null)
1812     {
1813       return null;
1814     }
1815     for (AlignFrame af : frames)
1816     {
1817       for (AlignmentPanel ap : af.alignPanels)
1818       {
1819         if (alignmentId == null
1820                 || alignmentId.equals(ap.av.getSequenceSetId()))
1821         {
1822           aps.add(ap);
1823         }
1824       }
1825     }
1826     if (aps.size() == 0)
1827     {
1828       return null;
1829     }
1830     AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
1831     return vap;
1832   }
1833
1834   /**
1835    * get all the viewports on an alignment.
1836    * 
1837    * @param sequenceSetId
1838    *          unique alignment id (may be null - all viewports returned in that
1839    *          case)
1840    * @return all viewports on the alignment bound to sequenceSetId
1841    */
1842   public static AlignmentViewport[] getViewports(String sequenceSetId)
1843   {
1844     List<AlignmentViewport> viewp = new ArrayList<>();
1845     if (desktop != null)
1846     {
1847       AlignFrame[] frames = Desktop.getAlignFrames();
1848
1849       for (AlignFrame afr : frames)
1850       {
1851         if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
1852                 .equals(sequenceSetId))
1853         {
1854           if (afr.alignPanels != null)
1855           {
1856             for (AlignmentPanel ap : afr.alignPanels)
1857             {
1858               if (sequenceSetId == null
1859                       || sequenceSetId.equals(ap.av.getSequenceSetId()))
1860               {
1861                 viewp.add(ap.av);
1862               }
1863             }
1864           }
1865           else
1866           {
1867             viewp.add(afr.getViewport());
1868           }
1869         }
1870       }
1871       if (viewp.size() > 0)
1872       {
1873         return viewp.toArray(new AlignmentViewport[viewp.size()]);
1874       }
1875     }
1876     return null;
1877   }
1878
1879   /**
1880    * Explode the views in the given frame into separate AlignFrame
1881    * 
1882    * @param af
1883    */
1884   public static void explodeViews(AlignFrame af)
1885   {
1886     int size = af.alignPanels.size();
1887     if (size < 2)
1888     {
1889       return;
1890     }
1891
1892     for (int i = 0; i < size; i++)
1893     {
1894       AlignmentPanel ap = af.alignPanels.get(i);
1895       AlignFrame newaf = new AlignFrame(ap);
1896
1897       /*
1898        * Restore the view's last exploded frame geometry if known. Multiple
1899        * views from one exploded frame share and restore the same (frame)
1900        * position and size.
1901        */
1902       Rectangle geometry = ap.av.getExplodedGeometry();
1903       if (geometry != null)
1904       {
1905         newaf.setBounds(geometry);
1906       }
1907
1908       ap.av.setGatherViewsHere(false);
1909
1910       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1911               AlignFrame.DEFAULT_HEIGHT);
1912     }
1913
1914     af.alignPanels.clear();
1915     af.closeMenuItem_actionPerformed(true);
1916
1917   }
1918
1919   /**
1920    * Gather expanded views (separate AlignFrame's) with the same sequence set
1921    * identifier back in to this frame as additional views, and close the expanded
1922    * views. Note the expanded frames may themselves have multiple views. We take
1923    * the lot.
1924    * 
1925    * @param source
1926    */
1927   public void gatherViews(AlignFrame source)
1928   {
1929     source.viewport.setGatherViewsHere(true);
1930     source.viewport.setExplodedGeometry(source.getBounds());
1931     JInternalFrame[] frames = desktop.getAllFrames();
1932     String viewId = source.viewport.getSequenceSetId();
1933
1934     for (int t = 0; t < frames.length; t++)
1935     {
1936       if (frames[t] instanceof AlignFrame && frames[t] != source)
1937       {
1938         AlignFrame af = (AlignFrame) frames[t];
1939         boolean gatherThis = false;
1940         for (int a = 0; a < af.alignPanels.size(); a++)
1941         {
1942           AlignmentPanel ap = af.alignPanels.get(a);
1943           if (viewId.equals(ap.av.getSequenceSetId()))
1944           {
1945             gatherThis = true;
1946             ap.av.setGatherViewsHere(false);
1947             ap.av.setExplodedGeometry(af.getBounds());
1948             source.addAlignmentPanel(ap, false);
1949           }
1950         }
1951
1952         if (gatherThis)
1953         {
1954           af.alignPanels.clear();
1955           af.closeMenuItem_actionPerformed(true);
1956         }
1957       }
1958     }
1959
1960   }
1961
1962   jalview.gui.VamsasApplication v_client = null;
1963
1964   @Override
1965   public void vamsasImport_actionPerformed(ActionEvent e)
1966   {
1967     // TODO: JAL-3048 not needed for Jalview-JS
1968
1969     if (v_client == null)
1970     {
1971       // Load and try to start a session.
1972       JalviewFileChooser chooser = new JalviewFileChooser(
1973               jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1974
1975       chooser.setFileView(new JalviewFileView());
1976       chooser.setDialogTitle(
1977               MessageManager.getString("label.open_saved_vamsas_session"));
1978       chooser.setToolTipText(MessageManager.getString(
1979               "label.select_vamsas_session_opened_as_new_vamsas_session"));
1980
1981       int value = chooser.showOpenDialog(this);
1982
1983       if (value == JalviewFileChooser.APPROVE_OPTION)
1984       {
1985         String fle = chooser.getSelectedFile().toString();
1986         if (!vamsasImport(chooser.getSelectedFile()))
1987         {
1988           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1989                   MessageManager.formatMessage(
1990                           "label.couldnt_import_as_vamsas_session",
1991                           new Object[]
1992                           { fle }),
1993                   MessageManager
1994                           .getString("label.vamsas_document_import_failed"),
1995                   JvOptionPane.ERROR_MESSAGE);
1996         }
1997       }
1998     }
1999     else
2000     {
2001       jalview.bin.Cache.log.error(
2002               "Implementation error - load session from a running session is not supported.");
2003     }
2004   }
2005
2006   /**
2007    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
2008    * 
2009    * @param file
2010    * @return true if import was a success and a session was started.
2011    */
2012   public boolean vamsasImport(URL url)
2013   {
2014     // TODO: create progress bar
2015     if (v_client != null)
2016     {
2017
2018       jalview.bin.Cache.log.error(
2019               "Implementation error - load session from a running session is not supported.");
2020       return false;
2021     }
2022
2023     try
2024     {
2025       // copy the URL content to a temporary local file
2026       // TODO: be a bit cleverer here with nio (?!)
2027       File file = File.createTempFile("vdocfromurl", ".vdj");
2028       FileOutputStream fos = new FileOutputStream(file);
2029       BufferedInputStream bis = new BufferedInputStream(url.openStream());
2030       byte[] buffer = new byte[2048];
2031       int ln;
2032       while ((ln = bis.read(buffer)) > -1)
2033       {
2034         fos.write(buffer, 0, ln);
2035       }
2036       bis.close();
2037       fos.close();
2038       v_client = new jalview.gui.VamsasApplication(this, file,
2039               url.toExternalForm());
2040     } catch (Exception ex)
2041     {
2042       jalview.bin.Cache.log.error(
2043               "Failed to create new vamsas session from contents of URL "
2044                       + url,
2045               ex);
2046       return false;
2047     }
2048     setupVamsasConnectedGui();
2049     v_client.initial_update(); // TODO: thread ?
2050     return v_client.inSession();
2051   }
2052
2053   /**
2054    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
2055    * 
2056    * @param file
2057    * @return true if import was a success and a session was started.
2058    */
2059   public boolean vamsasImport(File file)
2060   {
2061     if (v_client != null)
2062     {
2063
2064       jalview.bin.Cache.log.error(
2065               "Implementation error - load session from a running session is not supported.");
2066       return false;
2067     }
2068
2069     setProgressBar(MessageManager.formatMessage(
2070             "status.importing_vamsas_session_from", new Object[]
2071             { file.getName() }), file.hashCode());
2072     try
2073     {
2074       v_client = new jalview.gui.VamsasApplication(this, file, null);
2075     } catch (Exception ex)
2076     {
2077       setProgressBar(MessageManager.formatMessage(
2078               "status.importing_vamsas_session_from", new Object[]
2079               { file.getName() }), file.hashCode());
2080       jalview.bin.Cache.log.error(
2081               "New vamsas session from existing session file failed:", ex);
2082       return false;
2083     }
2084     setupVamsasConnectedGui();
2085     v_client.initial_update(); // TODO: thread ?
2086     setProgressBar(MessageManager.formatMessage(
2087             "status.importing_vamsas_session_from", new Object[]
2088             { file.getName() }), file.hashCode());
2089     return v_client.inSession();
2090   }
2091
2092   public boolean joinVamsasSession(String mysesid)
2093   {
2094     if (v_client != null)
2095     {
2096       throw new Error(MessageManager
2097               .getString("error.try_join_vamsas_session_another"));
2098     }
2099     if (mysesid == null)
2100     {
2101       throw new Error(
2102               MessageManager.getString("error.invalid_vamsas_session_id"));
2103     }
2104     v_client = new VamsasApplication(this, mysesid);
2105     setupVamsasConnectedGui();
2106     v_client.initial_update();
2107     return (v_client.inSession());
2108   }
2109
2110   @Override
2111   public void vamsasStart_actionPerformed(ActionEvent e)
2112   {
2113     if (v_client == null)
2114     {
2115       // Start a session.
2116       // we just start a default session for moment.
2117       /*
2118        * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
2119        * getProperty("LAST_DIRECTORY"));
2120        * 
2121        * chooser.setFileView(new JalviewFileView());
2122        * chooser.setDialogTitle("Load Vamsas file");
2123        * chooser.setToolTipText("Import");
2124        * 
2125        * int value = chooser.showOpenDialog(this);
2126        * 
2127        * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
2128        * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
2129        */
2130       v_client = new VamsasApplication(this);
2131       setupVamsasConnectedGui();
2132       v_client.initial_update(); // TODO: thread ?
2133     }
2134     else
2135     {
2136       // store current data in session.
2137       v_client.push_update(); // TODO: thread
2138     }
2139   }
2140
2141   protected void setupVamsasConnectedGui()
2142   {
2143     vamsasStart.setText(MessageManager.getString("label.session_update"));
2144     vamsasSave.setVisible(true);
2145     vamsasStop.setVisible(true);
2146     vamsasImport.setVisible(false); // Document import to existing session is
2147     // not possible for vamsas-client-1.0.
2148   }
2149
2150   protected void setupVamsasDisconnectedGui()
2151   {
2152     vamsasSave.setVisible(false);
2153     vamsasStop.setVisible(false);
2154     vamsasImport.setVisible(true);
2155     vamsasStart
2156             .setText(MessageManager.getString("label.new_vamsas_session"));
2157   }
2158
2159   @Override
2160   public void vamsasStop_actionPerformed(ActionEvent e)
2161   {
2162     if (v_client != null)
2163     {
2164       v_client.end_session();
2165       v_client = null;
2166       setupVamsasDisconnectedGui();
2167     }
2168   }
2169
2170   protected void buildVamsasStMenu()
2171   {
2172     if (v_client == null)
2173     {
2174       String[] sess = null;
2175       try
2176       {
2177         sess = VamsasApplication.getSessionList();
2178       } catch (Exception e)
2179       {
2180         jalview.bin.Cache.log.warn("Problem getting current sessions list.",
2181                 e);
2182         sess = null;
2183       }
2184       if (sess != null)
2185       {
2186         jalview.bin.Cache.log.debug(
2187                 "Got current sessions list: " + sess.length + " entries.");
2188         VamsasStMenu.removeAll();
2189         for (int i = 0; i < sess.length; i++)
2190         {
2191           JMenuItem sessit = new JMenuItem();
2192           sessit.setText(sess[i]);
2193           sessit.setToolTipText(MessageManager
2194                   .formatMessage("label.connect_to_session", new Object[]
2195                   { sess[i] }));
2196           final Desktop dsktp = this;
2197           final String mysesid = sess[i];
2198           sessit.addActionListener(new ActionListener()
2199           {
2200
2201             @Override
2202             public void actionPerformed(ActionEvent e)
2203             {
2204               if (dsktp.v_client == null)
2205               {
2206                 Thread rthr = new Thread(new Runnable()
2207                 {
2208
2209                   @Override
2210                   public void run()
2211                   {
2212                     dsktp.v_client = new VamsasApplication(dsktp, mysesid);
2213                     dsktp.setupVamsasConnectedGui();
2214                     dsktp.v_client.initial_update();
2215                   }
2216
2217                 });
2218                 rthr.start();
2219               }
2220             };
2221           });
2222           VamsasStMenu.add(sessit);
2223         }
2224         // don't show an empty menu.
2225         VamsasStMenu.setVisible(sess.length > 0);
2226
2227       }
2228       else
2229       {
2230         jalview.bin.Cache.log.debug("No current vamsas sessions.");
2231         VamsasStMenu.removeAll();
2232         VamsasStMenu.setVisible(false);
2233       }
2234     }
2235     else
2236     {
2237       // Not interested in the content. Just hide ourselves.
2238       VamsasStMenu.setVisible(false);
2239     }
2240   }
2241
2242   @Override
2243   public void vamsasSave_actionPerformed(ActionEvent e)
2244   {
2245     // TODO: JAL-3048 not needed for Jalview-JS
2246
2247     if (v_client != null)
2248     {
2249       // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
2250       JalviewFileChooser chooser = new JalviewFileChooser("vdj",
2251               "Vamsas Document");
2252
2253       chooser.setFileView(new JalviewFileView());
2254       chooser.setDialogTitle(MessageManager
2255               .getString("label.save_vamsas_document_archive"));
2256
2257       int value = chooser.showSaveDialog(this);
2258
2259       if (value == JalviewFileChooser.APPROVE_OPTION)
2260       {
2261         java.io.File choice = chooser.getSelectedFile();
2262         JPanel progpanel = addProgressPanel(MessageManager
2263                 .formatMessage("label.saving_vamsas_doc", new Object[]
2264                 { choice.getName() }));
2265         Cache.setProperty("LAST_DIRECTORY", choice.getParent());
2266         String warnmsg = null;
2267         String warnttl = null;
2268         try
2269         {
2270           v_client.vclient.storeDocument(choice);
2271         } catch (Error ex)
2272         {
2273           warnttl = "Serious Problem saving Vamsas Document";
2274           warnmsg = ex.toString();
2275           jalview.bin.Cache.log
2276                   .error("Error Whilst saving document to " + choice, ex);
2277
2278         } catch (Exception ex)
2279         {
2280           warnttl = "Problem saving Vamsas Document.";
2281           warnmsg = ex.toString();
2282           jalview.bin.Cache.log.warn(
2283                   "Exception Whilst saving document to " + choice, ex);
2284
2285         }
2286         removeProgressPanel(progpanel);
2287         if (warnmsg != null)
2288         {
2289           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2290
2291                   warnmsg, warnttl, JvOptionPane.ERROR_MESSAGE);
2292         }
2293       }
2294     }
2295   }
2296
2297   JPanel vamUpdate = null;
2298
2299   /**
2300    * hide vamsas user gui bits when a vamsas document event is being handled.
2301    * 
2302    * @param b
2303    *          true to hide gui, false to reveal gui
2304    */
2305   public void setVamsasUpdate(boolean b)
2306   {
2307     Cache.log.debug("Setting gui for Vamsas update "
2308             + (b ? "in progress" : "finished"));
2309
2310     if (vamUpdate != null)
2311     {
2312       this.removeProgressPanel(vamUpdate);
2313     }
2314     if (b)
2315     {
2316       vamUpdate = this.addProgressPanel(
2317               MessageManager.getString("label.updating_vamsas_session"));
2318     }
2319     vamsasStart.setVisible(!b);
2320     vamsasStop.setVisible(!b);
2321     vamsasSave.setVisible(!b);
2322   }
2323
2324   public JInternalFrame[] getAllFrames()
2325   {
2326     return desktop.getAllFrames();
2327   }
2328
2329   /**
2330    * Checks the given url to see if it gives a response indicating that the user
2331    * should be informed of a new questionnaire.
2332    * 
2333    * @param url
2334    */
2335   public void checkForQuestionnaire(String url)
2336   {
2337     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2338     // javax.swing.SwingUtilities.invokeLater(jvq);
2339     new Thread(jvq).start();
2340   }
2341
2342   public void checkURLLinks()
2343   {
2344     // Thread off the URL link checker
2345     addDialogThread(new Runnable()
2346     {
2347       @Override
2348       public void run()
2349       {
2350         if (Cache.getDefault("CHECKURLLINKS", true))
2351         {
2352           // check what the actual links are - if it's just the default don't
2353           // bother with the warning
2354           List<String> links = Preferences.sequenceUrlLinks
2355                   .getLinksForMenu();
2356
2357           // only need to check links if there is one with a
2358           // SEQUENCE_ID which is not the default EMBL_EBI link
2359           ListIterator<String> li = links.listIterator();
2360           boolean check = false;
2361           List<JLabel> urls = new ArrayList<>();
2362           while (li.hasNext())
2363           {
2364             String link = li.next();
2365             if (link.contains(SEQUENCE_ID)
2366                     && !UrlConstants.isDefaultString(link))
2367             {
2368               check = true;
2369               int barPos = link.indexOf("|");
2370               String urlMsg = barPos == -1 ? link
2371                       : link.substring(0, barPos) + ": "
2372                               + link.substring(barPos + 1);
2373               urls.add(new JLabel(urlMsg));
2374             }
2375           }
2376           if (!check)
2377           {
2378             return;
2379           }
2380
2381           // ask user to check in case URL links use old style tokens
2382           // ($SEQUENCE_ID$ for sequence id _or_ accession id)
2383           JPanel msgPanel = new JPanel();
2384           msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
2385           msgPanel.add(Box.createVerticalGlue());
2386           JLabel msg = new JLabel(MessageManager
2387                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
2388           JLabel msg2 = new JLabel(MessageManager
2389                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
2390           msgPanel.add(msg);
2391           for (JLabel url : urls)
2392           {
2393             msgPanel.add(url);
2394           }
2395           msgPanel.add(msg2);
2396
2397           final JCheckBox jcb = new JCheckBox(
2398                   MessageManager.getString("label.do_not_display_again"));
2399           jcb.addActionListener(new ActionListener()
2400           {
2401             @Override
2402             public void actionPerformed(ActionEvent e)
2403             {
2404               // update Cache settings for "don't show this again"
2405               boolean showWarningAgain = !jcb.isSelected();
2406               Cache.setProperty("CHECKURLLINKS",
2407                       Boolean.valueOf(showWarningAgain).toString());
2408             }
2409           });
2410           msgPanel.add(jcb);
2411
2412           JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
2413                   MessageManager
2414                           .getString("label.SEQUENCE_ID_no_longer_used"),
2415                   JvOptionPane.WARNING_MESSAGE);
2416         }
2417       }
2418     });
2419   }
2420
2421   /**
2422    * Proxy class for JDesktopPane which optionally displays the current memory
2423    * usage and highlights the desktop area with a red bar if free memory runs low.
2424    * 
2425    * @author AMW
2426    */
2427   public class MyDesktopPane extends JDesktopPane
2428           implements Runnable, PropertyChangeListener
2429   {
2430
2431     public Object[] dialogData;
2432
2433     // @Override
2434     @Override
2435     public void propertyChange(PropertyChangeEvent event)
2436     {
2437       // TODO this is obsolete with JAL-3048 - delete?
2438       Object val = event.getNewValue();
2439       String name = event.getPropertyName();
2440       System.out.println(name);
2441       switch (event.getSource().getClass().getName())
2442       {
2443       case "javax.swing.JOptionPane":
2444         switch (name)
2445         {
2446         case "inputValue":
2447           onDialogReturn(val);
2448           return;
2449         case "value":
2450           if (val instanceof Integer)
2451           {
2452             onDialogReturn(((Integer) val).intValue());
2453           }
2454           else
2455           {
2456             onDialogReturn(val);
2457           }
2458           return;
2459         }
2460         break;
2461       case "javax.swing.JFileChooser":
2462         switch (name)
2463         {
2464         case "SelectedFile":
2465           // in JavaScript, this File object will have a _bytes property,
2466           // because the file data has already been loaded
2467           onDialogReturn(new Object[] { (File) val });
2468           return;
2469         }
2470         break;
2471       }
2472       System.out.println(event.getSource().getClass().getName() + " "
2473               + event.getPropertyName() + ": " + event.getNewValue());
2474     }
2475
2476     // JSCOmponent.DialogCaller interface
2477     void onDialogReturn(Object value)
2478     {
2479       switch ((String) dialogData[0])
2480       {
2481       case "SelectedFile":
2482       case "runnable":
2483         dialogData[0] = value;
2484         ((Runnable) dialogData[1]).run();
2485         break;
2486       default:
2487       }
2488     }
2489
2490     // JSCOmponent.DialogCaller interface
2491     void onDialogReturn(int value)
2492     {
2493       if (value != Math.floor(value))
2494       {
2495         // in JavaScript, this will be NaN, oddly enough
2496         return;
2497       }
2498
2499       switch ((String) dialogData[0])
2500       {
2501       case "runnable":
2502         dialogData[0] = Integer.valueOf(value);
2503         ((Runnable) dialogData[1]).run();
2504         break;
2505       case "label.input_alignment_from_url":
2506         // reconstruct the parameter data
2507         int reply = value;
2508         AlignViewport viewport = (AlignViewport) dialogData[1];
2509         JComboBox history = (JComboBox) dialogData[2];
2510         // the rest of this is unchangaed
2511         if (reply != JvOptionPane.OK_OPTION)
2512         {
2513           return;
2514         }
2515
2516         String url = history.getSelectedItem().toString();
2517
2518         if (url.toLowerCase().endsWith(".jar"))
2519         {
2520           if (viewport != null)
2521           {
2522             new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
2523                     FileFormat.Jalview);
2524           }
2525           else
2526           {
2527             new FileLoader().LoadFile(url, DataSourceType.URL,
2528                     FileFormat.Jalview);
2529           }
2530         }
2531         else
2532         {
2533           FileFormatI format = null;
2534           try
2535           {
2536             format = new IdentifyFile().identify(url, DataSourceType.URL);
2537           } catch (FileFormatException e)
2538           {
2539             // TODO revise error handling, distinguish between
2540             // URL not found and response not valid
2541           }
2542
2543           if (format == null)
2544           {
2545             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2546                     MessageManager.formatMessage("label.couldnt_locate",
2547                             new Object[]
2548                             { url }),
2549                     MessageManager.getString("label.url_not_found"),
2550                     JvOptionPane.WARNING_MESSAGE);
2551
2552             return;
2553           }
2554
2555           if (viewport != null)
2556           {
2557             new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
2558                     format);
2559           }
2560           else
2561           {
2562             new FileLoader().LoadFile(url, DataSourceType.URL, format);
2563           }
2564         }
2565
2566         break;
2567       }
2568
2569     }
2570
2571     private static final float ONE_MB = 1048576f;
2572
2573     boolean showMemoryUsage = false;
2574
2575     Runtime runtime;
2576
2577     java.text.NumberFormat df;
2578
2579     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2580             percentUsage;
2581
2582     public MyDesktopPane(boolean showMemoryUsage)
2583     {
2584       showMemoryUsage(showMemoryUsage);
2585     }
2586
2587     public void showMemoryUsage(boolean showMemory)
2588     {
2589       this.showMemoryUsage = showMemory;
2590       if (showMemory)
2591       {
2592         Thread worker = new Thread(this);
2593         worker.start();
2594       }
2595       repaint();
2596     }
2597
2598     public boolean isShowMemoryUsage()
2599     {
2600       return showMemoryUsage;
2601     }
2602
2603     @Override
2604     public void run()
2605     {
2606       df = java.text.NumberFormat.getNumberInstance();
2607       df.setMaximumFractionDigits(2);
2608       runtime = Runtime.getRuntime();
2609
2610       while (showMemoryUsage)
2611       {
2612         try
2613         {
2614           maxMemory = runtime.maxMemory() / ONE_MB;
2615           allocatedMemory = runtime.totalMemory() / ONE_MB;
2616           freeMemory = runtime.freeMemory() / ONE_MB;
2617           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2618
2619           percentUsage = (totalFreeMemory / maxMemory) * 100;
2620
2621           // if (percentUsage < 20)
2622           {
2623             // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2624             // Color.red);
2625             // instance.set.setBorder(border1);
2626           }
2627           repaint();
2628           // sleep after showing usage
2629           Thread.sleep(3000);
2630         } catch (Exception ex)
2631         {
2632           ex.printStackTrace();
2633         }
2634       }
2635     }
2636
2637     @Override
2638     public void paintComponent(Graphics g)
2639     {
2640       if (showMemoryUsage && g != null && df != null)
2641       {
2642         if (percentUsage < 20)
2643         {
2644           g.setColor(Color.red);
2645         }
2646         FontMetrics fm = g.getFontMetrics();
2647         if (fm != null)
2648         {
2649           g.drawString(MessageManager.formatMessage("label.memory_stats",
2650                   new Object[]
2651                   { df.format(totalFreeMemory), df.format(maxMemory),
2652                       df.format(percentUsage) }),
2653                   10, getHeight() - fm.getHeight());
2654         }
2655       }
2656     }
2657   }
2658
2659   /**
2660    * Accessor method to quickly get all the AlignmentFrames loaded.
2661    * 
2662    * @return an array of AlignFrame, or null if none found
2663    */
2664   public static AlignFrame[] getAlignFrames()
2665   {
2666     if (Jalview.isHeadlessMode())
2667     {
2668       // Desktop.desktop is null in headless mode
2669       return new AlignFrame[] { Jalview.currentAlignFrame };
2670     }
2671
2672     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2673
2674     if (frames == null)
2675     {
2676       return null;
2677     }
2678     List<AlignFrame> avp = new ArrayList<>();
2679     // REVERSE ORDER
2680     for (int i = frames.length - 1; i > -1; i--)
2681     {
2682       if (frames[i] instanceof AlignFrame)
2683       {
2684         avp.add((AlignFrame) frames[i]);
2685       }
2686       else if (frames[i] instanceof SplitFrame)
2687       {
2688         /*
2689          * Also check for a split frame containing an AlignFrame
2690          */
2691         GSplitFrame sf = (GSplitFrame) frames[i];
2692         if (sf.getTopFrame() instanceof AlignFrame)
2693         {
2694           avp.add((AlignFrame) sf.getTopFrame());
2695         }
2696         if (sf.getBottomFrame() instanceof AlignFrame)
2697         {
2698           avp.add((AlignFrame) sf.getBottomFrame());
2699         }
2700       }
2701     }
2702     if (avp.size() == 0)
2703     {
2704       return null;
2705     }
2706     AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2707     return afs;
2708   }
2709
2710   /**
2711    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2712    * 
2713    * @return
2714    */
2715   public GStructureViewer[] getJmols()
2716   {
2717     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2718
2719     if (frames == null)
2720     {
2721       return null;
2722     }
2723     List<GStructureViewer> avp = new ArrayList<>();
2724     // REVERSE ORDER
2725     for (int i = frames.length - 1; i > -1; i--)
2726     {
2727       if (frames[i] instanceof AppJmol)
2728       {
2729         GStructureViewer af = (GStructureViewer) frames[i];
2730         avp.add(af);
2731       }
2732     }
2733     if (avp.size() == 0)
2734     {
2735       return null;
2736     }
2737     GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2738     return afs;
2739   }
2740
2741   /**
2742    * Add Groovy Support to Jalview
2743    */
2744   @Override
2745   public void groovyShell_actionPerformed()
2746   {
2747     try
2748     {
2749       openGroovyConsole();
2750     } catch (Exception ex)
2751     {
2752       jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2753       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2754
2755               MessageManager.getString("label.couldnt_create_groovy_shell"),
2756               MessageManager.getString("label.groovy_support_failed"),
2757               JvOptionPane.ERROR_MESSAGE);
2758     }
2759   }
2760
2761   /**
2762    * Open the Groovy console
2763    */
2764   void openGroovyConsole()
2765   {
2766     if (groovyConsole == null)
2767     {
2768       groovyConsole = new groovy.ui.Console();
2769       groovyConsole.setVariable("Jalview", this);
2770       groovyConsole.run();
2771
2772       /*
2773        * We allow only one console at a time, so that AlignFrame menu option
2774        * 'Calculate | Run Groovy script' is unambiguous.
2775        * Disable 'Groovy Console', and enable 'Run script', when the console is 
2776        * opened, and the reverse when it is closed
2777        */
2778       Window window = (Window) groovyConsole.getFrame();
2779       window.addWindowListener(new WindowAdapter()
2780       {
2781         @Override
2782         public void windowClosed(WindowEvent e)
2783         {
2784           /*
2785            * rebind CMD-Q from Groovy Console to Jalview Quit
2786            */
2787           addQuitHandler();
2788           enableExecuteGroovy(false);
2789         }
2790       });
2791     }
2792
2793     /*
2794      * show Groovy console window (after close and reopen)
2795      */
2796     ((Window) groovyConsole.getFrame()).setVisible(true);
2797
2798     /*
2799      * if we got this far, enable 'Run Groovy' in AlignFrame menus
2800      * and disable opening a second console
2801      */
2802     enableExecuteGroovy(true);
2803   }
2804
2805   /**
2806    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this binding
2807    * when opened
2808    */
2809   protected void addQuitHandler()
2810   {
2811     getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
2812             .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
2813                     Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
2814                     "Quit");
2815     getRootPane().getActionMap().put("Quit", new AbstractAction()
2816     {
2817       @Override
2818       public void actionPerformed(ActionEvent e)
2819       {
2820         quit();
2821       }
2822     });
2823   }
2824
2825   /**
2826    * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2827    * 
2828    * @param enabled
2829    *          true if Groovy console is open
2830    */
2831   public void enableExecuteGroovy(boolean enabled)
2832   {
2833     /*
2834      * disable opening a second Groovy console
2835      * (or re-enable when the console is closed)
2836      */
2837     groovyShell.setEnabled(!enabled);
2838
2839     AlignFrame[] alignFrames = getAlignFrames();
2840     if (alignFrames != null)
2841     {
2842       for (AlignFrame af : alignFrames)
2843       {
2844         af.setGroovyEnabled(enabled);
2845       }
2846     }
2847   }
2848
2849   /**
2850    * Progress bars managed by the IProgressIndicator method.
2851    */
2852   private Hashtable<Long, JPanel> progressBars;
2853
2854   private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2855
2856   /*
2857    * (non-Javadoc)
2858    * 
2859    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2860    */
2861   @Override
2862   public void setProgressBar(String message, long id)
2863   {
2864     if (progressBars == null)
2865     {
2866       progressBars = new Hashtable<>();
2867       progressBarHandlers = new Hashtable<>();
2868     }
2869
2870     if (progressBars.get(new Long(id)) != null)
2871     {
2872       JPanel panel = progressBars.remove(new Long(id));
2873       if (progressBarHandlers.contains(new Long(id)))
2874       {
2875         progressBarHandlers.remove(new Long(id));
2876       }
2877       removeProgressPanel(panel);
2878     }
2879     else
2880     {
2881       progressBars.put(new Long(id), addProgressPanel(message));
2882     }
2883   }
2884
2885   /*
2886    * (non-Javadoc)
2887    * 
2888    * @see jalview.gui.IProgressIndicator#registerHandler(long,
2889    * jalview.gui.IProgressIndicatorHandler)
2890    */
2891   @Override
2892   public void registerHandler(final long id,
2893           final IProgressIndicatorHandler handler)
2894   {
2895     if (progressBarHandlers == null
2896             || !progressBars.containsKey(new Long(id)))
2897     {
2898       throw new Error(MessageManager.getString(
2899               "error.call_setprogressbar_before_registering_handler"));
2900     }
2901     progressBarHandlers.put(new Long(id), handler);
2902     final JPanel progressPanel = progressBars.get(new Long(id));
2903     if (handler.canCancel())
2904     {
2905       JButton cancel = new JButton(
2906               MessageManager.getString("action.cancel"));
2907       final IProgressIndicator us = this;
2908       cancel.addActionListener(new ActionListener()
2909       {
2910
2911         @Override
2912         public void actionPerformed(ActionEvent e)
2913         {
2914           handler.cancelActivity(id);
2915           us.setProgressBar(MessageManager
2916                   .formatMessage("label.cancelled_params", new Object[]
2917                   { ((JLabel) progressPanel.getComponent(0)).getText() }),
2918                   id);
2919         }
2920       });
2921       progressPanel.add(cancel, BorderLayout.EAST);
2922     }
2923   }
2924
2925   /**
2926    * 
2927    * @return true if any progress bars are still active
2928    */
2929   @Override
2930   public boolean operationInProgress()
2931   {
2932     if (progressBars != null && progressBars.size() > 0)
2933     {
2934       return true;
2935     }
2936     return false;
2937   }
2938
2939   /**
2940    * This will return the first AlignFrame holding the given viewport instance. It
2941    * will break if there are more than one AlignFrames viewing a particular av.
2942    * 
2943    * @param viewport
2944    * @return alignFrame for viewport
2945    */
2946   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2947   {
2948     if (desktop != null)
2949     {
2950       AlignmentPanel[] aps = getAlignmentPanels(
2951               viewport.getSequenceSetId());
2952       for (int panel = 0; aps != null && panel < aps.length; panel++)
2953       {
2954         if (aps[panel] != null && aps[panel].av == viewport)
2955         {
2956           return aps[panel].alignFrame;
2957         }
2958       }
2959     }
2960     return null;
2961   }
2962
2963   public VamsasApplication getVamsasApplication()
2964   {
2965     return v_client;
2966
2967   }
2968
2969   /**
2970    * flag set if jalview GUI is being operated programmatically
2971    */
2972   private boolean inBatchMode = false;
2973
2974   /**
2975    * check if jalview GUI is being operated programmatically
2976    * 
2977    * @return inBatchMode
2978    */
2979   public boolean isInBatchMode()
2980   {
2981     return inBatchMode;
2982   }
2983
2984   /**
2985    * set flag if jalview GUI is being operated programmatically
2986    * 
2987    * @param inBatchMode
2988    */
2989   public void setInBatchMode(boolean inBatchMode)
2990   {
2991     this.inBatchMode = inBatchMode;
2992   }
2993
2994   public void startServiceDiscovery()
2995   {
2996     startServiceDiscovery(false);
2997   }
2998
2999   public void startServiceDiscovery(boolean blocking)
3000   {
3001     boolean alive = true;
3002     Thread t0 = null, t1 = null, t2 = null;
3003     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
3004     if (true)
3005     {
3006       // todo: changesupport handlers need to be transferred
3007       if (discoverer == null)
3008       {
3009         discoverer = new jalview.ws.jws1.Discoverer();
3010         // register PCS handler for desktop.
3011         discoverer.addPropertyChangeListener(changeSupport);
3012       }
3013       // JAL-940 - disabled JWS1 service configuration - always start discoverer
3014       // until we phase out completely
3015       (t0 = new Thread(discoverer)).start();
3016     }
3017
3018     if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
3019     {
3020       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
3021               .startDiscoverer(changeSupport);
3022     }
3023     Thread t3 = null;
3024     {
3025       // TODO: do rest service discovery
3026     }
3027     if (blocking)
3028     {
3029       while (alive)
3030       {
3031         try
3032         {
3033           Thread.sleep(15);
3034         } catch (Exception e)
3035         {
3036         }
3037         alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
3038                 || (t3 != null && t3.isAlive())
3039                 || (t0 != null && t0.isAlive());
3040       }
3041     }
3042   }
3043
3044   /**
3045    * called to check if the service discovery process completed successfully.
3046    * 
3047    * @param evt
3048    */
3049   protected void JalviewServicesChanged(PropertyChangeEvent evt)
3050   {
3051     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
3052     {
3053       final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
3054               .getErrorMessages();
3055       if (ermsg != null)
3056       {
3057         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
3058         {
3059           if (serviceChangedDialog == null)
3060           {
3061             // only run if we aren't already displaying one of these.
3062             addDialogThread(serviceChangedDialog = new Runnable()
3063             {
3064               @Override
3065               public void run()
3066               {
3067
3068                 /*
3069                  * JalviewDialog jd =new JalviewDialog() {
3070                  * 
3071                  * @Override protected void cancelPressed() { // TODO
3072                  * Auto-generated method stub
3073                  * 
3074                  * }@Override protected void okPressed() { // TODO
3075                  * Auto-generated method stub
3076                  * 
3077                  * }@Override protected void raiseClosed() { // TODO
3078                  * Auto-generated method stub
3079                  * 
3080                  * } }; jd.initDialogFrame(new
3081                  * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
3082                  * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
3083                  * + " or mis-configured HTTP proxy settings.<br/>" +
3084                  * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
3085                  * +
3086                  * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
3087                  * ), true, true, "Web Service Configuration Problem", 450,
3088                  * 400);
3089                  * 
3090                  * jd.waitForInput();
3091                  */
3092                 JvOptionPane.showConfirmDialog(Desktop.desktop,
3093                         new JLabel("<html><table width=\"450\"><tr><td>"
3094                                 + ermsg + "</td></tr></table>"
3095                                 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
3096                                 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
3097                                 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
3098                                 + " Tools->Preferences dialog box to change them.</p></html>"),
3099                         "Web Service Configuration Problem",
3100                         JvOptionPane.DEFAULT_OPTION,
3101                         JvOptionPane.ERROR_MESSAGE);
3102                 serviceChangedDialog = null;
3103
3104               }
3105             });
3106           }
3107         }
3108         else
3109         {
3110           Cache.log.error(
3111                   "Errors reported by JABA discovery service. Check web services preferences.\n"
3112                           + ermsg);
3113         }
3114       }
3115     }
3116   }
3117
3118   private Runnable serviceChangedDialog = null;
3119
3120   /**
3121    * start a thread to open a URL in the configured browser. Pops up a warning
3122    * dialog to the user if there is an exception when calling out to the browser
3123    * to open the URL.
3124    * 
3125    * @param url
3126    */
3127   public static void showUrl(final String url)
3128   {
3129     showUrl(url, Desktop.instance);
3130   }
3131
3132   /**
3133    * Like showUrl but allows progress handler to be specified
3134    * 
3135    * @param url
3136    * @param progress
3137    *          (null) or object implementing IProgressIndicator
3138    */
3139   public static void showUrl(final String url,
3140           final IProgressIndicator progress)
3141   {
3142     new Thread(new Runnable()
3143     {
3144       @Override
3145       public void run()
3146       {
3147         try
3148         {
3149           if (progress != null)
3150           {
3151             progress.setProgressBar(MessageManager
3152                     .formatMessage("status.opening_params", new Object[]
3153                     { url }), this.hashCode());
3154           }
3155           jalview.util.BrowserLauncher.openURL(url);
3156         } catch (Exception ex)
3157         {
3158           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3159                   MessageManager
3160                           .getString("label.web_browser_not_found_unix"),
3161                   MessageManager.getString("label.web_browser_not_found"),
3162                   JvOptionPane.WARNING_MESSAGE);
3163
3164           ex.printStackTrace();
3165         }
3166         if (progress != null)
3167         {
3168           progress.setProgressBar(null, this.hashCode());
3169         }
3170       }
3171     }).start();
3172   }
3173
3174   public static WsParamSetManager wsparamManager = null;
3175
3176   public static ParamManager getUserParameterStore()
3177   {
3178     if (wsparamManager == null)
3179     {
3180       wsparamManager = new WsParamSetManager();
3181     }
3182     return wsparamManager;
3183   }
3184
3185   /**
3186    * static hyperlink handler proxy method for use by Jalview's internal windows
3187    * 
3188    * @param e
3189    */
3190   public static void hyperlinkUpdate(HyperlinkEvent e)
3191   {
3192     if (e.getEventType() == EventType.ACTIVATED)
3193     {
3194       String url = null;
3195       try
3196       {
3197         url = e.getURL().toString();
3198         Desktop.showUrl(url);
3199       } catch (Exception x)
3200       {
3201         if (url != null)
3202         {
3203           if (Cache.log != null)
3204           {
3205             Cache.log.error("Couldn't handle string " + url + " as a URL.");
3206           }
3207           else
3208           {
3209             System.err.println(
3210                     "Couldn't handle string " + url + " as a URL.");
3211           }
3212         }
3213         // ignore any exceptions due to dud links.
3214       }
3215
3216     }
3217   }
3218
3219   /**
3220    * single thread that handles display of dialogs to user.
3221    */
3222   ExecutorService dialogExecutor = Executors.newSingleThreadExecutor();
3223
3224   /**
3225    * flag indicating if dialogExecutor should try to acquire a permit
3226    */
3227   private volatile boolean dialogPause = true;
3228
3229   /**
3230    * pause the queue
3231    */
3232   private java.util.concurrent.Semaphore block = new Semaphore(0);
3233
3234   private static groovy.ui.Console groovyConsole;
3235
3236   /**
3237    * add another dialog thread to the queue
3238    * 
3239    * @param prompter
3240    */
3241   public void addDialogThread(final Runnable prompter)
3242   {
3243     dialogExecutor.submit(new Runnable()
3244     {
3245       @Override
3246       public void run()
3247       {
3248         if (dialogPause)
3249         {
3250           try
3251           {
3252             block.acquire();
3253           } catch (InterruptedException x)
3254           {
3255           }
3256           ;
3257         }
3258         if (instance == null)
3259         {
3260           return;
3261         }
3262         try
3263         {
3264           SwingUtilities.invokeAndWait(prompter);
3265         } catch (Exception q)
3266         {
3267           Cache.log.warn("Unexpected Exception in dialog thread.", q);
3268         }
3269       }
3270     });
3271   }
3272
3273   public void startDialogQueue()
3274   {
3275     // set the flag so we don't pause waiting for another permit and semaphore
3276     // the current task to begin
3277     dialogPause = false;
3278     block.release();
3279   }
3280
3281   /**
3282    * Outputs an image of the desktop to file in EPS format, after prompting the
3283    * user for choice of Text or Lineart character rendering (unless a preference
3284    * has been set). The file name is generated as
3285    * 
3286    * <pre>
3287    * Jalview_snapshot_nnnnn.eps where nnnnn is the current timestamp in milliseconds
3288    * </pre>
3289    */
3290   @Override
3291   protected void snapShotWindow_actionPerformed(ActionEvent e)
3292   {
3293     // currently the menu option to do this is not shown
3294     invalidate();
3295
3296     int width = getWidth();
3297     int height = getHeight();
3298     File of = new File(
3299             "Jalview_snapshot_" + System.currentTimeMillis() + ".eps");
3300     ImageWriterI writer = new ImageWriterI()
3301     {
3302       @Override
3303       public void exportImage(Graphics g) throws Exception
3304       {
3305         paintAll(g);
3306         Cache.log.info("Successfully written snapshot to file "
3307                 + of.getAbsolutePath());
3308       }
3309     };
3310     String title = "View of desktop";
3311     ImageExporter exporter = new ImageExporter(writer, null, TYPE.EPS,
3312             title);
3313     exporter.doExport(of, this, width, height, title);
3314   }
3315
3316   /**
3317    * Explode the views in the given SplitFrame into separate SplitFrame windows.
3318    * This respects (remembers) any previous 'exploded geometry' i.e. the size and
3319    * location last time the view was expanded (if any). However it does not
3320    * remember the split pane divider location - this is set to match the
3321    * 'exploding' frame.
3322    * 
3323    * @param sf
3324    */
3325   public void explodeViews(SplitFrame sf)
3326   {
3327     AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3328     AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3329     List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3330             .getAlignPanels();
3331     List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3332             .getAlignPanels();
3333     int viewCount = topPanels.size();
3334     if (viewCount < 2)
3335     {
3336       return;
3337     }
3338
3339     /*
3340      * Processing in reverse order works, forwards order leaves the first panels
3341      * not visible. I don't know why!
3342      */
3343     for (int i = viewCount - 1; i >= 0; i--)
3344     {
3345       /*
3346        * Make new top and bottom frames. These take over the respective
3347        * AlignmentPanel objects, including their AlignmentViewports, so the
3348        * cdna/protein relationships between the viewports is carried over to the
3349        * new split frames.
3350        * 
3351        * explodedGeometry holds the (x, y) position of the previously exploded
3352        * SplitFrame, and the (width, height) of the AlignFrame component
3353        */
3354       AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3355       AlignFrame newTopFrame = new AlignFrame(topPanel);
3356       newTopFrame.setSize(oldTopFrame.getSize());
3357       newTopFrame.setVisible(true);
3358       Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3359               .getExplodedGeometry();
3360       if (geometry != null)
3361       {
3362         newTopFrame.setSize(geometry.getSize());
3363       }
3364
3365       AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3366       AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3367       newBottomFrame.setSize(oldBottomFrame.getSize());
3368       newBottomFrame.setVisible(true);
3369       geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3370               .getExplodedGeometry();
3371       if (geometry != null)
3372       {
3373         newBottomFrame.setSize(geometry.getSize());
3374       }
3375
3376       topPanel.av.setGatherViewsHere(false);
3377       bottomPanel.av.setGatherViewsHere(false);
3378       JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3379               newBottomFrame);
3380       if (geometry != null)
3381       {
3382         splitFrame.setLocation(geometry.getLocation());
3383       }
3384       Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3385     }
3386
3387     /*
3388      * Clear references to the panels (now relocated in the new SplitFrames)
3389      * before closing the old SplitFrame.
3390      */
3391     topPanels.clear();
3392     bottomPanels.clear();
3393     sf.close();
3394   }
3395
3396   /**
3397    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3398    * back into the given SplitFrame as additional views. Note that the gathered
3399    * frames may themselves have multiple views.
3400    * 
3401    * @param source
3402    */
3403   public void gatherViews(GSplitFrame source)
3404   {
3405     /*
3406      * special handling of explodedGeometry for a view within a SplitFrame: - it
3407      * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3408      * height) of the AlignFrame component
3409      */
3410     AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3411     AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3412     myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3413             source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3414     myBottomFrame.viewport
3415             .setExplodedGeometry(new Rectangle(source.getX(), source.getY(),
3416                     myBottomFrame.getWidth(), myBottomFrame.getHeight()));
3417     myTopFrame.viewport.setGatherViewsHere(true);
3418     myBottomFrame.viewport.setGatherViewsHere(true);
3419     String topViewId = myTopFrame.viewport.getSequenceSetId();
3420     String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3421
3422     JInternalFrame[] frames = desktop.getAllFrames();
3423     for (JInternalFrame frame : frames)
3424     {
3425       if (frame instanceof SplitFrame && frame != source)
3426       {
3427         SplitFrame sf = (SplitFrame) frame;
3428         AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3429         AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3430         boolean gatherThis = false;
3431         for (int a = 0; a < topFrame.alignPanels.size(); a++)
3432         {
3433           AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3434           AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3435           if (topViewId.equals(topPanel.av.getSequenceSetId())
3436                   && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3437           {
3438             gatherThis = true;
3439             topPanel.av.setGatherViewsHere(false);
3440             bottomPanel.av.setGatherViewsHere(false);
3441             topPanel.av.setExplodedGeometry(
3442                     new Rectangle(sf.getLocation(), topFrame.getSize()));
3443             bottomPanel.av.setExplodedGeometry(
3444                     new Rectangle(sf.getLocation(), bottomFrame.getSize()));
3445             myTopFrame.addAlignmentPanel(topPanel, false);
3446             myBottomFrame.addAlignmentPanel(bottomPanel, false);
3447           }
3448         }
3449
3450         if (gatherThis)
3451         {
3452           topFrame.getAlignPanels().clear();
3453           bottomFrame.getAlignPanels().clear();
3454           sf.close();
3455         }
3456       }
3457     }
3458
3459     /*
3460      * The dust settles...give focus to the tab we did this from.
3461      */
3462     myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3463   }
3464
3465   public static groovy.ui.Console getGroovyConsole()
3466   {
3467     return groovyConsole;
3468   }
3469
3470   /**
3471    * handles the payload of a drag and drop event.
3472    * 
3473    * TODO refactor to desktop utilities class
3474    * 
3475    * @param files
3476    *          - Data source strings extracted from the drop event
3477    * @param protocols
3478    *          - protocol for each data source extracted from the drop event
3479    * @param evt
3480    *          - the drop event
3481    * @param t
3482    *          - the payload from the drop event
3483    * @throws Exception
3484    */
3485   public static void transferFromDropTarget(List<Object> files,
3486           List<DataSourceType> protocols, DropTargetDropEvent evt,
3487           Transferable t) throws Exception
3488   {
3489
3490     // BH 2018 changed List<String> to List<Object> to allow for File from SwingJS
3491
3492     // DataFlavor[] flavors = t.getTransferDataFlavors();
3493     // for (int i = 0; i < flavors.length; i++) {
3494     // if (flavors[i].isFlavorJavaFileListType()) {
3495     // evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3496     // List<File> list = (List<File>) t.getTransferData(flavors[i]);
3497     // for (int j = 0; j < list.size(); j++) {
3498     // File file = (File) list.get(j);
3499     // byte[] data = getDroppedFileBytes(file);
3500     // fileName.setText(file.getName() + " - " + data.length + " " +
3501     // evt.getLocation());
3502     // JTextArea target = (JTextArea) ((DropTarget) evt.getSource()).getComponent();
3503     // target.setText(new String(data));
3504     // }
3505     // dtde.dropComplete(true);
3506     // return;
3507     // }
3508     //
3509
3510     DataFlavor uriListFlavor = new DataFlavor(
3511             "text/uri-list;class=java.lang.String"), urlFlavour = null;
3512     try
3513     {
3514       urlFlavour = new DataFlavor(
3515               "application/x-java-url; class=java.net.URL");
3516     } catch (ClassNotFoundException cfe)
3517     {
3518       Cache.log.debug("Couldn't instantiate the URL dataflavor.", cfe);
3519     }
3520
3521     if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
3522     {
3523
3524       try
3525       {
3526         java.net.URL url = (URL) t.getTransferData(urlFlavour);
3527         // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
3528         // means url may be null.
3529         if (url != null)
3530         {
3531           protocols.add(DataSourceType.URL);
3532           files.add(url.toString());
3533           Cache.log.debug("Drop handled as URL dataflavor "
3534                   + files.get(files.size() - 1));
3535           return;
3536         }
3537         else
3538         {
3539           if (Platform.isAMac())
3540           {
3541             System.err.println(
3542                     "Please ignore plist error - occurs due to problem with java 8 on OSX");
3543           }
3544           ;
3545         }
3546       } catch (Throwable ex)
3547       {
3548         Cache.log.debug("URL drop handler failed.", ex);
3549       }
3550     }
3551     if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3552     {
3553       // Works on Windows and MacOSX
3554       Cache.log.debug("Drop handled as javaFileListFlavor");
3555       for (Object file : (List) t
3556               .getTransferData(DataFlavor.javaFileListFlavor))
3557       {
3558         files.add(file);
3559         protocols.add(DataSourceType.FILE);
3560       }
3561     }
3562     else
3563     {
3564       // Unix like behaviour
3565       boolean added = false;
3566       String data = null;
3567       if (t.isDataFlavorSupported(uriListFlavor))
3568       {
3569         Cache.log.debug("Drop handled as uriListFlavor");
3570         // This is used by Unix drag system
3571         data = (String) t.getTransferData(uriListFlavor);
3572       }
3573       if (data == null)
3574       {
3575         // fallback to text: workaround - on OSX where there's a JVM bug
3576         Cache.log.debug("standard URIListFlavor failed. Trying text");
3577         // try text fallback
3578         DataFlavor textDf = new DataFlavor(
3579                 "text/plain;class=java.lang.String");
3580         if (t.isDataFlavorSupported(textDf))
3581         {
3582           data = (String) t.getTransferData(textDf);
3583         }
3584
3585         Cache.log.debug("Plain text drop content returned "
3586                 + (data == null ? "Null - failed" : data));
3587
3588       }
3589       if (data != null)
3590       {
3591         while (protocols.size() < files.size())
3592         {
3593           Cache.log.debug("Adding missing FILE protocol for "
3594                   + files.get(protocols.size()));
3595           protocols.add(DataSourceType.FILE);
3596         }
3597         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3598                 data, "\r\n"); st.hasMoreTokens();)
3599         {
3600           added = true;
3601           String s = st.nextToken();
3602           if (s.startsWith("#"))
3603           {
3604             // the line is a comment (as per the RFC 2483)
3605             continue;
3606           }
3607           java.net.URI uri = new java.net.URI(s);
3608           if (uri.getScheme().toLowerCase().startsWith("http"))
3609           {
3610             protocols.add(DataSourceType.URL);
3611             files.add(uri.toString());
3612           }
3613           else
3614           {
3615             // otherwise preserve old behaviour: catch all for file objects
3616             java.io.File file = new java.io.File(uri);
3617             protocols.add(DataSourceType.FILE);
3618             files.add(file.toString());
3619           }
3620         }
3621       }
3622
3623       if (Cache.log.isDebugEnabled())
3624       {
3625         if (data == null || !added)
3626         {
3627
3628           if (t.getTransferDataFlavors() != null
3629                   && t.getTransferDataFlavors().length > 0)
3630           {
3631             Cache.log.debug(
3632                     "Couldn't resolve drop data. Here are the supported flavors:");
3633             for (DataFlavor fl : t.getTransferDataFlavors())
3634             {
3635               Cache.log.debug(
3636                       "Supported transfer dataflavor: " + fl.toString());
3637               Object df = t.getTransferData(fl);
3638               if (df != null)
3639               {
3640                 Cache.log.debug("Retrieves: " + df);
3641               }
3642               else
3643               {
3644                 Cache.log.debug("Retrieved nothing");
3645               }
3646             }
3647           }
3648           else
3649           {
3650             Cache.log.debug("Couldn't resolve dataflavor for drop: "
3651                     + t.toString());
3652           }
3653         }
3654       }
3655     }
3656     if (Platform.isWindows())
3657
3658     {
3659       Cache.log.debug("Scanning dropped content for Windows Link Files");
3660
3661       // resolve any .lnk files in the file drop
3662       for (int f = 0; f < files.size(); f++)
3663       {
3664         String source = files.get(f).toString().toLowerCase();
3665         if (protocols.get(f).equals(DataSourceType.FILE)
3666                 && (source.endsWith(".lnk") || source.endsWith(".url")
3667                         || source.endsWith(".site")))
3668         {
3669           try
3670           {
3671             Object obj = files.get(f);
3672             File lf = (obj instanceof File ? (File) obj
3673                     : new File((String) obj));
3674             // process link file to get a URL
3675             Cache.log.debug("Found potential link file: " + lf);
3676             WindowsShortcut wscfile = new WindowsShortcut(lf);
3677             String fullname = wscfile.getRealFilename();
3678             protocols.set(f, FormatAdapter.checkProtocol(fullname));
3679             files.set(f, fullname);
3680             Cache.log.debug("Parsed real filename " + fullname
3681                     + " to extract protocol: " + protocols.get(f));
3682           } catch (Exception ex)
3683           {
3684             Cache.log.error(
3685                     "Couldn't parse " + files.get(f) + " as a link file.",
3686                     ex);
3687           }
3688         }
3689       }
3690     }
3691   }
3692
3693   /**
3694    * Sets the Preferences property for experimental features to True or False
3695    * depending on the state of the controlling menu item
3696    */
3697   @Override
3698   protected void showExperimental_actionPerformed(boolean selected)
3699   {
3700     Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
3701   }
3702
3703   /**
3704    * Answers a (possibly empty) list of any structure viewer frames (currently for
3705    * either Jmol or Chimera) which are currently open. This may optionally be
3706    * restricted to viewers of a specified class, or viewers linked to a specified
3707    * alignment panel.
3708    * 
3709    * @param apanel
3710    *          if not null, only return viewers linked to this panel
3711    * @param structureViewerClass
3712    *          if not null, only return viewers of this class
3713    * @return
3714    */
3715   public List<StructureViewerBase> getStructureViewers(
3716           AlignmentPanel apanel,
3717           Class<? extends StructureViewerBase> structureViewerClass)
3718   {
3719     List<StructureViewerBase> result = new ArrayList<>();
3720     JInternalFrame[] frames = Desktop.instance.getAllFrames();
3721
3722     for (JInternalFrame frame : frames)
3723     {
3724       if (frame instanceof StructureViewerBase)
3725       {
3726         if (structureViewerClass == null
3727                 || structureViewerClass.isInstance(frame))
3728         {
3729           if (apanel == null
3730                   || ((StructureViewerBase) frame).isLinkedWith(apanel))
3731           {
3732             result.add((StructureViewerBase) frame);
3733           }
3734         }
3735       }
3736     }
3737     return result;
3738   }
3739 }