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