JAL-4305 Isolate and unify the Jalview object from all the gubbins in jalview.bin...
[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/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   public QuitHandler.QResponse desktopQuit(boolean ui, boolean disposeFlag)
1481   {
1482     final Runnable doDesktopQuit = () -> {
1483       Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1484       Cache.setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
1485       Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height + "");
1486       storeLastKnownDimensions("", new Rectangle(getBounds().x,
1487               getBounds().y, getWidth(), getHeight()));
1488
1489       if (jconsole != null)
1490       {
1491         storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1492         jconsole.stopConsole();
1493       }
1494
1495       if (jvnews != null)
1496       {
1497         storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1498       }
1499
1500       // Frames should all close automatically. Keeping external
1501       // viewers open should already be decided by user.
1502       closeAll_actionPerformed(null);
1503
1504       // check for aborted quit
1505       if (QuitHandler.quitCancelled())
1506       {
1507         jalview.bin.Console.debug("Desktop aborting quit");
1508         return;
1509       }
1510
1511       if (dialogExecutor != null)
1512       {
1513         dialogExecutor.shutdownNow();
1514       }
1515
1516       if (groovyConsole != null)
1517       {
1518         // suppress a possible repeat prompt to save script
1519         groovyConsole.setDirty(false);
1520         groovyConsole.exit();
1521       }
1522
1523       if (QuitHandler.gotQuitResponse() == QResponse.FORCE_QUIT)
1524       {
1525         // note that shutdown hook will not be run
1526         jalview.bin.Console.debug("Force Quit selected by user");
1527         Runtime.getRuntime().halt(0);
1528       }
1529
1530       jalview.bin.Console.debug("Quit selected by user");
1531       if (disposeFlag)
1532       {
1533         instance.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
1534         // instance.dispose();
1535       }
1536       instance.quit();
1537     };
1538
1539     return QuitHandler.getQuitResponse(ui, doDesktopQuit, doDesktopQuit,
1540             QuitHandler.defaultCancelQuit);
1541   }
1542
1543   /**
1544    * Don't call this directly, use desktopQuit() above. Exits the program.
1545    */
1546   @Override
1547   public void quit()
1548   {
1549     // this will run the shutdownHook but QuitHandler.getQuitResponse() should
1550     // not run a second time if gotQuitResponse flag has been set (i.e. user
1551     // confirmed quit of some kind).
1552     Jalview.exit("Desktop exiting.", ExitCode.OK);
1553   }
1554
1555   private void storeLastKnownDimensions(String string, Rectangle jc)
1556   {
1557     jalview.bin.Console.debug("Storing last known dimensions for " + string
1558             + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1559             + " height:" + jc.height);
1560
1561     Cache.setProperty(string + "SCREEN_X", jc.x + "");
1562     Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1563     Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1564     Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1565   }
1566
1567   /**
1568    * DOCUMENT ME!
1569    * 
1570    * @param e
1571    *          DOCUMENT ME!
1572    */
1573   @Override
1574   public void aboutMenuItem_actionPerformed(ActionEvent e)
1575   {
1576     new Thread(new Runnable()
1577     {
1578       @Override
1579       public void run()
1580       {
1581         new SplashScreen(false);
1582       }
1583     }).start();
1584   }
1585
1586   /**
1587    * Returns the html text for the About screen, including any available version
1588    * number, build details, author details and citation reference, but without
1589    * the enclosing {@code html} tags
1590    * 
1591    * @return
1592    */
1593   public String getAboutMessage()
1594   {
1595     StringBuilder message = new StringBuilder(1024);
1596     message.append("<div style=\"font-family: sans-serif;\">")
1597             .append("<h1><strong>Version: ")
1598             .append(Cache.getProperty("VERSION")).append("</strong></h1>")
1599             .append("<strong>Built: <em>")
1600             .append(Cache.getDefault("BUILD_DATE", "unknown"))
1601             .append("</em> from ").append(Cache.getBuildDetailsForSplash())
1602             .append("</strong>");
1603
1604     String latestVersion = Cache.getDefault("LATEST_VERSION", "Checking");
1605     if (latestVersion.equals("Checking"))
1606     {
1607       // JBP removed this message for 2.11: May be reinstated in future version
1608       // message.append("<br>...Checking latest version...</br>");
1609     }
1610     else if (!latestVersion.equals(Cache.getProperty("VERSION")))
1611     {
1612       boolean red = false;
1613       if (Cache.getProperty("VERSION").toLowerCase(Locale.ROOT)
1614               .indexOf("automated build") == -1)
1615       {
1616         red = true;
1617         // Displayed when code version and jnlp version do not match and code
1618         // version is not a development build
1619         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1620       }
1621
1622       message.append("<br>!! Version ")
1623               .append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
1624               .append(" is available for download from ")
1625               .append(Cache.getDefault("www.jalview.org",
1626                       "https://www.jalview.org"))
1627               .append(" !!");
1628       if (red)
1629       {
1630         message.append("</div>");
1631       }
1632     }
1633     message.append("<br>Authors:  ");
1634     message.append(Cache.getDefault("AUTHORFNAMES", DEFAULT_AUTHORS));
1635     message.append(CITATION);
1636
1637     message.append("</div>");
1638
1639     return message.toString();
1640   }
1641
1642   /**
1643    * Action on requesting Help documentation
1644    */
1645   @Override
1646   public void documentationMenuItem_actionPerformed()
1647   {
1648     try
1649     {
1650       if (Platform.isJS())
1651       {
1652         BrowserLauncher.openURL("https://www.jalview.org/help.html");
1653       }
1654       else
1655       /**
1656        * Java only
1657        * 
1658        * @j2sIgnore
1659        */
1660       {
1661         Help.showHelpWindow();
1662       }
1663     } catch (Exception ex)
1664     {
1665       jalview.bin.Console
1666               .errPrintln("Error opening help: " + ex.getMessage());
1667     }
1668   }
1669
1670   @Override
1671   public void closeAll_actionPerformed(ActionEvent e)
1672   {
1673     // TODO show a progress bar while closing?
1674     JInternalFrame[] frames = desktop.getAllFrames();
1675     for (int i = 0; i < frames.length; i++)
1676     {
1677       try
1678       {
1679         frames[i].setClosed(true);
1680       } catch (java.beans.PropertyVetoException ex)
1681       {
1682       }
1683     }
1684     Jalview.getInstance().setCurrentAlignFrame(null);
1685     jalview.bin.Console.info("ALL CLOSED");
1686
1687     /*
1688      * reset state of singleton objects as appropriate (clear down session state
1689      * when all windows are closed)
1690      */
1691     StructureSelectionManager ssm = StructureSelectionManager
1692             .getStructureSelectionManager(this);
1693     if (ssm != null)
1694     {
1695       ssm.resetAll();
1696     }
1697   }
1698
1699   public int structureViewersStillRunningCount()
1700   {
1701     int count = 0;
1702     JInternalFrame[] frames = desktop.getAllFrames();
1703     for (int i = 0; i < frames.length; i++)
1704     {
1705       if (frames[i] != null
1706               && frames[i] instanceof JalviewStructureDisplayI)
1707       {
1708         if (((JalviewStructureDisplayI) frames[i]).stillRunning())
1709           count++;
1710       }
1711     }
1712     return count;
1713   }
1714
1715   @Override
1716   public void raiseRelated_actionPerformed(ActionEvent e)
1717   {
1718     reorderAssociatedWindows(false, false);
1719   }
1720
1721   @Override
1722   public void minimizeAssociated_actionPerformed(ActionEvent e)
1723   {
1724     reorderAssociatedWindows(true, false);
1725   }
1726
1727   void closeAssociatedWindows()
1728   {
1729     reorderAssociatedWindows(false, true);
1730   }
1731
1732   /*
1733    * (non-Javadoc)
1734    * 
1735    * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1736    * ActionEvent)
1737    */
1738   @Override
1739   protected void garbageCollect_actionPerformed(ActionEvent e)
1740   {
1741     // We simply collect the garbage
1742     jalview.bin.Console.debug("Collecting garbage...");
1743     System.gc();
1744     jalview.bin.Console.debug("Finished garbage collection.");
1745   }
1746
1747   /*
1748    * (non-Javadoc)
1749    * 
1750    * @see jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.
1751    * ActionEvent )
1752    */
1753   @Override
1754   protected void showMemusage_actionPerformed(ActionEvent e)
1755   {
1756     desktop.showMemoryUsage(showMemusage.isSelected());
1757   }
1758
1759   /*
1760    * (non-Javadoc)
1761    * 
1762    * @see
1763    * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1764    * )
1765    */
1766   @Override
1767   protected void showConsole_actionPerformed(ActionEvent e)
1768   {
1769     showConsole(showConsole.isSelected());
1770   }
1771
1772   Console jconsole = null;
1773
1774   /**
1775    * control whether the java console is visible or not
1776    * 
1777    * @param selected
1778    */
1779   void showConsole(boolean selected)
1780   {
1781     // TODO: decide if we should update properties file
1782     if (jconsole != null) // BH 2018
1783     {
1784       showConsole.setSelected(selected);
1785       Cache.setProperty("SHOW_JAVA_CONSOLE",
1786               Boolean.valueOf(selected).toString());
1787       jconsole.setVisible(selected);
1788     }
1789   }
1790
1791   void reorderAssociatedWindows(boolean minimize, boolean close)
1792   {
1793     JInternalFrame[] frames = desktop.getAllFrames();
1794     if (frames == null || frames.length < 1)
1795     {
1796       return;
1797     }
1798
1799     AlignmentViewport source = null, target = null;
1800     if (frames[0] instanceof AlignFrame)
1801     {
1802       source = ((AlignFrame) frames[0]).getCurrentView();
1803     }
1804     else if (frames[0] instanceof TreePanel)
1805     {
1806       source = ((TreePanel) frames[0]).getViewPort();
1807     }
1808     else if (frames[0] instanceof PCAPanel)
1809     {
1810       source = ((PCAPanel) frames[0]).av;
1811     }
1812     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1813     {
1814       source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1815     }
1816
1817     if (source != null)
1818     {
1819       for (int i = 0; i < frames.length; i++)
1820       {
1821         target = null;
1822         if (frames[i] == null)
1823         {
1824           continue;
1825         }
1826         if (frames[i] instanceof AlignFrame)
1827         {
1828           target = ((AlignFrame) frames[i]).getCurrentView();
1829         }
1830         else if (frames[i] instanceof TreePanel)
1831         {
1832           target = ((TreePanel) frames[i]).getViewPort();
1833         }
1834         else if (frames[i] instanceof PCAPanel)
1835         {
1836           target = ((PCAPanel) frames[i]).av;
1837         }
1838         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1839         {
1840           target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1841         }
1842
1843         if (source == target)
1844         {
1845           try
1846           {
1847             if (close)
1848             {
1849               frames[i].setClosed(true);
1850             }
1851             else
1852             {
1853               frames[i].setIcon(minimize);
1854               if (!minimize)
1855               {
1856                 frames[i].toFront();
1857               }
1858             }
1859
1860           } catch (java.beans.PropertyVetoException ex)
1861           {
1862           }
1863         }
1864       }
1865     }
1866   }
1867
1868   /**
1869    * DOCUMENT ME!
1870    * 
1871    * @param e
1872    *          DOCUMENT ME!
1873    */
1874   @Override
1875   protected void preferences_actionPerformed(ActionEvent e)
1876   {
1877     Preferences.openPreferences();
1878   }
1879
1880   /**
1881    * Prompts the user to choose a file and then saves the Jalview state as a
1882    * Jalview project file
1883    */
1884   @Override
1885   public void saveState_actionPerformed()
1886   {
1887     saveState_actionPerformed(false);
1888   }
1889
1890   public void saveState_actionPerformed(boolean saveAs)
1891   {
1892     java.io.File projectFile = getProjectFile();
1893     // autoSave indicates we already have a file and don't need to ask
1894     boolean autoSave = projectFile != null && !saveAs
1895             && BackupFiles.getEnabled();
1896
1897     // jalview.bin.Console.outPrintln("autoSave="+autoSave+",
1898     // projectFile='"+projectFile+"',
1899     // saveAs="+saveAs+", Backups
1900     // "+(BackupFiles.getEnabled()?"enabled":"disabled"));
1901
1902     boolean approveSave = false;
1903     if (!autoSave)
1904     {
1905       JalviewFileChooser chooser = new JalviewFileChooser("jvp",
1906               "Jalview Project");
1907
1908       chooser.setFileView(new JalviewFileView());
1909       chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1910
1911       int value = chooser.showSaveDialog(this);
1912
1913       if (value == JalviewFileChooser.APPROVE_OPTION)
1914       {
1915         projectFile = chooser.getSelectedFile();
1916         setProjectFile(projectFile);
1917         approveSave = true;
1918       }
1919     }
1920
1921     if (approveSave || autoSave)
1922     {
1923       final Desktop me = this;
1924       final java.io.File chosenFile = projectFile;
1925       new Thread(new Runnable()
1926       {
1927         @Override
1928         public void run()
1929         {
1930           // TODO: refactor to Jalview desktop session controller action.
1931           setProgressBar(MessageManager.formatMessage(
1932                   "label.saving_jalview_project", new Object[]
1933                   { chosenFile.getName() }), chosenFile.hashCode());
1934           Cache.setProperty("LAST_DIRECTORY", chosenFile.getParent());
1935           // TODO catch and handle errors for savestate
1936           // TODO prevent user from messing with the Desktop whilst we're saving
1937           try
1938           {
1939             boolean doBackup = BackupFiles.getEnabled();
1940             BackupFiles backupfiles = doBackup ? new BackupFiles(chosenFile)
1941                     : null;
1942
1943             new Jalview2XML().saveState(
1944                     doBackup ? backupfiles.getTempFile() : chosenFile);
1945
1946             if (doBackup)
1947             {
1948               backupfiles.setWriteSuccess(true);
1949               backupfiles.rollBackupsAndRenameTempFile();
1950             }
1951           } catch (OutOfMemoryError oom)
1952           {
1953             new OOMWarning("Whilst saving current state to "
1954                     + chosenFile.getName(), oom);
1955           } catch (Exception ex)
1956           {
1957             jalview.bin.Console.error("Problems whilst trying to save to "
1958                     + chosenFile.getName(), ex);
1959             JvOptionPane.showMessageDialog(me,
1960                     MessageManager.formatMessage(
1961                             "label.error_whilst_saving_current_state_to",
1962                             new Object[]
1963                             { chosenFile.getName() }),
1964                     MessageManager.getString("label.couldnt_save_project"),
1965                     JvOptionPane.WARNING_MESSAGE);
1966           }
1967           setProgressBar(null, chosenFile.hashCode());
1968         }
1969       }).start();
1970     }
1971   }
1972
1973   @Override
1974   public void saveAsState_actionPerformed(ActionEvent e)
1975   {
1976     saveState_actionPerformed(true);
1977   }
1978
1979   protected void setProjectFile(File choice)
1980   {
1981     this.projectFile = choice;
1982   }
1983
1984   public File getProjectFile()
1985   {
1986     return this.projectFile;
1987   }
1988
1989   /**
1990    * Shows a file chooser dialog and tries to read in the selected file as a
1991    * Jalview project
1992    */
1993   @Override
1994   public void loadState_actionPerformed()
1995   {
1996     final String[] suffix = new String[] { "jvp", "jar" };
1997     final String[] desc = new String[] { "Jalview Project",
1998         "Jalview Project (old)" };
1999     JalviewFileChooser chooser = new JalviewFileChooser(
2000             Cache.getProperty("LAST_DIRECTORY"), suffix, desc,
2001             "Jalview Project", true, BackupFiles.getEnabled()); // last two
2002                                                                 // booleans:
2003                                                                 // allFiles,
2004     // allowBackupFiles
2005     chooser.setFileView(new JalviewFileView());
2006     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
2007     chooser.setResponseHandler(0, () -> {
2008       File selectedFile = chooser.getSelectedFile();
2009       setProjectFile(selectedFile);
2010       String choice = selectedFile.getAbsolutePath();
2011       Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
2012       new Thread(new Runnable()
2013       {
2014         @Override
2015         public void run()
2016         {
2017           try
2018           {
2019             new Jalview2XML().loadJalviewAlign(selectedFile);
2020           } catch (OutOfMemoryError oom)
2021           {
2022             new OOMWarning("Whilst loading project from " + choice, oom);
2023           } catch (Exception ex)
2024           {
2025             jalview.bin.Console.error(
2026                     "Problems whilst loading project from " + choice, ex);
2027             JvOptionPane.showMessageDialog(Desktop.desktop,
2028                     MessageManager.formatMessage(
2029                             "label.error_whilst_loading_project_from",
2030                             new Object[]
2031                             { choice }),
2032                     MessageManager.getString("label.couldnt_load_project"),
2033                     JvOptionPane.WARNING_MESSAGE);
2034           }
2035         }
2036       }, "Project Loader").start();
2037     });
2038
2039     chooser.showOpenDialog(this);
2040   }
2041
2042   @Override
2043   public void inputSequence_actionPerformed(ActionEvent e)
2044   {
2045     new SequenceFetcher(this);
2046   }
2047
2048   JPanel progressPanel;
2049
2050   ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
2051
2052   public void startLoading(final Object fileName)
2053   {
2054     if (fileLoadingCount == 0)
2055     {
2056       fileLoadingPanels.add(addProgressPanel(MessageManager
2057               .formatMessage("label.loading_file", new Object[]
2058               { fileName })));
2059     }
2060     fileLoadingCount++;
2061   }
2062
2063   private JPanel addProgressPanel(String string)
2064   {
2065     if (progressPanel == null)
2066     {
2067       progressPanel = new JPanel(new GridLayout(1, 1));
2068       totalProgressCount = 0;
2069       instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
2070     }
2071     JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
2072     JProgressBar progressBar = new JProgressBar();
2073     progressBar.setIndeterminate(true);
2074
2075     thisprogress.add(new JLabel(string), BorderLayout.WEST);
2076
2077     thisprogress.add(progressBar, BorderLayout.CENTER);
2078     progressPanel.add(thisprogress);
2079     ((GridLayout) progressPanel.getLayout()).setRows(
2080             ((GridLayout) progressPanel.getLayout()).getRows() + 1);
2081     ++totalProgressCount;
2082     instance.validate();
2083     return thisprogress;
2084   }
2085
2086   int totalProgressCount = 0;
2087
2088   private void removeProgressPanel(JPanel progbar)
2089   {
2090     if (progressPanel != null)
2091     {
2092       synchronized (progressPanel)
2093       {
2094         progressPanel.remove(progbar);
2095         GridLayout gl = (GridLayout) progressPanel.getLayout();
2096         gl.setRows(gl.getRows() - 1);
2097         if (--totalProgressCount < 1)
2098         {
2099           this.getContentPane().remove(progressPanel);
2100           progressPanel = null;
2101         }
2102       }
2103     }
2104     validate();
2105   }
2106
2107   public void stopLoading()
2108   {
2109     fileLoadingCount--;
2110     if (fileLoadingCount < 1)
2111     {
2112       while (fileLoadingPanels.size() > 0)
2113       {
2114         removeProgressPanel(fileLoadingPanels.remove(0));
2115       }
2116       fileLoadingPanels.clear();
2117       fileLoadingCount = 0;
2118     }
2119     validate();
2120   }
2121
2122   public static int getViewCount(String alignmentId)
2123   {
2124     AlignmentViewport[] aps = getViewports(alignmentId);
2125     return (aps == null) ? 0 : aps.length;
2126   }
2127
2128   /**
2129    * 
2130    * @param alignmentId
2131    *          - if null, all sets are returned
2132    * @return all AlignmentPanels concerning the alignmentId sequence set
2133    */
2134   public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
2135   {
2136     if (Desktop.desktop == null)
2137     {
2138       // no frames created and in headless mode
2139       // TODO: verify that frames are recoverable when in headless mode
2140       return null;
2141     }
2142     List<AlignmentPanel> aps = new ArrayList<>();
2143     AlignFrame[] frames = Desktop.getDesktopAlignFrames();
2144     if (frames == null)
2145     {
2146       return null;
2147     }
2148     for (AlignFrame af : frames)
2149     {
2150       for (AlignmentPanel ap : af.alignPanels)
2151       {
2152         if (alignmentId == null
2153                 || alignmentId.equals(ap.av.getSequenceSetId()))
2154         {
2155           aps.add(ap);
2156         }
2157       }
2158     }
2159     if (aps.size() == 0)
2160     {
2161       return null;
2162     }
2163     AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
2164     return vap;
2165   }
2166
2167   /**
2168    * get all the viewports on an alignment.
2169    * 
2170    * @param sequenceSetId
2171    *          unique alignment id (may be null - all viewports returned in that
2172    *          case)
2173    * @return all viewports on the alignment bound to sequenceSetId
2174    */
2175   public static AlignmentViewport[] getViewports(String sequenceSetId)
2176   {
2177     List<AlignmentViewport> viewp = new ArrayList<>();
2178     if (desktop != null)
2179     {
2180       AlignFrame[] frames = Desktop.getDesktopAlignFrames();
2181
2182       for (AlignFrame afr : frames)
2183       {
2184         if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
2185                 .equals(sequenceSetId))
2186         {
2187           if (afr.alignPanels != null)
2188           {
2189             for (AlignmentPanel ap : afr.alignPanels)
2190             {
2191               if (sequenceSetId == null
2192                       || sequenceSetId.equals(ap.av.getSequenceSetId()))
2193               {
2194                 viewp.add(ap.av);
2195               }
2196             }
2197           }
2198           else
2199           {
2200             viewp.add(afr.getViewport());
2201           }
2202         }
2203       }
2204       if (viewp.size() > 0)
2205       {
2206         return viewp.toArray(new AlignmentViewport[viewp.size()]);
2207       }
2208     }
2209     return null;
2210   }
2211
2212   /**
2213    * Explode the views in the given frame into separate AlignFrame
2214    * 
2215    * @param af
2216    */
2217   public static void explodeViews(AlignFrame af)
2218   {
2219     int size = af.alignPanels.size();
2220     if (size < 2)
2221     {
2222       return;
2223     }
2224
2225     // FIXME: ideally should use UI interface API
2226     FeatureSettings viewFeatureSettings = (af.featureSettings != null
2227             && af.featureSettings.isOpen()) ? af.featureSettings : null;
2228     Rectangle fsBounds = af.getFeatureSettingsGeometry();
2229     for (int i = 0; i < size; i++)
2230     {
2231       AlignmentPanel ap = af.alignPanels.get(i);
2232
2233       AlignFrame newaf = new AlignFrame(ap);
2234
2235       // transfer reference for existing feature settings to new alignFrame
2236       if (ap == af.alignPanel)
2237       {
2238         if (viewFeatureSettings != null && viewFeatureSettings.fr.ap == ap)
2239         {
2240           newaf.featureSettings = viewFeatureSettings;
2241         }
2242         newaf.setFeatureSettingsGeometry(fsBounds);
2243       }
2244
2245       /*
2246        * Restore the view's last exploded frame geometry if known. Multiple views from
2247        * one exploded frame share and restore the same (frame) position and size.
2248        */
2249       Rectangle geometry = ap.av.getExplodedGeometry();
2250       if (geometry != null)
2251       {
2252         newaf.setBounds(geometry);
2253       }
2254
2255       ap.av.setGatherViewsHere(false);
2256
2257       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
2258               AlignFrame.DEFAULT_HEIGHT);
2259       // and materialise a new feature settings dialog instance for the new
2260       // alignframe
2261       // (closes the old as if 'OK' was pressed)
2262       if (ap == af.alignPanel && newaf.featureSettings != null
2263               && newaf.featureSettings.isOpen()
2264               && af.alignPanel.getAlignViewport().isShowSequenceFeatures())
2265       {
2266         newaf.showFeatureSettingsUI();
2267       }
2268     }
2269
2270     af.featureSettings = null;
2271     af.alignPanels.clear();
2272     af.closeMenuItem_actionPerformed(true);
2273
2274   }
2275
2276   /**
2277    * Gather expanded views (separate AlignFrame's) with the same sequence set
2278    * identifier back in to this frame as additional views, and close the
2279    * expanded views. Note the expanded frames may themselves have multiple
2280    * views. We take the lot.
2281    * 
2282    * @param source
2283    */
2284   public void gatherViews(AlignFrame source)
2285   {
2286     source.viewport.setGatherViewsHere(true);
2287     source.viewport.setExplodedGeometry(source.getBounds());
2288     JInternalFrame[] frames = desktop.getAllFrames();
2289     String viewId = source.viewport.getSequenceSetId();
2290     for (int t = 0; t < frames.length; t++)
2291     {
2292       if (frames[t] instanceof AlignFrame && frames[t] != source)
2293       {
2294         AlignFrame af = (AlignFrame) frames[t];
2295         boolean gatherThis = false;
2296         for (int a = 0; a < af.alignPanels.size(); a++)
2297         {
2298           AlignmentPanel ap = af.alignPanels.get(a);
2299           if (viewId.equals(ap.av.getSequenceSetId()))
2300           {
2301             gatherThis = true;
2302             ap.av.setGatherViewsHere(false);
2303             ap.av.setExplodedGeometry(af.getBounds());
2304             source.addAlignmentPanel(ap, false);
2305           }
2306         }
2307
2308         if (gatherThis)
2309         {
2310           if (af.featureSettings != null && af.featureSettings.isOpen())
2311           {
2312             if (source.featureSettings == null)
2313             {
2314               // preserve the feature settings geometry for this frame
2315               source.featureSettings = af.featureSettings;
2316               source.setFeatureSettingsGeometry(
2317                       af.getFeatureSettingsGeometry());
2318             }
2319             else
2320             {
2321               // close it and forget
2322               af.featureSettings.close();
2323             }
2324           }
2325           af.alignPanels.clear();
2326           af.closeMenuItem_actionPerformed(true);
2327         }
2328       }
2329     }
2330
2331     // refresh the feature setting UI for the source frame if it exists
2332     if (source.featureSettings != null && source.featureSettings.isOpen())
2333     {
2334       source.showFeatureSettingsUI();
2335     }
2336
2337   }
2338
2339   public JInternalFrame[] getAllFrames()
2340   {
2341     return desktop.getAllFrames();
2342   }
2343
2344   /**
2345    * Checks the given url to see if it gives a response indicating that the user
2346    * should be informed of a new questionnaire.
2347    * 
2348    * @param url
2349    */
2350   public void checkForQuestionnaire(String url)
2351   {
2352     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2353     // javax.swing.SwingUtilities.invokeLater(jvq);
2354     new Thread(jvq).start();
2355   }
2356
2357   public void checkURLLinks()
2358   {
2359     // Thread off the URL link checker
2360     addDialogThread(new Runnable()
2361     {
2362       @Override
2363       public void run()
2364       {
2365         if (Cache.getDefault("CHECKURLLINKS", true))
2366         {
2367           // check what the actual links are - if it's just the default don't
2368           // bother with the warning
2369           List<String> links = Preferences.sequenceUrlLinks
2370                   .getLinksForMenu();
2371
2372           // only need to check links if there is one with a
2373           // SEQUENCE_ID which is not the default EMBL_EBI link
2374           ListIterator<String> li = links.listIterator();
2375           boolean check = false;
2376           List<JLabel> urls = new ArrayList<>();
2377           while (li.hasNext())
2378           {
2379             String link = li.next();
2380             if (link.contains(jalview.util.UrlConstants.SEQUENCE_ID)
2381                     && !UrlConstants.isDefaultString(link))
2382             {
2383               check = true;
2384               int barPos = link.indexOf("|");
2385               String urlMsg = barPos == -1 ? link
2386                       : link.substring(0, barPos) + ": "
2387                               + link.substring(barPos + 1);
2388               urls.add(new JLabel(urlMsg));
2389             }
2390           }
2391           if (!check)
2392           {
2393             return;
2394           }
2395
2396           // ask user to check in case URL links use old style tokens
2397           // ($SEQUENCE_ID$ for sequence id _or_ accession id)
2398           JPanel msgPanel = new JPanel();
2399           msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
2400           msgPanel.add(Box.createVerticalGlue());
2401           JLabel msg = new JLabel(MessageManager
2402                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
2403           JLabel msg2 = new JLabel(MessageManager
2404                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
2405           msgPanel.add(msg);
2406           for (JLabel url : urls)
2407           {
2408             msgPanel.add(url);
2409           }
2410           msgPanel.add(msg2);
2411
2412           final JCheckBox jcb = new JCheckBox(
2413                   MessageManager.getString("label.do_not_display_again"));
2414           jcb.addActionListener(new ActionListener()
2415           {
2416             @Override
2417             public void actionPerformed(ActionEvent e)
2418             {
2419               // update Cache settings for "don't show this again"
2420               boolean showWarningAgain = !jcb.isSelected();
2421               Cache.setProperty("CHECKURLLINKS",
2422                       Boolean.valueOf(showWarningAgain).toString());
2423             }
2424           });
2425           msgPanel.add(jcb);
2426
2427           JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
2428                   MessageManager
2429                           .getString("label.SEQUENCE_ID_no_longer_used"),
2430                   JvOptionPane.WARNING_MESSAGE);
2431         }
2432       }
2433     });
2434   }
2435
2436   /**
2437    * Proxy class for JDesktopPane which optionally displays the current memory
2438    * usage and highlights the desktop area with a red bar if free memory runs
2439    * low.
2440    * 
2441    * @author AMW
2442    */
2443   public class MyDesktopPane extends JDesktopPane implements Runnable
2444   {
2445     private static final float ONE_MB = 1048576f;
2446
2447     boolean showMemoryUsage = false;
2448
2449     Runtime runtime;
2450
2451     java.text.NumberFormat df;
2452
2453     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2454             percentUsage;
2455
2456     public MyDesktopPane(boolean showMemoryUsage)
2457     {
2458       showMemoryUsage(showMemoryUsage);
2459     }
2460
2461     public void showMemoryUsage(boolean showMemory)
2462     {
2463       this.showMemoryUsage = showMemory;
2464       if (showMemory)
2465       {
2466         Thread worker = new Thread(this);
2467         worker.start();
2468       }
2469       repaint();
2470     }
2471
2472     public boolean isShowMemoryUsage()
2473     {
2474       return showMemoryUsage;
2475     }
2476
2477     @Override
2478     public void run()
2479     {
2480       df = java.text.NumberFormat.getNumberInstance();
2481       df.setMaximumFractionDigits(2);
2482       runtime = Runtime.getRuntime();
2483
2484       while (showMemoryUsage)
2485       {
2486         try
2487         {
2488           maxMemory = runtime.maxMemory() / ONE_MB;
2489           allocatedMemory = runtime.totalMemory() / ONE_MB;
2490           freeMemory = runtime.freeMemory() / ONE_MB;
2491           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2492
2493           percentUsage = (totalFreeMemory / maxMemory) * 100;
2494
2495           // if (percentUsage < 20)
2496           {
2497             // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2498             // Color.red);
2499             // instance.set.setBorder(border1);
2500           }
2501           repaint();
2502           // sleep after showing usage
2503           Thread.sleep(3000);
2504         } catch (Exception ex)
2505         {
2506           ex.printStackTrace();
2507         }
2508       }
2509     }
2510
2511     @Override
2512     public void paintComponent(Graphics g)
2513     {
2514       if (showMemoryUsage && g != null && df != null)
2515       {
2516         if (percentUsage < 20)
2517         {
2518           g.setColor(Color.red);
2519         }
2520         FontMetrics fm = g.getFontMetrics();
2521         if (fm != null)
2522         {
2523           g.drawString(MessageManager.formatMessage("label.memory_stats",
2524                   new Object[]
2525                   { df.format(totalFreeMemory), df.format(maxMemory),
2526                       df.format(percentUsage) }),
2527                   10, getHeight() - fm.getHeight());
2528         }
2529       }
2530
2531       // output debug scale message. Important for jalview.bin.HiDPISettingTest2
2532       Desktop.debugScaleMessage(Desktop.getDesktop().getGraphics());
2533     }
2534   }
2535
2536   /**
2537    * Accessor method to quickly get all the AlignmentFrames loaded.
2538    * 
2539    * @return an array of AlignFrame, or null if none found
2540    */
2541   @Override
2542   public AlignFrame[] getAlignFrames()
2543   {
2544     if (desktop == null)
2545     {
2546       return null;
2547     }
2548
2549     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2550
2551     if (frames == null)
2552     {
2553       return null;
2554     }
2555     List<AlignFrame> avp = new ArrayList<>();
2556     // REVERSE ORDER
2557     for (int i = frames.length - 1; i > -1; i--)
2558     {
2559       if (frames[i] instanceof AlignFrame)
2560       {
2561         avp.add((AlignFrame) frames[i]);
2562       }
2563       else if (frames[i] instanceof SplitFrame)
2564       {
2565         /*
2566          * Also check for a split frame containing an AlignFrame
2567          */
2568         GSplitFrame sf = (GSplitFrame) frames[i];
2569         if (sf.getTopFrame() instanceof AlignFrame)
2570         {
2571           avp.add((AlignFrame) sf.getTopFrame());
2572         }
2573         if (sf.getBottomFrame() instanceof AlignFrame)
2574         {
2575           avp.add((AlignFrame) sf.getBottomFrame());
2576         }
2577       }
2578     }
2579     if (avp.size() == 0)
2580     {
2581       return null;
2582     }
2583     AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2584     return afs;
2585   }
2586
2587   /**
2588    * static version
2589    */
2590   public static AlignFrame[] getDesktopAlignFrames()
2591   {
2592     if (Jalview.isHeadlessMode())
2593     {
2594       // Desktop.desktop is null in headless mode
2595       return Jalview.getInstance().getAlignFrames();
2596     }
2597
2598     if (instance != null && desktop != null)
2599     {
2600       return instance.getAlignFrames();
2601     }
2602
2603     return null;
2604   }
2605
2606   /**
2607    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2608    * 
2609    * @return
2610    */
2611   public GStructureViewer[] getJmols()
2612   {
2613     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2614
2615     if (frames == null)
2616     {
2617       return null;
2618     }
2619     List<GStructureViewer> avp = new ArrayList<>();
2620     // REVERSE ORDER
2621     for (int i = frames.length - 1; i > -1; i--)
2622     {
2623       if (frames[i] instanceof AppJmol)
2624       {
2625         GStructureViewer af = (GStructureViewer) frames[i];
2626         avp.add(af);
2627       }
2628     }
2629     if (avp.size() == 0)
2630     {
2631       return null;
2632     }
2633     GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2634     return afs;
2635   }
2636
2637   /**
2638    * Add Groovy Support to Jalview
2639    */
2640   @Override
2641   public void groovyShell_actionPerformed()
2642   {
2643     try
2644     {
2645       openGroovyConsole();
2646     } catch (Exception ex)
2647     {
2648       jalview.bin.Console.error("Groovy Console creation failed.", ex);
2649       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2650
2651               MessageManager.getString("label.couldnt_create_groovy_shell"),
2652               MessageManager.getString("label.groovy_support_failed"),
2653               JvOptionPane.ERROR_MESSAGE);
2654     }
2655   }
2656
2657   /**
2658    * Open the Groovy console
2659    */
2660   void openGroovyConsole()
2661   {
2662     if (groovyConsole == null)
2663     {
2664       JalviewObjectI j = new JalviewObject(this);
2665       groovyConsole = new groovy.console.ui.Console();
2666       groovyConsole.setVariable("Jalview", j);
2667       groovyConsole.setVariable("currentAlFrame", getCurrentAlignFrame());
2668       groovyConsole.run();
2669
2670       /*
2671        * We allow only one console at a time, so that AlignFrame menu option
2672        * 'Calculate | Run Groovy script' is unambiguous. Disable 'Groovy Console', and
2673        * enable 'Run script', when the console is opened, and the reverse when it is
2674        * closed
2675        */
2676       Window window = (Window) groovyConsole.getFrame();
2677       window.addWindowListener(new WindowAdapter()
2678       {
2679         @Override
2680         public void windowClosed(WindowEvent e)
2681         {
2682           /*
2683            * rebind CMD-Q from Groovy Console to Jalview Quit
2684            */
2685           addQuitHandler();
2686           enableExecuteGroovy(false);
2687         }
2688       });
2689     }
2690
2691     /*
2692      * show Groovy console window (after close and reopen)
2693      */
2694     ((Window) groovyConsole.getFrame()).setVisible(true);
2695
2696     /*
2697      * if we got this far, enable 'Run Groovy' in AlignFrame menus and disable
2698      * opening a second console
2699      */
2700     enableExecuteGroovy(true);
2701   }
2702
2703   /**
2704    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
2705    * binding when opened
2706    */
2707   protected void addQuitHandler()
2708   {
2709     getRootPane()
2710             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
2711                     KeyStroke
2712                             .getKeyStroke(KeyEvent.VK_Q,
2713                                     jalview.util.ShortcutKeyMaskExWrapper
2714                                             .getMenuShortcutKeyMaskEx()),
2715                     "Quit");
2716     getRootPane().getActionMap().put("Quit", new AbstractAction()
2717     {
2718       @Override
2719       public void actionPerformed(ActionEvent e)
2720       {
2721         desktopQuit();
2722       }
2723     });
2724   }
2725
2726   /**
2727    * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2728    * 
2729    * @param enabled
2730    *          true if Groovy console is open
2731    */
2732   public void enableExecuteGroovy(boolean enabled)
2733   {
2734     /*
2735      * disable opening a second Groovy console (or re-enable when the console is
2736      * closed)
2737      */
2738     groovyShell.setEnabled(!enabled);
2739
2740     AlignFrame[] alignFrames = getDesktopAlignFrames();
2741     if (alignFrames != null)
2742     {
2743       for (AlignFrame af : alignFrames)
2744       {
2745         af.setGroovyEnabled(enabled);
2746       }
2747     }
2748   }
2749
2750   /**
2751    * Progress bars managed by the IProgressIndicator method.
2752    */
2753   private Hashtable<Long, JPanel> progressBars;
2754
2755   private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2756
2757   /*
2758    * (non-Javadoc)
2759    * 
2760    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2761    */
2762   @Override
2763   public void setProgressBar(String message, long id)
2764   {
2765     if (progressBars == null)
2766     {
2767       progressBars = new Hashtable<>();
2768       progressBarHandlers = new Hashtable<>();
2769     }
2770
2771     if (progressBars.get(Long.valueOf(id)) != null)
2772     {
2773       JPanel panel = progressBars.remove(Long.valueOf(id));
2774       if (progressBarHandlers.contains(Long.valueOf(id)))
2775       {
2776         progressBarHandlers.remove(Long.valueOf(id));
2777       }
2778       removeProgressPanel(panel);
2779     }
2780     else
2781     {
2782       progressBars.put(Long.valueOf(id), addProgressPanel(message));
2783     }
2784   }
2785
2786   /*
2787    * (non-Javadoc)
2788    * 
2789    * @see jalview.gui.IProgressIndicator#registerHandler(long,
2790    * jalview.gui.IProgressIndicatorHandler)
2791    */
2792   @Override
2793   public void registerHandler(final long id,
2794           final IProgressIndicatorHandler handler)
2795   {
2796     if (progressBarHandlers == null
2797             || !progressBars.containsKey(Long.valueOf(id)))
2798     {
2799       throw new Error(MessageManager.getString(
2800               "error.call_setprogressbar_before_registering_handler"));
2801     }
2802     progressBarHandlers.put(Long.valueOf(id), handler);
2803     final JPanel progressPanel = progressBars.get(Long.valueOf(id));
2804     if (handler.canCancel())
2805     {
2806       JButton cancel = new JButton(
2807               MessageManager.getString("action.cancel"));
2808       final IProgressIndicator us = this;
2809       cancel.addActionListener(new ActionListener()
2810       {
2811
2812         @Override
2813         public void actionPerformed(ActionEvent e)
2814         {
2815           handler.cancelActivity(id);
2816           us.setProgressBar(MessageManager
2817                   .formatMessage("label.cancelled_params", new Object[]
2818                   { ((JLabel) progressPanel.getComponent(0)).getText() }),
2819                   id);
2820         }
2821       });
2822       progressPanel.add(cancel, BorderLayout.EAST);
2823     }
2824   }
2825
2826   /**
2827    * 
2828    * @return true if any progress bars are still active
2829    */
2830   @Override
2831   public boolean operationInProgress()
2832   {
2833     if (progressBars != null && progressBars.size() > 0)
2834     {
2835       return true;
2836     }
2837     return false;
2838   }
2839
2840   /**
2841    * This will return the first AlignFrame holding the given viewport instance.
2842    * It will break if there are more than one AlignFrames viewing a particular
2843    * av.
2844    * 
2845    * @param viewport
2846    * @return alignFrame for viewport
2847    */
2848   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2849   {
2850     if (desktop != null)
2851     {
2852       AlignmentPanel[] aps = getAlignmentPanels(
2853               viewport.getSequenceSetId());
2854       for (int panel = 0; aps != null && panel < aps.length; panel++)
2855       {
2856         if (aps[panel] != null && aps[panel].av == viewport)
2857         {
2858           return aps[panel].alignFrame;
2859         }
2860       }
2861     }
2862     return null;
2863   }
2864
2865   public VamsasApplication getVamsasApplication()
2866   {
2867     // TODO: JAL-3311 remove remaining code from Jalview relating to VAMSAS
2868     return null;
2869
2870   }
2871
2872   /**
2873    * flag set if jalview GUI is being operated programmatically
2874    */
2875   private boolean inBatchMode = false;
2876
2877   /**
2878    * check if jalview GUI is being operated programmatically
2879    * 
2880    * @return inBatchMode
2881    */
2882   public boolean isInBatchMode()
2883   {
2884     return inBatchMode;
2885   }
2886
2887   /**
2888    * set flag if jalview GUI is being operated programmatically
2889    * 
2890    * @param inBatchMode
2891    */
2892   public void setInBatchMode(boolean inBatchMode)
2893   {
2894     this.inBatchMode = inBatchMode;
2895   }
2896
2897   /**
2898    * start service discovery and wait till it is done
2899    */
2900   public void startServiceDiscovery()
2901   {
2902     startServiceDiscovery(false);
2903   }
2904
2905   /**
2906    * start service discovery threads - blocking or non-blocking
2907    * 
2908    * @param blocking
2909    */
2910   public void startServiceDiscovery(boolean blocking)
2911   {
2912     startServiceDiscovery(blocking, false);
2913   }
2914
2915   /**
2916    * start service discovery threads
2917    * 
2918    * @param blocking
2919    *          - false means call returns immediately
2920    * @param ignore_SHOW_JWS2_SERVICES_preference
2921    *          - when true JABA services are discovered regardless of user's JWS2
2922    *          discovery preference setting
2923    */
2924   public void startServiceDiscovery(boolean blocking,
2925           boolean ignore_SHOW_JWS2_SERVICES_preference)
2926   {
2927     boolean alive = true;
2928     Thread t0 = null, t1 = null, t2 = null;
2929     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
2930     if (true)
2931     {
2932       // todo: changesupport handlers need to be transferred
2933       if (discoverer == null)
2934       {
2935         discoverer = new jalview.ws.jws1.Discoverer();
2936         // register PCS handler for desktop.
2937         discoverer.addPropertyChangeListener(changeSupport);
2938       }
2939       // JAL-940 - disabled JWS1 service configuration - always start discoverer
2940       // until we phase out completely
2941       (t0 = new Thread(discoverer)).start();
2942     }
2943
2944     if (ignore_SHOW_JWS2_SERVICES_preference
2945             || Cache.getDefault("SHOW_JWS2_SERVICES", true))
2946     {
2947       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2948               .startDiscoverer(changeSupport);
2949     }
2950     Thread t3 = null;
2951     {
2952       // TODO: do rest service discovery
2953     }
2954     if (blocking)
2955     {
2956       while (alive)
2957       {
2958         try
2959         {
2960           Thread.sleep(15);
2961         } catch (Exception e)
2962         {
2963         }
2964         alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
2965                 || (t3 != null && t3.isAlive())
2966                 || (t0 != null && t0.isAlive());
2967       }
2968     }
2969   }
2970
2971   /**
2972    * called to check if the service discovery process completed successfully.
2973    * 
2974    * @param evt
2975    */
2976   protected void JalviewServicesChanged(PropertyChangeEvent evt)
2977   {
2978     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2979     {
2980       final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2981               .getErrorMessages();
2982       if (ermsg != null)
2983       {
2984         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2985         {
2986           if (serviceChangedDialog == null)
2987           {
2988             // only run if we aren't already displaying one of these.
2989             addDialogThread(serviceChangedDialog = new Runnable()
2990             {
2991               @Override
2992               public void run()
2993               {
2994
2995                 /*
2996                  * JalviewDialog jd =new JalviewDialog() {
2997                  * 
2998                  * @Override protected void cancelPressed() { // TODO Auto-generated method stub
2999                  * 
3000                  * }@Override protected void okPressed() { // TODO Auto-generated method stub
3001                  * 
3002                  * }@Override protected void raiseClosed() { // TODO Auto-generated method stub
3003                  * 
3004                  * } }; jd.initDialogFrame(new JLabel("<html><table width=\"450\"><tr><td>" +
3005                  * ermsg +
3006                  * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
3007                  * + " or mis-configured HTTP proxy settings.<br/>" +
3008                  * "Check the <em>Connections</em> and <em>Web services</em> tab of the" +
3009                  * " Tools->Preferences dialog box to change them.</td></tr></table></html>" ),
3010                  * true, true, "Web Service Configuration Problem", 450, 400);
3011                  * 
3012                  * jd.waitForInput();
3013                  */
3014                 JvOptionPane.showConfirmDialog(Desktop.desktop,
3015                         new JLabel("<html><table width=\"450\"><tr><td>"
3016                                 + ermsg + "</td></tr></table>"
3017                                 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
3018                                 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
3019                                 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
3020                                 + " Tools->Preferences dialog box to change them.</p></html>"),
3021                         "Web Service Configuration Problem",
3022                         JvOptionPane.DEFAULT_OPTION,
3023                         JvOptionPane.ERROR_MESSAGE);
3024                 serviceChangedDialog = null;
3025
3026               }
3027             });
3028           }
3029         }
3030         else
3031         {
3032           jalview.bin.Console.error(
3033                   "Errors reported by JABA discovery service. Check web services preferences.\n"
3034                           + ermsg);
3035         }
3036       }
3037     }
3038   }
3039
3040   private Runnable serviceChangedDialog = null;
3041
3042   /**
3043    * start a thread to open a URL in the configured browser. Pops up a warning
3044    * dialog to the user if there is an exception when calling out to the browser
3045    * to open the URL.
3046    * 
3047    * @param url
3048    */
3049   public static void showUrl(final String url)
3050   {
3051     showUrl(url, Desktop.instance);
3052   }
3053
3054   /**
3055    * Like showUrl but allows progress handler to be specified
3056    * 
3057    * @param url
3058    * @param progress
3059    *          (null) or object implementing IProgressIndicator
3060    */
3061   public static void showUrl(final String url,
3062           final IProgressIndicator progress)
3063   {
3064     new Thread(new Runnable()
3065     {
3066       @Override
3067       public void run()
3068       {
3069         try
3070         {
3071           if (progress != null)
3072           {
3073             progress.setProgressBar(MessageManager
3074                     .formatMessage("status.opening_params", new Object[]
3075                     { url }), this.hashCode());
3076           }
3077           jalview.util.BrowserLauncher.openURL(url);
3078         } catch (Exception ex)
3079         {
3080           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3081                   MessageManager
3082                           .getString("label.web_browser_not_found_unix"),
3083                   MessageManager.getString("label.web_browser_not_found"),
3084                   JvOptionPane.WARNING_MESSAGE);
3085
3086           ex.printStackTrace();
3087         }
3088         if (progress != null)
3089         {
3090           progress.setProgressBar(null, this.hashCode());
3091         }
3092       }
3093     }).start();
3094   }
3095
3096   public static WsParamSetManager wsparamManager = null;
3097
3098   public static ParamManager getUserParameterStore()
3099   {
3100     if (wsparamManager == null)
3101     {
3102       wsparamManager = new WsParamSetManager();
3103     }
3104     return wsparamManager;
3105   }
3106
3107   /**
3108    * static hyperlink handler proxy method for use by Jalview's internal windows
3109    * 
3110    * @param e
3111    */
3112   public static void hyperlinkUpdate(HyperlinkEvent e)
3113   {
3114     if (e.getEventType() == EventType.ACTIVATED)
3115     {
3116       String url = null;
3117       try
3118       {
3119         url = e.getURL().toString();
3120         Desktop.showUrl(url);
3121       } catch (Exception x)
3122       {
3123         if (url != null)
3124         {
3125           jalview.bin.Console
3126                   .error("Couldn't handle string " + url + " as a URL.");
3127         }
3128         // ignore any exceptions due to dud links.
3129       }
3130
3131     }
3132   }
3133
3134   /**
3135    * single thread that handles display of dialogs to user.
3136    */
3137   ExecutorService dialogExecutor = Executors.newFixedThreadPool(3);
3138
3139   /**
3140    * flag indicating if dialogExecutor should try to acquire a permit
3141    */
3142   private volatile boolean dialogPause = true;
3143
3144   /**
3145    * pause the queue
3146    */
3147   private Semaphore block = new Semaphore(0);
3148
3149   private static groovy.console.ui.Console groovyConsole;
3150
3151   /**
3152    * add another dialog thread to the queue
3153    * 
3154    * @param prompter
3155    */
3156   public void addDialogThread(final Runnable prompter)
3157   {
3158     dialogExecutor.submit(new Runnable()
3159     {
3160       @Override
3161       public void run()
3162       {
3163         if (dialogPause)
3164         {
3165           acquireDialogQueue();
3166         }
3167         if (instance == null)
3168         {
3169           return;
3170         }
3171         try
3172         {
3173           SwingUtilities.invokeAndWait(prompter);
3174         } catch (Exception q)
3175         {
3176           jalview.bin.Console.warn("Unexpected Exception in dialog thread.",
3177                   q);
3178         }
3179       }
3180     });
3181   }
3182
3183   private boolean dialogQueueStarted = false;
3184
3185   public void startDialogQueue()
3186   {
3187     if (dialogQueueStarted)
3188     {
3189       return;
3190     }
3191     // set the flag so we don't pause waiting for another permit and semaphore
3192     // the current task to begin
3193     releaseDialogQueue();
3194     dialogQueueStarted = true;
3195   }
3196
3197   public void acquireDialogQueue()
3198   {
3199     try
3200     {
3201       block.acquire();
3202       dialogPause = true;
3203     } catch (InterruptedException e)
3204     {
3205       jalview.bin.Console.debug("Interruption when acquiring DialogueQueue",
3206               e);
3207     }
3208   }
3209
3210   public void releaseDialogQueue()
3211   {
3212     if (!dialogPause)
3213     {
3214       return;
3215     }
3216     block.release();
3217     dialogPause = false;
3218   }
3219
3220   /**
3221    * Outputs an image of the desktop to file in EPS format, after prompting the
3222    * user for choice of Text or Lineart character rendering (unless a preference
3223    * has been set). The file name is generated as
3224    * 
3225    * <pre>
3226    * Jalview_snapshot_nnnnn.eps where nnnnn is the current timestamp in milliseconds
3227    * </pre>
3228    */
3229   @Override
3230   protected void snapShotWindow_actionPerformed(ActionEvent e)
3231   {
3232     // currently the menu option to do this is not shown
3233     invalidate();
3234
3235     int width = getWidth();
3236     int height = getHeight();
3237     File of = new File(
3238             "Jalview_snapshot_" + System.currentTimeMillis() + ".eps");
3239     ImageWriterI writer = new ImageWriterI()
3240     {
3241       @Override
3242       public void exportImage(Graphics g) throws Exception
3243       {
3244         paintAll(g);
3245         jalview.bin.Console.info("Successfully written snapshot to file "
3246                 + of.getAbsolutePath());
3247       }
3248     };
3249     String title = "View of desktop";
3250     ImageExporter exporter = new ImageExporter(writer, null, TYPE.EPS,
3251             title);
3252     try
3253     {
3254       exporter.doExport(of, this, width, height, title);
3255     } catch (ImageOutputException ioex)
3256     {
3257       jalview.bin.Console.error(
3258               "Unexpected error whilst writing Jalview desktop snapshot as EPS",
3259               ioex);
3260     }
3261   }
3262
3263   /**
3264    * Explode the views in the given SplitFrame into separate SplitFrame windows.
3265    * This respects (remembers) any previous 'exploded geometry' i.e. the size
3266    * and location last time the view was expanded (if any). However it does not
3267    * remember the split pane divider location - this is set to match the
3268    * 'exploding' frame.
3269    * 
3270    * @param sf
3271    */
3272   public void explodeViews(SplitFrame sf)
3273   {
3274     AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3275     AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3276     List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3277             .getAlignPanels();
3278     List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3279             .getAlignPanels();
3280     int viewCount = topPanels.size();
3281     if (viewCount < 2)
3282     {
3283       return;
3284     }
3285
3286     /*
3287      * Processing in reverse order works, forwards order leaves the first panels not
3288      * visible. I don't know why!
3289      */
3290     for (int i = viewCount - 1; i >= 0; i--)
3291     {
3292       /*
3293        * Make new top and bottom frames. These take over the respective AlignmentPanel
3294        * objects, including their AlignmentViewports, so the cdna/protein
3295        * relationships between the viewports is carried over to the new split frames.
3296        * 
3297        * explodedGeometry holds the (x, y) position of the previously exploded
3298        * SplitFrame, and the (width, height) of the AlignFrame component
3299        */
3300       AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3301       AlignFrame newTopFrame = new AlignFrame(topPanel);
3302       newTopFrame.setSize(oldTopFrame.getSize());
3303       newTopFrame.setVisible(true);
3304       Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3305               .getExplodedGeometry();
3306       if (geometry != null)
3307       {
3308         newTopFrame.setSize(geometry.getSize());
3309       }
3310
3311       AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3312       AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3313       newBottomFrame.setSize(oldBottomFrame.getSize());
3314       newBottomFrame.setVisible(true);
3315       geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3316               .getExplodedGeometry();
3317       if (geometry != null)
3318       {
3319         newBottomFrame.setSize(geometry.getSize());
3320       }
3321
3322       topPanel.av.setGatherViewsHere(false);
3323       bottomPanel.av.setGatherViewsHere(false);
3324       JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3325               newBottomFrame);
3326       if (geometry != null)
3327       {
3328         splitFrame.setLocation(geometry.getLocation());
3329       }
3330       Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3331     }
3332
3333     /*
3334      * Clear references to the panels (now relocated in the new SplitFrames) before
3335      * closing the old SplitFrame.
3336      */
3337     topPanels.clear();
3338     bottomPanels.clear();
3339     sf.close();
3340   }
3341
3342   /**
3343    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3344    * back into the given SplitFrame as additional views. Note that the gathered
3345    * frames may themselves have multiple views.
3346    * 
3347    * @param source
3348    */
3349   public void gatherViews(GSplitFrame source)
3350   {
3351     /*
3352      * special handling of explodedGeometry for a view within a SplitFrame: - it
3353      * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3354      * height) of the AlignFrame component
3355      */
3356     AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3357     AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3358     myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3359             source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3360     myBottomFrame.viewport
3361             .setExplodedGeometry(new Rectangle(source.getX(), source.getY(),
3362                     myBottomFrame.getWidth(), myBottomFrame.getHeight()));
3363     myTopFrame.viewport.setGatherViewsHere(true);
3364     myBottomFrame.viewport.setGatherViewsHere(true);
3365     String topViewId = myTopFrame.viewport.getSequenceSetId();
3366     String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3367
3368     JInternalFrame[] frames = desktop.getAllFrames();
3369     for (JInternalFrame frame : frames)
3370     {
3371       if (frame instanceof SplitFrame && frame != source)
3372       {
3373         SplitFrame sf = (SplitFrame) frame;
3374         AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3375         AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3376         boolean gatherThis = false;
3377         for (int a = 0; a < topFrame.alignPanels.size(); a++)
3378         {
3379           AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3380           AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3381           if (topViewId.equals(topPanel.av.getSequenceSetId())
3382                   && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3383           {
3384             gatherThis = true;
3385             topPanel.av.setGatherViewsHere(false);
3386             bottomPanel.av.setGatherViewsHere(false);
3387             topPanel.av.setExplodedGeometry(
3388                     new Rectangle(sf.getLocation(), topFrame.getSize()));
3389             bottomPanel.av.setExplodedGeometry(
3390                     new Rectangle(sf.getLocation(), bottomFrame.getSize()));
3391             myTopFrame.addAlignmentPanel(topPanel, false);
3392             myBottomFrame.addAlignmentPanel(bottomPanel, false);
3393           }
3394         }
3395
3396         if (gatherThis)
3397         {
3398           topFrame.getAlignPanels().clear();
3399           bottomFrame.getAlignPanels().clear();
3400           sf.close();
3401         }
3402       }
3403     }
3404
3405     /*
3406      * The dust settles...give focus to the tab we did this from.
3407      */
3408     myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3409   }
3410
3411   public static groovy.console.ui.Console getGroovyConsole()
3412   {
3413     return groovyConsole;
3414   }
3415
3416   /**
3417    * handles the payload of a drag and drop event.
3418    * 
3419    * TODO refactor to desktop utilities class
3420    * 
3421    * @param files
3422    *          - Data source strings extracted from the drop event
3423    * @param protocols
3424    *          - protocol for each data source extracted from the drop event
3425    * @param evt
3426    *          - the drop event
3427    * @param t
3428    *          - the payload from the drop event
3429    * @throws Exception
3430    */
3431   public static void transferFromDropTarget(List<Object> files,
3432           List<DataSourceType> protocols, DropTargetDropEvent evt,
3433           Transferable t) throws Exception
3434   {
3435
3436     DataFlavor uriListFlavor = new DataFlavor(
3437             "text/uri-list;class=java.lang.String"), urlFlavour = null;
3438     try
3439     {
3440       urlFlavour = new DataFlavor(
3441               "application/x-java-url; class=java.net.URL");
3442     } catch (ClassNotFoundException cfe)
3443     {
3444       jalview.bin.Console.debug("Couldn't instantiate the URL dataflavor.",
3445               cfe);
3446     }
3447
3448     if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
3449     {
3450
3451       try
3452       {
3453         java.net.URL url = (URL) t.getTransferData(urlFlavour);
3454         // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
3455         // means url may be null.
3456         if (url != null)
3457         {
3458           protocols.add(DataSourceType.URL);
3459           files.add(url.toString());
3460           jalview.bin.Console.debug("Drop handled as URL dataflavor "
3461                   + files.get(files.size() - 1));
3462           return;
3463         }
3464         else
3465         {
3466           if (Platform.isAMacAndNotJS())
3467           {
3468             jalview.bin.Console.errPrintln(
3469                     "Please ignore plist error - occurs due to problem with java 8 on OSX");
3470           }
3471         }
3472       } catch (Throwable ex)
3473       {
3474         jalview.bin.Console.debug("URL drop handler failed.", ex);
3475       }
3476     }
3477     if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3478     {
3479       // Works on Windows and MacOSX
3480       jalview.bin.Console.debug("Drop handled as javaFileListFlavor");
3481       for (Object file : (List) t
3482               .getTransferData(DataFlavor.javaFileListFlavor))
3483       {
3484         files.add(file);
3485         protocols.add(DataSourceType.FILE);
3486       }
3487     }
3488     else
3489     {
3490       // Unix like behaviour
3491       boolean added = false;
3492       String data = null;
3493       if (t.isDataFlavorSupported(uriListFlavor))
3494       {
3495         jalview.bin.Console.debug("Drop handled as uriListFlavor");
3496         // This is used by Unix drag system
3497         data = (String) t.getTransferData(uriListFlavor);
3498       }
3499       if (data == null)
3500       {
3501         // fallback to text: workaround - on OSX where there's a JVM bug
3502         jalview.bin.Console
3503                 .debug("standard URIListFlavor failed. Trying text");
3504         // try text fallback
3505         DataFlavor textDf = new DataFlavor(
3506                 "text/plain;class=java.lang.String");
3507         if (t.isDataFlavorSupported(textDf))
3508         {
3509           data = (String) t.getTransferData(textDf);
3510         }
3511
3512         jalview.bin.Console.debug("Plain text drop content returned "
3513                 + (data == null ? "Null - failed" : data));
3514
3515       }
3516       if (data != null)
3517       {
3518         while (protocols.size() < files.size())
3519         {
3520           jalview.bin.Console.debug("Adding missing FILE protocol for "
3521                   + files.get(protocols.size()));
3522           protocols.add(DataSourceType.FILE);
3523         }
3524         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3525                 data, "\r\n"); st.hasMoreTokens();)
3526         {
3527           added = true;
3528           String s = st.nextToken();
3529           if (s.startsWith("#"))
3530           {
3531             // the line is a comment (as per the RFC 2483)
3532             continue;
3533           }
3534           java.net.URI uri = new java.net.URI(s);
3535           if (uri.getScheme().toLowerCase(Locale.ROOT).startsWith("http"))
3536           {
3537             protocols.add(DataSourceType.URL);
3538             files.add(uri.toString());
3539           }
3540           else
3541           {
3542             // otherwise preserve old behaviour: catch all for file objects
3543             java.io.File file = new java.io.File(uri);
3544             protocols.add(DataSourceType.FILE);
3545             files.add(file.toString());
3546           }
3547         }
3548       }
3549
3550       if (jalview.bin.Console.isDebugEnabled())
3551       {
3552         if (data == null || !added)
3553         {
3554
3555           if (t.getTransferDataFlavors() != null
3556                   && t.getTransferDataFlavors().length > 0)
3557           {
3558             jalview.bin.Console.debug(
3559                     "Couldn't resolve drop data. Here are the supported flavors:");
3560             for (DataFlavor fl : t.getTransferDataFlavors())
3561             {
3562               jalview.bin.Console.debug(
3563                       "Supported transfer dataflavor: " + fl.toString());
3564               Object df = t.getTransferData(fl);
3565               if (df != null)
3566               {
3567                 jalview.bin.Console.debug("Retrieves: " + df);
3568               }
3569               else
3570               {
3571                 jalview.bin.Console.debug("Retrieved nothing");
3572               }
3573             }
3574           }
3575           else
3576           {
3577             jalview.bin.Console
3578                     .debug("Couldn't resolve dataflavor for drop: "
3579                             + t.toString());
3580           }
3581         }
3582       }
3583     }
3584     if (Platform.isWindowsAndNotJS())
3585     {
3586       jalview.bin.Console
3587               .debug("Scanning dropped content for Windows Link Files");
3588
3589       // resolve any .lnk files in the file drop
3590       for (int f = 0; f < files.size(); f++)
3591       {
3592         String source = files.get(f).toString().toLowerCase(Locale.ROOT);
3593         if (protocols.get(f).equals(DataSourceType.FILE)
3594                 && (source.endsWith(".lnk") || source.endsWith(".url")
3595                         || source.endsWith(".site")))
3596         {
3597           try
3598           {
3599             Object obj = files.get(f);
3600             File lf = (obj instanceof File ? (File) obj
3601                     : new File((String) obj));
3602             // process link file to get a URL
3603             jalview.bin.Console.debug("Found potential link file: " + lf);
3604             WindowsShortcut wscfile = new WindowsShortcut(lf);
3605             String fullname = wscfile.getRealFilename();
3606             protocols.set(f, FormatAdapter.checkProtocol(fullname));
3607             files.set(f, fullname);
3608             jalview.bin.Console.debug("Parsed real filename " + fullname
3609                     + " to extract protocol: " + protocols.get(f));
3610           } catch (Exception ex)
3611           {
3612             jalview.bin.Console.error(
3613                     "Couldn't parse " + files.get(f) + " as a link file.",
3614                     ex);
3615           }
3616         }
3617       }
3618     }
3619   }
3620
3621   /**
3622    * Sets the Preferences property for experimental features to True or False
3623    * depending on the state of the controlling menu item
3624    */
3625   @Override
3626   protected void showExperimental_actionPerformed(boolean selected)
3627   {
3628     Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
3629   }
3630
3631   /**
3632    * Answers a (possibly empty) list of any structure viewer frames (currently
3633    * for either Jmol or Chimera) which are currently open. This may optionally
3634    * be restricted to viewers of a specified class, or viewers linked to a
3635    * specified alignment panel.
3636    * 
3637    * @param apanel
3638    *          if not null, only return viewers linked to this panel
3639    * @param structureViewerClass
3640    *          if not null, only return viewers of this class
3641    * @return
3642    */
3643   public List<StructureViewerBase> getStructureViewers(
3644           AlignmentPanel apanel,
3645           Class<? extends StructureViewerBase> structureViewerClass)
3646   {
3647     List<StructureViewerBase> result = new ArrayList<>();
3648     JInternalFrame[] frames = Desktop.instance.getAllFrames();
3649
3650     for (JInternalFrame frame : frames)
3651     {
3652       if (frame instanceof StructureViewerBase)
3653       {
3654         if (structureViewerClass == null
3655                 || structureViewerClass.isInstance(frame))
3656         {
3657           if (apanel == null
3658                   || ((StructureViewerBase) frame).isLinkedWith(apanel))
3659           {
3660             result.add((StructureViewerBase) frame);
3661           }
3662         }
3663       }
3664     }
3665     return result;
3666   }
3667
3668   public static final String debugScaleMessage = "Desktop graphics transform scale=";
3669
3670   private static boolean debugScaleMessageDone = false;
3671
3672   public static void debugScaleMessage(Graphics g)
3673   {
3674     if (debugScaleMessageDone)
3675     {
3676       return;
3677     }
3678     // output used by tests to check HiDPI scaling settings in action
3679     try
3680     {
3681       Graphics2D gg = (Graphics2D) g;
3682       if (gg != null)
3683       {
3684         AffineTransform t = gg.getTransform();
3685         double scaleX = t.getScaleX();
3686         double scaleY = t.getScaleY();
3687         jalview.bin.Console.debug(debugScaleMessage + scaleX + " (X)");
3688         jalview.bin.Console.debug(debugScaleMessage + scaleY + " (Y)");
3689         debugScaleMessageDone = true;
3690       }
3691       else
3692       {
3693         jalview.bin.Console.debug("Desktop graphics null");
3694       }
3695     } catch (Exception e)
3696     {
3697       jalview.bin.Console.debug(Cache.getStackTraceString(e));
3698     }
3699   }
3700
3701   /**
3702    * closes the current instance window, disposes and forgets about it.
3703    */
3704   public static void closeDesktop()
3705   {
3706     if (Desktop.instance != null)
3707     {
3708       Desktop.instance.closeAll_actionPerformed(null);
3709       Desktop.instance.setVisible(false);
3710       Desktop us = Desktop.instance;
3711       Desktop.instance = null;
3712       // call dispose in a separate thread - try to avoid indirect deadlocks
3713       new Thread(new Runnable()
3714       {
3715         @Override
3716         public void run()
3717         {
3718           ExecutorService dex = us.dialogExecutor;
3719           if (dex != null)
3720           {
3721             dex.shutdownNow();
3722             us.dialogExecutor = null;
3723             us.block.drainPermits();
3724           }
3725           us.dispose();
3726         }
3727       }).start();
3728     }
3729   }
3730
3731   /**
3732    * checks if any progress bars are being displayed in any of the windows
3733    * managed by the desktop
3734    * 
3735    * @return
3736    */
3737   public boolean operationsAreInProgress()
3738   {
3739     JInternalFrame[] frames = getAllFrames();
3740     for (JInternalFrame frame : frames)
3741     {
3742       if (frame instanceof IProgressIndicator)
3743       {
3744         if (((IProgressIndicator) frame).operationInProgress())
3745         {
3746           return true;
3747         }
3748       }
3749     }
3750     return operationInProgress();
3751   }
3752
3753   /**
3754    * keep track of modal JvOptionPanes open as modal dialogs for AlignFrames.
3755    * The way the modal JInternalFrame is made means it cannot be a child of an
3756    * AlignFrame, so closing the AlignFrame might leave the modal open :(
3757    */
3758   private static Map<AlignFrame, JInternalFrame> alignFrameModalMap = new HashMap<>();
3759
3760   protected static void addModal(AlignFrame af, JInternalFrame jif)
3761   {
3762     alignFrameModalMap.put(af, jif);
3763   }
3764
3765   protected static void closeModal(AlignFrame af)
3766   {
3767     if (!alignFrameModalMap.containsKey(af))
3768     {
3769       return;
3770     }
3771     JInternalFrame jif = alignFrameModalMap.get(af);
3772     if (jif != null)
3773     {
3774       try
3775       {
3776         jif.setClosed(true);
3777       } catch (PropertyVetoException e)
3778       {
3779         e.printStackTrace();
3780       }
3781     }
3782     alignFrameModalMap.remove(af);
3783   }
3784
3785   public void nonBlockingDialog(String title, String message, String button,
3786           int type, boolean scrollable, boolean modal)
3787   {
3788     nonBlockingDialog(title, message, null, button, type, scrollable, false,
3789             modal, -1);
3790   }
3791
3792   public void nonBlockingDialog(String title, String message,
3793           String boxtext, String button, int type, boolean scrollable,
3794           boolean html, boolean modal, int timeout)
3795   {
3796     nonBlockingDialog(32, 2, title, message, boxtext, button, type,
3797             scrollable, html, modal, timeout);
3798   }
3799
3800   public void nonBlockingDialog(int width, int height, String title,
3801           String message, String boxtext, String button, int type,
3802           boolean scrollable, boolean html, boolean modal, int timeout)
3803   {
3804     if (type < 0)
3805     {
3806       type = JvOptionPane.WARNING_MESSAGE;
3807     }
3808     JLabel jl = new JLabel(message);
3809
3810     JTextComponent jtc = null;
3811     if (html)
3812     {
3813       JTextPane jtp = new JTextPane();
3814       jtp.setContentType("text/html");
3815       jtp.setEditable(false);
3816       jtp.setAutoscrolls(true);
3817       jtp.setText(boxtext);
3818
3819       jtc = jtp;
3820     }
3821     else
3822     {
3823       JTextArea jta = new JTextArea(height, width);
3824       // jta.setLineWrap(true);
3825       jta.setEditable(false);
3826       jta.setWrapStyleWord(true);
3827       jta.setAutoscrolls(true);
3828       jta.setText(boxtext);
3829
3830       jtc = jta;
3831     }
3832
3833     JScrollPane jsp = scrollable
3834             ? new JScrollPane(jtc, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
3835                     JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
3836             : null;
3837
3838     JvOptionPane jvp = JvOptionPane.newOptionDialog(this);
3839
3840     JPanel jp = new JPanel();
3841     jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
3842
3843     if (message != null)
3844     {
3845       jl.setAlignmentX(Component.LEFT_ALIGNMENT);
3846       jp.add(jl);
3847     }
3848     if (boxtext != null)
3849     {
3850       if (scrollable)
3851       {
3852         jsp.setAlignmentX(Component.LEFT_ALIGNMENT);
3853         jp.add(jsp);
3854       }
3855       else
3856       {
3857         jtc.setAlignmentX(Component.LEFT_ALIGNMENT);
3858         jp.add(jtc);
3859       }
3860     }
3861
3862     jvp.setResponseHandler(JOptionPane.YES_OPTION, () -> {
3863     });
3864     jvp.setTimeout(timeout);
3865     JButton jb = new JButton(button);
3866     jvp.showDialogOnTopAsync(this, jp, title, JOptionPane.YES_OPTION, type,
3867             null, new Object[]
3868             { button }, button, modal, new JButton[] { jb }, false);
3869   }
3870
3871   @Override
3872   public AlignFrame getCurrentAlignFrame()
3873   {
3874     return Jalview.getInstance().getCurrentAlignFrame();
3875   }
3876 }