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