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