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