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