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