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