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