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