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