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