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