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