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