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