6b46041e178f6882835fb9bbf5400e7fcabbc196
[jalview.git] / src / jalview / gui / AlignFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeEvent;
49 import java.io.File;
50 import java.io.FileWriter;
51 import java.io.IOException;
52 import java.io.PrintWriter;
53 import java.net.URL;
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.Deque;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.List;
60 import java.util.Locale;
61 import java.util.Vector;
62 import java.util.concurrent.Callable;
63
64 import javax.swing.ButtonGroup;
65 import javax.swing.JCheckBoxMenuItem;
66 import javax.swing.JComponent;
67 import javax.swing.JEditorPane;
68 import javax.swing.JInternalFrame;
69 import javax.swing.JLabel;
70 import javax.swing.JLayeredPane;
71 import javax.swing.JMenu;
72 import javax.swing.JMenuItem;
73 import javax.swing.JPanel;
74 import javax.swing.JScrollPane;
75 import javax.swing.SwingUtilities;
76
77 import ext.vamsas.ServiceHandle;
78 import jalview.analysis.AlignmentSorter;
79 import jalview.analysis.AlignmentUtils;
80 import jalview.analysis.CrossRef;
81 import jalview.analysis.Dna;
82 import jalview.analysis.GeneticCodeI;
83 import jalview.analysis.ParseProperties;
84 import jalview.analysis.SequenceIdMatcher;
85 import jalview.api.AlignExportSettingsI;
86 import jalview.api.AlignViewControllerGuiI;
87 import jalview.api.AlignViewControllerI;
88 import jalview.api.AlignViewportI;
89 import jalview.api.AlignmentViewPanel;
90 import jalview.api.FeatureSettingsControllerI;
91 import jalview.api.FeatureSettingsModelI;
92 import jalview.api.SplitContainerI;
93 import jalview.api.ViewStyleI;
94 import jalview.api.analysis.SimilarityParamsI;
95 import jalview.bin.Cache;
96 import jalview.bin.Console;
97 import jalview.bin.Jalview;
98 import jalview.commands.CommandI;
99 import jalview.commands.EditCommand;
100 import jalview.commands.EditCommand.Action;
101 import jalview.commands.OrderCommand;
102 import jalview.commands.RemoveGapColCommand;
103 import jalview.commands.RemoveGapsCommand;
104 import jalview.commands.SlideSequencesCommand;
105 import jalview.commands.TrimRegionCommand;
106 import jalview.datamodel.AlignExportSettingsAdapter;
107 import jalview.datamodel.AlignedCodonFrame;
108 import jalview.datamodel.Alignment;
109 import jalview.datamodel.AlignmentAnnotation;
110 import jalview.datamodel.AlignmentExportData;
111 import jalview.datamodel.AlignmentI;
112 import jalview.datamodel.AlignmentOrder;
113 import jalview.datamodel.AlignmentView;
114 import jalview.datamodel.ColumnSelection;
115 import jalview.datamodel.HiddenColumns;
116 import jalview.datamodel.PDBEntry;
117 import jalview.datamodel.SeqCigar;
118 import jalview.datamodel.Sequence;
119 import jalview.datamodel.SequenceGroup;
120 import jalview.datamodel.SequenceI;
121 import jalview.gui.ColourMenuHelper.ColourChangeListener;
122 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
123 import jalview.io.AlignmentProperties;
124 import jalview.io.AnnotationFile;
125 import jalview.io.BackupFiles;
126 import jalview.io.BioJsHTMLOutput;
127 import jalview.io.DataSourceType;
128 import jalview.io.FileFormat;
129 import jalview.io.FileFormatI;
130 import jalview.io.FileFormats;
131 import jalview.io.FileLoader;
132 import jalview.io.FileParse;
133 import jalview.io.FormatAdapter;
134 import jalview.io.HtmlSvgOutput;
135 import jalview.io.IdentifyFile;
136 import jalview.io.JPredFile;
137 import jalview.io.JalviewFileChooser;
138 import jalview.io.JalviewFileView;
139 import jalview.io.JnetAnnotationMaker;
140 import jalview.io.NewickFile;
141 import jalview.io.ScoreMatrixFile;
142 import jalview.io.TCoffeeScoreFile;
143 import jalview.io.vcf.VCFLoader;
144 import jalview.jbgui.GAlignFrame;
145 import jalview.project.Jalview2XML;
146 import jalview.schemes.ColourSchemeI;
147 import jalview.schemes.ColourSchemes;
148 import jalview.schemes.ResidueColourScheme;
149 import jalview.schemes.TCoffeeColourScheme;
150 import jalview.util.HttpUtils;
151 import jalview.util.ImageMaker.TYPE;
152 import jalview.util.MessageManager;
153 import jalview.util.Platform;
154 import jalview.viewmodel.AlignmentViewport;
155 import jalview.viewmodel.ViewportRanges;
156 import jalview.ws.DBRefFetcher;
157 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
158 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
159 import jalview.ws.jws1.Discoverer;
160 import jalview.ws.jws2.Jws2Discoverer;
161 import jalview.ws.jws2.jabaws2.Jws2Instance;
162 import jalview.ws.seqfetcher.DbSourceProxy;
163
164 /**
165  * DOCUMENT ME!
166  * 
167  * @author $author$
168  * @version $Revision$
169  */
170 @SuppressWarnings("serial")
171 public class AlignFrame extends GAlignFrame implements DropTargetListener,
172         IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 {
174
175   public static final int DEFAULT_WIDTH = 700;
176
177   public static final int DEFAULT_HEIGHT = 500;
178
179   /*
180    * The currently displayed panel (selected tabbed view if more than one)
181    */
182   public AlignmentPanel alignPanel;
183
184   AlignViewport viewport;
185
186   public AlignViewControllerI avc;
187
188   List<AlignmentPanel> alignPanels = new ArrayList<>();
189
190   /**
191    * Last format used to load or save alignments in this window
192    */
193   FileFormatI currentFileFormat = null;
194
195   /**
196    * Current filename for this alignment
197    */
198   String fileName = null;
199
200   File fileObject;
201
202   /**
203    * Creates a new AlignFrame object with specific width and height.
204    * 
205    * @param al
206    * @param width
207    * @param height
208    */
209   public AlignFrame(AlignmentI al, int width, int height)
210   {
211     this(al, null, width, height);
212   }
213
214   /**
215    * Creates a new AlignFrame object with specific width, height and
216    * sequenceSetId
217    * 
218    * @param al
219    * @param width
220    * @param height
221    * @param sequenceSetId
222    */
223   public AlignFrame(AlignmentI al, int width, int height,
224           String sequenceSetId)
225   {
226     this(al, null, width, height, sequenceSetId);
227   }
228
229   /**
230    * Creates a new AlignFrame object with specific width, height and
231    * sequenceSetId
232    * 
233    * @param al
234    * @param width
235    * @param height
236    * @param sequenceSetId
237    * @param viewId
238    */
239   public AlignFrame(AlignmentI al, int width, int height,
240           String sequenceSetId, String viewId)
241   {
242     this(al, null, width, height, sequenceSetId, viewId);
243   }
244
245   /**
246    * new alignment window with hidden columns
247    * 
248    * @param al
249    *          AlignmentI
250    * @param hiddenColumns
251    *          ColumnSelection or null
252    * @param width
253    *          Width of alignment frame
254    * @param height
255    *          height of frame.
256    */
257   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258           int height)
259   {
260     this(al, hiddenColumns, width, height, null);
261   }
262
263   /**
264    * Create alignment frame for al with hiddenColumns, a specific width and
265    * height, and specific sequenceId
266    * 
267    * @param al
268    * @param hiddenColumns
269    * @param width
270    * @param height
271    * @param sequenceSetId
272    *          (may be null)
273    */
274   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
275           int height, String sequenceSetId)
276   {
277     this(al, hiddenColumns, width, height, sequenceSetId, null);
278   }
279
280   /**
281    * Create alignment frame for al with hiddenColumns, a specific width and
282    * height, and specific sequenceId
283    * 
284    * @param al
285    * @param hiddenColumns
286    * @param width
287    * @param height
288    * @param sequenceSetId
289    *          (may be null)
290    * @param viewId
291    *          (may be null)
292    */
293   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
294           int height, String sequenceSetId, String viewId)
295   {
296     setSize(width, height);
297
298     if (al.getDataset() == null)
299     {
300       al.setDataset(null);
301     }
302
303     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
304
305     alignPanel = new AlignmentPanel(this, viewport);
306
307     addAlignmentPanel(alignPanel, true);
308     init();
309   }
310
311   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
312           HiddenColumns hiddenColumns, int width, int height)
313   {
314     setSize(width, height);
315
316     if (al.getDataset() == null)
317     {
318       al.setDataset(null);
319     }
320
321     viewport = new AlignViewport(al, hiddenColumns);
322
323     if (hiddenSeqs != null && hiddenSeqs.length > 0)
324     {
325       viewport.hideSequence(hiddenSeqs);
326     }
327     alignPanel = new AlignmentPanel(this, viewport);
328     addAlignmentPanel(alignPanel, true);
329     init();
330   }
331
332   /**
333    * Make a new AlignFrame from existing alignmentPanels
334    * 
335    * @param ap
336    *          AlignmentPanel
337    * @param av
338    *          AlignViewport
339    */
340   public AlignFrame(AlignmentPanel ap)
341   {
342     viewport = ap.av;
343     alignPanel = ap;
344     addAlignmentPanel(ap, false);
345     init();
346   }
347
348   /**
349    * initalise the alignframe from the underlying viewport data and the
350    * configurations
351    */
352   void init()
353   {
354     setFrameIcon(null);
355
356     // setBackground(Color.white); // BH 2019
357
358     if (!Jalview.isHeadlessMode())
359     {
360       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
361     }
362
363     avc = new jalview.controller.AlignViewController(this, viewport,
364             alignPanel);
365     if (viewport.getAlignmentConservationAnnotation() == null)
366     {
367       // BLOSUM62Colour.setEnabled(false);
368       conservationMenuItem.setEnabled(false);
369       modifyConservation.setEnabled(false);
370       // PIDColour.setEnabled(false);
371       // abovePIDThreshold.setEnabled(false);
372       // modifyPID.setEnabled(false);
373     }
374
375     String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
376
377     if (sortby.equals("Id"))
378     {
379       sortIDMenuItem_actionPerformed(null);
380     }
381     else if (sortby.equals("Pairwise Identity"))
382     {
383       sortPairwiseMenuItem_actionPerformed(null);
384     }
385
386     this.alignPanel.av
387             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
388
389     setMenusFromViewport(viewport);
390     buildSortByAnnotationScoresMenu();
391     calculateTree.addActionListener(new ActionListener()
392     {
393
394       @Override
395       public void actionPerformed(ActionEvent e)
396       {
397         openTreePcaDialog();
398       }
399     });
400     buildColourMenu();
401
402     if (Desktop.desktop != null)
403     {
404       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
405       if (!Platform.isJS())
406       {
407         addServiceListeners();
408       }
409       setGUINucleotide();
410     }
411
412     if (viewport.getWrapAlignment())
413     {
414       wrapMenuItem_actionPerformed(null);
415     }
416
417     if (Cache.getDefault("SHOW_OVERVIEW", false))
418     {
419       this.overviewMenuItem_actionPerformed(null);
420     }
421
422     addKeyListener();
423
424     final List<AlignmentViewPanel> selviews = new ArrayList<>();
425     final List<AlignmentPanel> origview = new ArrayList<>();
426     final String menuLabel = MessageManager
427             .getString("label.copy_format_from");
428     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
429             new ViewSetProvider()
430             {
431
432               @Override
433               public AlignmentPanel[] getAllAlignmentPanels()
434               {
435                 origview.clear();
436                 origview.add(alignPanel);
437                 // make an array of all alignment panels except for this one
438                 List<AlignmentPanel> aps = new ArrayList<>(
439                         Arrays.asList(Desktop.getAlignmentPanels(null)));
440                 aps.remove(AlignFrame.this.alignPanel);
441                 return aps.toArray(new AlignmentPanel[aps.size()]);
442               }
443             }, selviews, new ItemListener()
444             {
445
446               @Override
447               public void itemStateChanged(ItemEvent e)
448               {
449                 if (origview.size() > 0)
450                 {
451                   final AlignmentPanel ap = origview.get(0);
452
453                   /*
454                    * Copy the ViewStyle of the selected panel to 'this one'.
455                    * Don't change value of 'scaleProteinAsCdna' unless copying
456                    * from a SplitFrame.
457                    */
458                   ViewStyleI vs = selviews.get(0).getAlignViewport()
459                           .getViewStyle();
460                   boolean fromSplitFrame = selviews.get(0)
461                           .getAlignViewport().getCodingComplement() != null;
462                   if (!fromSplitFrame)
463                   {
464                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
465                             .getViewStyle().isScaleProteinAsCdna());
466                   }
467                   ap.getAlignViewport().setViewStyle(vs);
468
469                   /*
470                    * Also rescale ViewStyle of SplitFrame complement if there is
471                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
472                    * the whole ViewStyle (allow cDNA protein to have different
473                    * fonts)
474                    */
475                   AlignViewportI complement = ap.getAlignViewport()
476                           .getCodingComplement();
477                   if (complement != null && vs.isScaleProteinAsCdna())
478                   {
479                     AlignFrame af = Desktop.getAlignFrameFor(complement);
480                     ((SplitFrame) af.getSplitViewContainer())
481                             .adjustLayout();
482                     af.setMenusForViewport();
483                   }
484
485                   ap.updateLayout();
486                   ap.setSelected(true);
487                   ap.alignFrame.setMenusForViewport();
488
489                 }
490               }
491             });
492     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
493             .indexOf("devel") > -1
494             || Cache.getDefault("VERSION", "DEVELOPMENT")
495                     .toLowerCase(Locale.ROOT).indexOf("test") > -1)
496     {
497       formatMenu.add(vsel);
498     }
499     addFocusListener(new FocusAdapter()
500     {
501       @Override
502       public void focusGained(FocusEvent e)
503       {
504         Jalview.setCurrentAlignFrame(AlignFrame.this);
505       }
506     });
507
508   }
509
510   /**
511    * Change the filename and format for the alignment, and enable the 'reload'
512    * button functionality.
513    * 
514    * @param file
515    *          valid filename
516    * @param format
517    *          format of file
518    */
519   public void setFileName(String file, FileFormatI format)
520   {
521     fileName = file;
522     setFileFormat(format);
523     reload.setEnabled(true);
524   }
525
526   /**
527    * JavaScript will have this, maybe others. More dependable than a file name
528    * and maintains a reference to the actual bytes loaded.
529    * 
530    * @param file
531    */
532   public void setFileObject(File file)
533   {
534     this.fileObject = file;
535   }
536
537   /**
538    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
539    * events
540    */
541   void addKeyListener()
542   {
543     addKeyListener(new KeyAdapter()
544     {
545       @Override
546       public void keyPressed(KeyEvent evt)
547       {
548         if (viewport.cursorMode
549                 && ((evt.getKeyCode() >= KeyEvent.VK_0
550                         && evt.getKeyCode() <= KeyEvent.VK_9)
551                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
552                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
553                 && Character.isDigit(evt.getKeyChar()))
554         {
555           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
556         }
557
558         switch (evt.getKeyCode())
559         {
560
561         case 27: // escape key
562           deselectAllSequenceMenuItem_actionPerformed(null);
563
564           break;
565
566         case KeyEvent.VK_DOWN:
567           if (evt.isAltDown() || !viewport.cursorMode)
568           {
569             moveSelectedSequences(false);
570           }
571           if (viewport.cursorMode)
572           {
573             alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
574           }
575           break;
576
577         case KeyEvent.VK_UP:
578           if (evt.isAltDown() || !viewport.cursorMode)
579           {
580             moveSelectedSequences(true);
581           }
582           if (viewport.cursorMode)
583           {
584             alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
585           }
586
587           break;
588
589         case KeyEvent.VK_LEFT:
590           if (evt.isAltDown() || !viewport.cursorMode)
591           {
592             slideSequences(false,
593                     alignPanel.getSeqPanel().getKeyboardNo1());
594           }
595           else
596           {
597             alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
598           }
599
600           break;
601
602         case KeyEvent.VK_RIGHT:
603           if (evt.isAltDown() || !viewport.cursorMode)
604           {
605             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
606           }
607           else
608           {
609             alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
610           }
611           break;
612
613         case KeyEvent.VK_SPACE:
614           if (viewport.cursorMode)
615           {
616             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
617                     || evt.isShiftDown() || evt.isAltDown());
618           }
619           break;
620
621         // case KeyEvent.VK_A:
622         // if (viewport.cursorMode)
623         // {
624         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
625         // //System.out.println("A");
626         // }
627         // break;
628         /*
629          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
630          * System.out.println("closing bracket"); } break;
631          */
632         case KeyEvent.VK_DELETE:
633         case KeyEvent.VK_BACK_SPACE:
634           if (!viewport.cursorMode)
635           {
636             cut_actionPerformed();
637           }
638           else
639           {
640             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
641                     || evt.isShiftDown() || evt.isAltDown());
642           }
643
644           break;
645
646         case KeyEvent.VK_S:
647           if (viewport.cursorMode)
648           {
649             alignPanel.getSeqPanel().setCursorRow();
650           }
651           break;
652         case KeyEvent.VK_C:
653           if (viewport.cursorMode && !evt.isControlDown())
654           {
655             alignPanel.getSeqPanel().setCursorColumn();
656           }
657           break;
658         case KeyEvent.VK_P:
659           if (viewport.cursorMode)
660           {
661             alignPanel.getSeqPanel().setCursorPosition();
662           }
663           break;
664
665         case KeyEvent.VK_ENTER:
666         case KeyEvent.VK_COMMA:
667           if (viewport.cursorMode)
668           {
669             alignPanel.getSeqPanel().setCursorRowAndColumn();
670           }
671           break;
672
673         case KeyEvent.VK_Q:
674           if (viewport.cursorMode)
675           {
676             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
677           }
678           break;
679         case KeyEvent.VK_M:
680           if (viewport.cursorMode)
681           {
682             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
683           }
684           break;
685
686         case KeyEvent.VK_F2:
687           viewport.cursorMode = !viewport.cursorMode;
688           setStatus(MessageManager
689                   .formatMessage("label.keyboard_editing_mode", new String[]
690                   { (viewport.cursorMode ? "on" : "off") }));
691           if (viewport.cursorMode)
692           {
693             ViewportRanges ranges = viewport.getRanges();
694             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
695                     .getStartRes();
696             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
697                     .getStartSeq();
698           }
699           alignPanel.getSeqPanel().seqCanvas.repaint();
700           break;
701
702         case KeyEvent.VK_F1:
703           try
704           {
705             Help.showHelpWindow();
706           } catch (Exception ex)
707           {
708             ex.printStackTrace();
709           }
710           break;
711         case KeyEvent.VK_H:
712         {
713           boolean toggleSeqs = !evt.isControlDown();
714           boolean toggleCols = !evt.isShiftDown();
715           toggleHiddenRegions(toggleSeqs, toggleCols);
716           break;
717         }
718         case KeyEvent.VK_B:
719         {
720           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
721           boolean modifyExisting = true; // always modify, don't clear
722                                          // evt.isShiftDown();
723           boolean invertHighlighted = evt.isAltDown();
724           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
725                   toggleSel);
726           break;
727         }
728         case KeyEvent.VK_PAGE_UP:
729           viewport.getRanges().pageUp();
730           break;
731         case KeyEvent.VK_PAGE_DOWN:
732           viewport.getRanges().pageDown();
733           break;
734         }
735       }
736
737       @Override
738       public void keyReleased(KeyEvent evt)
739       {
740         switch (evt.getKeyCode())
741         {
742         case KeyEvent.VK_LEFT:
743           if (evt.isAltDown() || !viewport.cursorMode)
744           {
745             viewport.firePropertyChange("alignment", null,
746                     viewport.getAlignment().getSequences());
747           }
748           break;
749
750         case KeyEvent.VK_RIGHT:
751           if (evt.isAltDown() || !viewport.cursorMode)
752           {
753             viewport.firePropertyChange("alignment", null,
754                     viewport.getAlignment().getSequences());
755           }
756           break;
757         }
758       }
759     });
760   }
761
762   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
763   {
764     ap.alignFrame = this;
765     avc = new jalview.controller.AlignViewController(this, viewport,
766             alignPanel);
767
768     alignPanels.add(ap);
769
770     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
771
772     int aSize = alignPanels.size();
773
774     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
775
776     if (aSize == 1 && ap.av.getViewName() == null)
777     {
778       this.getContentPane().add(ap, BorderLayout.CENTER);
779     }
780     else
781     {
782       if (aSize == 2)
783       {
784         setInitialTabVisible();
785       }
786
787       expandViews.setEnabled(true);
788       gatherViews.setEnabled(true);
789       tabbedPane.addTab(ap.av.getViewName(), ap);
790
791       ap.setVisible(false);
792     }
793
794     if (newPanel)
795     {
796       if (ap.av.isPadGaps())
797       {
798         ap.av.getAlignment().padGaps();
799       }
800       ap.av.updateConservation(ap);
801       ap.av.updateConsensus(ap);
802       ap.av.updateStrucConsensus(ap);
803     }
804   }
805
806   public void setInitialTabVisible()
807   {
808     expandViews.setEnabled(true);
809     gatherViews.setEnabled(true);
810     tabbedPane.setVisible(true);
811     AlignmentPanel first = alignPanels.get(0);
812     tabbedPane.addTab(first.av.getViewName(), first);
813     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
814   }
815
816   public AlignViewport getViewport()
817   {
818     return viewport;
819   }
820
821   /* Set up intrinsic listeners for dynamically generated GUI bits. */
822   private void addServiceListeners()
823   {
824     final java.beans.PropertyChangeListener thisListener;
825     Desktop.instance.addJalviewPropertyChangeListener("services",
826             thisListener = new java.beans.PropertyChangeListener()
827             {
828               @Override
829               public void propertyChange(PropertyChangeEvent evt)
830               {
831                 // // System.out.println("Discoverer property change.");
832                 // if (evt.getPropertyName().equals("services"))
833                 {
834                   SwingUtilities.invokeLater(new Runnable()
835                   {
836
837                     @Override
838                     public void run()
839                     {
840                       System.err.println(
841                               "Rebuild WS Menu for service change");
842                       BuildWebServiceMenu();
843                     }
844
845                   });
846                 }
847               }
848             });
849     addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
850     {
851       @Override
852       public void internalFrameClosed(
853               javax.swing.event.InternalFrameEvent evt)
854       {
855         // System.out.println("deregistering discoverer listener");
856         Desktop.instance.removeJalviewPropertyChangeListener("services",
857                 thisListener);
858         closeMenuItem_actionPerformed(true);
859       }
860     });
861     // Finally, build the menu once to get current service state
862     new Thread(new Runnable()
863     {
864       @Override
865       public void run()
866       {
867         BuildWebServiceMenu();
868       }
869     }).start();
870   }
871
872   /**
873    * Configure menu items that vary according to whether the alignment is
874    * nucleotide or protein
875    */
876   public void setGUINucleotide()
877   {
878     AlignmentI al = getViewport().getAlignment();
879     boolean nucleotide = al.isNucleotide();
880
881     loadVcf.setVisible(nucleotide);
882     showTranslation.setVisible(nucleotide);
883     showReverse.setVisible(nucleotide);
884     showReverseComplement.setVisible(nucleotide);
885     conservationMenuItem.setEnabled(!nucleotide);
886     modifyConservation
887             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
888     showGroupConservation.setEnabled(!nucleotide);
889
890     showComplementMenuItem
891             .setText(nucleotide ? MessageManager.getString("label.protein")
892                     : MessageManager.getString("label.nucleotide"));
893   }
894
895   /**
896    * set up menus for the current viewport. This may be called after any
897    * operation that affects the data in the current view (selection changed,
898    * etc) to update the menus to reflect the new state.
899    */
900   @Override
901   public void setMenusForViewport()
902   {
903     setMenusFromViewport(viewport);
904   }
905
906   /**
907    * Need to call this method when tabs are selected for multiple views, or when
908    * loading from Jalview2XML.java
909    * 
910    * @param av
911    *          AlignViewport
912    */
913   public void setMenusFromViewport(AlignViewport av)
914   {
915     padGapsMenuitem.setSelected(av.isPadGaps());
916     colourTextMenuItem.setSelected(av.isShowColourText());
917     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
918     modifyPID.setEnabled(abovePIDThreshold.isSelected());
919     conservationMenuItem.setSelected(av.getConservationSelected());
920     modifyConservation.setEnabled(conservationMenuItem.isSelected());
921     seqLimits.setSelected(av.getShowJVSuffix());
922     idRightAlign.setSelected(av.isRightAlignIds());
923     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
924     renderGapsMenuItem.setSelected(av.isRenderGaps());
925     wrapMenuItem.setSelected(av.getWrapAlignment());
926     scaleAbove.setVisible(av.getWrapAlignment());
927     scaleLeft.setVisible(av.getWrapAlignment());
928     scaleRight.setVisible(av.getWrapAlignment());
929     annotationPanelMenuItem.setState(av.isShowAnnotation());
930     /*
931      * Show/hide annotations only enabled if annotation panel is shown
932      */
933     showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
934     hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
935     showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
936     hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
937     viewBoxesMenuItem.setSelected(av.getShowBoxes());
938     viewTextMenuItem.setSelected(av.getShowText());
939     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
940     showGroupConsensus.setSelected(av.isShowGroupConsensus());
941     showGroupConservation.setSelected(av.isShowGroupConservation());
942     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
943     showSequenceLogo.setSelected(av.isShowSequenceLogo());
944     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
945
946     ColourMenuHelper.setColourSelected(colourMenu,
947             av.getGlobalColourScheme());
948
949     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
950     hiddenMarkers.setState(av.getShowHiddenMarkers());
951     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
952     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
953     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
954     autoCalculate.setSelected(av.autoCalculateConsensus);
955     sortByTree.setSelected(av.sortByTree);
956     listenToViewSelections.setSelected(av.followSelection);
957
958     showProducts.setEnabled(canShowProducts());
959     setGroovyEnabled(Desktop.getGroovyConsole() != null);
960
961     updateEditMenuBar();
962   }
963
964   /**
965    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
966    * 
967    * @param b
968    */
969   public void setGroovyEnabled(boolean b)
970   {
971     runGroovy.setEnabled(b);
972   }
973
974   private IProgressIndicator progressBar;
975
976   /*
977    * (non-Javadoc)
978    * 
979    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
980    */
981   @Override
982   public void setProgressBar(String message, long id)
983   {
984     if (!Platform.isHeadless())
985       progressBar.setProgressBar(message, id);
986   }
987
988   @Override
989   public void registerHandler(final long id,
990           final IProgressIndicatorHandler handler)
991   {
992     progressBar.registerHandler(id, handler);
993   }
994
995   /**
996    * 
997    * @return true if any progress bars are still active
998    */
999   @Override
1000   public boolean operationInProgress()
1001   {
1002     return progressBar.operationInProgress();
1003   }
1004
1005   /**
1006    * Sets the text of the status bar. Note that setting a null or empty value
1007    * will cause the status bar to be hidden, with possibly undesirable flicker
1008    * of the screen layout.
1009    */
1010   @Override
1011   public void setStatus(String text)
1012   {
1013     statusBar.setText(text == null || text.isEmpty() ? " " : text);
1014   }
1015
1016   /*
1017    * Added so Castor Mapping file can obtain Jalview Version
1018    */
1019   public String getVersion()
1020   {
1021     return Cache.getProperty("VERSION");
1022   }
1023
1024   public FeatureRenderer getFeatureRenderer()
1025   {
1026     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1027   }
1028
1029   @Override
1030   public void fetchSequence_actionPerformed()
1031   {
1032     new SequenceFetcher(this);
1033   }
1034
1035   @Override
1036   public void addFromFile_actionPerformed(ActionEvent e)
1037   {
1038     Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1039   }
1040
1041   @Override
1042   public void reload_actionPerformed(ActionEvent e)
1043   {
1044     if (fileName != null)
1045     {
1046       // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1047       // originating file's format
1048       // TODO: work out how to recover feature settings for correct view(s) when
1049       // file is reloaded.
1050       if (FileFormat.Jalview.equals(currentFileFormat))
1051       {
1052         JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1053         for (int i = 0; i < frames.length; i++)
1054         {
1055           if (frames[i] instanceof AlignFrame && frames[i] != this
1056                   && ((AlignFrame) frames[i]).fileName != null
1057                   && ((AlignFrame) frames[i]).fileName.equals(fileName))
1058           {
1059             try
1060             {
1061               frames[i].setSelected(true);
1062               Desktop.instance.closeAssociatedWindows();
1063             } catch (java.beans.PropertyVetoException ex)
1064             {
1065             }
1066           }
1067
1068         }
1069         Desktop.instance.closeAssociatedWindows();
1070
1071         FileLoader loader = new FileLoader();
1072         DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1073                 ? DataSourceType.URL
1074                 : DataSourceType.FILE;
1075         loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1076       }
1077       else
1078       {
1079         Rectangle bounds = this.getBounds();
1080
1081         FileLoader loader = new FileLoader();
1082
1083         AlignFrame newframe = null;
1084
1085         if (fileObject == null)
1086         {
1087
1088           DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1089                   fileName) ? DataSourceType.URL : DataSourceType.FILE;
1090           newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1091                   currentFileFormat);
1092         }
1093         else
1094         {
1095           newframe = loader.LoadFileWaitTillLoaded(fileObject,
1096                   DataSourceType.FILE, currentFileFormat);
1097         }
1098
1099         newframe.setBounds(bounds);
1100         if (featureSettings != null && featureSettings.isShowing())
1101         {
1102           final Rectangle fspos = featureSettings.frame.getBounds();
1103           // TODO: need a 'show feature settings' function that takes bounds -
1104           // need to refactor Desktop.addFrame
1105           newframe.featureSettings_actionPerformed(null);
1106           final FeatureSettings nfs = newframe.featureSettings;
1107           SwingUtilities.invokeLater(new Runnable()
1108           {
1109             @Override
1110             public void run()
1111             {
1112               nfs.frame.setBounds(fspos);
1113             }
1114           });
1115           this.featureSettings.close();
1116           this.featureSettings = null;
1117         }
1118         this.closeMenuItem_actionPerformed(true);
1119       }
1120     }
1121   }
1122
1123   @Override
1124   public void addFromText_actionPerformed(ActionEvent e)
1125   {
1126     Desktop.instance
1127             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1128   }
1129
1130   @Override
1131   public void addFromURL_actionPerformed(ActionEvent e)
1132   {
1133     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1134   }
1135
1136   @Override
1137   public void save_actionPerformed(ActionEvent e)
1138   {
1139     if (fileName == null || (currentFileFormat == null)
1140             || HttpUtils.startsWithHttpOrHttps(fileName))
1141     {
1142       saveAs_actionPerformed();
1143     }
1144     else
1145     {
1146       saveAlignment(fileName, currentFileFormat);
1147     }
1148   }
1149
1150   /**
1151    * Saves the alignment to a file with a name chosen by the user, if necessary
1152    * warning if a file would be overwritten
1153    */
1154   @Override
1155   public void saveAs_actionPerformed()
1156   {
1157     String format = currentFileFormat == null ? null
1158             : currentFileFormat.getName();
1159     JalviewFileChooser chooser = JalviewFileChooser
1160             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1161
1162     chooser.setFileView(new JalviewFileView());
1163     chooser.setDialogTitle(
1164             MessageManager.getString("label.save_alignment_to_file"));
1165     chooser.setToolTipText(MessageManager.getString("action.save"));
1166
1167     int value = chooser.showSaveDialog(this);
1168
1169     if (value != JalviewFileChooser.APPROVE_OPTION)
1170     {
1171       return;
1172     }
1173     currentFileFormat = chooser.getSelectedFormat();
1174     // todo is this (2005) test now obsolete - value is never null?
1175     while (currentFileFormat == null)
1176     {
1177       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1178               MessageManager
1179                       .getString("label.select_file_format_before_saving"),
1180               MessageManager.getString("label.file_format_not_specified"),
1181               JvOptionPane.WARNING_MESSAGE);
1182       currentFileFormat = chooser.getSelectedFormat();
1183       value = chooser.showSaveDialog(this);
1184       if (value != JalviewFileChooser.APPROVE_OPTION)
1185       {
1186         return;
1187       }
1188     }
1189
1190     fileName = chooser.getSelectedFile().getPath();
1191
1192     Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1193     Cache.setProperty("LAST_DIRECTORY", fileName);
1194     saveAlignment(fileName, currentFileFormat);
1195   }
1196
1197   boolean lastSaveSuccessful = false;
1198
1199   FileFormatI lastFormatSaved;
1200
1201   String lastFilenameSaved;
1202
1203   /**
1204    * Raise a dialog or status message for the last call to saveAlignment.
1205    *
1206    * @return true if last call to saveAlignment(file, format) was successful.
1207    */
1208   public boolean isSaveAlignmentSuccessful()
1209   {
1210
1211     if (!lastSaveSuccessful)
1212     {
1213       if (!Platform.isHeadless())
1214       {
1215         JvOptionPane.showInternalMessageDialog(this, MessageManager
1216                 .formatMessage("label.couldnt_save_file", new Object[]
1217                 { lastFilenameSaved }),
1218                 MessageManager.getString("label.error_saving_file"),
1219                 JvOptionPane.WARNING_MESSAGE);
1220       }
1221       else
1222       {
1223         Console.error(MessageManager
1224                 .formatMessage("label.couldnt_save_file", new Object[]
1225                 { lastFilenameSaved }));
1226       }
1227     }
1228     else
1229     {
1230
1231       setStatus(MessageManager.formatMessage(
1232               "label.successfully_saved_to_file_in_format", new Object[]
1233               { lastFilenameSaved, lastFormatSaved }));
1234
1235     }
1236     return lastSaveSuccessful;
1237   }
1238
1239   /**
1240    * Saves the alignment to the specified file path, in the specified format,
1241    * which may be an alignment format, or Jalview project format. If the
1242    * alignment has hidden regions, or the format is one capable of including
1243    * non-sequence data (features, annotations, groups), then the user may be
1244    * prompted to specify what to include in the output.
1245    * 
1246    * @param file
1247    * @param format
1248    */
1249   public void saveAlignment(String file, FileFormatI format)
1250   {
1251     lastSaveSuccessful = true;
1252     lastFilenameSaved = file;
1253     lastFormatSaved = format;
1254
1255     if (FileFormat.Jalview.equals(format))
1256     {
1257       String shortName = title;
1258       if (shortName.indexOf(File.separatorChar) > -1)
1259       {
1260         shortName = shortName
1261                 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1262       }
1263       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1264               shortName);
1265
1266       Console.debug("lastSaveSuccessful=" + lastSaveSuccessful);
1267       if (lastSaveSuccessful)
1268       {
1269         this.getViewport().setSavedUpToDate(true);
1270       }
1271
1272       statusBar.setText(MessageManager.formatMessage(
1273               "label.successfully_saved_to_file_in_format", new Object[]
1274               { file, format }));
1275
1276       return;
1277     }
1278
1279     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1280     Callable<Void> cancelAction = () -> {
1281       lastSaveSuccessful = false;
1282       return null;
1283     };
1284     Callable<Void> outputAction = () -> {
1285       // todo defer this to inside formatSequences (or later)
1286       AlignmentExportData exportData = viewport.getAlignExportData(options);
1287       String output = new FormatAdapter(alignPanel, options)
1288               .formatSequences(format, exportData.getAlignment(),
1289                       exportData.getOmitHidden(),
1290                       exportData.getStartEndPostions(),
1291                       viewport.getAlignment().getHiddenColumns());
1292       if (output == null)
1293       {
1294         lastSaveSuccessful = false;
1295       }
1296       else
1297       {
1298         // create backupfiles object and get new temp filename destination
1299         boolean doBackup = BackupFiles.getEnabled();
1300         BackupFiles backupfiles = null;
1301         if (doBackup)
1302         {
1303           Console.trace("ALIGNFRAME making backupfiles object for " + file);
1304           backupfiles = new BackupFiles(file);
1305         }
1306         try
1307         {
1308           String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1309                   : file;
1310           Console.trace("ALIGNFRAME setting PrintWriter");
1311           PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1312
1313           if (backupfiles != null)
1314           {
1315             Console.trace("ALIGNFRAME about to write to temp file "
1316                     + backupfiles.getTempFilePath());
1317           }
1318
1319           out.print(output);
1320           Console.trace("ALIGNFRAME about to close file");
1321           out.close();
1322           Console.trace("ALIGNFRAME closed file");
1323           AlignFrame.this.setTitle(file);
1324           statusBar.setText(MessageManager.formatMessage(
1325                   "label.successfully_saved_to_file_in_format", new Object[]
1326                   { fileName, format.getName() }));
1327           lastSaveSuccessful = true;
1328         } catch (IOException e)
1329         {
1330           lastSaveSuccessful = false;
1331           Console.error(
1332                   "ALIGNFRAME Something happened writing the temp file");
1333           Console.error(e.getMessage());
1334           Console.debug(Cache.getStackTraceString(e));
1335         } catch (Exception ex)
1336         {
1337           lastSaveSuccessful = false;
1338           Console.error(
1339                   "ALIGNFRAME Something unexpected happened writing the temp file");
1340           Console.error(ex.getMessage());
1341           Console.debug(Cache.getStackTraceString(ex));
1342         }
1343
1344         if (doBackup)
1345         {
1346           backupfiles.setWriteSuccess(lastSaveSuccessful);
1347           Console.debug("ALIGNFRAME writing temp file was "
1348                   + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1349           // do the backup file roll and rename the temp file to actual file
1350           Console.trace("ALIGNFRAME about to rollBackupsAndRenameTempFile");
1351           lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1352           Console.debug("ALIGNFRAME performed rollBackupsAndRenameTempFile "
1353                   + (lastSaveSuccessful ? "" : "un") + "successfully");
1354         }
1355
1356         Console.debug("lastSaveSuccessful=" + lastSaveSuccessful);
1357         if (lastSaveSuccessful)
1358         {
1359           AlignFrame.this.getViewport().setSavedUpToDate(true);
1360         }
1361       }
1362       return null;
1363     };
1364
1365     /*
1366      * show dialog with export options if applicable; else just do it
1367      */
1368     if (AlignExportOptions.isNeeded(viewport, format))
1369     {
1370       AlignExportOptions choices = new AlignExportOptions(
1371               alignPanel.getAlignViewport(), format, options);
1372       choices.setResponseAction(0, outputAction);
1373       choices.setResponseAction(1, cancelAction);
1374       choices.showDialog();
1375     }
1376     else
1377     {
1378       try
1379       {
1380         outputAction.call();
1381       } catch (Exception e)
1382       {
1383         // TODO Auto-generated catch block
1384         e.printStackTrace();
1385       }
1386     }
1387   }
1388
1389   /**
1390    * Outputs the alignment to textbox in the requested format, if necessary
1391    * first prompting the user for whether to include hidden regions or
1392    * non-sequence data
1393    * 
1394    * @param fileFormatName
1395    */
1396   @Override
1397   protected void outputText_actionPerformed(String fileFormatName)
1398   {
1399     FileFormatI fileFormat = FileFormats.getInstance()
1400             .forName(fileFormatName);
1401     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1402     Callable<Void> outputAction = () -> {
1403       // todo defer this to inside formatSequences (or later)
1404       AlignmentExportData exportData = viewport.getAlignExportData(options);
1405       CutAndPasteTransfer cap = new CutAndPasteTransfer();
1406       cap.setForInput(null);
1407       try
1408       {
1409         FileFormatI format = fileFormat;
1410         cap.setText(new FormatAdapter(alignPanel, options).formatSequences(
1411                 format, exportData.getAlignment(),
1412                 exportData.getOmitHidden(),
1413                 exportData.getStartEndPostions(),
1414                 viewport.getAlignment().getHiddenColumns()));
1415         Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1416                 "label.alignment_output_command", new Object[]
1417                 { fileFormat.getName() }), 600, 500);
1418       } catch (OutOfMemoryError oom)
1419       {
1420         new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1421                 oom);
1422         cap.dispose();
1423       }
1424       return null;
1425     };
1426
1427     /*
1428      * show dialog with export options if applicable; else just do it
1429      */
1430     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1431     {
1432       AlignExportOptions choices = new AlignExportOptions(
1433               alignPanel.getAlignViewport(), fileFormat, options);
1434       choices.setResponseAction(0, outputAction);
1435       choices.showDialog();
1436     }
1437     else
1438     {
1439       try
1440       {
1441         outputAction.call();
1442       } catch (Exception e)
1443       {
1444         e.printStackTrace();
1445       }
1446     }
1447   }
1448
1449   /**
1450    * DOCUMENT ME!
1451    * 
1452    * @param e
1453    *          DOCUMENT ME!
1454    */
1455   @Override
1456   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1457   {
1458     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1459     htmlSVG.exportHTML(null);
1460   }
1461
1462   @Override
1463   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1464   {
1465     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1466     bjs.exportHTML(null);
1467   }
1468
1469   public void createImageMap(File file, String image)
1470   {
1471     alignPanel.makePNGImageMap(file, image);
1472   }
1473
1474   /**
1475    * Creates a PNG image of the alignment and writes it to the given file. If
1476    * the file is null, the user is prompted to choose a file.
1477    * 
1478    * @param f
1479    */
1480   @Override
1481   public void createPNG(File f)
1482   {
1483     createPNG(f, null);
1484   }
1485
1486   public void createPNG(File f, String renderer)
1487   {
1488     alignPanel.makeAlignmentImage(TYPE.PNG, f, renderer);
1489   }
1490
1491   /**
1492    * Creates an EPS image of the alignment and writes it to the given file. If
1493    * the file is null, the user is prompted to choose a file.
1494    * 
1495    * @param f
1496    */
1497   @Override
1498   public void createEPS(File f)
1499   {
1500     createEPS(f, null);
1501   }
1502
1503   public void createEPS(File f, String renderer)
1504   {
1505     alignPanel.makeAlignmentImage(TYPE.EPS, f, renderer);
1506   }
1507
1508   /**
1509    * Creates an SVG image of the alignment and writes it to the given file. If
1510    * the file is null, the user is prompted to choose a file.
1511    * 
1512    * @param f
1513    */
1514   @Override
1515   public void createSVG(File f)
1516   {
1517     createSVG(f, null);
1518   }
1519
1520   public void createSVG(File f, String renderer)
1521   {
1522     alignPanel.makeAlignmentImage(TYPE.SVG, f, renderer);
1523   }
1524
1525   @Override
1526   public void pageSetup_actionPerformed(ActionEvent e)
1527   {
1528     PrinterJob printJob = PrinterJob.getPrinterJob();
1529     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1530   }
1531
1532   /**
1533    * DOCUMENT ME!
1534    * 
1535    * @param e
1536    *          DOCUMENT ME!
1537    */
1538   @Override
1539   public void printMenuItem_actionPerformed(ActionEvent e)
1540   {
1541     // Putting in a thread avoids Swing painting problems
1542     PrintThread thread = new PrintThread(alignPanel);
1543     thread.start();
1544   }
1545
1546   @Override
1547   public void exportFeatures_actionPerformed(ActionEvent e)
1548   {
1549     new AnnotationExporter(alignPanel).exportFeatures();
1550   }
1551
1552   @Override
1553   public void exportAnnotations_actionPerformed(ActionEvent e)
1554   {
1555     new AnnotationExporter(alignPanel).exportAnnotations();
1556   }
1557
1558   @Override
1559   public void associatedData_actionPerformed(ActionEvent e)
1560   {
1561     final JalviewFileChooser chooser = new JalviewFileChooser(
1562             Cache.getProperty("LAST_DIRECTORY"));
1563     chooser.setFileView(new JalviewFileView());
1564     String tooltip = MessageManager
1565             .getString("label.load_jalview_annotations");
1566     chooser.setDialogTitle(tooltip);
1567     chooser.setToolTipText(tooltip);
1568     chooser.setResponseHandler(0, () -> {
1569       String choice = chooser.getSelectedFile().getPath();
1570       Cache.setProperty("LAST_DIRECTORY", choice);
1571       loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1572       return null;
1573     });
1574
1575     chooser.showOpenDialog(this);
1576   }
1577
1578   /**
1579    * Close the current view or all views in the alignment frame. If the frame
1580    * only contains one view then the alignment will be removed from memory.
1581    * 
1582    * @param closeAllTabs
1583    */
1584   @Override
1585   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1586   {
1587     if (alignPanels != null && alignPanels.size() < 2)
1588     {
1589       closeAllTabs = true;
1590     }
1591
1592     try
1593     {
1594       if (alignPanels != null)
1595       {
1596         if (closeAllTabs)
1597         {
1598           if (this.isClosed())
1599           {
1600             // really close all the windows - otherwise wait till
1601             // setClosed(true) is called
1602             for (int i = 0; i < alignPanels.size(); i++)
1603             {
1604               AlignmentPanel ap = alignPanels.get(i);
1605               ap.closePanel();
1606             }
1607           }
1608         }
1609         else
1610         {
1611           closeView(alignPanel);
1612         }
1613       }
1614       if (closeAllTabs)
1615       {
1616         if (featureSettings != null && featureSettings.isOpen())
1617         {
1618           featureSettings.close();
1619           featureSettings = null;
1620         }
1621         /*
1622          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1623          * be called recursively, with the frame now in 'closed' state
1624          */
1625         this.setClosed(true);
1626       }
1627     } catch (Exception ex)
1628     {
1629       ex.printStackTrace();
1630     }
1631   }
1632
1633   /**
1634    * Close the specified panel and close up tabs appropriately.
1635    * 
1636    * @param panelToClose
1637    */
1638   public void closeView(AlignmentPanel panelToClose)
1639   {
1640     int index = tabbedPane.getSelectedIndex();
1641     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1642     alignPanels.remove(panelToClose);
1643     panelToClose.closePanel();
1644     panelToClose = null;
1645
1646     tabbedPane.removeTabAt(closedindex);
1647     tabbedPane.validate();
1648
1649     if (index > closedindex || index == tabbedPane.getTabCount())
1650     {
1651       // modify currently selected tab index if necessary.
1652       index--;
1653     }
1654
1655     this.tabSelectionChanged(index);
1656   }
1657
1658   /**
1659    * DOCUMENT ME!
1660    */
1661   void updateEditMenuBar()
1662   {
1663
1664     if (viewport.getHistoryList().size() > 0)
1665     {
1666       undoMenuItem.setEnabled(true);
1667       CommandI command = viewport.getHistoryList().peek();
1668       undoMenuItem.setText(MessageManager
1669               .formatMessage("label.undo_command", new Object[]
1670               { command.getDescription() }));
1671     }
1672     else
1673     {
1674       undoMenuItem.setEnabled(false);
1675       undoMenuItem.setText(MessageManager.getString("action.undo"));
1676     }
1677
1678     if (viewport.getRedoList().size() > 0)
1679     {
1680       redoMenuItem.setEnabled(true);
1681
1682       CommandI command = viewport.getRedoList().peek();
1683       redoMenuItem.setText(MessageManager
1684               .formatMessage("label.redo_command", new Object[]
1685               { command.getDescription() }));
1686     }
1687     else
1688     {
1689       redoMenuItem.setEnabled(false);
1690       redoMenuItem.setText(MessageManager.getString("action.redo"));
1691     }
1692   }
1693
1694   @Override
1695   public void addHistoryItem(CommandI command)
1696   {
1697     if (command.getSize() > 0)
1698     {
1699       viewport.addToHistoryList(command);
1700       viewport.clearRedoList();
1701       updateEditMenuBar();
1702       viewport.updateHiddenColumns();
1703       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1704       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1705       // viewport.getColumnSelection()
1706       // .getHiddenColumns().size() > 0);
1707     }
1708   }
1709
1710   /**
1711    * 
1712    * @return alignment objects for all views
1713    */
1714   AlignmentI[] getViewAlignments()
1715   {
1716     if (alignPanels != null)
1717     {
1718       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1719       int i = 0;
1720       for (AlignmentPanel ap : alignPanels)
1721       {
1722         als[i++] = ap.av.getAlignment();
1723       }
1724       return als;
1725     }
1726     if (viewport != null)
1727     {
1728       return new AlignmentI[] { viewport.getAlignment() };
1729     }
1730     return null;
1731   }
1732
1733   /**
1734    * DOCUMENT ME!
1735    * 
1736    * @param e
1737    *          DOCUMENT ME!
1738    */
1739   @Override
1740   protected void undoMenuItem_actionPerformed(ActionEvent e)
1741   {
1742     if (viewport.getHistoryList().isEmpty())
1743     {
1744       return;
1745     }
1746     CommandI command = viewport.getHistoryList().pop();
1747     viewport.addToRedoList(command);
1748     command.undoCommand(getViewAlignments());
1749
1750     AlignmentViewport originalSource = getOriginatingSource(command);
1751     updateEditMenuBar();
1752
1753     if (originalSource != null)
1754     {
1755       if (originalSource != viewport)
1756       {
1757         Console.warn(
1758                 "Implementation worry: mismatch of viewport origin for undo");
1759       }
1760       originalSource.updateHiddenColumns();
1761       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1762       // null
1763       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1764       // viewport.getColumnSelection()
1765       // .getHiddenColumns().size() > 0);
1766       originalSource.firePropertyChange("alignment", null,
1767               originalSource.getAlignment().getSequences());
1768     }
1769   }
1770
1771   /**
1772    * DOCUMENT ME!
1773    * 
1774    * @param e
1775    *          DOCUMENT ME!
1776    */
1777   @Override
1778   protected void redoMenuItem_actionPerformed(ActionEvent e)
1779   {
1780     if (viewport.getRedoList().size() < 1)
1781     {
1782       return;
1783     }
1784
1785     CommandI command = viewport.getRedoList().pop();
1786     viewport.addToHistoryList(command);
1787     command.doCommand(getViewAlignments());
1788
1789     AlignmentViewport originalSource = getOriginatingSource(command);
1790     updateEditMenuBar();
1791
1792     if (originalSource != null)
1793     {
1794
1795       if (originalSource != viewport)
1796       {
1797         Console.warn(
1798                 "Implementation worry: mismatch of viewport origin for redo");
1799       }
1800       originalSource.updateHiddenColumns();
1801       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1802       // null
1803       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1804       // viewport.getColumnSelection()
1805       // .getHiddenColumns().size() > 0);
1806       originalSource.firePropertyChange("alignment", null,
1807               originalSource.getAlignment().getSequences());
1808     }
1809   }
1810
1811   AlignmentViewport getOriginatingSource(CommandI command)
1812   {
1813     AlignmentViewport originalSource = null;
1814     // For sequence removal and addition, we need to fire
1815     // the property change event FROM the viewport where the
1816     // original alignment was altered
1817     AlignmentI al = null;
1818     if (command instanceof EditCommand)
1819     {
1820       EditCommand editCommand = (EditCommand) command;
1821       al = editCommand.getAlignment();
1822       List<Component> comps = PaintRefresher.components
1823               .get(viewport.getSequenceSetId());
1824
1825       for (Component comp : comps)
1826       {
1827         if (comp instanceof AlignmentPanel)
1828         {
1829           if (al == ((AlignmentPanel) comp).av.getAlignment())
1830           {
1831             originalSource = ((AlignmentPanel) comp).av;
1832             break;
1833           }
1834         }
1835       }
1836     }
1837
1838     if (originalSource == null)
1839     {
1840       // The original view is closed, we must validate
1841       // the current view against the closed view first
1842       if (al != null)
1843       {
1844         PaintRefresher.validateSequences(al, viewport.getAlignment());
1845       }
1846
1847       originalSource = viewport;
1848     }
1849
1850     return originalSource;
1851   }
1852
1853   /**
1854    * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1855    * or the sequence under cursor in keyboard mode
1856    * 
1857    * @param up
1858    *          or down (if !up)
1859    */
1860   public void moveSelectedSequences(boolean up)
1861   {
1862     SequenceGroup sg = viewport.getSelectionGroup();
1863
1864     if (sg == null)
1865     {
1866       if (viewport.cursorMode)
1867       {
1868         sg = new SequenceGroup();
1869         sg.addSequence(viewport.getAlignment().getSequenceAt(
1870                 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1871       }
1872       else
1873       {
1874         return;
1875       }
1876     }
1877
1878     if (sg.getSize() < 1)
1879     {
1880       return;
1881     }
1882
1883     // TODO: JAL-3733 - add an event to the undo buffer for this !
1884
1885     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1886             viewport.getHiddenRepSequences(), up);
1887     alignPanel.paintAlignment(true, false);
1888   }
1889
1890   synchronized void slideSequences(boolean right, int size)
1891   {
1892     List<SequenceI> sg = new ArrayList<>();
1893     if (viewport.cursorMode)
1894     {
1895       sg.add(viewport.getAlignment()
1896               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1897     }
1898     else if (viewport.getSelectionGroup() != null
1899             && viewport.getSelectionGroup().getSize() != viewport
1900                     .getAlignment().getHeight())
1901     {
1902       sg = viewport.getSelectionGroup()
1903               .getSequences(viewport.getHiddenRepSequences());
1904     }
1905
1906     if (sg.size() < 1)
1907     {
1908       return;
1909     }
1910
1911     List<SequenceI> invertGroup = new ArrayList<>();
1912
1913     for (SequenceI seq : viewport.getAlignment().getSequences())
1914     {
1915       if (!sg.contains(seq))
1916       {
1917         invertGroup.add(seq);
1918       }
1919     }
1920
1921     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1922
1923     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1924     for (int i = 0; i < invertGroup.size(); i++)
1925     {
1926       seqs2[i] = invertGroup.get(i);
1927     }
1928
1929     SlideSequencesCommand ssc;
1930     if (right)
1931     {
1932       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1933               viewport.getGapCharacter());
1934     }
1935     else
1936     {
1937       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1938               viewport.getGapCharacter());
1939     }
1940
1941     int groupAdjustment = 0;
1942     if (ssc.getGapsInsertedBegin() && right)
1943     {
1944       if (viewport.cursorMode)
1945       {
1946         alignPanel.getSeqPanel().moveCursor(size, 0);
1947       }
1948       else
1949       {
1950         groupAdjustment = size;
1951       }
1952     }
1953     else if (!ssc.getGapsInsertedBegin() && !right)
1954     {
1955       if (viewport.cursorMode)
1956       {
1957         alignPanel.getSeqPanel().moveCursor(-size, 0);
1958       }
1959       else
1960       {
1961         groupAdjustment = -size;
1962       }
1963     }
1964
1965     if (groupAdjustment != 0)
1966     {
1967       viewport.getSelectionGroup().setStartRes(
1968               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1969       viewport.getSelectionGroup().setEndRes(
1970               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1971     }
1972
1973     /*
1974      * just extend the last slide command if compatible; but not if in
1975      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1976      */
1977     boolean appendHistoryItem = false;
1978     Deque<CommandI> historyList = viewport.getHistoryList();
1979     boolean inSplitFrame = getSplitViewContainer() != null;
1980     if (!inSplitFrame && historyList != null && historyList.size() > 0
1981             && historyList.peek() instanceof SlideSequencesCommand)
1982     {
1983       appendHistoryItem = ssc.appendSlideCommand(
1984               (SlideSequencesCommand) historyList.peek());
1985     }
1986
1987     if (!appendHistoryItem)
1988     {
1989       addHistoryItem(ssc);
1990     }
1991
1992     repaint();
1993   }
1994
1995   /**
1996    * DOCUMENT ME!
1997    * 
1998    * @param e
1999    *          DOCUMENT ME!
2000    */
2001   @Override
2002   protected void copy_actionPerformed()
2003   {
2004     if (viewport.getSelectionGroup() == null)
2005     {
2006       return;
2007     }
2008     // TODO: preserve the ordering of displayed alignment annotation in any
2009     // internal paste (particularly sequence associated annotation)
2010     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2011     String[] omitHidden = null;
2012
2013     if (viewport.hasHiddenColumns())
2014     {
2015       omitHidden = viewport.getViewAsString(true);
2016     }
2017
2018     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2019             seqs, omitHidden, null);
2020
2021     StringSelection ss = new StringSelection(output);
2022
2023     try
2024     {
2025       jalview.gui.Desktop.internalCopy = true;
2026       // Its really worth setting the clipboard contents
2027       // to empty before setting the large StringSelection!!
2028       Toolkit.getDefaultToolkit().getSystemClipboard()
2029               .setContents(new StringSelection(""), null);
2030
2031       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2032               Desktop.instance);
2033     } catch (OutOfMemoryError er)
2034     {
2035       new OOMWarning("copying region", er);
2036       return;
2037     }
2038
2039     HiddenColumns hiddenColumns = null;
2040     if (viewport.hasHiddenColumns())
2041     {
2042       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2043       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2044
2045       // create new HiddenColumns object with copy of hidden regions
2046       // between startRes and endRes, offset by startRes
2047       hiddenColumns = new HiddenColumns(
2048               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2049               hiddenCutoff, hiddenOffset);
2050     }
2051
2052     Desktop.jalviewClipboard = new Object[] { seqs,
2053         viewport.getAlignment().getDataset(), hiddenColumns };
2054     setStatus(MessageManager.formatMessage(
2055             "label.copied_sequences_to_clipboard", new Object[]
2056             { Integer.valueOf(seqs.length).toString() }));
2057   }
2058
2059   /**
2060    * DOCUMENT ME!
2061    * 
2062    * @param e
2063    *          DOCUMENT ME!
2064    */
2065   @Override
2066   protected void pasteNew_actionPerformed(ActionEvent e)
2067   {
2068     paste(true);
2069   }
2070
2071   /**
2072    * DOCUMENT ME!
2073    * 
2074    * @param e
2075    *          DOCUMENT ME!
2076    */
2077   @Override
2078   protected void pasteThis_actionPerformed(ActionEvent e)
2079   {
2080     paste(false);
2081   }
2082
2083   /**
2084    * Paste contents of Jalview clipboard
2085    * 
2086    * @param newAlignment
2087    *          true to paste to a new alignment, otherwise add to this.
2088    */
2089   void paste(boolean newAlignment)
2090   {
2091     boolean externalPaste = true;
2092     try
2093     {
2094       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2095       Transferable contents = c.getContents(this);
2096
2097       if (contents == null)
2098       {
2099         return;
2100       }
2101
2102       String str;
2103       FileFormatI format;
2104       try
2105       {
2106         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2107         if (str.length() < 1)
2108         {
2109           return;
2110         }
2111
2112         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2113
2114       } catch (OutOfMemoryError er)
2115       {
2116         new OOMWarning("Out of memory pasting sequences!!", er);
2117         return;
2118       }
2119
2120       SequenceI[] sequences;
2121       boolean annotationAdded = false;
2122       AlignmentI alignment = null;
2123
2124       if (Desktop.jalviewClipboard != null)
2125       {
2126         // The clipboard was filled from within Jalview, we must use the
2127         // sequences
2128         // And dataset from the copied alignment
2129         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2130         // be doubly sure that we create *new* sequence objects.
2131         sequences = new SequenceI[newseq.length];
2132         for (int i = 0; i < newseq.length; i++)
2133         {
2134           sequences[i] = new Sequence(newseq[i]);
2135         }
2136         alignment = new Alignment(sequences);
2137         externalPaste = false;
2138       }
2139       else
2140       {
2141         // parse the clipboard as an alignment.
2142         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2143                 format);
2144         sequences = alignment.getSequencesArray();
2145       }
2146
2147       int alwidth = 0;
2148       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2149       int fgroup = -1;
2150
2151       if (newAlignment)
2152       {
2153
2154         if (Desktop.jalviewClipboard != null)
2155         {
2156           // dataset is inherited
2157           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2158         }
2159         else
2160         {
2161           // new dataset is constructed
2162           alignment.setDataset(null);
2163         }
2164         alwidth = alignment.getWidth() + 1;
2165       }
2166       else
2167       {
2168         AlignmentI pastedal = alignment; // preserve pasted alignment object
2169         // Add pasted sequences and dataset into existing alignment.
2170         alignment = viewport.getAlignment();
2171         alwidth = alignment.getWidth() + 1;
2172         // decide if we need to import sequences from an existing dataset
2173         boolean importDs = Desktop.jalviewClipboard != null
2174                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2175         // importDs==true instructs us to copy over new dataset sequences from
2176         // an existing alignment
2177         Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2178                                                                       // create
2179         // minimum dataset set
2180
2181         for (int i = 0; i < sequences.length; i++)
2182         {
2183           if (importDs)
2184           {
2185             newDs.addElement(null);
2186           }
2187           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2188           // paste
2189           if (importDs && ds != null)
2190           {
2191             if (!newDs.contains(ds))
2192             {
2193               newDs.setElementAt(ds, i);
2194               ds = new Sequence(ds);
2195               // update with new dataset sequence
2196               sequences[i].setDatasetSequence(ds);
2197             }
2198             else
2199             {
2200               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2201             }
2202           }
2203           else
2204           {
2205             // copy and derive new dataset sequence
2206             sequences[i] = sequences[i].deriveSequence();
2207             alignment.getDataset()
2208                     .addSequence(sequences[i].getDatasetSequence());
2209             // TODO: avoid creation of duplicate dataset sequences with a
2210             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2211           }
2212           alignment.addSequence(sequences[i]); // merges dataset
2213         }
2214         if (newDs != null)
2215         {
2216           newDs.clear(); // tidy up
2217         }
2218         if (alignment.getAlignmentAnnotation() != null)
2219         {
2220           for (AlignmentAnnotation alan : alignment
2221                   .getAlignmentAnnotation())
2222           {
2223             if (alan.graphGroup > fgroup)
2224             {
2225               fgroup = alan.graphGroup;
2226             }
2227           }
2228         }
2229         if (pastedal.getAlignmentAnnotation() != null)
2230         {
2231           // Add any annotation attached to alignment.
2232           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2233           for (int i = 0; i < alann.length; i++)
2234           {
2235             annotationAdded = true;
2236             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2237             {
2238               AlignmentAnnotation newann = new AlignmentAnnotation(
2239                       alann[i]);
2240               if (newann.graphGroup > -1)
2241               {
2242                 if (newGraphGroups.size() <= newann.graphGroup
2243                         || newGraphGroups.get(newann.graphGroup) == null)
2244                 {
2245                   for (int q = newGraphGroups
2246                           .size(); q <= newann.graphGroup; q++)
2247                   {
2248                     newGraphGroups.add(q, null);
2249                   }
2250                   newGraphGroups.set(newann.graphGroup,
2251                           Integer.valueOf(++fgroup));
2252                 }
2253                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2254                         .intValue();
2255               }
2256
2257               newann.padAnnotation(alwidth);
2258               alignment.addAnnotation(newann);
2259             }
2260           }
2261         }
2262       }
2263       if (!newAlignment)
2264       {
2265         // /////
2266         // ADD HISTORY ITEM
2267         //
2268         addHistoryItem(new EditCommand(
2269                 MessageManager.getString("label.add_sequences"),
2270                 Action.PASTE, sequences, 0, alignment.getWidth(),
2271                 alignment));
2272       }
2273       // Add any annotations attached to sequences
2274       for (int i = 0; i < sequences.length; i++)
2275       {
2276         if (sequences[i].getAnnotation() != null)
2277         {
2278           AlignmentAnnotation newann;
2279           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2280           {
2281             annotationAdded = true;
2282             newann = sequences[i].getAnnotation()[a];
2283             newann.adjustForAlignment();
2284             newann.padAnnotation(alwidth);
2285             if (newann.graphGroup > -1)
2286             {
2287               if (newann.graphGroup > -1)
2288               {
2289                 if (newGraphGroups.size() <= newann.graphGroup
2290                         || newGraphGroups.get(newann.graphGroup) == null)
2291                 {
2292                   for (int q = newGraphGroups
2293                           .size(); q <= newann.graphGroup; q++)
2294                   {
2295                     newGraphGroups.add(q, null);
2296                   }
2297                   newGraphGroups.set(newann.graphGroup,
2298                           Integer.valueOf(++fgroup));
2299                 }
2300                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2301                         .intValue();
2302               }
2303             }
2304             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2305             // was
2306             // duplicated
2307             // earlier
2308             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2309                     a);
2310           }
2311         }
2312       }
2313       if (!newAlignment)
2314       {
2315
2316         // propagate alignment changed.
2317         viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2318         if (annotationAdded)
2319         {
2320           // Duplicate sequence annotation in all views.
2321           AlignmentI[] alview = this.getViewAlignments();
2322           for (int i = 0; i < sequences.length; i++)
2323           {
2324             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2325             if (sann == null)
2326             {
2327               continue;
2328             }
2329             for (int avnum = 0; avnum < alview.length; avnum++)
2330             {
2331               if (alview[avnum] != alignment)
2332               {
2333                 // duplicate in a view other than the one with input focus
2334                 int avwidth = alview[avnum].getWidth() + 1;
2335                 // this relies on sann being preserved after we
2336                 // modify the sequence's annotation array for each duplication
2337                 for (int a = 0; a < sann.length; a++)
2338                 {
2339                   AlignmentAnnotation newann = new AlignmentAnnotation(
2340                           sann[a]);
2341                   sequences[i].addAlignmentAnnotation(newann);
2342                   newann.padAnnotation(avwidth);
2343                   alview[avnum].addAnnotation(newann); // annotation was
2344                   // duplicated earlier
2345                   // TODO JAL-1145 graphGroups are not updated for sequence
2346                   // annotation added to several views. This may cause
2347                   // strangeness
2348                   alview[avnum].setAnnotationIndex(newann, a);
2349                 }
2350               }
2351             }
2352           }
2353           buildSortByAnnotationScoresMenu();
2354         }
2355         viewport.firePropertyChange("alignment", null,
2356                 alignment.getSequences());
2357         if (alignPanels != null)
2358         {
2359           for (AlignmentPanel ap : alignPanels)
2360           {
2361             ap.validateAnnotationDimensions(false);
2362           }
2363         }
2364         else
2365         {
2366           alignPanel.validateAnnotationDimensions(false);
2367         }
2368
2369       }
2370       else
2371       {
2372         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2373                 DEFAULT_HEIGHT);
2374         String newtitle = new String("Copied sequences");
2375
2376         if (Desktop.jalviewClipboard != null
2377                 && Desktop.jalviewClipboard[2] != null)
2378         {
2379           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2380           af.viewport.setHiddenColumns(hc);
2381         }
2382
2383         // >>>This is a fix for the moment, until a better solution is
2384         // found!!<<<
2385         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2386                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2387                         .getFeatureRenderer());
2388
2389         // TODO: maintain provenance of an alignment, rather than just make the
2390         // title a concatenation of operations.
2391         if (!externalPaste)
2392         {
2393           if (title.startsWith("Copied sequences"))
2394           {
2395             newtitle = title;
2396           }
2397           else
2398           {
2399             newtitle = newtitle.concat("- from " + title);
2400           }
2401         }
2402         else
2403         {
2404           newtitle = new String("Pasted sequences");
2405         }
2406
2407         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2408                 DEFAULT_HEIGHT);
2409
2410       }
2411
2412     } catch (Exception ex)
2413     {
2414       ex.printStackTrace();
2415       System.out.println("Exception whilst pasting: " + ex);
2416       // could be anything being pasted in here
2417     }
2418
2419   }
2420
2421   @Override
2422   protected void expand_newalign(ActionEvent e)
2423   {
2424     try
2425     {
2426       AlignmentI alignment = AlignmentUtils
2427               .expandContext(getViewport().getAlignment(), -1);
2428       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2429               DEFAULT_HEIGHT);
2430       String newtitle = new String("Flanking alignment");
2431
2432       if (Desktop.jalviewClipboard != null
2433               && Desktop.jalviewClipboard[2] != null)
2434       {
2435         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2436         af.viewport.setHiddenColumns(hc);
2437       }
2438
2439       // >>>This is a fix for the moment, until a better solution is
2440       // found!!<<<
2441       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2442               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2443                       .getFeatureRenderer());
2444
2445       // TODO: maintain provenance of an alignment, rather than just make the
2446       // title a concatenation of operations.
2447       {
2448         if (title.startsWith("Copied sequences"))
2449         {
2450           newtitle = title;
2451         }
2452         else
2453         {
2454           newtitle = newtitle.concat("- from " + title);
2455         }
2456       }
2457
2458       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2459
2460     } catch (Exception ex)
2461     {
2462       ex.printStackTrace();
2463       System.out.println("Exception whilst pasting: " + ex);
2464       // could be anything being pasted in here
2465     } catch (OutOfMemoryError oom)
2466     {
2467       new OOMWarning("Viewing flanking region of alignment", oom);
2468     }
2469   }
2470
2471   /**
2472    * Action Cut (delete and copy) the selected region
2473    */
2474   @Override
2475   protected void cut_actionPerformed()
2476   {
2477     copy_actionPerformed();
2478     delete_actionPerformed();
2479   }
2480
2481   /**
2482    * Performs menu option to Delete the currently selected region
2483    */
2484   @Override
2485   protected void delete_actionPerformed()
2486   {
2487
2488     SequenceGroup sg = viewport.getSelectionGroup();
2489     if (sg == null)
2490     {
2491       return;
2492     }
2493
2494     Callable okAction = () -> {
2495       SequenceI[] cut = sg.getSequences()
2496               .toArray(new SequenceI[sg.getSize()]);
2497
2498       addHistoryItem(new EditCommand(
2499               MessageManager.getString("label.cut_sequences"), Action.CUT,
2500               cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2501               viewport.getAlignment()));
2502
2503       viewport.setSelectionGroup(null);
2504       viewport.sendSelection();
2505       viewport.getAlignment().deleteGroup(sg);
2506
2507       viewport.firePropertyChange("alignment", null,
2508               viewport.getAlignment().getSequences());
2509       if (viewport.getAlignment().getHeight() < 1)
2510       {
2511         try
2512         {
2513           AlignFrame.this.setClosed(true);
2514         } catch (Exception ex)
2515         {
2516         }
2517       }
2518       return null;
2519     };
2520
2521     /*
2522      * If the cut affects all sequences, prompt for confirmation
2523      */
2524     boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2525             .getHeight();
2526     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2527             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2528     if (wholeHeight && wholeWidth)
2529     {
2530       JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2531       dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2532       Object[] options = new Object[] {
2533           MessageManager.getString("action.ok"),
2534           MessageManager.getString("action.cancel") };
2535       dialog.showDialog(MessageManager.getString("warn.delete_all"),
2536               MessageManager.getString("label.delete_all"),
2537               JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2538               options, options[0]);
2539     }
2540     else
2541     {
2542       try
2543       {
2544         okAction.call();
2545       } catch (Exception e)
2546       {
2547         e.printStackTrace();
2548       }
2549     }
2550   }
2551
2552   /**
2553    * DOCUMENT ME!
2554    * 
2555    * @param e
2556    *          DOCUMENT ME!
2557    */
2558   @Override
2559   protected void deleteGroups_actionPerformed(ActionEvent e)
2560   {
2561     if (avc.deleteGroups())
2562     {
2563       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2564       alignPanel.updateAnnotation();
2565       alignPanel.paintAlignment(true, true);
2566     }
2567   }
2568
2569   /**
2570    * DOCUMENT ME!
2571    * 
2572    * @param e
2573    *          DOCUMENT ME!
2574    */
2575   @Override
2576   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2577   {
2578     SequenceGroup sg = new SequenceGroup(
2579             viewport.getAlignment().getSequences());
2580
2581     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2582     viewport.setSelectionGroup(sg);
2583     viewport.isSelectionGroupChanged(true);
2584     viewport.sendSelection();
2585     // JAL-2034 - should delegate to
2586     // alignPanel to decide if overview needs
2587     // updating.
2588     alignPanel.paintAlignment(false, false);
2589     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2590   }
2591
2592   /**
2593    * DOCUMENT ME!
2594    * 
2595    * @param e
2596    *          DOCUMENT ME!
2597    */
2598   @Override
2599   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2600   {
2601     if (viewport.cursorMode)
2602     {
2603       alignPanel.getSeqPanel().keyboardNo1 = null;
2604       alignPanel.getSeqPanel().keyboardNo2 = null;
2605     }
2606     viewport.setSelectionGroup(null);
2607     viewport.getColumnSelection().clear();
2608     viewport.setSearchResults(null);
2609     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2610     // JAL-2034 - should delegate to
2611     // alignPanel to decide if overview needs
2612     // updating.
2613     alignPanel.paintAlignment(false, false);
2614     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2615     viewport.sendSelection();
2616   }
2617
2618   /**
2619    * DOCUMENT ME!
2620    * 
2621    * @param e
2622    *          DOCUMENT ME!
2623    */
2624   @Override
2625   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2626   {
2627     SequenceGroup sg = viewport.getSelectionGroup();
2628
2629     if (sg == null)
2630     {
2631       selectAllSequenceMenuItem_actionPerformed(null);
2632
2633       return;
2634     }
2635
2636     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2637     {
2638       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2639     }
2640     // JAL-2034 - should delegate to
2641     // alignPanel to decide if overview needs
2642     // updating.
2643
2644     alignPanel.paintAlignment(true, false);
2645     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2646     viewport.sendSelection();
2647   }
2648
2649   @Override
2650   public void invertColSel_actionPerformed(ActionEvent e)
2651   {
2652     viewport.invertColumnSelection();
2653     alignPanel.paintAlignment(true, false);
2654     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2655     viewport.sendSelection();
2656   }
2657
2658   /**
2659    * DOCUMENT ME!
2660    * 
2661    * @param e
2662    *          DOCUMENT ME!
2663    */
2664   @Override
2665   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2666   {
2667     trimAlignment(true);
2668   }
2669
2670   /**
2671    * DOCUMENT ME!
2672    * 
2673    * @param e
2674    *          DOCUMENT ME!
2675    */
2676   @Override
2677   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2678   {
2679     trimAlignment(false);
2680   }
2681
2682   void trimAlignment(boolean trimLeft)
2683   {
2684     ColumnSelection colSel = viewport.getColumnSelection();
2685     int column;
2686
2687     if (!colSel.isEmpty())
2688     {
2689       if (trimLeft)
2690       {
2691         column = colSel.getMin();
2692       }
2693       else
2694       {
2695         column = colSel.getMax();
2696       }
2697
2698       SequenceI[] seqs;
2699       if (viewport.getSelectionGroup() != null)
2700       {
2701         seqs = viewport.getSelectionGroup()
2702                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2703       }
2704       else
2705       {
2706         seqs = viewport.getAlignment().getSequencesArray();
2707       }
2708
2709       TrimRegionCommand trimRegion;
2710       if (trimLeft)
2711       {
2712         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2713                 column, viewport.getAlignment());
2714         viewport.getRanges().setStartRes(0);
2715       }
2716       else
2717       {
2718         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2719                 column, viewport.getAlignment());
2720       }
2721
2722       setStatus(MessageManager.formatMessage("label.removed_columns",
2723               new String[]
2724               { Integer.valueOf(trimRegion.getSize()).toString() }));
2725
2726       addHistoryItem(trimRegion);
2727
2728       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2729       {
2730         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2731                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2732         {
2733           viewport.getAlignment().deleteGroup(sg);
2734         }
2735       }
2736
2737       viewport.firePropertyChange("alignment", null,
2738               viewport.getAlignment().getSequences());
2739     }
2740   }
2741
2742   /**
2743    * DOCUMENT ME!
2744    * 
2745    * @param e
2746    *          DOCUMENT ME!
2747    */
2748   @Override
2749   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2750   {
2751     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2752
2753     SequenceI[] seqs;
2754     if (viewport.getSelectionGroup() != null)
2755     {
2756       seqs = viewport.getSelectionGroup()
2757               .getSequencesAsArray(viewport.getHiddenRepSequences());
2758       start = viewport.getSelectionGroup().getStartRes();
2759       end = viewport.getSelectionGroup().getEndRes();
2760     }
2761     else
2762     {
2763       seqs = viewport.getAlignment().getSequencesArray();
2764     }
2765
2766     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2767             "Remove Gapped Columns", seqs, start, end,
2768             viewport.getAlignment());
2769
2770     addHistoryItem(removeGapCols);
2771
2772     setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2773             new Object[]
2774             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2775
2776     // This is to maintain viewport position on first residue
2777     // of first sequence
2778     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2779     ViewportRanges ranges = viewport.getRanges();
2780     int startRes = seq.findPosition(ranges.getStartRes());
2781     // ShiftList shifts;
2782     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2783     // edit.alColumnChanges=shifts.getInverse();
2784     // if (viewport.hasHiddenColumns)
2785     // viewport.getColumnSelection().compensateForEdits(shifts);
2786     ranges.setStartRes(seq.findIndex(startRes) - 1);
2787     viewport.firePropertyChange("alignment", null,
2788             viewport.getAlignment().getSequences());
2789
2790   }
2791
2792   /**
2793    * DOCUMENT ME!
2794    * 
2795    * @param e
2796    *          DOCUMENT ME!
2797    */
2798   @Override
2799   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2800   {
2801     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2802
2803     SequenceI[] seqs;
2804     if (viewport.getSelectionGroup() != null)
2805     {
2806       seqs = viewport.getSelectionGroup()
2807               .getSequencesAsArray(viewport.getHiddenRepSequences());
2808       start = viewport.getSelectionGroup().getStartRes();
2809       end = viewport.getSelectionGroup().getEndRes();
2810     }
2811     else
2812     {
2813       seqs = viewport.getAlignment().getSequencesArray();
2814     }
2815
2816     // This is to maintain viewport position on first residue
2817     // of first sequence
2818     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2819     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2820
2821     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2822             viewport.getAlignment()));
2823
2824     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2825
2826     viewport.firePropertyChange("alignment", null,
2827             viewport.getAlignment().getSequences());
2828
2829   }
2830
2831   /**
2832    * DOCUMENT ME!
2833    * 
2834    * @param e
2835    *          DOCUMENT ME!
2836    */
2837   @Override
2838   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2839   {
2840     viewport.setPadGaps(padGapsMenuitem.isSelected());
2841     viewport.firePropertyChange("alignment", null,
2842             viewport.getAlignment().getSequences());
2843   }
2844
2845   /**
2846    * Opens a Finder dialog
2847    * 
2848    * @param e
2849    */
2850   @Override
2851   public void findMenuItem_actionPerformed(ActionEvent e)
2852   {
2853     new Finder(alignPanel, false, null);
2854   }
2855
2856   /**
2857    * Create a new view of the current alignment.
2858    */
2859   @Override
2860   public void newView_actionPerformed(ActionEvent e)
2861   {
2862     newView(null, true);
2863   }
2864
2865   /**
2866    * Creates and shows a new view of the current alignment.
2867    * 
2868    * @param viewTitle
2869    *          title of newly created view; if null, one will be generated
2870    * @param copyAnnotation
2871    *          if true then duplicate all annnotation, groups and settings
2872    * @return new alignment panel, already displayed.
2873    */
2874   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2875   {
2876     /*
2877      * Create a new AlignmentPanel (with its own, new Viewport)
2878      */
2879     AlignmentPanel newap = new jalview.project.Jalview2XML()
2880             .copyAlignPanel(alignPanel);
2881     if (!copyAnnotation)
2882     {
2883       /*
2884        * remove all groups and annotation except for the automatic stuff
2885        */
2886       newap.av.getAlignment().deleteAllGroups();
2887       newap.av.getAlignment().deleteAllAnnotations(false);
2888     }
2889
2890     newap.av.setGatherViewsHere(false);
2891
2892     if (viewport.getViewName() == null)
2893     {
2894       viewport.setViewName(
2895               MessageManager.getString("label.view_name_original"));
2896     }
2897
2898     /*
2899      * Views share the same edits undo and redo stacks
2900      */
2901     newap.av.setHistoryList(viewport.getHistoryList());
2902     newap.av.setRedoList(viewport.getRedoList());
2903
2904     /*
2905      * copy any visualisation settings that are not saved in the project
2906      */
2907     newap.av.setColourAppliesToAllGroups(
2908             viewport.getColourAppliesToAllGroups());
2909
2910     /*
2911      * Views share the same mappings; need to deregister any new mappings
2912      * created by copyAlignPanel, and register the new reference to the shared
2913      * mappings
2914      */
2915     newap.av.replaceMappings(viewport.getAlignment());
2916
2917     /*
2918      * start up cDNA consensus (if applicable) now mappings are in place
2919      */
2920     if (newap.av.initComplementConsensus())
2921     {
2922       newap.refresh(true); // adjust layout of annotations
2923     }
2924
2925     newap.av.setViewName(getNewViewName(viewTitle));
2926
2927     addAlignmentPanel(newap, true);
2928     newap.alignmentChanged();
2929
2930     if (alignPanels.size() == 2)
2931     {
2932       viewport.setGatherViewsHere(true);
2933     }
2934     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2935
2936     return newap;
2937   }
2938
2939   /**
2940    * Make a new name for the view, ensuring it is unique within the current
2941    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2942    * these now use viewId. Unique view names are still desirable for usability.)
2943    * 
2944    * @param viewTitle
2945    * @return
2946    */
2947   protected String getNewViewName(String viewTitle)
2948   {
2949     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2950     boolean addFirstIndex = false;
2951     if (viewTitle == null || viewTitle.trim().length() == 0)
2952     {
2953       viewTitle = MessageManager.getString("action.view");
2954       addFirstIndex = true;
2955     }
2956     else
2957     {
2958       index = 1;// we count from 1 if given a specific name
2959     }
2960     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2961
2962     List<Component> comps = PaintRefresher.components
2963             .get(viewport.getSequenceSetId());
2964
2965     List<String> existingNames = getExistingViewNames(comps);
2966
2967     while (existingNames.contains(newViewName))
2968     {
2969       newViewName = viewTitle + " " + (++index);
2970     }
2971     return newViewName;
2972   }
2973
2974   /**
2975    * Returns a list of distinct view names found in the given list of
2976    * components. View names are held on the viewport of an AlignmentPanel.
2977    * 
2978    * @param comps
2979    * @return
2980    */
2981   protected List<String> getExistingViewNames(List<Component> comps)
2982   {
2983     List<String> existingNames = new ArrayList<>();
2984     for (Component comp : comps)
2985     {
2986       if (comp instanceof AlignmentPanel)
2987       {
2988         AlignmentPanel ap = (AlignmentPanel) comp;
2989         if (!existingNames.contains(ap.av.getViewName()))
2990         {
2991           existingNames.add(ap.av.getViewName());
2992         }
2993       }
2994     }
2995     return existingNames;
2996   }
2997
2998   /**
2999    * Explode tabbed views into separate windows.
3000    */
3001   @Override
3002   public void expandViews_actionPerformed(ActionEvent e)
3003   {
3004     Desktop.explodeViews(this);
3005   }
3006
3007   /**
3008    * Gather views in separate windows back into a tabbed presentation.
3009    */
3010   @Override
3011   public void gatherViews_actionPerformed(ActionEvent e)
3012   {
3013     Desktop.instance.gatherViews(this);
3014   }
3015
3016   /**
3017    * DOCUMENT ME!
3018    * 
3019    * @param e
3020    *          DOCUMENT ME!
3021    */
3022   @Override
3023   public void font_actionPerformed(ActionEvent e)
3024   {
3025     new FontChooser(alignPanel);
3026   }
3027
3028   /**
3029    * DOCUMENT ME!
3030    * 
3031    * @param e
3032    *          DOCUMENT ME!
3033    */
3034   @Override
3035   protected void seqLimit_actionPerformed(ActionEvent e)
3036   {
3037     viewport.setShowJVSuffix(seqLimits.isSelected());
3038
3039     alignPanel.getIdPanel().getIdCanvas()
3040             .setPreferredSize(alignPanel.calculateIdWidth());
3041     alignPanel.paintAlignment(true, false);
3042   }
3043
3044   @Override
3045   public void idRightAlign_actionPerformed(ActionEvent e)
3046   {
3047     viewport.setRightAlignIds(idRightAlign.isSelected());
3048     alignPanel.paintAlignment(false, false);
3049   }
3050
3051   @Override
3052   public void centreColumnLabels_actionPerformed(ActionEvent e)
3053   {
3054     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3055     alignPanel.paintAlignment(false, false);
3056   }
3057
3058   /*
3059    * (non-Javadoc)
3060    * 
3061    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3062    */
3063   @Override
3064   protected void followHighlight_actionPerformed()
3065   {
3066     /*
3067      * Set the 'follow' flag on the Viewport (and scroll to position if now
3068      * true).
3069      */
3070     final boolean state = this.followHighlightMenuItem.getState();
3071     viewport.setFollowHighlight(state);
3072     if (state)
3073     {
3074       alignPanel.scrollToPosition(viewport.getSearchResults());
3075     }
3076   }
3077
3078   /**
3079    * DOCUMENT ME!
3080    * 
3081    * @param e
3082    *          DOCUMENT ME!
3083    */
3084   @Override
3085   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3086   {
3087     viewport.setColourText(colourTextMenuItem.isSelected());
3088     alignPanel.paintAlignment(false, false);
3089   }
3090
3091   /**
3092    * DOCUMENT ME!
3093    * 
3094    * @param e
3095    *          DOCUMENT ME!
3096    */
3097   @Override
3098   public void wrapMenuItem_actionPerformed(ActionEvent e)
3099   {
3100     scaleAbove.setVisible(wrapMenuItem.isSelected());
3101     scaleLeft.setVisible(wrapMenuItem.isSelected());
3102     scaleRight.setVisible(wrapMenuItem.isSelected());
3103     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3104     alignPanel.updateLayout();
3105   }
3106
3107   @Override
3108   public void showAllSeqs_actionPerformed(ActionEvent e)
3109   {
3110     viewport.showAllHiddenSeqs();
3111   }
3112
3113   @Override
3114   public void showAllColumns_actionPerformed(ActionEvent e)
3115   {
3116     viewport.showAllHiddenColumns();
3117     alignPanel.paintAlignment(true, true);
3118     viewport.sendSelection();
3119   }
3120
3121   @Override
3122   public void hideSelSequences_actionPerformed(ActionEvent e)
3123   {
3124     viewport.hideAllSelectedSeqs();
3125   }
3126
3127   /**
3128    * called by key handler and the hide all/show all menu items
3129    * 
3130    * @param toggleSeqs
3131    * @param toggleCols
3132    */
3133   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3134   {
3135
3136     boolean hide = false;
3137     SequenceGroup sg = viewport.getSelectionGroup();
3138     if (!toggleSeqs && !toggleCols)
3139     {
3140       // Hide everything by the current selection - this is a hack - we do the
3141       // invert and then hide
3142       // first check that there will be visible columns after the invert.
3143       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3144               && sg.getStartRes() <= sg.getEndRes()))
3145       {
3146         // now invert the sequence set, if required - empty selection implies
3147         // that no hiding is required.
3148         if (sg != null)
3149         {
3150           invertSequenceMenuItem_actionPerformed(null);
3151           sg = viewport.getSelectionGroup();
3152           toggleSeqs = true;
3153
3154         }
3155         viewport.expandColSelection(sg, true);
3156         // finally invert the column selection and get the new sequence
3157         // selection.
3158         invertColSel_actionPerformed(null);
3159         toggleCols = true;
3160       }
3161     }
3162
3163     if (toggleSeqs)
3164     {
3165       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3166       {
3167         hideSelSequences_actionPerformed(null);
3168         hide = true;
3169       }
3170       else if (!(toggleCols && viewport.hasSelectedColumns()))
3171       {
3172         showAllSeqs_actionPerformed(null);
3173       }
3174     }
3175
3176     if (toggleCols)
3177     {
3178       if (viewport.hasSelectedColumns())
3179       {
3180         hideSelColumns_actionPerformed(null);
3181         if (!toggleSeqs)
3182         {
3183           viewport.setSelectionGroup(sg);
3184         }
3185       }
3186       else if (!hide)
3187       {
3188         showAllColumns_actionPerformed(null);
3189       }
3190     }
3191   }
3192
3193   /*
3194    * (non-Javadoc)
3195    * 
3196    * @see
3197    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3198    * event.ActionEvent)
3199    */
3200   @Override
3201   public void hideAllButSelection_actionPerformed(ActionEvent e)
3202   {
3203     toggleHiddenRegions(false, false);
3204     viewport.sendSelection();
3205   }
3206
3207   /*
3208    * (non-Javadoc)
3209    * 
3210    * @see
3211    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3212    * .ActionEvent)
3213    */
3214   @Override
3215   public void hideAllSelection_actionPerformed(ActionEvent e)
3216   {
3217     SequenceGroup sg = viewport.getSelectionGroup();
3218     viewport.expandColSelection(sg, false);
3219     viewport.hideAllSelectedSeqs();
3220     viewport.hideSelectedColumns();
3221     alignPanel.updateLayout();
3222     alignPanel.paintAlignment(true, true);
3223     viewport.sendSelection();
3224   }
3225
3226   /*
3227    * (non-Javadoc)
3228    * 
3229    * @see
3230    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3231    * ActionEvent)
3232    */
3233   @Override
3234   public void showAllhidden_actionPerformed(ActionEvent e)
3235   {
3236     viewport.showAllHiddenColumns();
3237     viewport.showAllHiddenSeqs();
3238     alignPanel.paintAlignment(true, true);
3239     viewport.sendSelection();
3240   }
3241
3242   @Override
3243   public void hideSelColumns_actionPerformed(ActionEvent e)
3244   {
3245     viewport.hideSelectedColumns();
3246     alignPanel.updateLayout();
3247     alignPanel.paintAlignment(true, true);
3248     viewport.sendSelection();
3249   }
3250
3251   @Override
3252   public void hiddenMarkers_actionPerformed(ActionEvent e)
3253   {
3254     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3255     repaint();
3256   }
3257
3258   /**
3259    * DOCUMENT ME!
3260    * 
3261    * @param e
3262    *          DOCUMENT ME!
3263    */
3264   @Override
3265   protected void scaleAbove_actionPerformed(ActionEvent e)
3266   {
3267     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3268     alignPanel.updateLayout();
3269     alignPanel.paintAlignment(true, false);
3270   }
3271
3272   /**
3273    * DOCUMENT ME!
3274    * 
3275    * @param e
3276    *          DOCUMENT ME!
3277    */
3278   @Override
3279   protected void scaleLeft_actionPerformed(ActionEvent e)
3280   {
3281     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3282     alignPanel.updateLayout();
3283     alignPanel.paintAlignment(true, false);
3284   }
3285
3286   /**
3287    * DOCUMENT ME!
3288    * 
3289    * @param e
3290    *          DOCUMENT ME!
3291    */
3292   @Override
3293   protected void scaleRight_actionPerformed(ActionEvent e)
3294   {
3295     viewport.setScaleRightWrapped(scaleRight.isSelected());
3296     alignPanel.updateLayout();
3297     alignPanel.paintAlignment(true, false);
3298   }
3299
3300   /**
3301    * DOCUMENT ME!
3302    * 
3303    * @param e
3304    *          DOCUMENT ME!
3305    */
3306   @Override
3307   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3308   {
3309     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3310     alignPanel.paintAlignment(false, false);
3311   }
3312
3313   /**
3314    * DOCUMENT ME!
3315    * 
3316    * @param e
3317    *          DOCUMENT ME!
3318    */
3319   @Override
3320   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3321   {
3322     viewport.setShowText(viewTextMenuItem.isSelected());
3323     alignPanel.paintAlignment(false, false);
3324   }
3325
3326   /**
3327    * DOCUMENT ME!
3328    * 
3329    * @param e
3330    *          DOCUMENT ME!
3331    */
3332   @Override
3333   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3334   {
3335     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3336     alignPanel.paintAlignment(false, false);
3337   }
3338
3339   public FeatureSettings featureSettings;
3340
3341   @Override
3342   public FeatureSettingsControllerI getFeatureSettingsUI()
3343   {
3344     return featureSettings;
3345   }
3346
3347   @Override
3348   public void featureSettings_actionPerformed(ActionEvent e)
3349   {
3350     showFeatureSettingsUI();
3351   }
3352
3353   @Override
3354   public FeatureSettingsControllerI showFeatureSettingsUI()
3355   {
3356     if (featureSettings != null)
3357     {
3358       featureSettings.closeOldSettings();
3359       featureSettings = null;
3360     }
3361     if (!showSeqFeatures.isSelected())
3362     {
3363       // make sure features are actually displayed
3364       showSeqFeatures.setSelected(true);
3365       showSeqFeatures_actionPerformed(null);
3366     }
3367     featureSettings = new FeatureSettings(this);
3368     return featureSettings;
3369   }
3370
3371   /**
3372    * Set or clear 'Show Sequence Features'
3373    * 
3374    * @param evt
3375    *          DOCUMENT ME!
3376    */
3377   @Override
3378   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3379   {
3380     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3381     alignPanel.paintAlignment(true, true);
3382   }
3383
3384   /**
3385    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3386    * the annotations panel as a whole.
3387    * 
3388    * The options to show/hide all annotations should be enabled when the panel
3389    * is shown, and disabled when the panel is hidden.
3390    * 
3391    * @param e
3392    */
3393   @Override
3394   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3395   {
3396     final boolean setVisible = annotationPanelMenuItem.isSelected();
3397     viewport.setShowAnnotation(setVisible);
3398     this.showAllSeqAnnotations.setEnabled(setVisible);
3399     this.hideAllSeqAnnotations.setEnabled(setVisible);
3400     this.showAllAlAnnotations.setEnabled(setVisible);
3401     this.hideAllAlAnnotations.setEnabled(setVisible);
3402     alignPanel.updateLayout();
3403   }
3404
3405   @Override
3406   public void alignmentProperties()
3407   {
3408     JComponent pane;
3409     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3410
3411             .formatAsHtml();
3412     String content = MessageManager.formatMessage("label.html_content",
3413             new Object[]
3414             { contents.toString() });
3415     contents = null;
3416
3417     if (Platform.isJS())
3418     {
3419       JLabel textLabel = new JLabel();
3420       textLabel.setText(content);
3421       textLabel.setBackground(Color.WHITE);
3422
3423       pane = new JPanel(new BorderLayout());
3424       ((JPanel) pane).setOpaque(true);
3425       pane.setBackground(Color.WHITE);
3426       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3427     }
3428     else
3429     /**
3430      * Java only
3431      * 
3432      * @j2sIgnore
3433      */
3434     {
3435       JEditorPane editPane = new JEditorPane("text/html", "");
3436       editPane.setEditable(false);
3437       editPane.setText(content);
3438       pane = editPane;
3439     }
3440
3441     JInternalFrame frame = new JInternalFrame();
3442
3443     frame.getContentPane().add(new JScrollPane(pane));
3444
3445     Desktop.addInternalFrame(frame, MessageManager
3446             .formatMessage("label.alignment_properties", new Object[]
3447             { getTitle() }), 500, 400);
3448   }
3449
3450   /**
3451    * Opens an Overview panel for the alignment, unless one is open already
3452    * 
3453    * @param e
3454    */
3455   @Override
3456   public void overviewMenuItem_actionPerformed(ActionEvent e)
3457   {
3458     boolean showHiddenRegions = Cache
3459             .getDefault(Preferences.SHOW_OV_HIDDEN_AT_START, false);
3460     openOverviewPanel(showHiddenRegions);
3461   }
3462
3463   public OverviewPanel openOverviewPanel(boolean showHidden)
3464   {
3465     if (alignPanel.overviewPanel != null)
3466     {
3467       return alignPanel.overviewPanel;
3468     }
3469     JInternalFrame frame = new JInternalFrame();
3470     final OverviewPanel overview = new OverviewPanel(alignPanel, frame,
3471             showHidden);
3472     frame.setContentPane(overview);
3473     Desktop.addInternalFrame(frame, "", true, frame.getWidth(),
3474             frame.getHeight(), true, true);
3475     frame.setFrameIcon(null);
3476     frame.pack();
3477     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3478     final AlignmentPanel thePanel = this.alignPanel;
3479     frame.addInternalFrameListener(
3480             new javax.swing.event.InternalFrameAdapter()
3481             {
3482               @Override
3483               public void internalFrameClosed(
3484                       javax.swing.event.InternalFrameEvent evt)
3485               {
3486                 overview.dispose();
3487                 thePanel.setOverviewPanel(null);
3488               }
3489             });
3490     if (getKeyListeners().length > 0)
3491     {
3492       frame.addKeyListener(getKeyListeners()[0]);
3493     }
3494
3495     alignPanel.setOverviewPanel(overview);
3496     alignPanel.setOverviewTitle(this);
3497
3498     return overview;
3499   }
3500
3501   @Override
3502   public void textColour_actionPerformed()
3503   {
3504     new TextColourChooser().chooseColour(alignPanel, null);
3505   }
3506
3507   /*
3508    * public void covariationColour_actionPerformed() {
3509    * changeColour(new
3510    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3511    * ()[0])); }
3512    */
3513   @Override
3514   public void annotationColour_actionPerformed()
3515   {
3516     new AnnotationColourChooser(viewport, alignPanel);
3517   }
3518
3519   @Override
3520   public void annotationColumn_actionPerformed(ActionEvent e)
3521   {
3522     new AnnotationColumnChooser(viewport, alignPanel);
3523   }
3524
3525   /**
3526    * Action on the user checking or unchecking the option to apply the selected
3527    * colour scheme to all groups. If unchecked, groups may have their own
3528    * independent colour schemes.
3529    * 
3530    * @param selected
3531    */
3532   @Override
3533   public void applyToAllGroups_actionPerformed(boolean selected)
3534   {
3535     viewport.setColourAppliesToAllGroups(selected);
3536   }
3537
3538   /**
3539    * Action on user selecting a colour from the colour menu
3540    * 
3541    * @param name
3542    *          the name (not the menu item label!) of the colour scheme
3543    */
3544   @Override
3545   public void changeColour_actionPerformed(String name)
3546   {
3547     /*
3548      * 'User Defined' opens a panel to configure or load a
3549      * user-defined colour scheme
3550      */
3551     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3552     {
3553       new UserDefinedColours(alignPanel);
3554       return;
3555     }
3556
3557     /*
3558      * otherwise set the chosen colour scheme (or null for 'None')
3559      */
3560     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3561             viewport, viewport.getAlignment(),
3562             viewport.getHiddenRepSequences());
3563     changeColour(cs);
3564   }
3565
3566   /**
3567    * Actions on setting or changing the alignment colour scheme
3568    * 
3569    * @param cs
3570    */
3571   @Override
3572   public void changeColour(ColourSchemeI cs)
3573   {
3574     // TODO: pull up to controller method
3575     ColourMenuHelper.setColourSelected(colourMenu, cs);
3576
3577     viewport.setGlobalColourScheme(cs);
3578
3579     alignPanel.paintAlignment(true, true);
3580   }
3581
3582   /**
3583    * Show the PID threshold slider panel
3584    */
3585   @Override
3586   protected void modifyPID_actionPerformed()
3587   {
3588     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3589             alignPanel.getViewName());
3590     SliderPanel.showPIDSlider();
3591   }
3592
3593   /**
3594    * Show the Conservation slider panel
3595    */
3596   @Override
3597   protected void modifyConservation_actionPerformed()
3598   {
3599     SliderPanel.setConservationSlider(alignPanel,
3600             viewport.getResidueShading(), alignPanel.getViewName());
3601     SliderPanel.showConservationSlider();
3602   }
3603
3604   /**
3605    * Action on selecting or deselecting (Colour) By Conservation
3606    */
3607   @Override
3608   public void conservationMenuItem_actionPerformed(boolean selected)
3609   {
3610     modifyConservation.setEnabled(selected);
3611     viewport.setConservationSelected(selected);
3612     viewport.getResidueShading().setConservationApplied(selected);
3613
3614     changeColour(viewport.getGlobalColourScheme());
3615     if (selected)
3616     {
3617       modifyConservation_actionPerformed();
3618     }
3619     else
3620     {
3621       SliderPanel.hideConservationSlider();
3622     }
3623   }
3624
3625   /**
3626    * Action on selecting or deselecting (Colour) Above PID Threshold
3627    */
3628   @Override
3629   public void abovePIDThreshold_actionPerformed(boolean selected)
3630   {
3631     modifyPID.setEnabled(selected);
3632     viewport.setAbovePIDThreshold(selected);
3633     if (!selected)
3634     {
3635       viewport.getResidueShading().setThreshold(0,
3636               viewport.isIgnoreGapsConsensus());
3637     }
3638
3639     changeColour(viewport.getGlobalColourScheme());
3640     if (selected)
3641     {
3642       modifyPID_actionPerformed();
3643     }
3644     else
3645     {
3646       SliderPanel.hidePIDSlider();
3647     }
3648   }
3649
3650   /**
3651    * DOCUMENT ME!
3652    * 
3653    * @param e
3654    *          DOCUMENT ME!
3655    */
3656   @Override
3657   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3658   {
3659     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3660     AlignmentSorter.sortByPID(viewport.getAlignment(),
3661             viewport.getAlignment().getSequenceAt(0));
3662     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3663             viewport.getAlignment()));
3664     alignPanel.paintAlignment(true, false);
3665   }
3666
3667   /**
3668    * DOCUMENT ME!
3669    * 
3670    * @param e
3671    *          DOCUMENT ME!
3672    */
3673   @Override
3674   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3675   {
3676     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3677     AlignmentSorter.sortByID(viewport.getAlignment());
3678     addHistoryItem(
3679             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3680     alignPanel.paintAlignment(true, false);
3681   }
3682
3683   /**
3684    * DOCUMENT ME!
3685    * 
3686    * @param e
3687    *          DOCUMENT ME!
3688    */
3689   @Override
3690   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3691   {
3692     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3693     AlignmentSorter.sortByLength(viewport.getAlignment());
3694     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3695             viewport.getAlignment()));
3696     alignPanel.paintAlignment(true, false);
3697   }
3698
3699   /**
3700    * DOCUMENT ME!
3701    * 
3702    * @param e
3703    *          DOCUMENT ME!
3704    */
3705   @Override
3706   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3707   {
3708     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3709     AlignmentSorter.sortByGroup(viewport.getAlignment());
3710     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3711             viewport.getAlignment()));
3712
3713     alignPanel.paintAlignment(true, false);
3714   }
3715
3716   /**
3717    * DOCUMENT ME!
3718    * 
3719    * @param e
3720    *          DOCUMENT ME!
3721    */
3722   @Override
3723   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3724   {
3725     new RedundancyPanel(alignPanel, this);
3726   }
3727
3728   /**
3729    * DOCUMENT ME!
3730    * 
3731    * @param e
3732    *          DOCUMENT ME!
3733    */
3734   @Override
3735   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3736   {
3737     if ((viewport.getSelectionGroup() == null)
3738             || (viewport.getSelectionGroup().getSize() < 2))
3739     {
3740       JvOptionPane.showInternalMessageDialog(this,
3741               MessageManager.getString(
3742                       "label.you_must_select_least_two_sequences"),
3743               MessageManager.getString("label.invalid_selection"),
3744               JvOptionPane.WARNING_MESSAGE);
3745     }
3746     else
3747     {
3748       JInternalFrame frame = new JInternalFrame();
3749       frame.setContentPane(new PairwiseAlignPanel(viewport));
3750       Desktop.addInternalFrame(frame,
3751               MessageManager.getString("action.pairwise_alignment"), 600,
3752               500);
3753     }
3754   }
3755
3756   @Override
3757   public void autoCalculate_actionPerformed(ActionEvent e)
3758   {
3759     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3760     if (viewport.autoCalculateConsensus)
3761     {
3762       viewport.firePropertyChange("alignment", null,
3763               viewport.getAlignment().getSequences());
3764     }
3765   }
3766
3767   @Override
3768   public void sortByTreeOption_actionPerformed(ActionEvent e)
3769   {
3770     viewport.sortByTree = sortByTree.isSelected();
3771   }
3772
3773   @Override
3774   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3775   {
3776     viewport.followSelection = listenToViewSelections.isSelected();
3777   }
3778
3779   /**
3780    * Constructs a tree panel and adds it to the desktop
3781    * 
3782    * @param type
3783    *          tree type (NJ or AV)
3784    * @param modelName
3785    *          name of score model used to compute the tree
3786    * @param options
3787    *          parameters for the distance or similarity calculation
3788    */
3789   void newTreePanel(String type, String modelName,
3790           SimilarityParamsI options)
3791   {
3792     String frameTitle = "";
3793     TreePanel tp;
3794
3795     boolean onSelection = false;
3796     if (viewport.getSelectionGroup() != null
3797             && viewport.getSelectionGroup().getSize() > 0)
3798     {
3799       SequenceGroup sg = viewport.getSelectionGroup();
3800
3801       /* Decide if the selection is a column region */
3802       for (SequenceI _s : sg.getSequences())
3803       {
3804         if (_s.getLength() < sg.getEndRes())
3805         {
3806           JvOptionPane.showMessageDialog(Desktop.desktop,
3807                   MessageManager.getString(
3808                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3809                   MessageManager.getString(
3810                           "label.sequences_selection_not_aligned"),
3811                   JvOptionPane.WARNING_MESSAGE);
3812
3813           return;
3814         }
3815       }
3816       onSelection = true;
3817     }
3818     else
3819     {
3820       if (viewport.getAlignment().getHeight() < 2)
3821       {
3822         return;
3823       }
3824     }
3825
3826     tp = new TreePanel(alignPanel, type, modelName, options);
3827     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3828
3829     frameTitle += " from ";
3830
3831     if (viewport.getViewName() != null)
3832     {
3833       frameTitle += viewport.getViewName() + " of ";
3834     }
3835
3836     frameTitle += this.title;
3837
3838     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3839   }
3840
3841   /**
3842    * DOCUMENT ME!
3843    * 
3844    * @param title
3845    *          DOCUMENT ME!
3846    * @param order
3847    *          DOCUMENT ME!
3848    */
3849   public void addSortByOrderMenuItem(String title,
3850           final AlignmentOrder order)
3851   {
3852     final JMenuItem item = new JMenuItem(MessageManager
3853             .formatMessage("action.by_title_param", new Object[]
3854             { title }));
3855     sort.add(item);
3856     item.addActionListener(new java.awt.event.ActionListener()
3857     {
3858       @Override
3859       public void actionPerformed(ActionEvent e)
3860       {
3861         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3862
3863         // TODO: JBPNote - have to map order entries to curent SequenceI
3864         // pointers
3865         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3866
3867         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3868                 viewport.getAlignment()));
3869
3870         alignPanel.paintAlignment(true, false);
3871       }
3872     });
3873   }
3874
3875   /**
3876    * Add a new sort by annotation score menu item
3877    * 
3878    * @param sort
3879    *          the menu to add the option to
3880    * @param scoreLabel
3881    *          the label used to retrieve scores for each sequence on the
3882    *          alignment
3883    */
3884   public void addSortByAnnotScoreMenuItem(JMenu sort,
3885           final String scoreLabel)
3886   {
3887     final JMenuItem item = new JMenuItem(scoreLabel);
3888     sort.add(item);
3889     item.addActionListener(new java.awt.event.ActionListener()
3890     {
3891       @Override
3892       public void actionPerformed(ActionEvent e)
3893       {
3894         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3895         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3896                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3897         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3898                 viewport.getAlignment()));
3899         alignPanel.paintAlignment(true, false);
3900       }
3901     });
3902   }
3903
3904   /**
3905    * last hash for alignment's annotation array - used to minimise cost of
3906    * rebuild.
3907    */
3908   protected int _annotationScoreVectorHash;
3909
3910   /**
3911    * search the alignment and rebuild the sort by annotation score submenu the
3912    * last alignment annotation vector hash is stored to minimize cost of
3913    * rebuilding in subsequence calls.
3914    * 
3915    */
3916   @Override
3917   public void buildSortByAnnotationScoresMenu()
3918   {
3919     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3920     {
3921       return;
3922     }
3923
3924     if (viewport.getAlignment().getAlignmentAnnotation()
3925             .hashCode() != _annotationScoreVectorHash)
3926     {
3927       sortByAnnotScore.removeAll();
3928       // almost certainly a quicker way to do this - but we keep it simple
3929       Hashtable<String, String> scoreSorts = new Hashtable<>();
3930       AlignmentAnnotation aann[];
3931       for (SequenceI sqa : viewport.getAlignment().getSequences())
3932       {
3933         aann = sqa.getAnnotation();
3934         for (int i = 0; aann != null && i < aann.length; i++)
3935         {
3936           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3937           {
3938             scoreSorts.put(aann[i].label, aann[i].label);
3939           }
3940         }
3941       }
3942       Enumeration<String> labels = scoreSorts.keys();
3943       while (labels.hasMoreElements())
3944       {
3945         addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3946       }
3947       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3948       scoreSorts.clear();
3949
3950       _annotationScoreVectorHash = viewport.getAlignment()
3951               .getAlignmentAnnotation().hashCode();
3952     }
3953   }
3954
3955   /**
3956    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3957    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3958    * call. Listeners are added to remove the menu item when the treePanel is
3959    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3960    * modified.
3961    */
3962   @Override
3963   public void buildTreeSortMenu()
3964   {
3965     sortByTreeMenu.removeAll();
3966
3967     List<Component> comps = PaintRefresher.components
3968             .get(viewport.getSequenceSetId());
3969     List<TreePanel> treePanels = new ArrayList<>();
3970     for (Component comp : comps)
3971     {
3972       if (comp instanceof TreePanel)
3973       {
3974         treePanels.add((TreePanel) comp);
3975       }
3976     }
3977
3978     if (treePanels.size() < 1)
3979     {
3980       sortByTreeMenu.setVisible(false);
3981       return;
3982     }
3983
3984     sortByTreeMenu.setVisible(true);
3985
3986     for (final TreePanel tp : treePanels)
3987     {
3988       final JMenuItem item = new JMenuItem(tp.getTitle());
3989       item.addActionListener(new java.awt.event.ActionListener()
3990       {
3991         @Override
3992         public void actionPerformed(ActionEvent e)
3993         {
3994           tp.sortByTree_actionPerformed();
3995           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3996
3997         }
3998       });
3999
4000       sortByTreeMenu.add(item);
4001     }
4002   }
4003
4004   public boolean sortBy(AlignmentOrder alorder, String undoname)
4005   {
4006     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4007     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4008     if (undoname != null)
4009     {
4010       addHistoryItem(new OrderCommand(undoname, oldOrder,
4011               viewport.getAlignment()));
4012     }
4013     alignPanel.paintAlignment(true, false);
4014     return true;
4015   }
4016
4017   /**
4018    * Work out whether the whole set of sequences or just the selected set will
4019    * be submitted for multiple alignment.
4020    * 
4021    */
4022   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4023   {
4024     // Now, check we have enough sequences
4025     AlignmentView msa = null;
4026
4027     if ((viewport.getSelectionGroup() != null)
4028             && (viewport.getSelectionGroup().getSize() > 1))
4029     {
4030       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4031       // some common interface!
4032       /*
4033        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4034        * SequenceI[sz = seqs.getSize(false)];
4035        * 
4036        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4037        * seqs.getSequenceAt(i); }
4038        */
4039       msa = viewport.getAlignmentView(true);
4040     }
4041     else if (viewport.getSelectionGroup() != null
4042             && viewport.getSelectionGroup().getSize() == 1)
4043     {
4044       int option = JvOptionPane.showConfirmDialog(this,
4045               MessageManager.getString("warn.oneseq_msainput_selection"),
4046               MessageManager.getString("label.invalid_selection"),
4047               JvOptionPane.OK_CANCEL_OPTION);
4048       if (option == JvOptionPane.OK_OPTION)
4049       {
4050         msa = viewport.getAlignmentView(false);
4051       }
4052     }
4053     else
4054     {
4055       msa = viewport.getAlignmentView(false);
4056     }
4057     return msa;
4058   }
4059
4060   /**
4061    * Decides what is submitted to a secondary structure prediction service: the
4062    * first sequence in the alignment, or in the current selection, or, if the
4063    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4064    * region or the whole alignment. (where the first sequence in the set is the
4065    * one that the prediction will be for).
4066    */
4067   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4068   {
4069     AlignmentView seqs = null;
4070
4071     if ((viewport.getSelectionGroup() != null)
4072             && (viewport.getSelectionGroup().getSize() > 0))
4073     {
4074       seqs = viewport.getAlignmentView(true);
4075     }
4076     else
4077     {
4078       seqs = viewport.getAlignmentView(false);
4079     }
4080     // limit sequences - JBPNote in future - could spawn multiple prediction
4081     // jobs
4082     // TODO: viewport.getAlignment().isAligned is a global state - the local
4083     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4084     if (!viewport.getAlignment().isAligned(false))
4085     {
4086       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4087       // TODO: if seqs.getSequences().length>1 then should really have warned
4088       // user!
4089
4090     }
4091     return seqs;
4092   }
4093
4094   /**
4095    * DOCUMENT ME!
4096    * 
4097    * @param e
4098    *          DOCUMENT ME!
4099    */
4100   @Override
4101   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4102   {
4103     // Pick the tree file
4104     JalviewFileChooser chooser = new JalviewFileChooser(
4105             Cache.getProperty("LAST_DIRECTORY"));
4106     chooser.setFileView(new JalviewFileView());
4107     chooser.setDialogTitle(
4108             MessageManager.getString("label.select_newick_like_tree_file"));
4109     chooser.setToolTipText(
4110             MessageManager.getString("label.load_tree_file"));
4111
4112     chooser.setResponseHandler(0, () -> {
4113       String filePath = chooser.getSelectedFile().getPath();
4114       Cache.setProperty("LAST_DIRECTORY", filePath);
4115       NewickFile fin = null;
4116       try
4117       {
4118         fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4119                 DataSourceType.FILE));
4120         viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4121       } catch (Exception ex)
4122       {
4123         JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4124                 MessageManager.getString("label.problem_reading_tree_file"),
4125                 JvOptionPane.WARNING_MESSAGE);
4126         ex.printStackTrace();
4127       }
4128       if (fin != null && fin.hasWarningMessage())
4129       {
4130         JvOptionPane.showMessageDialog(Desktop.desktop,
4131                 fin.getWarningMessage(),
4132                 MessageManager
4133                         .getString("label.possible_problem_with_tree_file"),
4134                 JvOptionPane.WARNING_MESSAGE);
4135       }
4136       return null;
4137     });
4138     chooser.showOpenDialog(this);
4139   }
4140
4141   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4142   {
4143     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4144   }
4145
4146   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4147           int h, int x, int y)
4148   {
4149     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4150   }
4151
4152   /**
4153    * Add a treeviewer for the tree extracted from a Newick file object to the
4154    * current alignment view
4155    * 
4156    * @param nf
4157    *          the tree
4158    * @param title
4159    *          tree viewer title
4160    * @param input
4161    *          Associated alignment input data (or null)
4162    * @param w
4163    *          width
4164    * @param h
4165    *          height
4166    * @param x
4167    *          position
4168    * @param y
4169    *          position
4170    * @return TreePanel handle
4171    */
4172   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4173           AlignmentView input, int w, int h, int x, int y)
4174   {
4175     TreePanel tp = null;
4176
4177     try
4178     {
4179       nf.parse();
4180
4181       if (nf.getTree() != null)
4182       {
4183         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4184
4185         tp.setSize(w, h);
4186
4187         if (x > 0 && y > 0)
4188         {
4189           tp.setLocation(x, y);
4190         }
4191
4192         Desktop.addInternalFrame(tp, treeTitle, w, h);
4193       }
4194     } catch (Exception ex)
4195     {
4196       ex.printStackTrace();
4197     }
4198
4199     return tp;
4200   }
4201
4202   public void showContactMapTree(AlignmentAnnotation aa,
4203           PAEContactMatrix cm)
4204   {
4205     int x = 4, y = 5;
4206     int w = 400, h = 500;
4207
4208     try
4209     {
4210       NewickFile fin = new NewickFile(
4211               new FileParse(cm.getNewick(), DataSourceType.PASTE));
4212       String title = "PAE Matrix Tree for "
4213               + cm.getReferenceSeq().getDisplayId(false);
4214
4215       showColumnWiseTree(fin, aa, title, w, h, x, y);
4216     } catch (Throwable xx)
4217     {
4218       Console.error("Unexpected exception showing tree for contact matrix",
4219               xx);
4220     }
4221   }
4222
4223   public TreePanel showColumnWiseTree(NewickFile nf, AlignmentAnnotation aa,
4224           String treeTitle, int w, int h, int x, int y)
4225   {
4226     try
4227     {
4228       nf.parse();
4229       if (nf.getTree() == null)
4230       {
4231         return null;
4232       }
4233       TreePanel tp = new TreePanel(alignPanel, nf, aa, title);
4234
4235       tp.setSize(w, h);
4236
4237       if (x > 0 && y > 0)
4238       {
4239         tp.setLocation(x, y);
4240       }
4241
4242       Desktop.addInternalFrame(tp, title, w, h);
4243       return tp;
4244     } catch (Throwable xx)
4245     {
4246       Console.error("Unexpected exception showing tree for contact matrix",
4247               xx);
4248     }
4249     return null;
4250   }
4251
4252   private boolean buildingMenu = false;
4253
4254   /**
4255    * Generates menu items and listener event actions for web service clients
4256    * 
4257    */
4258   public void BuildWebServiceMenu()
4259   {
4260     while (buildingMenu)
4261     {
4262       try
4263       {
4264         System.err.println("Waiting for building menu to finish.");
4265         Thread.sleep(10);
4266       } catch (Exception e)
4267       {
4268       }
4269     }
4270     final AlignFrame me = this;
4271     buildingMenu = true;
4272     new Thread(new Runnable()
4273     {
4274       @Override
4275       public void run()
4276       {
4277         final List<JMenuItem> legacyItems = new ArrayList<>();
4278         try
4279         {
4280           // System.err.println("Building ws menu again "
4281           // + Thread.currentThread());
4282           // TODO: add support for context dependent disabling of services based
4283           // on
4284           // alignment and current selection
4285           // TODO: add additional serviceHandle parameter to specify abstract
4286           // handler
4287           // class independently of AbstractName
4288           // TODO: add in rediscovery GUI function to restart discoverer
4289           // TODO: group services by location as well as function and/or
4290           // introduce
4291           // object broker mechanism.
4292           final Vector<JMenu> wsmenu = new Vector<>();
4293           final IProgressIndicator af = me;
4294
4295           /*
4296            * do not i18n these strings - they are hard-coded in class
4297            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4298            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4299            */
4300           final JMenu msawsmenu = new JMenu("Alignment");
4301           final JMenu secstrmenu = new JMenu(
4302                   "Secondary Structure Prediction");
4303           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4304           final JMenu analymenu = new JMenu("Analysis");
4305           final JMenu dismenu = new JMenu("Protein Disorder");
4306           // JAL-940 - only show secondary structure prediction services from
4307           // the legacy server
4308           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4309               // &&
4310           Discoverer.services != null && (Discoverer.services.size() > 0))
4311           {
4312             // TODO: refactor to allow list of AbstractName/Handler bindings to
4313             // be
4314             // stored or retrieved from elsewhere
4315             // No MSAWS used any more:
4316             // Vector msaws = null; // (Vector)
4317             // Discoverer.services.get("MsaWS");
4318             Vector<ServiceHandle> secstrpr = Discoverer.services
4319                     .get("SecStrPred");
4320             if (secstrpr != null)
4321             {
4322               // Add any secondary structure prediction services
4323               for (int i = 0, j = secstrpr.size(); i < j; i++)
4324               {
4325                 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4326                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4327                         .getServiceClient(sh);
4328                 int p = secstrmenu.getItemCount();
4329                 impl.attachWSMenuEntry(secstrmenu, me);
4330                 int q = secstrmenu.getItemCount();
4331                 for (int litm = p; litm < q; litm++)
4332                 {
4333                   legacyItems.add(secstrmenu.getItem(litm));
4334                 }
4335               }
4336             }
4337           }
4338
4339           // Add all submenus in the order they should appear on the web
4340           // services menu
4341           wsmenu.add(msawsmenu);
4342           wsmenu.add(secstrmenu);
4343           wsmenu.add(dismenu);
4344           wsmenu.add(analymenu);
4345           // No search services yet
4346           // wsmenu.add(seqsrchmenu);
4347
4348           javax.swing.SwingUtilities.invokeLater(new Runnable()
4349           {
4350             @Override
4351             public void run()
4352             {
4353               try
4354               {
4355                 webService.removeAll();
4356                 // first, add discovered services onto the webservices menu
4357                 if (wsmenu.size() > 0)
4358                 {
4359                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4360                   {
4361                     webService.add(wsmenu.get(i));
4362                   }
4363                 }
4364                 else
4365                 {
4366                   webService.add(me.webServiceNoServices);
4367                 }
4368                 // TODO: move into separate menu builder class.
4369                 {
4370                   // logic for 2.11.1.4 is
4371                   // always look to see if there is a discover. if there isn't
4372                   // we can't show any Jws2 services
4373                   // if there are services available, show them - regardless of
4374                   // the 'show JWS2 preference'
4375                   // if the discoverer is running then say so
4376                   // otherwise offer to trigger discovery if 'show JWS2' is not
4377                   // enabled
4378                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4379                   if (jws2servs != null)
4380                   {
4381                     if (jws2servs.hasServices())
4382                     {
4383                       jws2servs.attachWSMenuEntry(webService, me);
4384                       for (Jws2Instance sv : jws2servs.getServices())
4385                       {
4386                         if (sv.description.toLowerCase(Locale.ROOT)
4387                                 .contains("jpred"))
4388                         {
4389                           for (JMenuItem jmi : legacyItems)
4390                           {
4391                             jmi.setVisible(false);
4392                           }
4393                         }
4394                       }
4395                     }
4396
4397                     if (jws2servs.isRunning())
4398                     {
4399                       JMenuItem tm = new JMenuItem(
4400                               "Still discovering JABA Services");
4401                       tm.setEnabled(false);
4402                       webService.add(tm);
4403                     }
4404                     else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4405                     {
4406                       JMenuItem enableJws2 = new JMenuItem(
4407                               "Discover Web Services");
4408                       enableJws2.setToolTipText(
4409                               "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4410                       enableJws2.setEnabled(true);
4411                       enableJws2.addActionListener(new ActionListener()
4412                       {
4413
4414                         @Override
4415                         public void actionPerformed(ActionEvent e)
4416                         {
4417                           // start service discoverer, but ignore preference
4418                           Desktop.instance.startServiceDiscovery(false,
4419                                   true);
4420                         }
4421                       });
4422                       webService.add(enableJws2);
4423                     }
4424                   }
4425                 }
4426                 build_urlServiceMenu(me.webService);
4427                 build_fetchdbmenu(webService);
4428                 for (JMenu item : wsmenu)
4429                 {
4430                   if (item.getItemCount() == 0)
4431                   {
4432                     item.setEnabled(false);
4433                   }
4434                   else
4435                   {
4436                     item.setEnabled(true);
4437                   }
4438                 }
4439               } catch (Exception e)
4440               {
4441                 Console.debug(
4442                         "Exception during web service menu building process.",
4443                         e);
4444               }
4445             }
4446           });
4447         } catch (Exception e)
4448         {
4449         }
4450         buildingMenu = false;
4451       }
4452     }).start();
4453
4454   }
4455
4456   /**
4457    * construct any groupURL type service menu entries.
4458    * 
4459    * @param webService
4460    */
4461   protected void build_urlServiceMenu(JMenu webService)
4462   {
4463     // TODO: remove this code when 2.7 is released
4464     // DEBUG - alignmentView
4465     /*
4466      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4467      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4468      * 
4469      * @Override public void actionPerformed(ActionEvent e) {
4470      * jalview.datamodel.AlignmentView
4471      * .testSelectionViews(af.viewport.getAlignment(),
4472      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4473      * 
4474      * }); webService.add(testAlView);
4475      */
4476     // TODO: refactor to RestClient discoverer and merge menu entries for
4477     // rest-style services with other types of analysis/calculation service
4478     // SHmmr test client - still being implemented.
4479     // DEBUG - alignmentView
4480
4481     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4482             .getRestClients())
4483     {
4484       client.attachWSMenuEntry(
4485               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4486               this);
4487     }
4488   }
4489
4490   /**
4491    * Searches the alignment sequences for xRefs and builds the Show
4492    * Cross-References menu (formerly called Show Products), with database
4493    * sources for which cross-references are found (protein sources for a
4494    * nucleotide alignment and vice versa)
4495    * 
4496    * @return true if Show Cross-references menu should be enabled
4497    */
4498   public boolean canShowProducts()
4499   {
4500     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4501     AlignmentI dataset = viewport.getAlignment().getDataset();
4502
4503     showProducts.removeAll();
4504     final boolean dna = viewport.getAlignment().isNucleotide();
4505
4506     if (seqs == null || seqs.length == 0)
4507     {
4508       // nothing to see here.
4509       return false;
4510     }
4511
4512     boolean showp = false;
4513     try
4514     {
4515       List<String> ptypes = new CrossRef(seqs, dataset)
4516               .findXrefSourcesForSequences(dna);
4517
4518       for (final String source : ptypes)
4519       {
4520         showp = true;
4521         final AlignFrame af = this;
4522         JMenuItem xtype = new JMenuItem(source);
4523         xtype.addActionListener(new ActionListener()
4524         {
4525           @Override
4526           public void actionPerformed(ActionEvent e)
4527           {
4528             showProductsFor(af.viewport.getSequenceSelection(), dna,
4529                     source);
4530           }
4531         });
4532         showProducts.add(xtype);
4533       }
4534       showProducts.setVisible(showp);
4535       showProducts.setEnabled(showp);
4536     } catch (Exception e)
4537     {
4538       Console.warn(
4539               "canShowProducts threw an exception - please report to help@jalview.org",
4540               e);
4541       return false;
4542     }
4543     return showp;
4544   }
4545
4546   /**
4547    * Finds and displays cross-references for the selected sequences (protein
4548    * products for nucleotide sequences, dna coding sequences for peptides).
4549    * 
4550    * @param sel
4551    *          the sequences to show cross-references for
4552    * @param dna
4553    *          true if from a nucleotide alignment (so showing proteins)
4554    * @param source
4555    *          the database to show cross-references for
4556    */
4557   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4558           final String source)
4559   {
4560     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4561             .start();
4562   }
4563
4564   /**
4565    * Construct and display a new frame containing the translation of this
4566    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4567    */
4568   @Override
4569   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4570   {
4571     AlignmentI al = null;
4572     try
4573     {
4574       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4575
4576       al = dna.translateCdna(codeTable);
4577     } catch (Exception ex)
4578     {
4579       Console.error("Exception during translation. Please report this !",
4580               ex);
4581       final String msg = MessageManager.getString(
4582               "label.error_when_translating_sequences_submit_bug_report");
4583       final String errorTitle = MessageManager
4584               .getString("label.implementation_error")
4585               + MessageManager.getString("label.translation_failed");
4586       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4587               JvOptionPane.ERROR_MESSAGE);
4588       return;
4589     }
4590     if (al == null || al.getHeight() == 0)
4591     {
4592       final String msg = MessageManager.getString(
4593               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4594       final String errorTitle = MessageManager
4595               .getString("label.translation_failed");
4596       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4597               JvOptionPane.WARNING_MESSAGE);
4598     }
4599     else
4600     {
4601       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4602       af.setFileFormat(this.currentFileFormat);
4603       final String newTitle = MessageManager
4604               .formatMessage("label.translation_of_params", new Object[]
4605               { this.getTitle(), codeTable.getId() });
4606       af.setTitle(newTitle);
4607       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4608       {
4609         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4610         viewport.openSplitFrame(af, new Alignment(seqs));
4611       }
4612       else
4613       {
4614         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4615                 DEFAULT_HEIGHT);
4616       }
4617     }
4618   }
4619
4620   /**
4621    * Set the file format
4622    * 
4623    * @param format
4624    */
4625   public void setFileFormat(FileFormatI format)
4626   {
4627     this.currentFileFormat = format;
4628   }
4629
4630   /**
4631    * Try to load a features file onto the alignment.
4632    * 
4633    * @param file
4634    *          contents or path to retrieve file or a File object
4635    * @param sourceType
4636    *          access mode of file (see jalview.io.AlignFile)
4637    * @return true if features file was parsed correctly.
4638    */
4639   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4640   {
4641     // BH 2018
4642     return avc.parseFeaturesFile(file, sourceType,
4643             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4644
4645   }
4646
4647   @Override
4648   public void refreshFeatureUI(boolean enableIfNecessary)
4649   {
4650     // note - currently this is only still here rather than in the controller
4651     // because of the featureSettings hard reference that is yet to be
4652     // abstracted
4653     if (enableIfNecessary)
4654     {
4655       viewport.setShowSequenceFeatures(true);
4656       showSeqFeatures.setSelected(true);
4657     }
4658
4659   }
4660
4661   @Override
4662   public void dragEnter(DropTargetDragEvent evt)
4663   {
4664   }
4665
4666   @Override
4667   public void dragExit(DropTargetEvent evt)
4668   {
4669   }
4670
4671   @Override
4672   public void dragOver(DropTargetDragEvent evt)
4673   {
4674   }
4675
4676   @Override
4677   public void dropActionChanged(DropTargetDragEvent evt)
4678   {
4679   }
4680
4681   @Override
4682   public void drop(DropTargetDropEvent evt)
4683   {
4684     // JAL-1552 - acceptDrop required before getTransferable call for
4685     // Java's Transferable for native dnd
4686     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4687     Transferable t = evt.getTransferable();
4688
4689     final AlignFrame thisaf = this;
4690     final List<Object> files = new ArrayList<>();
4691     List<DataSourceType> protocols = new ArrayList<>();
4692
4693     try
4694     {
4695       Desktop.transferFromDropTarget(files, protocols, evt, t);
4696     } catch (Exception e)
4697     {
4698       e.printStackTrace();
4699     }
4700     if (files != null)
4701     {
4702       new Thread(new Runnable()
4703       {
4704         @Override
4705         public void run()
4706         {
4707           try
4708           {
4709             // check to see if any of these files have names matching sequences
4710             // in
4711             // the alignment
4712             SequenceIdMatcher idm = new SequenceIdMatcher(
4713                     viewport.getAlignment().getSequencesArray());
4714             /**
4715              * Object[] { String,SequenceI}
4716              */
4717             ArrayList<Object[]> filesmatched = new ArrayList<>();
4718             ArrayList<Object> filesnotmatched = new ArrayList<>();
4719             for (int i = 0; i < files.size(); i++)
4720             {
4721               // BH 2018
4722               Object file = files.get(i);
4723               String fileName = file.toString();
4724               String pdbfn = "";
4725               DataSourceType protocol = (file instanceof File
4726                       ? DataSourceType.FILE
4727                       : FormatAdapter.checkProtocol(fileName));
4728               if (protocol == DataSourceType.FILE)
4729               {
4730                 File fl;
4731                 if (file instanceof File)
4732                 {
4733                   fl = (File) file;
4734                   Platform.cacheFileData(fl);
4735                 }
4736                 else
4737                 {
4738                   fl = new File(fileName);
4739                 }
4740                 pdbfn = fl.getName();
4741               }
4742               else if (protocol == DataSourceType.URL)
4743               {
4744                 URL url = new URL(fileName);
4745                 pdbfn = url.getFile();
4746               }
4747               if (pdbfn.length() > 0)
4748               {
4749                 // attempt to find a match in the alignment
4750                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4751                 int l = 0, c = pdbfn.indexOf(".");
4752                 while (mtch == null && c != -1)
4753                 {
4754                   do
4755                   {
4756                     l = c;
4757                   } while ((c = pdbfn.indexOf(".", l)) > l);
4758                   if (l > -1)
4759                   {
4760                     pdbfn = pdbfn.substring(0, l);
4761                   }
4762                   mtch = idm.findAllIdMatches(pdbfn);
4763                 }
4764                 if (mtch != null)
4765                 {
4766                   FileFormatI type;
4767                   try
4768                   {
4769                     type = new IdentifyFile().identify(file, protocol);
4770                   } catch (Exception ex)
4771                   {
4772                     type = null;
4773                   }
4774                   if (type != null && type.isStructureFile())
4775                   {
4776                     filesmatched.add(new Object[] { file, protocol, mtch });
4777                     continue;
4778                   }
4779                 }
4780                 // File wasn't named like one of the sequences or wasn't a PDB
4781                 // file.
4782                 filesnotmatched.add(file);
4783               }
4784             }
4785             int assocfiles = 0;
4786             if (filesmatched.size() > 0)
4787             {
4788               boolean autoAssociate = Cache
4789                       .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4790               if (!autoAssociate)
4791               {
4792                 String msg = MessageManager.formatMessage(
4793                         "label.automatically_associate_structure_files_with_sequences_same_name",
4794                         new Object[]
4795                         { Integer.valueOf(filesmatched.size())
4796                                 .toString() });
4797                 String ttl = MessageManager.getString(
4798                         "label.automatically_associate_structure_files_by_name");
4799                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4800                         ttl, JvOptionPane.YES_NO_OPTION);
4801                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4802               }
4803               if (autoAssociate)
4804               {
4805                 for (Object[] fm : filesmatched)
4806                 {
4807                   // try and associate
4808                   // TODO: may want to set a standard ID naming formalism for
4809                   // associating PDB files which have no IDs.
4810                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4811                   {
4812                     PDBEntry pe = new AssociatePdbFileWithSeq()
4813                             .associatePdbWithSeq(fm[0].toString(),
4814                                     (DataSourceType) fm[1], toassoc, false,
4815                                     Desktop.instance);
4816                     if (pe != null)
4817                     {
4818                       System.err.println("Associated file : "
4819                               + (fm[0].toString()) + " with "
4820                               + toassoc.getDisplayId(true));
4821                       assocfiles++;
4822                     }
4823                   }
4824                   // TODO: do we need to update overview ? only if features are
4825                   // shown I guess
4826                   alignPanel.paintAlignment(true, false);
4827                 }
4828               }
4829               else
4830               {
4831                 /*
4832                  * add declined structures as sequences
4833                  */
4834                 for (Object[] o : filesmatched)
4835                 {
4836                   filesnotmatched.add(o[0]);
4837                 }
4838               }
4839             }
4840             if (filesnotmatched.size() > 0)
4841             {
4842               if (assocfiles > 0 && (Cache.getDefault(
4843                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4844                       || JvOptionPane.showConfirmDialog(thisaf,
4845                               "<html>" + MessageManager.formatMessage(
4846                                       "label.ignore_unmatched_dropped_files_info",
4847                                       new Object[]
4848                                       { Integer.valueOf(
4849                                               filesnotmatched.size())
4850                                               .toString() })
4851                                       + "</html>",
4852                               MessageManager.getString(
4853                                       "label.ignore_unmatched_dropped_files"),
4854                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4855               {
4856                 return;
4857               }
4858               for (Object fn : filesnotmatched)
4859               {
4860                 loadJalviewDataFile(fn, null, null, null);
4861               }
4862
4863             }
4864           } catch (Exception ex)
4865           {
4866             ex.printStackTrace();
4867           }
4868         }
4869       }).start();
4870     }
4871   }
4872
4873   /**
4874    * Attempt to load a "dropped" file or URL string, by testing in turn for
4875    * <ul>
4876    * <li>an Annotation file</li>
4877    * <li>a JNet file</li>
4878    * <li>a features file</li>
4879    * <li>else try to interpret as an alignment file</li>
4880    * </ul>
4881    * 
4882    * @param file
4883    *          either a filename or a URL string.
4884    */
4885   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4886           FileFormatI format, SequenceI assocSeq)
4887   {
4888     // BH 2018 was String file
4889     try
4890     {
4891       if (sourceType == null)
4892       {
4893         sourceType = FormatAdapter.checkProtocol(file);
4894       }
4895       // if the file isn't identified, or not positively identified as some
4896       // other filetype (PFAM is default unidentified alignment file type) then
4897       // try to parse as annotation.
4898       boolean isAnnotation = (format == null
4899               || FileFormat.Pfam.equals(format))
4900                       ? new AnnotationFile().annotateAlignmentView(viewport,
4901                               file, sourceType)
4902                       : false;
4903
4904       if (!isAnnotation)
4905       {
4906         // first see if its a T-COFFEE score file
4907         TCoffeeScoreFile tcf = null;
4908         try
4909         {
4910           tcf = new TCoffeeScoreFile(file, sourceType);
4911           if (tcf.isValid())
4912           {
4913             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4914             {
4915               buildColourMenu();
4916               changeColour(
4917                       new TCoffeeColourScheme(viewport.getAlignment()));
4918               isAnnotation = true;
4919               setStatus(MessageManager.getString(
4920                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4921             }
4922             else
4923             {
4924               // some problem - if no warning its probable that the ID matching
4925               // process didn't work
4926               JvOptionPane.showMessageDialog(Desktop.desktop,
4927                       tcf.getWarningMessage() == null
4928                               ? MessageManager.getString(
4929                                       "label.check_file_matches_sequence_ids_alignment")
4930                               : tcf.getWarningMessage(),
4931                       MessageManager.getString(
4932                               "label.problem_reading_tcoffee_score_file"),
4933                       JvOptionPane.WARNING_MESSAGE);
4934             }
4935           }
4936           else
4937           {
4938             tcf = null;
4939           }
4940         } catch (Exception x)
4941         {
4942           Console.debug(
4943                   "Exception when processing data source as T-COFFEE score file",
4944                   x);
4945           tcf = null;
4946         }
4947         if (tcf == null)
4948         {
4949           // try to see if its a JNet 'concise' style annotation file *before*
4950           // we
4951           // try to parse it as a features file
4952           if (format == null)
4953           {
4954             format = new IdentifyFile().identify(file, sourceType);
4955           }
4956           if (FileFormat.ScoreMatrix == format)
4957           {
4958             ScoreMatrixFile sm = new ScoreMatrixFile(
4959                     new FileParse(file, sourceType));
4960             sm.parse();
4961             // todo: i18n this message
4962             setStatus(MessageManager.formatMessage(
4963                     "label.successfully_loaded_matrix",
4964                     sm.getMatrixName()));
4965           }
4966           else if (FileFormat.Jnet.equals(format))
4967           {
4968             JPredFile predictions = new JPredFile(file, sourceType);
4969             new JnetAnnotationMaker();
4970             JnetAnnotationMaker.add_annotation(predictions,
4971                     viewport.getAlignment(), 0, false);
4972             viewport.getAlignment().setupJPredAlignment();
4973             isAnnotation = true;
4974           }
4975           // else if (IdentifyFile.FeaturesFile.equals(format))
4976           else if (FileFormat.Features.equals(format))
4977           {
4978             if (parseFeaturesFile(file, sourceType))
4979             {
4980               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4981               if (splitFrame != null)
4982               {
4983                 splitFrame.repaint();
4984               }
4985               else
4986               {
4987                 alignPanel.paintAlignment(true, true);
4988               }
4989             }
4990           }
4991           else
4992           {
4993             new FileLoader().LoadFile(viewport, file, sourceType, format);
4994           }
4995         }
4996       }
4997       if (isAnnotation)
4998       {
4999
5000         alignPanel.adjustAnnotationHeight();
5001         viewport.updateSequenceIdColours();
5002         buildSortByAnnotationScoresMenu();
5003         alignPanel.paintAlignment(true, true);
5004       }
5005     } catch (Exception ex)
5006     {
5007       ex.printStackTrace();
5008     } catch (OutOfMemoryError oom)
5009     {
5010       try
5011       {
5012         System.gc();
5013       } catch (Exception x)
5014       {
5015       }
5016       new OOMWarning(
5017               "loading data "
5018                       + (sourceType != null
5019                               ? (sourceType == DataSourceType.PASTE
5020                                       ? "from clipboard."
5021                                       : "using " + sourceType + " from "
5022                                               + file)
5023                               : ".")
5024                       + (format != null
5025                               ? "(parsing as '" + format + "' file)"
5026                               : ""),
5027               oom, Desktop.desktop);
5028     }
5029   }
5030
5031   /**
5032    * Method invoked by the ChangeListener on the tabbed pane, in other words
5033    * when a different tabbed pane is selected by the user or programmatically.
5034    */
5035   @Override
5036   public void tabSelectionChanged(int index)
5037   {
5038     if (index > -1)
5039     {
5040       /*
5041        * update current Overview window title (if there is one)
5042        * to add view name "Original" if necessary
5043        */
5044       alignPanel.setOverviewTitle(this);
5045
5046       /*
5047        * switch panels and set Overview title (if there is one
5048        * because it was opened automatically)
5049        */
5050       alignPanel = alignPanels.get(index);
5051       alignPanel.setOverviewTitle(this);
5052
5053       viewport = alignPanel.av;
5054       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5055       setMenusFromViewport(viewport);
5056       if (featureSettings != null && featureSettings.isOpen()
5057               && featureSettings.fr.getViewport() != viewport)
5058       {
5059         if (viewport.isShowSequenceFeatures())
5060         {
5061           // refresh the featureSettings to reflect UI change
5062           showFeatureSettingsUI();
5063         }
5064         else
5065         {
5066           // close feature settings for this view.
5067           featureSettings.close();
5068         }
5069       }
5070
5071     }
5072
5073     /*
5074      * 'focus' any colour slider that is open to the selected viewport
5075      */
5076     if (viewport.getConservationSelected())
5077     {
5078       SliderPanel.setConservationSlider(alignPanel,
5079               viewport.getResidueShading(), alignPanel.getViewName());
5080     }
5081     else
5082     {
5083       SliderPanel.hideConservationSlider();
5084     }
5085     if (viewport.getAbovePIDThreshold())
5086     {
5087       SliderPanel.setPIDSliderSource(alignPanel,
5088               viewport.getResidueShading(), alignPanel.getViewName());
5089     }
5090     else
5091     {
5092       SliderPanel.hidePIDSlider();
5093     }
5094
5095     /*
5096      * If there is a frame linked to this one in a SplitPane, switch it to the
5097      * same view tab index. No infinite recursion of calls should happen, since
5098      * tabSelectionChanged() should not get invoked on setting the selected
5099      * index to an unchanged value. Guard against setting an invalid index
5100      * before the new view peer tab has been created.
5101      */
5102     final AlignViewportI peer = viewport.getCodingComplement();
5103     if (peer != null)
5104     {
5105       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5106               .getAlignPanel().alignFrame;
5107       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5108       {
5109         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5110       }
5111     }
5112   }
5113
5114   /**
5115    * On right mouse click on view tab, prompt for and set new view name.
5116    */
5117   @Override
5118   public void tabbedPane_mousePressed(MouseEvent e)
5119   {
5120     if (e.isPopupTrigger())
5121     {
5122       String msg = MessageManager.getString("label.enter_view_name");
5123       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5124       String reply = JvOptionPane.showInputDialog(msg, ttl);
5125
5126       if (reply != null)
5127       {
5128         viewport.setViewName(reply);
5129         // TODO warn if reply is in getExistingViewNames()?
5130         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5131       }
5132     }
5133   }
5134
5135   public AlignViewport getCurrentView()
5136   {
5137     return viewport;
5138   }
5139
5140   /**
5141    * Open the dialog for regex description parsing.
5142    */
5143   @Override
5144   protected void extractScores_actionPerformed(ActionEvent e)
5145   {
5146     ParseProperties pp = new jalview.analysis.ParseProperties(
5147             viewport.getAlignment());
5148     // TODO: verify regex and introduce GUI dialog for version 2.5
5149     // if (pp.getScoresFromDescription("col", "score column ",
5150     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5151     // true)>0)
5152     if (pp.getScoresFromDescription("description column",
5153             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5154     {
5155       buildSortByAnnotationScoresMenu();
5156     }
5157   }
5158
5159   /*
5160    * (non-Javadoc)
5161    * 
5162    * @see
5163    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5164    * )
5165    */
5166   @Override
5167   protected void showDbRefs_actionPerformed(ActionEvent e)
5168   {
5169     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5170   }
5171
5172   /*
5173    * (non-Javadoc)
5174    * 
5175    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5176    * ActionEvent)
5177    */
5178   @Override
5179   protected void showNpFeats_actionPerformed(ActionEvent e)
5180   {
5181     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5182   }
5183
5184   /**
5185    * find the viewport amongst the tabs in this alignment frame and close that
5186    * tab
5187    * 
5188    * @param av
5189    */
5190   public boolean closeView(AlignViewportI av)
5191   {
5192     if (viewport == av)
5193     {
5194       this.closeMenuItem_actionPerformed(false);
5195       return true;
5196     }
5197     Component[] comp = tabbedPane.getComponents();
5198     for (int i = 0; comp != null && i < comp.length; i++)
5199     {
5200       if (comp[i] instanceof AlignmentPanel)
5201       {
5202         if (((AlignmentPanel) comp[i]).av == av)
5203         {
5204           // close the view.
5205           closeView((AlignmentPanel) comp[i]);
5206           return true;
5207         }
5208       }
5209     }
5210     return false;
5211   }
5212
5213   protected void build_fetchdbmenu(JMenu webService)
5214   {
5215     // Temporary hack - DBRef Fetcher always top level ws entry.
5216     // TODO We probably want to store a sequence database checklist in
5217     // preferences and have checkboxes.. rather than individual sources selected
5218     // here
5219     final JMenu rfetch = new JMenu(
5220             MessageManager.getString("action.fetch_db_references"));
5221     rfetch.setToolTipText(MessageManager.getString(
5222             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5223     webService.add(rfetch);
5224
5225     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5226             MessageManager.getString("option.trim_retrieved_seqs"));
5227     trimrs.setToolTipText(
5228             MessageManager.getString("label.trim_retrieved_sequences"));
5229     trimrs.setSelected(
5230             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5231     trimrs.addActionListener(new ActionListener()
5232     {
5233       @Override
5234       public void actionPerformed(ActionEvent e)
5235       {
5236         trimrs.setSelected(trimrs.isSelected());
5237         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5238                 Boolean.valueOf(trimrs.isSelected()).toString());
5239       }
5240     });
5241     rfetch.add(trimrs);
5242     JMenuItem fetchr = new JMenuItem(
5243             MessageManager.getString("label.standard_databases"));
5244     fetchr.setToolTipText(
5245             MessageManager.getString("label.fetch_embl_uniprot"));
5246     fetchr.addActionListener(new ActionListener()
5247     {
5248
5249       @Override
5250       public void actionPerformed(ActionEvent e)
5251       {
5252         new Thread(new Runnable()
5253         {
5254           @Override
5255           public void run()
5256           {
5257             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5258                     .getAlignment().isNucleotide();
5259             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5260                     alignPanel.av.getSequenceSelection(),
5261                     alignPanel.alignFrame, null,
5262                     alignPanel.alignFrame.featureSettings, isNucleotide);
5263             dbRefFetcher.addListener(new FetchFinishedListenerI()
5264             {
5265               @Override
5266               public void finished()
5267               {
5268
5269                 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5270                         .getFeatureSettingsModels())
5271                 {
5272
5273                   alignPanel.av.mergeFeaturesStyle(srcSettings);
5274                 }
5275                 AlignFrame.this.setMenusForViewport();
5276               }
5277             });
5278             dbRefFetcher.fetchDBRefs(false);
5279           }
5280         }).start();
5281
5282       }
5283
5284     });
5285     rfetch.add(fetchr);
5286     new Thread(new Runnable()
5287     {
5288       @Override
5289       public void run()
5290       {
5291         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5292                 .getSequenceFetcherSingleton();
5293         javax.swing.SwingUtilities.invokeLater(new Runnable()
5294         {
5295           @Override
5296           public void run()
5297           {
5298             String[] dbclasses = sf.getNonAlignmentSources();
5299             List<DbSourceProxy> otherdb;
5300             JMenu dfetch = new JMenu();
5301             JMenu ifetch = new JMenu();
5302             JMenuItem fetchr = null;
5303             int comp = 0, icomp = 0, mcomp = 15;
5304             String mname = null;
5305             int dbi = 0;
5306             for (String dbclass : dbclasses)
5307             {
5308               otherdb = sf.getSourceProxy(dbclass);
5309               // add a single entry for this class, or submenu allowing 'fetch
5310               // all' or pick one
5311               if (otherdb == null || otherdb.size() < 1)
5312               {
5313                 continue;
5314               }
5315               if (mname == null)
5316               {
5317                 mname = "From " + dbclass;
5318               }
5319               if (otherdb.size() == 1)
5320               {
5321                 final DbSourceProxy[] dassource = otherdb
5322                         .toArray(new DbSourceProxy[0]);
5323                 DbSourceProxy src = otherdb.get(0);
5324                 fetchr = new JMenuItem(src.getDbSource());
5325                 fetchr.addActionListener(new ActionListener()
5326                 {
5327
5328                   @Override
5329                   public void actionPerformed(ActionEvent e)
5330                   {
5331                     new Thread(new Runnable()
5332                     {
5333
5334                       @Override
5335                       public void run()
5336                       {
5337                         boolean isNucleotide = alignPanel.alignFrame
5338                                 .getViewport().getAlignment()
5339                                 .isNucleotide();
5340                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5341                                 alignPanel.av.getSequenceSelection(),
5342                                 alignPanel.alignFrame, dassource,
5343                                 alignPanel.alignFrame.featureSettings,
5344                                 isNucleotide);
5345                         dbRefFetcher
5346                                 .addListener(new FetchFinishedListenerI()
5347                                 {
5348                                   @Override
5349                                   public void finished()
5350                                   {
5351                                     FeatureSettingsModelI srcSettings = dassource[0]
5352                                             .getFeatureColourScheme();
5353                                     alignPanel.av.mergeFeaturesStyle(
5354                                             srcSettings);
5355                                     AlignFrame.this.setMenusForViewport();
5356                                   }
5357                                 });
5358                         dbRefFetcher.fetchDBRefs(false);
5359                       }
5360                     }).start();
5361                   }
5362
5363                 });
5364                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5365                         MessageManager.formatMessage(
5366                                 "label.fetch_retrieve_from", new Object[]
5367                                 { src.getDbName() })));
5368                 dfetch.add(fetchr);
5369                 comp++;
5370               }
5371               else
5372               {
5373                 final DbSourceProxy[] dassource = otherdb
5374                         .toArray(new DbSourceProxy[0]);
5375                 // fetch all entry
5376                 DbSourceProxy src = otherdb.get(0);
5377                 fetchr = new JMenuItem(MessageManager
5378                         .formatMessage("label.fetch_all_param", new Object[]
5379                         { src.getDbSource() }));
5380                 fetchr.addActionListener(new ActionListener()
5381                 {
5382                   @Override
5383                   public void actionPerformed(ActionEvent e)
5384                   {
5385                     new Thread(new Runnable()
5386                     {
5387
5388                       @Override
5389                       public void run()
5390                       {
5391                         boolean isNucleotide = alignPanel.alignFrame
5392                                 .getViewport().getAlignment()
5393                                 .isNucleotide();
5394                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5395                                 alignPanel.av.getSequenceSelection(),
5396                                 alignPanel.alignFrame, dassource,
5397                                 alignPanel.alignFrame.featureSettings,
5398                                 isNucleotide);
5399                         dbRefFetcher
5400                                 .addListener(new FetchFinishedListenerI()
5401                                 {
5402                                   @Override
5403                                   public void finished()
5404                                   {
5405                                     AlignFrame.this.setMenusForViewport();
5406                                   }
5407                                 });
5408                         dbRefFetcher.fetchDBRefs(false);
5409                       }
5410                     }).start();
5411                   }
5412                 });
5413
5414                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5415                         MessageManager.formatMessage(
5416                                 "label.fetch_retrieve_from_all_sources",
5417                                 new Object[]
5418                                 { Integer.valueOf(otherdb.size())
5419                                         .toString(),
5420                                     src.getDbSource(), src.getDbName() })));
5421                 dfetch.add(fetchr);
5422                 comp++;
5423                 // and then build the rest of the individual menus
5424                 ifetch = new JMenu(MessageManager.formatMessage(
5425                         "label.source_from_db_source", new Object[]
5426                         { src.getDbSource() }));
5427                 icomp = 0;
5428                 String imname = null;
5429                 int i = 0;
5430                 for (DbSourceProxy sproxy : otherdb)
5431                 {
5432                   String dbname = sproxy.getDbName();
5433                   String sname = dbname.length() > 5
5434                           ? dbname.substring(0, 5) + "..."
5435                           : dbname;
5436                   String msname = dbname.length() > 10
5437                           ? dbname.substring(0, 10) + "..."
5438                           : dbname;
5439                   if (imname == null)
5440                   {
5441                     imname = MessageManager
5442                             .formatMessage("label.from_msname", new Object[]
5443                             { sname });
5444                   }
5445                   fetchr = new JMenuItem(msname);
5446                   final DbSourceProxy[] dassrc = { sproxy };
5447                   fetchr.addActionListener(new ActionListener()
5448                   {
5449
5450                     @Override
5451                     public void actionPerformed(ActionEvent e)
5452                     {
5453                       new Thread(new Runnable()
5454                       {
5455
5456                         @Override
5457                         public void run()
5458                         {
5459                           boolean isNucleotide = alignPanel.alignFrame
5460                                   .getViewport().getAlignment()
5461                                   .isNucleotide();
5462                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5463                                   alignPanel.av.getSequenceSelection(),
5464                                   alignPanel.alignFrame, dassrc,
5465                                   alignPanel.alignFrame.featureSettings,
5466                                   isNucleotide);
5467                           dbRefFetcher
5468                                   .addListener(new FetchFinishedListenerI()
5469                                   {
5470                                     @Override
5471                                     public void finished()
5472                                     {
5473                                       AlignFrame.this.setMenusForViewport();
5474                                     }
5475                                   });
5476                           dbRefFetcher.fetchDBRefs(false);
5477                         }
5478                       }).start();
5479                     }
5480
5481                   });
5482                   fetchr.setToolTipText(
5483                           "<html>" + MessageManager.formatMessage(
5484                                   "label.fetch_retrieve_from", new Object[]
5485                                   { dbname }));
5486                   ifetch.add(fetchr);
5487                   ++i;
5488                   if (++icomp >= mcomp || i == (otherdb.size()))
5489                   {
5490                     ifetch.setText(MessageManager.formatMessage(
5491                             "label.source_to_target", imname, sname));
5492                     dfetch.add(ifetch);
5493                     ifetch = new JMenu();
5494                     imname = null;
5495                     icomp = 0;
5496                     comp++;
5497                   }
5498                 }
5499               }
5500               ++dbi;
5501               if (comp >= mcomp || dbi >= (dbclasses.length))
5502               {
5503                 dfetch.setText(MessageManager.formatMessage(
5504                         "label.source_to_target", mname, dbclass));
5505                 rfetch.add(dfetch);
5506                 dfetch = new JMenu();
5507                 mname = null;
5508                 comp = 0;
5509               }
5510             }
5511           }
5512         });
5513       }
5514     }).start();
5515
5516   }
5517
5518   /**
5519    * Left justify the whole alignment.
5520    */
5521   @Override
5522   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5523   {
5524     AlignmentI al = viewport.getAlignment();
5525     al.justify(false);
5526     viewport.firePropertyChange("alignment", null, al);
5527   }
5528
5529   /**
5530    * Right justify the whole alignment.
5531    */
5532   @Override
5533   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5534   {
5535     AlignmentI al = viewport.getAlignment();
5536     al.justify(true);
5537     viewport.firePropertyChange("alignment", null, al);
5538   }
5539
5540   @Override
5541   public void setShowSeqFeatures(boolean b)
5542   {
5543     showSeqFeatures.setSelected(b);
5544     viewport.setShowSequenceFeatures(b);
5545   }
5546
5547   /*
5548    * (non-Javadoc)
5549    * 
5550    * @see
5551    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5552    * awt.event.ActionEvent)
5553    */
5554   @Override
5555   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5556   {
5557     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5558     alignPanel.paintAlignment(false, false);
5559   }
5560
5561   /*
5562    * (non-Javadoc)
5563    * 
5564    * @see
5565    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5566    * .ActionEvent)
5567    */
5568   @Override
5569   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5570   {
5571     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5572     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5573
5574   }
5575
5576   /*
5577    * (non-Javadoc)
5578    * 
5579    * @see
5580    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5581    * .event.ActionEvent)
5582    */
5583   @Override
5584   protected void showGroupConservation_actionPerformed(ActionEvent e)
5585   {
5586     viewport.setShowGroupConservation(showGroupConservation.getState());
5587     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5588   }
5589
5590   /*
5591    * (non-Javadoc)
5592    * 
5593    * @see
5594    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5595    * .event.ActionEvent)
5596    */
5597   @Override
5598   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5599   {
5600     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5601     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5602   }
5603
5604   /*
5605    * (non-Javadoc)
5606    * 
5607    * @see
5608    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5609    * .event.ActionEvent)
5610    */
5611   @Override
5612   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5613   {
5614     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5615     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5616   }
5617
5618   @Override
5619   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5620   {
5621     showSequenceLogo.setState(true);
5622     viewport.setShowSequenceLogo(true);
5623     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5624     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5625   }
5626
5627   @Override
5628   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5629   {
5630     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5631   }
5632
5633   /*
5634    * (non-Javadoc)
5635    * 
5636    * @see
5637    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5638    * .event.ActionEvent)
5639    */
5640   @Override
5641   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5642   {
5643     if (avc.makeGroupsFromSelection())
5644     {
5645       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5646       alignPanel.updateAnnotation();
5647       alignPanel.paintAlignment(true,
5648               viewport.needToUpdateStructureViews());
5649     }
5650   }
5651
5652   public void clearAlignmentSeqRep()
5653   {
5654     // TODO refactor alignmentseqrep to controller
5655     if (viewport.getAlignment().hasSeqrep())
5656     {
5657       viewport.getAlignment().setSeqrep(null);
5658       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5659       alignPanel.updateAnnotation();
5660       alignPanel.paintAlignment(true, true);
5661     }
5662   }
5663
5664   @Override
5665   protected void createGroup_actionPerformed(ActionEvent e)
5666   {
5667     if (avc.createGroup())
5668     {
5669       if (applyAutoAnnotationSettings.isSelected())
5670       {
5671         alignPanel.updateAnnotation(true, false);
5672       }
5673       alignPanel.alignmentChanged();
5674     }
5675   }
5676
5677   @Override
5678   protected void unGroup_actionPerformed(ActionEvent e)
5679   {
5680     if (avc.unGroup())
5681     {
5682       alignPanel.alignmentChanged();
5683     }
5684   }
5685
5686   /**
5687    * make the given alignmentPanel the currently selected tab
5688    * 
5689    * @param alignmentPanel
5690    */
5691   public void setDisplayedView(AlignmentPanel alignmentPanel)
5692   {
5693     if (!viewport.getSequenceSetId()
5694             .equals(alignmentPanel.av.getSequenceSetId()))
5695     {
5696       throw new Error(MessageManager.getString(
5697               "error.implementation_error_cannot_show_view_alignment_frame"));
5698     }
5699     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5700             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5701     {
5702       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5703     }
5704   }
5705
5706   /**
5707    * Action on selection of menu options to Show or Hide annotations.
5708    * 
5709    * @param visible
5710    * @param forSequences
5711    *          update sequence-related annotations
5712    * @param forAlignment
5713    *          update non-sequence-related annotations
5714    */
5715   @Override
5716   public void setAnnotationsVisibility(boolean visible,
5717           boolean forSequences, boolean forAlignment)
5718   {
5719     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5720             .getAlignmentAnnotation();
5721     if (anns == null)
5722     {
5723       return;
5724     }
5725     for (AlignmentAnnotation aa : anns)
5726     {
5727       /*
5728        * don't display non-positional annotations on an alignment
5729        */
5730       if (aa.annotations == null)
5731       {
5732         continue;
5733       }
5734       boolean apply = (aa.sequenceRef == null && forAlignment)
5735               || (aa.sequenceRef != null && forSequences);
5736       if (apply)
5737       {
5738         aa.visible = visible;
5739       }
5740     }
5741     alignPanel.validateAnnotationDimensions(true);
5742     alignPanel.alignmentChanged();
5743   }
5744
5745   /**
5746    * Store selected annotation sort order for the view and repaint.
5747    */
5748   @Override
5749   protected void sortAnnotations_actionPerformed()
5750   {
5751     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5752     this.alignPanel.av
5753             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5754     alignPanel.paintAlignment(false, false);
5755   }
5756
5757   /**
5758    * 
5759    * @return alignment panels in this alignment frame
5760    */
5761   public List<? extends AlignmentViewPanel> getAlignPanels()
5762   {
5763     // alignPanels is never null
5764     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5765     return alignPanels;
5766   }
5767
5768   /**
5769    * Open a new alignment window, with the cDNA associated with this (protein)
5770    * alignment, aligned as is the protein.
5771    */
5772   protected void viewAsCdna_actionPerformed()
5773   {
5774     // TODO no longer a menu action - refactor as required
5775     final AlignmentI alignment = getViewport().getAlignment();
5776     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5777     if (mappings == null)
5778     {
5779       return;
5780     }
5781     List<SequenceI> cdnaSeqs = new ArrayList<>();
5782     for (SequenceI aaSeq : alignment.getSequences())
5783     {
5784       for (AlignedCodonFrame acf : mappings)
5785       {
5786         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5787         if (dnaSeq != null)
5788         {
5789           /*
5790            * There is a cDNA mapping for this protein sequence - add to new
5791            * alignment. It will share the same dataset sequence as other mapped
5792            * cDNA (no new mappings need to be created).
5793            */
5794           final Sequence newSeq = new Sequence(dnaSeq);
5795           newSeq.setDatasetSequence(dnaSeq);
5796           cdnaSeqs.add(newSeq);
5797         }
5798       }
5799     }
5800     if (cdnaSeqs.size() == 0)
5801     {
5802       // show a warning dialog no mapped cDNA
5803       return;
5804     }
5805     AlignmentI cdna = new Alignment(
5806             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5807     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5808             AlignFrame.DEFAULT_HEIGHT);
5809     cdna.alignAs(alignment);
5810     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5811             + this.title;
5812     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5813             AlignFrame.DEFAULT_HEIGHT);
5814   }
5815
5816   /**
5817    * Set visibility of dna/protein complement view (available when shown in a
5818    * split frame).
5819    * 
5820    * @param show
5821    */
5822   @Override
5823   protected void showComplement_actionPerformed(boolean show)
5824   {
5825     SplitContainerI sf = getSplitViewContainer();
5826     if (sf != null)
5827     {
5828       sf.setComplementVisible(this, show);
5829     }
5830   }
5831
5832   /**
5833    * Generate the reverse (optionally complemented) of the selected sequences,
5834    * and add them to the alignment
5835    */
5836   @Override
5837   protected void showReverse_actionPerformed(boolean complement)
5838   {
5839     AlignmentI al = null;
5840     try
5841     {
5842       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5843       al = dna.reverseCdna(complement);
5844       viewport.addAlignment(al, "");
5845       addHistoryItem(new EditCommand(
5846               MessageManager.getString("label.add_sequences"), Action.PASTE,
5847               al.getSequencesArray(), 0, al.getWidth(),
5848               viewport.getAlignment()));
5849     } catch (Exception ex)
5850     {
5851       System.err.println(ex.getMessage());
5852       return;
5853     }
5854   }
5855
5856   /**
5857    * Try to run a script in the Groovy console, having first ensured that this
5858    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5859    * be targeted at this alignment.
5860    */
5861   @Override
5862   protected void runGroovy_actionPerformed()
5863   {
5864     Jalview.setCurrentAlignFrame(this);
5865     groovy.ui.Console console = Desktop.getGroovyConsole();
5866     if (console != null)
5867     {
5868       try
5869       {
5870         console.runScript();
5871       } catch (Exception ex)
5872       {
5873         System.err.println((ex.toString()));
5874         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5875                 MessageManager.getString("label.couldnt_run_groovy_script"),
5876                 MessageManager.getString("label.groovy_support_failed"),
5877                 JvOptionPane.ERROR_MESSAGE);
5878       }
5879     }
5880     else
5881     {
5882       System.err.println("Can't run Groovy script as console not found");
5883     }
5884   }
5885
5886   /**
5887    * Hides columns containing (or not containing) a specified feature, provided
5888    * that would not leave all columns hidden
5889    * 
5890    * @param featureType
5891    * @param columnsContaining
5892    * @return
5893    */
5894   public boolean hideFeatureColumns(String featureType,
5895           boolean columnsContaining)
5896   {
5897     boolean notForHiding = avc.markColumnsContainingFeatures(
5898             columnsContaining, false, false, featureType);
5899     if (notForHiding)
5900     {
5901       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5902               false, featureType))
5903       {
5904         getViewport().hideSelectedColumns();
5905         return true;
5906       }
5907     }
5908     return false;
5909   }
5910
5911   @Override
5912   protected void selectHighlightedColumns_actionPerformed(
5913           ActionEvent actionEvent)
5914   {
5915     // include key modifier check in case user selects from menu
5916     avc.markHighlightedColumns(
5917             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5918             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5919                     | ActionEvent.CTRL_MASK)) != 0);
5920   }
5921
5922   @Override
5923   protected void copyHighlightedColumns_actionPerformed(
5924           ActionEvent actionEvent)
5925   {
5926     avc.copyHighlightedRegionsToClipboard();
5927   }
5928
5929   /**
5930    * Rebuilds the Colour menu, including any user-defined colours which have
5931    * been loaded either on startup or during the session
5932    */
5933   public void buildColourMenu()
5934   {
5935     colourMenu.removeAll();
5936
5937     colourMenu.add(applyToAllGroups);
5938     colourMenu.add(textColour);
5939     colourMenu.addSeparator();
5940
5941     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5942             viewport.getAlignment(), false);
5943
5944     colourMenu.add(annotationColour);
5945     bg.add(annotationColour);
5946     colourMenu.addSeparator();
5947     colourMenu.add(conservationMenuItem);
5948     colourMenu.add(modifyConservation);
5949     colourMenu.add(abovePIDThreshold);
5950     colourMenu.add(modifyPID);
5951
5952     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5953     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5954   }
5955
5956   /**
5957    * Open a dialog (if not already open) that allows the user to select and
5958    * calculate PCA or Tree analysis
5959    */
5960   protected void openTreePcaDialog()
5961   {
5962     if (alignPanel.getCalculationDialog() == null)
5963     {
5964       new CalculationChooser(AlignFrame.this);
5965     }
5966   }
5967
5968   @Override
5969   protected void loadVcf_actionPerformed()
5970   {
5971     JalviewFileChooser chooser = new JalviewFileChooser(
5972             Cache.getProperty("LAST_DIRECTORY"));
5973     chooser.setFileView(new JalviewFileView());
5974     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5975     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5976     final AlignFrame us = this;
5977     chooser.setResponseHandler(0, () -> {
5978       String choice = chooser.getSelectedFile().getPath();
5979       Cache.setProperty("LAST_DIRECTORY", choice);
5980       SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5981       new VCFLoader(choice).loadVCF(seqs, us);
5982       return null;
5983     });
5984     chooser.showOpenDialog(null);
5985
5986   }
5987
5988   private Rectangle lastFeatureSettingsBounds = null;
5989
5990   @Override
5991   public void setFeatureSettingsGeometry(Rectangle bounds)
5992   {
5993     lastFeatureSettingsBounds = bounds;
5994   }
5995
5996   @Override
5997   public Rectangle getFeatureSettingsGeometry()
5998   {
5999     return lastFeatureSettingsBounds;
6000   }
6001
6002 }
6003
6004 class PrintThread extends Thread
6005 {
6006   AlignmentPanel ap;
6007
6008   public PrintThread(AlignmentPanel ap)
6009   {
6010     this.ap = ap;
6011   }
6012
6013   static PageFormat pf;
6014
6015   @Override
6016   public void run()
6017   {
6018     PrinterJob printJob = PrinterJob.getPrinterJob();
6019
6020     if (pf != null)
6021     {
6022       printJob.setPrintable(ap, pf);
6023     }
6024     else
6025     {
6026       printJob.setPrintable(ap);
6027     }
6028
6029     if (printJob.printDialog())
6030     {
6031       try
6032       {
6033         printJob.print();
6034       } catch (Exception PrintException)
6035       {
6036         PrintException.printStackTrace();
6037       }
6038     }
6039   }
6040 }