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