Clover icon

Coverage Report

  1. Project Clover database Thu Dec 4 2025 14:43:25 GMT
  2. Package jalview.gui

File Desktop.java

 

Coverage histogram

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

Code metrics

518
1,198
165
3
4,272
3,079
511
0.43
7.26
55
3.1

Classes

Class Line # Actions
Desktop 175 1,146 479
0.4397993444%
Desktop.MyDesktopManager 328 25 19
0.220%
Desktop.MyDesktopPane 2714 27 13
0.3095238231%
 

Contributing tests

This file is covered by 284 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  22885 toggle public static MyDesktopPane getDesktopPane()
290    {
291  22885 Desktop desktop = getInstance();
292  22885 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  34917 toggle public static Desktop getInstance()
303    {
304  34917 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  765 toggle @Override
339    public void activateFrame(JInternalFrame f)
340    {
341  765 try
342    {
343  765 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  524 toggle @Override
364    public void closeFrame(JInternalFrame f)
365    {
366  524 delegate.closeFrame(f);
367    }
368   
 
369  757 toggle @Override
370    public void deactivateFrame(JInternalFrame f)
371    {
372  757 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    // This is important for jalviewjsTest task and also early Getdown
702    // splashscreen removal
703  11 jalview.bin.Console.info((Platform.isJS() ? "JALVIEWJS" : "JALVIEW")
704    + ": CREATED DESKTOP");
705   
706    }
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  472 toggle public static synchronized void addInternalFrame(
957    final JInternalFrame frame, String title, int w, int h)
958    {
959    // 58 classes
960   
961  472 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  549 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  549 frame.setTitle(title);
997  549 if (frame.getWidth() < 1 || frame.getHeight() < 1)
998    {
999  138 frame.setSize(w, h);
1000    }
1001  549 if (getInstance() != null && !Jalview.isHeadlessMode())
1002  526 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  526 toggle private void addFrame(JInternalFrame frame, boolean makeVisible,
1020    boolean resizable, boolean ignoreMinSize)
1021    {
1022   
1023  526 openFrameCount++;
1024   
1025  526 boolean isEmbedded = (Platform.getEmbeddedAttribute(frame,
1026    "id") != null);
1027  526 boolean hasEmbeddedSize = (Platform.getDimIfEmbedded(frame, -1,
1028    -1) != null);
1029    // Web page embedding allows us to ignore minimum size
1030  526 ignoreMinSize |= hasEmbeddedSize;
1031   
1032  526 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  466 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  138 frame.setMinimumSize(
1047    new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
1048   
1049    }
1050    }
1051   
1052  526 frame.setVisible(makeVisible);
1053  526 frame.setClosable(true);
1054  526 frame.setResizable(resizable);
1055  526 frame.setMaximizable(resizable);
1056  526 frame.setIconifiable(resizable);
1057  526 frame.setOpaque(Platform.isJS());
1058   
1059  526 if (!isEmbedded && frame.getX() < 1 && frame.getY() < 1)
1060    {
1061  399 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  526 final JMenuItem menuItem = new JMenuItem(frame.getTitle());
1070  526 frame.addInternalFrameListener(new InternalFrameAdapter()
1071    {
 
1072  762 toggle @Override
1073    public void internalFrameActivated(InternalFrameEvent evt)
1074    {
1075  762 JInternalFrame itf = getDesktopPane().getSelectedFrame();
1076  762 if (itf != null)
1077    {
1078  762 if (itf instanceof AlignFrame)
1079    {
1080  518 Jalview.getInstance().setCurrentAlignFrame((AlignFrame) itf);
1081    }
1082  762 itf.requestFocus();
1083    }
1084    }
1085   
 
1086  571 toggle @Override
1087    public void internalFrameClosed(InternalFrameEvent evt)
1088    {
1089  571 PaintRefresher.RemoveComponent(frame);
1090   
1091    /*
1092    * defensive check to prevent frames being
1093    * added half off the window
1094    */
1095  571 if (openFrameCount > 0)
1096    {
1097  518 openFrameCount--;
1098    }
1099   
1100    /*
1101    * ensure no reference to alignFrame retained by menu item listener
1102    */
1103  571 if (menuItem.getActionListeners().length > 0)
1104    {
1105  518 menuItem.removeActionListener(menuItem.getActionListeners()[0]);
1106    }
1107  571 getInstance().windowMenu.remove(menuItem);
1108    }
1109    });
1110   
1111  526 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  526 setKeyBindings(frame);
1129   
1130    // Since the latest FlatLaf patch, we occasionally have problems showing
1131    // structureViewer frames...
1132  526 int tries = 3;
1133  526 boolean shown = false;
1134  526 Exception last = null;
1135  526 do
1136    {
1137  526 try
1138    {
1139  526 getDesktopPane().add(frame);
1140  526 shown = true;
1141    } catch (IllegalArgumentException iaex)
1142    {
1143  0 last = iaex;
1144  0 tries--;
1145  0 jalview.bin.Console.info("Squashed IllegalArgument Exception ("
1146    + tries + " left) for " + frame.getTitle(), iaex);
1147  0 try
1148    {
1149  0 Thread.sleep(5);
1150    } catch (InterruptedException iex)
1151    {
1152    }
1153  0 ;
1154    }
1155  526 } while (!shown && tries > 0);
1156  526 if (!shown)
1157    {
1158  0 jalview.bin.Console.error(
1159    "Serious Problem whilst showing window " + frame.getTitle(),
1160    last);
1161    }
1162   
1163  526 getInstance().windowMenu.add(menuItem);
1164   
1165  526 frame.toFront();
1166  526 try
1167    {
1168  526 frame.setSelected(true);
1169  526 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  526 toggle private static void setKeyBindings(JInternalFrame frame)
1187    {
1188  526 @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  526 KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
1202    InputEvent.CTRL_DOWN_MASK);
1203  526 KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
1204    Platform.SHORTCUT_KEY_MASK);
1205   
1206  526 InputMap inputMap = frame
1207    .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
1208  526 String ctrlW = ctrlWKey.toString();
1209  526 inputMap.put(ctrlWKey, ctrlW);
1210  526 inputMap.put(cmdWKey, ctrlW);
1211   
1212  526 ActionMap actionMap = frame.getActionMap();
1213  526 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  47 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  187 toggle private void storeLastKnownDimensions(String string, Rectangle jc)
1817    {
1818  187 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  187 Cache.setProperty(string + "SCREEN_X", jc.x + "");
1823  187 Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1824  187 Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1825  187 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  22 toggle public String getAboutMessage()
1855    {
1856  22 StringBuilder message = new StringBuilder(1024);
1857  22 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  22 String latestVersion = Cache.getDefault("LATEST_VERSION", "Checking");
1866  22 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  22 message.append("<br>Authors: ");
1895  22 message.append(Cache.getDefault("AUTHORFNAMES", DEFAULT_AUTHORS));
1896  22 message.append(CITATION);
1897   
1898  22 message.append("</div>");
1899   
1900  22 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  587 for (int i = 0; i < frames.length; i++)
1944    {
1945  324 try
1946    {
1947  324 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  428 toggle private JPanel addProgressPanel(String string)
2334    {
2335  428 if (progressPanel == null)
2336    {
2337  327 progressPanel = new JPanel(new GridLayout(1, 1));
2338  327 totalProgressCount = 0;
2339  327 getContentPane().add(progressPanel, BorderLayout.SOUTH);
2340    }
2341  428 JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
2342  428 JProgressBar progressBar = new JProgressBar();
2343  428 progressBar.setIndeterminate(true);
2344   
2345  428 thisprogress.add(new JLabel(string), BorderLayout.WEST);
2346   
2347  428 thisprogress.add(progressBar, BorderLayout.CENTER);
2348  428 progressPanel.add(thisprogress);
2349  428 ((GridLayout) progressPanel.getLayout()).setRows(
2350    ((GridLayout) progressPanel.getLayout()).getRows() + 1);
2351  428 ++totalProgressCount;
2352  428 validate();
2353  428 return thisprogress;
2354    }
2355   
2356    int totalProgressCount = 0;
2357   
 
2358  423 toggle private void removeProgressPanel(JPanel progbar)
2359    {
2360  423 if (progressPanel != null)
2361    {
2362  402 synchronized (progressPanel)
2363    {
2364  402 progressPanel.remove(progbar);
2365  402 GridLayout gl = (GridLayout) progressPanel.getLayout();
2366  402 gl.setRows(gl.getRows() - 1);
2367  402 if (--totalProgressCount < 1)
2368    {
2369  296 this.getContentPane().remove(progressPanel);
2370  296 progressPanel = null;
2371    }
2372    }
2373    }
2374  423 validate();
2375    }
2376   
 
2377  343 toggle public void stopLoading()
2378    {
2379  343 fileLoadingCount--;
2380  343 if (fileLoadingCount < 1)
2381    {
2382  646 while (fileLoadingPanels.size() > 0)
2383    {
2384  303 removeProgressPanel(fileLoadingPanels.remove(0));
2385    }
2386  343 fileLoadingPanels.clear();
2387  343 fileLoadingCount = 0;
2388    }
2389  343 validate();
2390    }
2391   
 
2392  10 toggle public static int getViewCount(String alignmentId)
2393    {
2394  10 AlignmentViewport[] aps = getViewports(alignmentId);
2395  10 return (aps == null) ? 0 : aps.length;
2396    }
2397   
2398    /**
2399    *
2400    * @param alignmentId
2401    * - if null, all sets are returned
2402    * @return all AlignmentPanels concerning the alignmentId sequence set
2403    */
 
2404  100 toggle public static AlignmentViewPanel[] getAlignmentPanels(String alignmentId)
2405    {
2406  100 if (getDesktopPane() == null)
2407    {
2408    // no frames created and in headless mode
2409    // TODO: verify that frames are recoverable when in headless mode
2410  0 return null;
2411    }
2412  100 List<AlignmentViewPanel> aps = new ArrayList<>();
2413  100 AlignFrame[] frames = Desktop.getDesktopAlignFrames();
2414  100 if (frames == null)
2415    {
2416  33 return null;
2417    }
2418  67 for (AlignFrame af : frames)
2419    {
2420  212 for (AlignmentViewPanel ap : af.getAlignPanels())
2421    {
2422  228 if (alignmentId == null || alignmentId
2423    .equals(ap.getAlignViewport().getSequenceSetId()))
2424    {
2425  138 aps.add(ap);
2426    }
2427    }
2428    }
2429  67 if (aps.size() == 0)
2430    {
2431  10 return null;
2432    }
2433  57 AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
2434  57 return vap;
2435    }
2436   
2437    /**
2438    * get all the viewports on an alignment.
2439    *
2440    * @param sequenceSetId
2441    * unique alignment id (may be null - all viewports returned in that
2442    * case)
2443    * @return all viewports on the alignment bound to sequenceSetId
2444    */
 
2445  10 toggle public static AlignmentViewport[] getViewports(String sequenceSetId)
2446    {
2447  10 List<AlignmentViewport> viewp = new ArrayList<>();
2448  10 if (getDesktopPane() != null)
2449    {
2450  10 AlignFrame[] frames = getDesktopAlignFrames();
2451   
2452  10 for (AlignFrame afr : frames)
2453    {
2454  44 if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
2455    .equals(sequenceSetId))
2456    {
2457  10 if (afr.alignPanels != null)
2458    {
2459  10 for (AlignmentPanel ap : afr.alignPanels)
2460    {
2461  11 if (sequenceSetId == null
2462    || sequenceSetId.equals(ap.av.getSequenceSetId()))
2463    {
2464  11 viewp.add(ap.av);
2465    }
2466    }
2467    }
2468    else
2469    {
2470  0 viewp.add(afr.getViewport());
2471    }
2472    }
2473    }
2474  10 if (viewp.size() > 0)
2475    {
2476  10 return viewp.toArray(new AlignmentViewport[viewp.size()]);
2477    }
2478    }
2479  0 return null;
2480    }
2481   
2482    /**
2483    * Explode the views in the given frame into separate AlignFrame
2484    *
2485    * @param af
2486    */
 
2487  1 toggle public static void explodeViews(AlignFrame af)
2488    {
2489  1 int size = af.alignPanels.size();
2490  1 if (size < 2)
2491    {
2492  0 return;
2493    }
2494   
2495    // FIXME: ideally should use UI interface API
2496  1 FeatureSettings viewFeatureSettings = (af.featureSettings != null
2497    && af.featureSettings.isOpen()) ? af.featureSettings : null;
2498  1 Rectangle fsBounds = af.getFeatureSettingsGeometry();
2499  6 for (int i = 0; i < size; i++)
2500    {
2501  5 AlignmentPanel ap = af.alignPanels.get(i);
2502   
2503  5 AlignFrame newaf = new AlignFrame(ap);
2504   
2505    // transfer reference for existing feature settings to new alignFrame
2506  5 if (ap == af.alignPanel)
2507    {
2508  1 if (viewFeatureSettings != null && viewFeatureSettings.fr.ap == ap)
2509    {
2510  0 newaf.featureSettings = viewFeatureSettings;
2511    }
2512  1 newaf.setFeatureSettingsGeometry(fsBounds);
2513    }
2514   
2515    /*
2516    * Restore the view's last exploded frame geometry if known. Multiple
2517    * views from one exploded frame share and restore the same (frame)
2518    * position and size.
2519    */
2520  5 Rectangle geometry = ap.av.getExplodedGeometry();
2521  5 if (geometry != null)
2522    {
2523  5 newaf.setBounds(geometry);
2524    }
2525   
2526  5 ap.av.setGatherViewsHere(false);
2527   
2528  5 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
2529    AlignFrame.DEFAULT_HEIGHT);
2530    // and materialise a new feature settings dialog instance for the new
2531    // alignframe
2532    // (closes the old as if 'OK' was pressed)
2533  5 if (ap == af.alignPanel && newaf.featureSettings != null
2534    && newaf.featureSettings.isOpen()
2535    && af.alignPanel.getAlignViewport().isShowSequenceFeatures())
2536    {
2537  0 newaf.showFeatureSettingsUI();
2538    }
2539    }
2540   
2541  1 af.featureSettings = null;
2542  1 af.alignPanels.clear();
2543  1 af.closeMenuItem_actionPerformed(true);
2544   
2545    }
2546   
2547    /**
2548    * Gather expanded views (separate AlignFrame's) with the same sequence set
2549    * identifier back in to this frame as additional views, and close the
2550    * expanded views. Note the expanded frames may themselves have multiple
2551    * views. We take the lot.
2552    *
2553    * @param source
2554    */
 
2555  14 toggle public void gatherViews(AlignFrame source)
2556    {
2557  14 source.viewport.setGatherViewsHere(true);
2558  14 source.viewport.setExplodedGeometry(source.getBounds());
2559  14 JInternalFrame[] frames = desktopPane.getAllFrames();
2560  14 String viewId = source.viewport.getSequenceSetId();
2561  103 for (int t = 0; t < frames.length; t++)
2562    {
2563  89 if (frames[t] instanceof AlignFrame && frames[t] != source)
2564    {
2565  45 AlignFrame af = (AlignFrame) frames[t];
2566  45 boolean gatherThis = false;
2567  93 for (int a = 0; a < af.alignPanels.size(); a++)
2568    {
2569  48 AlignmentPanel ap = af.alignPanels.get(a);
2570  48 if (viewId.equals(ap.av.getSequenceSetId()))
2571    {
2572  39 gatherThis = true;
2573  39 ap.av.setGatherViewsHere(false);
2574  39 ap.av.setExplodedGeometry(af.getBounds());
2575  39 source.addAlignmentPanel(ap, false);
2576    }
2577    }
2578   
2579  45 if (gatherThis)
2580    {
2581  39 if (af.featureSettings != null && af.featureSettings.isOpen())
2582    {
2583  0 if (source.featureSettings == null)
2584    {
2585    // preserve the feature settings geometry for this frame
2586  0 source.featureSettings = af.featureSettings;
2587  0 source.setFeatureSettingsGeometry(
2588    af.getFeatureSettingsGeometry());
2589    }
2590    else
2591    {
2592    // close it and forget
2593  0 af.featureSettings.close();
2594    }
2595    }
2596  39 af.alignPanels.clear();
2597  39 af.closeMenuItem_actionPerformed(true);
2598    }
2599    }
2600    }
2601   
2602    // refresh the feature setting UI for the source frame if it exists
2603  14 if (source.featureSettings != null && source.featureSettings.isOpen())
2604    {
2605  0 source.showFeatureSettingsUI();
2606    }
2607   
2608    }
2609   
 
2610  270 toggle public JInternalFrame[] getAllFrames()
2611    {
2612  270 return desktopPane.getAllFrames();
2613    }
2614   
2615    /**
2616    * Checks the given url to see if it gives a response indicating that the user
2617    * should be informed of a new questionnaire.
2618    *
2619    * @param url
2620    */
 
2621  39 toggle public void checkForQuestionnaire(String url)
2622    {
2623  39 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2624    // javax.swing.SwingUtilities.invokeLater(jvq);
2625  39 new Thread(jvq).start();
2626    }
2627   
 
2628  11 toggle public void checkURLLinks()
2629    {
2630    // Thread off the URL link checker
2631  11 addDialogThread(new Runnable()
2632    {
 
2633  11 toggle @Override
2634    public void run()
2635    {
2636  11 if (Cache.getDefault("CHECKURLLINKS", true))
2637    {
2638    // check what the actual links are - if it's just the default don't
2639    // bother with the warning
2640  11 List<String> links = Preferences.getInstance().sequenceUrlLinks
2641    .getLinksForMenu();
2642   
2643    // only need to check links if there is one with a
2644    // SEQUENCE_ID which is not the default EMBL_EBI link
2645  11 ListIterator<String> li = links.listIterator();
2646  11 boolean check = false;
2647  11 List<JLabel> urls = new ArrayList<>();
2648  22 while (li.hasNext())
2649    {
2650  11 String link = li.next();
2651  11 if (link.contains(jalview.util.UrlConstants.SEQUENCE_ID)
2652    && !UrlConstants.isDefaultString(link))
2653    {
2654  0 check = true;
2655  0 int barPos = link.indexOf("|");
2656  0 String urlMsg = barPos == -1 ? link
2657    : link.substring(0, barPos) + ": "
2658    + link.substring(barPos + 1);
2659  0 urls.add(new JLabel(urlMsg));
2660    }
2661    }
2662  11 if (!check)
2663    {
2664  11 return;
2665    }
2666   
2667    // ask user to check in case URL links use old style tokens
2668    // ($SEQUENCE_ID$ for sequence id _or_ accession id)
2669  0 JPanel msgPanel = new JPanel();
2670  0 msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
2671  0 msgPanel.add(Box.createVerticalGlue());
2672  0 JLabel msg = new JLabel(MessageManager
2673    .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
2674  0 JLabel msg2 = new JLabel(MessageManager
2675    .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
2676  0 msgPanel.add(msg);
2677  0 for (JLabel url : urls)
2678    {
2679  0 msgPanel.add(url);
2680    }
2681  0 msgPanel.add(msg2);
2682   
2683  0 final JCheckBox jcb = new JCheckBox(
2684    MessageManager.getString("label.do_not_display_again"));
2685  0 jcb.addActionListener(new ActionListener()
2686    {
 
2687  0 toggle @Override
2688    public void actionPerformed(ActionEvent e)
2689    {
2690    // update Cache settings for "don't show this again"
2691  0 boolean showWarningAgain = !jcb.isSelected();
2692  0 Cache.setProperty("CHECKURLLINKS",
2693    Boolean.valueOf(showWarningAgain).toString());
2694    }
2695    });
2696  0 msgPanel.add(jcb);
2697   
2698  0 JvOptionPane.showMessageDialog(desktopPane, msgPanel,
2699    MessageManager
2700    .getString("label.SEQUENCE_ID_no_longer_used"),
2701    JvOptionPane.WARNING_MESSAGE);
2702    }
2703    }
2704    });
2705    }
2706   
2707    /**
2708    * Proxy class for JDesktopPane which optionally displays the current memory
2709    * usage and highlights the desktop area with a red bar if free memory runs
2710    * low.
2711    *
2712    * @author AMW
2713    */
 
2714    public class MyDesktopPane extends JDesktopPane implements Runnable
2715    {
2716    private static final float ONE_MB = 1048576f;
2717   
2718    boolean showMemoryUsage = false;
2719   
2720    Runtime runtime;
2721   
2722    java.text.NumberFormat df;
2723   
2724    float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2725    percentUsage;
2726   
 
2727  11 toggle public MyDesktopPane(boolean showMemoryUsage)
2728    {
2729  11 showMemoryUsage(showMemoryUsage);
2730    }
2731   
 
2732  11 toggle public void showMemoryUsage(boolean showMemory)
2733    {
2734  11 this.showMemoryUsage = showMemory;
2735  11 if (showMemory)
2736    {
2737  0 Thread worker = new Thread(this);
2738  0 worker.start();
2739    }
2740  11 repaint();
2741    }
2742   
 
2743  606 toggle public boolean isShowMemoryUsage()
2744    {
2745  606 return showMemoryUsage;
2746    }
2747   
 
2748  0 toggle @Override
2749    public void run()
2750    {
2751  0 df = java.text.NumberFormat.getNumberInstance();
2752  0 df.setMaximumFractionDigits(2);
2753  0 runtime = Runtime.getRuntime();
2754   
2755  0 while (showMemoryUsage)
2756    {
2757  0 try
2758    {
2759  0 maxMemory = runtime.maxMemory() / ONE_MB;
2760  0 allocatedMemory = runtime.totalMemory() / ONE_MB;
2761  0 freeMemory = runtime.freeMemory() / ONE_MB;
2762  0 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2763   
2764  0 percentUsage = (totalFreeMemory / maxMemory) * 100;
2765   
2766    // if (percentUsage < 20)
2767    {
2768    // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2769    // Color.red);
2770    // instance.set.setBorder(border1);
2771    }
2772  0 repaint();
2773    // sleep after showing usage
2774  0 Thread.sleep(3000);
2775    } catch (Exception ex)
2776    {
2777  0 ex.printStackTrace();
2778    }
2779    }
2780    }
2781   
 
2782  1789 toggle @Override
2783    public void paintComponent(Graphics g)
2784    {
2785  1789 if (showMemoryUsage && g != null && df != null)
2786    {
2787  0 if (percentUsage < 20)
2788    {
2789  0 g.setColor(Color.red);
2790    }
2791  0 FontMetrics fm = g.getFontMetrics();
2792  0 if (fm != null)
2793    {
2794  0 g.drawString(MessageManager.formatMessage("label.memory_stats",
2795    new Object[]
2796    { df.format(totalFreeMemory), df.format(maxMemory),
2797    df.format(percentUsage) }),
2798    10, getHeight() - fm.getHeight());
2799    }
2800    }
2801   
2802    // output debug scale message. Important for jalview.bin.HiDPISettingTest2
2803  1789 Desktop.debugScaleMessage(Desktop.getDesktopPane().getGraphics());
2804    }
2805    }
2806   
2807    /**
2808    * Accessor method to quickly get all the AlignmentFrames loaded.
2809    *
2810    * @return an array of AlignFrame, or null if none found
2811    */
 
2812  337 toggle @Override
2813    public AlignFrame[] getAlignFrames()
2814    {
2815  337 if (getDesktopPane() == null)
2816    {
2817  0 return null;
2818    }
2819   
2820  337 JInternalFrame[] frames = getDesktopPane().getAllFrames();
2821   
2822  337 if (frames == null)
2823    {
2824  0 return null;
2825    }
2826  337 List<AlignFrame> avp = new ArrayList<>();
2827    // REVERSE ORDER
2828  1513 for (int i = frames.length - 1; i > -1; i--)
2829    {
2830  1176 if (frames[i] instanceof AlignFrame)
2831    {
2832  968 avp.add((AlignFrame) frames[i]);
2833    }
2834  208 else if (frames[i] instanceof SplitFrame)
2835    {
2836    /*
2837    * Also check for a split frame containing an AlignFrame
2838    */
2839  48 GSplitFrame sf = (GSplitFrame) frames[i];
2840  48 if (sf.getTopFrame() instanceof AlignFrame)
2841    {
2842  48 avp.add((AlignFrame) sf.getTopFrame());
2843    }
2844  48 if (sf.getBottomFrame() instanceof AlignFrame)
2845    {
2846  48 avp.add((AlignFrame) sf.getBottomFrame());
2847    }
2848    }
2849    }
2850  337 if (avp.size() == 0)
2851    {
2852  41 return null;
2853    }
2854  296 AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2855  296 return afs;
2856    }
2857   
2858    /**
2859    * static version
2860    */
 
2861  337 toggle public static AlignFrame[] getDesktopAlignFrames()
2862    {
2863  337 if (Jalview.isHeadlessMode())
2864    {
2865    // Desktop.desktop is null in headless mode
2866  0 return Jalview.getInstance().getAlignFrames();
2867    }
2868   
2869  337 if (getDesktopPane() != null)
2870    {
2871  337 return getInstance().getAlignFrames();
2872    }
2873   
2874  0 return null;
2875    }
2876   
2877    /**
2878    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2879    *
2880    * @return
2881    */
 
2882  0 toggle public GStructureViewer[] getJmols()
2883    {
2884  0 JInternalFrame[] frames = desktopPane.getAllFrames();
2885   
2886  0 if (frames == null)
2887    {
2888  0 return null;
2889    }
2890  0 List<GStructureViewer> avp = new ArrayList<>();
2891    // REVERSE ORDER
2892  0 for (int i = frames.length - 1; i > -1; i--)
2893    {
2894  0 if (frames[i] instanceof AppJmol)
2895    {
2896  0 GStructureViewer af = (GStructureViewer) frames[i];
2897  0 avp.add(af);
2898    }
2899    }
2900  0 if (avp.size() == 0)
2901    {
2902  0 return null;
2903    }
2904  0 GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2905  0 return afs;
2906    }
2907   
2908    /**
2909    * Add Groovy Support to Jalview
2910    */
 
2911  0 toggle @Override
2912    public void groovyShell_actionPerformed()
2913    {
2914  0 try
2915    {
2916  0 openGroovyConsole();
2917    } catch (Exception ex)
2918    {
2919  0 jalview.bin.Console.error("Groovy Console creation failed.", ex);
2920  0 JvOptionPane.showInternalMessageDialog(desktopPane,
2921   
2922    MessageManager.getString("label.couldnt_create_groovy_shell"),
2923    MessageManager.getString("label.groovy_support_failed"),
2924    JvOptionPane.ERROR_MESSAGE);
2925    }
2926    }
2927   
2928    /**
2929    * Open the Groovy console
2930    */
 
2931  0 toggle void openGroovyConsole()
2932    {
2933  0 if (groovyConsole == null)
2934    {
2935  0 JalviewObjectI j = new JalviewObject(this);
2936  0 groovyConsole = new groovy.console.ui.Console();
2937  0 groovyConsole.setVariable(JalviewObjectI.jalviewObjectName, j);
2938  0 groovyConsole.setVariable(JalviewObjectI.currentAlFrameName,
2939    getCurrentAlignFrame());
2940  0 groovyConsole.run();
2941   
2942    /*
2943    * We allow only one console at a time, so that AlignFrame menu option
2944    * 'Calculate | Run Groovy script' is unambiguous.
2945    * Disable 'Groovy Console', and enable 'Run script', when the console is
2946    * opened, and the reverse when it is closed
2947    */
2948  0 Window window = (Window) groovyConsole.getFrame();
2949  0 window.addWindowListener(new WindowAdapter()
2950    {
 
2951  0 toggle @Override
2952    public void windowClosed(WindowEvent e)
2953    {
2954    /*
2955    * rebind CMD-Q from Groovy Console to Jalview Quit
2956    */
2957  0 addQuitHandler();
2958  0 enableExecuteGroovy(false);
2959    }
2960    });
2961    }
2962   
2963    /*
2964    * show Groovy console window (after close and reopen)
2965    */
2966  0 ((Window) groovyConsole.getFrame()).setVisible(true);
2967   
2968    /*
2969    * if we got this far, enable 'Run Groovy' in AlignFrame menus
2970    * and disable opening a second console
2971    */
2972  0 enableExecuteGroovy(true);
2973    }
2974   
2975    /**
2976    * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
2977    * binding when opened
2978    */
 
2979  0 toggle protected void addQuitHandler()
2980    {
2981   
2982  0 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
2983    .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
2984    Platform.SHORTCUT_KEY_MASK), "Quit");
2985  0 getRootPane().getActionMap().put("Quit", new AbstractAction()
2986    {
 
2987  0 toggle @Override
2988    public void actionPerformed(ActionEvent e)
2989    {
2990  0 desktopQuit();
2991    }
2992    });
2993    }
2994   
2995    /**
2996    * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2997    *
2998    * @param enabled
2999    * true if Groovy console is open
3000    */
 
3001  0 toggle public void enableExecuteGroovy(boolean enabled)
3002    {
3003    /*
3004    * disable opening a second Groovy console
3005    * (or re-enable when the console is closed)
3006    */
3007  0 groovyShell.setEnabled(!enabled);
3008   
3009  0 AlignFrame[] alignFrames = getDesktopAlignFrames();
3010  0 if (alignFrames != null)
3011    {
3012  0 for (AlignFrame af : alignFrames)
3013    {
3014  0 af.setGroovyEnabled(enabled);
3015    }
3016    }
3017    }
3018   
3019    /**
3020    * Progress bars managed by the IProgressIndicator method. TODO - delegate to
3021    * jalview.gui.ProgressBar
3022    */
3023    private Hashtable<Long, JPanel> progressBars;
3024   
3025    private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
3026   
3027    private Hashtable<Long, String> progressBarMessages;
3028   
3029    /*
3030    * (non-Javadoc)
3031    *
3032    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
3033    */
 
3034  245 toggle @Override
3035    public void setProgressBar(String message, long id)
3036    {
3037    // Platform.timeCheck("Desktop " + message, Platform.TIME_MARK);
3038   
3039  245 if (progressBars == null)
3040    {
3041  10 progressBars = new Hashtable<>();
3042  10 progressBarHandlers = new Hashtable<>();
3043  10 progressBarMessages = new Hashtable<>();
3044    }
3045   
3046  245 if (progressBars.get(Long.valueOf(id)) != null)
3047    {
3048  120 JPanel panel = progressBars.remove(Long.valueOf(id));
3049  120 if (progressBarHandlers.contains(Long.valueOf(id)))
3050    {
3051  0 progressBarHandlers.remove(Long.valueOf(id));
3052    }
3053  120 removeProgressPanel(panel);
3054    }
3055    else
3056    {
3057  125 progressBars.put(Long.valueOf(id), addProgressPanel(message));
3058  125 if (message != null)
3059    {
3060  102 progressBarMessages.put(id, message);
3061    }
3062    else
3063    {
3064  23 progressBarMessages.remove(id);
3065    }
3066    }
3067    }
3068   
 
3069  0 toggle @Override
3070    public JProgressBar getProgressBar(long id)
3071    {
3072  0 if (progressBars == null)
3073  0 return null;
3074   
3075  0 if (progressBars.get(Long.valueOf(id)) == null)
3076  0 return null;
3077   
3078  0 for (Component c : progressBars.get(Long.valueOf(id)).getComponents())
3079    {
3080  0 if (c.getClass() == JProgressBar.class)
3081  0 return (JProgressBar) c;
3082    }
3083  0 return null;
3084    }
3085   
 
3086  0 toggle @Override
3087    public void addProgressBar(long id, String message)
3088    {
3089    // TODO
3090  0 throw new UnsupportedOperationException("not implemented");
3091    }
3092   
 
3093  0 toggle @Override
3094    public void removeProgressBar(long id)
3095    {
3096    // TODO
3097  0 throw new UnsupportedOperationException("not implemented");
3098    }
3099   
3100    /*
3101    * (non-Javadoc)
3102    *
3103    * @see jalview.gui.IProgressIndicator#registerHandler(long,
3104    * jalview.gui.IProgressIndicatorHandler)
3105    */
 
3106  0 toggle @Override
3107    public void registerHandler(final long id,
3108    final IProgressIndicatorHandler handler)
3109    {
3110  0 if (progressBarHandlers == null
3111    || !progressBars.containsKey(Long.valueOf(id)))
3112    {
3113  0 throw new Error(MessageManager.getString(
3114    "error.call_setprogressbar_before_registering_handler"));
3115    }
3116  0 progressBarHandlers.put(Long.valueOf(id), handler);
3117  0 final JPanel progressPanel = progressBars.get(Long.valueOf(id));
3118  0 if (handler.canCancel())
3119    {
3120  0 JButton cancel = new JButton(
3121    MessageManager.getString("action.cancel"));
3122  0 final IProgressIndicator us = this;
3123  0 cancel.addActionListener(new ActionListener()
3124    {
3125   
 
3126  0 toggle @Override
3127    public void actionPerformed(ActionEvent e)
3128    {
3129  0 handler.cancelActivity(id);
3130  0 us.setProgressBar(MessageManager
3131    .formatMessage("label.cancelled_params", new Object[]
3132    { ((JLabel) progressPanel.getComponent(0)).getText() }),
3133    id);
3134    }
3135    });
3136  0 progressPanel.add(cancel, BorderLayout.EAST);
3137    }
3138    }
3139   
 
3140  0 toggle @Override
3141    public String getMessage(long id)
3142    {
3143  0 return progressBarMessages.get(id);
3144    }
3145   
3146    /**
3147    * change the text shown alongside a progress bar
3148    *
3149    * @param id
3150    * @param message
3151    */
 
3152  0 toggle @Override
3153    public void setProgressBarMessage(long id, String message)
3154    {
3155  0 Container progBar = progressBars.get(id);
3156  0 if (progBar == null || progBar.getComponentCount() == 0)
3157    {
3158  0 return;
3159    }
3160  0 for (Component component : progBar.getComponents())
3161    {
3162  0 if (component.getClass().equals(JLabel.class))
3163    {
3164  0 ((JLabel) component).setText(message);
3165  0 ;
3166  0 progBar.revalidate();
3167    }
3168    }
3169    }
3170   
3171    /**
3172    *
3173    * @return true if any progress bars are still active
3174    */
 
3175  23 toggle @Override
3176    public boolean operationInProgress()
3177    {
3178  23 if (progressBars != null && progressBars.size() > 0)
3179    {
3180  0 return true;
3181    }
3182  23 return false;
3183    }
3184   
3185    /**
3186    * This will return the first AlignFrame holding the given viewport instance.
3187    * It will break if there are more than one AlignFrames viewing a particular
3188    * av.
3189    *
3190    * @param viewport
3191    * @return alignFrame for viewport
3192    */
 
3193  1 toggle public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
3194    {
3195  1 if (getDesktopPane() != null)
3196    {
3197  1 AlignmentViewPanel[] aps = getAlignmentPanels(
3198    viewport.getSequenceSetId());
3199  1 for (int panel = 0; aps != null && panel < aps.length; panel++)
3200    {
3201  1 if (aps[panel] != null && aps[panel].getAlignViewport() == viewport)
3202    {
3203    // TODO: remove cast here
3204  1 return ((jalview.gui.AlignmentPanel) aps[panel]).alignFrame;
3205    }
3206    }
3207    }
3208  0 return null;
3209    }
3210   
 
3211  0 toggle public VamsasApplication getVamsasApplication()
3212    {
3213    // TODO: JAL-3311 remove remaining code from Jalview relating to VAMSAS
3214  0 return null;
3215   
3216    }
3217   
3218    /**
3219    * flag set if jalview GUI is being operated programmatically
3220    */
3221    private boolean inBatchMode = false;
3222   
3223    /**
3224    * check if jalview GUI is being operated programmatically
3225    *
3226    * @return inBatchMode
3227    */
 
3228  56 toggle public boolean isInBatchMode()
3229    {
3230  56 return inBatchMode;
3231    }
3232   
3233    /**
3234    * set flag if jalview GUI is being operated programmatically
3235    *
3236    * @param inBatchMode
3237    */
 
3238  180 toggle public void setInBatchMode(boolean inBatchMode)
3239    {
3240  180 this.inBatchMode = inBatchMode;
3241    }
3242   
3243    /**
3244    * start service discovery and wait till it is done
3245    */
 
3246  166 toggle public void startServiceDiscovery()
3247    {
3248  166 startServiceDiscovery(false);
3249    }
3250   
3251    /**
3252    * start service discovery threads - blocking or non-blocking
3253    *
3254    * @param blocking
3255    */
 
3256  166 toggle public void startServiceDiscovery(boolean blocking)
3257    {
3258  166 jalview.bin.Console.debug("Starting service discovery");
3259   
3260  166 var tasks = new ArrayList<Future<?>>();
3261    // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
3262   
3263  166 System.out.println("loading services");
3264   
3265    /** @j2sIgnore */
3266    {
3267    // todo: changesupport handlers need to be transferred
3268  166 if (discoverer == null)
3269    {
3270  10 discoverer = jalview.ws.jws1.Discoverer.getInstance();
3271    // register PCS handler for desktop.
3272  10 discoverer.addPropertyChangeListener(changeSupport);
3273    }
3274    // JAL-940 - disabled JWS1 service configuration - always start discoverer
3275    // until we phase out completely
3276  166 var f = new FutureTask<Void>(discoverer, null);
3277  166 new Thread(f).start();
3278  166 tasks.add(f);
3279    }
3280   
3281  166 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
3282    {
3283  166 tasks.add(jalview.ws.jws2.Jws2Discoverer.getInstance()
3284    .startDiscoverer());
3285    }
3286  166 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
3287    {
3288  166 tasks.add(jalview.ws2.client.slivka.SlivkaWSDiscoverer.getInstance()
3289    .startDiscoverer());
3290    }
3291  166 if (Cache.getDefault("SHOW_EBI_SERVICES", true))
3292    {
3293  166 tasks.add(jalview.ws2.client.ebi.JobDispatcherWSDiscoverer
3294    .getInstance().startDiscoverer());
3295    }
3296  166 if (Cache.getDefault("SHOW_JPRED4_SERVICES", true))
3297    {
3298  166 tasks.add(jalview.ws2.client.jpred4.JPred4WSDiscoverer.getInstance()
3299    .startDiscoverer());
3300    }
3301  166 if (blocking)
3302    {
3303  0 for (Future<?> task : tasks)
3304    {
3305  0 try
3306    {
3307    // block until all discovery tasks are done
3308  0 task.get();
3309    } catch (Exception e)
3310    {
3311  0 e.printStackTrace();
3312    }
3313    }
3314    }
3315    }
3316   
3317    /**
3318    * called to check if the service discovery process completed successfully.
3319    *
3320    * @param evt
3321    */
 
3322  0 toggle protected void JalviewServicesChanged(PropertyChangeEvent evt)
3323    {
3324  0 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
3325    {
3326  0 final WSDiscovererI discoverer = jalview.ws.jws2.Jws2Discoverer
3327    .getInstance();
3328  0 final String ermsg = discoverer.getErrorMessages();
3329    // CONFLICT:ALT:? final String ermsg =
3330    // jalview.ws.jws2.Jws2Discoverer.getInstance()
3331  0 if (ermsg != null)
3332    {
3333  0 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
3334    {
3335  0 if (serviceChangedDialog == null)
3336    {
3337    // only run if we aren't already displaying one of these.
3338  0 addDialogThread(serviceChangedDialog = new Runnable()
3339    {
 
3340  0 toggle @Override
3341    public void run()
3342    {
3343   
3344    /*
3345    * JalviewDialog jd =new JalviewDialog() {
3346    *
3347    * @Override protected void cancelPressed() { // TODO
3348    * Auto-generated method stub
3349    *
3350    * }@Override protected void okPressed() { // TODO
3351    * Auto-generated method stub
3352    *
3353    * }@Override protected void raiseClosed() { // TODO
3354    * Auto-generated method stub
3355    *
3356    * } }; jd.initDialogFrame(new
3357    * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
3358    * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
3359    * + " or mis-configured HTTP proxy settings.<br/>" +
3360    * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
3361    * +
3362    * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
3363    * ), true, true, "Web Service Configuration Problem", 450,
3364    * 400);
3365    *
3366    * jd.waitForInput();
3367    */
3368  0 JvOptionPane.showConfirmDialog(desktopPane,
3369    new JLabel("<html><table width=\"450\"><tr><td>"
3370    + ermsg + "</td></tr></table>"
3371    + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
3372    + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
3373    + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
3374    + " Tools->Preferences dialog box to change them.</p></html>"),
3375    "Web Service Configuration Problem",
3376    JvOptionPane.DEFAULT_OPTION,
3377    JvOptionPane.ERROR_MESSAGE);
3378  0 serviceChangedDialog = null;
3379   
3380    }
3381    });
3382    }
3383    }
3384    else
3385    {
3386  0 jalview.bin.Console.error(
3387    "Errors reported by JABA discovery service. Check web services preferences.\n"
3388    + ermsg);
3389    }
3390    }
3391    }
3392    }
3393   
3394    private Runnable serviceChangedDialog = null;
3395   
3396    /**
3397    * start a thread to open a URL in the configured browser. Pops up a warning
3398    * dialog to the user if there is an exception when calling out to the browser
3399    * to open the URL.
3400    *
3401    * @param url
3402    */
 
3403  0 toggle public static void showUrl(final String url)
3404    {
3405  0 if (url != null && !url.trim().equals(""))
3406    {
3407  0 jalview.bin.Console.info("Opening URL: " + url);
3408  0 showUrl(url, getInstance());
3409    }
3410    else
3411    {
3412  0 jalview.bin.Console.warn("Ignoring attempt to show an empty URL.");
3413    }
3414   
3415    }
3416   
3417    /**
3418    * Like showUrl but allows progress handler to be specified
3419    *
3420    * @param url
3421    * @param progress
3422    * (null) or object implementing IProgressIndicator
3423    */
 
3424  0 toggle public static void showUrl(final String url,
3425    final IProgressIndicator progress)
3426    {
3427  0 new Thread(new Runnable()
3428    {
 
3429  0 toggle @Override
3430    public void run()
3431    {
3432  0 try
3433    {
3434  0 if (progress != null)
3435    {
3436  0 progress.setProgressBar(MessageManager
3437    .formatMessage("status.opening_params", new Object[]
3438    { url }), this.hashCode());
3439    }
3440  0 jalview.util.BrowserLauncher.openURL(url);
3441    } catch (Exception ex)
3442    {
3443  0 JvOptionPane.showInternalMessageDialog(getDesktopPane(),
3444    MessageManager
3445    .getString("label.web_browser_not_found_unix"),
3446    MessageManager.getString("label.web_browser_not_found"),
3447    JvOptionPane.WARNING_MESSAGE);
3448   
3449  0 ex.printStackTrace();
3450    }
3451  0 if (progress != null)
3452    {
3453  0 progress.setProgressBar(null, this.hashCode());
3454    }
3455    }
3456    }).start();
3457    }
3458   
3459    public static WsParamSetManager wsparamManager = null;
3460   
 
3461  481 toggle public static ParamManager getUserParameterStore()
3462    {
3463  481 if (wsparamManager == null)
3464    {
3465  4 wsparamManager = new WsParamSetManager();
3466    }
3467  481 return wsparamManager;
3468    }
3469   
3470    /**
3471    * static hyperlink handler proxy method for use by Jalview's internal windows
3472    *
3473    * @param e
3474    */
 
3475  0 toggle public static void hyperlinkUpdate(HyperlinkEvent e)
3476    {
3477  0 if (e.getEventType() == EventType.ACTIVATED)
3478    {
3479  0 String url = null;
3480  0 try
3481    {
3482  0 url = e.getURL().toString();
3483  0 showUrl(url);
3484    } catch (Exception x)
3485    {
3486  0 if (url != null)
3487    {
3488    // TODO does error send to stderr if no log exists ?
3489  0 jalview.bin.Console
3490    .error("Couldn't handle string " + url + " as a URL.");
3491    }
3492    // ignore any exceptions due to dud links.
3493    }
3494   
3495    }
3496    }
3497   
3498    /**
3499    * single thread that handles display of dialogs to user.
3500    */
3501    ExecutorService dialogExecutor = Executors.newFixedThreadPool(3);
3502   
3503    /**
3504    * flag indicating if dialogExecutor should try to acquire a permit
3505    */
3506    private volatile boolean dialogPause = true;
3507   
3508    /**
3509    * pause the queue
3510    */
3511    private Semaphore block = new Semaphore(0);
3512   
3513    private static groovy.console.ui.Console groovyConsole;
3514   
3515    /**
3516    * add another dialog thread to the queue
3517    *
3518    * @param prompter
3519    */
 
3520  98 toggle public void addDialogThread(final Runnable prompter)
3521    {
3522  98 if (dialogExecutor==null)
3523    {
3524    // Desktop was closed - ignore new dialog requests
3525  83 return;
3526    }
3527  15 dialogExecutor.submit(new Runnable()
3528    {
 
3529  15 toggle @Override
3530    public void run()
3531    {
3532  15 if (dialogPause)
3533    {
3534  0 acquireDialogQueue();
3535    }
3536  15 if (Jalview.isHeadlessMode())
3537    {
3538  0 return;
3539    }
3540  15 try
3541    {
3542  15 SwingUtilities.invokeAndWait(prompter);
3543    } catch (Exception q)
3544    {
3545  0 jalview.bin.Console.warn("Unexpected Exception in dialog thread.",
3546    q);
3547    }
3548    }
3549    });
3550    }
3551   
3552    private boolean dialogQueueStarted = false;
3553   
 
3554  16 toggle public void startDialogQueue()
3555    {
3556  16 if (dialogQueueStarted)
3557    {
3558  5 return;
3559    }
3560    // set the flag so we don't pause waiting for another permit and semaphore
3561    // the current task to begin
3562  11 releaseDialogQueue();
3563  11 dialogQueueStarted = true;
3564    }
3565   
 
3566  11 toggle public void acquireDialogQueue()
3567    {
3568  11 try
3569    {
3570  11 block.acquire();
3571  11 dialogPause = true;
3572    } catch (InterruptedException e)
3573    {
3574  0 jalview.bin.Console.debug("Interruption when acquiring DialogueQueue",
3575    e);
3576    }
3577    }
3578   
 
3579  27 toggle public void releaseDialogQueue()
3580    {
3581  27 if (!dialogPause)
3582    {
3583  5 return;
3584    }
3585  22 block.release();
3586  22 dialogPause = false;
3587    }
3588   
3589    /**
3590    * Outputs an image of the desktop to file in EPS format, after prompting the
3591    * user for choice of Text or Lineart character rendering (unless a preference
3592    * has been set). The file name is generated as
3593    *
3594    * <pre>
3595    * Jalview_snapshot_nnnnn.eps where nnnnn is the current timestamp in milliseconds
3596    * </pre>
3597    */
 
3598  0 toggle @Override
3599    protected void snapShotWindow_actionPerformed(ActionEvent e)
3600    {
3601    // currently the menu option to do this is not shown
3602  0 invalidate();
3603   
3604  0 int width = getWidth();
3605  0 int height = getHeight();
3606  0 File of = new File(
3607    "Jalview_snapshot_" + System.currentTimeMillis() + ".eps");
3608  0 ImageWriterI writer = new ImageWriterI()
3609    {
 
3610  0 toggle @Override
3611    public void exportImage(Graphics g) throws Exception
3612    {
3613  0 paintAll(g);
3614  0 jalview.bin.Console.info("Successfully written snapshot to file "
3615    + of.getAbsolutePath());
3616    }
3617    };
3618  0 String title = "View of desktop";
3619  0 ImageExporter exporter = new ImageExporter(writer, null, TYPE.EPS,
3620    title);
3621  0 try
3622    {
3623  0 exporter.doExport(of, this, width, height, title);
3624    } catch (ImageOutputException ioex)
3625    {
3626  0 jalview.bin.Console.error(
3627    "Unexpected error whilst writing Jalview desktop snapshot as EPS",
3628    ioex);
3629    }
3630    }
3631   
3632    /**
3633    * Explode the views in the given SplitFrame into separate SplitFrame windows.
3634    * This respects (remembers) any previous 'exploded geometry' i.e. the size
3635    * and location last time the view was expanded (if any). However it does not
3636    * remember the split pane divider location - this is set to match the
3637    * 'exploding' frame.
3638    *
3639    * @param sf
3640    */
 
3641  0 toggle public void explodeViews(SplitFrame sf)
3642    {
3643  0 AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3644  0 AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3645  0 List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3646    .getAlignPanels();
3647  0 List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3648    .getAlignPanels();
3649  0 int viewCount = topPanels.size();
3650  0 if (viewCount < 2)
3651    {
3652  0 return;
3653    }
3654   
3655    /*
3656    * Processing in reverse order works, forwards order leaves the first panels
3657    * not visible. I don't know why!
3658    */
3659  0 for (int i = viewCount - 1; i >= 0; i--)
3660    {
3661    /*
3662    * Make new top and bottom frames. These take over the respective
3663    * AlignmentPanel objects, including their AlignmentViewports, so the
3664    * cdna/protein relationships between the viewports is carried over to the
3665    * new split frames.
3666    *
3667    * explodedGeometry holds the (x, y) position of the previously exploded
3668    * SplitFrame, and the (width, height) of the AlignFrame component
3669    */
3670  0 AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3671  0 AlignFrame newTopFrame = new AlignFrame(topPanel);
3672  0 newTopFrame.setSize(oldTopFrame.getSize());
3673  0 newTopFrame.setVisible(true);
3674  0 Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3675    .getExplodedGeometry();
3676  0 if (geometry != null)
3677    {
3678  0 newTopFrame.setSize(geometry.getSize());
3679    }
3680   
3681  0 AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3682  0 AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3683  0 newBottomFrame.setSize(oldBottomFrame.getSize());
3684  0 newBottomFrame.setVisible(true);
3685  0 geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3686    .getExplodedGeometry();
3687  0 if (geometry != null)
3688    {
3689  0 newBottomFrame.setSize(geometry.getSize());
3690    }
3691   
3692  0 topPanel.av.setGatherViewsHere(false);
3693  0 bottomPanel.av.setGatherViewsHere(false);
3694  0 JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3695    newBottomFrame);
3696  0 if (geometry != null)
3697    {
3698  0 splitFrame.setLocation(geometry.getLocation());
3699    }
3700  0 addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3701    }
3702   
3703    /*
3704    * Clear references to the panels (now relocated in the new SplitFrames)
3705    * before closing the old SplitFrame.
3706    */
3707  0 topPanels.clear();
3708  0 bottomPanels.clear();
3709  0 sf.close();
3710    }
3711   
3712    /**
3713    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3714    * back into the given SplitFrame as additional views. Note that the gathered
3715    * frames may themselves have multiple views.
3716    *
3717    * @param source
3718    */
 
3719  0 toggle public void gatherViews(GSplitFrame source)
3720    {
3721    /*
3722    * special handling of explodedGeometry for a view within a SplitFrame: - it
3723    * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3724    * height) of the AlignFrame component
3725    */
3726  0 AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3727  0 AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3728  0 myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3729    source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3730  0 myBottomFrame.viewport
3731    .setExplodedGeometry(new Rectangle(source.getX(), source.getY(),
3732    myBottomFrame.getWidth(), myBottomFrame.getHeight()));
3733  0 myTopFrame.viewport.setGatherViewsHere(true);
3734  0 myBottomFrame.viewport.setGatherViewsHere(true);
3735  0 String topViewId = myTopFrame.viewport.getSequenceSetId();
3736  0 String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3737   
3738  0 JInternalFrame[] frames = desktopPane.getAllFrames();
3739  0 for (JInternalFrame frame : frames)
3740    {
3741  0 if (frame instanceof SplitFrame && frame != source)
3742    {
3743  0 SplitFrame sf = (SplitFrame) frame;
3744  0 AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3745  0 AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3746  0 boolean gatherThis = false;
3747  0 for (int a = 0; a < topFrame.alignPanels.size(); a++)
3748    {
3749  0 AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3750  0 AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3751  0 if (topViewId.equals(topPanel.av.getSequenceSetId())
3752    && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3753    {
3754  0 gatherThis = true;
3755  0 topPanel.av.setGatherViewsHere(false);
3756  0 bottomPanel.av.setGatherViewsHere(false);
3757  0 topPanel.av.setExplodedGeometry(
3758    new Rectangle(sf.getLocation(), topFrame.getSize()));
3759  0 bottomPanel.av.setExplodedGeometry(
3760    new Rectangle(sf.getLocation(), bottomFrame.getSize()));
3761  0 myTopFrame.addAlignmentPanel(topPanel, false);
3762  0 myBottomFrame.addAlignmentPanel(bottomPanel, false);
3763    }
3764    }
3765   
3766  0 if (gatherThis)
3767    {
3768  0 topFrame.getAlignPanels().clear();
3769  0 bottomFrame.getAlignPanels().clear();
3770  0 sf.close();
3771    }
3772    }
3773    }
3774   
3775    /*
3776    * The dust settles...give focus to the tab we did this from.
3777    */
3778  0 myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3779    }
3780   
 
3781  729 toggle public static groovy.console.ui.Console getGroovyConsole()
3782    {
3783  729 return groovyConsole;
3784    }
3785   
3786    /**
3787    * handles the payload of a drag and drop event.
3788    *
3789    * TODO refactor to desktop utilities class
3790    *
3791    * @param files
3792    * - Data source strings extracted from the drop event
3793    * @param protocols
3794    * - protocol for each data source extracted from the drop event
3795    * @param evt
3796    * - the drop event
3797    * @param t
3798    * - the payload from the drop event
3799    * @throws Exception
3800    */
 
3801  0 toggle @SuppressWarnings("unchecked")
3802    public static void transferFromDropTarget(List<Object> files,
3803    List<DataSourceType> protocols, DropTargetDropEvent evt,
3804    Transferable t) throws Exception
3805    {
3806   
3807    // BH 2018 changed List<String> to List<Object> to allow for File from
3808    // SwingJS
3809   
3810    // DataFlavor[] flavors = t.getTransferDataFlavors();
3811    // for (int i = 0; i < flavors.length; i++) {
3812    // if (flavors[i].isFlavorJavaFileListType()) {
3813    // evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3814    // List<File> list = (List<File>) t.getTransferData(flavors[i]);
3815    // for (int j = 0; j < list.size(); j++) {
3816    // File file = (File) list.get(j);
3817    // byte[] data = getDroppedFileBytes(file);
3818    // fileName.setText(file.getName() + " - " + data.length + " " +
3819    // evt.getLocation());
3820    // JTextArea target = (JTextArea) ((DropTarget)
3821    // evt.getSource()).getComponent();
3822    // target.setText(new String(data));
3823    // }
3824    // dtde.dropComplete(true);
3825    // return;
3826    // }
3827    //
3828   
3829  0 DataFlavor uriListFlavor = new DataFlavor(
3830    "text/uri-list;class=java.lang.String"), urlFlavour = null;
3831  0 try
3832    {
3833  0 urlFlavour = new DataFlavor(
3834    "application/x-java-url; class=java.net.URL");
3835    } catch (ClassNotFoundException cfe)
3836    {
3837  0 jalview.bin.Console.debug("Couldn't instantiate the URL dataflavor.",
3838    cfe);
3839    }
3840   
3841  0 if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
3842    {
3843   
3844  0 try
3845    {
3846  0 java.net.URL url = (URL) t.getTransferData(urlFlavour);
3847    // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
3848    // means url may be null.
3849  0 if (url != null)
3850    {
3851  0 protocols.add(DataSourceType.URL);
3852  0 files.add(url.toString());
3853  0 jalview.bin.Console.debug("Drop handled as URL dataflavor "
3854    + files.get(files.size() - 1));
3855  0 return;
3856    }
3857    else
3858    {
3859  0 if (Platform.isAMacAndNotJS())
3860    {
3861  0 jalview.bin.Console.errPrintln(
3862    "Please ignore plist error - occurs due to problem with java 8 on OSX");
3863    }
3864    }
3865    } catch (Throwable ex)
3866    {
3867  0 jalview.bin.Console.debug("URL drop handler failed.", ex);
3868    }
3869    }
3870  0 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3871    {
3872    // Works on Windows and MacOSX
3873  0 jalview.bin.Console.debug("Drop handled as javaFileListFlavor");
3874  0 for (File file : (List<File>) t
3875    .getTransferData(DataFlavor.javaFileListFlavor))
3876    {
3877  0 files.add(file);
3878  0 protocols.add(DataSourceType.FILE);
3879    }
3880    }
3881    else
3882    {
3883    // Unix like behaviour
3884  0 boolean added = false;
3885  0 String data = null;
3886  0 if (t.isDataFlavorSupported(uriListFlavor))
3887    {
3888  0 jalview.bin.Console.debug("Drop handled as uriListFlavor");
3889    // This is used by Unix drag system
3890  0 data = (String) t.getTransferData(uriListFlavor);
3891    }
3892  0 if (data == null)
3893    {
3894    // fallback to text: workaround - on OSX where there's a JVM bug
3895  0 jalview.bin.Console
3896    .debug("standard URIListFlavor failed. Trying text");
3897    // try text fallback
3898  0 DataFlavor textDf = new DataFlavor(
3899    "text/plain;class=java.lang.String");
3900  0 if (t.isDataFlavorSupported(textDf))
3901    {
3902  0 data = (String) t.getTransferData(textDf);
3903    }
3904   
3905  0 jalview.bin.Console.debug("Plain text drop content returned "
3906  0 + (data == null ? "Null - failed" : data));
3907   
3908    }
3909  0 if (data != null)
3910    {
3911  0 while (protocols.size() < files.size())
3912    {
3913  0 jalview.bin.Console.debug("Adding missing FILE protocol for "
3914    + files.get(protocols.size()));
3915  0 protocols.add(DataSourceType.FILE);
3916    }
3917  0 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3918  0 data, "\r\n"); st.hasMoreTokens();)
3919    {
3920  0 added = true;
3921  0 String s = st.nextToken();
3922  0 if (s.startsWith("#"))
3923    {
3924    // the line is a comment (as per the RFC 2483)
3925  0 continue;
3926    }
3927  0 java.net.URI uri = new java.net.URI(s);
3928  0 if (uri.getScheme().toLowerCase(Locale.ROOT).startsWith("http"))
3929    {
3930  0 protocols.add(DataSourceType.URL);
3931  0 files.add(uri.toString());
3932    }
3933    else
3934    {
3935    // otherwise preserve old behaviour: catch all for file objects
3936  0 java.io.File file = new java.io.File(uri);
3937  0 protocols.add(DataSourceType.FILE);
3938  0 files.add(file.toString());
3939    }
3940    }
3941    }
3942   
3943  0 if (jalview.bin.Console.isDebugEnabled())
3944    {
3945  0 if (data == null || !added)
3946    {
3947   
3948  0 if (t.getTransferDataFlavors() != null
3949    && t.getTransferDataFlavors().length > 0)
3950    {
3951  0 jalview.bin.Console.debug(
3952    "Couldn't resolve drop data. Here are the supported flavors:");
3953  0 for (DataFlavor fl : t.getTransferDataFlavors())
3954    {
3955  0 jalview.bin.Console.debug(
3956    "Supported transfer dataflavor: " + fl.toString());
3957  0 Object df = t.getTransferData(fl);
3958  0 if (df != null)
3959    {
3960  0 jalview.bin.Console.debug("Retrieves: " + df);
3961    }
3962    else
3963    {
3964  0 jalview.bin.Console.debug("Retrieved nothing");
3965    }
3966    }
3967    }
3968    else
3969    {
3970  0 jalview.bin.Console
3971    .debug("Couldn't resolve dataflavor for drop: "
3972    + t.toString());
3973    }
3974    }
3975    }
3976    }
3977  0 if (Platform.isWindowsAndNotJS())
3978    {
3979  0 jalview.bin.Console
3980    .debug("Scanning dropped content for Windows Link Files");
3981   
3982    // resolve any .lnk files in the file drop
3983  0 for (int f = 0; f < files.size(); f++)
3984    {
3985  0 String source = files.get(f).toString().toLowerCase(Locale.ROOT);
3986  0 if (protocols.get(f).equals(DataSourceType.FILE)
3987    && (source.endsWith(".lnk") || source.endsWith(".url")
3988    || source.endsWith(".site")))
3989    {
3990  0 try
3991    {
3992  0 Object obj = files.get(f);
3993  0 File lf = (obj instanceof File ? (File) obj
3994    : new File((String) obj));
3995    // process link file to get a URL
3996  0 jalview.bin.Console.debug("Found potential link file: " + lf);
3997  0 WindowsShortcut wscfile = new WindowsShortcut(lf);
3998  0 String fullname = wscfile.getRealFilename();
3999  0 protocols.set(f, FormatAdapter.checkProtocol(fullname));
4000  0 files.set(f, fullname);
4001  0 jalview.bin.Console.debug("Parsed real filename " + fullname
4002    + " to extract protocol: " + protocols.get(f));
4003    } catch (Exception ex)
4004    {
4005  0 jalview.bin.Console.error(
4006    "Couldn't parse " + files.get(f) + " as a link file.",
4007    ex);
4008    }
4009    }
4010    }
4011    }
4012    }
4013   
4014    /**
4015    * Sets the Preferences property for experimental features to True or False
4016    * depending on the state of the controlling menu item
4017    */
 
4018  0 toggle @Override
4019    protected void showExperimental_actionPerformed(boolean selected)
4020    {
4021  0 Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
4022    }
4023   
4024    /**
4025    * Answers a (possibly empty) list of any structure viewer frames (currently
4026    * for either Jmol or Chimera) which are currently open. This may optionally
4027    * be restricted to viewers of a specified class, or viewers linked to a
4028    * specified alignment panel.
4029    *
4030    * @param apanel
4031    * if not null, only return viewers linked to this panel
4032    * @param structureViewerClass
4033    * if not null, only return viewers of this class
4034    * @return
4035    */
 
4036  33 toggle public List<StructureViewerBase> getStructureViewers(
4037    AlignmentPanel apanel,
4038    Class<? extends StructureViewerBase> structureViewerClass)
4039    {
4040  33 List<StructureViewerBase> result = new ArrayList<>();
4041  33 JInternalFrame[] frames = getAllFrames();
4042   
4043  33 for (JInternalFrame frame : frames)
4044    {
4045  77 if (frame instanceof StructureViewerBase)
4046    {
4047  36 if (structureViewerClass == null
4048    || structureViewerClass.isInstance(frame))
4049    {
4050  36 if (apanel == null
4051    || ((StructureViewerBase) frame).isLinkedWith(apanel))
4052    {
4053  36 result.add((StructureViewerBase) frame);
4054    }
4055    }
4056    }
4057    }
4058  33 return result;
4059    }
4060   
4061    public static final String debugScaleMessage = "Desktop graphics transform scale=";
4062   
4063    private static boolean debugScaleMessageDone = false;
4064   
 
4065  1789 toggle public static void debugScaleMessage(Graphics g)
4066    {
4067  1789 if (debugScaleMessageDone)
4068    {
4069  1779 return;
4070    }
4071    // output used by tests to check HiDPI scaling settings in action
4072  10 try
4073    {
4074  10 Graphics2D gg = (Graphics2D) g;
4075  10 if (gg != null)
4076    {
4077  10 AffineTransform t = gg.getTransform();
4078  10 double scaleX = t.getScaleX();
4079  10 double scaleY = t.getScaleY();
4080  10 jalview.bin.Console.debug(debugScaleMessage + scaleX + " (X)");
4081  10 jalview.bin.Console.debug(debugScaleMessage + scaleY + " (Y)");
4082  10 debugScaleMessageDone = true;
4083    }
4084    else
4085    {
4086  0 jalview.bin.Console.debug("Desktop graphics null");
4087    }
4088    } catch (Exception e)
4089    {
4090  0 jalview.bin.Console.debug(Cache.getStackTraceString(e));
4091    }
4092    }
4093   
4094    /**
4095    * closes the current instance window, but leaves the JVM running. Bypasses
4096    * any shutdown prompts, but does not set window dispose on close in case JVM
4097    * terminates.
4098    */
 
4099  70 toggle public static void closeDesktop()
4100    {
4101  70 if (Desktop.getInstance() != null)
4102    {
4103  70 Desktop us = Desktop.getInstance();
4104  70 us.quitTheDesktop(false, false);
4105    // call dispose in a separate thread - try to avoid indirect deadlocks
4106  70 if (us != null)
4107    {
4108  70 new Thread(new Runnable()
4109    {
 
4110  70 toggle @Override
4111    public void run()
4112    {
4113  70 ExecutorService dex = us.dialogExecutor;
4114  70 if (dex != null)
4115    {
4116  3 dex.shutdownNow();
4117  3 us.dialogExecutor = null;
4118  3 us.block.drainPermits();
4119    }
4120  70 us.dispose();
4121    }
4122    }).start();
4123    }
4124    }
4125    }
4126   
4127    /**
4128    * checks if any progress bars are being displayed in any of the windows
4129    * managed by the desktop
4130    *
4131    * @return
4132    */
 
4133  41 toggle public boolean operationsAreInProgress()
4134    {
4135  41 JInternalFrame[] frames = getAllFrames();
4136  41 for (JInternalFrame frame : frames)
4137    {
4138  113 if (frame instanceof IProgressIndicator)
4139    {
4140  41 if (((IProgressIndicator) frame).operationInProgress())
4141    {
4142  18 return true;
4143    }
4144    }
4145    }
4146  23 return operationInProgress();
4147    }
4148   
4149    /**
4150    * keep track of modal JvOptionPanes open as modal dialogs for AlignFrames.
4151    * The way the modal JInternalFrame is made means it cannot be a child of an
4152    * AlignFrame, so closing the AlignFrame might leave the modal open :(
4153    */
4154    private static Map<AlignFrame, JInternalFrame> alignFrameModalMap = new HashMap<>();
4155   
 
4156  0 toggle protected static void addModal(AlignFrame af, JInternalFrame jif)
4157    {
4158  0 alignFrameModalMap.put(af, jif);
4159    }
4160   
 
4161  452 toggle protected static void closeModal(AlignFrame af)
4162    {
4163  452 if (!alignFrameModalMap.containsKey(af))
4164    {
4165  452 return;
4166    }
4167  0 JInternalFrame jif = alignFrameModalMap.get(af);
4168  0 if (jif != null)
4169    {
4170  0 try
4171    {
4172  0 jif.setClosed(true);
4173    } catch (PropertyVetoException e)
4174    {
4175  0 e.printStackTrace();
4176    }
4177    }
4178  0 alignFrameModalMap.remove(af);
4179    }
4180   
 
4181  0 toggle public void nonBlockingDialog(String title, String message, String button,
4182    int type, boolean scrollable, boolean modal)
4183    {
4184  0 nonBlockingDialog(title, message, null, button, type, scrollable, false,
4185    modal, -1);
4186    }
4187   
 
4188  1 toggle public void nonBlockingDialog(String title, String message,
4189    String boxtext, String button, int type, boolean scrollable,
4190    boolean html, boolean modal, int timeout)
4191    {
4192  1 nonBlockingDialog(32, 2, title, message, boxtext, button, type,
4193    scrollable, html, modal, timeout);
4194    }
4195   
 
4196  1 toggle public void nonBlockingDialog(int width, int height, String title,
4197    String message, String boxtext, String button, int type,
4198    boolean scrollable, boolean html, boolean modal, int timeout)
4199    {
4200  1 if (type < 0)
4201    {
4202  0 type = JvOptionPane.WARNING_MESSAGE;
4203    }
4204  1 JLabel jl = new JLabel(message);
4205   
4206  1 JTextComponent jtc = null;
4207  1 if (html)
4208    {
4209  1 JTextPane jtp = new JTextPane();
4210  1 jtp.setContentType("text/html");
4211  1 jtp.setEditable(false);
4212  1 jtp.setAutoscrolls(true);
4213  1 jtp.setText(boxtext);
4214   
4215  1 jtc = jtp;
4216    }
4217    else
4218    {
4219  0 JTextArea jta = new JTextArea(height, width);
4220    // jta.setLineWrap(true);
4221  0 jta.setEditable(false);
4222  0 jta.setWrapStyleWord(true);
4223  0 jta.setAutoscrolls(true);
4224  0 jta.setText(boxtext);
4225   
4226  0 jtc = jta;
4227    }
4228   
4229  1 JScrollPane jsp = scrollable
4230    ? new JScrollPane(jtc, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
4231    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
4232    : null;
4233   
4234  1 JvOptionPane jvp = JvOptionPane.newOptionDialog(this);
4235   
4236  1 JPanel jp = new JPanel();
4237  1 jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
4238   
4239  1 if (message != null)
4240    {
4241  1 jl.setAlignmentX(Component.LEFT_ALIGNMENT);
4242  1 jp.add(jl);
4243    }
4244  1 if (boxtext != null)
4245    {
4246  1 if (scrollable)
4247    {
4248  0 jsp.setAlignmentX(Component.LEFT_ALIGNMENT);
4249  0 jp.add(jsp);
4250    }
4251    else
4252    {
4253  1 jtc.setAlignmentX(Component.LEFT_ALIGNMENT);
4254  1 jp.add(jtc);
4255    }
4256    }
4257   
4258  1 jvp.setResponseHandler(JOptionPane.YES_OPTION, () -> {
4259    });
4260  1 jvp.setTimeout(timeout);
4261  1 JButton jb = new JButton(button);
4262  1 jvp.showDialogOnTopAsync(this, jp, title, JOptionPane.YES_OPTION, type,
4263    null, new Object[]
4264    { button }, button, modal, new JButton[] { jb }, false);
4265    }
4266   
 
4267  0 toggle @Override
4268    public AlignFrame getCurrentAlignFrame()
4269    {
4270  0 return Jalview.getInstance().getCurrentAlignFrame();
4271    }
4272    }