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