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