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