Clover icon

Coverage Report

  1. Project Clover database Fri Jan 16 2026 12:43:44 GMT
  2. Package jalview.gui

File Desktop.java

 

Coverage histogram

../../img/srcFileCovDistChart5.png
43% of files have more coverage

Code metrics

518
1,202
165
3
4,277
3,084
511
0.43
7.28
55
3.1

Classes

Class Line # Actions
Desktop 175 1,150 479
0.444938844.5%
Desktop.MyDesktopManager 328 25 19
0.220%
Desktop.MyDesktopPane 2719 27 13
0.3095238231%
 

Contributing tests

This file is covered by 298 tests. .

Source view

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