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