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