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