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