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