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