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