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