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