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