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