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