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