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