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