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