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