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