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