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