JAL-3599 Deliberate NPE to see if build plan fails
[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         System.err.println(
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     if (!Platform.isJS())
540     /**
541      * Java only
542      * 
543      * @j2sIgnore
544      */
545     {
546       jconsole = new Console(this, showjconsole);
547       jconsole.setHeader(Cache.getVersionDetailsForConsole());
548       showConsole(showjconsole);
549
550       showNews.setVisible(false);
551
552       experimentalFeatures.setSelected(showExperimental());
553
554       getIdentifiersOrgData();
555
556       checkURLLinks();
557
558       // Spawn a thread that shows the splashscreen
559       if (!nosplash)
560       {
561         SwingUtilities.invokeLater(new Runnable()
562         {
563           @Override
564           public void run()
565           {
566             new SplashScreen(true);
567           }
568         });
569       }
570
571       // Thread off a new instance of the file chooser - this reduces the time
572       // it
573       // takes to open it later on.
574       new Thread(new Runnable()
575       {
576         @Override
577         public void run()
578         {
579           jalview.bin.Console.debug("Filechooser init thread started.");
580           String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
581           JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
582                   fileFormat);
583           jalview.bin.Console.debug("Filechooser init thread finished.");
584         }
585       }).start();
586       // Add the service change listener
587       changeSupport.addJalviewPropertyChangeListener("services",
588               new PropertyChangeListener()
589               {
590
591                 @Override
592                 public void propertyChange(PropertyChangeEvent evt)
593                 {
594                   jalview.bin.Console
595                           .debug("Firing service changed event for "
596                                   + evt.getNewValue());
597                   JalviewServicesChanged(evt);
598                 }
599               });
600     }
601
602     this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
603
604     MouseAdapter ma;
605     this.addMouseListener(ma = new MouseAdapter()
606     {
607       @Override
608       public void mousePressed(MouseEvent evt)
609       {
610         if (evt.isPopupTrigger()) // Mac
611         {
612           showPasteMenu(evt.getX(), evt.getY());
613         }
614       }
615
616       @Override
617       public void mouseReleased(MouseEvent evt)
618       {
619         if (evt.isPopupTrigger()) // Windows
620         {
621           showPasteMenu(evt.getX(), evt.getY());
622         }
623       }
624     });
625     desktop.addMouseListener(ma);
626
627     if (Platform.isJS())
628     {
629       // emulate a problem
630       String a = null;
631       int l = a.length();
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         System.out.println(
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     desktop.add(frame);
1083
1084     windowMenu.add(menuItem);
1085
1086     frame.toFront();
1087     try
1088     {
1089       frame.setSelected(true);
1090       frame.requestFocus();
1091     } catch (java.beans.PropertyVetoException ve)
1092     {
1093     } catch (java.lang.ClassCastException cex)
1094     {
1095       jalview.bin.Console.warn(
1096               "Squashed a possible GUI implementation error. If you can recreate this, please look at https://issues.jalview.org/browse/JAL-869",
1097               cex);
1098     }
1099   }
1100
1101   /**
1102    * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
1103    * the window
1104    * 
1105    * @param frame
1106    */
1107   private static void setKeyBindings(JInternalFrame frame)
1108   {
1109     @SuppressWarnings("serial")
1110     final Action closeAction = new AbstractAction()
1111     {
1112       @Override
1113       public void actionPerformed(ActionEvent e)
1114       {
1115         frame.dispose();
1116       }
1117     };
1118
1119     /*
1120      * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
1121      */
1122     KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
1123             InputEvent.CTRL_DOWN_MASK);
1124     KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
1125             ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
1126
1127     InputMap inputMap = frame
1128             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
1129     String ctrlW = ctrlWKey.toString();
1130     inputMap.put(ctrlWKey, ctrlW);
1131     inputMap.put(cmdWKey, ctrlW);
1132
1133     ActionMap actionMap = frame.getActionMap();
1134     actionMap.put(ctrlW, closeAction);
1135   }
1136
1137   @Override
1138   public void lostOwnership(Clipboard clipboard, Transferable contents)
1139   {
1140     if (!internalCopy)
1141     {
1142       Desktop.jalviewClipboard = null;
1143     }
1144
1145     internalCopy = false;
1146   }
1147
1148   @Override
1149   public void dragEnter(DropTargetDragEvent evt)
1150   {
1151   }
1152
1153   @Override
1154   public void dragExit(DropTargetEvent evt)
1155   {
1156   }
1157
1158   @Override
1159   public void dragOver(DropTargetDragEvent evt)
1160   {
1161   }
1162
1163   @Override
1164   public void dropActionChanged(DropTargetDragEvent evt)
1165   {
1166   }
1167
1168   /**
1169    * DOCUMENT ME!
1170    * 
1171    * @param evt
1172    *          DOCUMENT ME!
1173    */
1174   @Override
1175   public void drop(DropTargetDropEvent evt)
1176   {
1177     boolean success = true;
1178     // JAL-1552 - acceptDrop required before getTransferable call for
1179     // Java's Transferable for native dnd
1180     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
1181     Transferable t = evt.getTransferable();
1182     List<Object> files = new ArrayList<>();
1183     List<DataSourceType> protocols = new ArrayList<>();
1184
1185     try
1186     {
1187       Desktop.transferFromDropTarget(files, protocols, evt, t);
1188     } catch (Exception e)
1189     {
1190       e.printStackTrace();
1191       success = false;
1192     }
1193
1194     if (files != null)
1195     {
1196       try
1197       {
1198         for (int i = 0; i < files.size(); i++)
1199         {
1200           // BH 2018 File or String
1201           Object file = files.get(i);
1202           String fileName = file.toString();
1203           DataSourceType protocol = (protocols == null)
1204                   ? DataSourceType.FILE
1205                   : protocols.get(i);
1206           FileFormatI format = null;
1207
1208           if (fileName.endsWith(".jar"))
1209           {
1210             format = FileFormat.Jalview;
1211
1212           }
1213           else
1214           {
1215             format = new IdentifyFile().identify(file, protocol);
1216           }
1217           if (file instanceof File)
1218           {
1219             Platform.cacheFileData((File) file);
1220           }
1221           new FileLoader().LoadFile(null, file, protocol, format);
1222
1223         }
1224       } catch (Exception ex)
1225       {
1226         success = false;
1227       }
1228     }
1229     evt.dropComplete(success); // need this to ensure input focus is properly
1230                                // transfered to any new windows created
1231   }
1232
1233   /**
1234    * DOCUMENT ME!
1235    * 
1236    * @param e
1237    *          DOCUMENT ME!
1238    */
1239   @Override
1240   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
1241   {
1242     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
1243     JalviewFileChooser chooser = JalviewFileChooser.forRead(
1244             Cache.getProperty("LAST_DIRECTORY"), fileFormat,
1245             BackupFiles.getEnabled());
1246
1247     chooser.setFileView(new JalviewFileView());
1248     chooser.setDialogTitle(
1249             MessageManager.getString("label.open_local_file"));
1250     chooser.setToolTipText(MessageManager.getString("action.open"));
1251
1252     chooser.setResponseHandler(0, () -> {
1253       File selectedFile = chooser.getSelectedFile();
1254       Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
1255
1256       FileFormatI format = chooser.getSelectedFormat();
1257
1258       /*
1259        * Call IdentifyFile to verify the file contains what its extension implies.
1260        * Skip this step for dynamically added file formats, because IdentifyFile does
1261        * not know how to recognise them.
1262        */
1263       if (FileFormats.getInstance().isIdentifiable(format))
1264       {
1265         try
1266         {
1267           format = new IdentifyFile().identify(selectedFile,
1268                   DataSourceType.FILE);
1269         } catch (FileFormatException e)
1270         {
1271           // format = null; //??
1272         }
1273       }
1274
1275       new FileLoader().LoadFile(viewport, selectedFile, DataSourceType.FILE,
1276               format);
1277     });
1278     chooser.showOpenDialog(this);
1279   }
1280
1281   /**
1282    * Shows a dialog for input of a URL at which to retrieve alignment data
1283    * 
1284    * @param viewport
1285    */
1286   @Override
1287   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
1288   {
1289     // This construct allows us to have a wider textfield
1290     // for viewing
1291     JLabel label = new JLabel(
1292             MessageManager.getString("label.input_file_url"));
1293
1294     JPanel panel = new JPanel(new GridLayout(2, 1));
1295     panel.add(label);
1296
1297     /*
1298      * the URL to fetch is input in Java: an editable combobox with history JS:
1299      * (pending JAL-3038) a plain text field
1300      */
1301     JComponent history;
1302     String urlBase = "https://www.";
1303     if (Platform.isJS())
1304     {
1305       history = new JTextField(urlBase, 35);
1306     }
1307     else
1308     /**
1309      * Java only
1310      * 
1311      * @j2sIgnore
1312      */
1313     {
1314       JComboBox<String> asCombo = new JComboBox<>();
1315       asCombo.setPreferredSize(new Dimension(400, 20));
1316       asCombo.setEditable(true);
1317       asCombo.addItem(urlBase);
1318       String historyItems = Cache.getProperty("RECENT_URL");
1319       if (historyItems != null)
1320       {
1321         for (String token : historyItems.split("\\t"))
1322         {
1323           asCombo.addItem(token);
1324         }
1325       }
1326       history = asCombo;
1327     }
1328     panel.add(history);
1329
1330     Object[] options = new Object[] { MessageManager.getString("action.ok"),
1331         MessageManager.getString("action.cancel") };
1332     Runnable action = () -> {
1333       @SuppressWarnings("unchecked")
1334       String url = (history instanceof JTextField
1335               ? ((JTextField) history).getText()
1336               : ((JComboBox<String>) history).getEditor().getItem()
1337                       .toString().trim());
1338
1339       if (url.toLowerCase(Locale.ROOT).endsWith(".jar"))
1340       {
1341         if (viewport != null)
1342         {
1343           new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
1344                   FileFormat.Jalview);
1345         }
1346         else
1347         {
1348           new FileLoader().LoadFile(url, DataSourceType.URL,
1349                   FileFormat.Jalview);
1350         }
1351       }
1352       else
1353       {
1354         FileFormatI format = null;
1355         try
1356         {
1357           format = new IdentifyFile().identify(url, DataSourceType.URL);
1358         } catch (FileFormatException e)
1359         {
1360           // TODO revise error handling, distinguish between
1361           // URL not found and response not valid
1362         }
1363
1364         if (format == null)
1365         {
1366           String msg = MessageManager.formatMessage("label.couldnt_locate",
1367                   url);
1368           JvOptionPane.showInternalMessageDialog(Desktop.desktop, msg,
1369                   MessageManager.getString("label.url_not_found"),
1370                   JvOptionPane.WARNING_MESSAGE);
1371           return;
1372         }
1373
1374         if (viewport != null)
1375         {
1376           new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
1377                   format);
1378         }
1379         else
1380         {
1381           new FileLoader().LoadFile(url, DataSourceType.URL, format);
1382         }
1383       }
1384     };
1385     String dialogOption = MessageManager
1386             .getString("label.input_alignment_from_url");
1387     JvOptionPane.newOptionDialog(desktop).setResponseHandler(0, action)
1388             .showInternalDialog(panel, dialogOption,
1389                     JvOptionPane.YES_NO_CANCEL_OPTION,
1390                     JvOptionPane.PLAIN_MESSAGE, null, options,
1391                     MessageManager.getString("action.ok"));
1392   }
1393
1394   /**
1395    * Opens the CutAndPaste window for the user to paste an alignment in to
1396    * 
1397    * @param viewPanel
1398    *          - if not null, the pasted alignment is added to the current
1399    *          alignment; if null, to a new alignment window
1400    */
1401   @Override
1402   public void inputTextboxMenuItem_actionPerformed(
1403           AlignmentViewPanel viewPanel)
1404   {
1405     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1406     cap.setForInput(viewPanel);
1407     Desktop.addInternalFrame(cap,
1408             MessageManager.getString("label.cut_paste_alignmen_file"), true,
1409             600, 500);
1410   }
1411
1412   /*
1413    * Check with user and saving files before actually quitting
1414    */
1415   public void desktopQuit()
1416   {
1417     desktopQuit(true, false);
1418   }
1419
1420   public QuitHandler.QResponse desktopQuit(boolean ui, boolean disposeFlag)
1421   {
1422     final Runnable doDesktopQuit = () -> {
1423       Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1424       Cache.setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
1425       Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height + "");
1426       storeLastKnownDimensions("", new Rectangle(getBounds().x,
1427               getBounds().y, getWidth(), getHeight()));
1428
1429       if (jconsole != null)
1430       {
1431         storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1432         jconsole.stopConsole();
1433       }
1434
1435       if (jvnews != null)
1436       {
1437         storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1438       }
1439
1440       // Frames should all close automatically. Keeping external
1441       // viewers open should already be decided by user.
1442       closeAll_actionPerformed(null);
1443
1444       // check for aborted quit
1445       if (QuitHandler.quitCancelled())
1446       {
1447         jalview.bin.Console.debug("Desktop aborting quit");
1448         return;
1449       }
1450
1451       if (dialogExecutor != null)
1452       {
1453         dialogExecutor.shutdownNow();
1454       }
1455
1456       if (groovyConsole != null)
1457       {
1458         // suppress a possible repeat prompt to save script
1459         groovyConsole.setDirty(false);
1460         groovyConsole.exit();
1461       }
1462
1463       if (QuitHandler.gotQuitResponse() == QResponse.FORCE_QUIT)
1464       {
1465         // note that shutdown hook will not be run
1466         jalview.bin.Console.debug("Force Quit selected by user");
1467         Runtime.getRuntime().halt(0);
1468       }
1469
1470       jalview.bin.Console.debug("Quit selected by user");
1471       if (disposeFlag)
1472       {
1473         instance.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
1474         // instance.dispose();
1475       }
1476       instance.quit();
1477     };
1478
1479     return QuitHandler.getQuitResponse(ui, doDesktopQuit, doDesktopQuit,
1480             QuitHandler.defaultCancelQuit);
1481   }
1482
1483   /**
1484    * Don't call this directly, use desktopQuit() above. Exits the program.
1485    */
1486   @Override
1487   public void quit()
1488   {
1489     // this will run the shutdownHook but QuitHandler.getQuitResponse() should
1490     // not run a second time if gotQuitResponse flag has been set (i.e. user
1491     // confirmed quit of some kind).
1492     Jalview.exit("Desktop exiting.", 0);
1493   }
1494
1495   private void storeLastKnownDimensions(String string, Rectangle jc)
1496   {
1497     jalview.bin.Console.debug("Storing last known dimensions for " + string
1498             + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1499             + " height:" + jc.height);
1500
1501     Cache.setProperty(string + "SCREEN_X", jc.x + "");
1502     Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1503     Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1504     Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1505   }
1506
1507   /**
1508    * DOCUMENT ME!
1509    * 
1510    * @param e
1511    *          DOCUMENT ME!
1512    */
1513   @Override
1514   public void aboutMenuItem_actionPerformed(ActionEvent e)
1515   {
1516     new Thread(new Runnable()
1517     {
1518       @Override
1519       public void run()
1520       {
1521         new SplashScreen(false);
1522       }
1523     }).start();
1524   }
1525
1526   /**
1527    * Returns the html text for the About screen, including any available version
1528    * number, build details, author details and citation reference, but without
1529    * the enclosing {@code html} tags
1530    * 
1531    * @return
1532    */
1533   public String getAboutMessage()
1534   {
1535     StringBuilder message = new StringBuilder(1024);
1536     message.append("<div style=\"font-family: sans-serif;\">")
1537             .append("<h1><strong>Version: ")
1538             .append(Cache.getProperty("VERSION")).append("</strong></h1>")
1539             .append("<strong>Built: <em>")
1540             .append(Cache.getDefault("BUILD_DATE", "unknown"))
1541             .append("</em> from ").append(Cache.getBuildDetailsForSplash())
1542             .append("</strong>");
1543
1544     String latestVersion = Cache.getDefault("LATEST_VERSION", "Checking");
1545     if (latestVersion.equals("Checking"))
1546     {
1547       // JBP removed this message for 2.11: May be reinstated in future version
1548       // message.append("<br>...Checking latest version...</br>");
1549     }
1550     else if (!latestVersion.equals(Cache.getProperty("VERSION")))
1551     {
1552       boolean red = false;
1553       if (Cache.getProperty("VERSION").toLowerCase(Locale.ROOT)
1554               .indexOf("automated build") == -1)
1555       {
1556         red = true;
1557         // Displayed when code version and jnlp version do not match and code
1558         // version is not a development build
1559         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1560       }
1561
1562       message.append("<br>!! Version ")
1563               .append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
1564               .append(" is available for download from ")
1565               .append(Cache.getDefault("www.jalview.org",
1566                       "https://www.jalview.org"))
1567               .append(" !!");
1568       if (red)
1569       {
1570         message.append("</div>");
1571       }
1572     }
1573     message.append("<br>Authors:  ");
1574     message.append(Cache.getDefault("AUTHORFNAMES", DEFAULT_AUTHORS));
1575     message.append(CITATION);
1576
1577     message.append("</div>");
1578
1579     return message.toString();
1580   }
1581
1582   /**
1583    * Action on requesting Help documentation
1584    */
1585   @Override
1586   public void documentationMenuItem_actionPerformed()
1587   {
1588     try
1589     {
1590       if (Platform.isJS())
1591       {
1592         BrowserLauncher.openURL("https://www.jalview.org/help.html");
1593       }
1594       else
1595       /**
1596        * Java only
1597        * 
1598        * @j2sIgnore
1599        */
1600       {
1601         Help.showHelpWindow();
1602       }
1603     } catch (Exception ex)
1604     {
1605       System.err.println("Error opening help: " + ex.getMessage());
1606     }
1607   }
1608
1609   @Override
1610   public void closeAll_actionPerformed(ActionEvent e)
1611   {
1612     // TODO show a progress bar while closing?
1613     JInternalFrame[] frames = desktop.getAllFrames();
1614     for (int i = 0; i < frames.length; i++)
1615     {
1616       try
1617       {
1618         frames[i].setClosed(true);
1619       } catch (java.beans.PropertyVetoException ex)
1620       {
1621       }
1622     }
1623     Jalview.setCurrentAlignFrame(null);
1624     jalview.bin.Console.info("ALL CLOSED");
1625
1626     /*
1627      * reset state of singleton objects as appropriate (clear down session state
1628      * when all windows are closed)
1629      */
1630     StructureSelectionManager ssm = StructureSelectionManager
1631             .getStructureSelectionManager(this);
1632     if (ssm != null)
1633     {
1634       ssm.resetAll();
1635     }
1636   }
1637
1638   public int structureViewersStillRunningCount()
1639   {
1640     int count = 0;
1641     JInternalFrame[] frames = desktop.getAllFrames();
1642     for (int i = 0; i < frames.length; i++)
1643     {
1644       if (frames[i] != null
1645               && frames[i] instanceof JalviewStructureDisplayI)
1646       {
1647         if (((JalviewStructureDisplayI) frames[i]).stillRunning())
1648           count++;
1649       }
1650     }
1651     return count;
1652   }
1653
1654   @Override
1655   public void raiseRelated_actionPerformed(ActionEvent e)
1656   {
1657     reorderAssociatedWindows(false, false);
1658   }
1659
1660   @Override
1661   public void minimizeAssociated_actionPerformed(ActionEvent e)
1662   {
1663     reorderAssociatedWindows(true, false);
1664   }
1665
1666   void closeAssociatedWindows()
1667   {
1668     reorderAssociatedWindows(false, true);
1669   }
1670
1671   /*
1672    * (non-Javadoc)
1673    * 
1674    * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1675    * ActionEvent)
1676    */
1677   @Override
1678   protected void garbageCollect_actionPerformed(ActionEvent e)
1679   {
1680     // We simply collect the garbage
1681     jalview.bin.Console.debug("Collecting garbage...");
1682     System.gc();
1683     jalview.bin.Console.debug("Finished garbage collection.");
1684   }
1685
1686   /*
1687    * (non-Javadoc)
1688    * 
1689    * @see jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.
1690    * ActionEvent )
1691    */
1692   @Override
1693   protected void showMemusage_actionPerformed(ActionEvent e)
1694   {
1695     desktop.showMemoryUsage(showMemusage.isSelected());
1696   }
1697
1698   /*
1699    * (non-Javadoc)
1700    * 
1701    * @see
1702    * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1703    * )
1704    */
1705   @Override
1706   protected void showConsole_actionPerformed(ActionEvent e)
1707   {
1708     showConsole(showConsole.isSelected());
1709   }
1710
1711   Console jconsole = null;
1712
1713   /**
1714    * control whether the java console is visible or not
1715    * 
1716    * @param selected
1717    */
1718   void showConsole(boolean selected)
1719   {
1720     // TODO: decide if we should update properties file
1721     if (jconsole != null) // BH 2018
1722     {
1723       showConsole.setSelected(selected);
1724       Cache.setProperty("SHOW_JAVA_CONSOLE",
1725               Boolean.valueOf(selected).toString());
1726       jconsole.setVisible(selected);
1727     }
1728   }
1729
1730   void reorderAssociatedWindows(boolean minimize, boolean close)
1731   {
1732     JInternalFrame[] frames = desktop.getAllFrames();
1733     if (frames == null || frames.length < 1)
1734     {
1735       return;
1736     }
1737
1738     AlignmentViewport source = null, target = null;
1739     if (frames[0] instanceof AlignFrame)
1740     {
1741       source = ((AlignFrame) frames[0]).getCurrentView();
1742     }
1743     else if (frames[0] instanceof TreePanel)
1744     {
1745       source = ((TreePanel) frames[0]).getViewPort();
1746     }
1747     else if (frames[0] instanceof PCAPanel)
1748     {
1749       source = ((PCAPanel) frames[0]).av;
1750     }
1751     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1752     {
1753       source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1754     }
1755
1756     if (source != null)
1757     {
1758       for (int i = 0; i < frames.length; i++)
1759       {
1760         target = null;
1761         if (frames[i] == null)
1762         {
1763           continue;
1764         }
1765         if (frames[i] instanceof AlignFrame)
1766         {
1767           target = ((AlignFrame) frames[i]).getCurrentView();
1768         }
1769         else if (frames[i] instanceof TreePanel)
1770         {
1771           target = ((TreePanel) frames[i]).getViewPort();
1772         }
1773         else if (frames[i] instanceof PCAPanel)
1774         {
1775           target = ((PCAPanel) frames[i]).av;
1776         }
1777         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1778         {
1779           target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1780         }
1781
1782         if (source == target)
1783         {
1784           try
1785           {
1786             if (close)
1787             {
1788               frames[i].setClosed(true);
1789             }
1790             else
1791             {
1792               frames[i].setIcon(minimize);
1793               if (!minimize)
1794               {
1795                 frames[i].toFront();
1796               }
1797             }
1798
1799           } catch (java.beans.PropertyVetoException ex)
1800           {
1801           }
1802         }
1803       }
1804     }
1805   }
1806
1807   /**
1808    * DOCUMENT ME!
1809    * 
1810    * @param e
1811    *          DOCUMENT ME!
1812    */
1813   @Override
1814   protected void preferences_actionPerformed(ActionEvent e)
1815   {
1816     Preferences.openPreferences();
1817   }
1818
1819   /**
1820    * Prompts the user to choose a file and then saves the Jalview state as a
1821    * Jalview project file
1822    */
1823   @Override
1824   public void saveState_actionPerformed()
1825   {
1826     saveState_actionPerformed(false);
1827   }
1828
1829   public void saveState_actionPerformed(boolean saveAs)
1830   {
1831     java.io.File projectFile = getProjectFile();
1832     // autoSave indicates we already have a file and don't need to ask
1833     boolean autoSave = projectFile != null && !saveAs
1834             && BackupFiles.getEnabled();
1835
1836     // System.out.println("autoSave="+autoSave+", projectFile='"+projectFile+"',
1837     // saveAs="+saveAs+", Backups
1838     // "+(BackupFiles.getEnabled()?"enabled":"disabled"));
1839
1840     boolean approveSave = false;
1841     if (!autoSave)
1842     {
1843       JalviewFileChooser chooser = new JalviewFileChooser("jvp",
1844               "Jalview Project");
1845
1846       chooser.setFileView(new JalviewFileView());
1847       chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1848
1849       int value = chooser.showSaveDialog(this);
1850
1851       if (value == JalviewFileChooser.APPROVE_OPTION)
1852       {
1853         projectFile = chooser.getSelectedFile();
1854         setProjectFile(projectFile);
1855         approveSave = true;
1856       }
1857     }
1858
1859     if (approveSave || autoSave)
1860     {
1861       final Desktop me = this;
1862       final java.io.File chosenFile = projectFile;
1863       new Thread(new Runnable()
1864       {
1865         @Override
1866         public void run()
1867         {
1868           // TODO: refactor to Jalview desktop session controller action.
1869           setProgressBar(MessageManager.formatMessage(
1870                   "label.saving_jalview_project", new Object[]
1871                   { chosenFile.getName() }), chosenFile.hashCode());
1872           Cache.setProperty("LAST_DIRECTORY", chosenFile.getParent());
1873           // TODO catch and handle errors for savestate
1874           // TODO prevent user from messing with the Desktop whilst we're saving
1875           try
1876           {
1877             boolean doBackup = BackupFiles.getEnabled();
1878             BackupFiles backupfiles = doBackup ? new BackupFiles(chosenFile)
1879                     : null;
1880
1881             new Jalview2XML().saveState(
1882                     doBackup ? backupfiles.getTempFile() : chosenFile);
1883
1884             if (doBackup)
1885             {
1886               backupfiles.setWriteSuccess(true);
1887               backupfiles.rollBackupsAndRenameTempFile();
1888             }
1889           } catch (OutOfMemoryError oom)
1890           {
1891             new OOMWarning("Whilst saving current state to "
1892                     + chosenFile.getName(), oom);
1893           } catch (Exception ex)
1894           {
1895             jalview.bin.Console.error("Problems whilst trying to save to "
1896                     + chosenFile.getName(), ex);
1897             JvOptionPane.showMessageDialog(me,
1898                     MessageManager.formatMessage(
1899                             "label.error_whilst_saving_current_state_to",
1900                             new Object[]
1901                             { chosenFile.getName() }),
1902                     MessageManager.getString("label.couldnt_save_project"),
1903                     JvOptionPane.WARNING_MESSAGE);
1904           }
1905           setProgressBar(null, chosenFile.hashCode());
1906         }
1907       }).start();
1908     }
1909   }
1910
1911   @Override
1912   public void saveAsState_actionPerformed(ActionEvent e)
1913   {
1914     saveState_actionPerformed(true);
1915   }
1916
1917   protected void setProjectFile(File choice)
1918   {
1919     this.projectFile = choice;
1920   }
1921
1922   public File getProjectFile()
1923   {
1924     return this.projectFile;
1925   }
1926
1927   /**
1928    * Shows a file chooser dialog and tries to read in the selected file as a
1929    * Jalview project
1930    */
1931   @Override
1932   public void loadState_actionPerformed()
1933   {
1934     final String[] suffix = new String[] { "jvp", "jar" };
1935     final String[] desc = new String[] { "Jalview Project",
1936         "Jalview Project (old)" };
1937     JalviewFileChooser chooser = new JalviewFileChooser(
1938             Cache.getProperty("LAST_DIRECTORY"), suffix, desc,
1939             "Jalview Project", true, BackupFiles.getEnabled()); // last two
1940                                                                 // booleans:
1941                                                                 // allFiles,
1942     // allowBackupFiles
1943     chooser.setFileView(new JalviewFileView());
1944     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
1945     chooser.setResponseHandler(0, () -> {
1946       File selectedFile = chooser.getSelectedFile();
1947       setProjectFile(selectedFile);
1948       String choice = selectedFile.getAbsolutePath();
1949       Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
1950       new Thread(new Runnable()
1951       {
1952         @Override
1953         public void run()
1954         {
1955           try
1956           {
1957             new Jalview2XML().loadJalviewAlign(selectedFile);
1958           } catch (OutOfMemoryError oom)
1959           {
1960             new OOMWarning("Whilst loading project from " + choice, oom);
1961           } catch (Exception ex)
1962           {
1963             jalview.bin.Console.error(
1964                     "Problems whilst loading project from " + choice, ex);
1965             JvOptionPane.showMessageDialog(Desktop.desktop,
1966                     MessageManager.formatMessage(
1967                             "label.error_whilst_loading_project_from",
1968                             new Object[]
1969                             { choice }),
1970                     MessageManager.getString("label.couldnt_load_project"),
1971                     JvOptionPane.WARNING_MESSAGE);
1972           }
1973         }
1974       }, "Project Loader").start();
1975     });
1976
1977     chooser.showOpenDialog(this);
1978   }
1979
1980   @Override
1981   public void inputSequence_actionPerformed(ActionEvent e)
1982   {
1983     new SequenceFetcher(this);
1984   }
1985
1986   JPanel progressPanel;
1987
1988   ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
1989
1990   public void startLoading(final Object fileName)
1991   {
1992     if (fileLoadingCount == 0)
1993     {
1994       fileLoadingPanels.add(addProgressPanel(MessageManager
1995               .formatMessage("label.loading_file", new Object[]
1996               { fileName })));
1997     }
1998     fileLoadingCount++;
1999   }
2000
2001   private JPanel addProgressPanel(String string)
2002   {
2003     if (progressPanel == null)
2004     {
2005       progressPanel = new JPanel(new GridLayout(1, 1));
2006       totalProgressCount = 0;
2007       instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
2008     }
2009     JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
2010     JProgressBar progressBar = new JProgressBar();
2011     progressBar.setIndeterminate(true);
2012
2013     thisprogress.add(new JLabel(string), BorderLayout.WEST);
2014
2015     thisprogress.add(progressBar, BorderLayout.CENTER);
2016     progressPanel.add(thisprogress);
2017     ((GridLayout) progressPanel.getLayout()).setRows(
2018             ((GridLayout) progressPanel.getLayout()).getRows() + 1);
2019     ++totalProgressCount;
2020     instance.validate();
2021     return thisprogress;
2022   }
2023
2024   int totalProgressCount = 0;
2025
2026   private void removeProgressPanel(JPanel progbar)
2027   {
2028     if (progressPanel != null)
2029     {
2030       synchronized (progressPanel)
2031       {
2032         progressPanel.remove(progbar);
2033         GridLayout gl = (GridLayout) progressPanel.getLayout();
2034         gl.setRows(gl.getRows() - 1);
2035         if (--totalProgressCount < 1)
2036         {
2037           this.getContentPane().remove(progressPanel);
2038           progressPanel = null;
2039         }
2040       }
2041     }
2042     validate();
2043   }
2044
2045   public void stopLoading()
2046   {
2047     fileLoadingCount--;
2048     if (fileLoadingCount < 1)
2049     {
2050       while (fileLoadingPanels.size() > 0)
2051       {
2052         removeProgressPanel(fileLoadingPanels.remove(0));
2053       }
2054       fileLoadingPanels.clear();
2055       fileLoadingCount = 0;
2056     }
2057     validate();
2058   }
2059
2060   public static int getViewCount(String alignmentId)
2061   {
2062     AlignmentViewport[] aps = getViewports(alignmentId);
2063     return (aps == null) ? 0 : aps.length;
2064   }
2065
2066   /**
2067    * 
2068    * @param alignmentId
2069    *          - if null, all sets are returned
2070    * @return all AlignmentPanels concerning the alignmentId sequence set
2071    */
2072   public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
2073   {
2074     if (Desktop.desktop == null)
2075     {
2076       // no frames created and in headless mode
2077       // TODO: verify that frames are recoverable when in headless mode
2078       return null;
2079     }
2080     List<AlignmentPanel> aps = new ArrayList<>();
2081     AlignFrame[] frames = getAlignFrames();
2082     if (frames == null)
2083     {
2084       return null;
2085     }
2086     for (AlignFrame af : frames)
2087     {
2088       for (AlignmentPanel ap : af.alignPanels)
2089       {
2090         if (alignmentId == null
2091                 || alignmentId.equals(ap.av.getSequenceSetId()))
2092         {
2093           aps.add(ap);
2094         }
2095       }
2096     }
2097     if (aps.size() == 0)
2098     {
2099       return null;
2100     }
2101     AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
2102     return vap;
2103   }
2104
2105   /**
2106    * get all the viewports on an alignment.
2107    * 
2108    * @param sequenceSetId
2109    *          unique alignment id (may be null - all viewports returned in that
2110    *          case)
2111    * @return all viewports on the alignment bound to sequenceSetId
2112    */
2113   public static AlignmentViewport[] getViewports(String sequenceSetId)
2114   {
2115     List<AlignmentViewport> viewp = new ArrayList<>();
2116     if (desktop != null)
2117     {
2118       AlignFrame[] frames = Desktop.getAlignFrames();
2119
2120       for (AlignFrame afr : frames)
2121       {
2122         if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
2123                 .equals(sequenceSetId))
2124         {
2125           if (afr.alignPanels != null)
2126           {
2127             for (AlignmentPanel ap : afr.alignPanels)
2128             {
2129               if (sequenceSetId == null
2130                       || sequenceSetId.equals(ap.av.getSequenceSetId()))
2131               {
2132                 viewp.add(ap.av);
2133               }
2134             }
2135           }
2136           else
2137           {
2138             viewp.add(afr.getViewport());
2139           }
2140         }
2141       }
2142       if (viewp.size() > 0)
2143       {
2144         return viewp.toArray(new AlignmentViewport[viewp.size()]);
2145       }
2146     }
2147     return null;
2148   }
2149
2150   /**
2151    * Explode the views in the given frame into separate AlignFrame
2152    * 
2153    * @param af
2154    */
2155   public static void explodeViews(AlignFrame af)
2156   {
2157     int size = af.alignPanels.size();
2158     if (size < 2)
2159     {
2160       return;
2161     }
2162
2163     // FIXME: ideally should use UI interface API
2164     FeatureSettings viewFeatureSettings = (af.featureSettings != null
2165             && af.featureSettings.isOpen()) ? af.featureSettings : null;
2166     Rectangle fsBounds = af.getFeatureSettingsGeometry();
2167     for (int i = 0; i < size; i++)
2168     {
2169       AlignmentPanel ap = af.alignPanels.get(i);
2170
2171       AlignFrame newaf = new AlignFrame(ap);
2172
2173       // transfer reference for existing feature settings to new alignFrame
2174       if (ap == af.alignPanel)
2175       {
2176         if (viewFeatureSettings != null && viewFeatureSettings.fr.ap == ap)
2177         {
2178           newaf.featureSettings = viewFeatureSettings;
2179         }
2180         newaf.setFeatureSettingsGeometry(fsBounds);
2181       }
2182
2183       /*
2184        * Restore the view's last exploded frame geometry if known. Multiple views from
2185        * one exploded frame share and restore the same (frame) position and size.
2186        */
2187       Rectangle geometry = ap.av.getExplodedGeometry();
2188       if (geometry != null)
2189       {
2190         newaf.setBounds(geometry);
2191       }
2192
2193       ap.av.setGatherViewsHere(false);
2194
2195       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
2196               AlignFrame.DEFAULT_HEIGHT);
2197       // and materialise a new feature settings dialog instance for the new
2198       // alignframe
2199       // (closes the old as if 'OK' was pressed)
2200       if (ap == af.alignPanel && newaf.featureSettings != null
2201               && newaf.featureSettings.isOpen()
2202               && af.alignPanel.getAlignViewport().isShowSequenceFeatures())
2203       {
2204         newaf.showFeatureSettingsUI();
2205       }
2206     }
2207
2208     af.featureSettings = null;
2209     af.alignPanels.clear();
2210     af.closeMenuItem_actionPerformed(true);
2211
2212   }
2213
2214   /**
2215    * Gather expanded views (separate AlignFrame's) with the same sequence set
2216    * identifier back in to this frame as additional views, and close the
2217    * expanded views. Note the expanded frames may themselves have multiple
2218    * views. We take the lot.
2219    * 
2220    * @param source
2221    */
2222   public void gatherViews(AlignFrame source)
2223   {
2224     source.viewport.setGatherViewsHere(true);
2225     source.viewport.setExplodedGeometry(source.getBounds());
2226     JInternalFrame[] frames = desktop.getAllFrames();
2227     String viewId = source.viewport.getSequenceSetId();
2228     for (int t = 0; t < frames.length; t++)
2229     {
2230       if (frames[t] instanceof AlignFrame && frames[t] != source)
2231       {
2232         AlignFrame af = (AlignFrame) frames[t];
2233         boolean gatherThis = false;
2234         for (int a = 0; a < af.alignPanels.size(); a++)
2235         {
2236           AlignmentPanel ap = af.alignPanels.get(a);
2237           if (viewId.equals(ap.av.getSequenceSetId()))
2238           {
2239             gatherThis = true;
2240             ap.av.setGatherViewsHere(false);
2241             ap.av.setExplodedGeometry(af.getBounds());
2242             source.addAlignmentPanel(ap, false);
2243           }
2244         }
2245
2246         if (gatherThis)
2247         {
2248           if (af.featureSettings != null && af.featureSettings.isOpen())
2249           {
2250             if (source.featureSettings == null)
2251             {
2252               // preserve the feature settings geometry for this frame
2253               source.featureSettings = af.featureSettings;
2254               source.setFeatureSettingsGeometry(
2255                       af.getFeatureSettingsGeometry());
2256             }
2257             else
2258             {
2259               // close it and forget
2260               af.featureSettings.close();
2261             }
2262           }
2263           af.alignPanels.clear();
2264           af.closeMenuItem_actionPerformed(true);
2265         }
2266       }
2267     }
2268
2269     // refresh the feature setting UI for the source frame if it exists
2270     if (source.featureSettings != null && source.featureSettings.isOpen())
2271     {
2272       source.showFeatureSettingsUI();
2273     }
2274
2275   }
2276
2277   public JInternalFrame[] getAllFrames()
2278   {
2279     return desktop.getAllFrames();
2280   }
2281
2282   /**
2283    * Checks the given url to see if it gives a response indicating that the user
2284    * should be informed of a new questionnaire.
2285    * 
2286    * @param url
2287    */
2288   public void checkForQuestionnaire(String url)
2289   {
2290     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2291     // javax.swing.SwingUtilities.invokeLater(jvq);
2292     new Thread(jvq).start();
2293   }
2294
2295   public void checkURLLinks()
2296   {
2297     // Thread off the URL link checker
2298     addDialogThread(new Runnable()
2299     {
2300       @Override
2301       public void run()
2302       {
2303         if (Cache.getDefault("CHECKURLLINKS", true))
2304         {
2305           // check what the actual links are - if it's just the default don't
2306           // bother with the warning
2307           List<String> links = Preferences.sequenceUrlLinks
2308                   .getLinksForMenu();
2309
2310           // only need to check links if there is one with a
2311           // SEQUENCE_ID which is not the default EMBL_EBI link
2312           ListIterator<String> li = links.listIterator();
2313           boolean check = false;
2314           List<JLabel> urls = new ArrayList<>();
2315           while (li.hasNext())
2316           {
2317             String link = li.next();
2318             if (link.contains(jalview.util.UrlConstants.SEQUENCE_ID)
2319                     && !UrlConstants.isDefaultString(link))
2320             {
2321               check = true;
2322               int barPos = link.indexOf("|");
2323               String urlMsg = barPos == -1 ? link
2324                       : link.substring(0, barPos) + ": "
2325                               + link.substring(barPos + 1);
2326               urls.add(new JLabel(urlMsg));
2327             }
2328           }
2329           if (!check)
2330           {
2331             return;
2332           }
2333
2334           // ask user to check in case URL links use old style tokens
2335           // ($SEQUENCE_ID$ for sequence id _or_ accession id)
2336           JPanel msgPanel = new JPanel();
2337           msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
2338           msgPanel.add(Box.createVerticalGlue());
2339           JLabel msg = new JLabel(MessageManager
2340                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
2341           JLabel msg2 = new JLabel(MessageManager
2342                   .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
2343           msgPanel.add(msg);
2344           for (JLabel url : urls)
2345           {
2346             msgPanel.add(url);
2347           }
2348           msgPanel.add(msg2);
2349
2350           final JCheckBox jcb = new JCheckBox(
2351                   MessageManager.getString("label.do_not_display_again"));
2352           jcb.addActionListener(new ActionListener()
2353           {
2354             @Override
2355             public void actionPerformed(ActionEvent e)
2356             {
2357               // update Cache settings for "don't show this again"
2358               boolean showWarningAgain = !jcb.isSelected();
2359               Cache.setProperty("CHECKURLLINKS",
2360                       Boolean.valueOf(showWarningAgain).toString());
2361             }
2362           });
2363           msgPanel.add(jcb);
2364
2365           JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
2366                   MessageManager
2367                           .getString("label.SEQUENCE_ID_no_longer_used"),
2368                   JvOptionPane.WARNING_MESSAGE);
2369         }
2370       }
2371     });
2372   }
2373
2374   /**
2375    * Proxy class for JDesktopPane which optionally displays the current memory
2376    * usage and highlights the desktop area with a red bar if free memory runs
2377    * low.
2378    * 
2379    * @author AMW
2380    */
2381   public class MyDesktopPane extends JDesktopPane implements Runnable
2382   {
2383     private static final float ONE_MB = 1048576f;
2384
2385     boolean showMemoryUsage = false;
2386
2387     Runtime runtime;
2388
2389     java.text.NumberFormat df;
2390
2391     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2392             percentUsage;
2393
2394     public MyDesktopPane(boolean showMemoryUsage)
2395     {
2396       showMemoryUsage(showMemoryUsage);
2397     }
2398
2399     public void showMemoryUsage(boolean showMemory)
2400     {
2401       this.showMemoryUsage = showMemory;
2402       if (showMemory)
2403       {
2404         Thread worker = new Thread(this);
2405         worker.start();
2406       }
2407       repaint();
2408     }
2409
2410     public boolean isShowMemoryUsage()
2411     {
2412       return showMemoryUsage;
2413     }
2414
2415     @Override
2416     public void run()
2417     {
2418       df = java.text.NumberFormat.getNumberInstance();
2419       df.setMaximumFractionDigits(2);
2420       runtime = Runtime.getRuntime();
2421
2422       while (showMemoryUsage)
2423       {
2424         try
2425         {
2426           maxMemory = runtime.maxMemory() / ONE_MB;
2427           allocatedMemory = runtime.totalMemory() / ONE_MB;
2428           freeMemory = runtime.freeMemory() / ONE_MB;
2429           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2430
2431           percentUsage = (totalFreeMemory / maxMemory) * 100;
2432
2433           // if (percentUsage < 20)
2434           {
2435             // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2436             // Color.red);
2437             // instance.set.setBorder(border1);
2438           }
2439           repaint();
2440           // sleep after showing usage
2441           Thread.sleep(3000);
2442         } catch (Exception ex)
2443         {
2444           ex.printStackTrace();
2445         }
2446       }
2447     }
2448
2449     @Override
2450     public void paintComponent(Graphics g)
2451     {
2452       if (showMemoryUsage && g != null && df != null)
2453       {
2454         if (percentUsage < 20)
2455         {
2456           g.setColor(Color.red);
2457         }
2458         FontMetrics fm = g.getFontMetrics();
2459         if (fm != null)
2460         {
2461           g.drawString(MessageManager.formatMessage("label.memory_stats",
2462                   new Object[]
2463                   { df.format(totalFreeMemory), df.format(maxMemory),
2464                       df.format(percentUsage) }),
2465                   10, getHeight() - fm.getHeight());
2466         }
2467       }
2468
2469       // output debug scale message. Important for jalview.bin.HiDPISettingTest2
2470       Desktop.debugScaleMessage(Desktop.getDesktop().getGraphics());
2471     }
2472   }
2473
2474   /**
2475    * Accessor method to quickly get all the AlignmentFrames loaded.
2476    * 
2477    * @return an array of AlignFrame, or null if none found
2478    */
2479   public static AlignFrame[] getAlignFrames()
2480   {
2481     if (Jalview.isHeadlessMode())
2482     {
2483       // Desktop.desktop is null in headless mode
2484       return new AlignFrame[] { Jalview.currentAlignFrame };
2485     }
2486
2487     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2488
2489     if (frames == null)
2490     {
2491       return null;
2492     }
2493     List<AlignFrame> avp = new ArrayList<>();
2494     // REVERSE ORDER
2495     for (int i = frames.length - 1; i > -1; i--)
2496     {
2497       if (frames[i] instanceof AlignFrame)
2498       {
2499         avp.add((AlignFrame) frames[i]);
2500       }
2501       else if (frames[i] instanceof SplitFrame)
2502       {
2503         /*
2504          * Also check for a split frame containing an AlignFrame
2505          */
2506         GSplitFrame sf = (GSplitFrame) frames[i];
2507         if (sf.getTopFrame() instanceof AlignFrame)
2508         {
2509           avp.add((AlignFrame) sf.getTopFrame());
2510         }
2511         if (sf.getBottomFrame() instanceof AlignFrame)
2512         {
2513           avp.add((AlignFrame) sf.getBottomFrame());
2514         }
2515       }
2516     }
2517     if (avp.size() == 0)
2518     {
2519       return null;
2520     }
2521     AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2522     return afs;
2523   }
2524
2525   /**
2526    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2527    * 
2528    * @return
2529    */
2530   public GStructureViewer[] getJmols()
2531   {
2532     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2533
2534     if (frames == null)
2535     {
2536       return null;
2537     }
2538     List<GStructureViewer> avp = new ArrayList<>();
2539     // REVERSE ORDER
2540     for (int i = frames.length - 1; i > -1; i--)
2541     {
2542       if (frames[i] instanceof AppJmol)
2543       {
2544         GStructureViewer af = (GStructureViewer) frames[i];
2545         avp.add(af);
2546       }
2547     }
2548     if (avp.size() == 0)
2549     {
2550       return null;
2551     }
2552     GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2553     return afs;
2554   }
2555
2556   /**
2557    * Add Groovy Support to Jalview
2558    */
2559   @Override
2560   public void groovyShell_actionPerformed()
2561   {
2562     try
2563     {
2564       openGroovyConsole();
2565     } catch (Exception ex)
2566     {
2567       jalview.bin.Console.error("Groovy Shell Creation failed.", ex);
2568       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2569
2570               MessageManager.getString("label.couldnt_create_groovy_shell"),
2571               MessageManager.getString("label.groovy_support_failed"),
2572               JvOptionPane.ERROR_MESSAGE);
2573     }
2574   }
2575
2576   /**
2577    * Open the Groovy console
2578    */
2579   void openGroovyConsole()
2580   {
2581     if (groovyConsole == null)
2582     {
2583       groovyConsole = new groovy.ui.Console();
2584       groovyConsole.setVariable("Jalview", this);
2585       groovyConsole.run();
2586
2587       /*
2588        * We allow only one console at a time, so that AlignFrame menu option
2589        * 'Calculate | Run Groovy script' is unambiguous. Disable 'Groovy Console', and
2590        * enable 'Run script', when the console is opened, and the reverse when it is
2591        * closed
2592        */
2593       Window window = (Window) groovyConsole.getFrame();
2594       window.addWindowListener(new WindowAdapter()
2595       {
2596         @Override
2597         public void windowClosed(WindowEvent e)
2598         {
2599           /*
2600            * rebind CMD-Q from Groovy Console to Jalview Quit
2601            */
2602           addQuitHandler();
2603           enableExecuteGroovy(false);
2604         }
2605       });
2606     }
2607
2608     /*
2609      * show Groovy console window (after close and reopen)
2610      */
2611     ((Window) groovyConsole.getFrame()).setVisible(true);
2612
2613     /*
2614      * if we got this far, enable 'Run Groovy' in AlignFrame menus and disable
2615      * opening a second console
2616      */
2617     enableExecuteGroovy(true);
2618   }
2619
2620   /**
2621    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
2622    * binding when opened
2623    */
2624   protected void addQuitHandler()
2625   {
2626     getRootPane()
2627             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
2628                     KeyStroke
2629                             .getKeyStroke(KeyEvent.VK_Q,
2630                                     jalview.util.ShortcutKeyMaskExWrapper
2631                                             .getMenuShortcutKeyMaskEx()),
2632                     "Quit");
2633     getRootPane().getActionMap().put("Quit", new AbstractAction()
2634     {
2635       @Override
2636       public void actionPerformed(ActionEvent e)
2637       {
2638         desktopQuit();
2639       }
2640     });
2641   }
2642
2643   /**
2644    * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2645    * 
2646    * @param enabled
2647    *          true if Groovy console is open
2648    */
2649   public void enableExecuteGroovy(boolean enabled)
2650   {
2651     /*
2652      * disable opening a second Groovy console (or re-enable when the console is
2653      * closed)
2654      */
2655     groovyShell.setEnabled(!enabled);
2656
2657     AlignFrame[] alignFrames = getAlignFrames();
2658     if (alignFrames != null)
2659     {
2660       for (AlignFrame af : alignFrames)
2661       {
2662         af.setGroovyEnabled(enabled);
2663       }
2664     }
2665   }
2666
2667   /**
2668    * Progress bars managed by the IProgressIndicator method.
2669    */
2670   private Hashtable<Long, JPanel> progressBars;
2671
2672   private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2673
2674   /*
2675    * (non-Javadoc)
2676    * 
2677    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2678    */
2679   @Override
2680   public void setProgressBar(String message, long id)
2681   {
2682     if (progressBars == null)
2683     {
2684       progressBars = new Hashtable<>();
2685       progressBarHandlers = new Hashtable<>();
2686     }
2687
2688     if (progressBars.get(Long.valueOf(id)) != null)
2689     {
2690       JPanel panel = progressBars.remove(Long.valueOf(id));
2691       if (progressBarHandlers.contains(Long.valueOf(id)))
2692       {
2693         progressBarHandlers.remove(Long.valueOf(id));
2694       }
2695       removeProgressPanel(panel);
2696     }
2697     else
2698     {
2699       progressBars.put(Long.valueOf(id), addProgressPanel(message));
2700     }
2701   }
2702
2703   /*
2704    * (non-Javadoc)
2705    * 
2706    * @see jalview.gui.IProgressIndicator#registerHandler(long,
2707    * jalview.gui.IProgressIndicatorHandler)
2708    */
2709   @Override
2710   public void registerHandler(final long id,
2711           final IProgressIndicatorHandler handler)
2712   {
2713     if (progressBarHandlers == null
2714             || !progressBars.containsKey(Long.valueOf(id)))
2715     {
2716       throw new Error(MessageManager.getString(
2717               "error.call_setprogressbar_before_registering_handler"));
2718     }
2719     progressBarHandlers.put(Long.valueOf(id), handler);
2720     final JPanel progressPanel = progressBars.get(Long.valueOf(id));
2721     if (handler.canCancel())
2722     {
2723       JButton cancel = new JButton(
2724               MessageManager.getString("action.cancel"));
2725       final IProgressIndicator us = this;
2726       cancel.addActionListener(new ActionListener()
2727       {
2728
2729         @Override
2730         public void actionPerformed(ActionEvent e)
2731         {
2732           handler.cancelActivity(id);
2733           us.setProgressBar(MessageManager
2734                   .formatMessage("label.cancelled_params", new Object[]
2735                   { ((JLabel) progressPanel.getComponent(0)).getText() }),
2736                   id);
2737         }
2738       });
2739       progressPanel.add(cancel, BorderLayout.EAST);
2740     }
2741   }
2742
2743   /**
2744    * 
2745    * @return true if any progress bars are still active
2746    */
2747   @Override
2748   public boolean operationInProgress()
2749   {
2750     if (progressBars != null && progressBars.size() > 0)
2751     {
2752       return true;
2753     }
2754     return false;
2755   }
2756
2757   /**
2758    * This will return the first AlignFrame holding the given viewport instance.
2759    * It will break if there are more than one AlignFrames viewing a particular
2760    * av.
2761    * 
2762    * @param viewport
2763    * @return alignFrame for viewport
2764    */
2765   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2766   {
2767     if (desktop != null)
2768     {
2769       AlignmentPanel[] aps = getAlignmentPanels(
2770               viewport.getSequenceSetId());
2771       for (int panel = 0; aps != null && panel < aps.length; panel++)
2772       {
2773         if (aps[panel] != null && aps[panel].av == viewport)
2774         {
2775           return aps[panel].alignFrame;
2776         }
2777       }
2778     }
2779     return null;
2780   }
2781
2782   public VamsasApplication getVamsasApplication()
2783   {
2784     // TODO: JAL-3311 remove remaining code from Jalview relating to VAMSAS
2785     return null;
2786
2787   }
2788
2789   /**
2790    * flag set if jalview GUI is being operated programmatically
2791    */
2792   private boolean inBatchMode = false;
2793
2794   /**
2795    * check if jalview GUI is being operated programmatically
2796    * 
2797    * @return inBatchMode
2798    */
2799   public boolean isInBatchMode()
2800   {
2801     return inBatchMode;
2802   }
2803
2804   /**
2805    * set flag if jalview GUI is being operated programmatically
2806    * 
2807    * @param inBatchMode
2808    */
2809   public void setInBatchMode(boolean inBatchMode)
2810   {
2811     this.inBatchMode = inBatchMode;
2812   }
2813
2814   /**
2815    * start service discovery and wait till it is done
2816    */
2817   public void startServiceDiscovery()
2818   {
2819     startServiceDiscovery(false);
2820   }
2821
2822   /**
2823    * start service discovery threads - blocking or non-blocking
2824    * 
2825    * @param blocking
2826    */
2827   public void startServiceDiscovery(boolean blocking)
2828   {
2829     startServiceDiscovery(blocking, false);
2830   }
2831
2832   /**
2833    * start service discovery threads
2834    * 
2835    * @param blocking
2836    *          - false means call returns immediately
2837    * @param ignore_SHOW_JWS2_SERVICES_preference
2838    *          - when true JABA services are discovered regardless of user's JWS2
2839    *          discovery preference setting
2840    */
2841   public void startServiceDiscovery(boolean blocking,
2842           boolean ignore_SHOW_JWS2_SERVICES_preference)
2843   {
2844     boolean alive = true;
2845     Thread t0 = null, t1 = null, t2 = null;
2846     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
2847     if (true)
2848     {
2849       // todo: changesupport handlers need to be transferred
2850       if (discoverer == null)
2851       {
2852         discoverer = new jalview.ws.jws1.Discoverer();
2853         // register PCS handler for desktop.
2854         discoverer.addPropertyChangeListener(changeSupport);
2855       }
2856       // JAL-940 - disabled JWS1 service configuration - always start discoverer
2857       // until we phase out completely
2858       (t0 = new Thread(discoverer)).start();
2859     }
2860
2861     if (ignore_SHOW_JWS2_SERVICES_preference
2862             || Cache.getDefault("SHOW_JWS2_SERVICES", true))
2863     {
2864       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2865               .startDiscoverer(changeSupport);
2866     }
2867     Thread t3 = null;
2868     {
2869       // TODO: do rest service discovery
2870     }
2871     if (blocking)
2872     {
2873       while (alive)
2874       {
2875         try
2876         {
2877           Thread.sleep(15);
2878         } catch (Exception e)
2879         {
2880         }
2881         alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
2882                 || (t3 != null && t3.isAlive())
2883                 || (t0 != null && t0.isAlive());
2884       }
2885     }
2886   }
2887
2888   /**
2889    * called to check if the service discovery process completed successfully.
2890    * 
2891    * @param evt
2892    */
2893   protected void JalviewServicesChanged(PropertyChangeEvent evt)
2894   {
2895     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2896     {
2897       final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2898               .getErrorMessages();
2899       if (ermsg != null)
2900       {
2901         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2902         {
2903           if (serviceChangedDialog == null)
2904           {
2905             // only run if we aren't already displaying one of these.
2906             addDialogThread(serviceChangedDialog = new Runnable()
2907             {
2908               @Override
2909               public void run()
2910               {
2911
2912                 /*
2913                  * JalviewDialog jd =new JalviewDialog() {
2914                  * 
2915                  * @Override protected void cancelPressed() { // TODO Auto-generated method stub
2916                  * 
2917                  * }@Override protected void okPressed() { // TODO Auto-generated method stub
2918                  * 
2919                  * }@Override protected void raiseClosed() { // TODO Auto-generated method stub
2920                  * 
2921                  * } }; jd.initDialogFrame(new JLabel("<html><table width=\"450\"><tr><td>" +
2922                  * ermsg +
2923                  * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
2924                  * + " or mis-configured HTTP proxy settings.<br/>" +
2925                  * "Check the <em>Connections</em> and <em>Web services</em> tab of the" +
2926                  * " Tools->Preferences dialog box to change them.</td></tr></table></html>" ),
2927                  * true, true, "Web Service Configuration Problem", 450, 400);
2928                  * 
2929                  * jd.waitForInput();
2930                  */
2931                 JvOptionPane.showConfirmDialog(Desktop.desktop,
2932                         new JLabel("<html><table width=\"450\"><tr><td>"
2933                                 + ermsg + "</td></tr></table>"
2934                                 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
2935                                 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
2936                                 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
2937                                 + " Tools->Preferences dialog box to change them.</p></html>"),
2938                         "Web Service Configuration Problem",
2939                         JvOptionPane.DEFAULT_OPTION,
2940                         JvOptionPane.ERROR_MESSAGE);
2941                 serviceChangedDialog = null;
2942
2943               }
2944             });
2945           }
2946         }
2947         else
2948         {
2949           jalview.bin.Console.error(
2950                   "Errors reported by JABA discovery service. Check web services preferences.\n"
2951                           + ermsg);
2952         }
2953       }
2954     }
2955   }
2956
2957   private Runnable serviceChangedDialog = null;
2958
2959   /**
2960    * start a thread to open a URL in the configured browser. Pops up a warning
2961    * dialog to the user if there is an exception when calling out to the browser
2962    * to open the URL.
2963    * 
2964    * @param url
2965    */
2966   public static void showUrl(final String url)
2967   {
2968     showUrl(url, Desktop.instance);
2969   }
2970
2971   /**
2972    * Like showUrl but allows progress handler to be specified
2973    * 
2974    * @param url
2975    * @param progress
2976    *          (null) or object implementing IProgressIndicator
2977    */
2978   public static void showUrl(final String url,
2979           final IProgressIndicator progress)
2980   {
2981     new Thread(new Runnable()
2982     {
2983       @Override
2984       public void run()
2985       {
2986         try
2987         {
2988           if (progress != null)
2989           {
2990             progress.setProgressBar(MessageManager
2991                     .formatMessage("status.opening_params", new Object[]
2992                     { url }), this.hashCode());
2993           }
2994           jalview.util.BrowserLauncher.openURL(url);
2995         } catch (Exception ex)
2996         {
2997           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2998                   MessageManager
2999                           .getString("label.web_browser_not_found_unix"),
3000                   MessageManager.getString("label.web_browser_not_found"),
3001                   JvOptionPane.WARNING_MESSAGE);
3002
3003           ex.printStackTrace();
3004         }
3005         if (progress != null)
3006         {
3007           progress.setProgressBar(null, this.hashCode());
3008         }
3009       }
3010     }).start();
3011   }
3012
3013   public static WsParamSetManager wsparamManager = null;
3014
3015   public static ParamManager getUserParameterStore()
3016   {
3017     if (wsparamManager == null)
3018     {
3019       wsparamManager = new WsParamSetManager();
3020     }
3021     return wsparamManager;
3022   }
3023
3024   /**
3025    * static hyperlink handler proxy method for use by Jalview's internal windows
3026    * 
3027    * @param e
3028    */
3029   public static void hyperlinkUpdate(HyperlinkEvent e)
3030   {
3031     if (e.getEventType() == EventType.ACTIVATED)
3032     {
3033       String url = null;
3034       try
3035       {
3036         url = e.getURL().toString();
3037         Desktop.showUrl(url);
3038       } catch (Exception x)
3039       {
3040         if (url != null)
3041         {
3042           jalview.bin.Console
3043                   .error("Couldn't handle string " + url + " as a URL.");
3044         }
3045         // ignore any exceptions due to dud links.
3046       }
3047
3048     }
3049   }
3050
3051   /**
3052    * single thread that handles display of dialogs to user.
3053    */
3054   ExecutorService dialogExecutor = Executors.newFixedThreadPool(3);
3055
3056   /**
3057    * flag indicating if dialogExecutor should try to acquire a permit
3058    */
3059   private volatile boolean dialogPause = true;
3060
3061   /**
3062    * pause the queue
3063    */
3064   private java.util.concurrent.Semaphore block = new Semaphore(0);
3065
3066   private static groovy.ui.Console groovyConsole;
3067
3068   /**
3069    * add another dialog thread to the queue
3070    * 
3071    * @param prompter
3072    */
3073   public void addDialogThread(final Runnable prompter)
3074   {
3075     dialogExecutor.submit(new Runnable()
3076     {
3077       @Override
3078       public void run()
3079       {
3080         if (dialogPause)
3081         {
3082           try
3083           {
3084             block.acquire();
3085           } catch (InterruptedException x)
3086           {
3087           }
3088         }
3089         if (instance == null)
3090         {
3091           return;
3092         }
3093         try
3094         {
3095           SwingUtilities.invokeAndWait(prompter);
3096         } catch (Exception q)
3097         {
3098           jalview.bin.Console.warn("Unexpected Exception in dialog thread.",
3099                   q);
3100         }
3101       }
3102     });
3103   }
3104
3105   public void startDialogQueue()
3106   {
3107     // set the flag so we don't pause waiting for another permit and semaphore
3108     // the current task to begin
3109     dialogPause = false;
3110     block.release();
3111   }
3112
3113   /**
3114    * Outputs an image of the desktop to file in EPS format, after prompting the
3115    * user for choice of Text or Lineart character rendering (unless a preference
3116    * has been set). The file name is generated as
3117    * 
3118    * <pre>
3119    * Jalview_snapshot_nnnnn.eps where nnnnn is the current timestamp in milliseconds
3120    * </pre>
3121    */
3122   @Override
3123   protected void snapShotWindow_actionPerformed(ActionEvent e)
3124   {
3125     // currently the menu option to do this is not shown
3126     invalidate();
3127
3128     int width = getWidth();
3129     int height = getHeight();
3130     File of = new File(
3131             "Jalview_snapshot_" + System.currentTimeMillis() + ".eps");
3132     ImageWriterI writer = new ImageWriterI()
3133     {
3134       @Override
3135       public void exportImage(Graphics g) throws Exception
3136       {
3137         paintAll(g);
3138         jalview.bin.Console.info("Successfully written snapshot to file "
3139                 + of.getAbsolutePath());
3140       }
3141     };
3142     String title = "View of desktop";
3143     ImageExporter exporter = new ImageExporter(writer, null, TYPE.EPS,
3144             title);
3145     try
3146     {
3147       exporter.doExport(of, this, width, height, title);
3148     } catch (ImageOutputException ioex)
3149     {
3150       jalview.bin.Console.error(
3151               "Unexpected error whilst writing Jalview desktop snapshot as EPS",
3152               ioex);
3153     }
3154   }
3155
3156   /**
3157    * Explode the views in the given SplitFrame into separate SplitFrame windows.
3158    * This respects (remembers) any previous 'exploded geometry' i.e. the size
3159    * and location last time the view was expanded (if any). However it does not
3160    * remember the split pane divider location - this is set to match the
3161    * 'exploding' frame.
3162    * 
3163    * @param sf
3164    */
3165   public void explodeViews(SplitFrame sf)
3166   {
3167     AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3168     AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3169     List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3170             .getAlignPanels();
3171     List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3172             .getAlignPanels();
3173     int viewCount = topPanels.size();
3174     if (viewCount < 2)
3175     {
3176       return;
3177     }
3178
3179     /*
3180      * Processing in reverse order works, forwards order leaves the first panels not
3181      * visible. I don't know why!
3182      */
3183     for (int i = viewCount - 1; i >= 0; i--)
3184     {
3185       /*
3186        * Make new top and bottom frames. These take over the respective AlignmentPanel
3187        * objects, including their AlignmentViewports, so the cdna/protein
3188        * relationships between the viewports is carried over to the new split frames.
3189        * 
3190        * explodedGeometry holds the (x, y) position of the previously exploded
3191        * SplitFrame, and the (width, height) of the AlignFrame component
3192        */
3193       AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3194       AlignFrame newTopFrame = new AlignFrame(topPanel);
3195       newTopFrame.setSize(oldTopFrame.getSize());
3196       newTopFrame.setVisible(true);
3197       Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3198               .getExplodedGeometry();
3199       if (geometry != null)
3200       {
3201         newTopFrame.setSize(geometry.getSize());
3202       }
3203
3204       AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3205       AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3206       newBottomFrame.setSize(oldBottomFrame.getSize());
3207       newBottomFrame.setVisible(true);
3208       geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3209               .getExplodedGeometry();
3210       if (geometry != null)
3211       {
3212         newBottomFrame.setSize(geometry.getSize());
3213       }
3214
3215       topPanel.av.setGatherViewsHere(false);
3216       bottomPanel.av.setGatherViewsHere(false);
3217       JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3218               newBottomFrame);
3219       if (geometry != null)
3220       {
3221         splitFrame.setLocation(geometry.getLocation());
3222       }
3223       Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3224     }
3225
3226     /*
3227      * Clear references to the panels (now relocated in the new SplitFrames) before
3228      * closing the old SplitFrame.
3229      */
3230     topPanels.clear();
3231     bottomPanels.clear();
3232     sf.close();
3233   }
3234
3235   /**
3236    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3237    * back into the given SplitFrame as additional views. Note that the gathered
3238    * frames may themselves have multiple views.
3239    * 
3240    * @param source
3241    */
3242   public void gatherViews(GSplitFrame source)
3243   {
3244     /*
3245      * special handling of explodedGeometry for a view within a SplitFrame: - it
3246      * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3247      * height) of the AlignFrame component
3248      */
3249     AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3250     AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3251     myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3252             source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3253     myBottomFrame.viewport
3254             .setExplodedGeometry(new Rectangle(source.getX(), source.getY(),
3255                     myBottomFrame.getWidth(), myBottomFrame.getHeight()));
3256     myTopFrame.viewport.setGatherViewsHere(true);
3257     myBottomFrame.viewport.setGatherViewsHere(true);
3258     String topViewId = myTopFrame.viewport.getSequenceSetId();
3259     String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3260
3261     JInternalFrame[] frames = desktop.getAllFrames();
3262     for (JInternalFrame frame : frames)
3263     {
3264       if (frame instanceof SplitFrame && frame != source)
3265       {
3266         SplitFrame sf = (SplitFrame) frame;
3267         AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3268         AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3269         boolean gatherThis = false;
3270         for (int a = 0; a < topFrame.alignPanels.size(); a++)
3271         {
3272           AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3273           AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3274           if (topViewId.equals(topPanel.av.getSequenceSetId())
3275                   && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3276           {
3277             gatherThis = true;
3278             topPanel.av.setGatherViewsHere(false);
3279             bottomPanel.av.setGatherViewsHere(false);
3280             topPanel.av.setExplodedGeometry(
3281                     new Rectangle(sf.getLocation(), topFrame.getSize()));
3282             bottomPanel.av.setExplodedGeometry(
3283                     new Rectangle(sf.getLocation(), bottomFrame.getSize()));
3284             myTopFrame.addAlignmentPanel(topPanel, false);
3285             myBottomFrame.addAlignmentPanel(bottomPanel, false);
3286           }
3287         }
3288
3289         if (gatherThis)
3290         {
3291           topFrame.getAlignPanels().clear();
3292           bottomFrame.getAlignPanels().clear();
3293           sf.close();
3294         }
3295       }
3296     }
3297
3298     /*
3299      * The dust settles...give focus to the tab we did this from.
3300      */
3301     myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3302   }
3303
3304   public static groovy.ui.Console getGroovyConsole()
3305   {
3306     return groovyConsole;
3307   }
3308
3309   /**
3310    * handles the payload of a drag and drop event.
3311    * 
3312    * TODO refactor to desktop utilities class
3313    * 
3314    * @param files
3315    *          - Data source strings extracted from the drop event
3316    * @param protocols
3317    *          - protocol for each data source extracted from the drop event
3318    * @param evt
3319    *          - the drop event
3320    * @param t
3321    *          - the payload from the drop event
3322    * @throws Exception
3323    */
3324   public static void transferFromDropTarget(List<Object> files,
3325           List<DataSourceType> protocols, DropTargetDropEvent evt,
3326           Transferable t) throws Exception
3327   {
3328
3329     DataFlavor uriListFlavor = new DataFlavor(
3330             "text/uri-list;class=java.lang.String"), urlFlavour = null;
3331     try
3332     {
3333       urlFlavour = new DataFlavor(
3334               "application/x-java-url; class=java.net.URL");
3335     } catch (ClassNotFoundException cfe)
3336     {
3337       jalview.bin.Console.debug("Couldn't instantiate the URL dataflavor.",
3338               cfe);
3339     }
3340
3341     if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
3342     {
3343
3344       try
3345       {
3346         java.net.URL url = (URL) t.getTransferData(urlFlavour);
3347         // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
3348         // means url may be null.
3349         if (url != null)
3350         {
3351           protocols.add(DataSourceType.URL);
3352           files.add(url.toString());
3353           jalview.bin.Console.debug("Drop handled as URL dataflavor "
3354                   + files.get(files.size() - 1));
3355           return;
3356         }
3357         else
3358         {
3359           if (Platform.isAMacAndNotJS())
3360           {
3361             System.err.println(
3362                     "Please ignore plist error - occurs due to problem with java 8 on OSX");
3363           }
3364         }
3365       } catch (Throwable ex)
3366       {
3367         jalview.bin.Console.debug("URL drop handler failed.", ex);
3368       }
3369     }
3370     if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3371     {
3372       // Works on Windows and MacOSX
3373       jalview.bin.Console.debug("Drop handled as javaFileListFlavor");
3374       for (Object file : (List) t
3375               .getTransferData(DataFlavor.javaFileListFlavor))
3376       {
3377         files.add(file);
3378         protocols.add(DataSourceType.FILE);
3379       }
3380     }
3381     else
3382     {
3383       // Unix like behaviour
3384       boolean added = false;
3385       String data = null;
3386       if (t.isDataFlavorSupported(uriListFlavor))
3387       {
3388         jalview.bin.Console.debug("Drop handled as uriListFlavor");
3389         // This is used by Unix drag system
3390         data = (String) t.getTransferData(uriListFlavor);
3391       }
3392       if (data == null)
3393       {
3394         // fallback to text: workaround - on OSX where there's a JVM bug
3395         jalview.bin.Console
3396                 .debug("standard URIListFlavor failed. Trying text");
3397         // try text fallback
3398         DataFlavor textDf = new DataFlavor(
3399                 "text/plain;class=java.lang.String");
3400         if (t.isDataFlavorSupported(textDf))
3401         {
3402           data = (String) t.getTransferData(textDf);
3403         }
3404
3405         jalview.bin.Console.debug("Plain text drop content returned "
3406                 + (data == null ? "Null - failed" : data));
3407
3408       }
3409       if (data != null)
3410       {
3411         while (protocols.size() < files.size())
3412         {
3413           jalview.bin.Console.debug("Adding missing FILE protocol for "
3414                   + files.get(protocols.size()));
3415           protocols.add(DataSourceType.FILE);
3416         }
3417         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3418                 data, "\r\n"); st.hasMoreTokens();)
3419         {
3420           added = true;
3421           String s = st.nextToken();
3422           if (s.startsWith("#"))
3423           {
3424             // the line is a comment (as per the RFC 2483)
3425             continue;
3426           }
3427           java.net.URI uri = new java.net.URI(s);
3428           if (uri.getScheme().toLowerCase(Locale.ROOT).startsWith("http"))
3429           {
3430             protocols.add(DataSourceType.URL);
3431             files.add(uri.toString());
3432           }
3433           else
3434           {
3435             // otherwise preserve old behaviour: catch all for file objects
3436             java.io.File file = new java.io.File(uri);
3437             protocols.add(DataSourceType.FILE);
3438             files.add(file.toString());
3439           }
3440         }
3441       }
3442
3443       if (jalview.bin.Console.isDebugEnabled())
3444       {
3445         if (data == null || !added)
3446         {
3447
3448           if (t.getTransferDataFlavors() != null
3449                   && t.getTransferDataFlavors().length > 0)
3450           {
3451             jalview.bin.Console.debug(
3452                     "Couldn't resolve drop data. Here are the supported flavors:");
3453             for (DataFlavor fl : t.getTransferDataFlavors())
3454             {
3455               jalview.bin.Console.debug(
3456                       "Supported transfer dataflavor: " + fl.toString());
3457               Object df = t.getTransferData(fl);
3458               if (df != null)
3459               {
3460                 jalview.bin.Console.debug("Retrieves: " + df);
3461               }
3462               else
3463               {
3464                 jalview.bin.Console.debug("Retrieved nothing");
3465               }
3466             }
3467           }
3468           else
3469           {
3470             jalview.bin.Console
3471                     .debug("Couldn't resolve dataflavor for drop: "
3472                             + t.toString());
3473           }
3474         }
3475       }
3476     }
3477     if (Platform.isWindowsAndNotJS())
3478     {
3479       jalview.bin.Console
3480               .debug("Scanning dropped content for Windows Link Files");
3481
3482       // resolve any .lnk files in the file drop
3483       for (int f = 0; f < files.size(); f++)
3484       {
3485         String source = files.get(f).toString().toLowerCase(Locale.ROOT);
3486         if (protocols.get(f).equals(DataSourceType.FILE)
3487                 && (source.endsWith(".lnk") || source.endsWith(".url")
3488                         || source.endsWith(".site")))
3489         {
3490           try
3491           {
3492             Object obj = files.get(f);
3493             File lf = (obj instanceof File ? (File) obj
3494                     : new File((String) obj));
3495             // process link file to get a URL
3496             jalview.bin.Console.debug("Found potential link file: " + lf);
3497             WindowsShortcut wscfile = new WindowsShortcut(lf);
3498             String fullname = wscfile.getRealFilename();
3499             protocols.set(f, FormatAdapter.checkProtocol(fullname));
3500             files.set(f, fullname);
3501             jalview.bin.Console.debug("Parsed real filename " + fullname
3502                     + " to extract protocol: " + protocols.get(f));
3503           } catch (Exception ex)
3504           {
3505             jalview.bin.Console.error(
3506                     "Couldn't parse " + files.get(f) + " as a link file.",
3507                     ex);
3508           }
3509         }
3510       }
3511     }
3512   }
3513
3514   /**
3515    * Sets the Preferences property for experimental features to True or False
3516    * depending on the state of the controlling menu item
3517    */
3518   @Override
3519   protected void showExperimental_actionPerformed(boolean selected)
3520   {
3521     Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
3522   }
3523
3524   /**
3525    * Answers a (possibly empty) list of any structure viewer frames (currently
3526    * for either Jmol or Chimera) which are currently open. This may optionally
3527    * be restricted to viewers of a specified class, or viewers linked to a
3528    * specified alignment panel.
3529    * 
3530    * @param apanel
3531    *          if not null, only return viewers linked to this panel
3532    * @param structureViewerClass
3533    *          if not null, only return viewers of this class
3534    * @return
3535    */
3536   public List<StructureViewerBase> getStructureViewers(
3537           AlignmentPanel apanel,
3538           Class<? extends StructureViewerBase> structureViewerClass)
3539   {
3540     List<StructureViewerBase> result = new ArrayList<>();
3541     JInternalFrame[] frames = Desktop.instance.getAllFrames();
3542
3543     for (JInternalFrame frame : frames)
3544     {
3545       if (frame instanceof StructureViewerBase)
3546       {
3547         if (structureViewerClass == null
3548                 || structureViewerClass.isInstance(frame))
3549         {
3550           if (apanel == null
3551                   || ((StructureViewerBase) frame).isLinkedWith(apanel))
3552           {
3553             result.add((StructureViewerBase) frame);
3554           }
3555         }
3556       }
3557     }
3558     return result;
3559   }
3560
3561   public static final String debugScaleMessage = "Desktop graphics transform scale=";
3562
3563   private static boolean debugScaleMessageDone = false;
3564
3565   public static void debugScaleMessage(Graphics g)
3566   {
3567     if (debugScaleMessageDone)
3568     {
3569       return;
3570     }
3571     // output used by tests to check HiDPI scaling settings in action
3572     try
3573     {
3574       Graphics2D gg = (Graphics2D) g;
3575       if (gg != null)
3576       {
3577         AffineTransform t = gg.getTransform();
3578         double scaleX = t.getScaleX();
3579         double scaleY = t.getScaleY();
3580         jalview.bin.Console.debug(debugScaleMessage + scaleX + " (X)");
3581         jalview.bin.Console.debug(debugScaleMessage + scaleY + " (Y)");
3582         debugScaleMessageDone = true;
3583       }
3584       else
3585       {
3586         jalview.bin.Console.debug("Desktop graphics null");
3587       }
3588     } catch (Exception e)
3589     {
3590       jalview.bin.Console.debug(Cache.getStackTraceString(e));
3591     }
3592   }
3593
3594   /**
3595    * closes the current instance window, disposes and forgets about it.
3596    */
3597   public static void closeDesktop()
3598   {
3599     if (Desktop.instance != null)
3600     {
3601       Desktop.instance.closeAll_actionPerformed(null);
3602       Desktop.instance.setVisible(false);
3603       Desktop.instance.dispose();
3604       Desktop.instance = null;
3605     }
3606   }
3607 }