JAL-3048 switch from 'dialogdata' to DialogRunner for load Features/Annotations/Other...
[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     final 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     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
1475         {
1476
1477           @Override
1478           public void run()
1479           {
1480             String choice = chooser.getSelectedFile().getPath();
1481             jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1482             loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1483           }
1484
1485         });
1486
1487     chooser.openDialog(this);
1488   }
1489
1490   /**
1491    * Close the current view or all views in the alignment frame. If the frame
1492    * only contains one view then the alignment will be removed from memory.
1493    * 
1494    * @param closeAllTabs
1495    */
1496   @Override
1497   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1498   {
1499     if (alignPanels != null && alignPanels.size() < 2)
1500     {
1501       closeAllTabs = true;
1502     }
1503
1504     try
1505     {
1506       if (alignPanels != null)
1507       {
1508         if (closeAllTabs)
1509         {
1510           if (this.isClosed())
1511           {
1512             // really close all the windows - otherwise wait till
1513             // setClosed(true) is called
1514             for (int i = 0; i < alignPanels.size(); i++)
1515             {
1516               AlignmentPanel ap = alignPanels.get(i);
1517               ap.closePanel();
1518             }
1519           }
1520         }
1521         else
1522         {
1523           closeView(alignPanel);
1524         }
1525       }
1526
1527       if (closeAllTabs)
1528       {
1529         /*
1530          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1531          * be called recursively, with the frame now in 'closed' state
1532          */
1533         this.setClosed(true);
1534       }
1535     } catch (Exception ex)
1536     {
1537       ex.printStackTrace();
1538     }
1539   }
1540
1541   /**
1542    * Close the specified panel and close up tabs appropriately.
1543    * 
1544    * @param panelToClose
1545    */
1546   public void closeView(AlignmentPanel panelToClose)
1547   {
1548     int index = tabbedPane.getSelectedIndex();
1549     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1550     alignPanels.remove(panelToClose);
1551     panelToClose.closePanel();
1552     panelToClose = null;
1553
1554     tabbedPane.removeTabAt(closedindex);
1555     tabbedPane.validate();
1556
1557     if (index > closedindex || index == tabbedPane.getTabCount())
1558     {
1559       // modify currently selected tab index if necessary.
1560       index--;
1561     }
1562
1563     this.tabSelectionChanged(index);
1564   }
1565
1566   /**
1567    * DOCUMENT ME!
1568    */
1569   void updateEditMenuBar()
1570   {
1571
1572     if (viewport.getHistoryList().size() > 0)
1573     {
1574       undoMenuItem.setEnabled(true);
1575       CommandI command = viewport.getHistoryList().peek();
1576       undoMenuItem.setText(MessageManager
1577               .formatMessage("label.undo_command", new Object[]
1578               { command.getDescription() }));
1579     }
1580     else
1581     {
1582       undoMenuItem.setEnabled(false);
1583       undoMenuItem.setText(MessageManager.getString("action.undo"));
1584     }
1585
1586     if (viewport.getRedoList().size() > 0)
1587     {
1588       redoMenuItem.setEnabled(true);
1589
1590       CommandI command = viewport.getRedoList().peek();
1591       redoMenuItem.setText(MessageManager
1592               .formatMessage("label.redo_command", new Object[]
1593               { command.getDescription() }));
1594     }
1595     else
1596     {
1597       redoMenuItem.setEnabled(false);
1598       redoMenuItem.setText(MessageManager.getString("action.redo"));
1599     }
1600   }
1601
1602   @Override
1603   public void addHistoryItem(CommandI command)
1604   {
1605     if (command.getSize() > 0)
1606     {
1607       viewport.addToHistoryList(command);
1608       viewport.clearRedoList();
1609       updateEditMenuBar();
1610       viewport.updateHiddenColumns();
1611       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1612       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1613       // viewport.getColumnSelection()
1614       // .getHiddenColumns().size() > 0);
1615     }
1616   }
1617
1618   /**
1619    * 
1620    * @return alignment objects for all views
1621    */
1622   AlignmentI[] getViewAlignments()
1623   {
1624     if (alignPanels != null)
1625     {
1626       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1627       int i = 0;
1628       for (AlignmentPanel ap : alignPanels)
1629       {
1630         als[i++] = ap.av.getAlignment();
1631       }
1632       return als;
1633     }
1634     if (viewport != null)
1635     {
1636       return new AlignmentI[] { viewport.getAlignment() };
1637     }
1638     return null;
1639   }
1640
1641   /**
1642    * DOCUMENT ME!
1643    * 
1644    * @param e
1645    *          DOCUMENT ME!
1646    */
1647   @Override
1648   protected void undoMenuItem_actionPerformed(ActionEvent e)
1649   {
1650     if (viewport.getHistoryList().isEmpty())
1651     {
1652       return;
1653     }
1654     CommandI command = viewport.getHistoryList().pop();
1655     viewport.addToRedoList(command);
1656     command.undoCommand(getViewAlignments());
1657
1658     AlignmentViewport originalSource = getOriginatingSource(command);
1659     updateEditMenuBar();
1660
1661     if (originalSource != null)
1662     {
1663       if (originalSource != viewport)
1664       {
1665         Cache.log.warn(
1666                 "Implementation worry: mismatch of viewport origin for undo");
1667       }
1668       originalSource.updateHiddenColumns();
1669       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1670       // null
1671       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1672       // viewport.getColumnSelection()
1673       // .getHiddenColumns().size() > 0);
1674       originalSource.firePropertyChange("alignment", null,
1675               originalSource.getAlignment().getSequences());
1676     }
1677   }
1678
1679   /**
1680    * DOCUMENT ME!
1681    * 
1682    * @param e
1683    *          DOCUMENT ME!
1684    */
1685   @Override
1686   protected void redoMenuItem_actionPerformed(ActionEvent e)
1687   {
1688     if (viewport.getRedoList().size() < 1)
1689     {
1690       return;
1691     }
1692
1693     CommandI command = viewport.getRedoList().pop();
1694     viewport.addToHistoryList(command);
1695     command.doCommand(getViewAlignments());
1696
1697     AlignmentViewport originalSource = getOriginatingSource(command);
1698     updateEditMenuBar();
1699
1700     if (originalSource != null)
1701     {
1702
1703       if (originalSource != viewport)
1704       {
1705         Cache.log.warn(
1706                 "Implementation worry: mismatch of viewport origin for redo");
1707       }
1708       originalSource.updateHiddenColumns();
1709       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1710       // null
1711       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1712       // viewport.getColumnSelection()
1713       // .getHiddenColumns().size() > 0);
1714       originalSource.firePropertyChange("alignment", null,
1715               originalSource.getAlignment().getSequences());
1716     }
1717   }
1718
1719   AlignmentViewport getOriginatingSource(CommandI command)
1720   {
1721     AlignmentViewport originalSource = null;
1722     // For sequence removal and addition, we need to fire
1723     // the property change event FROM the viewport where the
1724     // original alignment was altered
1725     AlignmentI al = null;
1726     if (command instanceof EditCommand)
1727     {
1728       EditCommand editCommand = (EditCommand) command;
1729       al = editCommand.getAlignment();
1730       List<Component> comps = PaintRefresher.components
1731               .get(viewport.getSequenceSetId());
1732
1733       for (Component comp : comps)
1734       {
1735         if (comp instanceof AlignmentPanel)
1736         {
1737           if (al == ((AlignmentPanel) comp).av.getAlignment())
1738           {
1739             originalSource = ((AlignmentPanel) comp).av;
1740             break;
1741           }
1742         }
1743       }
1744     }
1745
1746     if (originalSource == null)
1747     {
1748       // The original view is closed, we must validate
1749       // the current view against the closed view first
1750       if (al != null)
1751       {
1752         PaintRefresher.validateSequences(al, viewport.getAlignment());
1753       }
1754
1755       originalSource = viewport;
1756     }
1757
1758     return originalSource;
1759   }
1760
1761   /**
1762    * DOCUMENT ME!
1763    * 
1764    * @param up
1765    *          DOCUMENT ME!
1766    */
1767   public void moveSelectedSequences(boolean up)
1768   {
1769     SequenceGroup sg = viewport.getSelectionGroup();
1770
1771     if (sg == null)
1772     {
1773       return;
1774     }
1775     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1776             viewport.getHiddenRepSequences(), up);
1777     alignPanel.paintAlignment(true, false);
1778   }
1779
1780   synchronized void slideSequences(boolean right, int size)
1781   {
1782     List<SequenceI> sg = new ArrayList<>();
1783     if (viewport.cursorMode)
1784     {
1785       sg.add(viewport.getAlignment()
1786               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1787     }
1788     else if (viewport.getSelectionGroup() != null
1789             && viewport.getSelectionGroup().getSize() != viewport
1790                     .getAlignment().getHeight())
1791     {
1792       sg = viewport.getSelectionGroup()
1793               .getSequences(viewport.getHiddenRepSequences());
1794     }
1795
1796     if (sg.size() < 1)
1797     {
1798       return;
1799     }
1800
1801     List<SequenceI> invertGroup = new ArrayList<>();
1802
1803     for (SequenceI seq : viewport.getAlignment().getSequences())
1804     {
1805       if (!sg.contains(seq))
1806       {
1807         invertGroup.add(seq);
1808       }
1809     }
1810
1811     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1812
1813     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1814     for (int i = 0; i < invertGroup.size(); i++)
1815     {
1816       seqs2[i] = invertGroup.get(i);
1817     }
1818
1819     SlideSequencesCommand ssc;
1820     if (right)
1821     {
1822       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1823               viewport.getGapCharacter());
1824     }
1825     else
1826     {
1827       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1828               viewport.getGapCharacter());
1829     }
1830
1831     int groupAdjustment = 0;
1832     if (ssc.getGapsInsertedBegin() && right)
1833     {
1834       if (viewport.cursorMode)
1835       {
1836         alignPanel.getSeqPanel().moveCursor(size, 0);
1837       }
1838       else
1839       {
1840         groupAdjustment = size;
1841       }
1842     }
1843     else if (!ssc.getGapsInsertedBegin() && !right)
1844     {
1845       if (viewport.cursorMode)
1846       {
1847         alignPanel.getSeqPanel().moveCursor(-size, 0);
1848       }
1849       else
1850       {
1851         groupAdjustment = -size;
1852       }
1853     }
1854
1855     if (groupAdjustment != 0)
1856     {
1857       viewport.getSelectionGroup().setStartRes(
1858               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1859       viewport.getSelectionGroup().setEndRes(
1860               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1861     }
1862
1863     /*
1864      * just extend the last slide command if compatible; but not if in
1865      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1866      */
1867     boolean appendHistoryItem = false;
1868     Deque<CommandI> historyList = viewport.getHistoryList();
1869     boolean inSplitFrame = getSplitViewContainer() != null;
1870     if (!inSplitFrame && historyList != null && historyList.size() > 0
1871             && historyList.peek() instanceof SlideSequencesCommand)
1872     {
1873       appendHistoryItem = ssc.appendSlideCommand(
1874               (SlideSequencesCommand) historyList.peek());
1875     }
1876
1877     if (!appendHistoryItem)
1878     {
1879       addHistoryItem(ssc);
1880     }
1881
1882     repaint();
1883   }
1884
1885   /**
1886    * DOCUMENT ME!
1887    * 
1888    * @param e
1889    *          DOCUMENT ME!
1890    */
1891   @Override
1892   protected void copy_actionPerformed(ActionEvent e)
1893   {
1894     if (viewport.getSelectionGroup() == null)
1895     {
1896       return;
1897     }
1898     // TODO: preserve the ordering of displayed alignment annotation in any
1899     // internal paste (particularly sequence associated annotation)
1900     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1901     String[] omitHidden = null;
1902
1903     if (viewport.hasHiddenColumns())
1904     {
1905       omitHidden = viewport.getViewAsString(true);
1906     }
1907
1908     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1909             seqs, omitHidden, null);
1910
1911     StringSelection ss = new StringSelection(output);
1912
1913     try
1914     {
1915       jalview.gui.Desktop.internalCopy = true;
1916       // Its really worth setting the clipboard contents
1917       // to empty before setting the large StringSelection!!
1918       Toolkit.getDefaultToolkit().getSystemClipboard()
1919               .setContents(new StringSelection(""), null);
1920
1921       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1922               Desktop.instance);
1923     } catch (OutOfMemoryError er)
1924     {
1925       new OOMWarning("copying region", er);
1926       return;
1927     }
1928
1929     HiddenColumns hiddenColumns = null;
1930     if (viewport.hasHiddenColumns())
1931     {
1932       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1933       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1934
1935       // create new HiddenColumns object with copy of hidden regions
1936       // between startRes and endRes, offset by startRes
1937       hiddenColumns = new HiddenColumns(
1938               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1939               hiddenCutoff, hiddenOffset);
1940     }
1941
1942     Desktop.jalviewClipboard = new Object[] { seqs,
1943         viewport.getAlignment().getDataset(), hiddenColumns };
1944     statusBar.setText(MessageManager.formatMessage(
1945             "label.copied_sequences_to_clipboard", new Object[]
1946             { Integer.valueOf(seqs.length).toString() }));
1947   }
1948
1949   /**
1950    * DOCUMENT ME!
1951    * 
1952    * @param e
1953    *          DOCUMENT ME!
1954    */
1955   @Override
1956   protected void pasteNew_actionPerformed(ActionEvent e)
1957   {
1958     paste(true);
1959   }
1960
1961   /**
1962    * DOCUMENT ME!
1963    * 
1964    * @param e
1965    *          DOCUMENT ME!
1966    */
1967   @Override
1968   protected void pasteThis_actionPerformed(ActionEvent e)
1969   {
1970     paste(false);
1971   }
1972
1973   /**
1974    * Paste contents of Jalview clipboard
1975    * 
1976    * @param newAlignment
1977    *          true to paste to a new alignment, otherwise add to this.
1978    */
1979   void paste(boolean newAlignment)
1980   {
1981     boolean externalPaste = true;
1982     try
1983     {
1984       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1985       Transferable contents = c.getContents(this);
1986
1987       if (contents == null)
1988       {
1989         return;
1990       }
1991
1992       String str;
1993       FileFormatI format;
1994       try
1995       {
1996         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1997         if (str.length() < 1)
1998         {
1999           return;
2000         }
2001
2002         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2003
2004       } catch (OutOfMemoryError er)
2005       {
2006         new OOMWarning("Out of memory pasting sequences!!", er);
2007         return;
2008       }
2009
2010       SequenceI[] sequences;
2011       boolean annotationAdded = false;
2012       AlignmentI alignment = null;
2013
2014       if (Desktop.jalviewClipboard != null)
2015       {
2016         // The clipboard was filled from within Jalview, we must use the
2017         // sequences
2018         // And dataset from the copied alignment
2019         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2020         // be doubly sure that we create *new* sequence objects.
2021         sequences = new SequenceI[newseq.length];
2022         for (int i = 0; i < newseq.length; i++)
2023         {
2024           sequences[i] = new Sequence(newseq[i]);
2025         }
2026         alignment = new Alignment(sequences);
2027         externalPaste = false;
2028       }
2029       else
2030       {
2031         // parse the clipboard as an alignment.
2032         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2033                 format);
2034         sequences = alignment.getSequencesArray();
2035       }
2036
2037       int alwidth = 0;
2038       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2039       int fgroup = -1;
2040
2041       if (newAlignment)
2042       {
2043
2044         if (Desktop.jalviewClipboard != null)
2045         {
2046           // dataset is inherited
2047           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2048         }
2049         else
2050         {
2051           // new dataset is constructed
2052           alignment.setDataset(null);
2053         }
2054         alwidth = alignment.getWidth() + 1;
2055       }
2056       else
2057       {
2058         AlignmentI pastedal = alignment; // preserve pasted alignment object
2059         // Add pasted sequences and dataset into existing alignment.
2060         alignment = viewport.getAlignment();
2061         alwidth = alignment.getWidth() + 1;
2062         // decide if we need to import sequences from an existing dataset
2063         boolean importDs = Desktop.jalviewClipboard != null
2064                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2065         // importDs==true instructs us to copy over new dataset sequences from
2066         // an existing alignment
2067         Vector newDs = (importDs) ? new Vector() : null; // used to create
2068         // minimum dataset set
2069
2070         for (int i = 0; i < sequences.length; i++)
2071         {
2072           if (importDs)
2073           {
2074             newDs.addElement(null);
2075           }
2076           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2077           // paste
2078           if (importDs && ds != null)
2079           {
2080             if (!newDs.contains(ds))
2081             {
2082               newDs.setElementAt(ds, i);
2083               ds = new Sequence(ds);
2084               // update with new dataset sequence
2085               sequences[i].setDatasetSequence(ds);
2086             }
2087             else
2088             {
2089               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2090             }
2091           }
2092           else
2093           {
2094             // copy and derive new dataset sequence
2095             sequences[i] = sequences[i].deriveSequence();
2096             alignment.getDataset()
2097                     .addSequence(sequences[i].getDatasetSequence());
2098             // TODO: avoid creation of duplicate dataset sequences with a
2099             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2100           }
2101           alignment.addSequence(sequences[i]); // merges dataset
2102         }
2103         if (newDs != null)
2104         {
2105           newDs.clear(); // tidy up
2106         }
2107         if (alignment.getAlignmentAnnotation() != null)
2108         {
2109           for (AlignmentAnnotation alan : alignment
2110                   .getAlignmentAnnotation())
2111           {
2112             if (alan.graphGroup > fgroup)
2113             {
2114               fgroup = alan.graphGroup;
2115             }
2116           }
2117         }
2118         if (pastedal.getAlignmentAnnotation() != null)
2119         {
2120           // Add any annotation attached to alignment.
2121           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2122           for (int i = 0; i < alann.length; i++)
2123           {
2124             annotationAdded = true;
2125             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2126             {
2127               AlignmentAnnotation newann = new AlignmentAnnotation(
2128                       alann[i]);
2129               if (newann.graphGroup > -1)
2130               {
2131                 if (newGraphGroups.size() <= newann.graphGroup
2132                         || newGraphGroups.get(newann.graphGroup) == null)
2133                 {
2134                   for (int q = newGraphGroups
2135                           .size(); q <= newann.graphGroup; q++)
2136                   {
2137                     newGraphGroups.add(q, null);
2138                   }
2139                   newGraphGroups.set(newann.graphGroup,
2140                           new Integer(++fgroup));
2141                 }
2142                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2143                         .intValue();
2144               }
2145
2146               newann.padAnnotation(alwidth);
2147               alignment.addAnnotation(newann);
2148             }
2149           }
2150         }
2151       }
2152       if (!newAlignment)
2153       {
2154         // /////
2155         // ADD HISTORY ITEM
2156         //
2157         addHistoryItem(new EditCommand(
2158                 MessageManager.getString("label.add_sequences"),
2159                 Action.PASTE, sequences, 0, alignment.getWidth(),
2160                 alignment));
2161       }
2162       // Add any annotations attached to sequences
2163       for (int i = 0; i < sequences.length; i++)
2164       {
2165         if (sequences[i].getAnnotation() != null)
2166         {
2167           AlignmentAnnotation newann;
2168           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2169           {
2170             annotationAdded = true;
2171             newann = sequences[i].getAnnotation()[a];
2172             newann.adjustForAlignment();
2173             newann.padAnnotation(alwidth);
2174             if (newann.graphGroup > -1)
2175             {
2176               if (newann.graphGroup > -1)
2177               {
2178                 if (newGraphGroups.size() <= newann.graphGroup
2179                         || newGraphGroups.get(newann.graphGroup) == null)
2180                 {
2181                   for (int q = newGraphGroups
2182                           .size(); q <= newann.graphGroup; q++)
2183                   {
2184                     newGraphGroups.add(q, null);
2185                   }
2186                   newGraphGroups.set(newann.graphGroup,
2187                           new Integer(++fgroup));
2188                 }
2189                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2190                         .intValue();
2191               }
2192             }
2193             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2194             // was
2195             // duplicated
2196             // earlier
2197             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2198                     a);
2199           }
2200         }
2201       }
2202       if (!newAlignment)
2203       {
2204
2205         // propagate alignment changed.
2206         viewport.getRanges().setEndSeq(alignment.getHeight());
2207         if (annotationAdded)
2208         {
2209           // Duplicate sequence annotation in all views.
2210           AlignmentI[] alview = this.getViewAlignments();
2211           for (int i = 0; i < sequences.length; i++)
2212           {
2213             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2214             if (sann == null)
2215             {
2216               continue;
2217             }
2218             for (int avnum = 0; avnum < alview.length; avnum++)
2219             {
2220               if (alview[avnum] != alignment)
2221               {
2222                 // duplicate in a view other than the one with input focus
2223                 int avwidth = alview[avnum].getWidth() + 1;
2224                 // this relies on sann being preserved after we
2225                 // modify the sequence's annotation array for each duplication
2226                 for (int a = 0; a < sann.length; a++)
2227                 {
2228                   AlignmentAnnotation newann = new AlignmentAnnotation(
2229                           sann[a]);
2230                   sequences[i].addAlignmentAnnotation(newann);
2231                   newann.padAnnotation(avwidth);
2232                   alview[avnum].addAnnotation(newann); // annotation was
2233                   // duplicated earlier
2234                   // TODO JAL-1145 graphGroups are not updated for sequence
2235                   // annotation added to several views. This may cause
2236                   // strangeness
2237                   alview[avnum].setAnnotationIndex(newann, a);
2238                 }
2239               }
2240             }
2241           }
2242           buildSortByAnnotationScoresMenu();
2243         }
2244         viewport.firePropertyChange("alignment", null,
2245                 alignment.getSequences());
2246         if (alignPanels != null)
2247         {
2248           for (AlignmentPanel ap : alignPanels)
2249           {
2250             ap.validateAnnotationDimensions(false);
2251           }
2252         }
2253         else
2254         {
2255           alignPanel.validateAnnotationDimensions(false);
2256         }
2257
2258       }
2259       else
2260       {
2261         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2262                 DEFAULT_HEIGHT);
2263         String newtitle = new String("Copied sequences");
2264
2265         if (Desktop.jalviewClipboard != null
2266                 && Desktop.jalviewClipboard[2] != null)
2267         {
2268           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2269           af.viewport.setHiddenColumns(hc);
2270         }
2271
2272         // >>>This is a fix for the moment, until a better solution is
2273         // found!!<<<
2274         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2275                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2276                         .getFeatureRenderer());
2277
2278         // TODO: maintain provenance of an alignment, rather than just make the
2279         // title a concatenation of operations.
2280         if (!externalPaste)
2281         {
2282           if (title.startsWith("Copied sequences"))
2283           {
2284             newtitle = title;
2285           }
2286           else
2287           {
2288             newtitle = newtitle.concat("- from " + title);
2289           }
2290         }
2291         else
2292         {
2293           newtitle = new String("Pasted sequences");
2294         }
2295
2296         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2297                 DEFAULT_HEIGHT);
2298
2299       }
2300
2301     } catch (Exception ex)
2302     {
2303       ex.printStackTrace();
2304       System.out.println("Exception whilst pasting: " + ex);
2305       // could be anything being pasted in here
2306     }
2307
2308   }
2309
2310   @Override
2311   protected void expand_newalign(ActionEvent e)
2312   {
2313     try
2314     {
2315       AlignmentI alignment = AlignmentUtils
2316               .expandContext(getViewport().getAlignment(), -1);
2317       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2318               DEFAULT_HEIGHT);
2319       String newtitle = new String("Flanking alignment");
2320
2321       if (Desktop.jalviewClipboard != null
2322               && Desktop.jalviewClipboard[2] != null)
2323       {
2324         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2325         af.viewport.setHiddenColumns(hc);
2326       }
2327
2328       // >>>This is a fix for the moment, until a better solution is
2329       // found!!<<<
2330       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2331               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2332                       .getFeatureRenderer());
2333
2334       // TODO: maintain provenance of an alignment, rather than just make the
2335       // title a concatenation of operations.
2336       {
2337         if (title.startsWith("Copied sequences"))
2338         {
2339           newtitle = title;
2340         }
2341         else
2342         {
2343           newtitle = newtitle.concat("- from " + title);
2344         }
2345       }
2346
2347       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2348
2349     } catch (Exception ex)
2350     {
2351       ex.printStackTrace();
2352       System.out.println("Exception whilst pasting: " + ex);
2353       // could be anything being pasted in here
2354     } catch (OutOfMemoryError oom)
2355     {
2356       new OOMWarning("Viewing flanking region of alignment", oom);
2357     }
2358   }
2359
2360   /**
2361    * DOCUMENT ME!
2362    * 
2363    * @param e
2364    *          DOCUMENT ME!
2365    */
2366   @Override
2367   protected void cut_actionPerformed(ActionEvent e)
2368   {
2369     copy_actionPerformed(null);
2370     delete_actionPerformed(null);
2371   }
2372
2373   /**
2374    * DOCUMENT ME!
2375    * 
2376    * @param e
2377    *          DOCUMENT ME!
2378    */
2379   @Override
2380   protected void delete_actionPerformed(ActionEvent evt)
2381   {
2382
2383     SequenceGroup sg = viewport.getSelectionGroup();
2384     if (sg == null)
2385     {
2386       return;
2387     }
2388
2389     /*
2390      * If the cut affects all sequences, warn, remove highlighted columns
2391      */
2392     if (sg.getSize() == viewport.getAlignment().getHeight())
2393     {
2394       boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2395               + 1) == viewport.getAlignment().getWidth()) ? true : false;
2396       if (isEntireAlignWidth)
2397       {
2398         int confirm = JvOptionPane.showConfirmDialog(this,
2399                 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2400                 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2401                 JvOptionPane.OK_CANCEL_OPTION);
2402
2403         if (confirm == JvOptionPane.CANCEL_OPTION
2404                 || confirm == JvOptionPane.CLOSED_OPTION)
2405         {
2406           return;
2407         }
2408       }
2409       viewport.getColumnSelection().removeElements(sg.getStartRes(),
2410               sg.getEndRes() + 1);
2411     }
2412     SequenceI[] cut = sg.getSequences()
2413             .toArray(new SequenceI[sg.getSize()]);
2414
2415     addHistoryItem(new EditCommand(
2416             MessageManager.getString("label.cut_sequences"), Action.CUT,
2417             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2418             viewport.getAlignment()));
2419
2420     viewport.setSelectionGroup(null);
2421     viewport.sendSelection();
2422     viewport.getAlignment().deleteGroup(sg);
2423
2424     viewport.firePropertyChange("alignment", null,
2425             viewport.getAlignment().getSequences());
2426     if (viewport.getAlignment().getHeight() < 1)
2427     {
2428       try
2429       {
2430         this.setClosed(true);
2431       } catch (Exception ex)
2432       {
2433       }
2434     }
2435   }
2436
2437   /**
2438    * DOCUMENT ME!
2439    * 
2440    * @param e
2441    *          DOCUMENT ME!
2442    */
2443   @Override
2444   protected void deleteGroups_actionPerformed(ActionEvent e)
2445   {
2446     if (avc.deleteGroups())
2447     {
2448       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2449       alignPanel.updateAnnotation();
2450       alignPanel.paintAlignment(true, true);
2451     }
2452   }
2453
2454   /**
2455    * DOCUMENT ME!
2456    * 
2457    * @param e
2458    *          DOCUMENT ME!
2459    */
2460   @Override
2461   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2462   {
2463     SequenceGroup sg = new SequenceGroup();
2464
2465     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2466     {
2467       sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2468     }
2469
2470     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2471     viewport.setSelectionGroup(sg);
2472     viewport.sendSelection();
2473     // JAL-2034 - should delegate to
2474     // alignPanel to decide if overview needs
2475     // updating.
2476     alignPanel.paintAlignment(false, false);
2477     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2478   }
2479
2480   /**
2481    * DOCUMENT ME!
2482    * 
2483    * @param e
2484    *          DOCUMENT ME!
2485    */
2486   @Override
2487   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2488   {
2489     if (viewport.cursorMode)
2490     {
2491       alignPanel.getSeqPanel().keyboardNo1 = null;
2492       alignPanel.getSeqPanel().keyboardNo2 = null;
2493     }
2494     viewport.setSelectionGroup(null);
2495     viewport.getColumnSelection().clear();
2496     viewport.setSelectionGroup(null);
2497     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2498     // JAL-2034 - should delegate to
2499     // alignPanel to decide if overview needs
2500     // updating.
2501     alignPanel.paintAlignment(false, false);
2502     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2503     viewport.sendSelection();
2504   }
2505
2506   /**
2507    * DOCUMENT ME!
2508    * 
2509    * @param e
2510    *          DOCUMENT ME!
2511    */
2512   @Override
2513   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2514   {
2515     SequenceGroup sg = viewport.getSelectionGroup();
2516
2517     if (sg == null)
2518     {
2519       selectAllSequenceMenuItem_actionPerformed(null);
2520
2521       return;
2522     }
2523
2524     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2525     {
2526       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2527     }
2528     // JAL-2034 - should delegate to
2529     // alignPanel to decide if overview needs
2530     // updating.
2531
2532     alignPanel.paintAlignment(true, false);
2533     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2534     viewport.sendSelection();
2535   }
2536
2537   @Override
2538   public void invertColSel_actionPerformed(ActionEvent e)
2539   {
2540     viewport.invertColumnSelection();
2541     alignPanel.paintAlignment(true, false);
2542     viewport.sendSelection();
2543   }
2544
2545   /**
2546    * DOCUMENT ME!
2547    * 
2548    * @param e
2549    *          DOCUMENT ME!
2550    */
2551   @Override
2552   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2553   {
2554     trimAlignment(true);
2555   }
2556
2557   /**
2558    * DOCUMENT ME!
2559    * 
2560    * @param e
2561    *          DOCUMENT ME!
2562    */
2563   @Override
2564   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2565   {
2566     trimAlignment(false);
2567   }
2568
2569   void trimAlignment(boolean trimLeft)
2570   {
2571     ColumnSelection colSel = viewport.getColumnSelection();
2572     int column;
2573
2574     if (!colSel.isEmpty())
2575     {
2576       if (trimLeft)
2577       {
2578         column = colSel.getMin();
2579       }
2580       else
2581       {
2582         column = colSel.getMax();
2583       }
2584
2585       SequenceI[] seqs;
2586       if (viewport.getSelectionGroup() != null)
2587       {
2588         seqs = viewport.getSelectionGroup()
2589                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2590       }
2591       else
2592       {
2593         seqs = viewport.getAlignment().getSequencesArray();
2594       }
2595
2596       TrimRegionCommand trimRegion;
2597       if (trimLeft)
2598       {
2599         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2600                 column, viewport.getAlignment());
2601         viewport.getRanges().setStartRes(0);
2602       }
2603       else
2604       {
2605         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2606                 column, viewport.getAlignment());
2607       }
2608
2609       statusBar.setText(MessageManager
2610               .formatMessage("label.removed_columns", new String[]
2611               { Integer.valueOf(trimRegion.getSize()).toString() }));
2612
2613       addHistoryItem(trimRegion);
2614
2615       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2616       {
2617         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2618                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2619         {
2620           viewport.getAlignment().deleteGroup(sg);
2621         }
2622       }
2623
2624       viewport.firePropertyChange("alignment", null,
2625               viewport.getAlignment().getSequences());
2626     }
2627   }
2628
2629   /**
2630    * DOCUMENT ME!
2631    * 
2632    * @param e
2633    *          DOCUMENT ME!
2634    */
2635   @Override
2636   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2637   {
2638     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2639
2640     SequenceI[] seqs;
2641     if (viewport.getSelectionGroup() != null)
2642     {
2643       seqs = viewport.getSelectionGroup()
2644               .getSequencesAsArray(viewport.getHiddenRepSequences());
2645       start = viewport.getSelectionGroup().getStartRes();
2646       end = viewport.getSelectionGroup().getEndRes();
2647     }
2648     else
2649     {
2650       seqs = viewport.getAlignment().getSequencesArray();
2651     }
2652
2653     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2654             "Remove Gapped Columns", seqs, start, end,
2655             viewport.getAlignment());
2656
2657     addHistoryItem(removeGapCols);
2658
2659     statusBar.setText(MessageManager
2660             .formatMessage("label.removed_empty_columns", new Object[]
2661             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2662
2663     // This is to maintain viewport position on first residue
2664     // of first sequence
2665     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2666     ViewportRanges ranges = viewport.getRanges();
2667     int startRes = seq.findPosition(ranges.getStartRes());
2668     // ShiftList shifts;
2669     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2670     // edit.alColumnChanges=shifts.getInverse();
2671     // if (viewport.hasHiddenColumns)
2672     // viewport.getColumnSelection().compensateForEdits(shifts);
2673     ranges.setStartRes(seq.findIndex(startRes) - 1);
2674     viewport.firePropertyChange("alignment", null,
2675             viewport.getAlignment().getSequences());
2676
2677   }
2678
2679   /**
2680    * DOCUMENT ME!
2681    * 
2682    * @param e
2683    *          DOCUMENT ME!
2684    */
2685   @Override
2686   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2687   {
2688     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2689
2690     SequenceI[] seqs;
2691     if (viewport.getSelectionGroup() != null)
2692     {
2693       seqs = viewport.getSelectionGroup()
2694               .getSequencesAsArray(viewport.getHiddenRepSequences());
2695       start = viewport.getSelectionGroup().getStartRes();
2696       end = viewport.getSelectionGroup().getEndRes();
2697     }
2698     else
2699     {
2700       seqs = viewport.getAlignment().getSequencesArray();
2701     }
2702
2703     // This is to maintain viewport position on first residue
2704     // of first sequence
2705     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2706     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2707
2708     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2709             viewport.getAlignment()));
2710
2711     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2712
2713     viewport.firePropertyChange("alignment", null,
2714             viewport.getAlignment().getSequences());
2715
2716   }
2717
2718   /**
2719    * DOCUMENT ME!
2720    * 
2721    * @param e
2722    *          DOCUMENT ME!
2723    */
2724   @Override
2725   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2726   {
2727     viewport.setPadGaps(padGapsMenuitem.isSelected());
2728     viewport.firePropertyChange("alignment", null,
2729             viewport.getAlignment().getSequences());
2730   }
2731
2732   /**
2733    * DOCUMENT ME!
2734    * 
2735    * @param e
2736    *          DOCUMENT ME!
2737    */
2738   @Override
2739   public void findMenuItem_actionPerformed(ActionEvent e)
2740   {
2741     new Finder();
2742   }
2743
2744   /**
2745    * Create a new view of the current alignment.
2746    */
2747   @Override
2748   public void newView_actionPerformed(ActionEvent e)
2749   {
2750     newView(null, true);
2751   }
2752
2753   /**
2754    * Creates and shows a new view of the current alignment.
2755    * 
2756    * @param viewTitle
2757    *          title of newly created view; if null, one will be generated
2758    * @param copyAnnotation
2759    *          if true then duplicate all annnotation, groups and settings
2760    * @return new alignment panel, already displayed.
2761    */
2762   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2763   {
2764     /*
2765      * Create a new AlignmentPanel (with its own, new Viewport)
2766      */
2767     AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2768     if (!copyAnnotation)
2769     {
2770       /*
2771        * remove all groups and annotation except for the automatic stuff
2772        */
2773       newap.av.getAlignment().deleteAllGroups();
2774       newap.av.getAlignment().deleteAllAnnotations(false);
2775     }
2776
2777     newap.av.setGatherViewsHere(false);
2778
2779     if (viewport.viewName == null)
2780     {
2781       viewport.viewName = MessageManager
2782               .getString("label.view_name_original");
2783     }
2784
2785     /*
2786      * Views share the same edits undo and redo stacks
2787      */
2788     newap.av.setHistoryList(viewport.getHistoryList());
2789     newap.av.setRedoList(viewport.getRedoList());
2790
2791     /*
2792      * Views share the same mappings; need to deregister any new mappings
2793      * created by copyAlignPanel, and register the new reference to the shared
2794      * mappings
2795      */
2796     newap.av.replaceMappings(viewport.getAlignment());
2797
2798     /*
2799      * start up cDNA consensus (if applicable) now mappings are in place
2800      */
2801     if (newap.av.initComplementConsensus())
2802     {
2803       newap.refresh(true); // adjust layout of annotations
2804     }
2805
2806     newap.av.viewName = getNewViewName(viewTitle);
2807
2808     addAlignmentPanel(newap, true);
2809     newap.alignmentChanged();
2810
2811     if (alignPanels.size() == 2)
2812     {
2813       viewport.setGatherViewsHere(true);
2814     }
2815     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2816     return newap;
2817   }
2818
2819   /**
2820    * Make a new name for the view, ensuring it is unique within the current
2821    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2822    * these now use viewId. Unique view names are still desirable for usability.)
2823    * 
2824    * @param viewTitle
2825    * @return
2826    */
2827   protected String getNewViewName(String viewTitle)
2828   {
2829     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2830     boolean addFirstIndex = false;
2831     if (viewTitle == null || viewTitle.trim().length() == 0)
2832     {
2833       viewTitle = MessageManager.getString("action.view");
2834       addFirstIndex = true;
2835     }
2836     else
2837     {
2838       index = 1;// we count from 1 if given a specific name
2839     }
2840     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2841
2842     List<Component> comps = PaintRefresher.components
2843             .get(viewport.getSequenceSetId());
2844
2845     List<String> existingNames = getExistingViewNames(comps);
2846
2847     while (existingNames.contains(newViewName))
2848     {
2849       newViewName = viewTitle + " " + (++index);
2850     }
2851     return newViewName;
2852   }
2853
2854   /**
2855    * Returns a list of distinct view names found in the given list of
2856    * components. View names are held on the viewport of an AlignmentPanel.
2857    * 
2858    * @param comps
2859    * @return
2860    */
2861   protected List<String> getExistingViewNames(List<Component> comps)
2862   {
2863     List<String> existingNames = new ArrayList<>();
2864     for (Component comp : comps)
2865     {
2866       if (comp instanceof AlignmentPanel)
2867       {
2868         AlignmentPanel ap = (AlignmentPanel) comp;
2869         if (!existingNames.contains(ap.av.viewName))
2870         {
2871           existingNames.add(ap.av.viewName);
2872         }
2873       }
2874     }
2875     return existingNames;
2876   }
2877
2878   /**
2879    * Explode tabbed views into separate windows.
2880    */
2881   @Override
2882   public void expandViews_actionPerformed(ActionEvent e)
2883   {
2884     Desktop.explodeViews(this);
2885   }
2886
2887   /**
2888    * Gather views in separate windows back into a tabbed presentation.
2889    */
2890   @Override
2891   public void gatherViews_actionPerformed(ActionEvent e)
2892   {
2893     Desktop.instance.gatherViews(this);
2894   }
2895
2896   /**
2897    * DOCUMENT ME!
2898    * 
2899    * @param e
2900    *          DOCUMENT ME!
2901    */
2902   @Override
2903   public void font_actionPerformed(ActionEvent e)
2904   {
2905     new FontChooser(alignPanel);
2906   }
2907
2908   /**
2909    * DOCUMENT ME!
2910    * 
2911    * @param e
2912    *          DOCUMENT ME!
2913    */
2914   @Override
2915   protected void seqLimit_actionPerformed(ActionEvent e)
2916   {
2917     viewport.setShowJVSuffix(seqLimits.isSelected());
2918
2919     alignPanel.getIdPanel().getIdCanvas()
2920             .setPreferredSize(alignPanel.calculateIdWidth());
2921     alignPanel.paintAlignment(true, false);
2922   }
2923
2924   @Override
2925   public void idRightAlign_actionPerformed(ActionEvent e)
2926   {
2927     viewport.setRightAlignIds(idRightAlign.isSelected());
2928     alignPanel.paintAlignment(false, false);
2929   }
2930
2931   @Override
2932   public void centreColumnLabels_actionPerformed(ActionEvent e)
2933   {
2934     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2935     alignPanel.paintAlignment(false, false);
2936   }
2937
2938   /*
2939    * (non-Javadoc)
2940    * 
2941    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2942    */
2943   @Override
2944   protected void followHighlight_actionPerformed()
2945   {
2946     /*
2947      * Set the 'follow' flag on the Viewport (and scroll to position if now
2948      * true).
2949      */
2950     final boolean state = this.followHighlightMenuItem.getState();
2951     viewport.setFollowHighlight(state);
2952     if (state)
2953     {
2954       alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2955     }
2956   }
2957
2958   /**
2959    * DOCUMENT ME!
2960    * 
2961    * @param e
2962    *          DOCUMENT ME!
2963    */
2964   @Override
2965   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2966   {
2967     viewport.setColourText(colourTextMenuItem.isSelected());
2968     alignPanel.paintAlignment(false, false);
2969   }
2970
2971   /**
2972    * DOCUMENT ME!
2973    * 
2974    * @param e
2975    *          DOCUMENT ME!
2976    */
2977   @Override
2978   public void wrapMenuItem_actionPerformed(ActionEvent e)
2979   {
2980     scaleAbove.setVisible(wrapMenuItem.isSelected());
2981     scaleLeft.setVisible(wrapMenuItem.isSelected());
2982     scaleRight.setVisible(wrapMenuItem.isSelected());
2983     viewport.setWrapAlignment(wrapMenuItem.isSelected());
2984     alignPanel.updateLayout();
2985   }
2986
2987   @Override
2988   public void showAllSeqs_actionPerformed(ActionEvent e)
2989   {
2990     viewport.showAllHiddenSeqs();
2991   }
2992
2993   @Override
2994   public void showAllColumns_actionPerformed(ActionEvent e)
2995   {
2996     viewport.showAllHiddenColumns();
2997     alignPanel.paintAlignment(true, true);
2998     viewport.sendSelection();
2999   }
3000
3001   @Override
3002   public void hideSelSequences_actionPerformed(ActionEvent e)
3003   {
3004     viewport.hideAllSelectedSeqs();
3005   }
3006
3007   /**
3008    * called by key handler and the hide all/show all menu items
3009    * 
3010    * @param toggleSeqs
3011    * @param toggleCols
3012    */
3013   private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3014   {
3015
3016     boolean hide = false;
3017     SequenceGroup sg = viewport.getSelectionGroup();
3018     if (!toggleSeqs && !toggleCols)
3019     {
3020       // Hide everything by the current selection - this is a hack - we do the
3021       // invert and then hide
3022       // first check that there will be visible columns after the invert.
3023       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3024               && sg.getStartRes() <= sg.getEndRes()))
3025       {
3026         // now invert the sequence set, if required - empty selection implies
3027         // that no hiding is required.
3028         if (sg != null)
3029         {
3030           invertSequenceMenuItem_actionPerformed(null);
3031           sg = viewport.getSelectionGroup();
3032           toggleSeqs = true;
3033
3034         }
3035         viewport.expandColSelection(sg, true);
3036         // finally invert the column selection and get the new sequence
3037         // selection.
3038         invertColSel_actionPerformed(null);
3039         toggleCols = true;
3040       }
3041     }
3042
3043     if (toggleSeqs)
3044     {
3045       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3046       {
3047         hideSelSequences_actionPerformed(null);
3048         hide = true;
3049       }
3050       else if (!(toggleCols && viewport.hasSelectedColumns()))
3051       {
3052         showAllSeqs_actionPerformed(null);
3053       }
3054     }
3055
3056     if (toggleCols)
3057     {
3058       if (viewport.hasSelectedColumns())
3059       {
3060         hideSelColumns_actionPerformed(null);
3061         if (!toggleSeqs)
3062         {
3063           viewport.setSelectionGroup(sg);
3064         }
3065       }
3066       else if (!hide)
3067       {
3068         showAllColumns_actionPerformed(null);
3069       }
3070     }
3071   }
3072
3073   /*
3074    * (non-Javadoc)
3075    * 
3076    * @see
3077    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3078    * event.ActionEvent)
3079    */
3080   @Override
3081   public void hideAllButSelection_actionPerformed(ActionEvent e)
3082   {
3083     toggleHiddenRegions(false, false);
3084     viewport.sendSelection();
3085   }
3086
3087   /*
3088    * (non-Javadoc)
3089    * 
3090    * @see
3091    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3092    * .ActionEvent)
3093    */
3094   @Override
3095   public void hideAllSelection_actionPerformed(ActionEvent e)
3096   {
3097     SequenceGroup sg = viewport.getSelectionGroup();
3098     viewport.expandColSelection(sg, false);
3099     viewport.hideAllSelectedSeqs();
3100     viewport.hideSelectedColumns();
3101     alignPanel.paintAlignment(true, true);
3102     viewport.sendSelection();
3103   }
3104
3105   /*
3106    * (non-Javadoc)
3107    * 
3108    * @see
3109    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3110    * ActionEvent)
3111    */
3112   @Override
3113   public void showAllhidden_actionPerformed(ActionEvent e)
3114   {
3115     viewport.showAllHiddenColumns();
3116     viewport.showAllHiddenSeqs();
3117     alignPanel.paintAlignment(true, true);
3118     viewport.sendSelection();
3119   }
3120
3121   @Override
3122   public void hideSelColumns_actionPerformed(ActionEvent e)
3123   {
3124     viewport.hideSelectedColumns();
3125     alignPanel.paintAlignment(true, true);
3126     viewport.sendSelection();
3127   }
3128
3129   @Override
3130   public void hiddenMarkers_actionPerformed(ActionEvent e)
3131   {
3132     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3133     repaint();
3134   }
3135
3136   /**
3137    * DOCUMENT ME!
3138    * 
3139    * @param e
3140    *          DOCUMENT ME!
3141    */
3142   @Override
3143   protected void scaleAbove_actionPerformed(ActionEvent e)
3144   {
3145     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3146     // TODO: do we actually need to update overview for scale above change ?
3147     alignPanel.paintAlignment(true, false);
3148   }
3149
3150   /**
3151    * DOCUMENT ME!
3152    * 
3153    * @param e
3154    *          DOCUMENT ME!
3155    */
3156   @Override
3157   protected void scaleLeft_actionPerformed(ActionEvent e)
3158   {
3159     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3160     alignPanel.paintAlignment(true, false);
3161   }
3162
3163   /**
3164    * DOCUMENT ME!
3165    * 
3166    * @param e
3167    *          DOCUMENT ME!
3168    */
3169   @Override
3170   protected void scaleRight_actionPerformed(ActionEvent e)
3171   {
3172     viewport.setScaleRightWrapped(scaleRight.isSelected());
3173     alignPanel.paintAlignment(true, false);
3174   }
3175
3176   /**
3177    * DOCUMENT ME!
3178    * 
3179    * @param e
3180    *          DOCUMENT ME!
3181    */
3182   @Override
3183   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3184   {
3185     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3186     alignPanel.paintAlignment(false, false);
3187   }
3188
3189   /**
3190    * DOCUMENT ME!
3191    * 
3192    * @param e
3193    *          DOCUMENT ME!
3194    */
3195   @Override
3196   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3197   {
3198     viewport.setShowText(viewTextMenuItem.isSelected());
3199     alignPanel.paintAlignment(false, false);
3200   }
3201
3202   /**
3203    * DOCUMENT ME!
3204    * 
3205    * @param e
3206    *          DOCUMENT ME!
3207    */
3208   @Override
3209   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3210   {
3211     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3212     alignPanel.paintAlignment(false, false);
3213   }
3214
3215   public FeatureSettings featureSettings;
3216
3217   @Override
3218   public FeatureSettingsControllerI getFeatureSettingsUI()
3219   {
3220     return featureSettings;
3221   }
3222
3223   @Override
3224   public void featureSettings_actionPerformed(ActionEvent e)
3225   {
3226     if (featureSettings != null)
3227     {
3228       featureSettings.close();
3229       featureSettings = null;
3230     }
3231     if (!showSeqFeatures.isSelected())
3232     {
3233       // make sure features are actually displayed
3234       showSeqFeatures.setSelected(true);
3235       showSeqFeatures_actionPerformed(null);
3236     }
3237     featureSettings = new FeatureSettings(this);
3238   }
3239
3240   /**
3241    * Set or clear 'Show Sequence Features'
3242    * 
3243    * @param evt
3244    *          DOCUMENT ME!
3245    */
3246   @Override
3247   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3248   {
3249     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3250     alignPanel.paintAlignment(true, true);
3251   }
3252
3253   /**
3254    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3255    * the annotations panel as a whole.
3256    * 
3257    * The options to show/hide all annotations should be enabled when the panel
3258    * is shown, and disabled when the panel is hidden.
3259    * 
3260    * @param e
3261    */
3262   @Override
3263   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3264   {
3265     final boolean setVisible = annotationPanelMenuItem.isSelected();
3266     viewport.setShowAnnotation(setVisible);
3267     this.showAllSeqAnnotations.setEnabled(setVisible);
3268     this.hideAllSeqAnnotations.setEnabled(setVisible);
3269     this.showAllAlAnnotations.setEnabled(setVisible);
3270     this.hideAllAlAnnotations.setEnabled(setVisible);
3271     alignPanel.updateLayout();
3272   }
3273
3274   @Override
3275   public void alignmentProperties()
3276   {
3277     JEditorPane editPane = new JEditorPane("text/html", "");
3278     editPane.setEditable(false);
3279     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3280             .formatAsHtml();
3281     editPane.setText(
3282             MessageManager.formatMessage("label.html_content", new Object[]
3283             { contents.toString() }));
3284     JInternalFrame frame = new JInternalFrame();
3285     frame.getContentPane().add(new JScrollPane(editPane));
3286
3287     Desktop.addInternalFrame(frame, MessageManager
3288             .formatMessage("label.alignment_properties", new Object[]
3289             { getTitle() }), 500, 400);
3290   }
3291
3292   /**
3293    * DOCUMENT ME!
3294    * 
3295    * @param e
3296    *          DOCUMENT ME!
3297    */
3298   @Override
3299   public void overviewMenuItem_actionPerformed(ActionEvent e)
3300   {
3301     if (alignPanel.overviewPanel != null)
3302     {
3303       return;
3304     }
3305
3306     JInternalFrame frame = new JInternalFrame();
3307     final OverviewPanel overview = new OverviewPanel(alignPanel);
3308     frame.setContentPane(overview);
3309     Desktop.addInternalFrame(frame, MessageManager
3310             .formatMessage("label.overview_params", new Object[]
3311             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3312             true, true);
3313     frame.pack();
3314     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3315     frame.addInternalFrameListener(
3316             new javax.swing.event.InternalFrameAdapter()
3317             {
3318               @Override
3319               public void internalFrameClosed(
3320                       javax.swing.event.InternalFrameEvent evt)
3321               {
3322                 overview.dispose();
3323                 alignPanel.setOverviewPanel(null);
3324               };
3325             });
3326     if (getKeyListeners().length > 0)
3327     {
3328       frame.addKeyListener(getKeyListeners()[0]);
3329     }
3330
3331     alignPanel.setOverviewPanel(overview);
3332   }
3333
3334   @Override
3335   public void textColour_actionPerformed()
3336   {
3337     new TextColourChooser().chooseColour(alignPanel, null);
3338   }
3339
3340   /*
3341    * public void covariationColour_actionPerformed() {
3342    * changeColour(new
3343    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3344    * ()[0])); }
3345    */
3346   @Override
3347   public void annotationColour_actionPerformed()
3348   {
3349     new AnnotationColourChooser(viewport, alignPanel);
3350   }
3351
3352   @Override
3353   public void annotationColumn_actionPerformed(ActionEvent e)
3354   {
3355     new AnnotationColumnChooser(viewport, alignPanel);
3356   }
3357
3358   /**
3359    * Action on the user checking or unchecking the option to apply the selected
3360    * colour scheme to all groups. If unchecked, groups may have their own
3361    * independent colour schemes.
3362    * 
3363    * @param selected
3364    */
3365   @Override
3366   public void applyToAllGroups_actionPerformed(boolean selected)
3367   {
3368     viewport.setColourAppliesToAllGroups(selected);
3369   }
3370
3371   /**
3372    * Action on user selecting a colour from the colour menu
3373    * 
3374    * @param name
3375    *          the name (not the menu item label!) of the colour scheme
3376    */
3377   @Override
3378   public void changeColour_actionPerformed(String name)
3379   {
3380     /*
3381      * 'User Defined' opens a panel to configure or load a
3382      * user-defined colour scheme
3383      */
3384     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3385     {
3386       new UserDefinedColours(alignPanel);
3387       return;
3388     }
3389
3390     /*
3391      * otherwise set the chosen colour scheme (or null for 'None')
3392      */
3393     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3394             viewport.getAlignment(), viewport.getHiddenRepSequences());
3395     changeColour(cs);
3396   }
3397
3398   /**
3399    * Actions on setting or changing the alignment colour scheme
3400    * 
3401    * @param cs
3402    */
3403   @Override
3404   public void changeColour(ColourSchemeI cs)
3405   {
3406     // TODO: pull up to controller method
3407     ColourMenuHelper.setColourSelected(colourMenu, cs);
3408
3409     viewport.setGlobalColourScheme(cs);
3410
3411     alignPanel.paintAlignment(true, true);
3412   }
3413
3414   /**
3415    * Show the PID threshold slider panel
3416    */
3417   @Override
3418   protected void modifyPID_actionPerformed()
3419   {
3420     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3421             alignPanel.getViewName());
3422     SliderPanel.showPIDSlider();
3423   }
3424
3425   /**
3426    * Show the Conservation slider panel
3427    */
3428   @Override
3429   protected void modifyConservation_actionPerformed()
3430   {
3431     SliderPanel.setConservationSlider(alignPanel,
3432             viewport.getResidueShading(), alignPanel.getViewName());
3433     SliderPanel.showConservationSlider();
3434   }
3435
3436   /**
3437    * Action on selecting or deselecting (Colour) By Conservation
3438    */
3439   @Override
3440   public void conservationMenuItem_actionPerformed(boolean selected)
3441   {
3442     modifyConservation.setEnabled(selected);
3443     viewport.setConservationSelected(selected);
3444     viewport.getResidueShading().setConservationApplied(selected);
3445
3446     changeColour(viewport.getGlobalColourScheme());
3447     if (selected)
3448     {
3449       modifyConservation_actionPerformed();
3450     }
3451     else
3452     {
3453       SliderPanel.hideConservationSlider();
3454     }
3455   }
3456
3457   /**
3458    * Action on selecting or deselecting (Colour) Above PID Threshold
3459    */
3460   @Override
3461   public void abovePIDThreshold_actionPerformed(boolean selected)
3462   {
3463     modifyPID.setEnabled(selected);
3464     viewport.setAbovePIDThreshold(selected);
3465     if (!selected)
3466     {
3467       viewport.getResidueShading().setThreshold(0,
3468               viewport.isIgnoreGapsConsensus());
3469     }
3470
3471     changeColour(viewport.getGlobalColourScheme());
3472     if (selected)
3473     {
3474       modifyPID_actionPerformed();
3475     }
3476     else
3477     {
3478       SliderPanel.hidePIDSlider();
3479     }
3480   }
3481
3482   /**
3483    * DOCUMENT ME!
3484    * 
3485    * @param e
3486    *          DOCUMENT ME!
3487    */
3488   @Override
3489   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3490   {
3491     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3492     AlignmentSorter.sortByPID(viewport.getAlignment(),
3493             viewport.getAlignment().getSequenceAt(0));
3494     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3495             viewport.getAlignment()));
3496     alignPanel.paintAlignment(true, false);
3497   }
3498
3499   /**
3500    * DOCUMENT ME!
3501    * 
3502    * @param e
3503    *          DOCUMENT ME!
3504    */
3505   @Override
3506   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3507   {
3508     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3509     AlignmentSorter.sortByID(viewport.getAlignment());
3510     addHistoryItem(
3511             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3512     alignPanel.paintAlignment(true, false);
3513   }
3514
3515   /**
3516    * DOCUMENT ME!
3517    * 
3518    * @param e
3519    *          DOCUMENT ME!
3520    */
3521   @Override
3522   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3523   {
3524     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3525     AlignmentSorter.sortByLength(viewport.getAlignment());
3526     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3527             viewport.getAlignment()));
3528     alignPanel.paintAlignment(true, false);
3529   }
3530
3531   /**
3532    * DOCUMENT ME!
3533    * 
3534    * @param e
3535    *          DOCUMENT ME!
3536    */
3537   @Override
3538   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3539   {
3540     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3541     AlignmentSorter.sortByGroup(viewport.getAlignment());
3542     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3543             viewport.getAlignment()));
3544
3545     alignPanel.paintAlignment(true, false);
3546   }
3547
3548   /**
3549    * DOCUMENT ME!
3550    * 
3551    * @param e
3552    *          DOCUMENT ME!
3553    */
3554   @Override
3555   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3556   {
3557     new RedundancyPanel(alignPanel, this);
3558   }
3559
3560   /**
3561    * DOCUMENT ME!
3562    * 
3563    * @param e
3564    *          DOCUMENT ME!
3565    */
3566   @Override
3567   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3568   {
3569     if ((viewport.getSelectionGroup() == null)
3570             || (viewport.getSelectionGroup().getSize() < 2))
3571     {
3572       JvOptionPane.showInternalMessageDialog(this,
3573               MessageManager.getString(
3574                       "label.you_must_select_least_two_sequences"),
3575               MessageManager.getString("label.invalid_selection"),
3576               JvOptionPane.WARNING_MESSAGE);
3577     }
3578     else
3579     {
3580       JInternalFrame frame = new JInternalFrame();
3581       frame.setContentPane(new PairwiseAlignPanel(viewport));
3582       Desktop.addInternalFrame(frame,
3583               MessageManager.getString("action.pairwise_alignment"), 600,
3584               500);
3585     }
3586   }
3587
3588   @Override
3589   public void autoCalculate_actionPerformed(ActionEvent e)
3590   {
3591     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3592     if (viewport.autoCalculateConsensus)
3593     {
3594       viewport.firePropertyChange("alignment", null,
3595               viewport.getAlignment().getSequences());
3596     }
3597   }
3598
3599   @Override
3600   public void sortByTreeOption_actionPerformed(ActionEvent e)
3601   {
3602     viewport.sortByTree = sortByTree.isSelected();
3603   }
3604
3605   @Override
3606   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3607   {
3608     viewport.followSelection = listenToViewSelections.isSelected();
3609   }
3610
3611   /**
3612    * Constructs a tree panel and adds it to the desktop
3613    * 
3614    * @param type
3615    *          tree type (NJ or AV)
3616    * @param modelName
3617    *          name of score model used to compute the tree
3618    * @param options
3619    *          parameters for the distance or similarity calculation
3620    */
3621   void newTreePanel(String type, String modelName,
3622           SimilarityParamsI options)
3623   {
3624     String frameTitle = "";
3625     TreePanel tp;
3626
3627     boolean onSelection = false;
3628     if (viewport.getSelectionGroup() != null
3629             && viewport.getSelectionGroup().getSize() > 0)
3630     {
3631       SequenceGroup sg = viewport.getSelectionGroup();
3632
3633       /* Decide if the selection is a column region */
3634       for (SequenceI _s : sg.getSequences())
3635       {
3636         if (_s.getLength() < sg.getEndRes())
3637         {
3638           JvOptionPane.showMessageDialog(Desktop.desktop,
3639                   MessageManager.getString(
3640                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3641                   MessageManager.getString(
3642                           "label.sequences_selection_not_aligned"),
3643                   JvOptionPane.WARNING_MESSAGE);
3644
3645           return;
3646         }
3647       }
3648       onSelection = true;
3649     }
3650     else
3651     {
3652       if (viewport.getAlignment().getHeight() < 2)
3653       {
3654         return;
3655       }
3656     }
3657
3658     tp = new TreePanel(alignPanel, type, modelName, options);
3659     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3660
3661     frameTitle += " from ";
3662
3663     if (viewport.viewName != null)
3664     {
3665       frameTitle += viewport.viewName + " of ";
3666     }
3667
3668     frameTitle += this.title;
3669
3670     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3671   }
3672
3673   /**
3674    * DOCUMENT ME!
3675    * 
3676    * @param title
3677    *          DOCUMENT ME!
3678    * @param order
3679    *          DOCUMENT ME!
3680    */
3681   public void addSortByOrderMenuItem(String title,
3682           final AlignmentOrder order)
3683   {
3684     final JMenuItem item = new JMenuItem(MessageManager
3685             .formatMessage("action.by_title_param", new Object[]
3686             { title }));
3687     sort.add(item);
3688     item.addActionListener(new java.awt.event.ActionListener()
3689     {
3690       @Override
3691       public void actionPerformed(ActionEvent e)
3692       {
3693         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3694
3695         // TODO: JBPNote - have to map order entries to curent SequenceI
3696         // pointers
3697         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3698
3699         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3700                 viewport.getAlignment()));
3701
3702         alignPanel.paintAlignment(true, false);
3703       }
3704     });
3705   }
3706
3707   /**
3708    * Add a new sort by annotation score menu item
3709    * 
3710    * @param sort
3711    *          the menu to add the option to
3712    * @param scoreLabel
3713    *          the label used to retrieve scores for each sequence on the
3714    *          alignment
3715    */
3716   public void addSortByAnnotScoreMenuItem(JMenu sort,
3717           final String scoreLabel)
3718   {
3719     final JMenuItem item = new JMenuItem(scoreLabel);
3720     sort.add(item);
3721     item.addActionListener(new java.awt.event.ActionListener()
3722     {
3723       @Override
3724       public void actionPerformed(ActionEvent e)
3725       {
3726         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3727         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3728                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3729         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3730                 viewport.getAlignment()));
3731         alignPanel.paintAlignment(true, false);
3732       }
3733     });
3734   }
3735
3736   /**
3737    * last hash for alignment's annotation array - used to minimise cost of
3738    * rebuild.
3739    */
3740   protected int _annotationScoreVectorHash;
3741
3742   /**
3743    * search the alignment and rebuild the sort by annotation score submenu the
3744    * last alignment annotation vector hash is stored to minimize cost of
3745    * rebuilding in subsequence calls.
3746    * 
3747    */
3748   @Override
3749   public void buildSortByAnnotationScoresMenu()
3750   {
3751     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3752     {
3753       return;
3754     }
3755
3756     if (viewport.getAlignment().getAlignmentAnnotation()
3757             .hashCode() != _annotationScoreVectorHash)
3758     {
3759       sortByAnnotScore.removeAll();
3760       // almost certainly a quicker way to do this - but we keep it simple
3761       Hashtable scoreSorts = new Hashtable();
3762       AlignmentAnnotation aann[];
3763       for (SequenceI sqa : viewport.getAlignment().getSequences())
3764       {
3765         aann = sqa.getAnnotation();
3766         for (int i = 0; aann != null && i < aann.length; i++)
3767         {
3768           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3769           {
3770             scoreSorts.put(aann[i].label, aann[i].label);
3771           }
3772         }
3773       }
3774       Enumeration labels = scoreSorts.keys();
3775       while (labels.hasMoreElements())
3776       {
3777         addSortByAnnotScoreMenuItem(sortByAnnotScore,
3778                 (String) labels.nextElement());
3779       }
3780       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3781       scoreSorts.clear();
3782
3783       _annotationScoreVectorHash = viewport.getAlignment()
3784               .getAlignmentAnnotation().hashCode();
3785     }
3786   }
3787
3788   /**
3789    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3790    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3791    * call. Listeners are added to remove the menu item when the treePanel is
3792    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3793    * modified.
3794    */
3795   @Override
3796   public void buildTreeSortMenu()
3797   {
3798     sortByTreeMenu.removeAll();
3799
3800     List<Component> comps = PaintRefresher.components
3801             .get(viewport.getSequenceSetId());
3802     List<TreePanel> treePanels = new ArrayList<>();
3803     for (Component comp : comps)
3804     {
3805       if (comp instanceof TreePanel)
3806       {
3807         treePanels.add((TreePanel) comp);
3808       }
3809     }
3810
3811     if (treePanels.size() < 1)
3812     {
3813       sortByTreeMenu.setVisible(false);
3814       return;
3815     }
3816
3817     sortByTreeMenu.setVisible(true);
3818
3819     for (final TreePanel tp : treePanels)
3820     {
3821       final JMenuItem item = new JMenuItem(tp.getTitle());
3822       item.addActionListener(new java.awt.event.ActionListener()
3823       {
3824         @Override
3825         public void actionPerformed(ActionEvent e)
3826         {
3827           tp.sortByTree_actionPerformed();
3828           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3829
3830         }
3831       });
3832
3833       sortByTreeMenu.add(item);
3834     }
3835   }
3836
3837   public boolean sortBy(AlignmentOrder alorder, String undoname)
3838   {
3839     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3840     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3841     if (undoname != null)
3842     {
3843       addHistoryItem(new OrderCommand(undoname, oldOrder,
3844               viewport.getAlignment()));
3845     }
3846     alignPanel.paintAlignment(true, false);
3847     return true;
3848   }
3849
3850   /**
3851    * Work out whether the whole set of sequences or just the selected set will
3852    * be submitted for multiple alignment.
3853    * 
3854    */
3855   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3856   {
3857     // Now, check we have enough sequences
3858     AlignmentView msa = null;
3859
3860     if ((viewport.getSelectionGroup() != null)
3861             && (viewport.getSelectionGroup().getSize() > 1))
3862     {
3863       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3864       // some common interface!
3865       /*
3866        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3867        * SequenceI[sz = seqs.getSize(false)];
3868        * 
3869        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3870        * seqs.getSequenceAt(i); }
3871        */
3872       msa = viewport.getAlignmentView(true);
3873     }
3874     else if (viewport.getSelectionGroup() != null
3875             && viewport.getSelectionGroup().getSize() == 1)
3876     {
3877       int option = JvOptionPane.showConfirmDialog(this,
3878               MessageManager.getString("warn.oneseq_msainput_selection"),
3879               MessageManager.getString("label.invalid_selection"),
3880               JvOptionPane.OK_CANCEL_OPTION);
3881       if (option == JvOptionPane.OK_OPTION)
3882       {
3883         msa = viewport.getAlignmentView(false);
3884       }
3885     }
3886     else
3887     {
3888       msa = viewport.getAlignmentView(false);
3889     }
3890     return msa;
3891   }
3892
3893   /**
3894    * Decides what is submitted to a secondary structure prediction service: the
3895    * first sequence in the alignment, or in the current selection, or, if the
3896    * alignment is 'aligned' (ie padded with gaps), then the currently selected
3897    * region or the whole alignment. (where the first sequence in the set is the
3898    * one that the prediction will be for).
3899    */
3900   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3901   {
3902     AlignmentView seqs = null;
3903
3904     if ((viewport.getSelectionGroup() != null)
3905             && (viewport.getSelectionGroup().getSize() > 0))
3906     {
3907       seqs = viewport.getAlignmentView(true);
3908     }
3909     else
3910     {
3911       seqs = viewport.getAlignmentView(false);
3912     }
3913     // limit sequences - JBPNote in future - could spawn multiple prediction
3914     // jobs
3915     // TODO: viewport.getAlignment().isAligned is a global state - the local
3916     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3917     if (!viewport.getAlignment().isAligned(false))
3918     {
3919       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3920       // TODO: if seqs.getSequences().length>1 then should really have warned
3921       // user!
3922
3923     }
3924     return seqs;
3925   }
3926
3927   /**
3928    * DOCUMENT ME!
3929    * 
3930    * @param e
3931    *          DOCUMENT ME!
3932    */
3933   @Override
3934   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3935   {
3936     // Pick the tree file
3937     JalviewFileChooser chooser = new JalviewFileChooser(
3938             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3939     chooser.setFileView(new JalviewFileView());
3940     chooser.setDialogTitle(
3941             MessageManager.getString("label.select_newick_like_tree_file"));
3942     chooser.setToolTipText(
3943             MessageManager.getString("label.load_tree_file"));
3944
3945     chooser.response(
3946             new jalview.util.dialogrunner.RunResponse(JalviewFileChooser.APPROVE_OPTION)
3947             {
3948               @Override
3949               public void run()
3950               {
3951                 String filePath = chooser.getSelectedFile().getPath();
3952                 Cache.setProperty("LAST_DIRECTORY", filePath);
3953                 NewickFile fin = null;
3954                 try
3955                 {
3956                   fin = new NewickFile(new FileParse(
3957                           chooser.getSelectedFile(), DataSourceType.FILE));
3958                   viewport.setCurrentTree(
3959                           showNewickTree(fin, filePath).getTree());
3960                 } catch (Exception ex)
3961                 {
3962                   JvOptionPane.showMessageDialog(Desktop.desktop,
3963                           ex.getMessage(),
3964                           MessageManager.getString(
3965                                   "label.problem_reading_tree_file"),
3966                           JvOptionPane.WARNING_MESSAGE);
3967                   ex.printStackTrace();
3968                 }
3969                 if (fin != null && fin.hasWarningMessage())
3970                 {
3971                   JvOptionPane.showMessageDialog(Desktop.desktop,
3972                           fin.getWarningMessage(),
3973                           MessageManager.getString(
3974                                   "label.possible_problem_with_tree_file"),
3975                           JvOptionPane.WARNING_MESSAGE);
3976                 }
3977               }
3978             }).openDialog(this);
3979   }
3980
3981   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3982   {
3983     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3984   }
3985
3986   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3987           int h, int x, int y)
3988   {
3989     return showNewickTree(nf, treeTitle, null, w, h, x, y);
3990   }
3991
3992   /**
3993    * Add a treeviewer for the tree extracted from a Newick file object to the
3994    * current alignment view
3995    * 
3996    * @param nf
3997    *          the tree
3998    * @param title
3999    *          tree viewer title
4000    * @param input
4001    *          Associated alignment input data (or null)
4002    * @param w
4003    *          width
4004    * @param h
4005    *          height
4006    * @param x
4007    *          position
4008    * @param y
4009    *          position
4010    * @return TreePanel handle
4011    */
4012   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4013           AlignmentView input, int w, int h, int x, int y)
4014   {
4015     TreePanel tp = null;
4016
4017     try
4018     {
4019       nf.parse();
4020
4021       if (nf.getTree() != null)
4022       {
4023         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4024
4025         tp.setSize(w, h);
4026
4027         if (x > 0 && y > 0)
4028         {
4029           tp.setLocation(x, y);
4030         }
4031
4032         Desktop.addInternalFrame(tp, treeTitle, w, h);
4033       }
4034     } catch (Exception ex)
4035     {
4036       ex.printStackTrace();
4037     }
4038
4039     return tp;
4040   }
4041
4042   private boolean buildingMenu = false;
4043
4044   /**
4045    * Generates menu items and listener event actions for web service clients
4046    * 
4047    */
4048   public void BuildWebServiceMenu()
4049   {
4050     while (buildingMenu)
4051     {
4052       try
4053       {
4054         System.err.println("Waiting for building menu to finish.");
4055         Thread.sleep(10);
4056       } catch (Exception e)
4057       {
4058       }
4059     }
4060     final AlignFrame me = this;
4061     buildingMenu = true;
4062     new Thread(new Runnable()
4063     {
4064       @Override
4065       public void run()
4066       {
4067         final List<JMenuItem> legacyItems = new ArrayList<>();
4068         try
4069         {
4070           // System.err.println("Building ws menu again "
4071           // + Thread.currentThread());
4072           // TODO: add support for context dependent disabling of services based
4073           // on
4074           // alignment and current selection
4075           // TODO: add additional serviceHandle parameter to specify abstract
4076           // handler
4077           // class independently of AbstractName
4078           // TODO: add in rediscovery GUI function to restart discoverer
4079           // TODO: group services by location as well as function and/or
4080           // introduce
4081           // object broker mechanism.
4082           final Vector<JMenu> wsmenu = new Vector<>();
4083           final IProgressIndicator af = me;
4084
4085           /*
4086            * do not i18n these strings - they are hard-coded in class
4087            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4088            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4089            */
4090           final JMenu msawsmenu = new JMenu("Alignment");
4091           final JMenu secstrmenu = new JMenu(
4092                   "Secondary Structure Prediction");
4093           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4094           final JMenu analymenu = new JMenu("Analysis");
4095           final JMenu dismenu = new JMenu("Protein Disorder");
4096           // JAL-940 - only show secondary structure prediction services from
4097           // the legacy server
4098           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4099               // &&
4100           Discoverer.services != null && (Discoverer.services.size() > 0))
4101           {
4102             // TODO: refactor to allow list of AbstractName/Handler bindings to
4103             // be
4104             // stored or retrieved from elsewhere
4105             // No MSAWS used any more:
4106             // Vector msaws = null; // (Vector)
4107             // Discoverer.services.get("MsaWS");
4108             Vector secstrpr = (Vector) Discoverer.services
4109                     .get("SecStrPred");
4110             if (secstrpr != null)
4111             {
4112               // Add any secondary structure prediction services
4113               for (int i = 0, j = secstrpr.size(); i < j; i++)
4114               {
4115                 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4116                         .get(i);
4117                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4118                         .getServiceClient(sh);
4119                 int p = secstrmenu.getItemCount();
4120                 impl.attachWSMenuEntry(secstrmenu, me);
4121                 int q = secstrmenu.getItemCount();
4122                 for (int litm = p; litm < q; litm++)
4123                 {
4124                   legacyItems.add(secstrmenu.getItem(litm));
4125                 }
4126               }
4127             }
4128           }
4129
4130           // Add all submenus in the order they should appear on the web
4131           // services menu
4132           wsmenu.add(msawsmenu);
4133           wsmenu.add(secstrmenu);
4134           wsmenu.add(dismenu);
4135           wsmenu.add(analymenu);
4136           // No search services yet
4137           // wsmenu.add(seqsrchmenu);
4138
4139           javax.swing.SwingUtilities.invokeLater(new Runnable()
4140           {
4141             @Override
4142             public void run()
4143             {
4144               try
4145               {
4146                 webService.removeAll();
4147                 // first, add discovered services onto the webservices menu
4148                 if (wsmenu.size() > 0)
4149                 {
4150                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4151                   {
4152                     webService.add(wsmenu.get(i));
4153                   }
4154                 }
4155                 else
4156                 {
4157                   webService.add(me.webServiceNoServices);
4158                 }
4159                 // TODO: move into separate menu builder class.
4160                 boolean new_sspred = false;
4161                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4162                 {
4163                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4164                   if (jws2servs != null)
4165                   {
4166                     if (jws2servs.hasServices())
4167                     {
4168                       jws2servs.attachWSMenuEntry(webService, me);
4169                       for (Jws2Instance sv : jws2servs.getServices())
4170                       {
4171                         if (sv.description.toLowerCase().contains("jpred"))
4172                         {
4173                           for (JMenuItem jmi : legacyItems)
4174                           {
4175                             jmi.setVisible(false);
4176                           }
4177                         }
4178                       }
4179
4180                     }
4181                     if (jws2servs.isRunning())
4182                     {
4183                       JMenuItem tm = new JMenuItem(
4184                               "Still discovering JABA Services");
4185                       tm.setEnabled(false);
4186                       webService.add(tm);
4187                     }
4188                   }
4189                 }
4190                 build_urlServiceMenu(me.webService);
4191                 build_fetchdbmenu(webService);
4192                 for (JMenu item : wsmenu)
4193                 {
4194                   if (item.getItemCount() == 0)
4195                   {
4196                     item.setEnabled(false);
4197                   }
4198                   else
4199                   {
4200                     item.setEnabled(true);
4201                   }
4202                 }
4203               } catch (Exception e)
4204               {
4205                 Cache.log.debug(
4206                         "Exception during web service menu building process.",
4207                         e);
4208               }
4209             }
4210           });
4211         } catch (Exception e)
4212         {
4213         }
4214         buildingMenu = false;
4215       }
4216     }).start();
4217
4218   }
4219
4220   /**
4221    * construct any groupURL type service menu entries.
4222    * 
4223    * @param webService
4224    */
4225   private void build_urlServiceMenu(JMenu webService)
4226   {
4227     // TODO: remove this code when 2.7 is released
4228     // DEBUG - alignmentView
4229     /*
4230      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4231      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4232      * 
4233      * @Override public void actionPerformed(ActionEvent e) {
4234      * jalview.datamodel.AlignmentView
4235      * .testSelectionViews(af.viewport.getAlignment(),
4236      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4237      * 
4238      * }); webService.add(testAlView);
4239      */
4240     // TODO: refactor to RestClient discoverer and merge menu entries for
4241     // rest-style services with other types of analysis/calculation service
4242     // SHmmr test client - still being implemented.
4243     // DEBUG - alignmentView
4244
4245     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4246             .getRestClients())
4247     {
4248       client.attachWSMenuEntry(
4249               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4250               this);
4251     }
4252   }
4253
4254   /**
4255    * Searches the alignment sequences for xRefs and builds the Show
4256    * Cross-References menu (formerly called Show Products), with database
4257    * sources for which cross-references are found (protein sources for a
4258    * nucleotide alignment and vice versa)
4259    * 
4260    * @return true if Show Cross-references menu should be enabled
4261    */
4262   public boolean canShowProducts()
4263   {
4264     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4265     AlignmentI dataset = viewport.getAlignment().getDataset();
4266
4267     showProducts.removeAll();
4268     final boolean dna = viewport.getAlignment().isNucleotide();
4269
4270     if (seqs == null || seqs.length == 0)
4271     {
4272       // nothing to see here.
4273       return false;
4274     }
4275
4276     boolean showp = false;
4277     try
4278     {
4279       List<String> ptypes = new CrossRef(seqs, dataset)
4280               .findXrefSourcesForSequences(dna);
4281
4282       for (final String source : ptypes)
4283       {
4284         showp = true;
4285         final AlignFrame af = this;
4286         JMenuItem xtype = new JMenuItem(source);
4287         xtype.addActionListener(new ActionListener()
4288         {
4289           @Override
4290           public void actionPerformed(ActionEvent e)
4291           {
4292             showProductsFor(af.viewport.getSequenceSelection(), dna,
4293                     source);
4294           }
4295         });
4296         showProducts.add(xtype);
4297       }
4298       showProducts.setVisible(showp);
4299       showProducts.setEnabled(showp);
4300     } catch (Exception e)
4301     {
4302       Cache.log.warn(
4303               "canShowProducts threw an exception - please report to help@jalview.org",
4304               e);
4305       return false;
4306     }
4307     return showp;
4308   }
4309
4310   /**
4311    * Finds and displays cross-references for the selected sequences (protein
4312    * products for nucleotide sequences, dna coding sequences for peptides).
4313    * 
4314    * @param sel
4315    *          the sequences to show cross-references for
4316    * @param dna
4317    *          true if from a nucleotide alignment (so showing proteins)
4318    * @param source
4319    *          the database to show cross-references for
4320    */
4321   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4322           final String source)
4323   {
4324     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4325             .start();
4326   }
4327
4328   /**
4329    * Construct and display a new frame containing the translation of this
4330    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4331    */
4332   @Override
4333   public void showTranslation_actionPerformed(ActionEvent e)
4334   {
4335     AlignmentI al = null;
4336     try
4337     {
4338       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4339
4340       al = dna.translateCdna();
4341     } catch (Exception ex)
4342     {
4343       jalview.bin.Cache.log.error(
4344               "Exception during translation. Please report this !", ex);
4345       final String msg = MessageManager.getString(
4346               "label.error_when_translating_sequences_submit_bug_report");
4347       final String errorTitle = MessageManager
4348               .getString("label.implementation_error")
4349               + MessageManager.getString("label.translation_failed");
4350       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4351               JvOptionPane.ERROR_MESSAGE);
4352       return;
4353     }
4354     if (al == null || al.getHeight() == 0)
4355     {
4356       final String msg = MessageManager.getString(
4357               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4358       final String errorTitle = MessageManager
4359               .getString("label.translation_failed");
4360       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4361               JvOptionPane.WARNING_MESSAGE);
4362     }
4363     else
4364     {
4365       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4366       af.setFileFormat(this.currentFileFormat);
4367       final String newTitle = MessageManager
4368               .formatMessage("label.translation_of_params", new Object[]
4369               { this.getTitle() });
4370       af.setTitle(newTitle);
4371       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4372       {
4373         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4374         viewport.openSplitFrame(af, new Alignment(seqs));
4375       }
4376       else
4377       {
4378         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4379                 DEFAULT_HEIGHT);
4380       }
4381     }
4382   }
4383
4384   /**
4385    * Set the file format
4386    * 
4387    * @param format
4388    */
4389   public void setFileFormat(FileFormatI format)
4390   {
4391     this.currentFileFormat = format;
4392   }
4393
4394   /**
4395    * Try to load a features file onto the alignment.
4396    * 
4397    * @param file
4398    *          contents or path to retrieve file or a File object
4399    * @param sourceType
4400    *          access mode of file (see jalview.io.AlignFile)
4401    * @return true if features file was parsed correctly.
4402    */
4403   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4404   {
4405     // BH 2018 
4406     return avc.parseFeaturesFile(file, sourceType,
4407             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4408
4409   }
4410
4411   @Override
4412   public void refreshFeatureUI(boolean enableIfNecessary)
4413   {
4414     // note - currently this is only still here rather than in the controller
4415     // because of the featureSettings hard reference that is yet to be
4416     // abstracted
4417     if (enableIfNecessary)
4418     {
4419       viewport.setShowSequenceFeatures(true);
4420       showSeqFeatures.setSelected(true);
4421     }
4422
4423   }
4424
4425   @Override
4426   public void dragEnter(DropTargetDragEvent evt)
4427   {
4428   }
4429
4430   @Override
4431   public void dragExit(DropTargetEvent evt)
4432   {
4433   }
4434
4435   @Override
4436   public void dragOver(DropTargetDragEvent evt)
4437   {
4438   }
4439
4440   @Override
4441   public void dropActionChanged(DropTargetDragEvent evt)
4442   {
4443   }
4444
4445   @Override
4446   public void drop(DropTargetDropEvent evt)
4447   {
4448     // JAL-1552 - acceptDrop required before getTransferable call for
4449     // Java's Transferable for native dnd
4450     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4451     Transferable t = evt.getTransferable();
4452     
4453     
4454     final AlignFrame thisaf = this;
4455     final List<Object> files = new ArrayList<>();
4456     List<DataSourceType> protocols = new ArrayList<>();
4457
4458     try
4459     {
4460       Desktop.transferFromDropTarget(files, protocols, evt, t);
4461     } catch (Exception e)
4462     {
4463       e.printStackTrace();
4464     }
4465     if (files != null)
4466     {
4467       new Thread(new Runnable()
4468       {
4469         @Override
4470         public void run()
4471         {
4472           try
4473           {
4474             // check to see if any of these files have names matching sequences
4475             // in
4476             // the alignment
4477             SequenceIdMatcher idm = new SequenceIdMatcher(
4478                     viewport.getAlignment().getSequencesArray());
4479             /**
4480              * Object[] { String,SequenceI}
4481              */
4482             ArrayList<Object[]> filesmatched = new ArrayList<>();
4483             ArrayList<Object> filesnotmatched = new ArrayList<>();
4484             for (int i = 0; i < files.size(); i++)
4485             {
4486               // BH 2018 
4487               Object file = files.get(i);
4488               String fileName = file.toString();
4489               String pdbfn = "";
4490               DataSourceType protocol = (file instanceof File ? DataSourceType.FILE : FormatAdapter.checkProtocol(fileName));
4491               if (protocol == DataSourceType.FILE)
4492               {
4493                 File fl = (file instanceof File ? (File) file : new File(fileName));
4494                 pdbfn = fl.getName();
4495               }
4496               else if (protocol == DataSourceType.URL)
4497               {
4498                 URL url = new URL(fileName);
4499                 pdbfn = url.getFile();
4500               }
4501               if (pdbfn.length() > 0)
4502               {
4503                 // attempt to find a match in the alignment
4504                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4505                 int l = 0, c = pdbfn.indexOf(".");
4506                 while (mtch == null && c != -1)
4507                 {
4508                   do
4509                   {
4510                     l = c;
4511                   } while ((c = pdbfn.indexOf(".", l)) > l);
4512                   if (l > -1)
4513                   {
4514                     pdbfn = pdbfn.substring(0, l);
4515                   }
4516                   mtch = idm.findAllIdMatches(pdbfn);
4517                 }
4518                 if (mtch != null)
4519                 {
4520                   FileFormatI type;
4521                   try
4522                   {
4523                     type = new IdentifyFile().identify(file, protocol);
4524                   } catch (Exception ex)
4525                   {
4526                     type = null;
4527                   }
4528                   if (type != null && type.isStructureFile())
4529                   {
4530                     filesmatched.add(new Object[] { file, protocol, mtch });
4531                     continue;
4532                   }
4533                 }
4534                 // File wasn't named like one of the sequences or wasn't a PDB
4535                 // file.
4536                 filesnotmatched.add(file);
4537               }
4538             }
4539             int assocfiles = 0;
4540             if (filesmatched.size() > 0)
4541             {
4542               boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4543               if (!autoAssociate)
4544               {
4545                 String msg = MessageManager.formatMessage(
4546                         "label.automatically_associate_structure_files_with_sequences_same_name",
4547                         new Object[]
4548                         { Integer.valueOf(filesmatched.size())
4549                                 .toString() });
4550                 String ttl = MessageManager.getString(
4551                         "label.automatically_associate_structure_files_by_name");
4552                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4553                         ttl, JvOptionPane.YES_NO_OPTION);
4554                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4555               }
4556               if (autoAssociate)
4557               {
4558                 for (Object[] fm : filesmatched)
4559                 {
4560                   // try and associate
4561                   // TODO: may want to set a standard ID naming formalism for
4562                   // associating PDB files which have no IDs.
4563                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4564                   {
4565                     PDBEntry pe = new AssociatePdbFileWithSeq()
4566                             .associatePdbWithSeq((String) fm[0],
4567                                     (DataSourceType) fm[1], toassoc, false,
4568                                     Desktop.instance);
4569                     if (pe != null)
4570                     {
4571                       System.err.println("Associated file : "
4572                               + ((String) fm[0]) + " with "
4573                               + toassoc.getDisplayId(true));
4574                       assocfiles++;
4575                     }
4576                   }
4577                   // TODO: do we need to update overview ? only if features are
4578                   // shown I guess
4579                   alignPanel.paintAlignment(true, false);
4580                 }
4581               }
4582               else
4583               {
4584                 /*
4585                  * add declined structures as sequences
4586                  */
4587                 for (Object[] o : filesmatched)
4588                 {
4589                   filesnotmatched.add(o[0]);
4590                 }
4591               }
4592             }
4593             if (filesnotmatched.size() > 0)
4594             {
4595               if (assocfiles > 0 && (Cache.getDefault(
4596                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4597                       || JvOptionPane.showConfirmDialog(thisaf,
4598                               "<html>" + MessageManager.formatMessage(
4599                                       "label.ignore_unmatched_dropped_files_info",
4600                                       new Object[]
4601                                       { Integer.valueOf(
4602                                               filesnotmatched.size())
4603                                               .toString() })
4604                                       + "</html>",
4605                               MessageManager.getString(
4606                                       "label.ignore_unmatched_dropped_files"),
4607                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4608               {
4609                 return;
4610               }
4611               for (Object fn : filesnotmatched)
4612               {
4613                 loadJalviewDataFile(fn, null, null, null);
4614               }
4615
4616             }
4617           } catch (Exception ex)
4618           {
4619             ex.printStackTrace();
4620           }
4621         }
4622       }).start();
4623     }
4624   }
4625
4626   /**
4627    * Attempt to load a "dropped" file or URL string, by testing in turn for
4628    * <ul>
4629    * <li>an Annotation file</li>
4630    * <li>a JNet file</li>
4631    * <li>a features file</li>
4632    * <li>else try to interpret as an alignment file</li>
4633    * </ul>
4634    * 
4635    * @param file
4636    *          either a filename or a URL string.
4637    */
4638   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4639           FileFormatI format, SequenceI assocSeq)
4640   {
4641     // BH 2018 was String file
4642     try
4643     {
4644       if (sourceType == null)
4645       {
4646         sourceType = FormatAdapter.checkProtocol(file);
4647       }
4648       // if the file isn't identified, or not positively identified as some
4649       // other filetype (PFAM is default unidentified alignment file type) then
4650       // try to parse as annotation.
4651       boolean isAnnotation = (format == null
4652               || FileFormat.Pfam.equals(format))
4653                       ? new AnnotationFile().annotateAlignmentView(viewport,
4654                               file, sourceType)
4655                       : false;
4656
4657       if (!isAnnotation)
4658       {
4659         // first see if its a T-COFFEE score file
4660         TCoffeeScoreFile tcf = null;
4661         try
4662         {
4663           tcf = new TCoffeeScoreFile(file, sourceType);
4664           if (tcf.isValid())
4665           {
4666             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4667             {
4668               buildColourMenu();
4669               changeColour(
4670                       new TCoffeeColourScheme(viewport.getAlignment()));
4671               isAnnotation = true;
4672               statusBar.setText(MessageManager.getString(
4673                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4674             }
4675             else
4676             {
4677               // some problem - if no warning its probable that the ID matching
4678               // process didn't work
4679               JvOptionPane.showMessageDialog(Desktop.desktop,
4680                       tcf.getWarningMessage() == null
4681                               ? MessageManager.getString(
4682                                       "label.check_file_matches_sequence_ids_alignment")
4683                               : tcf.getWarningMessage(),
4684                       MessageManager.getString(
4685                               "label.problem_reading_tcoffee_score_file"),
4686                       JvOptionPane.WARNING_MESSAGE);
4687             }
4688           }
4689           else
4690           {
4691             tcf = null;
4692           }
4693         } catch (Exception x)
4694         {
4695           Cache.log.debug(
4696                   "Exception when processing data source as T-COFFEE score file",
4697                   x);
4698           tcf = null;
4699         }
4700         if (tcf == null)
4701         {
4702           // try to see if its a JNet 'concise' style annotation file *before*
4703           // we
4704           // try to parse it as a features file
4705           if (format == null)
4706           {
4707             format = new IdentifyFile().identify(file, sourceType);
4708           }
4709           if (FileFormat.ScoreMatrix == format)
4710           {
4711             ScoreMatrixFile sm = new ScoreMatrixFile(
4712                     new FileParse(file, sourceType));
4713             sm.parse();
4714             // todo: i18n this message
4715             statusBar.setText(MessageManager.formatMessage(
4716                     "label.successfully_loaded_matrix",
4717                     sm.getMatrixName()));
4718           }
4719           else if (FileFormat.Jnet.equals(format))
4720           {
4721             JPredFile predictions = new JPredFile(file, sourceType);
4722             new JnetAnnotationMaker();
4723             JnetAnnotationMaker.add_annotation(predictions,
4724                     viewport.getAlignment(), 0, false);
4725             viewport.getAlignment().setupJPredAlignment();
4726             isAnnotation = true;
4727           }
4728           // else if (IdentifyFile.FeaturesFile.equals(format))
4729           else if (FileFormat.Features.equals(format))
4730           {
4731             if (parseFeaturesFile(file, sourceType))
4732             {
4733               alignPanel.paintAlignment(true, true);
4734             }
4735           }
4736           else
4737           {
4738             new FileLoader().LoadFile(viewport, file, sourceType, format);
4739           }
4740         }
4741       }
4742       if (isAnnotation)
4743       {
4744
4745         alignPanel.adjustAnnotationHeight();
4746         viewport.updateSequenceIdColours();
4747         buildSortByAnnotationScoresMenu();
4748         alignPanel.paintAlignment(true, true);
4749       }
4750     } catch (Exception ex)
4751     {
4752       ex.printStackTrace();
4753     } catch (OutOfMemoryError oom)
4754     {
4755       try
4756       {
4757         System.gc();
4758       } catch (Exception x)
4759       {
4760       }
4761       new OOMWarning(
4762               "loading data "
4763                       + (sourceType != null
4764                               ? (sourceType == DataSourceType.PASTE
4765                                       ? "from clipboard."
4766                                       : "using " + sourceType + " from "
4767                                               + file)
4768                               : ".")
4769                       + (format != null
4770                               ? "(parsing as '" + format + "' file)"
4771                               : ""),
4772               oom, Desktop.desktop);
4773     }
4774   }
4775
4776   /**
4777    * Method invoked by the ChangeListener on the tabbed pane, in other words
4778    * when a different tabbed pane is selected by the user or programmatically.
4779    */
4780   @Override
4781   public void tabSelectionChanged(int index)
4782   {
4783     if (index > -1)
4784     {
4785       alignPanel = alignPanels.get(index);
4786       viewport = alignPanel.av;
4787       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4788       setMenusFromViewport(viewport);
4789     }
4790
4791     /*
4792      * 'focus' any colour slider that is open to the selected viewport
4793      */
4794     if (viewport.getConservationSelected())
4795     {
4796       SliderPanel.setConservationSlider(alignPanel,
4797               viewport.getResidueShading(), alignPanel.getViewName());
4798     }
4799     else
4800     {
4801       SliderPanel.hideConservationSlider();
4802     }
4803     if (viewport.getAbovePIDThreshold())
4804     {
4805       SliderPanel.setPIDSliderSource(alignPanel,
4806               viewport.getResidueShading(), alignPanel.getViewName());
4807     }
4808     else
4809     {
4810       SliderPanel.hidePIDSlider();
4811     }
4812
4813     /*
4814      * If there is a frame linked to this one in a SplitPane, switch it to the
4815      * same view tab index. No infinite recursion of calls should happen, since
4816      * tabSelectionChanged() should not get invoked on setting the selected
4817      * index to an unchanged value. Guard against setting an invalid index
4818      * before the new view peer tab has been created.
4819      */
4820     final AlignViewportI peer = viewport.getCodingComplement();
4821     if (peer != null)
4822     {
4823       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4824               .getAlignPanel().alignFrame;
4825       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4826       {
4827         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4828       }
4829     }
4830   }
4831
4832   /**
4833    * On right mouse click on view tab, prompt for and set new view name.
4834    */
4835   @Override
4836   public void tabbedPane_mousePressed(MouseEvent e)
4837   {
4838     if (e.isPopupTrigger())
4839     {
4840       String msg = MessageManager.getString("label.enter_view_name");
4841       String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4842               JvOptionPane.QUESTION_MESSAGE);
4843
4844       if (reply != null)
4845       {
4846         viewport.viewName = reply;
4847         // TODO warn if reply is in getExistingViewNames()?
4848         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4849       }
4850     }
4851   }
4852
4853   public AlignViewport getCurrentView()
4854   {
4855     return viewport;
4856   }
4857
4858   /**
4859    * Open the dialog for regex description parsing.
4860    */
4861   @Override
4862   protected void extractScores_actionPerformed(ActionEvent e)
4863   {
4864     ParseProperties pp = new jalview.analysis.ParseProperties(
4865             viewport.getAlignment());
4866     // TODO: verify regex and introduce GUI dialog for version 2.5
4867     // if (pp.getScoresFromDescription("col", "score column ",
4868     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4869     // true)>0)
4870     if (pp.getScoresFromDescription("description column",
4871             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4872     {
4873       buildSortByAnnotationScoresMenu();
4874     }
4875   }
4876
4877   /*
4878    * (non-Javadoc)
4879    * 
4880    * @see
4881    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4882    * )
4883    */
4884   @Override
4885   protected void showDbRefs_actionPerformed(ActionEvent e)
4886   {
4887     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4888   }
4889
4890   /*
4891    * (non-Javadoc)
4892    * 
4893    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4894    * ActionEvent)
4895    */
4896   @Override
4897   protected void showNpFeats_actionPerformed(ActionEvent e)
4898   {
4899     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4900   }
4901
4902   /**
4903    * find the viewport amongst the tabs in this alignment frame and close that
4904    * tab
4905    * 
4906    * @param av
4907    */
4908   public boolean closeView(AlignViewportI av)
4909   {
4910     if (viewport == av)
4911     {
4912       this.closeMenuItem_actionPerformed(false);
4913       return true;
4914     }
4915     Component[] comp = tabbedPane.getComponents();
4916     for (int i = 0; comp != null && i < comp.length; i++)
4917     {
4918       if (comp[i] instanceof AlignmentPanel)
4919       {
4920         if (((AlignmentPanel) comp[i]).av == av)
4921         {
4922           // close the view.
4923           closeView((AlignmentPanel) comp[i]);
4924           return true;
4925         }
4926       }
4927     }
4928     return false;
4929   }
4930
4931   protected void build_fetchdbmenu(JMenu webService)
4932   {
4933     // Temporary hack - DBRef Fetcher always top level ws entry.
4934     // TODO We probably want to store a sequence database checklist in
4935     // preferences and have checkboxes.. rather than individual sources selected
4936     // here
4937     final JMenu rfetch = new JMenu(
4938             MessageManager.getString("action.fetch_db_references"));
4939     rfetch.setToolTipText(MessageManager.getString(
4940             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4941     webService.add(rfetch);
4942
4943     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4944             MessageManager.getString("option.trim_retrieved_seqs"));
4945     trimrs.setToolTipText(
4946             MessageManager.getString("label.trim_retrieved_sequences"));
4947     trimrs.setSelected(
4948             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4949     trimrs.addActionListener(new ActionListener()
4950     {
4951       @Override
4952       public void actionPerformed(ActionEvent e)
4953       {
4954         trimrs.setSelected(trimrs.isSelected());
4955         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4956                 Boolean.valueOf(trimrs.isSelected()).toString());
4957       };
4958     });
4959     rfetch.add(trimrs);
4960     JMenuItem fetchr = new JMenuItem(
4961             MessageManager.getString("label.standard_databases"));
4962     fetchr.setToolTipText(
4963             MessageManager.getString("label.fetch_embl_uniprot"));
4964     fetchr.addActionListener(new ActionListener()
4965     {
4966
4967       @Override
4968       public void actionPerformed(ActionEvent e)
4969       {
4970         new Thread(new Runnable()
4971         {
4972           @Override
4973           public void run()
4974           {
4975             boolean isNucleotide = alignPanel.alignFrame.getViewport()
4976                     .getAlignment().isNucleotide();
4977             DBRefFetcher dbRefFetcher = new DBRefFetcher(
4978                     alignPanel.av.getSequenceSelection(),
4979                     alignPanel.alignFrame, null,
4980                     alignPanel.alignFrame.featureSettings, isNucleotide);
4981             dbRefFetcher.addListener(new FetchFinishedListenerI()
4982             {
4983               @Override
4984               public void finished()
4985               {
4986                 AlignFrame.this.setMenusForViewport();
4987               }
4988             });
4989             dbRefFetcher.fetchDBRefs(false);
4990           }
4991         }).start();
4992
4993       }
4994
4995     });
4996     rfetch.add(fetchr);
4997     final AlignFrame me = this;
4998     new Thread(new Runnable()
4999     {
5000       @Override
5001       public void run()
5002       {
5003         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5004                 .getSequenceFetcherSingleton(me);
5005         javax.swing.SwingUtilities.invokeLater(new Runnable()
5006         {
5007           @Override
5008           public void run()
5009           {
5010             String[] dbclasses = sf.getOrderedSupportedSources();
5011             // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5012             // jalview.util.QuickSort.sort(otherdb, otherdb);
5013             List<DbSourceProxy> otherdb;
5014             JMenu dfetch = new JMenu();
5015             JMenu ifetch = new JMenu();
5016             JMenuItem fetchr = null;
5017             int comp = 0, icomp = 0, mcomp = 15;
5018             String mname = null;
5019             int dbi = 0;
5020             for (String dbclass : dbclasses)
5021             {
5022               otherdb = sf.getSourceProxy(dbclass);
5023               // add a single entry for this class, or submenu allowing 'fetch
5024               // all' or pick one
5025               if (otherdb == null || otherdb.size() < 1)
5026               {
5027                 continue;
5028               }
5029               // List<DbSourceProxy> dbs=otherdb;
5030               // otherdb=new ArrayList<DbSourceProxy>();
5031               // for (DbSourceProxy db:dbs)
5032               // {
5033               // if (!db.isA(DBRefSource.ALIGNMENTDB)
5034               // }
5035               if (mname == null)
5036               {
5037                 mname = "From " + dbclass;
5038               }
5039               if (otherdb.size() == 1)
5040               {
5041                 final DbSourceProxy[] dassource = otherdb
5042                         .toArray(new DbSourceProxy[0]);
5043                 DbSourceProxy src = otherdb.get(0);
5044                 fetchr = new JMenuItem(src.getDbSource());
5045                 fetchr.addActionListener(new ActionListener()
5046                 {
5047
5048                   @Override
5049                   public void actionPerformed(ActionEvent e)
5050                   {
5051                     new Thread(new Runnable()
5052                     {
5053
5054                       @Override
5055                       public void run()
5056                       {
5057                         boolean isNucleotide = alignPanel.alignFrame
5058                                 .getViewport().getAlignment()
5059                                 .isNucleotide();
5060                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5061                                 alignPanel.av.getSequenceSelection(),
5062                                 alignPanel.alignFrame, dassource,
5063                                 alignPanel.alignFrame.featureSettings,
5064                                 isNucleotide);
5065                         dbRefFetcher
5066                                 .addListener(new FetchFinishedListenerI()
5067                                 {
5068                                   @Override
5069                                   public void finished()
5070                                   {
5071                                     AlignFrame.this.setMenusForViewport();
5072                                   }
5073                                 });
5074                         dbRefFetcher.fetchDBRefs(false);
5075                       }
5076                     }).start();
5077                   }
5078
5079                 });
5080                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5081                         MessageManager.formatMessage(
5082                                 "label.fetch_retrieve_from", new Object[]
5083                                 { src.getDbName() })));
5084                 dfetch.add(fetchr);
5085                 comp++;
5086               }
5087               else
5088               {
5089                 final DbSourceProxy[] dassource = otherdb
5090                         .toArray(new DbSourceProxy[0]);
5091                 // fetch all entry
5092                 DbSourceProxy src = otherdb.get(0);
5093                 fetchr = new JMenuItem(MessageManager
5094                         .formatMessage("label.fetch_all_param", new Object[]
5095                         { src.getDbSource() }));
5096                 fetchr.addActionListener(new ActionListener()
5097                 {
5098                   @Override
5099                   public void actionPerformed(ActionEvent e)
5100                   {
5101                     new Thread(new Runnable()
5102                     {
5103
5104                       @Override
5105                       public void run()
5106                       {
5107                         boolean isNucleotide = alignPanel.alignFrame
5108                                 .getViewport().getAlignment()
5109                                 .isNucleotide();
5110                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5111                                 alignPanel.av.getSequenceSelection(),
5112                                 alignPanel.alignFrame, dassource,
5113                                 alignPanel.alignFrame.featureSettings,
5114                                 isNucleotide);
5115                         dbRefFetcher
5116                                 .addListener(new FetchFinishedListenerI()
5117                                 {
5118                                   @Override
5119                                   public void finished()
5120                                   {
5121                                     AlignFrame.this.setMenusForViewport();
5122                                   }
5123                                 });
5124                         dbRefFetcher.fetchDBRefs(false);
5125                       }
5126                     }).start();
5127                   }
5128                 });
5129
5130                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5131                         MessageManager.formatMessage(
5132                                 "label.fetch_retrieve_from_all_sources",
5133                                 new Object[]
5134                                 { Integer.valueOf(otherdb.size())
5135                                         .toString(),
5136                                     src.getDbSource(), src.getDbName() })));
5137                 dfetch.add(fetchr);
5138                 comp++;
5139                 // and then build the rest of the individual menus
5140                 ifetch = new JMenu(MessageManager.formatMessage(
5141                         "label.source_from_db_source", new Object[]
5142                         { src.getDbSource() }));
5143                 icomp = 0;
5144                 String imname = null;
5145                 int i = 0;
5146                 for (DbSourceProxy sproxy : otherdb)
5147                 {
5148                   String dbname = sproxy.getDbName();
5149                   String sname = dbname.length() > 5
5150                           ? dbname.substring(0, 5) + "..."
5151                           : dbname;
5152                   String msname = dbname.length() > 10
5153                           ? dbname.substring(0, 10) + "..."
5154                           : dbname;
5155                   if (imname == null)
5156                   {
5157                     imname = MessageManager
5158                             .formatMessage("label.from_msname", new Object[]
5159                             { sname });
5160                   }
5161                   fetchr = new JMenuItem(msname);
5162                   final DbSourceProxy[] dassrc = { sproxy };
5163                   fetchr.addActionListener(new ActionListener()
5164                   {
5165
5166                     @Override
5167                     public void actionPerformed(ActionEvent e)
5168                     {
5169                       new Thread(new Runnable()
5170                       {
5171
5172                         @Override
5173                         public void run()
5174                         {
5175                           boolean isNucleotide = alignPanel.alignFrame
5176                                   .getViewport().getAlignment()
5177                                   .isNucleotide();
5178                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5179                                   alignPanel.av.getSequenceSelection(),
5180                                   alignPanel.alignFrame, dassrc,
5181                                   alignPanel.alignFrame.featureSettings,
5182                                   isNucleotide);
5183                           dbRefFetcher
5184                                   .addListener(new FetchFinishedListenerI()
5185                                   {
5186                                     @Override
5187                                     public void finished()
5188                                     {
5189                                       AlignFrame.this.setMenusForViewport();
5190                                     }
5191                                   });
5192                           dbRefFetcher.fetchDBRefs(false);
5193                         }
5194                       }).start();
5195                     }
5196
5197                   });
5198                   fetchr.setToolTipText(
5199                           "<html>" + MessageManager.formatMessage(
5200                                   "label.fetch_retrieve_from", new Object[]
5201                                   { dbname }));
5202                   ifetch.add(fetchr);
5203                   ++i;
5204                   if (++icomp >= mcomp || i == (otherdb.size()))
5205                   {
5206                     ifetch.setText(MessageManager.formatMessage(
5207                             "label.source_to_target", imname, sname));
5208                     dfetch.add(ifetch);
5209                     ifetch = new JMenu();
5210                     imname = null;
5211                     icomp = 0;
5212                     comp++;
5213                   }
5214                 }
5215               }
5216               ++dbi;
5217               if (comp >= mcomp || dbi >= (dbclasses.length))
5218               {
5219                 dfetch.setText(MessageManager.formatMessage(
5220                         "label.source_to_target", mname, dbclass));
5221                 rfetch.add(dfetch);
5222                 dfetch = new JMenu();
5223                 mname = null;
5224                 comp = 0;
5225               }
5226             }
5227           }
5228         });
5229       }
5230     }).start();
5231
5232   }
5233
5234   /**
5235    * Left justify the whole alignment.
5236    */
5237   @Override
5238   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5239   {
5240     AlignmentI al = viewport.getAlignment();
5241     al.justify(false);
5242     viewport.firePropertyChange("alignment", null, al);
5243   }
5244
5245   /**
5246    * Right justify the whole alignment.
5247    */
5248   @Override
5249   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5250   {
5251     AlignmentI al = viewport.getAlignment();
5252     al.justify(true);
5253     viewport.firePropertyChange("alignment", null, al);
5254   }
5255
5256   @Override
5257   public void setShowSeqFeatures(boolean b)
5258   {
5259     showSeqFeatures.setSelected(b);
5260     viewport.setShowSequenceFeatures(b);
5261   }
5262
5263   /*
5264    * (non-Javadoc)
5265    * 
5266    * @see
5267    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5268    * awt.event.ActionEvent)
5269    */
5270   @Override
5271   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5272   {
5273     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5274     alignPanel.paintAlignment(false, false);
5275   }
5276
5277   /*
5278    * (non-Javadoc)
5279    * 
5280    * @see
5281    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5282    * .ActionEvent)
5283    */
5284   @Override
5285   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5286   {
5287     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5288     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5289
5290   }
5291
5292   /*
5293    * (non-Javadoc)
5294    * 
5295    * @see
5296    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5297    * .event.ActionEvent)
5298    */
5299   @Override
5300   protected void showGroupConservation_actionPerformed(ActionEvent e)
5301   {
5302     viewport.setShowGroupConservation(showGroupConservation.getState());
5303     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5304   }
5305
5306   /*
5307    * (non-Javadoc)
5308    * 
5309    * @see
5310    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5311    * .event.ActionEvent)
5312    */
5313   @Override
5314   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5315   {
5316     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5317     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5318   }
5319
5320   /*
5321    * (non-Javadoc)
5322    * 
5323    * @see
5324    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5325    * .event.ActionEvent)
5326    */
5327   @Override
5328   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5329   {
5330     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5331     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5332   }
5333
5334   @Override
5335   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5336   {
5337     showSequenceLogo.setState(true);
5338     viewport.setShowSequenceLogo(true);
5339     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5340     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5341   }
5342
5343   @Override
5344   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5345   {
5346     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5347   }
5348
5349   /*
5350    * (non-Javadoc)
5351    * 
5352    * @see
5353    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5354    * .event.ActionEvent)
5355    */
5356   @Override
5357   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5358   {
5359     if (avc.makeGroupsFromSelection())
5360     {
5361       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5362       alignPanel.updateAnnotation();
5363       alignPanel.paintAlignment(true, true);
5364     }
5365   }
5366
5367   public void clearAlignmentSeqRep()
5368   {
5369     // TODO refactor alignmentseqrep to controller
5370     if (viewport.getAlignment().hasSeqrep())
5371     {
5372       viewport.getAlignment().setSeqrep(null);
5373       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5374       alignPanel.updateAnnotation();
5375       alignPanel.paintAlignment(true, true);
5376     }
5377   }
5378
5379   @Override
5380   protected void createGroup_actionPerformed(ActionEvent e)
5381   {
5382     if (avc.createGroup())
5383     {
5384       alignPanel.alignmentChanged();
5385     }
5386   }
5387
5388   @Override
5389   protected void unGroup_actionPerformed(ActionEvent e)
5390   {
5391     if (avc.unGroup())
5392     {
5393       alignPanel.alignmentChanged();
5394     }
5395   }
5396
5397   /**
5398    * make the given alignmentPanel the currently selected tab
5399    * 
5400    * @param alignmentPanel
5401    */
5402   public void setDisplayedView(AlignmentPanel alignmentPanel)
5403   {
5404     if (!viewport.getSequenceSetId()
5405             .equals(alignmentPanel.av.getSequenceSetId()))
5406     {
5407       throw new Error(MessageManager.getString(
5408               "error.implementation_error_cannot_show_view_alignment_frame"));
5409     }
5410     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5411             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5412     {
5413       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5414     }
5415   }
5416
5417   /**
5418    * Action on selection of menu options to Show or Hide annotations.
5419    * 
5420    * @param visible
5421    * @param forSequences
5422    *          update sequence-related annotations
5423    * @param forAlignment
5424    *          update non-sequence-related annotations
5425    */
5426   @Override
5427   protected void setAnnotationsVisibility(boolean visible,
5428           boolean forSequences, boolean forAlignment)
5429   {
5430     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5431             .getAlignmentAnnotation();
5432     if (anns == null)
5433     {
5434       return;
5435     }
5436     for (AlignmentAnnotation aa : anns)
5437     {
5438       /*
5439        * don't display non-positional annotations on an alignment
5440        */
5441       if (aa.annotations == null)
5442       {
5443         continue;
5444       }
5445       boolean apply = (aa.sequenceRef == null && forAlignment)
5446               || (aa.sequenceRef != null && forSequences);
5447       if (apply)
5448       {
5449         aa.visible = visible;
5450       }
5451     }
5452     alignPanel.validateAnnotationDimensions(true);
5453     alignPanel.alignmentChanged();
5454   }
5455
5456   /**
5457    * Store selected annotation sort order for the view and repaint.
5458    */
5459   @Override
5460   protected void sortAnnotations_actionPerformed()
5461   {
5462     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5463     this.alignPanel.av
5464             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5465     alignPanel.paintAlignment(false, false);
5466   }
5467
5468   /**
5469    * 
5470    * @return alignment panels in this alignment frame
5471    */
5472   public List<? extends AlignmentViewPanel> getAlignPanels()
5473   {
5474     return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5475   }
5476
5477   /**
5478    * Open a new alignment window, with the cDNA associated with this (protein)
5479    * alignment, aligned as is the protein.
5480    */
5481   protected void viewAsCdna_actionPerformed()
5482   {
5483     // TODO no longer a menu action - refactor as required
5484     final AlignmentI alignment = getViewport().getAlignment();
5485     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5486     if (mappings == null)
5487     {
5488       return;
5489     }
5490     List<SequenceI> cdnaSeqs = new ArrayList<>();
5491     for (SequenceI aaSeq : alignment.getSequences())
5492     {
5493       for (AlignedCodonFrame acf : mappings)
5494       {
5495         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5496         if (dnaSeq != null)
5497         {
5498           /*
5499            * There is a cDNA mapping for this protein sequence - add to new
5500            * alignment. It will share the same dataset sequence as other mapped
5501            * cDNA (no new mappings need to be created).
5502            */
5503           final Sequence newSeq = new Sequence(dnaSeq);
5504           newSeq.setDatasetSequence(dnaSeq);
5505           cdnaSeqs.add(newSeq);
5506         }
5507       }
5508     }
5509     if (cdnaSeqs.size() == 0)
5510     {
5511       // show a warning dialog no mapped cDNA
5512       return;
5513     }
5514     AlignmentI cdna = new Alignment(
5515             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5516     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5517             AlignFrame.DEFAULT_HEIGHT);
5518     cdna.alignAs(alignment);
5519     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5520             + this.title;
5521     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5522             AlignFrame.DEFAULT_HEIGHT);
5523   }
5524
5525   /**
5526    * Set visibility of dna/protein complement view (available when shown in a
5527    * split frame).
5528    * 
5529    * @param show
5530    */
5531   @Override
5532   protected void showComplement_actionPerformed(boolean show)
5533   {
5534     SplitContainerI sf = getSplitViewContainer();
5535     if (sf != null)
5536     {
5537       sf.setComplementVisible(this, show);
5538     }
5539   }
5540
5541   /**
5542    * Generate the reverse (optionally complemented) of the selected sequences,
5543    * and add them to the alignment
5544    */
5545   @Override
5546   protected void showReverse_actionPerformed(boolean complement)
5547   {
5548     AlignmentI al = null;
5549     try
5550     {
5551       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5552       al = dna.reverseCdna(complement);
5553       viewport.addAlignment(al, "");
5554       addHistoryItem(new EditCommand(
5555               MessageManager.getString("label.add_sequences"), Action.PASTE,
5556               al.getSequencesArray(), 0, al.getWidth(),
5557               viewport.getAlignment()));
5558     } catch (Exception ex)
5559     {
5560       System.err.println(ex.getMessage());
5561       return;
5562     }
5563   }
5564
5565   /**
5566    * Try to run a script in the Groovy console, having first ensured that this
5567    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5568    * be targeted at this alignment.
5569    */
5570   @Override
5571   protected void runGroovy_actionPerformed()
5572   {
5573     Jalview.setCurrentAlignFrame(this);
5574     groovy.ui.Console console = Desktop.getGroovyConsole();
5575     if (console != null)
5576     {
5577       try
5578       {
5579         console.runScript();
5580       } catch (Exception ex)
5581       {
5582         System.err.println((ex.toString()));
5583         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5584                 MessageManager.getString("label.couldnt_run_groovy_script"),
5585                 MessageManager.getString("label.groovy_support_failed"),
5586                 JvOptionPane.ERROR_MESSAGE);
5587       }
5588     }
5589     else
5590     {
5591       System.err.println("Can't run Groovy script as console not found");
5592     }
5593   }
5594
5595   /**
5596    * Hides columns containing (or not containing) a specified feature, provided
5597    * that would not leave all columns hidden
5598    * 
5599    * @param featureType
5600    * @param columnsContaining
5601    * @return
5602    */
5603   public boolean hideFeatureColumns(String featureType,
5604           boolean columnsContaining)
5605   {
5606     boolean notForHiding = avc.markColumnsContainingFeatures(
5607             columnsContaining, false, false, featureType);
5608     if (notForHiding)
5609     {
5610       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5611               false, featureType))
5612       {
5613         getViewport().hideSelectedColumns();
5614         return true;
5615       }
5616     }
5617     return false;
5618   }
5619
5620   @Override
5621   protected void selectHighlightedColumns_actionPerformed(
5622           ActionEvent actionEvent)
5623   {
5624     // include key modifier check in case user selects from menu
5625     avc.markHighlightedColumns(
5626             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5627             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5628                     | ActionEvent.CTRL_MASK)) != 0);
5629   }
5630
5631   /**
5632    * Rebuilds the Colour menu, including any user-defined colours which have
5633    * been loaded either on startup or during the session
5634    */
5635   public void buildColourMenu()
5636   {
5637     colourMenu.removeAll();
5638
5639     colourMenu.add(applyToAllGroups);
5640     colourMenu.add(textColour);
5641     colourMenu.addSeparator();
5642
5643     ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5644             false);
5645
5646     colourMenu.addSeparator();
5647     colourMenu.add(conservationMenuItem);
5648     colourMenu.add(modifyConservation);
5649     colourMenu.add(abovePIDThreshold);
5650     colourMenu.add(modifyPID);
5651     colourMenu.add(annotationColour);
5652
5653     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5654     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5655   }
5656
5657   /**
5658    * Open a dialog (if not already open) that allows the user to select and
5659    * calculate PCA or Tree analysis
5660    */
5661   protected void openTreePcaDialog()
5662   {
5663     if (alignPanel.getCalculationDialog() == null)
5664     {
5665       new CalculationChooser(AlignFrame.this);
5666     }
5667   }
5668
5669   @Override
5670   protected void loadVcf_actionPerformed()
5671   {
5672     JalviewFileChooser chooser = new JalviewFileChooser(
5673             Cache.getProperty("LAST_DIRECTORY"));
5674     chooser.setFileView(new JalviewFileView());
5675     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5676     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5677     final AlignFrame us = this;
5678     chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
5679     {
5680       @Override
5681       public void run()
5682       {
5683
5684         {
5685           String choice = chooser.getSelectedFile().getPath();
5686           Cache.setProperty("LAST_DIRECTORY", choice);
5687           SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5688           new VCFLoader(choice).loadVCF(seqs, us);
5689         }
5690
5691       };
5692     }).openDialog(null);
5693
5694   }
5695
5696 }
5697
5698 class PrintThread extends Thread
5699 {
5700   AlignmentPanel ap;
5701
5702   public PrintThread(AlignmentPanel ap)
5703   {
5704     this.ap = ap;
5705   }
5706
5707   static PageFormat pf;
5708
5709   @Override
5710   public void run()
5711   {
5712     PrinterJob printJob = PrinterJob.getPrinterJob();
5713
5714     if (pf != null)
5715     {
5716       printJob.setPrintable(ap, pf);
5717     }
5718     else
5719     {
5720       printJob.setPrintable(ap);
5721     }
5722
5723     if (printJob.printDialog())
5724     {
5725       try
5726       {
5727         printJob.print();
5728       } catch (Exception PrintException)
5729       {
5730         PrintException.printStackTrace();
5731       }
5732     }
5733   }
5734 }