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