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