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