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