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