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