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