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