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