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